yushnitp commited on
Commit
6a2b3c6
·
verified ·
1 Parent(s): 6e7efc8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +114 -100
app.py CHANGED
@@ -1,139 +1,94 @@
1
  import os
2
  import gradio as gr
3
  import requests
 
4
  import pandas as pd
5
- import json
6
- import mimetypes
7
- import tempfile
8
- import fitz # PyMuPDF for PDF parsing
9
- from openai import OpenAI
10
 
 
11
  # --- Constants ---
12
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
- OPENAI_FALLBACK_KEY = "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" # <<< Replace with your actual key here
14
-
15
- # --- OpenAI Agent with enhanced formatting and logic ---
16
- class OpenAIAgent:
17
- def __init__(self, model="gpt-4"):
18
- self.model = model
19
- self.system_prompt = (
20
- "You are a precise assistant that always returns a single, direct answer, with no explanation or justification. "
21
- "If the task asks for a list, format it exactly as instructed (e.g., comma-separated, alphabetized). "
22
- "If there is a file missing, infer the answer using the question context. "
23
- "Avoid all disclaimers, apologies, or messages about being a language model."
24
- )
25
- api_key = os.getenv("OPENAI_API_KEY") or OPENAI_FALLBACK_KEY
26
- if not api_key or "sk-" not in api_key:
27
- raise ValueError("A valid OpenAI API key must be set in the environment or OPENAI_FALLBACK_KEY.")
28
- self.client = OpenAI(api_key=api_key)
29
-
30
- def __call__(self, question: str, task_id: str = None, file_name: str = "") -> str:
31
- context = ""
32
- if task_id and file_name:
33
- try:
34
- context = self._fetch_file_context(task_id)
35
- except Exception as e:
36
- print(f"Warning: Failed to fetch or parse file for task {task_id}: {e}")
37
- # Add custom cues based on the question content
38
- if "comma separated" in question.lower():
39
- question = "Format your answer as a comma-separated list in alphabetical order.\n\n" + question
40
- if "only list the ingredients" in question.lower():
41
- question = "Output just the ingredient names, comma-separated.\n\n" + question
42
- if "numeric output" in question.lower():
43
- question = "Only provide the final numeric result, no units or explanation.\n\n" + question
44
-
45
- user_input = f"{question}\n\nAdditional context:\n{context}" if context else question
46
- return self._call_openai(user_input)
47
-
48
- def _call_openai(self, prompt: str) -> str:
49
- try:
50
- response = self.client.chat.completions.create(
51
- model=self.model,
52
- messages=[
53
- {"role": "system", "content": self.system_prompt},
54
- {"role": "user", "content": prompt},
55
- ],
56
- temperature=0,
57
- max_tokens=256,
58
- )
59
- return response.choices[0].message.content.strip()
60
- except Exception as e:
61
- print(f"OpenAI Agent error: {e}")
62
- return "ERROR"
63
-
64
- def _fetch_file_context(self, task_id: str) -> str:
65
- file_url = f"{DEFAULT_API_URL}/files/{task_id}"
66
- response = requests.get(file_url, timeout=10)
67
- if response.status_code == 404:
68
- print(f"No file found for task {task_id}. Continuing without context.")
69
- return ""
70
- response.raise_for_status()
71
- content_type = response.headers.get("content-type")
72
- extension = mimetypes.guess_extension(content_type)
73
-
74
- with tempfile.NamedTemporaryFile(delete=True, suffix=extension) as tmp_file:
75
- tmp_file.write(response.content)
76
- tmp_file.flush()
77
 
78
- if extension == ".pdf":
79
- return self._parse_pdf(tmp_file.name)
80
- elif extension in [".txt", ".csv", ".py"]:
81
- return response.text
82
- else:
83
- return f"[Non-text file of type {extension}, not processed.]"
84
 
85
- def _parse_pdf(self, filepath):
86
- doc = fitz.open(filepath)
87
- return "\n".join([page.get_text() for page in doc]).strip()
 
 
 
 
88
 
89
-
90
- def run_and_submit_all(profile: gr.OAuthProfile | None):
91
- space_id = os.getenv("SPACE_ID")
92
  if profile:
93
- username = f"{profile.username}"
94
  print(f"User logged in: {username}")
