vladd19 commited on
Commit
6603541
·
verified ·
1 Parent(s): d48f0e3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +187 -1
app.py CHANGED
@@ -1,3 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
  # --- Basic Agent Definition ---
2
  class BasicAgent:
3
  def __init__(self):
@@ -49,4 +61,178 @@ class BasicAgent:
49
  except Exception as e:
50
  error_msg = f"ERROR: {str(e)}"
51
  print(f"Ошибка при работе агента: {error_msg}")
52
- return error_msg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
  # --- Basic Agent Definition ---
14
  class BasicAgent:
15
  def __init__(self):
 
61
  except Exception as e:
62
  error_msg = f"ERROR: {str(e)}"
63
  print(f"Ошибка при работе агента: {error_msg}")
64
+ return error_msg
65
+
66
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
67
+ """
68
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
69
+ and displays the results.
70
+ """
71
+ # --- Determine HF Space Runtime URL and Repo URL ---
72
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
73
+
74
+ if profile:
75
+ username= f"{profile.username}"
76
+ print(f"User logged in: {username}")
77
+ else:
78
+ print("User not logged in.")
79
+ return "Please Login to Hugging Face with the button.", None
80
+
81
+ api_url = DEFAULT_API_URL
82
+ questions_url = f"{api_url}/questions"
83
+ submit_url = f"{api_url}/submit"
84
+
85
+ # 1. Instantiate Agent ( modify this part to create your agent)
86
+ try:
87
+ agent = BasicAgent()
88
+ except Exception as e:
89
+ print(f"Error instantiating agent: {e}")
90
+ return f"Error initializing agent: {e}", None
91
+ # 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)
92
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
93
+ print(agent_code)
94
+
95
+ # 2. Fetch Questions
96
+ print(f"Fetching questions from: {questions_url}")
97
+ try:
98
+ response = requests.get(questions_url, timeout=15)
99
+ response.raise_for_status()
100
+ questions_data = response.json()
101
+ if not questions_data:
102
+ print("Fetched questions list is empty.")
103
+ return "Fetched questions list is empty or invalid format.", None
104
+ print(f"Fetched {len(questions_data)} questions.")
105
+ except requests.exceptions.RequestException as e:
106
+ print(f"Error fetching questions: {e}")
107
+ return f"Error fetching questions: {e}", None
108
+ except requests.exceptions.JSONDecodeError as e:
109
+ print(f"Error decoding JSON response from questions endpoint: {e}")
110
+ print(f"Response text: {response.text[:500]}")
111
+ return f"Error decoding server response for questions: {e}", None
112
+ except Exception as e:
113
+ print(f"An unexpected error occurred fetching questions: {e}")
114
+ return f"An unexpected error occurred fetching questions: {e}", None
115
+
116
+ # 3. Run your Agent
117
+ results_log = []
118
+ answers_payload = []
119
+ print(f"Running agent on {len(questions_data)} questions...")
120
+ for item in questions_data:
121
+ task_id = item.get("task_id")
122
+ question_text = item.get("question")
123
+ if not task_id or question_text is None:
124
+ print(f"Skipping item with missing task_id or question: {item}")
125
+ continue
126
+ try:
127
+ submitted_answer = agent(question_text)
128
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
129
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
130
+ except Exception as e:
131
+ print(f"Error running agent on task {task_id}: {e}")
132
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
133
+
134
+ if not answers_payload:
135
+ print("Agent did not produce any answers to submit.")
136
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
137
+
138
+ # 4. Prepare Submission
139
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
140
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
141
+ print(status_update)
142
+
143
+ # 5. Submit
144
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
145
+ try:
146
+ response = requests.post(submit_url, json=submission_data, timeout=60)
147
+ response.raise_for_status()
148
+ result_data = response.json()
149
+ final_status = (
150
+ f"Submission Successful!\n"
151
+ f"User: {result_data.get('username')}\n"
152
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
153
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
154
+ f"Message: {result_data.get('message', 'No message received.')}"
155
+ )
156
+ print("Submission successful.")
157
+ results_df = pd.DataFrame(results_log)
158
+ return final_status, results_df
159
+ except requests.exceptions.HTTPError as e:
160
+ error_detail = f"Server responded with status {e.response.status_code}."
161
+ try:
162
+ error_json = e.response.json()
163
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
164
+ except requests.exceptions.JSONDecodeError:
165
+ error_detail += f" Response: {e.response.text[:500]}"
166
+ status_message = f"Submission Failed: {error_detail}"
167
+ print(status_message)
168
+ results_df = pd.DataFrame(results_log)
169
+ return status_message, results_df
170
+ except requests.exceptions.Timeout:
171
+ status_message = "Submission Failed: The request timed out."
172
+ print(status_message)
173
+ results_df = pd.DataFrame(results_log)
174
+ return status_message, results_df
175
+ except requests.exceptions.RequestException as e:
176
+ status_message = f"Submission Failed: Network error - {e}"
177
+ print(status_message)
178
+ results_df = pd.DataFrame(results_log)
179
+ return status_message, results_df
180
+ except Exception as e:
181
+ status_message = f"An unexpected error occurred during submission: {e}"
182
+ print(status_message)
183
+ results_df = pd.DataFrame(results_log)
184
+ return status_message, results_df
185
+
186
+
187
+ # --- Build Gradio Interface using Blocks ---
188
+ with gr.Blocks() as demo:
189
+ gr.Markdown("# Basic Agent Evaluation Runner")
190
+ gr.Markdown(
191
+ """
192
+ **Instructions:**
193
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
194
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
195
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
196
+ ---
197
+ **Disclaimers:**
198
+ 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).
199
+ 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.
200
+ """
201
+ )
202
+
203
+ gr.LoginButton()
204
+
205
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
206
+
207
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
208
+ # Removed max_rows=10 from DataFrame constructor
209
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
210
+
211
+ run_button.click(
212
+ fn=run_and_submit_all,
213
+ outputs=[status_output, results_table]
214
+ )
215
+
216
+ if __name__ == "__main__":
217
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
218
+ # Check for SPACE_HOST and SPACE_ID at startup for information
219
+ space_host_startup = os.getenv("SPACE_HOST")
220
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
221
+
222
+ if space_host_startup:
223
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
224
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
225
+ else:
226
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
227
+
228
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
229
+ print(f"✅ SPACE_ID found: {space_id_startup}")
230
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
231
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
232
+ else:
233
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
234
+
235
+ print("-"*(60 + len(" App Starting ")) + "\n")
236
+
237
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
238
+ demo.launch(debug=True, share=False)