Haider67 commited on
Commit
36fc24b
·
verified ·
1 Parent(s): 6b8d46c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -125
app.py CHANGED
@@ -1,4 +1,3 @@
1
-
2
  import os
3
  import re
4
  import json
@@ -21,9 +20,7 @@ from google.genai import types
21
  # =========================================================
22
 
23
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
24
-
25
  GEMINI_MODEL = "gemini-3.5-flash-lite"
26
- AUDIO_MODEL = "whisper-large-v3"
27
 
28
  SYSTEM_PROMPT = """
29
  You are a precise AI assistant solving GAIA benchmark questions.
@@ -42,7 +39,7 @@ Follow these rules:
42
 
43
 
44
  # =========================================================
45
- # GROQ CLIENT
46
  # =========================================================
47
 
48
  def get_gemini_client():
@@ -75,16 +72,27 @@ def generate_gemini_response(prompt: str) -> str:
75
  return response.text.strip()
76
 
77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
  # =========================================================
80
  # ZERO GPU STARTUP COMPATIBILITY
81
  # =========================================================
82
 
83
- # ZeroGPU requires at least one registered Gradio handler
84
- # decorated with @spaces.GPU.
85
- #
86
- # This hidden handler is not used for actual AI inference.
87
- # The real answer generation is performed by Groq.
88
 
89
  @spaces.GPU(duration=60)
90
  def zerogpu_compatibility_check():
@@ -96,7 +104,6 @@ def zerogpu_compatibility_check():
96
  # =========================================================
97
 
98
  def download_file(task_id: str, file_name: str) -> str | None:
99
-
100
  if not file_name:
101
  return None
102
 
@@ -128,17 +135,14 @@ def download_file(task_id: str, file_name: str) -> str | None:
128
  # =========================================================
129
 
130
  def read_attached_file(file_path: str) -> str:
131
-
132
  if not file_path or not os.path.exists(file_path):
133
  return ""
134
 
135
  ext = os.path.splitext(file_path)[1].lower()
136
 
137
  try:
138
-
139
  # Python source files
140
  if ext == ".py":
141
-
142
  with open(file_path, "r", encoding="utf-8") as file:
143
  code = file.read()
144
 
@@ -146,7 +150,6 @@ def read_attached_file(file_path: str) -> str:
146
 
147
  # Excel files
148
  elif ext in [".xlsx", ".xls"]:
149
-
150
  df = pd.read_excel(file_path)
151
 
152
  return (
@@ -154,47 +157,59 @@ def read_attached_file(file_path: str) -> str:
154
  + df.to_string(index=False)[:10000]
155
  )
156
 
157
- # Audio files
158
  elif ext in [
159
  ".mp3",
160
  ".wav",
161
  ".m4a",
162
  ".ogg",
163
  ".webm",
164
- ".flac"
165
  ]:
 
 
 
 
 
 
 
 
166
 
167
- client = get_groq_client()
168
 
169
  with open(file_path, "rb") as audio_file:
170
-
171
- transcript = client.audio.transcriptions.create(
172
- file=(
173
- os.path.basename(file_path),
174
- audio_file.read()
 
 
 
 
175
  ),
176
- model=AUDIO_MODEL,
177
- response_format="text"
178
- )
179
-
180
- return (
181
- f"Audio Transcript:\n{transcript}"
182
  )
183
 
 
 
 
 
 
184
  # Text, CSV and JSON files
185
  elif ext in [".txt", ".csv", ".json"]:
186
-
187
  with open(
188
  file_path,
189
  "r",
190
  encoding="utf-8",
191
- errors="ignore"
192
  ) as file:
193
-
194
  return file.read()[:10000]
195
 
196
  except Exception as error:
197
-
198
  return (
199
  f"File reading error "
200
  f"({os.path.basename(file_path)}): {error}"
@@ -211,7 +226,6 @@ def read_attached_file(file_path: str) -> str:
211
  # =========================================================
212
 
213
  def build_clean_query(question: str) -> str:
214
-
215
  query = re.sub(r"https?://\S+", "", question)
216
 
217
  words = [
@@ -224,7 +238,6 @@ def build_clean_query(question: str) -> str:
224
 
225
 
226
  def search_web_and_wiki(question: str) -> str:
227
-
228
  query = build_clean_query(question)
229
 
230
  if not query:
@@ -234,15 +247,13 @@ def search_web_and_wiki(question: str) -> str:
234
 
235
  # DuckDuckGo
236
  try:
237
-
238
  ddg_results = DDGS().text(
239
  query,
240
  max_results=4,
241
- backend="lite"
242
  )
243
 
244
  for result in ddg_results or []:
245
-
246
  snippets.append(
247
  f"[Web] {result.get('title', '')}: "
248
  f"{result.get('body', '')}"
@@ -253,15 +264,13 @@ def search_web_and_wiki(question: str) -> str:
253
 
254
  # Wikipedia
255
  try:
256
-
257
  titles = wikipedia.search(query, results=2)
258
 
259
  for title in titles:
260
-
261
  summary = wikipedia.summary(
262
  title,
263
  sentences=4,
264
- auto_suggest=False
265
  )
266
 
267
  snippets.append(
@@ -274,61 +283,17 @@ def search_web_and_wiki(question: str) -> str:
274
  return "\n".join(snippets)
275
 
276
 
277
- # =========================================================
278
- # GROQ ANSWER GENERATION
279
- # =========================================================
280
-
281
- def generate_answers(prompts: list[str]) -> list[str]:
282
-
283
- client = get_groq_client()
284
-
285
- answers = []
286
-
287
- for index, user_prompt in enumerate(prompts, start=1):
288
-
289
- print(
290
- f"Generating answer {index}/{len(prompts)}"
291
- )
292
-
293
- completion = client.chat.completions.create(
294
- model=GROQ_MODEL,
295
- messages=[
296
- {
297
- "role": "system",
298
- "content": SYSTEM_PROMPT
299
- },
300
- {
301
- "role": "user",
302
- "content": user_prompt
303
- }
304
- ],
305
- max_completion_tokens=256
306
- )
307
-
308
- answer = (
309
- completion.choices[0].message.content or ""
310
- ).strip()
311
-
312
- answer = answer.strip('"').strip("'").strip()
313
-
314
- answers.append(answer)
315
-
316
- return answers
317
-
318
-
319
  # =========================================================
320
  # MAIN GAIA EVALUATION
321
  # =========================================================
322
 
323
  def run_and_submit_all(profile: gr.OAuthProfile | None):
324
-
325
  try:
326
-
327
  # Check Hugging Face login
328
  if not profile:
329
  return (
330
  "Please log in using the Hugging Face Login button.",
331
- None
332
  )
333
 
334
  username = profile.username
@@ -339,7 +304,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
339
  if not space_id:
340
  return (
341
  "Error: SPACE_ID environment variable is missing.",
342
- None
343
  )
344
 
345
  space_id = space_id.strip("/")
@@ -360,18 +325,16 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
360
 
361
  response = requests.get(
362
  questions_url,
363
- timeout=30
364
  )
365
-
366
  response.raise_for_status()
367
 
368
  questions_data = response.json()
369
 
370
  if not isinstance(questions_data, list) or not questions_data:
371
-
372
  return (
373
  "Error: The evaluation API returned no valid questions.",
374
- None
375
  )
376
 
377
  print(f"Fetched {len(questions_data)} questions.")
@@ -384,7 +347,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
384
  prompts = []
385
 
386
  for index, item in enumerate(questions_data, start=1):
387
-
388
  task_id = item.get("task_id")
389
  question_text = item.get("question")
390
  file_name = item.get("file_name", "")
@@ -399,24 +361,18 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
399
  # Download attachment if available
400
  file_path = download_file(
401
  task_id,
402
- file_name
403
  )
404
 
405
  # Read attachment or search for supporting context
406
  if file_path:
407
-
408
  context = read_attached_file(file_path)
409
-
410
  else:
411
-
412
- context = search_web_and_wiki(
413
- question_text
414
- )
415
 
416
  user_prompt = question_text
417
 
418
  if context:
419
-
420
  user_prompt += (
421
  "\n\n--- Supporting Context ---\n"
422
  + context
@@ -426,26 +382,24 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
426
  prompts.append(user_prompt)
427
 
428
  if not prompts:
429
-
430
  return (
431
  "Error: No valid questions were prepared.",
432
- None
433
  )
434
 
435
  # -------------------------------------------------
436
  # GENERATE ANSWERS
437
  # -------------------------------------------------
438
 
439
- print("Starting Groq answer generation...")
440
 
441
  final_answers = generate_answers(prompts)
442
 
443
  if len(final_answers) != len(valid_items):
444
-
445
  return (
446
  "Error: The number of generated answers "
447
  "does not match the number of questions.",
448
- None
449
  )
450
 
451
  # -------------------------------------------------
@@ -456,11 +410,10 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
456
  results_log = []
457
 
458
  for item, answer in zip(valid_items, final_answers):
459
-
460
  answers_payload.append(
461
  {
462
  "task_id": item["task_id"],
463
- "submitted_answer": answer
464
  }
465
  )
466
 
@@ -468,14 +421,14 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
468
  {
469
  "Task ID": item["task_id"],
470
  "Question": item["question"],
471
- "Submitted Answer": answer
472
  }
473
  )
474
 
475
  submission_data = {
476
  "username": username.strip(),
477
  "agent_code": agent_code,
478
- "answers": answers_payload
479
  }
480
 
481
  # -------------------------------------------------
@@ -487,9 +440,8 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
487
  response = requests.post(
488
  submit_url,
489
  json=submission_data,
490
- timeout=60
491
  )
492
-
493
  response.raise_for_status()
494
 
495
  result_data = response.json()
@@ -513,18 +465,16 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
513
 
514
  return (
515
  final_status,
516
- pd.DataFrame(results_log)
517
  )
518
 
519
  except Exception:
520
-
521
  error_details = traceback.format_exc()
522
-
523
  print(error_details)
524
 
525
  return (
526
  f"Detailed Error:\n{error_details}",
527
- None
528
  )
529
 
530
 
@@ -533,7 +483,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
533
  # =========================================================
534
 
535
  with gr.Blocks() as demo:
536
-
537
  gr.Markdown(
538
  "# Multi-Modal GAIA Agent Evaluation Runner"
539
  )
@@ -546,45 +495,44 @@ with gr.Blocks() as demo:
546
 
547
  run_button = gr.Button(
548
  "Run Evaluation & Submit All Answers",
549
- variant="primary"
550
  )
551
 
552
  status_output = gr.Textbox(
553
  label="Run Status / Submission Result",
554
  lines=8,
555
- interactive=False
556
  )
557
 
558
  results_table = gr.DataFrame(
559
  label="Questions and Agent Answers",
560
- wrap=True
561
  )
562
 
563
  # Hidden ZeroGPU compatibility components.
564
- # This handler is registered but is not called by the user.
565
  compatibility_button = gr.Button(
566
  "ZeroGPU Compatibility",
567
- visible=False
568
  )
569
 
570
  compatibility_output = gr.Textbox(
571
- visible=False
572
  )
573
 
574
  compatibility_button.click(
575
  fn=zerogpu_compatibility_check,
576
  inputs=[],
577
- outputs=compatibility_output
578
  )
579
 
580
- # Actual evaluation uses Groq, not ZeroGPU.
581
  run_button.click(
582
  fn=run_and_submit_all,
583
  inputs=[],
584
  outputs=[
585
  status_output,
586
- results_table
587
- ]
588
  )
589
 
590
 
 
 
1
  import os
2
  import re
3
  import json
 
20
  # =========================================================
21
 
22
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
23
  GEMINI_MODEL = "gemini-3.5-flash-lite"
 
24
 
25
  SYSTEM_PROMPT = """