95
  else:
 
96
  return "Please Login to Hugging Face with the button.", None
97
 
98
  api_url = DEFAULT_API_URL
99
  questions_url = f"{api_url}/questions"
100
  submit_url = f"{api_url}/submit"
101
 
 
102
  try:
103
- agent = OpenAIAgent()
104
  except Exception as e:
 
105
  return f"Error initializing agent: {e}", None
106
-
107
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
 
108
 
 
 
109
  try:
110
  response = requests.get(questions_url, timeout=15)
111
  response.raise_for_status()
112
  questions_data = response.json()
113
  if not questions_data:
114
- return "Fetched questions list is empty or invalid format.", None
115
- except Exception as e:
 
 
 
116
  return f"Error fetching questions: {e}", None
 
 
 
 
 
 
 
117
 
 
118
  results_log = []
119
  answers_payload = []
 
120
  for item in questions_data:
121
  task_id = item.get("task_id")
122
  question_text = item.get("question")
123
- file_name = item.get("file_name", "")
124
  if not task_id or question_text is None:
 
125
  continue
126
  try:
127
- submitted_answer = agent(question_text, task_id=task_id, file_name=file_name)
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
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
132
 
133
  if not answers_payload:
 
134
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
135
 
 
136
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
 
 
 
 
 
137
  try:
138
  response = requests.post(submit_url, json=submission_data, timeout=60)
139
  response.raise_for_status()
@@ -145,27 +100,86 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
145
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
146
  f"Message: {result_data.get('message', 'No message received.')}"
147
  )
148
- return final_status, pd.DataFrame(results_log)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  except Exception as e:
150
- return f"Submission Failed: {e}", pd.DataFrame(results_log)
 
 
 
151
 
152
 
 
153
  with gr.Blocks() as demo:
154
- gr.Markdown("# OpenAI Agent Evaluation Runner")
155
- gr.Markdown("""
 
156
  **Instructions:**
157
- 1. Clone the space and modify code logic as needed.
158
- 2. Login with your Hugging Face account.
159
- 3. Click 'Run Evaluation & Submit All Answers' to evaluate.
160
- """)
 
 
 
 
 
161
 
162
  gr.LoginButton()
 
163
  run_button = gr.Button("Run Evaluation & Submit All Answers")
 
164
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
165
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
166
 
167
- run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
 
 
 
168
 
169
  if __name__ == "__main__":
170
- print("Launching Gradio Interface for OpenAI Agent Evaluation...")
171
- demo.launch(debug=True, share=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import gradio as gr
3
  import requests
4
+ import inspect
5
  import pandas as pd
6
+ from agent import BasicAgent
 
 
 
 
7
 
8
+ # (Keep Constants as is)
9
  # --- Constants ---
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
 
 
 
 
 
 
12
 
13
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
14
+ """
15
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
16
+ and displays the results.
17
+ """
18
+ # --- Determine HF Space Runtime URL and Repo URL ---
19
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
20
 
 
 
 
21
  if profile:
22
+ username= f"{profile.username}"
23
  print(f"User logged in: {username}")
24
  else:
25
+ print("User not logged in.")
26
  return "Please Login to Hugging Face with the button.", None
27
 
28
  api_url = DEFAULT_API_URL
29
  questions_url = f"{api_url}/questions"
30
  submit_url = f"{api_url}/submit"
31
 
32
+ # 1. Instantiate Agent ( modify this part to create your agent)
33
  try:
34
+ agent = BasicAgent()
35
  except Exception as e:
36
+ print(f"Error instantiating agent: {e}")
37
  return f"Error initializing agent: {e}", None
38
+ # 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)
39
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
40
+ print(agent_code)
41
 
42
+ # 2. Fetch Questions
43
+ print(f"Fetching questions from: {questions_url}")
44
  try:
45
  response = requests.get(questions_url, timeout=15)
46
  response.raise_for_status()
47
  questions_data = response.json()
48
  if not questions_data:
49
+ print("Fetched questions list is empty.")
50
+ return "Fetched questions list is empty or invalid format.", None
51
+ print(f"Fetched {len(questions_data)} questions.")
52
+ except requests.exceptions.RequestException as e:
53
+ print(f"Error fetching questions: {e}")
54
  return f"Error fetching questions: {e}", None
55
+ except requests.exceptions.JSONDecodeError as e:
56
+ print(f"Error decoding JSON response from questions endpoint: {e}")
57
+ print(f"Response text: {response.text[:500]}")
58
+ return f"Error decoding server response for questions: {e}", None
59
+ except Exception as e:
60
+ print(f"An unexpected error occurred fetching questions: {e}")
61
+ return f"An unexpected error occurred fetching questions: {e}", None
62
 
63
+ # 3. Run your Agent
64
  results_log = []
65
  answers_payload = []
66
+ print(f"Running agent on {len(questions_data)} questions...")
67
  for item in questions_data:
68
  task_id = item.get("task_id")
69
  question_text = item.get("question")
 
70
  if not task_id or question_text is None:
71
+ print(f"Skipping item with missing task_id or question: {item}")
72
  continue
73
  try:
74
+ submitted_answer = agent(question_text)
75
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
76
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
77
  except Exception as e:
78
+ print(f"Error running agent on task {task_id}: {e}")
79
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
80
 
81
  if not answers_payload:
82
+ print("Agent did not produce any answers to submit.")
83
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
84
 
85
+ # 4. Prepare Submission
86
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
87
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
88
+ print(status_update)
89
+
90
+ # 5. Submit
91
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
92
  try:
93
  response = requests.post(submit_url, json=submission_data, timeout=60)
94
  response.raise_for_status()
 
100
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
101
  f"Message: {result_data.get('message', 'No message received.')}"
102
  )
