Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,73 +1,178 @@
|
|
1 |
import os
|
2 |
import gradio as gr
|
3 |
import requests
|
|
|
4 |
import pandas as pd
|
5 |
-
import subprocess # Needed for runtime pip install
|
6 |
-
import sys # Needed for runtime pip install
|
7 |
|
8 |
-
#
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
try:
|
18 |
-
#
|
19 |
-
|
20 |
-
print("ddgs installed successfully.")
|
21 |
except Exception as e:
|
22 |
-
print(f"
|
23 |
-
|
24 |
-
raise RuntimeError(f"CRITICAL: Failed to install ddgs: {e}")
|
25 |
-
# --- END: Force ddgs installation workaround ---
|
26 |
|
27 |
-
#
|
28 |
-
|
|
|
29 |
|
30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
#
|
38 |
-
|
39 |
-
|
40 |
-
# Send output to the scoring API
|
41 |
try:
|
42 |
-
response = requests.post(
|
43 |
-
|
44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
)
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
except requests.exceptions.RequestException as e:
|
51 |
-
|
|
|
|
|
|
|
52 |
except Exception as e:
|
53 |
-
|
|
|
|
|
|
|
54 |
|
55 |
-
# Gradio Interface
|
56 |
with gr.Blocks() as demo:
|
57 |
-
gr.Markdown("#
|
58 |
-
gr.Markdown(
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
|
65 |
run_button.click(
|
66 |
-
fn=
|
67 |
-
|
68 |
-
outputs=output_text
|
69 |
)
|
70 |
|
71 |
-
|
72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
|
|
|
1 |
import os
|
2 |
import gradio as gr
|
3 |
import requests
|
4 |
+
import inspect # Behåll denna, mallen använder den kanske internt
|
5 |
import pandas as pd
|
|
|
|
|
6 |
|
7 |
+
# Importera din GaiaAgent från den separata agent.py filen
|
8 |
+
from agent import GaiaAgent
|
9 |
+
|
10 |
+
# --- Constants ---
|
11 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
12 |
+
|
13 |
+
# --- Main Evaluation Function ---
|
14 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
15 |
+
"""
|
16 |
+
Fetches all questions, runs the GaiaAgent on them, submits all answers,
|
17 |
+
and displays the results.
|
18 |
+
"""
|
19 |
+
# --- Determine HF Space Runtime URL and Repo URL ---
|
20 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
21 |
+
if profile:
|
22 |
+
username= f"{profile.username}"
|
23 |
+
print(f"User logged in: {username}")
|
24 |
+
else:
|
25 |
+
print("User not logged in.")
|
26 |
+
return "Please Login to Hugging Face with the button.", None
|
27 |
+
api_url = DEFAULT_API_URL
|
28 |
+
questions_url = f"{api_url}/questions"
|
29 |
+
submit_url = f"{api_url}/submit"
|
30 |
+
|
31 |
+
# 1. Instantiate Agent (MODIFY THIS PART to create your agent)
|
32 |
try:
|
33 |
+
# Instantiera din GaiaAgent här istället för BasicAgent
|
34 |
+
agent = GaiaAgent()
|
|
|
35 |
except Exception as e:
|
36 |
+
print(f"Error instantiating agent: {e}")
|
37 |
+
return f"Error initializing agent: {e}", None
|
|
|
|
|
38 |
|
39 |
+
# In the case of an app running as a hugging Face space, this link points toward your codebase ( useful for others so please keep it public)
|
40 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
41 |
+
print(agent_code)
|
42 |
|
43 |
+
# 2. Fetch Questions
|
44 |
+
print(f"Fetching questions from: {questions_url}")
|
45 |
+
try:
|
46 |
+
response = requests.get(questions_url, timeout=15)
|
47 |
+
response.raise_for_status()
|
48 |
+
questions_data = response.json()
|
49 |
+
if not questions_data:
|
50 |
+
print("Fetched questions list is empty.")
|
51 |
+
return "Fetched questions list is empty or invalid format.", None
|
52 |
+
print(f"Fetched {len(questions_data)} questions.")
|
53 |
+
except requests.exceptions.RequestException as e:
|
54 |
+
print(f"Error fetching questions: {e}")
|
55 |
+
return f"Error fetching questions: {e}", None
|
56 |
+
except requests.exceptions.JSONDecodeError as e:
|
57 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
58 |
+
print(f"Response text: {response.text[:500]}")
|
59 |
+
return f"Error decoding server response for questions: {e}", None
|
60 |
+
except Exception as e:
|
61 |
+
print(f"An unexpected error occurred fetching questions: {e}")
|
62 |
+
return f"An unexpected error occurred fetching questions: {e}", None
|
63 |
+
|
64 |
+
# 3. Run your Agent
|
65 |
+
results_log = []
|
66 |
+
answers_payload = []
|
67 |
+
print(f"Running agent on {len(questions_data)} questions...")
|
68 |
+
for item in questions_data:
|
69 |
+
task_id = item.get("task_id")
|
70 |
+
question_text = item.get("question")
|
71 |
+
if not task_id or question_text is None:
|
72 |
+
print(f"Skipping item with missing task_id or question: {item}")
|
73 |
+
continue
|
74 |
+
try:
|
75 |
+
# Anropa din GaiaAgent med frågan
|
76 |
+
submitted_answer = agent(question_text)
|
77 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
78 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
79 |
+
except Exception as e:
|
80 |
+
print(f"Error running agent on task {task_id}: {e}")
|
81 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
82 |
+
|
83 |
+
if not answers_payload:
|
84 |
+
print("Agent did not produce any answers to submit.")
|
85 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
86 |
|
87 |
+
# 4. Prepare Submission
|
88 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
89 |
+
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
90 |
+
print(status_update)
|
91 |
+
|
92 |
+
# 5. Submit
|
93 |
+
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
|
|
|
|
94 |
try:
|
95 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
96 |
+
response.raise_for_status()
|
97 |
+
result_data = response.json()
|
98 |
+
final_status = (
|
99 |
+
f"Submission Successful!\n"
|
100 |
+
f"User: {result_data.get('username')}\n"
|
101 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
102 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
103 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
104 |
)
|
105 |
+
print("Submission successful.")
|
106 |
+
results_df = pd.DataFrame(results_log)
|
107 |
+
return final_status, results_df
|
108 |
+
except requests.exceptions.HTTPError as e:
|
109 |
+
error_detail = f"Server responded with status {e.response.status_code}."
|
110 |
+
try:
|
111 |
+
error_json = e.response.json()
|
112 |
+
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
113 |
+
except requests.exceptions.JSONDecodeError:
|
114 |
+
error_detail += f" Response: {e.response.text[:500]}"
|
115 |
+
status_message = f"Submission Failed: {error_detail}"
|
116 |
+
print(status_message)
|
117 |
+
results_df = pd.DataFrame(results_log)
|
118 |
+
return status_message, results_df
|
119 |
+
except requests.exceptions.Timeout:
|
120 |
+
status_message = "Submission Failed: The request timed out."
|
121 |
+
print(status_message)
|
122 |
+
results_df = pd.DataFrame(results_log)
|
123 |
+
return status_message, results_df
|
124 |
except requests.exceptions.RequestException as e:
|
125 |
+
status_message = f"Submission Failed: Network error - {e}"
|
126 |
+
print(status_message)
|
127 |
+
results_df = pd.DataFrame(results_log)
|
128 |
+
return status_message, results_df
|
129 |
except Exception as e:
|
130 |
+
status_message = f"An unexpected error occurred during submission: {e}"
|
131 |
+
print(status_message)
|
132 |
+
results_df = pd.DataFrame(results_log)
|
133 |
+
return status_message, results_df
|
134 |
|
135 |
+
# --- Build Gradio Interface using Blocks ---
|
136 |
with gr.Blocks() as demo:
|
137 |
+
gr.Markdown("# Basic Agent Evaluation Runner")
|
138 |
+
gr.Markdown(
|
139 |
+
"""
|
140 |
+
**Instructions:**
|
141 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
142 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
143 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
144 |
+
---
|
145 |
+
**Disclaimers:**
|
146 |
+
Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
|
147 |
+
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
|
148 |
+
"""
|
149 |
+
)
|
150 |
+
gr.LoginButton()
|
151 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
152 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
153 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True) # Ensure max_rows is not breaking it
|
154 |
|
155 |
run_button.click(
|
156 |
+
fn=run_and_submit_all,
|
157 |
+
outputs=[status_output, results_table]
|
|
|
158 |
)
|
159 |
|
160 |
+
if __name__ == "__main__":
|
161 |
+
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
162 |
+
space_host_startup = os.getenv("SPACE_HOST")
|
163 |
+
space_id_startup = os.getenv("SPACE_ID")
|
164 |
+
if space_host_startup:
|
165 |
+
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
166 |
+
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
167 |
+
else:
|
168 |
+
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
169 |
+
if space_id_startup:
|
170 |
+
print(f"✅ SPACE_ID found: {space_id_startup}")
|
171 |
+
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
172 |
+
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
173 |
+
else:
|
174 |
+
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
175 |
+
print("-"*(60 + len(" App Starting ")) + "\n")
|
176 |
+
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
177 |
+
demo.launch(debug=True, share=False)
|
178 |
|