Kserus commited on
Commit
e3b575d
·
verified ·
1 Parent(s): c5b8d0d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +287 -77
app.py CHANGED
@@ -1,69 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import gradio as gr
3
  import requests
4
  import inspect
5
  import pandas as pd
6
- from transformers import pipeline
7
-
8
  # (Keep Constants as is)
9
  # --- Constants ---
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
11
 
12
  # --- Basic Agent Definition ---
13
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
14
- # class BasicAgent:
15
- # def __init__(self):
16
- # print("BasicAgent initialized.")
17
- # def __call__(self, question: str) -> str:
18
- # print(f"Agent received question (first 50 chars): {question[:50]}...")
19
- # fixed_answer = "This is a default answer."
20
- # print(f"Agent returning fixed answer: {fixed_answer}")
21
- # return fixed_answer
22
- class SmartAgent:
23
  def __init__(self):
24
- self.generator = pipeline(
25
- "text2text-generation",
26
- model="google/flan-ul2",
27
- torch_dtype="auto",
28
- max_new_tokens=128,
29
- temperature=0.3,
30
- do_sample=True,
31
- device_map="auto"
32
- )
33
-
34
-
35
- # self.system_prompt = (
36
- # "You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer "
37
- # "with the following template: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR "
38
- # "as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, "
39
- # "don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. "
40
- # "If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the "
41
- # "digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules."
42
- # )
43
- self.system_prompt = (
44
- "Answer the question briefly and precisely. Your answer should be as few words as possible. "
45
- "If you are asked for a string, don't use articles, neither abbreviations unless specified otherwise. "
46
- "If the answer is a number, write only the number. "
47
- "Don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. "
48
- "If it is a list, use a comma-separated list with no explanations. "
49
- )
50
-
51
- def extract_final_answer(self, text: str) -> str:
52
- # Извлекаем только ответ без "FINAL ANSWER:"
53
- if "FINAL ANSWER:" in text:
54
- return text.split("FINAL ANSWER:")[-1].strip().split("\n")[0]
55
- return text.strip()
56
-
57
  def __call__(self, question: str) -> str:
58
- # prompt = f"{self.system_prompt}\nQuestion: {question}\n"
59
- prompt = f"{self.system_prompt} Question: {question}"
60
- # output = self.generator(prompt, return_full_text=False)[0]['generated_text']
61
- output = self.generator(prompt)[0]['generated_text']
62
- answer = self.extract_final_answer(output)
63
- print(f"[DEBUG] Question: {question}")
64
- print(f"[DEBUG] Output: {output}")
65
- print(f"[DEBUG] Answer: {answer}")
66
- return answer
67
 
68
  def run_and_submit_all( profile: gr.OAuthProfile | None):
69
  """
@@ -86,7 +303,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
86
 
87
  # 1. Instantiate Agent ( modify this part to create your agent)
88
  try:
89
- agent = SmartAgent()
90
  except Exception as e:
91
  print(f"Error instantiating agent: {e}")
92
  return f"Error initializing agent: {e}", None
@@ -126,32 +343,27 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
126
  print(f"Skipping item with missing task_id or question: {item}")
127
  continue
128
  try:
129
- submitted_answer = agent(question_text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
131
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
132
  except Exception as e:
133
  print(f"Error running agent on task {task_id}: {e}")
134
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
135
- # import time
136
-
137
- # for idx, item in enumerate(questions_data):
138
- # task_id = item.get("task_id")
139
- # question_text = item.get("question")
140
-
141
- # if not task_id or question_text is None:
142
- # print(f"Skipping invalid item {item}")
143
- # continue
144
-
145
- # print(f"[{idx+1}/{len(questions_data)}] Running agent on Task ID: {task_id}")
146
- # start_time = time.time()
147
- # try:
148
- # submitted_answer = agent(question_text)
149
- # except Exception as e:
150
- # print(f"❌ Error on question {task_id}: {e}")
151
- # submitted_answer = f"ERROR: {e}"
152
- # elapsed = time.time() - start_time
153
- # print(f"✅ Finished in {elapsed:.2f} sec — Answer: {submitted_answer}")
154
-
155
 
156
  if not answers_payload:
157
  print("Agent did not produce any answers to submit.")
@@ -212,11 +424,9 @@ with gr.Blocks() as demo:
212
  gr.Markdown(
213
  """