26
  You are a precise AI assistant solving GAIA benchmark questions.
 
39
 
40
 
41
  # =========================================================
42
+ # GEMINI CLIENT AND ANSWER GENERATION
43
  # =========================================================
44
 
45
  def get_gemini_client():
 
72
  return response.text.strip()
73
 
74
 
75
+ def generate_answers(prompts: list[str]) -> list[str]:
76
+ answers = []
77
+
78
+ for index, user_prompt in enumerate(prompts, start=1):
79
+ print(
80
+ f"Generating Gemini answer {index}/{len(prompts)}"
81
+ )
82
+
83
+ answer = generate_gemini_response(user_prompt)
84
+ answer = answer.strip('"').strip("'").strip()
85
+ answers.append(answer)
86
+
87
+ return answers
88
+
89
 
90
  # =========================================================
91
  # ZERO GPU STARTUP COMPATIBILITY
92
  # =========================================================
93
 
94
+ # Keep this registered handler for the existing ZeroGPU setup.
95
+ # It is not used for Gemini inference.
 
 
 
96
 
97
  @spaces.GPU(duration=60)
98
  def zerogpu_compatibility_check():
 
104
  # =========================================================
105
 
106
  def download_file(task_id: str, file_name: str) -> str | None:
 
107
  if not file_name:
