Haider67 commited on
Commit
54d38c4
·
verified ·
1 Parent(s): 0dfaeae

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -94
app.py CHANGED
@@ -4,8 +4,8 @@ import re
4
  import json
5
  import traceback
6
  import tempfile
7
- import subprocess
8
 
 
9
  import wikipedia
10
  import gradio as gr
11
  import requests
@@ -19,7 +19,6 @@ from groq import Groq
19
  # CONFIGURATION
20
  # =========================================================
21
 
22
- # Hugging Face Agents Course evaluation API
23
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
24
 
25
  GROQ_MODEL = "openai/gpt-oss-120b"
@@ -28,14 +27,16 @@ AUDIO_MODEL = "whisper-large-v3"
28
  SYSTEM_PROMPT = """
29
  You are a precise AI assistant solving GAIA benchmark questions.
30
 
31
- CRITICAL OUTPUT RULES:
32
- - Reply with ONLY the exact final answer and nothing else.
33
- - Do NOT write 'FINAL ANSWER', explanations, full sentences, or trailing periods.
34
- - If a number is requested, output only the digits (e.g., 42).
35
- - If USD with two decimal places is requested, output e.g. 123.45.
36
- - If a comma-separated list is requested, follow exact alphabetical or ascending order and spacing (e.g., apple, banana).
37
- - Carefully inspect the question and supporting context before answering.
38
- - Never invent facts. If the answer cannot be determined, make your best evidence-based attempt.
 
 
39
  """
40
 
41
 
@@ -48,15 +49,30 @@ def get_groq_client():
48
 
49
  if not api_key:
50
  raise RuntimeError(
51
- "GROQ_API_KEY is missing. "
52
- "Add it in Hugging Face Space Settings > Variables and secrets."
53
  )
54
 
55
  return Groq(api_key=api_key)
56
 
57
 
58
  # =========================================================
59
- # FILE DOWNLOAD
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  # =========================================================
61
 
62
  def download_file(task_id: str, file_name: str) -> str | None:
@@ -70,24 +86,25 @@ def download_file(task_id: str, file_name: str) -> str | None:
70
  response = requests.get(url, timeout=30)
71
  response.raise_for_status()
72
 
73
- if response.content:
74
- tmp_dir = tempfile.mkdtemp()
75
- safe_name = os.path.basename(file_name)
76
- file_path = os.path.join(tmp_dir, safe_name)
77
 
78
- with open(file_path, "wb") as file:
79
- file.write(response.content)
 
80
 
81
- return file_path
 
82
 
83
- except Exception as error:
84
- print(f"File download failed for {task_id}: {error}")
85
 
86
- return None
 
 
87
 
88
 
89
  # =========================================================
90
- # ATTACHED FILE READER
91
  # =========================================================
92
 
93
  def read_attached_file(file_path: str) -> str:
@@ -99,24 +116,13 @@ def read_attached_file(file_path: str) -> str:
99
 
100
  try:
101
 
102
- # Python files
103
  if ext == ".py":
104
 
105
  with open(file_path, "r", encoding="utf-8") as file:
106
  code = file.read()
107
 
108
- result = subprocess.run(
109
- ["python3", file_path],
110
- capture_output=True,
111
- text=True,
112
- timeout=15
113
- )
114
-
115
- return (
116
- f"Python Code:\n{code}\n\n"
117
- f"Execution Output:\n{result.stdout.strip()}\n\n"
118
- f"Execution Errors:\n{result.stderr.strip()}"
119
- )
120
 
121
  # Excel files
122
  elif ext in [".xlsx", ".xls"]:
@@ -125,7 +131,7 @@ def read_attached_file(file_path: str) -> str:
125
 
126
  return (
127
  "Excel Table Contents:\n"
128
- + df.to_string(index=False)
129
  )
130
 
131
  # Audio files
@@ -152,9 +158,7 @@ def read_attached_file(file_path: str) -> str:
152
  )
153
 
154
  return (
155
- f"Audio Transcript "
156
- f"({os.path.basename(file_path)}):\n"
157
- f"{transcript}"
158
  )
