ptoloudis commited on
Commit
5327893
·
verified ·
1 Parent(s): 3f71280

Delete app.py

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