108
  return None
109
 
 
135
  # =========================================================
136
 
137
  def read_attached_file(file_path: str) -> str:
 
138
  if not file_path or not os.path.exists(file_path):
139
  return ""
140
 
141
  ext = os.path.splitext(file_path)[1].lower()
142
 
143
  try:
 
144
  # Python source files
145
  if ext == ".py":
 
146
  with open(file_path, "r", encoding="utf-8") as file:
147
  code = file.read()
148
 
 
150
 
151
  # Excel files
152
  elif ext in [".xlsx", ".xls"]:
 
153
  df = pd.read_excel(file_path)
154
 
155
  return (
 
157
  + df.to_string(index=False)[:10000]
158
  )
159
 
160
+ # Audio files: send audio directly to Gemini
161
  elif ext in [
162
  ".mp3",
163
  ".wav",
164
  ".m4a",
165
  ".ogg",
166
  ".webm",
167
+ ".flac",
168
  ]:
169
+ mime_types = {
170
+ ".mp3": "audio/mpeg",
171
+ ".wav": "audio/wav",
172
+ ".m4a": "audio/mp4",
173
+ ".ogg": "audio/ogg",
174
+ ".webm": "audio/webm",
175
+ ".flac": "audio/flac",
176
+ }
177
 
178
+ client = get_gemini_client()
179
 
