Toumaima commited on
Commit
513d2f4
·
verified ·
1 Parent(s): d58e25a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -188
app.py CHANGED
@@ -1,169 +1,3 @@
1
- import os
2
- import gradio as gr
3
- import requests
4
- import string
5
- import warnings
6
- import pandas as pd
7
- from huggingface_hub import login
8
- import re
9
- import json
10
- from groq import Groq
11
-
12
- # --- Constants ---
13
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
14
-
15
-
16
- # --- Basic Agent Definition ---
17
- class BasicAgent:
18
- def __init__(self):
19
- print("BasicAgent initialized.")
20
- self.client = Groq(api_key=os.environ["GROQ_API_KEY"])
21
- self.agent_prompt = (
22
- """You are a general AI assistant. I will ask you a question. Report your thoughts, and
23
- finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER].
24
- YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated
25
- list of numbers and/or strings.
26
- If you are asked for a number, don't use comma to write your number neither use units such as $
27
- or percent sign unless specified otherwise.
28
- If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the
29
- digits in plain text unless specified otherwise.
30
- If you are asked for a comma separated list, apply the above rules depending of whether the element
31
- to be put in the list is a number or a string."""
32
- )
33
-
34
- def format_final_answer(self, answer: str) -> str:
35
- cleaned = " ".join(answer.split())
36
- return f"FINAL ANSWER: {cleaned}"
37
-
38
- def check_commutativity(self):
39
- S = ['a', 'b', 'c', 'd', 'e']
40
- counter_example_elements = set()
41
- index = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}
42
- self.operation_table = [
43
- ['a', 'b', 'c', 'b', 'd'],
44
- ['b', 'c', 'a', 'e', 'c'],
45
- ['c', 'a', 'b', 'b', 'a'],
46
- ['b', 'e', 'b', 'e', 'd'],
47
- ['d', 'b', 'a', 'd', 'c']
48
- ]
49
- for x in S:
50
- for y in S:
51
- x_idx = index[x]
52
- y_idx = index[y]
53
- if self.operation_table[x_idx][y_idx] != self.operation_table[y_idx][x_idx]:
54
- counter_example_elements.add(x)
55
- counter_example_elements.add(y)
56
- return self.format_final_answer(", ".join(sorted(counter_example_elements)))
57
-
58
- def maybe_reversed(self, text: str) -> bool:
59
- words = text.split()
60
- reversed_ratio = sum(
61
- 1 for word in words if word[::-1].lower() in {
62
- "if", "you", "understand", "this", "sentence", "write",
63
- "opposite", "of", "the", "word", "left", "answer"
64
- }
65
- ) / len(words)
66
- return reversed_ratio > 0.3
67
-
68
- def solve_riddle(self, question: str) -> str:
69
- question = question[::-1]
70
- if "opposite of the word" in question:
71
- match = re.search(r"opposite of the word ['\"](\w+)['\"]", question)
72
- if match:
73
- word = match.group(1).lower()
74
- opposites = {
75
- "left": "right", "up": "down", "hot": "cold",
76
- "true": "false", "yes": "no", "black": "white"
77
- }
78
- opposite = opposites.get(word, f"UNKNOWN_OPPOSITE_OF_{word}")
79
- return "FINAL ANSWER: RIGHT"
80
- return self.format_final_answer("COULD_NOT_SOLVE")
81
-
82
- def query_groq(self, question: str) -> str:
83
- full_prompt = f"{self.agent_prompt}\n\nQuestion: {question}"
84
- try:
85
- response = self.client.chat.completions.create(
86
- model="llama3-8b-8192",
87
- messages=[{"role": "user", "content": full_prompt}]
88
- )
89
- answer = response.choices[0].message.content
90
- if "FINAL ANSWER: " in answer:
91
- return answer.split("FINAL ANSWER: ")[-1].strip().upper()
92
- else:
93
- return self.format_final_answer(answer).upper()
94
- except Exception as e:
95
- print(f"[Groq ERROR]: {e}")
96
- return self.format_final_answer("GROQ_ERROR")
97
-
98
- def __call__(self, question: str) -> str:
99
- print(f"Received question: {question[:50]}...")
100
- if "commutative" in question.lower():
101
- return self.check_commutativity()
102
- if self.maybe_reversed(question):
103
- print("Detected likely reversed riddle.")
104
- return self.solve_riddle(question)
105
- return self.query_groq(question)
106
-
107
- def question_scorer(model_answer: str, ground_truth: str) -> bool:
108
- def normalize_str(input_str, remove_punct=True) -> str:
109
- no_spaces = re.sub(r"\s", "", input_str)
110
- if remove_punct:
111
- translator = str.maketrans("", "", string.punctuation)
112
- return no_spaces.lower().translate(translator)
113
- else:
114
- return no_spaces.lower()
115
-
116
- def normalize_number_str(number_str: str) -> float | None:
117
- for char in ["$", "%", ","]:
118
- number_str = number_str.replace(char, "")
119
- try:
120
- return float(number_str)
121
- except ValueError:
122
- print(f"String '{number_str}' cannot be normalized to number.")
123
- return None
124
-
125
- def split_string(s: str, char_list: list[str] = [",", ";"]) -> list[str]:
126
- pattern = f"[{''.join(map(re.escape, char_list))}]"
127
- return [elem.strip() for elem in re.split(pattern, s)]
128
-
129
- def is_float(val) -> bool:
130
- try:
131
- float(val)
132
- return True
133
- except ValueError:
134
- return False
135
-
136
- if model_answer is None:
137
- model_answer = "None"
138
-
139
- if is_float(ground_truth):
140
- print(f"Evaluating '{model_answer}' as a number.")
141
- normalized = normalize_number_str(model_answer)
142
- return normalized == float(ground_truth) if normalized is not None else False
143
-
144
- elif any(char in ground_truth for char in [",", ";"]):
145
- print(f"Evaluating '{model_answer}' as a comma/semicolon-separated list.")
146
- gt_elems = split_string(ground_truth)
147
- ma_elems = split_string(model_answer)
148
-
149
- if len(gt_elems) != len(ma_elems):
150
- warnings.warn("Answer lists have different lengths, returning False.", UserWarning)
151
- return False
152
-
153
- for ma_elem, gt_elem in zip(ma_elems, gt_elems):
154
- if is_float(gt_elem):
155
- normalized = normalize_number_str(ma_elem)
156
- if normalized != float(gt_elem):
157
- return False
158
- else:
159
- if normalize_str(ma_elem, remove_punct=False) != normalize_str(gt_elem, remove_punct=False):
160
- return False
161
- return True
162
-
163
- else:
164
- print(f"Evaluating '{model_answer}' as a string.")
165
- return normalize_str(model_answer) == normalize_str(ground_truth)
166
-
167
  def run_and_submit_all(profile: gr.OAuthProfile | None):