159
 
160
  # Text, CSV and JSON files
@@ -167,16 +171,19 @@ def read_attached_file(file_path: str) -> str:
167
  errors="ignore"
168
  ) as file:
169
 
170
- return file.read()[:6000]
171
 
172
  except Exception as error:
173
 
174
  return (
175
- f"File read error "
176
  f"({os.path.basename(file_path)}): {error}"
177
  )
178
 
179
- return f"[Attached file: {os.path.basename(file_path)}]"
 
 
 
180
 
181
 
182
  # =========================================================
@@ -205,7 +212,7 @@ def search_web_and_wiki(question: str) -> str:
205
 
206
  snippets = []
207
 
208
- # DuckDuckGo search
209
  try:
210
 
211
  ddg_results = DDGS().text(
@@ -222,9 +229,9 @@ def search_web_and_wiki(question: str) -> str:
222
  )
223
 
224
  except Exception as error:
225
- print(f"Web search error: {error}")
226
 
227
- # Wikipedia search
228
  try:
229
 
230
  titles = wikipedia.search(query, results=2)
@@ -259,7 +266,9 @@ def generate_answers(prompts: list[str]) -> list[str]:
259
 
260
  for index, user_prompt in enumerate(prompts, start=1):
261
 
262
- print(f"Generating answer {index}/{len(prompts)}")
 
 
263
 
264
  completion = client.chat.completions.create(
265
  model=GROQ_MODEL,
@@ -288,7 +297,7 @@ def generate_answers(prompts: list[str]) -> list[str]:
288
 
289
 
290
  # =========================================================
291
- # MAIN EVALUATION AND SUBMISSION
292
  # =========================================================
293
 
294
  def run_and_submit_all(profile: gr.OAuthProfile | None):
@@ -298,7 +307,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
298
  # Check Hugging Face login
299
  if not profile:
300
  return (
301
- "Please log in to Hugging Face using the Login button.",
302
  None
303
  )
304
 
@@ -315,7 +324,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
315
 
316
  space_id = space_id.strip("/")
317
 
318
- # Evaluation API endpoints
319
  questions_url = f"{DEFAULT_API_URL}/questions"
320
  submit_url = f"{DEFAULT_API_URL}/submit"
321
 
@@ -327,43 +336,28 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
327
  # FETCH QUESTIONS
328
  # -------------------------------------------------
329
 
330
- questions_data = None
331
-
332
- try:
333
-
334
- response = requests.get(
335
- questions_url,
336
- timeout=30
337
- )
338
-
339
- response.raise_for_status()
340
-
341
- questions_data = response.json()
342
-
343
- except Exception as error:
344
 
345
- print(f"Question API error: {error}")
346
-
347
- # Local fallback
348
- if not questions_data and os.path.exists("questions.json"):
349
 
350
- with open(
351
- "questions.json",
352
- "r",
353
- encoding="utf-8"
354
- ) as file:
355
 
356
- questions_data = json.load(file)
357
 
358
- if not questions_data:
359
 
360
  return (
361
- "Error: Could not load evaluation questions.",
362
  None
363
  )
364
 
 
 
365
  # -------------------------------------------------
366
- # PROCESS QUESTIONS
367
  # -------------------------------------------------
368
 
369
  valid_items = []
@@ -379,17 +373,16 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
379
  continue
380
 
381
  print(
382
- f"Processing question {index}/"
383
- f"{len(questions_data)}"
384
  )
385
 
386
- # Download attached file
387
  file_path = download_file(
388
  task_id,
389
  file_name
390
  )
391
 
392
- # Read attachment or search for context
393
  if file_path:
394
 
395
  context = read_attached_file(file_path)
@@ -400,7 +393,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
400
  question_text
401
  )
402
 
403
- # Build prompt
404
  user_prompt = question_text
405
 
406
  if context:
@@ -416,22 +408,32 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
416
  if not prompts:
417
 
418
  return (
419
- "Error: No valid questions were found.",
420
  None
421
  )
422
 