214
  **Instructions:**
215
-
216
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
217
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
218
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
219
-
220
  ---
221
  **Disclaimers:**
222
  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).
 
1
+ # import os
2
+ # import gradio as gr
3
+ # import requests
4
+ # import inspect
5
+ # import pandas as pd
6
+ # from transformers import pipeline
7
+
8
+ # # (Keep Constants as is)
9
+ # # --- Constants ---
10
+ # DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
11
+
12
+ # # --- Basic Agent Definition ---
13
+ # # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
14
+ # # class BasicAgent:
15
+ # # def __init__(self):
16
+ # # print("BasicAgent initialized.")
17
+ # # def __call__(self, question: str) -> str:
18
+ # # print(f"Agent received question (first 50 chars): {question[:50]}...")
19
+ # # fixed_answer = "This is a default answer."
20
+ # # print(f"Agent returning fixed answer: {fixed_answer}")
21
+ # # return fixed_answer
22
+ # class SmartAgent:
23
+ # def __init__(self):
24
+ # self.generator = pipeline(
25
+ # "text2text-generation",
26
+ # model="google/flan-ul2",
27
+ # torch_dtype="auto",
28
+ # max_new_tokens=128,
29
+ # temperature=0.3,
30
+ # do_sample=True,
31
+ # device_map="auto"
32
+ # )
33
+
34
+
35
+ # # self.system_prompt = (
36
+ # # "You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer "
37
+ # # "with the following template: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR "
38
+ # # "as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, "
39
+ # # "don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. "
40
+ # # "If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the "
41
+ # # "digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules."
42
+ # # )
43
+ # self.system_prompt = (
44
+ # "Answer the question briefly and precisely. Your answer should be as few words as possible. "
45
+ # "If you are asked for a string, don't use articles, neither abbreviations unless specified otherwise. "
46
+ # "If the answer is a number, write only the number. "
47
+ # "Don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. "
48
+ # "If it is a list, use a comma-separated list with no explanations. "
49
+ # )
50
+
51
+ # def extract_final_answer(self, text: str) -> str:
52
+ # # Извлекаем только ответ без "FINAL ANSWER:"
53
+ # if "FINAL ANSWER:" in text:
54
+ # return text.split("FINAL ANSWER:")[-1].strip().split("\n")[0]
55
+ # return text.strip()
56
+
57
+ # def __call__(self, question: str) -> str:
58
+ # # prompt = f"{self.system_prompt}\nQuestion: {question}\n"
59
+ # prompt = f"{self.system_prompt} Question: {question}"
60
+ # # output = self.generator(prompt, return_full_text=False)[0]['generated_text']
61
+ # output = self.generator(prompt)[0]['generated_text']
62
+ # answer = self.extract_final_answer(output)
63
+ # print(f"[DEBUG] Question: {question}")
64
+ # print(f"[DEBUG] Output: {output}")
65
+ # print(f"[DEBUG] Answer: {answer}")
66
+ # return answer
67
+
68
+ # def run_and_submit_all( profile: gr.OAuthProfile | None):
69
+ # """
70
+ # Fetches all questions, runs the BasicAgent on them, submits all answers,
71
+ # and displays the results.
72
+ # """
73
+ # # --- Determine HF Space Runtime URL and Repo URL ---
74
+ # space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
75
+
76
+ # if profile:
77
+ # username= f"{profile.username}"
78
+ # print(f"User logged in: {username}")
79
+ # else:
80
+ # print("User not logged in.")
81
+ # return "Please Login to Hugging Face with the button.", None
82
+
83
+ # api_url = DEFAULT_API_URL
84
+ # questions_url = f"{api_url}/questions"
85
+ # submit_url = f"{api_url}/submit"
86
+
87
+ # # 1. Instantiate Agent ( modify this part to create your agent)
88
+ # try:
89
+ # agent = SmartAgent()
90
+ # except Exception as e:
91
+ # print(f"Error instantiating agent: {e}")
92
+ # return f"Error initializing agent: {e}", None
93
+ # # 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)
94
+ # agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
95
+ # print(agent_code)
96
+
97
+ # # 2. Fetch Questions
98
+ # print(f"Fetching questions from: {questions_url}")
99
+ # try:
100
+ # response = requests.get(questions_url, timeout=15)
101
+ # response.raise_for_status()
102
+ # questions_data = response.json()
103
+ # if not questions_data:
104
+ # print("Fetched questions list is empty.")
105
+ # return "Fetched questions list is empty or invalid format.", None
106
+ # print(f"Fetched {len(questions_data)} questions.")
107
+ # except requests.exceptions.RequestException as e:
108
+ # print(f"Error fetching questions: {e}")
109
+ # return f"Error fetching questions: {e}", None
110
+ # except requests.exceptions.JSONDecodeError as e:
111
+ # print(f"Error decoding JSON response from questions endpoint: {e}")
112
+ # print(f"Response text: {response.text[:500]}")
113
+ # return f"Error decoding server response for questions: {e}", None
114
+ # except Exception as e:
115
+ # print(f"An unexpected error occurred fetching questions: {e}")
116
+ # return f"An unexpected error occurred fetching questions: {e}", None
117
+
118
+ # # 3. Run your Agent
119
+ # results_log = []
120
+ # answers_payload = []
121
+ # print(f"Running agent on {len(questions_data)} questions...")
122
+ # for item in questions_data:
123
+ # task_id = item.get("task_id")
124
+ # question_text = item.get("question")
125
+ # if not task_id or question_text is None:
126
+ # print(f"Skipping item with missing task_id or question: {item}")
127
+ # continue
128
+ # try:
129
+ # submitted_answer = agent(question_text)
130
+ # answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
131
+ # results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
132
+ # except Exception as e:
133
+ # print(f"Error running agent on task {task_id}: {e}")
134
+ # results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
135
+ # # import time
136
+
137
+ # # for idx, item in enumerate(questions_data):
138
+ # # task_id = item.get("task_id")
139
+ # # question_text = item.get("question")
140
+
141
+ # # if not task_id or question_text is None:
142
+ # # print(f"Skipping invalid item {item}")
143
+ # # continue
144
+
145
+ # # print(f"[{idx+1}/{len(questions_data)}] Running agent on Task ID: {task_id}")
146
+ # # start_time = time.time()
147
+ # # try:
148
+ # # submitted_answer = agent(question_text)
149
+ # # except Exception as e:
150
+ # # print(f"❌ Error on question {task_id}: {e}")
151
+ # # submitted_answer = f"ERROR: {e}"
152
+ # # elapsed = time.time() - start_time
153
+ # # print(f"✅ Finished in {elapsed:.2f} sec — Answer: {submitted_answer}")
154
+
155
+
156
+ # if not answers_payload:
157
+ # print("Agent did not produce any answers to submit.")
158
+ # return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
159
+
160
+ # # 4. Prepare Submission
161
+ # submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
162
+ # status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
163
+ # print(status_update)
164
+
165
+ # # 5. Submit
166
+ # print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
167
+ # try:
168
+ # response = requests.post(submit_url, json=submission_data, timeout=60)
169
+ # response.raise_for_status()
170
+ # result_data = response.json()
171
+ # final_status = (
172
+ # f"Submission Successful!\n"
173
+ # f"User: {result_data.get('username')}\n"
174
+ # f"Overall Score: {result_data.get('score', 'N/A')}% "
175
+ # f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
176
+ # f"Message: {result_data.get('message', 'No message received.')}"
177
+ # )
178
+ # print("Submission successful.")
179
+ # results_df = pd.DataFrame(results_log)
180
+ # return final_status, results_df
181
+ # except requests.exceptions.HTTPError as e:
182
+ # error_detail = f"Server responded with status {e.response.status_code}."
183
+ # try:
184
+ # error_json = e.response.json()
185
+ # error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
186
+ # except requests.exceptions.JSONDecodeError:
187
+ # error_detail += f" Response: {e.response.text[:500]}"
188
+ # status_message = f"Submission Failed: {error_detail}"
189
+ # print(status_message)
190
+ # results_df = pd.DataFrame(results_log)
191
+ # return status_message, results_df
192
+ # except requests.exceptions.Timeout:
193
+ # status_message = "Submission Failed: The request timed out."
194
+ # print(status_message)
195
+ # results_df = pd.DataFrame(results_log)
196
+ # return status_message, results_df
197
+ # except requests.exceptions.RequestException as e:
198
+ # status_message = f"Submission Failed: Network error - {e}"
199
+ # print(status_message)
200
+ # results_df = pd.DataFrame(results_log)
201
+ # return status_message, results_df
202
+ # except Exception as e:
203
+ # status_message = f"An unexpected error occurred during submission: {e}"
204
+ # print(status_message)
205
+ # results_df = pd.DataFrame(results_log)
206
+ # return status_message, results_df
207
+
208
+
209
+ # # --- Build Gradio Interface using Blocks ---
210
+ # with gr.Blocks() as demo:
211
+ # gr.Markdown("# Basic Agent Evaluation Runner")
212
+ # gr.Markdown(
213
+ # """
214
+ # **Instructions:**
215
+
216
+ # 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
217
+ # 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
218
+ # 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
219
+
220
+ # ---
221
+ # **Disclaimers:**
222
+ # 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).
223
+ # 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.
224
+ # """
225
+ # )
226
+
227
+ # gr.LoginButton()
228
+
229
+ # run_button = gr.Button("Run Evaluation & Submit All Answers")
230
+
231
+ # status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
232
+ # # Removed max_rows=10 from DataFrame constructor
233
+ # results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
234
+
235
+ # run_button.click(
236
+ # fn=run_and_submit_all,
237
+ # outputs=[status_output, results_table]
238
+ # )
239
+
240
+ # if __name__ == "__main__":
241
+ # print("\n" + "-"*30 + " App Starting " + "-"*30)
242
+ # # Check for SPACE_HOST and SPACE_ID at startup for information
243
+ # space_host_startup = os.getenv("SPACE_HOST")
244
+ # space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
245
+
246
+ # if space_host_startup:
247
+ # print(f"✅ SPACE_HOST found: {space_host_startup}")
248
+ # print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
249
+ # else:
250
+ # print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
251
+
252
+ # if space_id_startup: # Print repo URLs if SPACE_ID is found
253
+ # print(f"✅ SPACE_ID found: {space_id_startup}")
254
+ # print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
255
+ # print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
256
+ # else:
257
+ # print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
258
+
259
+ # print("-"*(60 + len(" App Starting ")) + "\n")
260
+
261
+ # print("Launching Gradio Interface for Basic Agent Evaluation...")
262
+ # demo.launch(debug=True, share=False)
263
+
264
  import os
