Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -3,41 +3,92 @@ import gradio as gr
|
|
3 |
import requests
|
4 |
import inspect
|
5 |
import pandas as pd
|
6 |
-
|
7 |
-
from smolagents import CodeAgent,
|
8 |
-
|
|
|
9 |
# (Keep Constants as is)
|
10 |
# --- Constants ---
|
11 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
12 |
-
|
13 |
# --- Basic Agent Definition ---
|
14 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
15 |
-
class BasicAgent:
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
|
25 |
class myAgent:
|
26 |
def __init__(self):
|
27 |
print("myAgent initialized.")
|
28 |
|
29 |
self.agent = CodeAgent(
|
30 |
-
model=
|
31 |
-
|
|
|
|
|
|
|
|
|
32 |
add_base_tools=True,
|
33 |
-
additional_authorized_imports=['pandas','numpy','csv']
|
34 |
)
|
35 |
|
36 |
-
def __call__(self, question: str) -> str:
|
37 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
38 |
-
|
39 |
-
|
40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
|
42 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
43 |
"""
|
@@ -56,6 +107,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
56 |
|
57 |
api_url = DEFAULT_API_URL
|
58 |
questions_url = f"{api_url}/questions"
|
|
|
59 |
submit_url = f"{api_url}/submit"
|
60 |
|
61 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
@@ -96,20 +148,51 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
96 |
for item in questions_data:
|
97 |
task_id = item.get("task_id")
|
98 |
question_text = item.get("question")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
99 |
if not task_id or question_text is None:
|
100 |
print(f"Skipping item with missing task_id or question: {item}")
|
101 |
continue
|
102 |
try:
|
103 |
-
|
|
|
|
|
|
|
|
|
104 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
105 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
106 |
except Exception as e:
|
107 |
print(f"Error running agent on task {task_id}: {e}")
|
108 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
109 |
-
|
110 |
-
if not answers_payload:
|
111 |
-
print("Agent did not produce any answers to submit.")
|
112 |
-
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
113 |
|
114 |
# 4. Prepare Submission
|
115 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
|
|
3 |
import requests
|
4 |
import inspect
|
5 |
import pandas as pd
|
6 |
+
import time
|
7 |
+
from smolagents import CodeAgent, WikipediaSearchTool, DuckDuckGoSearchTool, OpenAIServerModel
|
8 |
+
from PIL import Image
|
9 |
+
from io import BytesIO
|
10 |
# (Keep Constants as is)
|
11 |
# --- Constants ---
|
12 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
13 |
+
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
|
14 |
# --- Basic Agent Definition ---
|
15 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
16 |
+
# class BasicAgent:
|
17 |
+
# def __init__(self):
|
18 |
+
# print("BasicAgent initialized.")
|
19 |
+
# def __call__(self, question: str) -> str:
|
20 |
+
# print(f"Agent received question (first 50 chars): {question[:50]}...")
|
21 |
+
# fixed_answer = "This is a default answer."
|
22 |
+
# print(f"Agent returning fixed answer: {fixed_answer}")
|
23 |
+
# return fixed_answer
|
24 |
|
25 |
+
def is_valid_image_pillow(file_name):
|
26 |
+
try:
|
27 |
+
with Image.open(file_name) as img:
|
28 |
+
img.verify() # Verify the image file
|
29 |
+
return True
|
30 |
+
except (IOError, SyntaxError):
|
31 |
+
return False
|
32 |
|
33 |
class myAgent:
|
34 |
def __init__(self):
|
35 |
print("myAgent initialized.")
|
36 |
|
37 |
self.agent = CodeAgent(
|
38 |
+
model = OpenAIServerModel(
|
39 |
+
model_id="gemini-2.0-flash-lite",
|
40 |
+
api_base="https://generativelanguage.googleapis.com/v1beta/openai/",
|
41 |
+
api_key=GEMINI_API_KEY,
|
42 |
+
),
|
43 |
+
tools=[DuckDuckGoSearchTool(), WikipediaSearchTool()],
|
44 |
add_base_tools=True,
|
45 |
+
# additional_authorized_imports=['pandas','numpy','csv']
|
46 |
)
|
47 |
|
48 |
+
def __call__(self, question: str, file_data=None) -> str: # Renamed img to file_data
|
49 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
50 |
+
|
51 |
+
images_for_agent = [] # List to hold image objects
|
52 |
+
text_from_file = "" # String to hold text content from files
|
53 |
+
|
54 |
+
if file_data:
|
55 |
+
print(f"Agent received file data of size: {len(file_data)} bytes")
|
56 |
+
# Attempt to open as an image
|
57 |
+
try:
|
58 |
+
img_obj = Image.open(BytesIO(file_data))
|
59 |
+
img_obj.verify() # Verify if it's a valid image
|
60 |
+
images_for_agent.append(img_obj)
|
61 |
+
print("File identified as an image.")
|
62 |
+
except (IOError, SyntaxError):
|
63 |
+
print("File is not an image, attempting to decode as text.")
|
64 |
+
# If not an image, try to decode as text
|
65 |
+
try:
|
66 |
+
text_from_file = file_data.decode('utf-8')
|
67 |
+
# You might want to add more sophisticated parsing here for CSV/JSON/etc.
|
68 |
+
# For example, if it's a CSV:
|
69 |
+
# df = pd.read_csv(StringIO(text_from_file))
|
70 |
+
# text_from_file = df.to_string() # Convert DataFrame to string for agent
|
71 |
+
print(f"File decoded as text (first 200 chars): {text_from_file[:200]}...")
|
72 |
+
except UnicodeDecodeError:
|
73 |
+
text_from_file = f"Could not decode file as UTF-8 text. Raw bytes size: {len(file_data)}"
|
74 |
+
print("File could not be decoded as UTF-8 text.")
|
75 |
+
except Exception as e:
|
76 |
+
print(f"Unexpected error processing file data: {e}")
|
77 |
+
text_from_file = f"Error processing file: {e}"
|
78 |
+
|
79 |
+
# Combine question with file content if available
|
80 |
+
if text_from_file:
|
81 |
+
# You might want to prepend or append, or format this more intelligently
|
82 |
+
question_with_file_context = f"{question}\n\n[FILE CONTENT START]\n{text_from_file}\n[FILE CONTENT END]"
|
83 |
+
else:
|
84 |
+
question_with_file_context = question
|
85 |
+
|
86 |
+
# Pass images and the possibly augmented question to the CodeAgent
|
87 |
+
answer = self.agent.run(question_with_file_context, images=images_for_agent if images_for_agent else None)
|
88 |
+
|
89 |
+
time.sleep(5)
|
90 |
+
print(f"Agent returning answer: {answer}")
|
91 |
+
return answer
|
92 |
|
93 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
94 |
"""
|
|
|
107 |
|
108 |
api_url = DEFAULT_API_URL
|
109 |
questions_url = f"{api_url}/questions"
|
110 |
+
files_url = f"{api_url}/files"
|
111 |
submit_url = f"{api_url}/submit"
|
112 |
|
113 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
|
|
148 |
for item in questions_data:
|
149 |
task_id = item.get("task_id")
|
150 |
question_text = item.get("question")
|
151 |
+
file_name = item.get("file_name")
|
152 |
+
|
153 |
+
file_content_to_pass = None # Initialize to None
|
154 |
+
|
155 |
+
if file_name:
|
156 |
+
# Fetch files
|
157 |
+
print(f"Fetching file '{file_name}' for task_id: {task_id}")
|
158 |
+
try:
|
159 |
+
response = requests.get(f'{files_url}/{task_id}', timeout=15, allow_redirects=True)
|
160 |
+
print("Response status code:", response.status_code)
|
161 |
+
if response.status_code == 404:
|
162 |
+
print(f"File not found for task_id {task_id}. Skipping file processing for this task.")
|
163 |
+
# Continue without a file, agent will still receive the question
|
164 |
+
else:
|
165 |
+
response.raise_for_status()
|
166 |
+
file_content_to_pass = response.content # Store the raw content
|
167 |
+
print(f"Fetched file for task_id {task_id}: {file_name} (size: {len(file_content_to_pass)} bytes)")
|
168 |
+
|
169 |
+
# Optional: Add specific handling for image files if your agent needs them
|
170 |
+
# The `img` parameter in `myAgent.__call__` suggests it's designed for images.
|
171 |
+
# If you want to pass image objects for image files, and raw content for others,
|
172 |
+
# you'll need to adapt how `myAgent` uses the `img` parameter.
|
173 |
+
# For now, we'll just pass the raw content.
|
174 |
+
|
175 |
+
except requests.exceptions.RequestException as e:
|
176 |
+
print(f"Error fetching file for task {task_id}: {e}. Agent will run without file.")
|
177 |
+
# Do not return here, allow agent to run with just the question if file fetch fails
|
178 |
+
except Exception as e:
|
179 |
+
print(f"An unexpected error occurred fetching file for task {task_id}: {e}. Agent will run without file.")
|
180 |
+
# Do not return here, allow agent to run with just the question if file fetch fails
|
181 |
+
|
182 |
if not task_id or question_text is None:
|
183 |
print(f"Skipping item with missing task_id or question: {item}")
|
184 |
continue
|
185 |
try:
|
186 |
+
# Pass file_content_to_pass to the agent.
|
187 |
+
# Your agent's __call__ method needs to be ready to handle
|
188 |
+
# raw byte content for the 'img' parameter, or you might
|
189 |
+
# rename it to something more generic like 'file_data'.
|
190 |
+
submitted_answer = agent(question_text, file_content_to_pass)
|
191 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
192 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer, "File Name": file_name if file_name else "N/A"})
|
193 |
except Exception as e:
|
194 |
print(f"Error running agent on task {task_id}: {e}")
|
195 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}", "File Name": file_name if file_name else "N/A"})
|
|
|
|
|
|
|
|
|
196 |
|
197 |
# 4. Prepare Submission
|
198 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|