423
  # -------------------------------------------------
424
- # GENERATE ANSWERS USING GROQ
425
  # -------------------------------------------------
426
 
 
 
427
  final_answers = generate_answers(prompts)
428
 
 
 
 
 
 
 
 
 
429
  # -------------------------------------------------
430
  # PREPARE SUBMISSION
431
  # -------------------------------------------------
432
 
433
- results_log = []
434
  answers_payload = []
 
435
 
436
  for item, answer in zip(valid_items, final_answers):
437
 
@@ -457,9 +459,11 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
457
  }
458
 
459
  # -------------------------------------------------
460
- # SUBMIT ANSWERS
461
  # -------------------------------------------------
462
 
 
 
463
  response = requests.post(
464
  submit_url,
465
  json=submission_data,
@@ -471,19 +475,26 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
471
  result_data = response.json()
472
 
473
  # -------------------------------------------------
474
- # DISPLAY RESULT
475
  # -------------------------------------------------
476
 
477
  final_status = (
478
  "Submission Successful!\n"
479
  f"User: {result_data.get('username', username)}\n"
480
  f"Overall Score: {result_data.get('score', 'N/A')}%\n"
481
- f"Correct: {result_data.get('correct_count', '?')}/"
 
482
  f"{result_data.get('total_attempted', '?')}\n"
483
- f"Message: {result_data.get('message', 'No message received.')}"
 
484
  )
485
 
486
- return final_status, pd.DataFrame(results_log)
 
 
 
 
 
487
 
488
  except Exception:
489
 
@@ -508,7 +519,7 @@ with gr.Blocks() as demo:
508
  )
509
 
510
  gr.Markdown(
511
- "Log in with Hugging Face and run the evaluation."
512
  )
513
 
514
  gr.LoginButton()
@@ -529,8 +540,27 @@ with gr.Blocks() as demo:
529
  wrap=True
530
  )
531
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532
  run_button.click(
533
  fn=run_and_submit_all,
 
534
  outputs=[
535
  status_output,
536
  results_table
@@ -539,9 +569,8 @@ with gr.Blocks() as demo:
539
 
540
 
541
  # =========================================================
542
- # APPLICATION START
543
  # =========================================================
544
 
545
  if __name__ == "__main__":
546
-
547
  demo.launch()
 
4
  import json
5
  import traceback
6
  import tempfile
 
7
 
8
+ import spaces
9
  import wikipedia
10
  import gradio as gr
11
  import requests
 
19
  # CONFIGURATION
20
  # =========================================================
21
 
 
22
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
23
 
24
  GROQ_MODEL = "openai/gpt-oss-120b"
 
27
  SYSTEM_PROMPT = """
28
  You are a precise AI assistant solving GAIA benchmark questions.
29
 
30
+ Follow these rules:
31
+ - Return only the exact answer.
32
+ - Do not write "FINAL ANSWER".
33
+ - Do not include explanations unless the question requests them.
34
+ - Do not add unnecessary introductory text or trailing punctuation.
35
+ - If a number is requested, return only the number.
36
+ - If USD with two decimal places is requested, use the format 123.45.
37
+ - If a comma-separated list is requested, follow the requested order and spacing.
38
+ - Use the question and supporting context carefully.
39
+ - Never invent facts.
40
  """
41
 
42
 
 
49
 
50
  if not api_key:
51
  raise RuntimeError(
52
+ "GROQ_API_KEY is missing. Add it under "
53
+ "Hugging Face Space Settings > Variables and secrets."
54
  )
55
 
56
  return Groq(api_key=api_key)
57
 
58
 
59
  # =========================================================
60
+ # ZERO GPU STARTUP COMPATIBILITY
61
+ # =========================================================
62
+
63
+ # ZeroGPU requires at least one registered Gradio handler
64
+ # decorated with @spaces.GPU.
65
+ #
66
+ # This hidden handler is not used for actual AI inference.
67
+ # The real answer generation is performed by Groq.
68
+
69
+ @spaces.GPU(duration=60)
70
+ def zerogpu_compatibility_check():
71
+ return "ZeroGPU compatibility handler registered."
72
+
73
+
74
+ # =========================================================
75
+ # DOWNLOAD ATTACHED FILES
76
  # =========================================================
77
 
78
  def download_file(task_id: str, file_name: str) -> str | None:
 
86
  response = requests.get(url, timeout=30)
87
  response.raise_for_status()
88
 
89
+ if not response.content:
90
+ return None
 
 
91
 
92
+ temp_dir = tempfile.mkdtemp()
93
+ safe_name = os.path.basename(file_name)
94
+ file_path = os.path.join(temp_dir, safe_name)
95
 
96
+ with open(file_path, "wb") as file:
97
+ file.write(response.content)
98
 
99
+ return file_path
 
100
 
101
+ except Exception as error:
102
+ print(f"File download error for {task_id}: {error}")
103
+ return None
104
 
105
 
106
  # =========================================================
107
+ # READ ATTACHED FILES
108
  # =========================================================
109
 
110
  def read_attached_file(file_path: str) -> str:
 
116
 
117
  try:
118
 
119
+ # Python source files
120
  if ext == ".py":
121
 
122
  with open(file_path, "r", encoding="utf-8") as file:
123
  code = file.read()
124
 
125
+ return f"Python Source Code:\n{code[:10000]}"
 
 
 
 
 
 
 
 
 
 
 
126
 
127
  # Excel files
128
  elif ext in [".xlsx", ".xls"]:
 
131
 
132
  return (
133
  "Excel Table Contents:\n"
134
+ + df.to_string(index=False)[:10000]
135
  )
136
 
137
  # Audio files
 
158
  )
159
 
160
  return (
161
+ f"Audio Transcript:\n{transcript}"
 
 
162
  )
163
 
164
  # Text, CSV and JSON files
 
171
  errors="ignore"
172
  ) as file:
