Manuel Zafra commited on
Commit
cff44ee
·
verified ·
1 Parent(s): e032ac7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -16
app.py CHANGED
@@ -38,7 +38,10 @@ MESSAGES = {
38
  "history_limit_label": "Number of songs to show",
39
  "no_history": "📋 No song recognition history yet",
40
  "empty_history": "📋 Song history is empty",
41
- "history_error": "❌ Error loading song history: {error}"
 
 
 
42
  },
43
  "es": {
44
  "title": "# 🎵 Reconocimiento Musical y Datos Curiosos",
@@ -59,7 +62,10 @@ MESSAGES = {
59
  "history_limit_label": "Número de canciones a mostrar",
60
  "no_history": "📋 No hay historial de canciones reconocidas todavía",
61
  "empty_history": "📋 El historial de canciones está vacío",
62
- "history_error": "❌ Error al cargar el historial: {error}"
 
 
 
63
  },
64
  "fr": {
65
  "title": "# 🎵 Reconnaissance Musicale et Anecdotes",
@@ -80,28 +86,28 @@ MESSAGES = {
80
  "history_limit_label": "Nombre de chansons à afficher",
81
  "no_history": "📋 Aucun historique de reconnaissance de chansons pour l'instant",
82
  "empty_history": "📋 L'historique des chansons est vide",
83
- "history_error": "❌ Erreur lors du chargement de l'historique : {error}"
 
 
 
84
  }
85
  }
86
 
87
  @tool
88
  def recognize_song(audio_path: str) -> dict:
89
- """Recognizes a song from an audio file using AudD API
90
  Args:
91
  audio_path: path to the audio file to recognize
92
  """
93
  AUDD_API_TOKEN = os.getenv("AUDD_API_TOKEN")
94
- print(f"Token usado: {AUDD_API_TOKEN}")
95
  if not os.path.exists(audio_path):
96
- print(f"Audio file not found: {audio_path}")
97
  return {"error": "The audio file does not exist"}
 
98
  try:
99
  with open(audio_path, 'rb') as file:
100
  data = {'api_token': AUDD_API_TOKEN, 'return': 'spotify,apple_music'}
101
  files = {'file': file}
102
- print(f"Sending request to AudD API for {audio_path}")
103
  response = requests.post('https://api.audd.io/', data=data, files=files)
104
- print(f"AudD Response: {response.status_code} - {response.text}")
105
 
106
  if response.status_code != 200:
107
  return {"error": f"API Error: {response.status_code}"}
@@ -125,19 +131,24 @@ def recognize_song(audio_path: str) -> dict:
125
  save_to_history(song_data)
126
  return song_data
127
  except Exception as e:
128
- print(f"Error processing audio {audio_path}: {str(e)}")
129
  return {"error": f"Error processing audio: {str(e)}"}
130
 
131
  def save_to_history(song_data):
 
132
  try:
133
  if os.path.exists(HISTORY_FILE):
134
  with open(HISTORY_FILE, 'r') as f:
135
- history = json.load(f)
 
 
 
136
  else:
137
  history = []
 
138
  history.insert(0, song_data)
139
  if len(history) > 50:
140
  history = history[:50]
 
141
  with open(HISTORY_FILE, 'w') as f:
142
  json.dump(history, f, indent=2)
143
  except Exception as e:
@@ -145,13 +156,21 @@ def save_to_history(song_data):
145
 
146
  @tool
147
  def view_song_history(limit: int = 10, language: str = "en") -> str:
 
 
 
 
 
148
  lang = LANGUAGES.get(language, "en")
149
  try:
150
  if not os.path.exists(HISTORY_FILE):
151
  return f"📋 {MESSAGES[lang]['no_history']}"
152
 
153
  with open(HISTORY_FILE, 'r') as f:
154
- history = json.load(f)
 
 
 
155
 
156
  if not history:
157
  return f"📋 {MESSAGES[lang]['empty_history']}"
@@ -172,6 +191,12 @@ def view_song_history(limit: int = 10, language: str = "en") -> str:
172
 
173
  @tool
174
  def get_artist_info(artist_name: str, song_title: str, language: str = "en") -> dict:
 
 
 
 
 
 
175
  prompts = {
176
  "en": f"Provide a detailed overview of the music artist '{artist_name}' including general information about their career, anecdotes, fun facts about the group, and specific details about the creation of their song '{song_title}' if available. Include an image URL if possible. Keep it engaging and positive.",
177
  "es": f"Proporciona una visión detallada del artista musical '{artist_name}' incluyendo información general sobre su carrera, anécdotas, datos curiosos sobre el grupo y detalles específicos sobre la creación de su canción '{song_title}' si están disponibles. Incluye una URL de imagen si es posible. Mantenlo atractivo y positivo.",
@@ -185,7 +210,6 @@ def get_artist_info(artist_name: str, song_title: str, language: str = "en") ->
185
 
186
  try:
187
  response = model(messages)
188
- # Simple parsing to extract image URL if present (assuming model might return something like [Image: URL])
189
  content = response.content
190
  image_url = None
191
  if "[Image:" in content:
@@ -197,6 +221,7 @@ def get_artist_info(artist_name: str, song_title: str, language: str = "en") ->
197
  except Exception as e:
198
  return {"text": f"Could not retrieve information about {artist_name}: {str(e)}", "image": None}
199
 
 
200
  final_answer = FinalAnswerTool()
201
  model = HfApiModel(
202
  max_tokens=2096,
@@ -235,7 +260,7 @@ with gr.Blocks(title="Music Recognition & Fun Facts", css=".large-text {font-siz
235
 
236
  with gr.Row():
237
  with gr.Column(scale=1):
238
- audio_input = gr.Audio(type="filepath", visible=False, source="microphone", streaming=False)
239
  record_btn = gr.Button(
240
  lambda: MESSAGES[selected_language.value]["rec_button"],
241
  elem_classes="big-button",
@@ -251,6 +276,19 @@ with gr.Blocks(title="Music Recognition & Fun Facts", css=".large-text {font-siz
251
  artist_info_text = gr.Markdown("")
252
  artist_info_image = gr.Image(type="url", label="Artist Image")
253
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
  with gr.Row():
255
  history_limit = gr.Slider(
256
  minimum=5, maximum=50, value=10, step=5,
@@ -267,7 +305,6 @@ with gr.Blocks(title="Music Recognition & Fun Facts", css=".large-text {font-siz
267
 
268
  def update_audio_status(audio_path):
269
  lang = LANGUAGES.get(selected_language.value, "en")
270
- print(f"Ruta del archivo de audio: {audio_path}")
271
  if audio_path:
272
  return "ready", MESSAGES[lang]["audio_loaded"]
273
  return "no_audio", MESSAGES[lang]["no_audio"]
@@ -282,7 +319,6 @@ with gr.Blocks(title="Music Recognition & Fun Facts", css=".large-text {font-siz
282
 
283
  result = recognize_song(audio_path)
284
  if "error" in result:
285
- print(f"Error desde AudD: {result['error']}")
286
  return None, "", "", MESSAGES[lang]["error"].format(error=result['error']), ""
287
 
288
  recognition_msg = f"### 🎵 {result['Song']}\n\n"
@@ -298,6 +334,16 @@ with gr.Blocks(title="Music Recognition & Fun Facts", css=".large-text {font-siz
298
 
299
  return result, recognition_msg, artist_info_content, MESSAGES[lang]["recognized"], artist_info['image'] or ""
300
 
 
 
 
 
 
 
 
 
 
 
301
  def view_history_process(limit, language_name):
302
  return view_song_history(int(limit), LANGUAGES.get(language_name, "en"))
303
 
@@ -309,6 +355,9 @@ with gr.Blocks(title="Music Recognition & Fun Facts", css=".large-text {font-siz
309
  gr.update(label=MESSAGES[lang]["language_label"]),
310
  MESSAGES[lang]["rec_button"],
311
  MESSAGES[lang]["recognize_button"],
 
 
 
312
  gr.update(label=MESSAGES[lang]["history_limit_label"]),
313
  MESSAGES[lang]["history_button"]
314
  )
@@ -316,7 +365,7 @@ with gr.Blocks(title="Music Recognition & Fun Facts", css=".large-text {font-siz
316
  language_dropdown.change(
317
  fn=update_language,
318
  inputs=[language_dropdown],
319
- outputs=[demo.get_component(0), demo.get_component(1), language_dropdown, record_btn, recognize_btn, history_limit, view_history_btn]
320
  )
321
 
322
  record_btn.click(
@@ -337,6 +386,16 @@ with gr.Blocks(title="Music Recognition & Fun Facts", css=".large-text {font-siz
337
  outputs=[song_info_state, recognition_results, artist_info_text, audio_status_msg, artist_info_image]
338
  )
339
 
 
 
 
 
 
 
 
 
 
 
340
  view_history_btn.click(
341
  fn=view_history_process,
342
  inputs=[history_limit, language_dropdown],
 
38
  "history_limit_label": "Number of songs to show",
39
  "no_history": "📋 No song recognition history yet",
40
  "empty_history": "📋 Song history is empty",
41
+ "history_error": "❌ Error loading song history: {error}",
42
+ "chat_title": "### Ask me more about this artist or music in general",
43
+ "chat_placeholder": "Ask about the artist, song, or anything music related...",
44
+ "chat_button": "Send"
45
  },
46
  "es": {
47
  "title": "# 🎵 Reconocimiento Musical y Datos Curiosos",
 
62
  "history_limit_label": "Número de canciones a mostrar",
63
  "no_history": "📋 No hay historial de canciones reconocidas todavía",
64
  "empty_history": "📋 El historial de canciones está vacío",
65
+ "history_error": "❌ Error al cargar el historial: {error}",
66
+ "chat_title": "### Pregúntame más sobre este artista o música en general",
67
+ "chat_placeholder": "Pregunta sobre el artista, la canción o cualquier tema musical...",
68
+ "chat_button": "Enviar"
69
  },
70
  "fr": {
71
  "title": "# 🎵 Reconnaissance Musicale et Anecdotes",
 
86
  "history_limit_label": "Nombre de chansons à afficher",
87
  "no_history": "📋 Aucun historique de reconnaissance de chansons pour l'instant",
88
  "empty_history": "📋 L'historique des chansons est vide",
89
+ "history_error": "❌ Erreur lors du chargement de l'historique : {error}",
90
+ "chat_title": "### Posez-moi des questions sur cet artiste ou la musique en général",
91
+ "chat_placeholder": "Posez des questions sur l'artiste, la chanson ou tout sujet musical...",
92
+ "chat_button": "Envoyer"
93
  }
94
  }
95
 
96
  @tool
97
  def recognize_song(audio_path: str) -> dict:
98
+ """Recognizes a song from an audio file
99
  Args:
100
  audio_path: path to the audio file to recognize
101
  """
102
  AUDD_API_TOKEN = os.getenv("AUDD_API_TOKEN")
 
103
  if not os.path.exists(audio_path):
 
104
  return {"error": "The audio file does not exist"}
105
+
106
  try:
107
  with open(audio_path, 'rb') as file:
108
  data = {'api_token': AUDD_API_TOKEN, 'return': 'spotify,apple_music'}
109
  files = {'file': file}
 
110
  response = requests.post('https://api.audd.io/', data=data, files=files)
 
111
 
112
  if response.status_code != 200:
113
  return {"error": f"API Error: {response.status_code}"}
 
131
  save_to_history(song_data)
132
  return song_data
133
  except Exception as e:
 
134
  return {"error": f"Error processing audio: {str(e)}"}
135
 
136
  def save_to_history(song_data):
137
+ """Saves a song to the history"""
138
  try:
139
  if os.path.exists(HISTORY_FILE):
140
  with open(HISTORY_FILE, 'r') as f:
141
+ try:
142
+ history = json.load(f)
143
+ except json.JSONDecodeError:
144
+ history = []
145
  else:
146
  history = []
147
+
148
  history.insert(0, song_data)
149
  if len(history) > 50:
150
  history = history[:50]
151
+
152
  with open(HISTORY_FILE, 'w') as f:
153
  json.dump(history, f, indent=2)
154
  except Exception as e:
 
156
 
157
  @tool
158
  def view_song_history(limit: int = 10, language: str = "en") -> str:
159
+ """Shows the history of recognized songs
160
+ Args:
161
+ limit: maximum number of songs to display (default 10)
162
+ language: language code (en, es, fr)
163
+ """
164
  lang = LANGUAGES.get(language, "en")
165
  try:
166
  if not os.path.exists(HISTORY_FILE):
167
  return f"📋 {MESSAGES[lang]['no_history']}"
168
 
169
  with open(HISTORY_FILE, 'r') as f:
170
+ try:
171
+ history = json.load(f)
172
+ except json.JSONDecodeError:
173
+ return f"📋 Error loading song history."
174
 
175
  if not history:
176
  return f"📋 {MESSAGES[lang]['empty_history']}"
 
191
 
192
  @tool
193
  def get_artist_info(artist_name: str, song_title: str, language: str = "en") -> dict:
194
+ """Gets detailed artist info including anecdotes and song creation facts
195
+ Args:
196
+ artist_name: name of the artist
197
+ song_title: title of the song
198
+ language: language code (en, es, fr)
199
+ """
200
  prompts = {
201
  "en": f"Provide a detailed overview of the music artist '{artist_name}' including general information about their career, anecdotes, fun facts about the group, and specific details about the creation of their song '{song_title}' if available. Include an image URL if possible. Keep it engaging and positive.",
202
  "es": f"Proporciona una visión detallada del artista musical '{artist_name}' incluyendo información general sobre su carrera, anécdotas, datos curiosos sobre el grupo y detalles específicos sobre la creación de su canción '{song_title}' si están disponibles. Incluye una URL de imagen si es posible. Mantenlo atractivo y positivo.",
 
210
 
211
  try:
212
  response = model(messages)
 
213
  content = response.content
214
  image_url = None
215
  if "[Image:" in content:
 
221
  except Exception as e:
222
  return {"text": f"Could not retrieve information about {artist_name}: {str(e)}", "image": None}
223
 
224
+ # Agent configuration
225
  final_answer = FinalAnswerTool()
226
  model = HfApiModel(
227
  max_tokens=2096,
 
260
 
261
  with gr.Row():
262
  with gr.Column(scale=1):
263
+ audio_input = gr.Audio(type="filepath", visible=False, source="microphone")
264
  record_btn = gr.Button(
265
  lambda: MESSAGES[selected_language.value]["rec_button"],
266
  elem_classes="big-button",
 
276
  artist_info_text = gr.Markdown("")
277
  artist_info_image = gr.Image(type="url", label="Artist Image")
278
 
279
+ gr.Markdown(lambda: MESSAGES[selected_language.value]["chat_title"])
280
+ chat_history = gr.Chatbot(label="Music Chat")
281
+
282
+ with gr.Row():
283
+ chat_input = gr.Textbox(
284
+ placeholder=lambda: MESSAGES[selected_language.value]["chat_placeholder"],
285
+ label="Your question"
286
+ )
287
+ chat_btn = gr.Button(
288
+ lambda: MESSAGES[selected_language.value]["chat_button"],
289
+ variant="primary"
290
+ )
291
+
292
  with gr.Row():
293
  history_limit = gr.Slider(
294
  minimum=5, maximum=50, value=10, step=5,
 
305
 
306
  def update_audio_status(audio_path):
307
  lang = LANGUAGES.get(selected_language.value, "en")
 
308
  if audio_path:
309
  return "ready", MESSAGES[lang]["audio_loaded"]
310
  return "no_audio", MESSAGES[lang]["no_audio"]
 
319
 
320
  result = recognize_song(audio_path)
321
  if "error" in result:
 
322
  return None, "", "", MESSAGES[lang]["error"].format(error=result['error']), ""
323
 
324
  recognition_msg = f"### 🎵 {result['Song']}\n\n"
 
334
 
335
  return result, recognition_msg, artist_info_content, MESSAGES[lang]["recognized"], artist_info['image'] or ""
336
 
337
+ def process_chat(query, language_name, song_info):
338
+ lang = LANGUAGES.get(language_name, "en")
339
+ if not query or not song_info:
340
+ return []
341
+ try:
342
+ response = chat_with_assistant(query, "", lang)
343
+ return [(query, response)]
344
+ except Exception as e:
345
+ return [(query, f"Sorry, I couldn't process your request: {str(e)}")]
346
+
347
  def view_history_process(limit, language_name):
348
  return view_song_history(int(limit), LANGUAGES.get(language_name, "en"))
349
 
 
355
  gr.update(label=MESSAGES[lang]["language_label"]),
356
  MESSAGES[lang]["rec_button"],
357
  MESSAGES[lang]["recognize_button"],
358
+ MESSAGES[lang]["chat_title"],
359
+ gr.update(placeholder=MESSAGES[lang]["chat_placeholder"]),
360
+ MESSAGES[lang]["chat_button"],
361
  gr.update(label=MESSAGES[lang]["history_limit_label"]),
362
  MESSAGES[lang]["history_button"]
363
  )
 
365
  language_dropdown.change(
366
  fn=update_language,
367
  inputs=[language_dropdown],
368
+ outputs=[demo.get_component(0), demo.get_component(1), language_dropdown, record_btn, recognize_btn, demo.get_component(8), chat_input, chat_btn, history_limit, view_history_btn]
369
  )
370
 
371
  record_btn.click(
 
386
  outputs=[song_info_state, recognition_results, artist_info_text, audio_status_msg, artist_info_image]
387
  )
388
 
389
+ chat_btn.click(
390
+ fn=process_chat,
391
+ inputs=[chat_input, language_dropdown, song_info_state],
392
+ outputs=[chat_history]
393
+ ).then(
394
+ fn=lambda: "",
395
+ inputs=[],
396
+ outputs=[chat_input]
397
+ )
398
+
399
  view_history_btn.click(
400
  fn=view_history_process,
401
  inputs=[history_limit, language_dropdown],