keenthinker commited on
Commit
f948384
·
verified ·
1 Parent(s): 3da9738

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +629 -0
app.py ADDED
@@ -0,0 +1,629 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import requests
4
+ import pandas as pd
5
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIServerModel, Tool, PythonInterpreterTool
6
+ import os
7
+ import re
8
+ import requests
9
+ import pandas as pd
10
+ from youtube_transcript_api import YouTubeTranscriptApi
11
+ import whisper
12
+ from SPARQLWrapper import SPARQLWrapper, JSON
13
+ import chess
14
+ import chess.engine
15
+ import shutil
16
+ import traceback
17
+ # --- Constants ---
18
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
19
+ class YouTubeTranscriptTool(Tool):
20
+ name = "youtube_transcript"
21
+ description = (
22
+ "Fetches the transcript of a YouTube video given its URL or ID.\n"
23
+ "Returns plain text (no timestamps) or raw with timestamps."
24
+ )
25
+ inputs = {
26
+ "video_url": {"type": "string", "description": "YouTube URL or video ID."},
27
+ "raw": {"type": "boolean", "description": "Include timestamps?", "nullable": True}
28
+ }
29
+ output_type = "string"
30
+
31
+ def forward(self, video_url: str, raw: bool = False) -> str:
32
+ # Extract video ID
33
+ video_id = video_url.strip().split("?v=")[-1]
34
+ transcript = YouTubeTranscriptApi.get_transcript(video_id)
35
+ if raw:
36
+ return "\n".join(f"{int(e['start'])}s: {e['text']}" for e in transcript)
37
+ return " ".join(e['text'] for e in transcript)
38
+
39
+
40
+ class SpeechToTextTool(Tool):
41
+ name = "speech_to_text"
42
+ description = (
43
+ "Converts an audio file to text using OpenAI Whisper."
44
+ )
45
+ inputs = {
46
+ "audio_path": {"type": "string", "description": "Path to audio file (.mp3, .wav)"},
47
+ }
48
+ output_type = "string"
49
+
50
+ def __init__(self):
51
+ super().__init__()
52
+ self.model = whisper.load_model("base")
53
+
54
+ def forward(self, audio_path: str) -> str:
55
+ if not os.path.exists(audio_path):
56
+ return f"Error: File not found at {audio_path}"
57
+ result = self.model.transcribe(audio_path)
58
+ return result.get("text", "")
59
+
60
+ class WikidataQueryTool(Tool):
61
+ name = "wikidata_query"
62
+ description = (
63
+ "Runs SPARQL queries on Wikidata and returns JSON results."
64
+ )
65
+ inputs = {
66
+ "query": {"type": "string", "description": "The SPARQL query to execute."}
67
+ }
68
+ output_type = "dict"
69
+
70
+ def forward(self, query: str) -> dict:
71
+ sparql = SPARQLWrapper("https://query.wikidata.org/sparql")
72
+ sparql.setQuery(query)
73
+ sparql.setReturnFormat(JSON)
74
+ results = sparql.query().convert()
75
+ return results
76
+
77
+
78
+ class WikipediaAPIExtractor(Tool):
79
+ name = "wikipedia_api"
80
+ description = (
81
+ "Fetches and parses a Wikipedia page's sections as structured JSON."
82
+ )
83
+ inputs = {
84
+ "page_title": {"type": "string", "description": "Title of the Wikipedia page."}
85
+ }
86
+ output_type = "dict"
87
+
88
+ def forward(self, page_title: str) -> dict:
89
+ api_url = (
90
+ f"https://en.wikipedia.org/api/rest_v1/page/mobile-sections/{page_title}"
91
+ )
92
+ resp = requests.get(api_url)
93
+ resp.raise_for_status()
94
+ data = resp.json()
95
+ # merge lead with sections without requiring Python 3.9's dict union
96
+ lead = data.get("lead", {})
97
+ sections = data.get("remaining", {}).get("sections", [])
98
+ return {**lead, "sections": sections}
99
+
100
+ class TableParseTool(Tool):
101
+ name = "table_parse"
102
+ description = (
103
+ "Parses an ASCII or markdown table (or image) into a pandas DataFrame."
104
+ )
105
+ inputs = {
106
+ "table_text": {"type": "string", "description": "The raw table string."}
107
+ }
108
+ output_type = "pandas.DataFrame"
109
+
110
+ def forward(self, table_text: str) -> pd.DataFrame:
111
+ # Leveraging pandas read_csv on StringIO with markdown separators
112
+ from io import StringIO
113
+ # Clean pipes and extra spaces
114
+ clean = re.sub(r"^\||\|$", "", table_text.strip(), flags=re.MULTILINE)
115
+ return pd.read_csv(StringIO(clean), sep=r"\s*\|\s*", engine="python")
116
+
117
+ class ChessEngineTool(Tool):
118
+ name = "chess_engine"
119
+ description = "Analyzes a chess position (FEN) with Stockfish and returns the best move."
120
+ inputs = {
121
+ "fen": {"type": "string", "description": "FEN string of the position."},
122
+ "time_limit": {"type": "number", "description": "Time in seconds for engine analysis.", "nullable": True}
123
+ }
124
+ output_type = "string"
125
+
126
+ def forward(self, fen: str, time_limit: float = 0.1) -> str:
127
+ # figure out where the binary actually is
128
+ sf_bin = shutil.which("stockfish") or "/usr/games/stockfish"
129
+ if not sf_bin:
130
+ raise RuntimeError(
131
+ f"Cannot find stockfish on PATH or at /usr/games/stockfish. "
132
+ "Did you install it in apt.txt or via apt-get?"
133
+ )
134
+
135
+ board = chess.Board(fen)
136
+ engine = chess.engine.SimpleEngine.popen_uci(sf_bin)
137
+ result = engine.play(board, chess.engine.Limit(time=time_limit))
138
+ engine.quit()
139
+ return board.san(result.move)
140
+
141
+ class RegexTool(Tool):
142
+ name = "regex"
143
+ description = (
144
+ "Performs regex search and replace on an input string."
145
+ )
146
+ inputs = {
147
+ "text": {"type": "string", "description": "Input text."},
148
+ "pattern": {"type": "string", "description": "Regex pattern."},
149
+ "replacement": {"type": "string", "description": "Replacement string."}
150
+ }
151
+ output_type = "string"
152
+
153
+ def forward(self, text: str, pattern: str, replacement: str) -> str:
154
+ return re.sub(pattern, replacement, text)
155
+
156
+
157
+ class MathSolverTool(Tool):
158
+ name = "math_solver"
159
+ description = (
160
+ "Solves arithmetic or symbolic expressions via sympy or numpy."
161
+ )
162
+ inputs = {
163
+ "expression": {"type": "string", "description": "Math expression to solve."}
164
+ }
165
+ output_type = "string"
166
+
167
+ def forward(self, expression: str) -> str:
168
+ try:
169
+ import sympy as sp
170
+ expr = sp.sympify(expression)
171
+ solution = sp.solve(expr)
172
+ return str(solution)
173
+ except Exception:
174
+ try:
175
+ result = eval(expression, {"__builtins__": None}, {})
176
+ return str(result)
177
+ except Exception as e:
178
+ return f"Error evaluating expression: {e}"
179
+
180
+ # Custom file reading tool
181
+ class FileReadTool(Tool):
182
+ name = "file_reader"
183
+ description = """
184
+ This tool reads the content of text files.
185
+ It's useful for processing plain text files (.txt, .csv, .json, etc).
186
+ """
187
+ inputs = {
188
+ "file_path": {
189
+ "type": "string",
190
+ "description": "The path to the file to read",
191
+ }
192
+ }
193
+ output_type = "string"
194
+
195
+ def forward(self, file_path: str) -> str:
196
+ """
197
+ Reads the content of the given file.
198
+ """
199
+ try:
200
+ # Check if the file exists
201
+ if not os.path.exists(file_path):
202
+ return f"Error: File not found at {file_path}"
203
+
204
+ # Read the file
205
+ with open(file_path, 'r', encoding='utf-8') as file:
206
+ content = file.read()
207
+
208
+ # If the content is too long, truncate it
209
+ if len(content) > 10000:
210
+ content = content[:10000] + "...\n[Text truncated due to length]"
211
+
212
+ return content or "File is empty."
213
+
214
+ except Exception as e:
215
+ return f"Error reading file: {str(e)}"
216
+
217
+ class PDFReaderTool(Tool):
218
+ name = "pdf_reader"
219
+ description = """
220
+ This tool extracts text content from PDF files.
221
+ It's useful for reading research papers, reports, or other document types.
222
+ """
223
+ inputs = {
224
+ "pdf_path": {
225
+ "type": "string",
226
+ "description": "The path to the PDF file to read",
227
+ }
228
+ }
229
+ output_type = "string"
230
+
231
+ def forward(self, pdf_path: str) -> str:
232
+ """
233
+ Extracts text from the given PDF file.
234
+ """
235
+ try:
236
+ # Check if the file exists
237
+ if not os.path.exists(pdf_path):
238
+ return f"Error: PDF file not found at {pdf_path}"
239
+
240
+ import PyPDF2
241
+
242
+ # Open the PDF file
243
+ with open(pdf_path, 'rb') as file:
244
+ # Create a PDF reader object
245
+ pdf_reader = PyPDF2.PdfReader(file)
246
+
247
+ # Get the number of pages
248
+ num_pages = len(pdf_reader.pages)
249
+
250
+ # Extract text from all pages
251
+ text = ""
252
+ for page_num in range(num_pages):
253
+ page = pdf_reader.pages[page_num]
254
+ text += page.extract_text() + "\n\n"
255
+
256
+ # If the text is too long, truncate it
257
+ if len(text) > 10000:
258
+ text = text[:10000] + "...\n[Text truncated due to length]"
259
+
260
+ return text or "No text could be extracted from the PDF."
261
+
262
+ except Exception as e:
263
+ return f"Error reading PDF: {str(e)}"
264
+
265
+ class ExcelReaderTool(Tool):
266
+ name = "excel_reader"
267
+ description = """
268
+ This tool reads and processes Excel files (.xlsx, .xls).
269
+ It can extract data, calculate statistics, and perform data analysis on spreadsheets.
270
+ """
271
+ inputs = {
272
+ "excel_path": {
273
+ "type": "string",
274
+ "description": "The path to the Excel file to read",
275
+ },
276
+ "sheet_name": {
277
+ "type": "string",
278
+ "description": "The name of the sheet to read (optional, defaults to first sheet)",
279
+ "nullable": True
280
+ }
281
+ }
282
+ output_type = "string"
283
+
284
+ def forward(self, excel_path: str, sheet_name: str = None) -> str:
285
+ """
286
+ Reads and processes the given Excel file.
287
+ """
288
+ try:
289
+ # Check if the file exists
290
+ if not os.path.exists(excel_path):
291
+ return f"Error: Excel file not found at {excel_path}"
292
+
293
+ import pandas as pd
294
+
295
+ # Read the Excel file
296
+ if sheet_name:
297
+ df = pd.read_excel(excel_path, sheet_name=sheet_name)
298
+ else:
299
+ df = pd.read_excel(excel_path)
300
+
301
+ # Get basic info about the data
302
+ info = {
303
+ "shape": df.shape,
304
+ "columns": list(df.columns),
305
+ "dtypes": df.dtypes.to_dict(),
306
+ "head": df.head(5).to_dict()
307
+ }
308
+
309
+ # Return formatted info
310
+ result = f"Excel file: {excel_path}\n"
311
+ result += f"Shape: {info['shape'][0]} rows × {info['shape'][1]} columns\n\n"
312
+ result += "Columns:\n"
313
+ for col in info['columns']:
314
+ result += f"- {col} ({info['dtypes'].get(col)})\n"
315
+
316
+ result += "\nPreview (first 5 rows):\n"
317
+ result += df.head(5).to_string()
318
+
319
+ return result
320
+
321
+ except Exception as e:
322
+ return f"Error reading Excel file: {str(e)}"
323
+
324
+ class ImageAnalysisTool(Tool):
325
+ name = "image_analysis"
326
+ description = """
327
+ This tool analyzes an image and extracts relevant information from it.
328
+ It can describe image content, extract text from images, identify objects, etc.
329
+ """
330
+ inputs = {
331
+ "image_path": {
332
+ "type": "string",
333
+ "description": "The path to the image file to analyze",
334
+ }
335
+ }
336
+ output_type = "string"
337
+
338
+ def forward(self, image_path: str) -> str:
339
+ """
340
+ Analyzes the given image and returns relevant information using OpenAI's ChatGPT API.
341
+ """
342
+ try:
343
+ # Check if the file exists
344
+ if not os.path.exists(image_path):
345
+ return f"Error: Image file not found at {image_path}"
346
+
347
+ import requests
348
+ import base64
349
+ import json
350
+ from PIL import Image
351
+
352
+ # Load the image
353
+ with open(image_path, "rb") as image_file:
354
+ image_bytes = image_file.read()
355
+
356
+ # Convert to base64 for OpenAI API
357
+ encoded_image = base64.b64encode(image_bytes).decode('utf-8')
358
+
359
+ # Get API key from environment
360
+ api_key = os.getenv('OPENAI_KEY', '')
361
+ if not api_key:
362
+ return "OpenAI API key not configured. Please add the OPENAI_API_KEY to your environment variables."
363
+
364
+ # Prepare the API request for ChatGPT with vision capabilities
365
+ api_url = "https://api.openai.com/v1/chat/completions"
366
+ headers = {
367
+ "Content-Type": "application/json",
368
+ "Authorization": f"Bearer {api_key}"
369
+ }
370
+
371
+ payload = {
372
+ "model": "gpt-4o-mini-2024-07-18", # Vision-capable model
373
+ "messages": [
374
+ {
375
+ "role": "user",
376
+ "content": [
377
+ {
378
+ "type": "text",
379
+ "text": "Analyze this image in detail. Describe what you see, including main subjects, activities, background elements, colors, and any text visible in the image. If there's text in the image, please extract it."
380
+ },
381
+ {
382
+ "type": "image_url",
383
+ "image_url": {
384
+ "url": f"data:image/jpeg;base64,{encoded_image}"
385
+ }
386
+ }
387
+ ]
388
+ }
389
+ ],
390
+ "max_tokens": 500
391
+ }
392
+
393
+ response = requests.post(
394
+ api_url,
395
+ headers=headers,
396
+ json=payload
397
+ )
398
+
399
+ if response.status_code != 200:
400
+ return f"Error: OpenAI API returned status code {response.status_code}. Details: {response.text}"
401
+
402
+ result = response.json()
403
+
404
+ # Extract the response content
405
+ if "choices" in result and len(result["choices"]) > 0:
406
+ analysis = result["choices"][0]["message"]["content"]
407
+ return f"Image analysis result: {analysis}"
408
+ else:
409
+ return f"Error: Unexpected response format from OpenAI API: {result}"
410
+
411
+ except Exception as e:
412
+ return f"Error analyzing image: {str(e)}"
413
+
414
+ # --- Basic Agent Definition ---
415
+ class BasicAgent:
416
+ def __init__(self):
417
+ print("BasicAgent initialized.")
418
+ # Initialize the model
419
+ model = OpenAIServerModel(model_id="gpt-4o-mini-2024-07-18")
420
+
421
+ # Initialize tools
422
+ self.tools = [
423
+ YouTubeTranscriptTool(),
424
+ SpeechToTextTool(),
425
+ ChessEngineTool(),
426
+
427
+ DuckDuckGoSearchTool(), # Built-in web search tool
428
+ FileReadTool(), # Custom file reader
429
+ PDFReaderTool(), # PDF reader
430
+ ExcelReaderTool(), # Excel reader
431
+ ImageAnalysisTool(), # Image analysis
432
+ # Code execution
433
+ ]
434
+
435
+ # Initialize Agent
436
+ self.agent = CodeAgent(
437
+ model=model,
438
+ tools=self.tools,
439
+ add_base_tools=True, # Add basic tools like math
440
+ )
441
+
442
+ def __call__(self, question: str) -> str:
443
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
444
+ try:
445
+ answer = self.agent.run(question)
446
+ print(f"Agent returned answer (first 50 chars): {answer[:50]}...")
447
+ return answer
448
+ except Exception as e:
449
+ print(traceback.format_exc())
450
+ error_msg = f"Error running agent: {str(e)}"
451
+ print(error_msg)
452
+ return f"I encountered an issue while processing your question: {str(e)}"
453
+
454
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
455
+ """
456
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
457
+ and displays the results.
458
+ """
459
+ # --- Determine HF Space Runtime URL and Repo URL ---
460
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
461
+
462
+ if profile:
463
+ username = f"{profile.username}"
464
+ print(f"User logged in: {username}")
465
+ else:
466
+ print("User not logged in.")
467
+ return "Please Login to Hugging Face with the button.", None
468
+
469
+ api_url = DEFAULT_API_URL
470
+ questions_url = f"{api_url}/questions"
471
+ submit_url = f"{api_url}/submit"
472
+
473
+ # 1. Instantiate Agent
474
+ try:
475
+ agent = BasicAgent()
476
+ except Exception as e:
477
+ print(f"Error instantiating agent: {e}")
478
+ return f"Error initializing agent: {e}", None
479
+
480
+ # In the case of an app running as a Hugging Face space, this link points toward your codebase
481
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
482
+ print(agent_code)
483
+
484
+ # 2. Fetch Questions
485
+ print(f"Fetching questions from: {questions_url}")
486
+ try:
487
+ response = requests.get(questions_url, timeout=15)
488
+ response.raise_for_status()
489
+ questions_data = response.json()
490
+ if not questions_data:
491
+ print("Fetched questions list is empty.")
492
+ return "Fetched questions list is empty or invalid format.", None
493
+ print(f"Fetched {len(questions_data)} questions.")
494
+ except requests.exceptions.RequestException as e:
495
+ print(f"Error fetching questions: {e}")
496
+ return f"Error fetching questions: {e}", None
497
+ except requests.exceptions.JSONDecodeError as e:
498
+ print(f"Error decoding JSON response from questions endpoint: {e}")
499
+ print(f"Response text: {response.text[:500]}")
500
+ return f"Error decoding server response for questions: {e}", None
501
+ except Exception as e:
502
+ print(f"An unexpected error occurred fetching questions: {e}")
503
+ return f"An unexpected error occurred fetching questions: {e}", None
504
+
505
+ # 3. Run your Agent
506
+ results_log = []
507
+ answers_payload = []
508
+ print(f"Running agent on {len(questions_data)} questions...")
509
+ for item in questions_data:
510
+ task_id = item.get("task_id")
511
+ question_text = item.get("question")
512
+ if not task_id or question_text is None:
513
+ print(f"Skipping item with missing task_id or question: {item}")
514
+ continue
515
+ try:
516
+ print(f"Processing task {task_id}: {question_text[:50]}...")
517
+ submitted_answer = agent(question_text)
518
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
519
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
520
+ print(f"Completed task {task_id}")
521
+ except Exception as e:
522
+ print(f"Error running agent on task {task_id}: {e}")
523
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
524
+
525
+ if not answers_payload:
526
+ print("Agent did not produce any answers to submit.")
527
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
528
+
529
+ # 4. Prepare Submission
530
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
531
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
532
+ print(status_update)
533
+
534
+ # 5. Submit
535
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
536
+ try:
537
+ response = requests.post(submit_url, json=submission_data, timeout=60)
538
+ response.raise_for_status()
539
+ result_data = response.json()
540
+ final_status = (
541
+ f"Submission Successful!\n"
542
+ f"User: {result_data.get('username')}\n"
543
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
544
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
545
+ f"Message: {result_data.get('message', 'No message received.')}"
546
+ )
547
+ print("Submission successful.")
548
+ results_df = pd.DataFrame(results_log)
549
+ return final_status, results_df
550
+ except requests.exceptions.HTTPError as e:
551
+ error_detail = f"Server responded with status {e.response.status_code}."
552
+ try:
553
+ error_json = e.response.json()
554
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
555
+ except requests.exceptions.JSONDecodeError:
556
+ error_detail += f" Response: {e.response.text[:500]}"
557
+ status_message = f"Submission Failed: {error_detail}"
558
+ print(status_message)
559
+ results_df = pd.DataFrame(results_log)
560
+ return status_message, results_df
561
+ except requests.exceptions.Timeout:
562
+ status_message = "Submission Failed: The request timed out."
563
+ print(status_message)
564
+ results_df = pd.DataFrame(results_log)
565
+ return status_message, results_df
566
+ except requests.exceptions.RequestException as e:
567
+ status_message = f"Submission Failed: Network error - {e}"
568
+ print(status_message)
569
+ results_df = pd.DataFrame(results_log)
570
+ return status_message, results_df
571
+ except Exception as e:
572
+ status_message = f"An unexpected error occurred during submission: {e}"
573
+ print(status_message)
574
+ results_df = pd.DataFrame(results_log)
575
+ return status_message, results_df
576
+
577
+
578
+ # --- Build Gradio Interface using Blocks ---
579
+ with gr.Blocks() as demo:
580
+ gr.Markdown("# Advanced Agent Evaluation Runner")
581
+ gr.Markdown(
582
+ """
583
+ **Instructions:**
584
+
585
+ 1. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
586
+ 2. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
587
+
588
+ ---
589
+ **Note:**
590
+ Once you click on the "submit" button, it may take quite some time as the agent processes all the questions.
591
+ The agent is using SmolaAgents with multiple tools including web search, file processing, and code execution.
592
+ """
593
+ )
594
+
595
+ gr.LoginButton()
596
+
597
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
598
+
599
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
600
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
601
+
602
+ run_button.click(
603
+ fn=run_and_submit_all,
604
+ outputs=[status_output, results_table]
605
+ )
606
+
607
+ if __name__ == "__main__":
608
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
609
+ # Check for SPACE_HOST and SPACE_ID at startup for information
610
+ space_host_startup = os.getenv("SPACE_HOST")
611
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
612
+
613
+ if space_host_startup:
614
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
615
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
616
+ else:
617
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
618
+
619
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
620
+ print(f"✅ SPACE_ID found: {space_id_startup}")
621
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
622
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
623
+ else:
624
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
625
+
626
+ print("-"*(60 + len(" App Starting ")) + "\n")
627
+
628
+ print("Launching Gradio Interface for Advanced Agent Evaluation...")
629
+ demo.launch(debug=True, share=False)