173
 
174
+ return file.read()[:10000]
175
 
176
  except Exception as error:
177
 
178
  return (
179
+ f"File reading error "
180
  f"({os.path.basename(file_path)}): {error}"
181
  )
182
 
183
+ return (
184
+ f"Attachment: {os.path.basename(file_path)}. "
185
+ "This file format is not currently supported."
186
+ )
187
 
188
 
189
  # =========================================================
 
212
 
213
  snippets = []
214
 
215
+ # DuckDuckGo
216
  try:
217
 
218
  ddg_results = DDGS().text(
 
229
  )
230
 
231
  except Exception as error:
232
+ print(f"DuckDuckGo search error: {error}")
233
 
234
+ # Wikipedia
235
  try:
236
 
237
  titles = wikipedia.search(query, results=2)
 
266
 
267
  for index, user_prompt in enumerate(prompts, start=1):
268
 
269
+ print(
270
+ f"Generating answer {index}/{len(prompts)}"
271
+ )
272
 
273
  completion = client.chat.completions.create(
274
  model=GROQ_MODEL,
 
297
 
298
 
299
  # =========================================================
300
+ # MAIN GAIA EVALUATION
301
  # =========================================================
302
 
303
  def run_and_submit_all(profile: gr.OAuthProfile | None):
 
307
  # Check Hugging Face login
308
  if not profile:
309
  return (
310
+ "Please log in using the Hugging Face Login button.",
311
  None
312
  )
313
 
 
324
 
325
  space_id = space_id.strip("/")
326
 
327
+ # API endpoints
328
  questions_url = f"{DEFAULT_API_URL}/questions"
329
  submit_url = f"{DEFAULT_API_URL}/submit"
330
 
 
336
  # FETCH QUESTIONS
337
  # -------------------------------------------------
338
 
339
+ print("Fetching GAIA questions...")
 
 
 
 
 
 
 
 
 
 
 
 
 
340
 
341
+ response = requests.get(
342
+ questions_url,
343
+ timeout=30
344
+ )
345
 
346
+ response.raise_for_status()
 
 
 
 
347
 
348
+ questions_data = response.json()
349
 
350
+ if not isinstance(questions_data, list) or not questions_data:
351
 
352
  return (
353
+ "Error: The evaluation API returned no valid questions.",
354
  None
355
  )
356
 
357
+ print(f"Fetched {len(questions_data)} questions.")
358
+
359
  # -------------------------------------------------
360
+ # PREPARE QUESTIONS AND CONTEXT
361
  # -------------------------------------------------
362
 
363
  valid_items = []
 
373
  continue
374
 
375
  print(
376
+ f"Preparing question {index}/{len(questions_data)}"
 
377
  )
378
 
379
+ # Download attachment if available
380
  file_path = download_file(
381
  task_id,
382
  file_name
383
  )
384
 
385
+ # Read attachment or search for supporting context
386
  if file_path:
387
 
388
  context = read_attached_file(file_path)
 
393
  question_text
394
  )
