makatony commited on
Commit
bc2cc75
Β·
1 Parent(s): f082354

trying to make it work by copying the code from the sample space

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