Diego-0121 commited on
Commit
40553d3
1 Parent(s): 3629f8b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -97
app.py CHANGED
@@ -1,111 +1,61 @@
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('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
-
69
- def recommend_song_interface(song_name, artist_name):
70
- recommendations_df = recommend_song(song_name, artist_name, spotify_data_processed)
71
-
72
- if isinstance(recommendations_df, pd.DataFrame) and not recommendations_df.empty and {'song', 'artist'}.issubset(recommendations_df.columns):
73
- recommendations_list = recommendations_df[['song', 'artist']].values.tolist()
74
- formatted_recommendations = ["{} by {}".format(song, artist) for song, artist in recommendations_list]
75
- while len(formatted_recommendations) < 4:
76
- formatted_recommendations.append("")
77
- return formatted_recommendations[:4]
78
  else:
79
- # Si no se encuentran recomendaciones, seleccionar una canci贸n aleatoria del dataset
80
- random_song = spotify_data_processed.sample()
81
- random_song_name = random_song['song'].iloc[0]
82
- random_artist_name = random_song['artist'].iloc[0]
83
-
84
- # Obtener recomendaciones para la canci贸n aleatoria
85
- random_recommendations_df = recommend_song(random_song_name, random_artist_name, spotify_data_processed)
86
- random_recommendations_list = random_recommendations_df[['song', 'artist']].values.tolist()
87
- formatted_random_recommendations = ["{} by {}".format(song, artist) for song, artist in random_recommendations_list]
88
-
89
- # Rellenar con cadenas vac铆as si hay menos de 4 recomendaciones
90
- while len(formatted_random_recommendations) < 4:
91
- formatted_random_recommendations.append("")
92
- return formatted_random_recommendations[:4]
93
- recommendations = recommend_song_interface("song_name", "artist_name")
94
-
95
-
96
- # Crear la interfaz con Gradio
 
 
 
97
  iface = gr.Interface(
98
- fn=recommend_song_interface,
99
  inputs=[
100
  gr.Textbox(placeholder="Ingrese el t铆tulo de la canci贸n", label="T铆tulo de la Canci贸n"),
101
  gr.Textbox(placeholder="Ingrese el nombre del artista", label="Nombre del Artista")
102
  ],
103
- outputs=[gr.Text(label="Recomendaci贸n 1"),
104
- gr.Text(label="Recomendaci贸n 2"),
105
- gr.Text(label="Recomendaci贸n 3"),
106
- gr.Text(label="Recomendaci贸n 4")],
107
- title="Recomendador de Canciones",
108
- description="Ingrese el t铆tulo de una canci贸n y el nombre del artista para obtener recomendaciones.",
109
  theme="dark", # Comenta o elimina si el tema oscuro no est谩 disponible
110
  css="""
111
  body {font-family: Arial, sans-serif;}
@@ -115,4 +65,3 @@ iface = gr.Interface(
115
  )
116
 
117
  iface.launch()
118
-
 
1
+ from Recomendation import recommend_song_interface
 
 
 
 
2
  import gradio as gr
3
+ import requests
 
 
4
 
 
 
 
 
5
 
 
 
 
 
 
 
 
6
 
7
+ def search_youtube(song, artist, api_key):
8
+ query = f"{song} by {artist}"
9
+ search_url = "https://www.googleapis.com/youtube/v3/search"
10
+ params = {
11
+ 'part': 'snippet',
12
+ 'q': query,
13
+ 'type': 'video',
14
+ 'maxResults': 1,
15
+ 'key': api_key
16
+ }
17
 
18
+ response = requests.get(search_url, params=params)
19
+ response_json = response.json()
20
 
21
+ if 'items' in response_json and response_json['items']:
22
+ video_id = response_json['items'][0]['id']['videoId']
23
+ youtube_link = f"https://www.youtube.com/watch?v={video_id}"
24
+ return youtube_link
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  else:
26
+ return "No se encontraron resultados."
27
+
28
+ def add_youtube_links(recommendations, api_key):
29
+ recommendations_with_links = []
30
+ for recommendation in recommendations:
31
+ if recommendation: # Si la recomendaci贸n no es una cadena vac铆a
32
+ song, artist = recommendation.split(" by ")
33
+ youtube_link = search_youtube(song, artist, api_key)
34
+ recommendations_with_links.append(f"{recommendation} - YouTube Link: {youtube_link}")
35
+ else:
36
+ recommendations_with_links.append("")
37
+
38
+ return recommendations_with_links
39
+
40
+ def recommend_with_youtube_links(song_name, artist_name):
41
+ api_key = "AIzaSyAnFiRh8g13HW_wLhUW7wZwRE2SsPo0aJs"
42
+ recommendations = recommend_song_interface(song_name, artist_name)
43
+ recommendations_with_links = add_youtube_links(recommendations, api_key)
44
+ return recommendations_with_links
45
+
46
+ # Configuraci贸n de la interfaz Gradio
47
  iface = gr.Interface(
48
+ fn=recommend_with_youtube_links,
49
  inputs=[
50
  gr.Textbox(placeholder="Ingrese el t铆tulo de la canci贸n", label="T铆tulo de la Canci贸n"),
51
  gr.Textbox(placeholder="Ingrese el nombre del artista", label="Nombre del Artista")
52
  ],
53
+ outputs=[gr.HTML(label="Recomendaci贸n 1"),
54
+ gr.HTML(label="Recomendaci贸n 2"),
55
+ gr.HTML(label="Recomendaci贸n 3"),
56
+ gr.HTML(label="Recomendaci贸n 4")],
57
+ title="Recomendador de Canciones con Enlaces de YouTube",
58
+ description="Ingrese el t铆tulo de una canci贸n y el nombre del artista.",
59
  theme="dark", # Comenta o elimina si el tema oscuro no est谩 disponible
60
  css="""
61
  body {font-family: Arial, sans-serif;}
 
65
  )
66
 
67
  iface.launch()