ATK20 commited on
Commit
4e281a3
·
verified ·
1 Parent(s): d21ad06

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -108
app.py CHANGED
@@ -1,7 +1,6 @@
1
  import os
2
  import gradio as gr
3
  import requests
4
- import inspect
5
  import pandas as pd
6
  from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
7
 
@@ -16,7 +15,6 @@ class BasicAgent:
16
  self.hf_token = hf_token
17
  self.model_name = model_name
18
  self.llm = None
19
- self.tokenizer = None
20
 
21
  if hf_token:
22
  try:
@@ -55,84 +53,59 @@ class BasicAgent:
55
  return f"Error generating answer: {e}"
56
 
57
  def run_and_submit_all(profile: gr.OAuthProfile | None, hf_token: str):
58
- """
59
- Fetches all questions, runs the BasicAgent on them, submits all answers,
60
- and displays the results.
61
- """
62
- # --- Determine HF Space Runtime URL and Repo URL ---
63
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
64
-
65
- if profile:
66
- username= f"{profile.username}"
67
- print(f"User logged in: {username}")
68
- else:
69
- print("User not logged in.")
70
  return "Please Login to Hugging Face with the button.", None
71
 
 
72
  api_url = DEFAULT_API_URL
73
  questions_url = f"{api_url}/questions"
74
  submit_url = f"{api_url}/submit"
75
 
76
- # 1. Instantiate Agent
77
  try:
78
  agent = BasicAgent(hf_token=hf_token)
79
  except Exception as e:
80
- print(f"Error instantiating agent: {e}")
81
  return f"Error initializing agent: {e}", None
82
 
83
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
84
- print(agent_code)
85
 
86
- # 2. Fetch Questions
87
- print(f"Fetching questions from: {questions_url}")
88
  try:
89
  response = requests.get(questions_url, timeout=15)
90
  response.raise_for_status()
91
  questions_data = response.json()
92
  if not questions_data:
93
- print("Fetched questions list is empty.")
94
- return "Fetched questions list is empty or invalid format.", None
95
- print(f"Fetched {len(questions_data)} questions.")
96
- except requests.exceptions.RequestException as e:
97
- print(f"Error fetching questions: {e}")
98
- return f"Error fetching questions: {e}", None
99
- except requests.exceptions.JSONDecodeError as e:
100
- print(f"Error decoding JSON response from questions endpoint: {e}")
101
- print(f"Response text: {response.text[:500]}")
102
- return f"Error decoding server response for questions: {e}", None
103
  except Exception as e:
104
- print(f"An unexpected error occurred fetching questions: {e}")
105
- return f"An unexpected error occurred fetching questions: {e}", None
106
 
107
- # 3. Run your Agent
108
  results_log = []
109
  answers_payload = []
110
- print(f"Running agent on {len(questions_data)} questions...")
111
  for item in questions_data:
112
  task_id = item.get("task_id")
113
  question_text = item.get("question")
114
  if not task_id or question_text is None:
115
- print(f"Skipping item with missing task_id or question: {item}")
116
  continue
117
  try:
118
  submitted_answer = agent(question_text)
119
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
120
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
121
  except Exception as e:
122
- print(f"Error running agent on task {task_id}: {e}")
123
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
124
 
125
  if not answers_payload:
126
- print("Agent did not produce any answers to submit.")
127
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
128
 
129
- # 4. Prepare Submission
130
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
131
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
132
- print(status_update)
133
-
134
- # 5. Submit
135
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
136
  try:
137
  response = requests.post(submit_url, json=submission_data, timeout=60)
138
  response.raise_for_status()
@@ -144,67 +117,35 @@ def run_and_submit_all(profile: gr.OAuthProfile | None, hf_token: str):
144
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
145
  f"Message: {result_data.get('message', 'No message received.')}"
146
  )
147
- print("Submission successful.")
148
- results_df = pd.DataFrame(results_log)
149
- return final_status, results_df
150
- except requests.exceptions.HTTPError as e:
151
- error_detail = f"Server responded with status {e.response.status_code}."
152
- try:
153
- error_json = e.response.json()
154
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
155
- except requests.exceptions.JSONDecodeError:
156
- error_detail += f" Response: {e.response.text[:500]}"
157
- status_message = f"Submission Failed: {error_detail}"
158
- print(status_message)
159
- results_df = pd.DataFrame(results_log)
160
- return status_message, results_df
161
- except requests.exceptions.Timeout:
162
- status_message = "Submission Failed: The request timed out."
163
- print(status_message)
164
- results_df = pd.DataFrame(results_log)
165
- return status_message, results_df
166
- except requests.exceptions.RequestException as e:
167
- status_message = f"Submission Failed: Network error - {e}"
168
- print(status_message)
169
- results_df = pd.DataFrame(results_log)
170
- return status_message, results_df
171
  except Exception as e:
172
- status_message = f"An unexpected error occurred during submission: {e}"
173
- print(status_message)
174
- results_df = pd.DataFrame(results_log)
175
- return status_message, results_df
176
-
177
 
178
- # --- Build Gradio Interface using Blocks ---
179
  with gr.Blocks() as demo:
180
  gr.Markdown("# LLM Agent Evaluation Runner")