168
  space_id = os.getenv("SPACE_ID")
169
  if profile:
@@ -183,6 +17,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
183
  return f"Error initializing agent: {e}", None
184
 
185
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
 
186
  try:
187
  response = requests.get(questions_url, timeout=15)
188
  response.raise_for_status()
@@ -194,21 +29,50 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
194
 
195
  results_log = []
196
  answers_payload = []
 
 
 
197
  for item in questions_data:
198
  task_id = item.get("task_id")
199
  question_text = item.get("question")
 
 
200
  if not task_id or question_text is None:
201
  continue
 
202
  try:
203
  submitted_answer = agent(question_text)
204
- print(submitted_answer)
205
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
206
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
  except Exception as e:
208
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
 
 
209
 
210
  if not answers_payload:
211
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
 
212
  submission_data = {
213
  "username": username.strip(),
214
  "agent_code": agent_code,
@@ -220,30 +84,21 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
220
  response.raise_for_status()
221
  result_data = response.json()
222
  print(result_data)
 
 
 
 
 
 
223
  final_status = (
224
  f"Submission Successful!\n"
225
  f"User: {result_data.get('username')}\n"
226
- f"Overall Score: {result_data.get('score', '?')}% "
227
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
228
  f"Message: {result_data.get('message', 'No message received.')}"
 
229
  )
230
  return final_status, pd.DataFrame(results_log)
 
231
  except Exception as e:
232
  return f"Submission Failed: {e}", pd.DataFrame(results_log)
233
-
234
- # --- Build Gradio Interface ---
235
- with gr.Blocks() as demo:
236
- gr.Markdown("# Basic Agent Evaluation Runner")
237
- gr.LoginButton()
238
- run_button = gr.Button("Run Evaluation & Submit All Answers")
239
- status_output = gr.Textbox(label="Run Status / Submission Result", max_lines=5, interactive=False, max_length=200)
240
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
241
-
242
- run_button.click(
243
- fn=run_and_submit_all,
244
- outputs=[status_output, results_table]
245
- )
246
-
247
- if __name__ == "__main__":
248
- print("Launching Gradio Interface for Basic Agent Evaluation...")
249
- demo.launch(debug=True, share=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  def run_and_submit_all(profile: gr.OAuthProfile | None):
2
  space_id = os.getenv("SPACE_ID")
3
  if profile:
 
17
  return f"Error initializing agent: {e}", None
18
 
19
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
20
+
21
  try:
22
  response = requests.get(questions_url, timeout=15)
23
  response.raise_for_status()
 
29
 
30
  results_log = []
31
  answers_payload = []
32
+ correct_count = 0
33
+ total_with_gold = 0
34
+
35
  for item in questions_data:
36
  task_id = item.get("task_id")
37
  question_text = item.get("question")
38
+ gold_answer = item.get("gold_answer")
39
+
40
  if not task_id or question_text is None:
41
  continue
42
+
43
  try:
44
  submitted_answer = agent(question_text)
45
+ is_correct = question_scorer(submitted_answer, gold_answer) if gold_answer else None
46
+
47
+ if is_correct is not None:
48
+ total_with_gold += 1
49
+ if is_correct:
50
+ correct_count += 1
51
+
52
+ answers_payload.append({
53
+ "task_id": task_id,
54
+ "submitted_answer": submitted_answer
55
+ })
56
+
57
+ results_log.append({
58
+ "Task ID": task_id,
59
+ "Question": question_text,
60
+ "Submitted Answer": submitted_answer,
61
+ "Gold Answer": gold_answer,
62
+ "Correct?": "✅" if is_correct else "❌" if is_correct is not None else "N/A"
63
+ })
64
  except Exception as e:
65
+ results_log.append({
66
+ "Task ID": task_id,
67
+ "Question": question_text,
68
+ "Submitted Answer": f"AGENT ERROR: {e}",
69
+ "Gold Answer": gold_answer,
70
+ "Correct?": "❌"
71
+ })
72
 
73
  if not answers_payload:
74
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
75
+
76
  submission_data = {
77
  "username": username.strip(),
78
  "agent_code": agent_code,
 
84
  response.raise_for_status()
85
  result_data = response.json()
86
  print(result_data)
87
+
88
+ accuracy_text = ""
89
+ if total_with_gold > 0:
90
+ accuracy = (correct_count / total_with_gold) * 100
91
+ accuracy_text = f"\nLocal Accuracy: {accuracy:.2f}% ({correct_count}/{total_with_gold} correct)"
92
+
93
  final_status = (
94
  f"Submission Successful!\n"
95
  f"User: {result_data.get('username')}\n"
96
+ f"Overall Score (from server): {result_data.get('score', '?')}% "
97
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
98
  f"Message: {result_data.get('message', 'No message received.')}"
99
+ f"{accuracy_text}"
100
  )
101
  return final_status, pd.DataFrame(results_log)
102
+
103
  except Exception as e:
104
  return f"Submission Failed: {e}", pd.DataFrame(results_log)