WileCoyotte commited on
Commit
9b7a8fe
·
verified ·
1 Parent(s): c4b4d0e

Upload 5 files

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