Update app.py
Browse files
app.py
CHANGED
|
@@ -4,7 +4,7 @@ import requests
|
|
| 4 |
import pandas as pd
|
| 5 |
import re
|
| 6 |
import sympy as sp
|
| 7 |
-
import
|
| 8 |
from bs4 import BeautifulSoup
|
| 9 |
|
| 10 |
# --- Constants ---
|
|
@@ -20,13 +20,15 @@ class BasicAgent:
|
|
| 20 |
if not self.api_token:
|
| 21 |
raise ValueError("HF_TOKEN environment variable not set.")
|
| 22 |
self.headers = {"Authorization": f"Bearer {self.api_token}"}
|
| 23 |
-
|
|
|
|
|
|
|
| 24 |
|
| 25 |
def __call__(self, question: str) -> tuple[str, str]:
|
| 26 |
-
print(f"
|
| 27 |
reasoning = []
|
| 28 |
-
|
| 29 |
-
# Step 1:
|
| 30 |
is_math = any(keyword in question.lower() for keyword in ["calculate", "solve", "what is", "+", "-", "*", "/", "=", "equation", "how many"])
|
| 31 |
if is_math:
|
| 32 |
try:
|
|
@@ -42,36 +44,37 @@ class BasicAgent:
|
|
| 42 |
concise_answer = str(result)
|
| 43 |
reasoning.append(f"Math Solver (SymPy): Evaluated expression '{expr}'. Result: {concise_answer}")
|
| 44 |
if concise_answer != "No solution":
|
| 45 |
-
print(f"
|
| 46 |
return concise_answer, "\n".join(reasoning)
|
| 47 |
except Exception as e:
|
| 48 |
reasoning.append(f"Math Solver (SymPy) failed: {e}")
|
| 49 |
|
| 50 |
# Step 2: Try Wikipedia for factual questions
|
| 51 |
try:
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
else:
|
| 66 |
-
|
| 67 |
-
wiki_reasoning = wiki_answer
|
| 68 |
-
reasoning.append(f"Wikipedia: Searched '{key_terms}'. Summary: {wiki_summary[:100]}... Answer: {concise_answer}")
|
| 69 |
-
print(f"Agent returning concise answer (Wikipedia): {concise_answer}")
|
| 70 |
-
return concise_answer, "\n".join(reasoning)
|
| 71 |
-
except wikipedia.exceptions.DisambiguationError:
|
| 72 |
-
reasoning.append("Wikipedia: Disambiguation error, multiple results found.")
|
| 73 |
except Exception as e:
|
| 74 |
-
reasoning.append(f"Wikipedia failed: {e}")
|
| 75 |
|
| 76 |
# Step 3: Try web search with DuckDuckGo
|
| 77 |
try:
|
|
@@ -95,7 +98,7 @@ class BasicAgent:
|
|
| 95 |
concise_answer = self._extract_concise_answer(search_answer)
|
| 96 |
search_reasoning = search_answer
|
| 97 |
reasoning.append(f"Web Search (DuckDuckGo): Searched '{question}'. Answer: {concise_answer}")
|
| 98 |
-
print(f"
|
| 99 |
return concise_answer, "\n".join(reasoning)
|
| 100 |
else:
|
| 101 |
reasoning.append("Web Search (DuckDuckGo): No relevant results found.")
|
|
@@ -119,7 +122,7 @@ class BasicAgent:
|
|
| 119 |
concise_answer = self._extract_concise_answer(full_response)
|
| 120 |
llm_reasoning = full_response
|
| 121 |
reasoning.append(f"LLM (Flan-T5-Base): {llm_reasoning}")
|
| 122 |
-
print(f"
|
| 123 |
return concise_answer, "\n".join(reasoning)
|
| 124 |
except Exception as e:
|
| 125 |
print(f"Error querying Inference API: {e}")
|
|
@@ -155,10 +158,10 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 155 |
and displays the results.
|
| 156 |
"""
|
| 157 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 158 |
-
space_id = os.getenv("SPACE_ID")
|
| 159 |
|
| 160 |
if profile:
|
| 161 |
-
username= f"{profile.username}"
|
| 162 |
print(f"User logged in: {username}")
|
| 163 |
else:
|
| 164 |
print("User not logged in.")
|
|
@@ -184,16 +187,16 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 184 |
response.raise_for_status()
|
| 185 |
questions_data = response.json()
|
| 186 |
if not questions_data:
|
| 187 |
-
|
| 188 |
-
|
| 189 |
print(f"Fetched {len(questions_data)} questions.")
|
| 190 |
except requests.exceptions.RequestException as e:
|
| 191 |
print(f"Error fetching questions: {e}")
|
| 192 |
return f"Error fetching questions: {e}", None
|
| 193 |
except requests.exceptions.JSONDecodeError as e:
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
except Exception as e:
|
| 198 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 199 |
return f"An unexpected error occurred fetching questions: {e}", None
|
|
@@ -218,19 +221,19 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 218 |
"Reasoning": reasoning
|
| 219 |
})
|
| 220 |
except Exception as e:
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
|
| 229 |
if not answers_payload:
|
| 230 |
print("Agent did not produce any answers to submit.")
|
| 231 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 232 |
|
| 233 |
-
# 4. Prepare Submission
|
| 234 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 235 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 236 |
print(status_update)
|
|
@@ -310,7 +313,7 @@ if __name__ == "__main__":
|
|
| 310 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 311 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 312 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 313 |
-
space_id_startup = os.getenv("SPACE_ID")
|
| 314 |
|
| 315 |
if space_host_startup:
|
| 316 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
@@ -318,7 +321,7 @@ if __name__ == "__main__":
|
|
| 318 |
else:
|
| 319 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 320 |
|
| 321 |
-
if space_id_startup:
|
| 322 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 323 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 324 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
import re
|
| 6 |
import sympy as sp
|
| 7 |
+
from wikipedia_api import Wikipedia
|
| 8 |
from bs4 import BeautifulSoup
|
| 9 |
|
| 10 |
# --- Constants ---
|
|
|
|
| 20 |
if not self.api_token:
|
| 21 |
raise ValueError("HF_TOKEN environment variable not set.")
|
| 22 |
self.headers = {"Authorization": f"Bearer {self.api_token}"}
|
| 23 |
+
# Initialize Wikipedia API
|
| 24 |
+
self.wiki = Wikipedia(language='en', user_agent='Mozilla/5.0')
|
| 25 |
+
print("BasicAgent initialized with Flan-T5-Base, SymPy, Wikipedia API, and DuckDuckGo search.")
|
| 26 |
|
| 27 |
def __call__(self, question: str) -> tuple[str, str]:
|
| 28 |
+
print(f"Question: {question[:50]}...")
|
| 29 |
reasoning = []
|
| 30 |
+
|
| 31 |
+
# Step 1: Check for mathematical questions
|
| 32 |
is_math = any(keyword in question.lower() for keyword in ["calculate", "solve", "what is", "+", "-", "*", "/", "=", "equation", "how many"])
|
| 33 |
if is_math:
|
| 34 |
try:
|
|
|
|
| 44 |
concise_answer = str(result)
|
| 45 |
reasoning.append(f"Math Solver (SymPy): Evaluated expression '{expr}'. Result: {concise_answer}")
|
| 46 |
if concise_answer != "No solution":
|
| 47 |
+
print(f"Returning concise answer (math): {concise_answer}")
|
| 48 |
return concise_answer, "\n".join(reasoning)
|
| 49 |
except Exception as e:
|
| 50 |
reasoning.append(f"Math Solver (SymPy) failed: {e}")
|
| 51 |
|
| 52 |
# Step 2: Try Wikipedia for factual questions
|
| 53 |
try:
|
| 54 |
+
key_terms = " ".join(question.split()[:5]).strip("?")
|
| 55 |
+
wiki_page = self.wiki.page(key_terms)
|
| 56 |
+
if wiki_page.exists():
|
| 57 |
+
wiki_summary = wiki_page.summary[:500] # Limit to 500 chars
|
| 58 |
+
prompt = (
|
| 59 |
+
f"Question: {question}\n"
|
| 60 |
+
f"Context: {wiki_summary}\n"
|
| 61 |
+
"Provide a concise answer (e.g., a number or short phrase) based on the context."
|
| 62 |
+
)
|
| 63 |
+
wiki_answer = self._query_llm(prompt)
|
| 64 |
+
answer_match = re.search(r"Answer: (.*?)(?:\n|$)", wiki_answer, re.DOTALL)
|
| 65 |
+
if answer_match:
|
| 66 |
+
concise_answer = answer_match.group(1).strip()
|
| 67 |
+
wiki_reasoning = wiki_answer if wiki_answer else "No reasoning provided."
|
| 68 |
+
else:
|
| 69 |
+
concise_answer = self._extract_concise_answer(wiki_answer)
|
| 70 |
+
wiki_reasoning = wiki_answer
|
| 71 |
+
reasoning.append(f"Wikipedia API: Searched '{key_terms}'. Summary: {wiki_summary[:100]}... Answer: {concise_answer}")
|
| 72 |
+
print(f"Returning concise answer (Wikipedia): {concise_answer}")
|
| 73 |
+
return concise_answer, "\n".join(reasoning)
|
| 74 |
else:
|
| 75 |
+
reasoning.append(f"Wikipedia API: No page found for '{key_terms}'.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
except Exception as e:
|
| 77 |
+
reasoning.append(f"Wikipedia API failed: {e}")
|
| 78 |
|
| 79 |
# Step 3: Try web search with DuckDuckGo
|
| 80 |
try:
|
|
|
|
| 98 |
concise_answer = self._extract_concise_answer(search_answer)
|
| 99 |
search_reasoning = search_answer
|
| 100 |
reasoning.append(f"Web Search (DuckDuckGo): Searched '{question}'. Answer: {concise_answer}")
|
| 101 |
+
print(f"Returning concise answer (search): {concise_answer}")
|
| 102 |
return concise_answer, "\n".join(reasoning)
|
| 103 |
else:
|
| 104 |
reasoning.append("Web Search (DuckDuckGo): No relevant results found.")
|
|
|
|
| 122 |
concise_answer = self._extract_concise_answer(full_response)
|
| 123 |
llm_reasoning = full_response
|
| 124 |
reasoning.append(f"LLM (Flan-T5-Base): {llm_reasoning}")
|
| 125 |
+
print(f"Returning concise answer (LLM): {concise_answer}")
|
| 126 |
return concise_answer, "\n".join(reasoning)
|
| 127 |
except Exception as e:
|
| 128 |
print(f"Error querying Inference API: {e}")
|
|
|
|
| 158 |
and displays the results.
|
| 159 |
"""
|
| 160 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 161 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 162 |
|
| 163 |
if profile:
|
| 164 |
+
username = f"{profile.username}"
|
| 165 |
print(f"User logged in: {username}")
|
| 166 |
else:
|
| 167 |
print("User not logged in.")
|
|
|
|
| 187 |
response.raise_for_status()
|
| 188 |
questions_data = response.json()
|
| 189 |
if not questions_data:
|
| 190 |
+
print("Fetched questions list is empty.")
|
| 191 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 192 |
print(f"Fetched {len(questions_data)} questions.")
|
| 193 |
except requests.exceptions.RequestException as e:
|
| 194 |
print(f"Error fetching questions: {e}")
|
| 195 |
return f"Error fetching questions: {e}", None
|
| 196 |
except requests.exceptions.JSONDecodeError as e:
|
| 197 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 198 |
+
print(f"Response text: {response.text[:500]}")
|
| 199 |
+
return f"Error decoding server response for questions: {e}", None
|
| 200 |
except Exception as e:
|
| 201 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 202 |
return f"An unexpected error occurred fetching questions: {e}", None
|
|
|
|
| 221 |
"Reasoning": reasoning
|
| 222 |
})
|
| 223 |
except Exception as e:
|
| 224 |
+
print(f"Error running agent on task {task_id}: {e}")
|
| 225 |
+
results_log.append({
|
| 226 |
+
"Task ID": task_id,
|
| 227 |
+
"Question": question_text,
|
| 228 |
+
"Submitted Answer": f"AGENT ERROR: {e}",
|
| 229 |
+
"Reasoning": f"Error: {e}"
|
| 230 |
+
})
|
| 231 |
|
| 232 |
if not answers_payload:
|
| 233 |
print("Agent did not produce any answers to submit.")
|
| 234 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 235 |
|
| 236 |
+
# 4. Prepare Submission
|
| 237 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 238 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 239 |
print(status_update)
|
|
|
|
| 313 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 314 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 315 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 316 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 317 |
|
| 318 |
if space_host_startup:
|
| 319 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
|
| 321 |
else:
|
| 322 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 323 |
|
| 324 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 325 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 326 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 327 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|