Update app.py
Browse filesAdded some code
app.py
CHANGED
@@ -7,13 +7,16 @@ import pandas as pd
|
|
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}")
|
@@ -29,8 +32,10 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
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 |
|
@@ -42,10 +47,12 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
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
|
@@ -55,28 +62,35 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
55 |
response.raise_for_status()
|
56 |
questions_data = response.json()
|
57 |
if not questions_data:
|
|
|
58 |
print("Fetched questions list is empty.")
|
59 |
return "Fetched questions list is empty or invalid format.", None
|
|
|
60 |
print(f"Fetched {len(questions_data)} questions.")
|
61 |
except requests.exceptions.RequestException as e:
|
|
|
62 |
print(f"Error fetching questions: {e}")
|
63 |
return f"Error fetching questions: {e}", None
|
64 |
except requests.exceptions.JSONDecodeError as e:
|
65 |
-
|
66 |
-
|
67 |
-
|
|
|
68 |
except Exception as e:
|
|
|
69 |
print(f"An unexpected error occurred fetching questions: {e}")
|
70 |
return f"An unexpected error occurred fetching questions: {e}", None
|
71 |
|
72 |
# 3. Run your Agent
|
73 |
results_log = []
|
74 |
answers_payload = []
|
|
|
75 |
print(f"Running agent on {len(questions_data)} questions...")
|
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:
|
@@ -84,19 +98,23 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
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 |
-
|
88 |
-
|
|
|
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}
|
96 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
|
|
97 |
print(status_update)
|
98 |
|
99 |
# 5. Submit
|
|
|
100 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
101 |
try:
|
102 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
@@ -109,6 +127,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
109 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
110 |
f"Message: {result_data.get('message', 'No message received.')}"
|
111 |
)
|
|
|
112 |
print("Submission successful.")
|
113 |
results_df = pd.DataFrame(results_log)
|
114 |
return final_status, results_df
|
@@ -120,21 +139,25 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
120 |
except requests.exceptions.JSONDecodeError:
|
121 |
error_detail += f" Response: {e.response.text[:500]}"
|
122 |
status_message = f"Submission Failed: {error_detail}"
|
|
|
123 |
print(status_message)
|
124 |
results_df = pd.DataFrame(results_log)
|
125 |
return status_message, results_df
|
126 |
except requests.exceptions.Timeout:
|
127 |
status_message = "Submission Failed: The request timed out."
|
|
|
128 |
print(status_message)
|
129 |
results_df = pd.DataFrame(results_log)
|
130 |
return status_message, results_df
|
131 |
except requests.exceptions.RequestException as e:
|
132 |
status_message = f"Submission Failed: Network error - {e}"
|
|
|
133 |
print(status_message)
|
134 |
results_df = pd.DataFrame(results_log)
|
135 |
return status_message, results_df
|
136 |
except Exception as e:
|
137 |
status_message = f"An unexpected error occurred during submission: {e}"
|
|
|
138 |
print(status_message)
|
139 |
results_df = pd.DataFrame(results_log)
|
140 |
return status_message, results_df
|
@@ -172,25 +195,32 @@ with gr.Blocks() as demo:
|
|
172 |
)
|
173 |
|
174 |
if __name__ == "__main__":
|
|
|
175 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
176 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
177 |
space_host_startup = os.getenv("SPACE_HOST")
|
178 |
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
179 |
|
180 |
if space_host_startup:
|
|
|
181 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
182 |
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
183 |
else:
|
|
|
184 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
185 |
|
186 |
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
|
|
187 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
188 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
189 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
190 |
else:
|
|
|
191 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
192 |
|
|
|
193 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
194 |
|
|
|
195 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
196 |
demo.launch(debug=True, share=False)
|
|
|
7 |
# (Keep Constants as is)
|
8 |
# --- Constants ---
|
9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
10 |
+
user_name = "rahulraj42"
|
11 |
|
12 |
# --- Basic Agent Definition ---
|
13 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
14 |
class BasicAgent:
|
15 |
def __init__(self):
|
16 |
+
print(f"{user_name}")
|
17 |
print("BasicAgent initialized.")
|
18 |
def __call__(self, question: str) -> str:
|
19 |
+
print(f"{user_name}")
|
20 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
21 |
fixed_answer = "This is a default answer."
|
22 |
print(f"Agent returning fixed answer: {fixed_answer}")
|
|
|
32 |
|
33 |
if profile:
|
34 |
username= f"{profile.username}"
|
35 |
+
print(f"{user_name}")
|
36 |
print(f"User logged in: {username}")
|
37 |
else:
|
38 |
+
print(f"{user_name}")
|
39 |
print("User not logged in.")
|
40 |
return "Please Login to Hugging Face with the button.", None
|
41 |
|
|
|
47 |
try:
|
48 |
agent = BasicAgent()
|
49 |
except Exception as e:
|
50 |
+
print(f"{user_name}")
|
51 |
print(f"Error instantiating agent: {e}")
|
52 |
return f"Error initializing agent: {e}", None
|
53 |
# 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)
|
54 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
55 |
+
print(f"{user_name}")
|
56 |
print(agent_code)
|
57 |
|
58 |
# 2. Fetch Questions
|
|
|
62 |
response.raise_for_status()
|
63 |
questions_data = response.json()
|
64 |
if not questions_data:
|
65 |
+
print(f"{user_name}")
|
66 |
print("Fetched questions list is empty.")
|
67 |
return "Fetched questions list is empty or invalid format.", None
|
68 |
+
print(f"{user_name}")
|
69 |
print(f"Fetched {len(questions_data)} questions.")
|
70 |
except requests.exceptions.RequestException as e:
|
71 |
+
print(f"{user_name}")
|
72 |
print(f"Error fetching questions: {e}")
|
73 |
return f"Error fetching questions: {e}", None
|
74 |
except requests.exceptions.JSONDecodeError as e:
|
75 |
+
print(f"{user_name}")
|
76 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
77 |
+
print(f"Response text: {response.text[:500]}")
|
78 |
+
return f"Error decoding server response for questions: {e}", None
|
79 |
except Exception as e:
|
80 |
+
print(f"{user_name}")
|
81 |
print(f"An unexpected error occurred fetching questions: {e}")
|
82 |
return f"An unexpected error occurred fetching questions: {e}", None
|
83 |
|
84 |
# 3. Run your Agent
|
85 |
results_log = []
|
86 |
answers_payload = []
|
87 |
+
print(f"{user_name}")
|
88 |
print(f"Running agent on {len(questions_data)} questions...")
|
89 |
for item in questions_data:
|
90 |
task_id = item.get("task_id")
|
91 |
question_text = item.get("question")
|
92 |
if not task_id or question_text is None:
|
93 |
+
print(f"{user_name}")
|
94 |
print(f"Skipping item with missing task_id or question: {item}")
|
95 |
continue
|
96 |
try:
|
|
|
98 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
99 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
100 |
except Exception as e:
|
101 |
+
print(f"{user_name}")
|
102 |
+
print(f"Error running agent on task {task_id}: {e}")
|
103 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
104 |
|
105 |
if not answers_payload:
|
106 |
+
print(f"{user_name}")
|
107 |
print("Agent did not produce any answers to submit.")
|
108 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
109 |
|
110 |
# 4. Prepare Submission
|
111 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
112 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
113 |
+
print(f"{user_name}")
|
114 |
print(status_update)
|
115 |
|
116 |
# 5. Submit
|
117 |
+
print(f"{user_name}")
|
118 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
119 |
try:
|
120 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
|
|
127 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
128 |
f"Message: {result_data.get('message', 'No message received.')}"
|
129 |
)
|
130 |
+
print(f"{user_name}")
|
131 |
print("Submission successful.")
|
132 |
results_df = pd.DataFrame(results_log)
|
133 |
return final_status, results_df
|
|
|
139 |
except requests.exceptions.JSONDecodeError:
|
140 |
error_detail += f" Response: {e.response.text[:500]}"
|
141 |
status_message = f"Submission Failed: {error_detail}"
|
142 |
+
print(f"{user_name}")
|
143 |
print(status_message)
|
144 |
results_df = pd.DataFrame(results_log)
|
145 |
return status_message, results_df
|
146 |
except requests.exceptions.Timeout:
|
147 |
status_message = "Submission Failed: The request timed out."
|
148 |
+
print(f"{user_name}")
|
149 |
print(status_message)
|
150 |
results_df = pd.DataFrame(results_log)
|
151 |
return status_message, results_df
|
152 |
except requests.exceptions.RequestException as e:
|
153 |
status_message = f"Submission Failed: Network error - {e}"
|
154 |
+
print(f"{user_name}")
|
155 |
print(status_message)
|
156 |
results_df = pd.DataFrame(results_log)
|
157 |
return status_message, results_df
|
158 |
except Exception as e:
|
159 |
status_message = f"An unexpected error occurred during submission: {e}"
|
160 |
+
print(f"{user_name}")
|
161 |
print(status_message)
|
162 |
results_df = pd.DataFrame(results_log)
|
163 |
return status_message, results_df
|
|
|
195 |
)
|
196 |
|
197 |
if __name__ == "__main__":
|
198 |
+
print(f"{user_name}")
|
199 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
200 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
201 |
space_host_startup = os.getenv("SPACE_HOST")
|
202 |
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
203 |
|
204 |
if space_host_startup:
|
205 |
+
print(f"{user_name}")
|
206 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
207 |
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
208 |
else:
|
209 |
+
print(f"{user_name}")
|
210 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
211 |
|
212 |
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
213 |
+
print(f"{user_name}")
|
214 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
215 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
216 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
217 |
else:
|
218 |
+
print(f"{user_name}")
|
219 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
220 |
|
221 |
+
print(f"{user_name}")
|
222 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
223 |
|
224 |
+
print(f"{user_name}")
|
225 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
226 |
demo.launch(debug=True, share=False)
|