ArdaKaratas commited on
Commit
af1fda7
·
verified ·
1 Parent(s): 0fd0c3f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -7
app.py CHANGED
@@ -32,7 +32,7 @@ HF_TOKEN = os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACE_HUB_TOKEN")
32
 
33
  def get_space_url():
34
  """Get the Hugging Face Space URL."""
35
- space_id = os.getenv("SPACE_ID", f"{HF_USERNAME}/{HF_SPACE_NAME}")
36
  return f"https://huggingface.co/spaces/{space_id}/tree/main"
37
 
38
  def fetch_questions():
@@ -55,6 +55,49 @@ def fetch_random_question():
55
  except Exception as e:
56
  return "", f"Error fetching random question: {str(e)}"
57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  def get_answer_from_metadata(question: str):
59
  """Get the correct answer from metadata.jsonl if available."""
60
  if not os.path.exists(METADATA_FILE):
@@ -147,9 +190,15 @@ def process_all_questions(username: str, space_code: str, use_agent: bool = True
147
  answer_source = "Error"
148
  else:
149
  try:
150
- answer = run_agent(question)
151
- if not answer or answer.strip() == "":
152
  answer = "Agent returned empty answer"
 
 
 
 
 
 
153
  answer_source = "Agent"
154
  except Exception as e:
155
  error_msg = str(e)
@@ -199,11 +248,22 @@ def process_all_questions(username: str, space_code: str, use_agent: bool = True
199
  }
200
 
201
  try:
 
 
 
 
202
  response = requests.post(
203
  f"{DEFAULT_API_URL}/submit",
204
  json=submission_data,
205
- timeout=60
206
  )
 
 
 
 
 
 
 
207
  response.raise_for_status()
208
  result_data = response.json()
209
 
@@ -216,8 +276,23 @@ def process_all_questions(username: str, space_code: str, use_agent: bool = True
216
  )
217
 
218
  return status, results
 
 
 
 
 
 
 
 
 
 
 
 
219
  except Exception as e:
220
- return f" Submission failed: {str(e)}", results
 
 
 
221
 
222
  # Gradio Interface
223
  with gr.Blocks(title="GAIA Agent") as app:
@@ -279,8 +354,8 @@ with gr.Blocks(title="GAIA Agent") as app:
279
 
280
  space_code_input = gr.Textbox(
281
  label="Space Code Link (optional)",
282
- placeholder="https://huggingface.co/spaces/your-username/your-space/tree/main",
283
- value="https://huggingface.co/spaces/ArdaKaratas/agent_hugging/tree/main"
284
  )
285
 
286
  use_agent_checkbox = gr.Checkbox(
 
32
 
33
  def get_space_url():
34
  """Get the Hugging Face Space URL."""
35
+ space_id = os.getenv("SPACE_ID", HF_USERNAME)
36
  return f"https://huggingface.co/spaces/{space_id}/tree/main"
37
 
38
  def fetch_questions():
 
55
  except Exception as e:
56
  return "", f"Error fetching random question: {str(e)}"
57
 
58
+ def clean_agent_answer(answer: str) -> str:
59
+ """
60
+ Clean agent answer to extract only the final answer.
61
+ Removes prefixes like "FINAL ANSWER:", explanations, etc.
62
+ """
63
+ if not answer:
64
+ return ""
65
+
66
+ answer = str(answer).strip()
67
+
68
+ # Remove "FINAL ANSWER:" prefix if present
69
+ prefixes = ["FINAL ANSWER:", "Final Answer:", "final answer:", "ANSWER:", "Answer:"]
70
+ for prefix in prefixes:
71
+ if answer.startswith(prefix):
72
+ answer = answer[len(prefix):].strip()
73
+
74
+ # Try to extract just the answer if there's a lot of explanation
75
+ # Look for common patterns
76
+ lines = answer.split('\n')
77
+
78
+ # If answer is very long, try to find the actual answer
79
+ if len(answer) > 500:
80
+ # Look for lines that might be the answer (short lines, numbers, etc.)
81
+ for line in reversed(lines):
82
+ line = line.strip()
83
+ if line and len(line) < 200 and not line.startswith(('The', 'This', 'I', 'We')):
84
+ # Might be the answer
85
+ if any(char.isdigit() for char in line) or len(line.split()) < 20:
86
+ answer = line
87
+ break
88
+
89
+ # Remove markdown formatting if present
90
+ answer = answer.replace('**', '').replace('*', '').replace('`', '')
91
+
92
+ # Take only first line if it seems like the answer
93
+ if '\n' in answer:
94
+ first_line = lines[0].strip()
95
+ # If first line is short and looks like an answer, use it
96
+ if len(first_line) < 200 and first_line:
97
+ answer = first_line
98
+
99
+ return answer.strip()
100
+
101
  def get_answer_from_metadata(question: str):
102
  """Get the correct answer from metadata.jsonl if available."""
103
  if not os.path.exists(METADATA_FILE):
 
190
  answer_source = "Error"
191
  else:
192
  try:
193
+ raw_answer = run_agent(question)
194
+ if not raw_answer or raw_answer.strip() == "":
195
  answer = "Agent returned empty answer"
196
+ else:
197
+ # Clean the answer to extract only the final answer
198
+ answer = clean_agent_answer(raw_answer)
199
+ if not answer or answer.strip() == "":
200
+ # If cleaning removed everything, use original
201
+ answer = raw_answer.strip()[:500] # Limit length
202
  answer_source = "Agent"
203
  except Exception as e:
204
  error_msg = str(e)
 
248
  }
249
 
250
  try:
251
+ # Log submission data for debugging
252
+ print(f"Submitting {len(answers_payload)} answers for user: {username}")
253
+ print(f"Space code: {space_code}")
254
+
255
  response = requests.post(
256
  f"{DEFAULT_API_URL}/submit",
257
  json=submission_data,
258
+ timeout=300 # Increased timeout for large submissions
259
  )
260
+
261
+ # Check response status
262
+ if response.status_code != 200:
263
+ error_text = response.text
264
+ print(f"Submission failed with status {response.status_code}: {error_text}")
265
+ return f"❌ Submission failed with status {response.status_code}: {error_text}", results
266
+
267
  response.raise_for_status()
268
  result_data = response.json()
269
 
 
276
  )
277
 
278
  return status, results
279
+ except requests.exceptions.Timeout:
280
+ return f"❌ Submission timed out. This may take a while. Please try again or check your agent's response time.", results
281
+ except requests.exceptions.RequestException as e:
282
+ error_msg = f"Request error: {str(e)}"
283
+ print(error_msg)
284
+ if hasattr(e, 'response') and e.response is not None:
285
+ try:
286
+ error_detail = e.response.json()
287
+ error_msg += f"\nDetails: {error_detail}"
288
+ except:
289
+ error_msg += f"\nResponse: {e.response.text[:500]}"
290
+ return f"❌ Submission failed: {error_msg}", results
291
  except Exception as e:
292
+ error_msg = f"Unexpected error: {str(e)}"
293
+ print(error_msg)
294
+ traceback.print_exc()
295
+ return f"❌ Submission failed: {error_msg}", results
296
 
297
  # Gradio Interface
298
  with gr.Blocks(title="GAIA Agent") as app:
 
354
 
355
  space_code_input = gr.Textbox(
356
  label="Space Code Link (optional)",
357
+ placeholder="https://huggingface.co/spaces/your-username/tree/main",
358
+ value="https://huggingface.co/spaces/ArdaKaratas/tree/main"
359
  )
360
 
361
  use_agent_checkbox = gr.Checkbox(