jcollado commited on
Commit
65283ec
·
verified ·
1 Parent(s): 81917a3

Update app.py

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