103
+ print("Submission successful.")
104
+ results_df = pd.DataFrame(results_log)
105
+ return final_status, results_df
106
+ except requests.exceptions.HTTPError as e:
107
+ error_detail = f"Server responded with status {e.response.status_code}."
108
+ try:
109
+ error_json = e.response.json()
110
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
111
+ except requests.exceptions.JSONDecodeError:
112
+ error_detail += f" Response: {e.response.text[:500]}"
113
+ status_message = f"Submission Failed: {error_detail}"
114
+ print(status_message)
115
+ results_df = pd.DataFrame(results_log)
116
+ return status_message, results_df
117
+ except requests.exceptions.Timeout:
118
+ status_message = "Submission Failed: The request timed out."
119
+ print(status_message)
120
+ results_df = pd.DataFrame(results_log)
121
+ return status_message, results_df
122
+ except requests.exceptions.RequestException as e:
123
+ status_message = f"Submission Failed: Network error - {e}"
124
+ print(status_message)
125
+ results_df = pd.DataFrame(results_log)
126
+ return status_message, results_df
127
  except Exception as e:
128
+ status_message = f"An unexpected error occurred during submission: {e}"
129
+ print(status_message)
130
+ results_df = pd.DataFrame(results_log)
131
+ return status_message, results_df
132
 
133
 
134
+ # --- Build Gradio Interface using Blocks ---
135
  with gr.Blocks() as demo:
136
+ gr.Markdown("# Basic Agent Evaluation Runner")
137
+ gr.Markdown(
138
+ """
139
  **Instructions:**
140
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
141
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
142
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
143
+ ---
144
+ **Disclaimers:**
145
+ 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).
146
+ 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.
147
+ """
148
+ )
149
 
150
  gr.LoginButton()
151
+
152
  run_button = gr.Button("Run Evaluation & Submit All Answers")
153
+
154
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
155
+ # Removed max_rows=10 from DataFrame constructor
156
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
157
 
158
+ run_button.click(
159
+ fn=run_and_submit_all,
160
+ outputs=[status_output, results_table]
161
+ )
162
 
163
  if __name__ == "__main__":
164
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
165
+ # Check for SPACE_HOST and SPACE_ID at startup for information
166
+ space_host_startup = os.getenv("SPACE_HOST")
167
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
168
+
169
+ if space_host_startup:
170
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
171
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
172
+ else:
173
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
174
+
175
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
176
+ print(f"✅ SPACE_ID found: {space_id_startup}")
177
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
178
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
179
+ else:
180
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
181
+
182
+ print("-"*(60 + len(" App Starting ")) + "\n")
183
+
184
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
185
+ demo.launch(debug=True, share=False)