Spaces:
Sleeping
Sleeping
Download tools.py from zaizou/Final_Assignment_Template: direct link, hf CLI and curl.
- Browser
- Download file 12.9 kB
-
https://huggingface.co/spaces/zaizou/Final_Assignment_Template/resolve/main/tools.py
- Command line
-
hf download hf://spaces/zaizou/Final_Assignment_Template/tools.py
-
curl -L -o tools.py https://huggingface.co/spaces/zaizou/Final_Assignment_Template/resolve/main/tools.py
12.9 kB
| # tools.py | |
| import os | |
| import tempfile | |
| import requests | |
| import pandas as pd | |
| from pathlib import Path | |
| from typing import Optional | |
| import openai | |
| from bs4 import BeautifulSoup | |
| from smolagents import tool | |
| from smolagents.tools import Tool, PipelineTool | |
| import tempfile, os, cv2, pytesseract | |
| from pytube import YouTube | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # π§Ύ EXCEL β MARKDOWN TABLE TOOL (Class-based) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class ExcelToTextTool(Tool): | |
| name = "excel_to_markdown" | |
| description = "Convert an Excel worksheet to a Markdown table." | |
| inputs = { | |
| "excel_path": {"type": "string", "description": "Path to the Excel file"}, | |
| "sheet_name": {"type": "string", "description": "Sheet name or index (optional)", "nullable": True}, | |
| } | |
| output_type = "string" | |
| def forward(self, excel_path: str, sheet_name: Optional[str] = None) -> str: | |
| path = Path(excel_path).expanduser().resolve() | |
| if not path.exists(): | |
| return f"β File not found: {path}" | |
| try: | |
| sheet = int(sheet_name) if sheet_name and sheet_name.isdigit() else sheet_name or 0 | |
| df = pd.read_excel(path, sheet_name=sheet) | |
| if hasattr(df, "to_markdown"): | |
| return df.to_markdown(index=False) | |
| return df.to_string(index=False) | |
| except Exception as e: | |
| return f"β Excel read error: {e}" | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # π AUDIO β TEXT TOOL (Whisper via OpenAI) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class SpeechToTextTool(PipelineTool): | |
| default_checkpoint = "openai/whisper-1" | |
| name = "whisper_transcribe" | |
| description = "Transcribe local audio file to text using OpenAI Whisper." | |
| inputs = { | |
| "audio": {"type": "string", "description": "Path to an audio file"}, | |
| } | |
| output_type = "string" | |
| def __init__(self): | |
| # now you can just call super with no args | |
| super().__init__() | |
| def __call__(self, audio: str) -> str: | |
| return self._transcribe(audio) | |
| def _transcribe(audio_path: str) -> str: | |
| path = Path(audio_path).expanduser().resolve() | |
| if not path.is_file(): | |
| return f"β Audio file not found: {audio_path}" | |
| try: | |
| with path.open("rb") as fp: | |
| transcript = openai.audio.transcriptions.create( | |
| file=fp, | |
| model="whisper-1", | |
| response_format="text" | |
| ) | |
| return transcript | |
| except Exception as e: | |
| return f"β Whisper error: {e}" | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # π DOWNLOAD FILE TOOL (Decorator) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def download_file_from_url(url: str, filename: Optional[str] = None) -> str: | |
| """ | |
| Download a file from a URL and save it locally. | |
| Args: | |
| url: URL to fetch. | |
| filename: Optional desired filename; if omitted, extracted from URL. | |
| Returns: | |
| Local file path or error message. | |
| """ | |
| try: | |
| from urllib.parse import urlparse | |
| if not filename: | |
| parsed = urlparse(url).path | |
| filename = os.path.basename(parsed) or f"file_{os.urandom(4).hex()}" | |
| dest = os.path.join(tempfile.gettempdir(), filename) | |
| r = requests.get(url, stream=True, timeout=15) | |
| r.raise_for_status() | |
| with open(dest, "wb") as f: | |
| for chunk in r.iter_content(8192): | |
| f.write(chunk) | |
| return dest | |
| except Exception as e: | |
| return f"β Download error: {e}" | |
| def save_and_read_file(content: str, filename: Optional[str] = None) -> str: | |
| """ | |
| Save content to a temporary file and return the path. | |
| Useful for processing files from the GAIA API. | |
| Args: | |
| content: The content to save to the file | |
| filename: Optional filename, will generate a random name if not provided | |
| Returns: | |
| Path to the saved file | |
| """ | |
| temp_dir = tempfile.gettempdir() | |
| if filename is None: | |
| temp_file = tempfile.NamedTemporaryFile(delete=False) | |
| filepath = temp_file.name | |
| else: | |
| filepath = os.path.join(temp_dir, filename) | |
| # Write content to the file | |
| with open(filepath, 'w') as f: | |
| f.write(content) | |
| return f"File saved to {filepath}. You can read this file to process its contents." | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # π CSV ANALYZER TOOL (Decorator) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def analyze_csv_file(file_path: str, query: str) -> str: | |
| """ | |
| Load a CSV and return row/column counts, column names, and summary stats. | |
| Args: | |
| file_path: Path to CSV. | |
| query: Question context (unused, for agent reference). | |
| Returns: | |
| Text summary of the CSV. | |
| """ | |
| try: | |
| df = pd.read_csv(file_path) | |
| summary = [ | |
| f"Rows: {len(df)}, Columns: {len(df.columns)}", | |
| "Columns: " + ", ".join(df.columns), | |
| "Stats:\n" + df.describe(include="all").to_string() | |
| ] | |
| return "\n".join(summary) | |
| except Exception as e: | |
| return f"β CSV analyze error: {e}" | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # π EXCEL ANALYZER TOOL (Decorator) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def analyze_excel_file(file_path: str, query: str) -> str: | |
| """ | |
| Load an Excel file and return row/column counts, column names, and summary stats. | |
| Args: | |
| file_path: Path to Excel. | |
| query: Question context (unused). | |
| Returns: | |
| Text summary of the sheet. | |
| """ | |
| try: | |
| df = pd.read_excel(file_path) | |
| summary = [ | |
| f"Rows: {len(df)}, Columns: {len(df.columns)}", | |
| "Columns: " + ", ".join(df.columns), | |
| "Stats:\n" + df.describe(include="all").to_string() | |
| ] | |
| return "\n".join(summary) | |
| except Exception as e: | |
| return f"β Excel analyze error: {e}" | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # π WIKIPEDIA FULL PAGE FETCH TOOL (Decorator) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def wikipedia_page_fetch(title: str) -> str: | |
| """ | |
| Fetch the full HTML content of an English Wikipedia page. | |
| Args: | |
| title: Article title (spaces OK). | |
| Returns: | |
| Raw HTML or error message. | |
| """ | |
| try: | |
| slug = title.replace(" ", "_") | |
| url = f"https://en.wikipedia.org/api/rest_v1/page/html/{slug}" | |
| resp = requests.get(url, timeout=15) | |
| resp.raise_for_status() | |
| return resp.text | |
| except Exception as e: | |
| return f"β Wiki fetch error: {e}" | |
| def reverse_text(s: str) -> str: | |
| """ | |
| Reverse a string and return it for further reasoning. | |
| Args: | |
| s: The text to reverse (e.g. a backward-written sentence). | |
| Returns: | |
| The reversed string, so it reads forward. | |
| """ | |
| return s[::-1] | |
| def extract_wiki_list(html: str, section_id: str) -> list[str]: | |
| """ | |
| Given Wikipedia HTML and a section anchor (e.g. 'Studio_albums'), | |
| return the list items under that heading. | |
| Args: | |
| html: Full page HTML from wikipedia_page_fetch(...) | |
| section_id: The <span id="β¦"> anchor to look for. | |
| Returns: | |
| A Python list of the <li> texts in that section. | |
| """ | |
| soup = BeautifulSoup(html, "html.parser") | |
| header = soup.find("span", {"id": section_id}) | |
| if not header: | |
| return [] | |
| ul = header.find_next_sibling("ul") | |
| return [li.get_text(strip=True) for li in ul.find_all("li")] | |
| def highest_ocr_number_in_video(video_path: str) -> int: | |
| """ | |
| Extract all integer tokens from every frame of a video and return the highest one found. | |
| Args: | |
| video_path: Path to the local video file. | |
| Returns: | |
| The largest integer recognized via OCR in the video, or 0 if no digits are found. | |
| """ | |
| cap = cv2.VideoCapture(video_path) | |
| max_num = 0 | |
| while True: | |
| ret, frame = cap.read() | |
| if not ret: break | |
| text = pytesseract.image_to_string(frame, config="--psm 6 digits") | |
| for token in text.split(): | |
| if token.isdigit(): | |
| max_num = max(max_num, int(token)) | |
| cap.release() | |
| return max_num | |
| def extract_text_from_image(image_path: str) -> str: | |
| """ | |
| Extract text from an image using pytesseract (if available). | |
| Args: | |
| image_path: Path to the image file | |
| Returns: | |
| Extracted text or error message | |
| """ | |
| try: | |
| # Try to import pytesseract | |
| import pytesseract | |
| from PIL import Image | |
| # Open the image | |
| image = Image.open(image_path) | |
| # Extract text | |
| text = pytesseract.image_to_string(image) | |
| return f"Extracted text from image:\n\n{text}" | |
| except ImportError: | |
| return "Error: pytesseract is not installed. Please install it with 'pip install pytesseract' and ensure Tesseract OCR is installed on your system." | |
| except Exception as e: | |
| return f"Error extracting text from image: {str(e)}" | |
| def download_youtube_audio(url: str) -> str: | |
| """ | |
| Download the audio from a YouTube video and save it locally as an MP4 file. | |
| Args: | |
| url: YouTube video URL. | |
| Returns: | |
| Path to the downloaded audio file. | |
| """ | |
| try: | |
| from pytube import YouTube | |
| yt = YouTube(url) | |
| audio_stream = yt.streams.filter(only_audio=True).first() | |
| if not audio_stream: | |
| return "β No audio stream found." | |
| temp_dir = tempfile.gettempdir() | |
| safe_title = yt.title.replace(" ", "_").replace("/", "_")[:50] # Avoid long names | |
| audio_path = os.path.join(temp_dir, f"{safe_title}.mp4") | |
| audio_stream.download(filename=audio_path) | |
| return audio_path | |
| except Exception as e: | |
| return f"β Error downloading YouTube audio: {e}" | |
| def extract_audio_from_video(video_path: str) -> str: | |
| """ | |
| Extract audio from a video file and save it as a WAV file. | |
| Args: | |
| video_path: Path to the input video file. | |
| Returns: | |
| Path to the extracted WAV audio file. | |
| """ | |
| try: | |
| from moviepy import VideoFileClip | |
| clip = VideoFileClip(video_path) | |
| audio_path = video_path.rsplit(".", 1)[0] + ".wav" | |
| clip.audio.write_audiofile(audio_path, codec='pcm_s16le') | |
| return audio_path | |
| except Exception as e: | |
| return f"β Error extracting audio: {e}" | |
| def final_answer(input_text: str) -> str: | |
| """ | |
| Return the final answer to conclude the task. | |
| Args: | |
| input_text: The final answer text to submit. | |
| Returns: | |
| The final answer as a plain string. | |
| """ | |
| return input_text | |