Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,17 +1,142 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
|
|
|
|
|
|
| 3 |
import requests
|
| 4 |
-
import
|
|
|
|
| 5 |
import pandas as pd
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
| 11 |
-
|
| 12 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
class BasicAgent:
|
| 14 |
def __init__(self):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
print("BasicAgent initialized.")
|
| 16 |
def __call__(self, question: str) -> str:
|
| 17 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
|
@@ -19,13 +144,14 @@ class BasicAgent:
|
|
| 19 |
print(f"Agent returning fixed answer: {fixed_answer}")
|
| 20 |
return fixed_answer
|
| 21 |
|
|
|
|
| 22 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 23 |
"""
|
| 24 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 25 |
and displays the results.
|
| 26 |
"""
|
| 27 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 28 |
-
space_id = os.getenv("SPACE_ID")
|
| 29 |
|
| 30 |
if profile:
|
| 31 |
username= f"{profile.username}"
|
|
|
|
| 1 |
import os
|
| 2 |
+
import re
|
| 3 |
+
import openai
|
| 4 |
+
import pathlib
|
| 5 |
import requests
|
| 6 |
+
import tempfile
|
| 7 |
+
import gradio as gr
|
| 8 |
import pandas as pd
|
| 9 |
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from tabulate import tabulate
|
| 12 |
+
from typing import Union, Optional
|
| 13 |
+
from smolagents.tools import PipelineTool, Tool
|
| 14 |
+
from smolagents import OpenAIServerModel, DuckDuckGoSearchTool, CodeAgent, WikipediaSearchTool
|
| 15 |
+
|
| 16 |
+
|
| 17 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 18 |
|
| 19 |
+
#-------------------------------------------------
|
| 20 |
+
# TOOLS
|
| 21 |
+
#-------------------------------------------------
|
| 22 |
+
|
| 23 |
+
#SpeeachToText
|
| 24 |
+
class SpeechToTextTool(PipelineTool):
|
| 25 |
+
"""
|
| 26 |
+
Transcribes an audio file to text using the OpenAI Whisper API.
|
| 27 |
+
Only local file paths are supported.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
name = "transcriber"
|
| 31 |
+
description = (
|
| 32 |
+
"This tool sends an audio file to OpenAI Whisper and returns the "
|
| 33 |
+
"transcribed text."
|
| 34 |
+
)
|
| 35 |
+
inputs = {
|
| 36 |
+
"audio": {
|
| 37 |
+
"type": "string",
|
| 38 |
+
"description": "Absolute or relative path to a local audio file."
|
| 39 |
+
}
|
| 40 |
+
}
|
| 41 |
+
output_type = "string"
|
| 42 |
+
|
| 43 |
+
def __call__(self, audio: str) -> str:
|
| 44 |
+
"""
|
| 45 |
+
Allows the tool to be called like a regular function:
|
| 46 |
+
text = SpeechToTextTool()(path_to_audio)
|
| 47 |
+
"""
|
| 48 |
+
return self._transcribe(audio)
|
| 49 |
+
|
| 50 |
+
@staticmethod
|
| 51 |
+
def _transcribe(audio_path: str) -> str:
|
| 52 |
+
"""
|
| 53 |
+
Validates the file path and sends the audio to OpenAI Whisper API.
|
| 54 |
+
Returns the transcribed text.
|
| 55 |
+
"""
|
| 56 |
+
if not isinstance(audio_path, str):
|
| 57 |
+
raise TypeError("Parameter 'audio' must be a string with the file path.")
|
| 58 |
+
|
| 59 |
+
path = Path(audio_path).expanduser().resolve()
|
| 60 |
+
if not path.is_file():
|
| 61 |
+
raise FileNotFoundError(f"No such audio file: {path}")
|
| 62 |
+
|
| 63 |
+
with path.open("rb") as file:
|
| 64 |
+
response = openai.audio.transcriptions.create(
|
| 65 |
+
file=file,
|
| 66 |
+
model="whisper-1",
|
| 67 |
+
response_format="text"
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
return response
|
| 71 |
+
|
| 72 |
+
# ExcelToText
|
| 73 |
+
class ExcelToTextTool(Tool):
|
| 74 |
+
"""Render an Excel worksheet as Markdown text."""
|
| 75 |
+
|
| 76 |
+
name = "excel_to_text"
|
| 77 |
+
description = (
|
| 78 |
+
"Read an Excel file and return a Markdown table of the requested sheet. "
|
| 79 |
+
"Accepts either the sheet name or the zero-based index."
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
inputs = {
|
| 83 |
+
"excel_path": {
|
| 84 |
+
"type": "string",
|
| 85 |
+
"description": "Path to the Excel file (.xlsx / .xls).",
|
| 86 |
+
},
|
| 87 |
+
"sheet_name": {
|
| 88 |
+
"type": "string",
|
| 89 |
+
"description": (
|
| 90 |
+
"Worksheet name or zero‑based index *as a string* (optional; default first sheet)."
|
| 91 |
+
),
|
| 92 |
+
"nullable": True,
|
| 93 |
+
},
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
output_type = "string"
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def forward(self, excel_path: str, sheet_name: Optional[str] = None) -> str:
|
| 100 |
+
"""Load *excel_path* and return the sheet as a Markdown table."""
|
| 101 |
+
path = self._resolve_path(excel_path)
|
| 102 |
+
if not path.exists():
|
| 103 |
+
return f"Error: Excel file not found at {path}"
|
| 104 |
+
|
| 105 |
+
try:
|
| 106 |
+
sheet = self._parse_sheet_identifier(sheet_name)
|
| 107 |
+
df = pd.read_excel(path, sheet_name=sheet)
|
| 108 |
+
return self._render_dataframe(df)
|
| 109 |
+
|
| 110 |
+
except Exception as exc:
|
| 111 |
+
return f"Error reading Excel file: {exc}"
|
| 112 |
+
|
| 113 |
+
def _resolve_path(self, path_str: str) -> pathlib.Path:
|
| 114 |
+
return pathlib.Path(path_str).expanduser().resolve()
|
| 115 |
+
|
| 116 |
+
def _parse_sheet_identifier(self, name: Optional[str]) -> Union[str, int]:
|
| 117 |
+
if not name:
|
| 118 |
+
return 0
|
| 119 |
+
return int(name) if name.isdigit() else name
|
| 120 |
+
|
| 121 |
+
def _render_dataframe(self, df: pd.DataFrame) -> str:
|
| 122 |
+
if hasattr(df, "to_markdown"):
|
| 123 |
+
return df.to_markdown(index=False)
|
| 124 |
+
|
| 125 |
+
from tabulate import tabulate
|
| 126 |
+
return tabulate(df, headers="keys", tablefmt="github", showindex=False)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
#-------------------------------------------------
|
| 130 |
+
# AGENT DEFINITION
|
| 131 |
+
#-------------------------------------------------
|
| 132 |
class BasicAgent:
|
| 133 |
def __init__(self):
|
| 134 |
+
self.agent = CodeAgent(
|
| 135 |
+
model=OpenAIServerModel(model_id="gpt-4o"),
|
| 136 |
+
tools=[DuckDuckGoSearchTool(), WikipediaSearchTool(), SpeechToTextTool(), ExcelToTextTool()],
|
| 137 |
+
add_base_tools=True,
|
| 138 |
+
additional_authorized_imports=['pandas','numpy','csv','subprocess']
|
| 139 |
+
)
|
| 140 |
print("BasicAgent initialized.")
|
| 141 |
def __call__(self, question: str) -> str:
|
| 142 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
|
|
|
| 144 |
print(f"Agent returning fixed answer: {fixed_answer}")
|
| 145 |
return fixed_answer
|
| 146 |
|
| 147 |
+
|
| 148 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 149 |
"""
|
| 150 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 151 |
and displays the results.
|
| 152 |
"""
|
| 153 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 154 |
+
space_id = os.getenv("SPACE_ID")
|
| 155 |
|
| 156 |
if profile:
|
| 157 |
username= f"{profile.username}"
|