181
- gr.Markdown(
182
- """
183
  **Instructions:**
184
  1. Get your Hugging Face API token from [your settings](https://huggingface.co/settings/tokens)
185
- 2. Enter your token below (it will be used only during this session)
186
  3. Log in to your Hugging Face account
187
- 4. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
188
-
189
- ---
190
- **Note:** The first run will take longer as it downloads the model.
191
- """
192
- )
193
 
194
  with gr.Row():
195
  hf_token_input = gr.Textbox(
196
  label="Hugging Face API Token",
197
  type="password",
198
- placeholder="Enter your HF API token here (required for LLM)",
199
- info="Get your token from https://huggingface.co/settings/tokens"
200
  )
201
 
202
  gr.LoginButton()
203
 
204
  run_button = gr.Button("Run Evaluation & Submit All Answers")
205
 
206
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
207
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
208
 
209
  run_button.click(
210
  fn=run_and_submit_all,
@@ -213,24 +154,4 @@ with gr.Blocks() as demo:
213
  )
214
 
215
  if __name__ == "__main__":
216
- print("\n" + "-"*30 + " App Starting " + "-"*30)
217
- space_host_startup = os.getenv("SPACE_HOST")
218
- space_id_startup = os.getenv("SPACE_ID")
219
-
220
- if space_host_startup:
221
- print(f"✅ SPACE_HOST found: {space_host_startup}")
222
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
223
- else:
224
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
225
-
226
- if space_id_startup:
227
- print(f"✅ SPACE_ID found: {space_id_startup}")
228
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
229
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
230
- else:
231
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
232
-
233
- print("-"*(60 + len(" App Starting ")) + "\n")
234
-
235
- print("Launching Gradio Interface for LLM Agent Evaluation...")
236
- demo.launch(debug=True, share=False)
 
1
  import os
2
  import gradio as gr
3
  import requests
 
4
  import pandas as pd
5
  from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
6
 
 
15
  self.hf_token = hf_token
16
  self.model_name = model_name
17
  self.llm = None
 
18
 
19
  if hf_token:
20
  try:
 
53
  return f"Error generating answer: {e}"
54
 
55
  def run_and_submit_all(profile: gr.OAuthProfile | None, hf_token: str):
56
+ """Main function to run evaluation and submit answers"""
57
+ space_id = os.getenv("SPACE_ID")
58
+ if not profile:
 
 
 
 
 
 
 
 
 
59
  return "Please Login to Hugging Face with the button.", None
60
 
61
+ username = profile.username
62
  api_url = DEFAULT_API_URL
63
  questions_url = f"{api_url}/questions"
64
  submit_url = f"{api_url}/submit"
65
 
66
+ # Initialize agent
67
  try:
68
  agent = BasicAgent(hf_token=hf_token)
69
  except Exception as e:
 
70
  return f"Error initializing agent: {e}", None
71
 
72
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
 
73
 
74
+ # Fetch questions
 
75
  try:
76
  response = requests.get(questions_url, timeout=15)
77
  response.raise_for_status()
78
  questions_data = response.json()
79
  if not questions_data:
80
+ return "Fetched questions list is empty or invalid format.", None
 
 
 
 
 
 
 
 
 
81
  except Exception as e:
82
+ return f"Error fetching questions: {e}", None
 
83
 
84
+ # Process questions
85
  results_log = []
86
  answers_payload = []
 
87
  for item in questions_data:
88
  task_id = item.get("task_id")
89
  question_text = item.get("question")
90
  if not task_id or question_text is None:
 
91
  continue
92
  try:
93
  submitted_answer = agent(question_text)
94
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
95
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
96
  except Exception as e:
97
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
98
 
99
  if not answers_payload:
 
100
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
101
 
102
+ # Submit answers
103
+ submission_data = {
104
+ "username": username.strip(),
105
+ "agent_code": agent_code,
106
+ "answers": answers_payload
107
+ }
108
+
109
  try:
110
  response = requests.post(submit_url, json=submission_data, timeout=60)
111
  response.raise_for_status()
 
117
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
118
  f"Message: {result_data.get('message', 'No message received.')}"
119
  )
120
+ return final_status, pd.DataFrame(results_log)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  except Exception as e:
122
+ return f"Submission Failed: {e}", pd.DataFrame(results_log)
 
 
 
 
123
 
124
+ # --- Gradio Interface ---
125
  with gr.Blocks() as demo:
126
  gr.Markdown("# LLM Agent Evaluation Runner")
127
+ gr.Markdown("""
 
128
  **Instructions:**
129
  1. Get your Hugging Face API token from [your settings](https://huggingface.co/settings/tokens)
130
+ 2. Enter your token below
131
  3. Log in to your Hugging Face account
132
+ 4. Click 'Run Evaluation & Submit All Answers'
133
+ """)
 
 
 
 
134
 
135
  with gr.Row():
136
  hf_token_input = gr.Textbox(
137
  label="Hugging Face API Token",
138
  type="password",
139
+ placeholder="hf_xxxxxxxxxxxxxxxx",
140
+ info="Required for LLM access"
141
  )
142
 
143
  gr.LoginButton()
144
 
145
  run_button = gr.Button("Run Evaluation & Submit All Answers")
146
 
147
+ status_output = gr.Textbox(label="Run Status", lines=5)
148
+ results_table = gr.DataFrame(label="Results", wrap=True)
149
 
150
  run_button.click(
151
  fn=run_and_submit_all,
 
154
  )
155
 
156
  if __name__ == "__main__":
157
+ demo.launch()