magdap116 commited on
Commit
6b01f84
·
verified ·
1 Parent(s): 3d32e7d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +287 -287
app.py CHANGED
@@ -1,287 +1,287 @@
1
- import os
2
- import gradio as gr
3
- import requests
4
- import inspect
5
- import pandas as pd
6
- from smolagents import DuckDuckGoSearchTool, HfApiModel, PythonInterpreterTool, VisitWebpageTool, CodeAgent
7
- import hashlib
8
- import json
9
- from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline, TransformersEngine
10
- import wikipedia
11
- import torch
12
- from tooling import MathModelQuerer, WikipediaPageFetcher, YoutubeTranscriptFetcher, CodeModelQuerer
13
-
14
- # (Keep Constants as is)
15
- # --- Constants ---
16
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
17
-
18
- # --- Basic Agent Definition ---
19
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
20
- import os
21
-
22
- cache = {}
23
-
24
- web_search = DuckDuckGoSearchTool()
25
- python_interpreter = PythonInterpreterTool()
26
- visit_webpage_tool = VisitWebpageTool()
27
- wiki_tool = WikipediaPageFetcher()
28
- yt_transcript_fetcher = YoutubeTranscriptFetcher()
29
- math_model_querer = MathModelQuerer()
30
- code_model_querer = CodeModelQuerer()
31
-
32
-
33
- def load_cached_answer(question_id: str) -> str:
34
- if question_id in cache.keys():
35
- return cache[question_id]
36
- else:
37
- return None
38
-
39
-
40
- def cache_answer(question_id: str, answer: str):
41
- cache[question_id] = answer
42
-
43
-
44
- # --- Model Setup ---
45
- MODEL_NAME = 'Qwen/Qwen2.5-3B-Instruct' # 'meta-llama/Llama-3.2-3B-Instruct'
46
-
47
-
48
- # "Qwen/Qwen2.5-VL-3B-Instruct"#'meta-llama/Llama-2-7b-hf'#'meta-llama/Llama-3.1-8B-Instruct'#'TinyLlama/TinyLlama-1.1B-Chat-v1.0'#'mistralai/Mistral-7B-Instruct-v0.2'#'microsoft/DialoGPT-small'# 'EleutherAI/gpt-neo-2.7B'#'distilbert/distilgpt2'#'deepseek-ai/DeepSeek-R1-Distill-Qwen-7B'#'mistralai/Mistral-7B-Instruct-v0.2'
49
-
50
-
51
- def load_model(model_name):
52
- """Download and load the model and tokenizer."""
53
- try:
54
- print(f"Loading model {MODEL_NAME}...")
55
- model = AutoModelForCausalLM.from_pretrained(MODEL_NAME)
56
- tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
57
-
58
- if tokenizer.pad_token is None:
59
- tokenizer.pad_token = tokenizer.eos_token
60
-
61
- print(f"Model {MODEL_NAME} loaded successfully.")
62
-
63
- transformers_engine = TransformersEngine(pipeline("text-generation", model=model, tokenizer=tokenizer))
64
-
65
- return transformers_engine, model
66
- except Exception as e:
67
- print(f"Error loading model: {e}")
68
- raise
69
-
70
-
71
- # Load the model and tokenizer locally
72
- # model, tokenizer = load_model()
73
- model = HfApiModel() # model_id=MODEL_NAME, max_tokens=512)
74
- model_id = "reedmayhew/claude-3.7-sonnet-reasoning-gemma3-12B" # "microsoft/phi-2"# not working out of the box"google/gemma-2-2b-it" #toobig"Qwen/Qwen1.5-7B-Chat"#working but stupid: "meta-llama/Llama-3.2-3B-Instruct"
75
- model = HfApiModel(model_id)
76
- #from smolagents import TransformersModel
77
- # model = TransformersModel(
78
- # model_id=model_id,
79
- # max_new_tokens=256)
80
-
81
- # model = HfApiModel()
82
-
83
-
84
- class BasicAgent:
85
- def __init__(self):
86
- print("BasicAgent initialized.")
87
- self.agent = CodeAgent(
88
- model=model,
89
- tools=[web_search, python_interpreter, visit_webpage_tool, wiki_tool, code_model_querer, math_model_querer],
90
- max_steps=3,
91
- verbosity_level=1,
92
- grammar=None,
93
- planning_interval=3,
94
- add_base_tools=True,
95
- additional_authorized_imports=['requests', 'wikipedia', 'pandas']
96
-
97
- )
98
-
99
- def __call__(self, question: str) -> str:
100
- print(f"Agent received question (first 50 chars): {question[:50]}...")
101
- answer = self.agent.run(question)
102
- return answer
103
-
104
-
105
- def run_and_submit_all(profile: gr.OAuthProfile | None):
106
- """
107
- Fetches all questions, runs the BasicAgent on them, submits all answers,
108
- and displays the results.
109
- """
110
- # --- Determine HF Space Runtime URL and Repo URL ---
111
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
112
-
113
- if profile:
114
- username = f"{profile.username}"
115
- print(f"User logged in: {username}")
116
- else:
117
- print("User not logged in.")
118
- return "Please Login to Hugging Face with the button.", None
119
-
120
- api_url = DEFAULT_API_URL
121
- questions_url = f"{api_url}/questions"
122
- submit_url = f"{api_url}/submit"
123
-
124
- # 1. Instantiate Agent ( modify this part to create your agent)
125
- try:
126
- agent = BasicAgent()
127
- except Exception as e:
128
- print(f"Error instantiating agent: {e}")
129
- return f"Error initializing agent: {e}", None
130
- # 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)
131
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
132
- print(agent_code)
133
-
134
- # 2. Fetch Questions
135
- print(f"Fetching questions from: {questions_url}")
136
- try:
137
- response = requests.get(questions_url, timeout=15)
138
- response.raise_for_status()
139
- questions_data = response.json()
140
- if not questions_data:
141
- print("Fetched questions list is empty.")
142
- return "Fetched questions list is empty or invalid format.", None
143
- print(f"Fetched {len(questions_data)} questions.")
144
- except requests.exceptions.RequestException as e:
145
- print(f"Error fetching questions: {e}")
146
- return f"Error fetching questions: {e}", None
147
- except requests.exceptions.JSONDecodeError as e:
148
- print(f"Error decoding JSON response from questions endpoint: {e}")
149
- print(f"Response text: {response.text[:500]}")
150
- return f"Error decoding server response for questions: {e}", None
151
- except Exception as e:
152
- print(f"An unexpected error occurred fetching questions: {e}")
153
- return f"An unexpected error occurred fetching questions: {e}", None
154
-
155
- # 3. Run your Agent
156
- results_log = []
157
- answers_payload = []
158
- print(f"Running agent on {len(questions_data)} questions...")
159
- for item in questions_data[:1]:
160
- task_id = item.get("task_id")
161
- question_text = item.get("question")
162
- if not task_id or question_text is None:
163
- print(f"Skipping item with missing task_id or question: {item}")
164
- continue
165
- try:
166
- cached = load_cached_answer(task_id)
167
- if cached:
168
- submitted_answer = cached
169
- print(f"Loaded cached answer for task {task_id}")
170
- else:
171
- submitted_answer = agent(question_text)
172
- cache_answer(task_id, submitted_answer)
173
- print(f"Generated and cached answer for task {task_id}")
174
-
175
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
176
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
177
- except Exception as e:
178
- print(f"Error running agent on task {task_id}: {e}")
179
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
180
-
181
- if not answers_payload:
182
- print("Agent did not produce any answers to submit.")
183
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
184
-
185
- # 4. Prepare Submission
186
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
187
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
188
- print(status_update)
189
-
190
- # 5. Submit
191
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
192
- try:
193
- response = requests.post(submit_url, json=submission_data, timeout=60)
194
- response.raise_for_status()
195
- result_data = response.json()
196
- final_status = (
197
- f"Submission Successful!\n"
198
- f"User: {result_data.get('username')}\n"
199
- f"Overall Score: {result_data.get('score', 'N/A')}% "
200
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
201
- f"Message: {result_data.get('message', 'No message received.')}"
202
- )
203
- print("Submission successful.")
204
- results_df = pd.DataFrame(results_log)
205
- return final_status, results_df
206
- except requests.exceptions.HTTPError as e:
207
- error_detail = f"Server responded with status {e.response.status_code}."
208
- try:
209
- error_json = e.response.json()
210
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
211
- except requests.exceptions.JSONDecodeError:
212
- error_detail += f" Response: {e.response.text[:500]}"
213
- status_message = f"Submission Failed: {error_detail}"
214
- print(status_message)
215
- results_df = pd.DataFrame(results_log)
216
- return status_message, results_df
217
- except requests.exceptions.Timeout:
218
- status_message = "Submission Failed: The request timed out."
219
- print(status_message)
220
- results_df = pd.DataFrame(results_log)
221
- return status_message, results_df
222
- except requests.exceptions.RequestException as e:
223
- status_message = f"Submission Failed: Network error - {e}"
224
- print(status_message)
225
- results_df = pd.DataFrame(results_log)
226
- return status_message, results_df
227
- except Exception as e:
228
- status_message = f"An unexpected error occurred during submission: {e}"
229
- print(status_message)
230
- results_df = pd.DataFrame(results_log)
231
- return status_message, results_df
232
-
233
-
234
- # --- Build Gradio Interface using Blocks ---
235
- with gr.Blocks() as demo:
236
- gr.Markdown("# Basic Agent Evaluation Runner")
237
- gr.Markdown(
238
- """
239
- **Instructions:**
240
-
241
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
242
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
243
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
244
-
245
- ---
246
- **Disclaimers:**
247
- 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).
248
- 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.
249
- """
250
- )
251
-
252
- gr.LoginButton()
253
-
254
- run_button = gr.Button("Run Evaluation & Submit All Answers")
255
-
256
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
257
- # Removed max_rows=10 from DataFrame constructor
258
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
259
-
260
- run_button.click(
261
- fn=run_and_submit_all,
262
- outputs=[status_output, results_table]
263
- )
264
-
265
- if __name__ == "__main__":
266
- print("\n" + "-" * 30 + " App Starting " + "-" * 30)
267
- # Check for SPACE_HOST and SPACE_ID at startup for information
268
- space_host_startup = os.getenv("SPACE_HOST")
269
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
270
-
271
- if space_host_startup:
272
- print(f"✅ SPACE_HOST found: {space_host_startup}")
273
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
274
- else:
275
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
276
-
277
- if space_id_startup: # Print repo URLs if SPACE_ID is found
278
- print(f"✅ SPACE_ID found: {space_id_startup}")
279
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
280
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
281
- else:
282
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
283
-
284
- print("-" * (60 + len(" App Starting ")) + "\n")
285
-
286
- print("Launching Gradio Interface for Basic Agent Evaluation...")
287
- demo.launch(debug=True, share=False)
 