395
 
 
396
  user_prompt = question_text
397
 
398
  if context:
 
408
  if not prompts:
409
 
410
  return (
411
+ "Error: No valid questions were prepared.",
412
  None
413
  )
414
 
415
  # -------------------------------------------------
416
+ # GENERATE ANSWERS
417
  # -------------------------------------------------
418
 
419
+ print("Starting Groq answer generation...")
420
+
421
  final_answers = generate_answers(prompts)
422
 
423
+ if len(final_answers) != len(valid_items):
424
+
425
+ return (
426
+ "Error: The number of generated answers "
427
+ "does not match the number of questions.",
428
+ None
429
+ )
430
+
431
  # -------------------------------------------------
432
  # PREPARE SUBMISSION
433
  # -------------------------------------------------
434
 
 
435
  answers_payload = []
436
+ results_log = []
437
 
438
  for item, answer in zip(valid_items, final_answers):
439
 
 
459
  }
460
 
461
  # -------------------------------------------------
462
+ # SUBMIT TO GAIA SCORING API
463
  # -------------------------------------------------
464
 
465
+ print("Submitting answers to the scoring API...")
466
+
467
  response = requests.post(
468
  submit_url,
469
  json=submission_data,
 
475
  result_data = response.json()
476
 
477
  # -------------------------------------------------
478
+ # DISPLAY SCORE
479
  # -------------------------------------------------
480
 
481
  final_status = (
482
  "Submission Successful!\n"
483
  f"User: {result_data.get('username', username)}\n"
484
  f"Overall Score: {result_data.get('score', 'N/A')}%\n"
485
+ f"Correct Answers: "
486
+ f"{result_data.get('correct_count', '?')}/"
487
  f"{result_data.get('total_attempted', '?')}\n"
488
+ f"Message: "
489
+ f"{result_data.get('message', 'No message received.')}"
490
  )
491
 
492
+ print(final_status)
493
+
494
+ return (
495
+ final_status,
496
+ pd.DataFrame(results_log)
497
+ )
498
 
499
  except Exception:
500
 
 
519
  )
520
 
521
  gr.Markdown(
522
+ "Log in with Hugging Face and run your GAIA evaluation."
523
  )
524
 
525
  gr.LoginButton()
 
540
  wrap=True
541
  )
542
 
543
+ # Hidden ZeroGPU compatibility components.
544
+ # This handler is registered but is not called by the user.
545
+ compatibility_button = gr.Button(
546
+ "ZeroGPU Compatibility",
547
+ visible=False
548
+ )
549
+
550
+ compatibility_output = gr.Textbox(
551
+ visible=False
552
+ )
553
+
554
+ compatibility_button.click(
555
+ fn=zerogpu_compatibility_check,
556
+ inputs=[],
557
+ outputs=compatibility_output
558
+ )
559
+
560
+ # Actual evaluation uses Groq, not ZeroGPU.
561
  run_button.click(
562
  fn=run_and_submit_all,
563
+ inputs=[],
564
  outputs=[
565
  status_output,
566
  results_table
 
569
 
570
 
571
  # =========================================================
572
+ # START APPLICATION
573
  # =========================================================
574
 
575
  if __name__ == "__main__":
 
576
  demo.launch()