0f3dy commited on
Commit
dfbfa3b
·
verified ·
1 Parent(s): 8c9ad01

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -186
app.py DELETED
@@ -1,186 +0,0 @@
1
- import os
2
- import time
3
-
4
- import gradio as gr
5
- import pandas as pd
6
- import requests
7
-
8
- from agentcourse_unit4.api.agent_eval_api import AgentEvalApi
9
- from agentcourse_unit4.api.answer_data import AnswerData
10
- from agentcourse_unit4.basic_agent import BasicAgent
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_client = AgentEvalApi()
29
-
30
- # 1. Instantiate Agent ( modify this part to create your agent)
31
- try:
32
- agent = BasicAgent()
33
- except Exception as e:
34
- print(f"Error instantiating agent: {e}")
35
- return f"Error initializing agent: {e}", None
36
- # 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)
37
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
38
- print(agent_code)
39
-
40
- # 2. Fetch Questions
41
- print(f"Fetching questions from: {api_client.questions_url}")
42
- try:
43
- questions_data = api_client.get_questions()
44
- if not questions_data:
45
- print("Fetched questions list is empty.")
46
- return "Fetched questions list is empty or invalid format.", None
47
- print(f"Fetched {len(questions_data)} questions.")
48
- except requests.exceptions.RequestException as e:
49
- print(f"Error fetching questions: {e}")
50
- return f"Error fetching questions: {e}", None
51
- except requests.exceptions.JSONDecodeError as e:
52
- print(f"Error decoding JSON response from questions endpoint: {e}")
53
- print(f"Response text: {e.response.text[:500]}")
54
- return f"Error decoding server response for questions: {e}", None
55
- except Exception as e:
56
- print(f"An unexpected error occurred fetching questions: {e}")
57
- return f"An unexpected error occurred fetching questions: {e}", None
58
-
59
- # 3. Run your Agent
60
- results_log = []
61
- answers_payload = []
62
- print(f"Running agent on {len(questions_data)} questions...")
63
- for item in questions_data:
64
- task_id = item.task_id
65
- question_text = item.question
66
- file_name = item.file_name
67
-
68
- if not task_id or question_text is None:
69
- print(f"Skipping item with missing task_id or question: {item}")
70
- continue
71
-
72
- try:
73
- file_path = api_client.download_file(task_id, file_name) if len(file_name) > 0 else None
74
- submitted_answer = agent.run(question_text, file_path)
75
- answers_payload.append(AnswerData(task_id=task_id, answer=str(submitted_answer)))
76
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
77
-
78
- time.sleep(60) # to not exceed free limits
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
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
89
- print(status_update)
90
-
91
- # 5. Submit
92
- print(f"Submitting {len(answers_payload)} answers to: {api_client.submit_url}")
93
- try:
94
- result_data = api_client.submit_answers(username=username, agent_code=agent_code, answers=answers_payload)
95
- final_status = (
96
- f"Submission Successful!\n"
97
- f"User: {result_data.username}\n"
98
- f"Overall Score: {result_data.score}% "
99
- f"({result_data.correct_count}/{result_data.total_attempted} correct)\n"
100
- f"Message: {result_data.message}"
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
-
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
- ---
145
- **Disclaimers:**
146
- 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).
147
- 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.
148
- """
149
- )
150
-
151
- gr.LoginButton()
152
-
153
- run_button = gr.Button("Run Evaluation & Submit All Answers")
154
-
155
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
156
- # Removed max_rows=10 from DataFrame constructor
157
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
158
-
159
- run_button.click(
160
- fn=run_and_submit_all,
161
- outputs=[status_output, results_table]
162
- )
163
-
164
- if __name__ == "__main__":
165
- print("\n" + "-" * 30 + " App Starting " + "-" * 30)
166
- # Check for SPACE_HOST and SPACE_ID at startup for information
167
- space_host_startup = os.getenv("SPACE_HOST")
168
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
169
-
170
- if space_host_startup:
171
- print(f"✅ SPACE_HOST found: {space_host_startup}")
172
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
173
- else:
174
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
175
-
176
- if space_id_startup: # Print repo URLs if SPACE_ID is found
177
- print(f"✅ SPACE_ID found: {space_id_startup}")
178
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
179
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
180
- else:
181
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
182
-
183
- print("-" * (60 + len(" App Starting ")) + "\n")
184
-
185
- print("Launching Gradio Interface for Basic Agent Evaluation...")
186
- demo.launch(debug=True, share=False)