shreya3999 commited on
Commit
7145d28
·
verified ·
1 Parent(s): f0940ef

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +185 -0
app.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import requests
4
+ import inspect
5
+ import pandas as pd
6
+ from unit4_final.agent import BasicAgent
7
+
8
+
9
+ # (Keep Constants as is)
10
+ # --- Constants ---
11
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
+
13
+
14
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
15
+ """
16
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
17
+ and displays the results.
18
+ """
19
+ # --- Determine HF Space Runtime URL and Repo URL ---
20
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
21
+
22
+ if profile:
23
+ username= f"{profile.username}"
24
+ print(f"User logged in: {username}")
25
+ else:
26
+ print("User not logged in.")
27
+ return "Please Login to Hugging Face with the button.", None
28
+
29
+ api_url = DEFAULT_API_URL
30
+ questions_url = f"{api_url}/questions"
31
+ submit_url = f"{api_url}/submit"
32
+
33
+ # 1. Instantiate Agent ( modify this part to create your agent)
34
+ try:
35
+ agent = BasicAgent()
36
+ except Exception as e:
37
+ print(f"Error instantiating agent: {e}")
38
+ return f"Error initializing agent: {e}", None
39
+ # 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)
40
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
41
+ print(agent_code)
42
+
43
+ # 2. Fetch Questions
44
+ print(f"Fetching questions from: {questions_url}")
45
+ try:
46
+ response = requests.get(questions_url, timeout=15)
47
+ response.raise_for_status()
48
+ questions_data = response.json()
49
+ if not questions_data:
50
+ print("Fetched questions list is empty.")
51
+ return "Fetched questions list is empty or invalid format.", None
52
+ print(f"Fetched {len(questions_data)} questions.")
53
+ except requests.exceptions.RequestException as e:
54
+ print(f"Error fetching questions: {e}")
55
+ return f"Error fetching questions: {e}", None
56
+ except requests.exceptions.JSONDecodeError as e:
57
+ print(f"Error decoding JSON response from questions endpoint: {e}")
58
+ print(f"Response text: {response.text[:500]}")
59
+ return f"Error decoding server response for questions: {e}", None
60
+ except Exception as e:
61
+ print(f"An unexpected error occurred fetching questions: {e}")
62
+ return f"An unexpected error occurred fetching questions: {e}", None
63
+
64
+ # 3. Run your Agent
65
+ results_log = []
66
+ answers_payload = []
67
+ print(f"Running agent on {len(questions_data)} questions...")
68
+ for item in questions_data:
69
+ task_id = item.get("task_id")
70
+ question_text = item.get("question")
71
+ if not task_id or question_text is None:
72
+ print(f"Skipping item with missing task_id or question: {item}")
73
+ continue
74
+ try:
75
+ submitted_answer = agent(question_text)
76
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
77
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
78
+
79
+ except Exception as e:
80
+ print(f"Error running agent on task {task_id}: {e}")
81
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
82
+
83
+ if not answers_payload:
84
+ print("Agent did not produce any answers to submit.")
85
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
86
+
87
+ # 4. Prepare Submission
88
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
89
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
90
+ print(status_update)
91
+
92
+ # 5. Submit
93
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
94
+ try:
95
+ response = requests.post(submit_url, json=submission_data, timeout=60)
96
+ response.raise_for_status()
97
+ result_data = response.json()
98
+ final_status = (
99
+ f"Submission Successful!\n"
100
+ f"User: {result_data.get('username')}\n"
101
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
102
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
103
+ f"Message: {result_data.get('message', 'No message received.')}"
104
+ )
105
+ print("Submission successful.")
106
+ results_df = pd.DataFrame(results_log)
107
+ return final_status, results_df
108
+ except requests.exceptions.HTTPError as e:
109
+ error_detail = f"Server responded with status {e.response.status_code}."
110
+ try:
111
+ error_json = e.response.json()
112
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
113
+ except requests.exceptions.JSONDecodeError:
114
+ error_detail += f" Response: {e.response.text[:500]}"
115
+ status_message = f"Submission Failed: {error_detail}"
116
+ print(status_message)
117
+ results_df = pd.DataFrame(results_log)
118
+ return status_message, results_df
119
+ except requests.exceptions.Timeout:
120
+ status_message = "Submission Failed: The request timed out."
121
+ print(status_message)
122
+ results_df = pd.DataFrame(results_log)
123
+ return status_message, results_df
124
+ except requests.exceptions.RequestException as e:
125
+ status_message = f"Submission Failed: Network error - {e}"
126
+ print(status_message)
127
+ results_df = pd.DataFrame(results_log)
128
+ return status_message, results_df
129
+ except Exception as e:
130
+ status_message = f"An unexpected error occurred during submission: {e}"
131
+ print(status_message)
132
+ results_df = pd.DataFrame(results_log)
133
+ return status_message, results_df
134
+
135
+
136
+ # --- Build Gradio Interface using Blocks ---
137
+ with gr.Blocks() as demo:
138
+ gr.Markdown("# Basic Agent Evaluation Runner")
139
+ gr.Markdown(
140
+ """
141
+ **Instructions:**
142
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
143
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
144
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
145
+ ---
146
+ **Disclaimers:**
147
+ 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).
148
+ 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.
149
+ """
150
+ )
151
+ gr.LoginButton()
152
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
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
+
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)