1
+ import os
2
+ import gradio as gr
3
+ import requests
4
+ import inspect
5
+ import pandas as pd
6
+ from smolagents import DuckDuckGoSearchTool, HfApiModel, PythonInterpreterTool, VisitWebpageTool, CodeAgent
7
+ import hashlib
8
+ import json
9
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline, TransformersEngine
10
+ import wikipedia
11
+ import torch
12
+ from tooling import MathModelQuerer, WikipediaPageFetcher, YoutubeTranscriptFetcher, CodeModelQuerer
13
+
14
+ # (Keep Constants as is)
15
+ # --- Constants ---
16
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
17
+
18
+ # --- Basic Agent Definition ---
19
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
20
+ import os
21
+
22
+ cache = {}
23
+
24
+ web_search = DuckDuckGoSearchTool()
25
+ python_interpreter = PythonInterpreterTool()
26
+ visit_webpage_tool = VisitWebpageTool()
27
+ wiki_tool = WikipediaPageFetcher()
28
+ yt_transcript_fetcher = YoutubeTranscriptFetcher()
29
+ math_model_querer = MathModelQuerer()
30
+ code_model_querer = CodeModelQuerer()
31
+
32
+
33
+ def load_cached_answer(question_id: str) -> str:
34
+ if question_id in cache.keys():
35
+ return cache[question_id]
36
+ else:
37
+ return None
38
+
39
+
40
+ def cache_answer(question_id: str, answer: str):
41
+ cache[question_id] = answer
42
+
43
+
44
+ # --- Model Setup ---
45
+ MODEL_NAME = 'Qwen/Qwen2.5-3B-Instruct' # 'meta-llama/Llama-3.2-3B-Instruct'
46
+
47
+
48
+ # "Qwen/Qwen2.5-VL-3B-Instruct"#'meta-llama/Llama-2-7b-hf'#'meta-llama/Llama-3.1-8B-Instruct'#'TinyLlama/TinyLlama-1.1B-Chat-v1.0'#'mistralai/Mistral-7B-Instruct-v0.2'#'microsoft/DialoGPT-small'# 'EleutherAI/gpt-neo-2.7B'#'distilbert/distilgpt2'#'deepseek-ai/DeepSeek-R1-Distill-Qwen-7B'#'mistralai/Mistral-7B-Instruct-v0.2'
49
+
50
+
51
+ def load_model(model_name):
52
+ """Download and load the model and tokenizer."""
53
+ try:
54
+ print(f"Loading model {MODEL_NAME}...")
55
+ model = AutoModelForCausalLM.from_pretrained(MODEL_NAME)
56
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
57
+
58
+ if tokenizer.pad_token is None:
59
+ tokenizer.pad_token = tokenizer.eos_token
60
+
61
+ print(f"Model {MODEL_NAME} loaded successfully.")
62
+
63
+ transformers_engine = TransformersEngine(pipeline("text-generation", model=model, tokenizer=tokenizer))
64
+
65
+ return transformers_engine, model
66
+ except Exception as e:
67
+ print(f"Error loading model: {e}")
68
+ raise
69
+
70
+
71
+ # Load the model and tokenizer locally
72
+ # model, tokenizer = load_model()
73
+ model = HfApiModel() # model_id=MODEL_NAME, max_tokens=512)
74
+ model_id = "mistralai/Mistral-Small-3.1-24B-Instruct-2503" # "microsoft/phi-2"# not working out of the box"google/gemma-2-2b-it" #toobig"Qwen/Qwen1.5-7B-Chat"#working but stupid: "meta-llama/Llama-3.2-3B-Instruct"
75
+ model = HfApiModel(model_id)
76
+ #from smolagents import TransformersModel
77
+ # model = TransformersModel(
78
+ # model_id=model_id,
79
+ # max_new_tokens=256)
80
+
81
+ # model = HfApiModel()
82
+
83
+
84
+ class BasicAgent:
85
+ def __init__(self):
86
+ print("BasicAgent initialized.")
87
+ self.agent = CodeAgent(
88
+ model=model,
89
+ tools=[web_search, python_interpreter, visit_webpage_tool, wiki_tool, code_model_querer, math_model_querer],
90
+ max_steps=3,
91
+ verbosity_level=1,
92
+ grammar=None,
93
+ planning_interval=3,
94
+ add_base_tools=True,
95
+ additional_authorized_imports=['requests', 'wikipedia', 'pandas']
96
+
97
+ )
98
+
99
+ def __call__(self, question: str) -> str:
100
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
101
+ answer = self.agent.run(question)
102
+ return answer
103
+
104
+
105
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
106
+ """
107
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
108
+ and displays the results.
109
+ """
110
+ # --- Determine HF Space Runtime URL and Repo URL ---
111
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
112
+
113
+ if profile:
114
+ username = f"{profile.username}"
115
+ print(f"User logged in: {username}")
116
+ else:
117
+ print("User not logged in.")
118
+ return "Please Login to Hugging Face with the button.", None
119
+
120
+ api_url = DEFAULT_API_URL
121
+ questions_url = f"{api_url}/questions"
122
+ submit_url = f"{api_url}/submit"
123
+
124
+ # 1. Instantiate Agent ( modify this part to create your agent)
125
+ try:
126
+ agent = BasicAgent()
127
+ except Exception as e:
128
+ print(f"Error instantiating agent: {e}")
129
+ return f"Error initializing agent: {e}", None
130
+ # 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)
131
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
132
+ print(agent_code)
133
+
134
+ # 2. Fetch Questions
135
+ print(f"Fetching questions from: {questions_url}")
136
+ try:
137
+ response = requests.get(questions_url, timeout=15)
138
+ response.raise_for_status()
139
+ questions_data = response.json()
140
+ if not questions_data:
141
+ print("Fetched questions list is empty.")
142
+ return "Fetched questions list is empty or invalid format.", None
143
+ print(f"Fetched {len(questions_data)} questions.")
144
+ except requests.exceptions.RequestException as e:
145
+ print(f"Error fetching questions: {e}")
146
+ return f"Error fetching questions: {e}", None
147
+ except requests.exceptions.JSONDecodeError as e:
148
+ print(f"Error decoding JSON response from questions endpoint: {e}")
149
+ print(f"Response text: {response.text[:500]}")
150
+ return f"Error decoding server response for questions: {e}", None
151
+ except Exception as e:
152
+ print(f"An unexpected error occurred fetching questions: {e}")
153
+ return f"An unexpected error occurred fetching questions: {e}", None
154
+
155
+ # 3. Run your Agent
156
+ results_log = []
157
+ answers_payload = []
158
+ print(f"Running agent on {len(questions_data)} questions...")
159
+ for item in questions_data[:1]:
160
+ task_id = item.get("task_id")
161
+ question_text = item.get("question")
162
+ if not task_id or question_text is None:
163
+ print(f"Skipping item with missing task_id or question: {item}")
164
+ continue
165
+ try:
166
+ cached = load_cached_answer(task_id)
167
+ if cached:
168
+ submitted_answer = cached
169
+ print(f"Loaded cached answer for task {task_id}")
170
+ else:
171
+ submitted_answer = agent(question_text)
172
+ cache_answer(task_id, submitted_answer)
173
+ print(f"Generated and cached answer for task {task_id}")
174
+
175
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
176
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
177
+ except Exception as e:
178
+ print(f"Error running agent on task {task_id}: {e}")
179
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
180
+
181
+ if not answers_payload:
182
+ print("Agent did not produce any answers to submit.")
183
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
184
+
185
+ # 4. Prepare Submission
186
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
187
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
188
+ print(status_update)
189
+
190
+ # 5. Submit
191
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
192
+ try:
193
+ response = requests.post(submit_url, json=submission_data, timeout=60)
194
+ response.raise_for_status()
195
+ result_data = response.json()
196
+ final_status = (
197
+ f"Submission Successful!\n"
198
+ f"User: {result_data.get('username')}\n"
199
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
200
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
201
+ f"Message: {result_data.get('message', 'No message received.')}"
202
+ )
203
+ print("Submission successful.")
204
+ results_df = pd.DataFrame(results_log)
205
+ return final_status, results_df
206
+ except requests.exceptions.HTTPError as e:
207
+ error_detail = f"Server responded with status {e.response.status_code}."
208
+ try:
209
+ error_json = e.response.json()
210
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
211
+ except requests.exceptions.JSONDecodeError:
212
+ error_detail += f" Response: {e.response.text[:500]}"
213
+ status_message = f"Submission Failed: {error_detail}"
214
+ print(status_message)
215
+ results_df = pd.DataFrame(results_log)
216
+ return status_message, results_df
217
+ except requests.exceptions.Timeout:
218
+ status_message = "Submission Failed: The request timed out."
219
+ print(status_message)
220
+ results_df = pd.DataFrame(results_log)
221
+ return status_message, results_df
222
+ except requests.exceptions.RequestException as e:
223
+ status_message = f"Submission Failed: Network error - {e}"
224
+ print(status_message)
225
+ results_df = pd.DataFrame(results_log)
226
+ return status_message, results_df
227
+ except Exception as e:
228
+ status_message = f"An unexpected error occurred during submission: {e}"
229
+ print(status_message)
230
+ results_df = pd.DataFrame(results_log)
231
+ return status_message, results_df
232
+
233
+
234
+ # --- Build Gradio Interface using Blocks ---
235
+ with gr.Blocks() as demo:
236
+ gr.Markdown("# Basic Agent Evaluation Runner")
237
+ gr.Markdown(
238
+ """
239
+ **Instructions:**
240
+
241
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
242
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
243
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
244
+
245
+ ---
246
+ **Disclaimers:**
247
+ 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).
248
+ 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.
249
+ """
250
+ )
251
+
252
+ gr.LoginButton()
253
+
254
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
255
+
256
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
257
+ # Removed max_rows=10 from DataFrame constructor
258
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
259
+
260
+ run_button.click(
261
+ fn=run_and_submit_all,
262
+ outputs=[status_output, results_table]
263
+ )
264
+
265
+ if __name__ == "__main__":
266
+ print("\n" + "-" * 30 + " App Starting " + "-" * 30)
267
+ # Check for SPACE_HOST and SPACE_ID at startup for information
268
+ space_host_startup = os.getenv("SPACE_HOST")
269
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
270
+
271
+ if space_host_startup:
272
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
273
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
274
+ else:
275
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
276
+
277
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
278
+ print(f"✅ SPACE_ID found: {space_id_startup}")
279
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
280
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
281
+ else:
282
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
283
+
284
+ print("-" * (60 + len(" App Starting ")) + "\n")
285
+
286
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
287
+ demo.launch(debug=True, share=False)