Spaces:
Sleeping
Sleeping
Commit
路
ba23493
1
Parent(s):
f883925
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
2 |
+
import pandas as pd
|
3 |
+
import numpy as np
|
4 |
+
from vectorization import spotify_data
|
5 |
+
import json
|
6 |
+
import gradio as gr
|
7 |
+
from gradio.components import Textbox
|
8 |
+
from ast import literal_eval
|
9 |
+
spotify_data_processed = pd.read_csv('C:\\Users\\34640\\Desktop\\Saturdays.ai\\spotify_dset\\dataset_modificado.csv')
|
10 |
+
|
11 |
+
def convert_string_to_array(str_vector):
|
12 |
+
# Si str_vector ya es un array de NumPy, devolverlo directamente
|
13 |
+
if isinstance(str_vector, np.ndarray):
|
14 |
+
return str_vector
|
15 |
+
|
16 |
+
try:
|
17 |
+
cleaned_str = str_vector.replace('[', '').replace(']', '').replace('\n', ' ').replace('\r', '').strip()
|
18 |
+
vector_elements = [float(item) for item in cleaned_str.split()]
|
19 |
+
return np.array(vector_elements)
|
20 |
+
except ValueError as e:
|
21 |
+
print("Error:", e)
|
22 |
+
return np.zeros((100,))
|
23 |
+
|
24 |
+
|
25 |
+
spotify_data_processed['song_vector'] = spotify_data_processed['song_vector'].apply(convert_string_to_array)
|
26 |
+
|
27 |
+
|
28 |
+
# Aplicar la funci贸n a las primeras filas para ver los resultados
|
29 |
+
sample_data = spotify_data_processed['song_vector'].head()
|
30 |
+
converted_vectors = sample_data.apply(convert_string_to_array)
|
31 |
+
print(converted_vectors)
|
32 |
+
|
33 |
+
|
34 |
+
|
35 |
+
def recommend_song(song_name, artist_name, spotify_data_processed, top_n=4):
|
36 |
+
# Filtrar para encontrar la canci贸n espec铆fica
|
37 |
+
specific_song = spotify_data_processed[(spotify_data_processed['song'] == song_name)
|
38 |
+
& (spotify_data_processed['artist'] == artist_name)]
|
39 |
+
|
40 |
+
# Verificar si la canci贸n existe en el dataset
|
41 |
+
if specific_song.empty:
|
42 |
+
return pd.DataFrame({"Error": ["Canci贸n no encontrada en la base de datos."]})
|
43 |
+
|
44 |
+
|
45 |
+
# Obtener el vector de la canci贸n espec铆fica
|
46 |
+
song_vec = specific_song['song_vector'].iloc[0]
|
47 |
+
|
48 |
+
# Asegurarte de que song_vec sea un array de NumPy
|
49 |
+
if isinstance(song_vec, str):
|
50 |
+
song_vec = convert_string_to_array(song_vec)
|
51 |
+
|
52 |
+
all_song_vectors = np.array(spotify_data_processed['song_vector'].tolist())
|
53 |
+
|
54 |
+
# Calcular similitudes
|
55 |
+
similarities = cosine_similarity([song_vec], all_song_vectors)[0]
|
56 |
+
|
57 |
+
# Obtener los 铆ndices de las canciones m谩s similares
|
58 |
+
top_indices = np.argsort(similarities)[::-1][1:top_n+1]
|
59 |
+
|
60 |
+
# Devolver los nombres y artistas de las canciones m谩s similares
|
61 |
+
recommended_songs = spotify_data_processed.iloc[top_indices][['song', 'artist']]
|
62 |
+
return recommended_songs
|
63 |
+
|
64 |
+
|
65 |
+
|
66 |
+
|
67 |
+
|
68 |
+
def recommend_song_interface(song_name, artist_name):
|
69 |
+
recommendations_df = recommend_song(song_name, artist_name, spotify_data_processed)
|
70 |
+
|
71 |
+
if isinstance(recommendations_df, pd.DataFrame):
|
72 |
+
# Convierte el DataFrame en una lista de listas y luego a un formato de texto plano para la salida
|
73 |
+
recommendations_list = recommendations_df.values.tolist()
|
74 |
+
return ["{} by {}".format(song, artist) for song, artist in recommendations_list]
|
75 |
+
else:
|
76 |
+
# Si no es un DataFrame, devolver el mensaje de error
|
77 |
+
return recommendations_df
|
78 |
+
|
79 |
+
# Crear la interfaz con Gradio
|
80 |
+
iface = gr.Interface(
|
81 |
+
fn=recommend_song_interface,
|
82 |
+
inputs=[
|
83 |
+
gr.Textbox(placeholder="Ingrese el t铆tulo de la canci贸n", label="T铆tulo de la Canci贸n"),
|
84 |
+
gr.Textbox(placeholder="Ingrese el nombre del artista", label="Nombre del Artista")
|
85 |
+
],
|
86 |
+
outputs=[gr.Text(label="Recomendaci贸n 1"),
|
87 |
+
gr.Text(label="Recomendaci贸n 2"),
|
88 |
+
gr.Text(label="Recomendaci贸n 3"),
|
89 |
+
gr.Text(label="Recomendaci贸n 4")],
|
90 |
+
title="Recomendador de Canciones",
|
91 |
+
description="Ingrese el t铆tulo de una canci贸n y el nombre del artista para obtener recomendaciones.",
|
92 |
+
theme="dark", # Comenta o elimina si el tema oscuro no est谩 disponible
|
93 |
+
css="""
|
94 |
+
body {font-family: Arial, sans-serif;}
|
95 |
+
.input_text {background-color: #f0f0f0; border-radius: 5px;}
|
96 |
+
.output_text {border: 2px solid #f0f0f0; border-radius: 5px; padding: 10px;}
|
97 |
+
"""
|
98 |
+
)
|
99 |
+
|
100 |
+
iface.launch()
|
101 |
+
|