AC-Angelo93 commited on
Commit
36b2b84
·
verified ·
1 Parent(s): 0628003

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +174 -23
app.py CHANGED
@@ -1,33 +1,184 @@
1
- import gradio as gr
2
- from agent import MistralAgent
3
- from api_utils import fetch_questions, submit_answers
4
  import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- API_URL = "https://.../questions"
7
- SUBMIT_URL = "https://.../submit"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
- # Read your Hugging Face token from environment (safer)
10
- HF_TOKEN = os.environ.get("HF_TOKEN")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
- def run_evaluation(username):
13
- agent = MistralAgent(hf_token=HF_TOKEN)
14
- questions = fetch_questions(API_URL)
15
 
16
- answers = []
17
- for q in questions:
18
- task_id = q["task_id"]
19
- question = q["question"]
20
- submitted_answer = agent.run(question)
21
- answers.append({"task_id": task_id, "output": submitted_answer})
22
 
23
- result = submit_answers(SUBMIT_URL, username, answers)
24
- return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
 
 
26
  with gr.Blocks() as demo:
27
- username = gr.Textbox(label="Username")
28
- run_button = gr.Button("Run Evaluation and Submit")
29
- output_text = gr.Textbox(label="Output")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
- run_button.click(fn=run_evaluation, inputs=[username], outputs=[output_text])
32
 
33
- demo.launch()
 
 
 
 
 
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
+
12
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
13
+ """
14
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
15
+ and displays the results.
16
+ """
17
+ # --- Determine HF Space Runtime URL and Repo URL ---
18
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
19
+
20
+ if profile:
21
+ username= f"{profile.username}"
22
+ print(f"User logged in: {username}")
23
+ else:
24
+ print("User not logged in.")
25
+ return "Please Login to Hugging Face with the button.", None
26
+
27
+ api_url = DEFAULT_API_URL
28
+ questions_url = f"{api_url}/questions"
29
+ submit_url = f"{api_url}/submit"
30
+
31
+ # 1. Instantiate Agent ( modify this part to create your agent)
32
+ try:
33
+ agent = BasicAgent()
34
+ except Exception as e:
35
+ print(f"Error instantiating agent: {e}")
36
+ return f"Error initializing agent: {e}", None
37
+ # 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)
38
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
39
+ print(agent_code)
40
 
41
+ # 2. Fetch Questions
42
+ print(f"Fetching questions from: {questions_url}")
43
+ try:
44
+ response = requests.get(questions_url, timeout=15)
45
+ response.raise_for_status()
46
+ questions_data = response.json()
47
+ if not questions_data:
48
+ print("Fetched questions list is empty.")
49
+ return "Fetched questions list is empty or invalid format.", None
50
+ print(f"Fetched {len(questions_data)} questions.")
51
+ except requests.exceptions.RequestException as e:
52
+ print(f"Error fetching questions: {e}")
53
+ return f"Error fetching questions: {e}", None
54
+ except requests.exceptions.JSONDecodeError as e:
55
+ print(f"Error decoding JSON response from questions endpoint: {e}")
56
+ print(f"Response text: {response.text[:500]}")
57
+ return f"Error decoding server response for questions: {e}", None
58
+ except Exception as e:
59
+ print(f"An unexpected error occurred fetching questions: {e}")
60
+ return f"An unexpected error occurred fetching questions: {e}", None
61
 
62
+ # 3. Run your Agent
63
+ results_log = []
64
+ answers_payload = []
65
+ print(f"Running agent on {len(questions_data)} questions...")
66
+ for item in questions_data:
67
+ task_id = item.get("task_id")
68
+ question_text = item.get("question")
69
+ if not task_id or question_text is None:
70
+ print(f"Skipping item with missing task_id or question: {item}")
71
+ continue
72
+ try:
73
+ submitted_answer = agent(question_text)
74
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
75
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
76
+ except Exception as e:
77
+ print(f"Error running agent on task {task_id}: {e}")
78
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
79
 
80
+ if not answers_payload:
81
+ print("Agent did not produce any answers to submit.")
82
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
83
 
84
+ # 4. Prepare Submission
85
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
86
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
87
+ print(status_update)
 
 
88
 
89
+ # 5. Submit
90
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
91
+ try:
92
+ response = requests.post(submit_url, json=submission_data, timeout=60)
93
+ response.raise_for_status()
94
+ result_data = response.json()
95
+ final_status = (
96
+ f"Submission Successful!\n"
97
+ f"User: {result_data.get('username')}\n"
98
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
99
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
100
+ f"Message: {result_data.get('message', 'No message received.')}"
101
+ )
102
+ print("Submission successful.")
103
+ results_df = pd.DataFrame(results_log)
104
+ return final_status, results_df
105
+ except requests.exceptions.HTTPError as e:
106
+ error_detail = f"Server responded with status {e.response.status_code}."
107
+ try:
108
+ error_json = e.response.json()
109
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
110
+ except requests.exceptions.JSONDecodeError:
111
+ error_detail += f" Response: {e.response.text[:500]}"
112
+ status_message = f"Submission Failed: {error_detail}"
113
+ print(status_message)
114
+ results_df = pd.DataFrame(results_log)
115
+ return status_message, results_df
116
+ except requests.exceptions.Timeout:
117
+ status_message = "Submission Failed: The request timed out."
118
+ print(status_message)
119
+ results_df = pd.DataFrame(results_log)
120
+ return status_message, results_df
121
+ except requests.exceptions.RequestException as e:
122
+ status_message = f"Submission Failed: Network error - {e}"
123
+ print(status_message)
124
+ results_df = pd.DataFrame(results_log)
125
+ return status_message, results_df
126
+ except Exception as e:
127
+ status_message = f"An unexpected error occurred during submission: {e}"
128
+ print(status_message)
129
+ results_df = pd.DataFrame(results_log)
130
+ return status_message, results_df
131
 
132
+
133
+ # --- Build Gradio Interface using Blocks ---
134
  with gr.Blocks() as demo:
135
+ gr.Markdown("# Basic Agent Evaluation Runner")
136
+ gr.Markdown(
137
+ """
138
+ **Instructions:**
139
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
140
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
141
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
142
+ ---
143
+ **Disclaimers:**
144
+ 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).
145
+ 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.
146
+ """
147
+ )
148
+
149
+ gr.LoginButton()
150
+
151
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
152
+
153
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
154
+ # Removed max_rows=10 from DataFrame constructor
155
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
156
+
157
+ run_button.click(
158
+ fn=run_and_submit_all,
159
+ outputs=[status_output, results_table]
160
+ )
161
+
162
+ if __name__ == "__main__":
163
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
164
+ # Check for SPACE_HOST and SPACE_ID at startup for information
165
+ space_host_startup = os.getenv("SPACE_HOST")
166
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
167
+
168
+ if space_host_startup:
169
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
170
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
171
+ else:
172
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
173
+
174
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
175
+ print(f"✅ SPACE_ID found: {space_id_startup}")
176
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
177
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
178
+ else:
179
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
180
 
181
+ print("-"*(60 + len(" App Starting ")) + "\n")
182
 
183
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
184
+ demo.launch(debug=True, share=False)