Aref Hebri commited on
Commit
d48436a
·
1 Parent(s): b1e7f85
Files changed (1) hide show
  1. app.py +79 -7
app.py CHANGED
@@ -3,6 +3,8 @@ import gradio as gr
3
  import requests
4
  import inspect
5
  import pandas as pd
 
 
6
 
7
  from agent import agent
8
 
@@ -13,16 +15,43 @@ print("Gemini_Key in env:", "Gemini_Key" in os.environ)
13
  # --- Constants ---
14
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
15
 
 
 
 
 
 
 
 
 
 
 
 
16
  # --- Basic Agent Definition ---
17
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
18
  class BasicAgent:
19
  def __init__(self):
20
  print("BasicAgent initialized.")
21
  self.agent = agent
22
- def __call__(self, question: str) -> str:
23
- print(f"Agent received question (first 50 chars): {question[:50]}...")
24
- answer = self.agent.run(question)
25
- print(f"Agent returning answer: {answer}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  return answer
27
 
28
  def run_and_submit_all( profile: gr.OAuthProfile | None):
@@ -54,6 +83,11 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
54
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
55
  print(agent_code)
56
 
 
 
 
 
 
57
  # 2. Fetch Questions
58
  print(f"Fetching questions from: {questions_url}")
59
  try:
@@ -82,16 +116,54 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
82
  for item in questions_data:
83
  task_id = item.get("task_id")
84
  question_text = item.get("question")
 
 
 
85
  if not task_id or question_text is None:
86
  print(f"Skipping item with missing task_id or question: {item}")
87
  continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  try:
89
- submitted_answer = agent(question_text)
 
90
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
91
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
 
 
92
  except Exception as e:
93
  print(f"Error running agent on task {task_id}: {e}")
94
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
 
95
 
96
  if not answers_payload:
97
  print("Agent did not produce any answers to submit.")
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ from pathlib import Path
7
+ from PIL import Image as PILImage
8
 
9
  from agent import agent
10
 
 
15
  # --- Constants ---
16
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
17
 
18
+ # Helper function to check for images
19
+ def is_image_file(filepath: Path) -> bool:
20
+ if not filepath or not filepath.is_file():
21
+ return False
22
+ try:
23
+ with PILImage.open(filepath) as img:
24
+ img.verify() # Verify it's an image without loading all pixel data
25
+ return True
26
+ except Exception: # Catches PIL.UnidentifiedImageError, IOError, SyntaxError, etc.
27
+ return False
28
+
29
  # --- Basic Agent Definition ---
30
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
31
  class BasicAgent:
32
  def __init__(self):
33
  print("BasicAgent initialized.")
34
  self.agent = agent
35
+ def __call__(self, task_id: str, question: str, filename: Path | None = None) -> str:
36
+ print(f"Agent received task_id: {task_id}, question (first 50 chars): {question[:50]}...")
37
+ if filename:
38
+ print(f"Associated file: {filename.name}")
39
+
40
+ # Augment the question for the LLM
41
+ prompt = f"Task ID: {task_id}\\nQuestion: {question}"
42
+ if filename:
43
+ # Still inform about the file in the text prompt, as a fallback or for context
44
+ prompt += f"\\n\\nThis question may relate to an attached file named: '{filename.name}'. The file has been downloaded if it was provided with the question."
45
+
46
+ run_kwargs = {}
47
+ if filename and is_image_file(filename):
48
+ print(f"File {filename.name} is an image. Adding to agent.run arguments.")
49
+ # Assuming agent.run can take an 'images' kwarg with a list of Path objects or PIL.Image objects
50
+ # Passing Path object directly for simplicity, smolagents might handle it.
51
+ run_kwargs["images"] = [filename]
52
+
53
+ answer = self.agent.run(prompt, **run_kwargs)
54
+ print(f"Agent returning answer: {answer}")
55
  return answer
56
 
57
  def run_and_submit_all( profile: gr.OAuthProfile | None):
 
83
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
84
  print(agent_code)
85
 
86
+ # Create a directory for downloaded files
87
+ files_dir = Path("downloaded_files")
88
+ files_dir.mkdir(exist_ok=True)
89
+ print(f"Files will be downloaded to: {files_dir.resolve()}")
90
+
91
  # 2. Fetch Questions
92
  print(f"Fetching questions from: {questions_url}")
93
  try:
 
116
  for item in questions_data:
117
  task_id = item.get("task_id")
118
  question_text = item.get("question")
119
+ file_name_str = item.get("file_name") # Check for a filename
120
+ file_path: Path | None = None # Initialize file_path
121
+
122
  if not task_id or question_text is None:
123
  print(f"Skipping item with missing task_id or question: {item}")
124
  continue
125
+
126
+ if file_name_str:
127
+ print(f"Task {task_id} has an associated file: {file_name_str}")
128
+ # Construct download URL - using the structure suggested by GaiaClient in the prompt
129
+ # The API seems to be GET /files/{task_id} and filename is for local saving
130
+ file_url = f"{api_url}/files/{task_id}"
131
+ local_file_path = files_dir / file_name_str
132
+
133
+ try:
134
+ print(f"Attempting to download file from: {file_url} to {local_file_path}")
135
+ response = requests.get(file_url, timeout=30) # Increased timeout for file download
136
+ response.raise_for_status() # Will raise an HTTPError for bad responses (4XX or 5XX)
137
+ with open(local_file_path, "wb") as f:
138
+ f.write(response.content)
139
+ file_path = local_file_path
140
+ print(f"Successfully downloaded {file_name_str} for task {task_id}.")
141
+ except requests.exceptions.HTTPError as e_http:
142
+ print(f"HTTP error downloading file for task {task_id} ({file_name_str}): {e_http}")
143
+ print(f"Response status: {e_http.response.status_code}, Response text: {e_http.response.text[:200]}")
144
+ except requests.exceptions.RequestException as e_req:
145
+ print(f"Error downloading file for task {task_id} ({file_name_str}): {e_req}")
146
+ except Exception as e_file:
147
+ print(f"An unexpected error occurred downloading file for task {task_id} ({file_name_str}): {e_file}")
148
+
149
  try:
150
+ # Pass task_id, original question_text, and file_path to the agent
151
+ submitted_answer = agent(task_id, question_text, file_path)
152
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
153
+ results_log.append({
154
+ "Task ID": task_id,
155
+ "Question": question_text,
156
+ "File": file_name_str if file_name_str else "N/A", # Log file name
157
+ "Submitted Answer": submitted_answer
158
+ })
159
  except Exception as e:
160
  print(f"Error running agent on task {task_id}: {e}")
161
+ results_log.append({
162
+ "Task ID": task_id,
163
+ "Question": question_text,
164
+ "File": file_name_str if file_name_str else "N/A",
165
+ "Submitted Answer": f"AGENT ERROR: {e}"
166
+ })
167
 
168
  if not answers_payload:
169
  print("Agent did not produce any answers to submit.")