Spaces:
Runtime error
Runtime error
Mike Jay
commited on
Commit
·
8850f30
1
Parent(s):
dea8abd
app starts and log in works
Browse files- app.py +9 -117
- config.py +0 -2
- fetch_questions.py +0 -26
- requirements.txt +1 -1
app.py
CHANGED
@@ -1,127 +1,18 @@
|
|
|
|
|
|
1 |
import os
|
2 |
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 |
-
"""
|
24 |
-
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
25 |
-
and displays the results.
|
26 |
-
"""
|
27 |
-
# --- Determine HF Space Runtime URL and Repo URL ---
|
28 |
-
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
29 |
|
|
|
|
|
|
|
30 |
if profile:
|
31 |
-
username= f"{profile.username}"
|
32 |
print(f"User logged in: {username}")
|
33 |
else:
|
34 |
print("User not logged in.")
|
35 |
return "Please Login to Hugging Face with the button.", 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
|
47 |
-
# In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
|
48 |
-
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
49 |
-
print(agent_code)
|
50 |
-
|
51 |
-
# 2. Fetch Questions
|
52 |
-
status_output, questions_data = fetch_questions(questions_url)
|
53 |
-
if not question_data:
|
54 |
-
return status_output, None
|
55 |
-
|
56 |
-
# 3. Run your Agent
|
57 |
-
results_log = []
|
58 |
-
answers_payload = []
|
59 |
-
print(f"Running agent on {len(questions_data)} questions...")
|
60 |
-
for item in questions_data:
|
61 |
-
task_id = item.get("task_id")
|
62 |
-
question_text = item.get("question")
|
63 |
-
if not task_id or question_text is None:
|
64 |
-
print(f"Skipping item with missing task_id or question: {item}")
|
65 |
-
continue
|
66 |
-
try:
|
67 |
-
submitted_answer = agent(question_text)
|
68 |
-
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
69 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
70 |
-
except Exception as e:
|
71 |
-
print(f"Error running agent on task {task_id}: {e}")
|
72 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
73 |
-
|
74 |
-
if not answers_payload:
|
75 |
-
print("Agent did not produce any answers to submit.")
|
76 |
-
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
77 |
-
|
78 |
-
# 4. Prepare Submission
|
79 |
-
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
80 |
-
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
81 |
-
print(status_update)
|
82 |
-
|
83 |
-
# 5. Submit
|
84 |
-
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
85 |
-
try:
|
86 |
-
response = requests.post(submit_url, json=submission_data, timeout=60)
|
87 |
-
response.raise_for_status()
|
88 |
-
result_data = response.json()
|
89 |
-
final_status = (
|
90 |
-
f"Submission Successful!\n"
|
91 |
-
f"User: {result_data.get('username')}\n"
|
92 |
-
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
93 |
-
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
94 |
-
f"Message: {result_data.get('message', 'No message received.')}"
|
95 |
-
)
|
96 |
-
print("Submission successful.")
|
97 |
-
results_df = pd.DataFrame(results_log)
|
98 |
-
return final_status, results_df
|
99 |
-
except requests.exceptions.HTTPError as e:
|
100 |
-
error_detail = f"Server responded with status {e.response.status_code}."
|
101 |
-
try:
|
102 |
-
error_json = e.response.json()
|
103 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
104 |
-
except requests.exceptions.JSONDecodeError:
|
105 |
-
error_detail += f" Response: {e.response.text[:500]}"
|
106 |
-
status_message = f"Submission Failed: {error_detail}"
|
107 |
-
print(status_message)
|
108 |
-
results_df = pd.DataFrame(results_log)
|
109 |
-
return status_message, results_df
|
110 |
-
except requests.exceptions.Timeout:
|
111 |
-
status_message = "Submission Failed: The request timed out."
|
112 |
-
print(status_message)
|
113 |
-
results_df = pd.DataFrame(results_log)
|
114 |
-
return status_message, results_df
|
115 |
-
except requests.exceptions.RequestException as e:
|
116 |
-
status_message = f"Submission Failed: Network error - {e}"
|
117 |
-
print(status_message)
|
118 |
-
results_df = pd.DataFrame(results_log)
|
119 |
-
return status_message, results_df
|
120 |
-
except Exception as e:
|
121 |
-
status_message = f"An unexpected error occurred during submission: {e}"
|
122 |
-
print(status_message)
|
123 |
-
results_df = pd.DataFrame(results_log)
|
124 |
-
return status_message, results_df
|
125 |
|
126 |
|
127 |
# --- Build Gradio Interface using Blocks ---
|
@@ -177,4 +68,5 @@ if __name__ == "__main__":
|
|
177 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
178 |
|
179 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
180 |
-
demo.launch(debug=True, share=False)
|
|
|
|
1 |
+
"""Application"""
|
2 |
+
|
3 |
import os
|
4 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
+
|
7 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
8 |
+
"""Run and Submit All"""
|
9 |
if profile:
|
10 |
+
username = f"{profile.username}"
|
11 |
print(f"User logged in: {username}")
|
12 |
else:
|
13 |
print("User not logged in.")
|
14 |
return "Please Login to Hugging Face with the button.", None
|
15 |
+
return "Status", None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
|
17 |
|
18 |
# --- Build Gradio Interface using Blocks ---
|
|
|
68 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
69 |
|
70 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
71 |
+
demo.launch(debug=True, share=False)
|
72 |
+
|
config.py
DELETED
@@ -1,2 +0,0 @@
|
|
1 |
-
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
2 |
-
|
|
|
|
|
|
fetch_questions.py
DELETED
@@ -1,26 +0,0 @@
|
|
1 |
-
"""Fetch Questions from Hugging Face API"""
|
2 |
-
|
3 |
-
import requests
|
4 |
-
|
5 |
-
from config import DEFAULT_API_URL
|
6 |
-
|
7 |
-
def fetch_questions(questions_url: str) -> str, list:
|
8 |
-
print(f"Fetching questions from: {questions_url}")
|
9 |
-
try:
|
10 |
-
response = requests.get(questions_url, timeout=15)
|
11 |
-
response.raise_for_status()
|
12 |
-
questions_data = response.json()
|
13 |
-
if not questions_data:
|
14 |
-
print("Fetched questions list is empty.")
|
15 |
-
return "Fetched questions list is empty or invalid format.", None
|
16 |
-
print(f"Fetched {len(questions_data)} questions.")
|
17 |
-
except requests.exceptions.RequestException as e:
|
18 |
-
print(f"Error fetching questions: {e}")
|
19 |
-
return f"Error fetching questions: {e}", None
|
20 |
-
except requests.exceptions.JSONDecodeError as e:
|
21 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
22 |
-
print(f"Response text: {response.text[:500]}")
|
23 |
-
return f"Error decoding server response for questions: {e}", None
|
24 |
-
except Exception as e:
|
25 |
-
print(f"An unexpected error occurred fetching questions: {e}")
|
26 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
@@ -1,3 +1,3 @@
|
|
1 |
-
gradio
|
2 |
requests
|
3 |
|
|
|
1 |
+
gradio[oauth]
|
2 |
requests
|
3 |
|