Update app.py
Browse files
app.py
CHANGED
@@ -1,253 +1,70 @@
|
|
1 |
import os
|
2 |
import gradio as gr
|
3 |
import requests
|
4 |
-
import inspect
|
5 |
import pandas as pd
|
6 |
import json
|
7 |
import re
|
8 |
from typing import List, Dict, Any, Optional
|
9 |
|
10 |
-
# (Keep Constants as is)
|
11 |
# --- Constants ---
|
12 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
13 |
|
14 |
-
# ---
|
15 |
-
|
16 |
-
class EnhancedGAIAAgent:
|
17 |
def __init__(self):
|
18 |
-
print("
|
19 |
-
self.tools = {
|
20 |
-
"web_search": self._web_search,
|
21 |
-
"calculator": self._calculator,
|
22 |
-
"image_analysis": self._image_analysis,
|
23 |
-
"text_analysis": self._text_analysis,
|
24 |
-
"code_execution": self._code_execution
|
25 |
-
}
|
26 |
|
27 |
-
# Tracking for reasoning steps
|
28 |
-
self.reasoning_steps = []
|
29 |
-
self.max_reasoning_steps = 5
|
30 |
-
|
31 |
-
def _web_search(self, query: str) -> str:
|
32 |
-
"""Simulates web search functionality"""
|
33 |
-
print(f"Performing web search for: {query}")
|
34 |
-
|
35 |
-
# Simulate search results based on query keywords
|
36 |
-
if "population" in query.lower():
|
37 |
-
return "The population of the queried location is approximately X million people as of 2023."
|
38 |
-
elif "capital" in query.lower():
|
39 |
-
return "The capital city of the queried location is X, with a population of Y million."
|
40 |
-
elif "president" in query.lower() or "prime minister" in query.lower() or "leader" in query.lower():
|
41 |
-
return "The current leader of the queried location is X, who has been in office since Y."
|
42 |
-
elif "tallest" in query.lower() or "highest" in query.lower():
|
43 |
-
return "The tallest structure in the queried location is X, with a height of Y meters."
|
44 |
-
elif "founded" in query.lower() or "established" in query.lower() or "history" in query.lower():
|
45 |
-
return "The queried entity was established/founded in X year. Its history includes Y and Z significant events."
|
46 |
-
elif "weather" in query.lower() or "temperature" in query.lower() or "climate" in query.lower():
|
47 |
-
return "The current weather/climate in the queried location is X with temperatures ranging from Y to Z degrees."
|
48 |
-
else:
|
49 |
-
return f"Search results for '{query}' include various websites and information sources that may contain relevant information."
|
50 |
-
|
51 |
-
def _calculator(self, expression: str) -> str:
|
52 |
-
"""Performs mathematical calculations"""
|
53 |
-
print(f"Calculating: {expression}")
|
54 |
-
|
55 |
-
# Clean the expression
|
56 |
-
cleaned_expr = expression.replace('×', '*').replace('÷', '/')
|
57 |
-
cleaned_expr = re.sub(r'[^0-9+\-*/().^ ]', '', cleaned_expr)
|
58 |
-
|
59 |
-
try:
|
60 |
-
# Handle exponentiation separately
|
61 |
-
if '^' in cleaned_expr:
|
62 |
-
cleaned_expr = cleaned_expr.replace('^', '**')
|
63 |
-
|
64 |
-
# Safely evaluate the expression
|
65 |
-
result = eval(cleaned_expr)
|
66 |
-
return f"The result of {expression} is {result}"
|
67 |
-
except Exception as e:
|
68 |
-
return f"Error calculating {expression}: {str(e)}"
|
69 |
-
|
70 |
-
def _image_analysis(self, image_description: str) -> str:
|
71 |
-
"""Simulates image analysis functionality"""
|
72 |
-
print(f"Analyzing image: {image_description}")
|
73 |
-
|
74 |
-
# Simulate image analysis based on description keywords
|
75 |
-
if "person" in image_description.lower() or "people" in image_description.lower() or "human" in image_description.lower():
|
76 |
-
return "The image contains one or more people. They appear to be [activity/pose/expression]."
|
77 |
-
elif "animal" in image_description.lower() or "dog" in image_description.lower() or "cat" in image_description.lower():
|
78 |
-
return "The image shows an animal, likely a [specific animal]. It appears to be [activity/state]."
|
79 |
-
elif "building" in image_description.lower() or "architecture" in image_description.lower():
|
80 |
-
return "The image depicts a building or architectural structure. It appears to be [style/type] architecture."
|
81 |
-
elif "landscape" in image_description.lower() or "nature" in image_description.lower():
|
82 |
-
return "The image shows a natural landscape featuring [elements like mountains, rivers, forests, etc.]."
|
83 |
-
elif "chart" in image_description.lower() or "graph" in image_description.lower() or "diagram" in image_description.lower():
|
84 |
-
return "The image contains a chart/graph showing data about [topic]. The trend appears to be [increasing/decreasing/stable]."
|
85 |
-
else:
|
86 |
-
return f"The image appears to show {image_description}. Key elements include [objects/subjects] and [notable features]."
|
87 |
-
|
88 |
-
def _text_analysis(self, text: str) -> str:
|
89 |
-
"""Analyzes text for sentiment, entities, and key information"""
|
90 |
-
print(f"Analyzing text (first 50 chars): {text[:50]}...")
|
91 |
-
|
92 |
-
# Count words and sentences
|
93 |
-
word_count = len(text.split())
|
94 |
-
sentence_count = len(re.split(r'[.!?]+', text))
|
95 |
-
|
96 |
-
# Simple sentiment analysis
|
97 |
-
positive_words = ['good', 'great', 'excellent', 'positive', 'happy', 'best', 'love', 'wonderful', 'fantastic']
|
98 |
-
negative_words = ['bad', 'poor', 'negative', 'terrible', 'worst', 'hate', 'awful', 'horrible', 'disappointing']
|
99 |
-
|
100 |
-
positive_count = sum(1 for word in text.lower().split() if word in positive_words)
|
101 |
-
negative_count = sum(1 for word in text.lower().split() if word in negative_words)
|
102 |
-
|
103 |
-
if positive_count > negative_count:
|
104 |
-
sentiment = "positive"
|
105 |
-
elif negative_count > positive_count:
|
106 |
-
sentiment = "negative"
|
107 |
-
else:
|
108 |
-
sentiment = "neutral"
|
109 |
-
|
110 |
-
return f"Text analysis: {word_count} words, {sentence_count} sentences. The sentiment appears to be {sentiment}."
|
111 |
-
|
112 |
-
def _code_execution(self, code: str) -> str:
|
113 |
-
"""Simulates code execution and analysis"""
|
114 |
-
print(f"Analyzing code (first 50 chars): {code[:50]}...")
|
115 |
-
|
116 |
-
# Identify language
|
117 |
-
language = "unknown"
|
118 |
-
if "def " in code or "import " in code or "print(" in code:
|
119 |
-
language = "Python"
|
120 |
-
elif "function " in code or "var " in code or "const " in code or "let " in code:
|
121 |
-
language = "JavaScript"
|
122 |
-
elif "public class " in code or "System.out.println" in code:
|
123 |
-
language = "Java"
|
124 |
-
elif "#include" in code or "int main" in code:
|
125 |
-
language = "C/C++"
|
126 |
-
|
127 |
-
# Simple code analysis
|
128 |
-
lines = code.count('\n') + 1
|
129 |
-
|
130 |
-
return f"Code analysis: {lines} lines of {language} code. The code appears to [purpose/functionality]."
|
131 |
-
|
132 |
-
def _reason(self, question: str) -> List[str]:
|
133 |
-
"""Performs step-by-step reasoning about the question"""
|
134 |
-
reasoning = []
|
135 |
-
|
136 |
-
# Initial analysis
|
137 |
-
reasoning.append(f"Question: '{question}'")
|
138 |
-
reasoning.append("Let me analyze what this question is asking for.")
|
139 |
-
|
140 |
-
# Identify question type
|
141 |
-
if any(keyword in question.lower() for keyword in ["calculate", "compute", "sum", "difference", "product", "divide"]):
|
142 |
-
reasoning.append("This appears to be a calculation question.")
|
143 |
-
|
144 |
-
# Extract mathematical expression
|
145 |
-
expression = re.search(r'calculate\s+(.+?)(?:\?|$)', question.lower())
|
146 |
-
if expression:
|
147 |
-
reasoning.append(f"I need to calculate: {expression.group(1)}")
|
148 |
-
reasoning.append(f"Using the calculator tool to compute this.")
|
149 |
-
else:
|
150 |
-
reasoning.append("I need to identify the mathematical operation required.")
|
151 |
-
|
152 |
-
elif any(keyword in question.lower() for keyword in ["image", "picture", "photo", "graph", "chart"]):
|
153 |
-
reasoning.append("This question involves analyzing an image or visual content.")
|
154 |
-
reasoning.append("I should use image analysis to identify key elements in the image.")
|
155 |
-
|
156 |
-
elif any(keyword in question.lower() for keyword in ["population", "capital", "country", "city", "president", "leader"]):
|
157 |
-
reasoning.append("This is a factual question about geography, demographics, or leadership.")
|
158 |
-
reasoning.append("I should search for the most up-to-date information.")
|
159 |
-
|
160 |
-
elif any(keyword in question.lower() for keyword in ["code", "function", "program", "algorithm"]):
|
161 |
-
reasoning.append("This question involves code analysis or programming.")
|
162 |
-
reasoning.append("I should examine the code structure and functionality.")
|
163 |
-
|
164 |
-
else:
|
165 |
-
reasoning.append("This appears to be a general knowledge question.")
|
166 |
-
reasoning.append("I'll need to search for relevant information and synthesize an answer.")
|
167 |
-
|
168 |
-
return reasoning
|
169 |
-
|
170 |
def __call__(self, question: str) -> str:
|
171 |
"""Main method to process questions and generate answers"""
|
172 |
print(f"Agent received question: {question}")
|
173 |
|
174 |
-
#
|
175 |
-
|
176 |
-
|
177 |
-
# Step 2: Determine approach and tools to use
|
178 |
-
answer = ""
|
179 |
|
180 |
# Handle calculation questions
|
181 |
-
if any(keyword in
|
182 |
-
# Extract
|
183 |
-
|
184 |
-
if
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
if int(numbers[1]) != 0:
|
202 |
-
result = int(numbers[0]) / int(numbers[1])
|
203 |
-
answer = f"The result of dividing {numbers[0]} by {numbers[1]} is {result}"
|
204 |
-
else:
|
205 |
-
answer = "Cannot divide by zero"
|
206 |
-
else:
|
207 |
-
answer = "I couldn't identify a clear calculation to perform."
|
208 |
|
209 |
# Handle image analysis questions
|
210 |
-
elif any(keyword in
|
211 |
-
|
212 |
-
image_desc = question
|
213 |
-
answer = self._image_analysis(image_desc)
|
214 |
|
215 |
# Handle factual questions
|
216 |
-
elif any(keyword in
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
answer += " The location is notable for its geographical and cultural significance."
|
230 |
-
|
231 |
-
# Handle code questions
|
232 |
-
elif any(keyword in question.lower() for keyword in ["code", "function", "program", "algorithm"]):
|
233 |
-
# Extract code if present or use the question itself
|
234 |
-
code_sample = question
|
235 |
-
answer = self._code_execution(code_sample)
|
236 |
|
237 |
# General knowledge questions
|
238 |
else:
|
239 |
-
|
240 |
-
search_results = self._web_search(question)
|
241 |
-
text_analysis = self._text_analysis(question)
|
242 |
-
|
243 |
-
answer = f"To answer your question: {search_results}"
|
244 |
-
|
245 |
-
# Add reasoning steps if available
|
246 |
-
if self.reasoning_steps:
|
247 |
-
reasoning_summary = " ".join(self.reasoning_steps[-2:]) # Use last two reasoning steps
|
248 |
-
answer = f"{answer}\n\nReasoning: {reasoning_summary}"
|
249 |
-
|
250 |
-
return answer
|
251 |
|
252 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
253 |
"""
|
@@ -268,7 +85,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
268 |
|
269 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
270 |
try:
|
271 |
-
agent =
|
272 |
except Exception as e:
|
273 |
print(f"Error instantiating agent: {e}")
|
274 |
return f"Error initializing agent: {e}", None
|
|
|
1 |
import os
|
2 |
import gradio as gr
|
3 |
import requests
|
|
|
4 |
import pandas as pd
|
5 |
import json
|
6 |
import re
|
7 |
from typing import List, Dict, Any, Optional
|
8 |
|
|
|
9 |
# --- Constants ---
|
10 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
11 |
|
12 |
+
# --- Simple GAIA Agent Definition ---
|
13 |
+
class SimpleGAIAAgent:
|
|
|
14 |
def __init__(self):
|
15 |
+
print("SimpleGAIAAgent initialized.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
def __call__(self, question: str) -> str:
|
18 |
"""Main method to process questions and generate answers"""
|
19 |
print(f"Agent received question: {question}")
|
20 |
|
21 |
+
# Basic question analysis
|
22 |
+
question_lower = question.lower()
|
|
|
|
|
|
|
23 |
|
24 |
# Handle calculation questions
|
25 |
+
if any(keyword in question_lower for keyword in ["calculate", "compute", "sum", "difference", "product", "divide"]):
|
26 |
+
# Extract numbers
|
27 |
+
numbers = re.findall(r'\d+', question)
|
28 |
+
if len(numbers) >= 2:
|
29 |
+
if "sum" in question_lower or "add" in question_lower or "plus" in question_lower:
|
30 |
+
result = sum(int(num) for num in numbers)
|
31 |
+
return f"The sum of the numbers is {result}"
|
32 |
+
elif "difference" in question_lower or "subtract" in question_lower or "minus" in question_lower:
|
33 |
+
result = int(numbers[0]) - int(numbers[1])
|
34 |
+
return f"The difference between {numbers[0]} and {numbers[1]} is {result}"
|
35 |
+
elif "product" in question_lower or "multiply" in question_lower:
|
36 |
+
result = int(numbers[0]) * int(numbers[1])
|
37 |
+
return f"The product of {numbers[0]} and {numbers[1]} is {result}"
|
38 |
+
elif "divide" in question_lower:
|
39 |
+
if int(numbers[1]) != 0:
|
40 |
+
result = int(numbers[0]) / int(numbers[1])
|
41 |
+
return f"The result of dividing {numbers[0]} by {numbers[1]} is {result}"
|
42 |
+
else:
|
43 |
+
return "Cannot divide by zero"
|
44 |
+
return "I'll calculate this for you: " + question
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
|
46 |
# Handle image analysis questions
|
47 |
+
elif any(keyword in question_lower for keyword in ["image", "picture", "photo", "graph", "chart"]):
|
48 |
+
return "Based on the image, I can see several key elements that help answer your question. The main subject appears to be [description] which indicates [answer]."
|
|
|
|
|
49 |
|
50 |
# Handle factual questions
|
51 |
+
elif any(keyword in question_lower for keyword in ["who", "what", "where", "when", "why", "how"]):
|
52 |
+
if "who" in question_lower:
|
53 |
+
return "The person involved is a notable figure in this field with significant contributions and achievements."
|
54 |
+
elif "when" in question_lower:
|
55 |
+
return "This occurred during a significant historical period, specifically in the early part of the relevant era."
|
56 |
+
elif "where" in question_lower:
|
57 |
+
return "The location is in a region known for its historical and cultural significance."
|
58 |
+
elif "what" in question_lower:
|
59 |
+
return "This refers to an important concept or entity that has several key characteristics and functions."
|
60 |
+
elif "why" in question_lower:
|
61 |
+
return "This happened due to a combination of factors including historical context, individual decisions, and broader societal trends."
|
62 |
+
elif "how" in question_lower:
|
63 |
+
return "The process involves several key steps that must be followed in sequence to achieve the desired outcome."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
|
65 |
# General knowledge questions
|
66 |
else:
|
67 |
+
return "Based on my analysis, the answer to your question involves several important factors. First, we need to consider the context and specific details mentioned. Taking all available information into account, the most accurate response would be a comprehensive explanation that addresses all aspects of your query."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
|
69 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
70 |
"""
|
|
|
85 |
|
86 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
87 |
try:
|
88 |
+
agent = SimpleGAIAAgent()
|
89 |
except Exception as e:
|
90 |
print(f"Error instantiating agent: {e}")
|
91 |
return f"Error initializing agent: {e}", None
|