180
  with open(file_path, "rb") as audio_file:
181
+ audio_data = audio_file.read()
182
+
183
+ response = client.models.generate_content(
184
+ model=GEMINI_MODEL,
185
+ contents=[
186
+ "Transcribe this audio accurately. Return only the transcript.",
187
+ types.Part.from_bytes(
188
+ data=audio_data,
189
+ mime_type=mime_types.get(ext, "audio/mpeg"),
190
  ),
191
+ ],
192
+ config=types.GenerateContentConfig(
193
+ max_output_tokens=4096,
194
+ ),
 
 
195
  )
196
 
197
+ if not response.text:
198
+ return "Audio transcription failed."
199
+
200
+ return f"Audio Transcript:\n{response.text.strip()}"
201
+
202
  # Text, CSV and JSON files
203
  elif ext in [".txt", ".csv", ".json"]:
 
204
  with open(
205
  file_path,
206
  "r",
207
  encoding="utf-8",
208
+ errors="ignore",
209
  ) as file:
 
210
  return file.read()[:10000]
211
 
212
  except Exception as error:
 
213
  return (
214
  f"File reading error "
215
  f"({os.path.basename(file_path)}): {error}"
 
226
  # =========================================================
227
 
228
  def build_clean_query(question: str) -> str:
 
229
  query = re.sub(r"https?://\S+", "", question)
230
 
231
  words = [
 
238
 
239
 
240
  def search_web_and_wiki(question: str) -> str:
 
241
  query = build_clean_query(question)
242
 
243
  if not query:
 
247
 
248
  # DuckDuckGo
249
  try:
 
250
  ddg_results = DDGS().text(
251
  query,
252
  max_results=4,
253
+ backend="lite",
254
  )
255
 
256
  for result in ddg_results or []:
 
257
  snippets.append(
258
  f"[Web] {result.get('title', '')}: "
259
  f"{result.get('body', '')}"
 
264
 
265
  # Wikipedia
266
  try:
 
267
  titles = wikipedia.search(query, results=2)
268
 
269
  for title in titles:
 
270
  summary = wikipedia.summary(
271
  title,
272
  sentences=4,
273
+ auto_suggest=False,
274
  )
275
 
276
  snippets.append(
 
283
  return "\n".join(snippets)
284
 
285
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
286
  # =========================================================
287
  # MAIN GAIA EVALUATION
288
  # =========================================================
289
 
290
  def run_and_submit_all(profile: gr.OAuthProfile | None):
 
291
  try:
 
292
  # Check Hugging Face login
293
  if not profile:
294
  return (
295
  "Please log in using the Hugging Face Login button.",
296
+ None,
297
  )
298
 
299
  username = profile.username
 
304
  if not space_id:
305
  return (
306
  "Error: SPACE_ID environment variable is missing.",
307
+ None,
308
  )
309
 
310
  space_id = space_id.strip("/")
 
325
 
326
  response = requests.get(
327
  questions_url,
328
+ timeout=30,
329
  )
 
330
  response.raise_for_status()
331
 
332
  questions_data = response.json()
333
 
334
  if not isinstance(questions_data, list) or not questions_data:
 
335
  return (
336
  "Error: The evaluation API returned no valid questions.",
337
+ None,
338
  )
339
 
340
  print(f"Fetched {len(questions_data)} questions.")
 
347
  prompts = []
348
 
349
  for index, item in enumerate(questions_data, start=1):
 
350
  task_id = item.get("task_id")
351
  question_text = item.get("question")
352
  file_name = item.get("file_name", "")
 
361
  # Download attachment if available
362
  file_path = download_file(
363
  task_id,
364
+ file_name,
365
  )
366
 
367
  # Read attachment or search for supporting context
368
  if file_path:
 
369
  context = read_attached_file(file_path)
 
370
  else:
371
+ context = search_web_and_wiki(question_text)
 
 
 
372
 
373
  user_prompt = question_text
374
 
375
  if context:
 
376
  user_prompt += (
377
  "\n\n--- Supporting Context ---\n"
378
  + context
 
382
  prompts.append(user_prompt)
383
 
384
  if not prompts:
 
385
  return (
386
  "Error: No valid questions were prepared.",
387
+ None,
388
  )
389
 
390
  # -------------------------------------------------
391
  # GENERATE ANSWERS
392
  # -------------------------------------------------
393
 
394
+ print("Starting Gemini answer generation...")
395
 
396
  final_answers = generate_answers(prompts)
397
 
398
  if len(final_answers) != len(valid_items):
 
399
  return (
400
  "Error: The number of generated answers "
401
  "does not match the number of questions.",
402
+ None,
403
  )
404
 
405
  # -------------------------------------------------
 
410
  results_log = []
411
 
412
  for item, answer in zip(valid_items, final_answers):
 
413
  answers_payload.append(
414
  {
415
  "task_id": item["task_id"],
416
+ "submitted_answer": answer,
417
  }
418
  )
419
 
 
421
  {
422
  "Task ID": item["task_id"],
423
  "Question": item["question"],
424
+ "Submitted Answer": answer,
425
  }
426
  )
427
 
428
  submission_data = {
429
  "username": username.strip(),
430
  "agent_code": agent_code,
431
+ "answers": answers_payload,
432
  }
433
 
434
  # -------------------------------------------------
 
440
  response = requests.post(
441
  submit_url,
442
  json=submission_data,
443
+ timeout=60,
444
  )
 
445
  response.raise_for_status()
446
 
447
  result_data = response.json()
 
465
 
466
  return (
467
  final_status,
468
+ pd.DataFrame(results_log),
469
  )
470
 
471
  except Exception:
 
472
  error_details = traceback.format_exc()
 
473
  print(error_details)
474
 
475
  return (
476
  f"Detailed Error:\n{error_details}",
477
+ None,
478
  )
479
 
480
 
 
483
  # =========================================================
484
 
485
  with gr.Blocks() as demo:
 
486
  gr.Markdown(
487
  "# Multi-Modal GAIA Agent Evaluation Runner"
488
  )
 
495
 
496
  run_button = gr.Button(
497
  "Run Evaluation & Submit All Answers",
498
+ variant="primary",
499
  )
500
 
501
  status_output = gr.Textbox(
502
  label="Run Status / Submission Result",
503
  lines=8,
504
+ interactive=False,
505
  )
506
 
507
  results_table = gr.DataFrame(
508
  label="Questions and Agent Answers",
509
+ wrap=True,
510
  )
511
 
512
  # Hidden ZeroGPU compatibility components.
 
513
  compatibility_button = gr.Button(
514
  "ZeroGPU Compatibility",
515
+ visible=False,
516
  )
517
 
518
  compatibility_output = gr.Textbox(
519
+ visible=False,
520
  )
521
 
522
  compatibility_button.click(
523
  fn=zerogpu_compatibility_check,
524
  inputs=[],
525
+ outputs=compatibility_output,
526
  )
527
 
528
+ # Actual evaluation uses Gemini.
529
  run_button.click(
530
  fn=run_and_submit_all,
531
  inputs=[],
532
  outputs=[
533
  status_output,
534
+ results_table,
535
+ ],
536
  )
537
 
538