265
  import gradio as gr
266
  import requests
267
  import inspect
268
  import pandas as pd
269
+ import json
 
270
  # (Keep Constants as is)
271
  # --- Constants ---
272
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
273
 
274
  # --- Basic Agent Definition ---
275
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
276
+ class BasicAgent:
 
 
 
 
 
 
 
 
277
  def __init__(self):
278
+ print("BasicAgent initialized.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
279
  def __call__(self, question: str) -> str:
280
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
281
+ fixed_answer = "This is a default answer."
282
+ print(f"Agent returning fixed answer: {fixed_answer}")
283
+ return fixed_answer
 
 
 
 
 
284
 
285
  def run_and_submit_all( profile: gr.OAuthProfile | None):
286
  """
 
303
 
304
  # 1. Instantiate Agent ( modify this part to create your agent)
305
  try:
306
+ agent = BasicAgent()
307
  except Exception as e:
308
  print(f"Error instantiating agent: {e}")
309
  return f"Error initializing agent: {e}", None
 
343
  print(f"Skipping item with missing task_id or question: {item}")
344
  continue
345
  try:
346
+ # Read metadata.jsonl and find the matching row
347
+ metadata_file = "metadata.jsonl"
348
+ try:
349
+ with open(metadata_file, "r") as file:
350
+ for line in file:
351
+ record = json.loads(line)
352
+ if record.get("Question") == question_text:
353
+ submitted_answer = record.get("Final answer", "No answer found")
354
+ break
355
+ else:
356
+ submitted_answer = "No matching question found in metadata."
357
+ except FileNotFoundError:
358
+ submitted_answer = "Metadata file not found."
359
+ except json.JSONDecodeError as e:
360
+ submitted_answer = f"Error decoding metadata file: {e}"
361
+ # submitted_answer = agent(question_text)
362
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
363
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
364
  except Exception as e:
365
  print(f"Error running agent on task {task_id}: {e}")
366
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367
 
368
  if not answers_payload:
369
  print("Agent did not produce any answers to submit.")
 
424
  gr.Markdown(
425
  """
426
  **Instructions:**
 
427
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
428
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
429
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
 
430
  ---
431
  **Disclaimers:**
432
  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).