Spaces:
Sleeping
Sleeping
File size: 17,929 Bytes
e8579ca 3b1d4c4 5f7af35 e8579ca 5f7af35 e8579ca dfa0869 e8579ca dfa0869 e8579ca dfa0869 e8579ca dfa0869 e8579ca dfa0869 e8579ca 7bcef3d e8579ca | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 | import os
from smolagents import tool
import spaces
from dotenv import load_dotenv
# ----------------------------------------------------------------------------
# SECTION 1: Vision & Multimodal
# ----------------------------------------------------------------------------
load_dotenv()
@spaces.GPU(duration=20)
def initialize_gpu() :
return 0
@tool
def vision_tool(prompt: str, image_list: list) -> str:
"""
Analyzes one or more images using a multimodal model to answer specific questions.
It processes image content and returns the model's text-based response.
Args:
prompt: The user question or task to perform on the images.
image_list: A list of PIL Image objects to be analyzed.
"""
import io, base64, os
from smolagents import OpenAIServerModel
from PIL import Image
initialize_gpu()
model = OpenAIServerModel(
model_id='gemma4:31b-cloud',
api_base='https://ollama.com/v1',
api_key=os.getenv('GEMMA_API_KEY'),
temperature=0.0,
max_tokens=2048,
)
payload = [{"type": "text", "text": prompt}]
for img in image_list:
try:
buffered = io.BytesIO()
img.save(buffered, format="JPEG")
b64_img = base64.b64encode(buffered.getvalue()).decode("utf-8")
payload.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64_img}"}})
except Exception as e:
return f"Error processing image: {str(e)}"
return model([{"role": "user", "content": payload}]).content
# ----------------------------------------------------------------------------
# SECTION 2: YouTube Pipeline (Tout-en-un pour la robustesse)
# ----------------------------------------------------------------------------
@tool
def ask_youtube_full_pipeline(url: str, question: str) -> str:
"""
Downloads a YouTube video, extracts key frames at regular intervals, and uses a multimodal model to answer questions about the video's content.
Args:
url: The YouTube video URL to process.
question: The specific question to ask about the video content.
"""
import os, re, tempfile, yt_dlp, imageio
from PIL import Image
from smolagents import OpenAIServerModel
initialize_gpu()
# 1. Extraction ID interne
patterns = [r"v=([a-zA-Z0-9_-]{11})", r"youtu\.be/([a-zA-Z0-9_-]{11})"]
video_id = None
for pat in patterns:
match = re.search(pat, url)
if match:
video_id = match.group(1)
break
if not video_id:
return "Erreur: URL invalide."
with tempfile.TemporaryDirectory() as tmpdir:
# Configuration optimisée : légère (évite les timeouts) et robuste
ydl_opts = {
'format': 'best[ext=mp4]/best', # Récupère un fichier MP4 direct déjà fusionné
'outtmpl': os.path.join(tmpdir, 'downloaded_video.%(ext)s'),
'quiet': True,
'no_warnings': True
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.extract_info(url, download=True)
# CORRECTIF CRITIQUE : On liste le dossier pour trouver le fichier, peu importe son extension exacte
downloaded_files = os.listdir(tmpdir)
if not downloaded_files:
return "Erreur: Le téléchargement de la vidéo a échoué."
video_path = os.path.join(tmpdir, downloaded_files[0])
# Extraction des images via le chemin dynamique détecté
reader = imageio.get_reader(video_path, format='ffmpeg')
frames = [Image.fromarray(f) for i, f in enumerate(reader) if i % 60 == 0][:8]
reader.close()
# 2. Analyse VLM (Auto-contenu)
model = OpenAIServerModel(model_id='gemma4:31b-cloud', api_base='https://ollama.com/v1', api_key=os.getenv('GEMMA_API_KEY'))
import base64, io
payload = [{"type": "text", "text": question}]
for img in frames:
b = io.BytesIO()
img.save(b, format="JPEG")
payload.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64.b64encode(b.getvalue()).decode()}"}})
return model([{"role": "user", "content": payload}]).content
# ----------------------------------------------------------------------------
# SECTION 3: Fichiers & Audio
# ----------------------------------------------------------------------------
@tool
def read_pdf_file(file_path: str) -> str:
"""
Reads the content of a PDF file, extracting all visible text page by page.
Args:
file_path: The absolute or relative path to the .pdf file that needs to be read.
"""
import os
from pypdf import PdfReader
initialize_gpu()
if not os.path.exists(file_path):
return f"Erreur : Le fichier au chemin '{file_path}' est introuvable."
try:
reader = PdfReader(file_path)
full_text = []
# Parcourir et extraire le texte de chaque page
for page_num, page in enumerate(reader.pages, start=1):
page_text = page.extract_text()
if page_text and page_text.strip():
full_text.append(f"\n--- [Page {page_num}] ---")
full_text.append(page_text.strip())
output = "\n".join(full_text)
return output if output.strip() else "Le document PDF semble vide ou ne contient que des images (scan)."
except Exception as e:
return f"Erreur lors de la lecture du fichier PDF : {str(e)}"
@tool
def read_docx_file(file_path: str) -> str:
"""
Reads the content of a Word document (.docx file), extracting all text from paragraphs and tables.
Args:
file_path: The path to the .docx file that needs to be read.
"""
import docx
import os
initialize_gpu()
if not os.path.exists(file_path):
return f"Erreur : Le fichier au chemin '{file_path}' est introuvable."
try:
doc = docx.Document(file_path)
full_text = []
# 1. Extraction du texte des paragraphes classiques
for para in doc.paragraphs:
if para.text.strip():
full_text.append(para.text.strip())
# 2. Extraction du texte des tableaux (très fréquent dans GAIA)
for table in doc.tables:
full_text.append("\n--- [Tableau détecté] ---")
for row in table.rows:
row_text = [cell.text.strip() for cell in row.cells if cell.text.strip()]
if row_text:
# On sépare les colonnes par des barres verticales pour l'agent
full_text.append(" | ".join(row_text))
full_text.append("-------------------------\n")
# Renvoyer le tout proprement assemblé
output = "\n".join(full_text)
return output if output.strip() else "Le document est vide."
except Exception as e:
return f"Erreur lors de la lecture du fichier .docx : {str(e)}"
@tool
def file_from_url(url: str, save_as: str = "downloaded_file") -> str:
"""
Downloads a file from a provided URL, determines its extension properly, and saves it.
Args:
url: The source URL of the file to download.
save_as: Optional filename to save the file as. If not provided, derives the name from the URL or headers.
"""
import requests
import os
from urllib.parse import urlparse
import mimetypes
# 1. Utiliser un répertoire local dédié et contrôlé (comme ton dossier downloads)
download_dir = os.path.abspath("downloads")
os.makedirs(download_dir, exist_ok=True)
try:
with requests.get(url, stream=True, timeout=20) as r:
r.raise_for_status()
# 2. Détermination intelligente du nom et de l'extension
if save_as == "downloaded_file":
base_name = os.path.basename(urlparse(url).path)
if not base_name or "." not in base_name:
# Si l'URL est opaque, on regarde le Content-Type envoyé par le serveur
content_type = r.headers.get('content-type', '').split(';')[0]
ext = mimetypes.guess_extension(content_type) or ".txt"
base_name = f"downloaded_media_{int(os.path.getctime(download_dir))}{ext}"
save_as = base_name
file_path = os.path.join(download_dir, save_as)
# 3. Écriture par blocs (chunks)
with open(file_path, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
# Renvoie le chemin absolu impeccable pour tes autres sous-agents
return os.path.abspath(file_path)
except Exception as e:
return f"Erreur lors du téléchargement du fichier depuis l'URL : {str(e)}"
@tool
def transcribe_youtube(yt_url: str) -> str:
"""
Downloads the audio from a YouTube video and performs speech-to-text transcription using the Groq cloud API (Whisper).
Useful for retrieving text content or answering questions based on video dialogue without local heavy models.
Args:
yt_url: The URL of the YouTube video to transcribe.
"""
import os, tempfile, yt_dlp, requests
groq_api_key = os.getenv("GROQ_API_KEY")
if not groq_api_key:
return "Erreur : La variable d'environnement GROQ_API_KEY n'est pas configurée dans l'environnement."
with tempfile.TemporaryDirectory() as tmpdir:
# Téléchargement de l'audio uniquement
ydl_opts = {
"format": "bestaudio",
"outtmpl": os.path.join(tmpdir, "audio.%(ext)s"),
"quiet": True,
"postprocessors": [{"key": "FFmpegExtractAudio", "preferredcodec": "mp3"}]
}
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.extract_info(yt_url, download=True)
audio_path = os.path.join(tmpdir, "audio.mp3")
# Appel API Groq Cloud (Whisper Large V3)
url = "https://api.groq.com/openai/v1/audio/transcriptions"
headers = {"Authorization": f"Bearer {groq_api_key}"}
with open(audio_path, 'rb') as f:
files = {"file": f}
data = {"model": "whisper-large-v3"}
response = requests.post(url, headers=headers, files=files, data=data)
if response.status_code != 200:
return f"Erreur API Groq : {response.text}"
return response.json().get("text", "")
except Exception as e:
return f"Erreur de traitement audio / API : {str(e)}"
@tool
def read_text_file(file_path: str) -> str:
"""
Reads and returns the raw plain text content from a specified local file path.
Args:
file_path: The full local path to the text file.
"""
with open(file_path, "r", encoding="utf-8") as f: return f.read()
# ----------------------------------------------------------------------------
# SECTION 4: OCR & Tabulaire
# ----------------------------------------------------------------------------
@tool
def extract_text_via_ocr(image_path: str) -> str:
"""
Extracts text from an image using the cloud-based OCR.space API.
Returns the detected text found within the provided image path without heavy local dependencies.
Args:
image_path: The local path to the image file containing text.
"""
import requests, os
# Utilisation de la clé publique 'helloworld' d'OCR.space si aucune clé n'est configurée
api_key = os.getenv("OCR_SPACE_API_KEY", "helloworld")
try:
with open(image_path, 'rb') as f:
response = requests.post(
'https://api.ocr.space/parse/image',
files={'file': f},
data={'apikey': api_key, 'language': 'fra'}
)
result = response.json()
if result.get("IsErroredOnProcessing"):
return f"Erreur OCR.space : {result.get('ErrorMessage')}"
parsed_results = result.get('ParsedResults', [])
if not parsed_results:
return "Aucun texte détecté sur l'image."
return parsed_results[0].get('ParsedText', '')
except Exception as e:
return f"Erreur lors de l'appel API OCR : {str(e)}"
@tool
def summarize_csv_data(path: str, query: str = "") -> str:
"""
Loads a CSV file into a pandas DataFrame and generates a descriptive summary, including column statistics.
Optionally allows filtering rows via a pandas query string.
Args:
path: The local file path to the CSV file.
query: Optional pandas query expression to filter rows before summarizing (e.g., "age > 30").
"""
import pandas as pd
df = pd.read_csv(path)
if query: df = df.query(query)
return df.describe().to_string()
@tool
def calculer_probabilite_loi(loi: str, parametres: dict, valeur_k: float) -> str:
"""
Calculates the exact or cumulative probability for a specified statistical distribution law (Normal or Binomial).
Args:
loi: The distribution type, either 'normale' or 'binomiale'.
parametres: Dictionary containing distribution parameters (e.g., {'moyenne': float, 'ecart_type': float} for Normal).
valeur_k: The value or bound for which the cumulative probability P(X <= k) is calculated.
"""
# Import local obligatoire pour l'autonomie en sandbox
from scipy import stats
try:
if loi.lower() == "normale":
loc = parametres.get("moyenne", 0)
scale = parametres.get("ecart_type", 1)
prob = stats.norm.cdf(valeur_k, loc=loc, scale=scale)
return f"Pour une Loi Normale({loc}, {scale}), P(X <= {valeur_k}) = {prob:.6f}"
elif loi.lower() == "binomiale":
n = int(parametres.get("n", 1))
p = float(parametres.get("p", 0.5))
prob = stats.binom.cdf(valeur_k, n, p)
prob_exacte = stats.binom.pmf(valeur_k, n, p)
return (
f"Pour une Loi Binomiale(n={n}, p={p}) :\n"
f"- Probabilité exacte P(X = {valeur_k}) = {prob_exacte:.6f}\n"
f"- Probabilité cumulative P(X <= {valeur_k}) = {prob:.6f}"
)
else:
return "Loi non supportée. Utilisez 'normale' ou 'binomiale'."
except Exception as e:
return f"Erreur de paramètres : {str(e)}"
@tool
def summarize_excel_data(path: str, query: str = "") -> str:
"""
Loads an Excel file (.xls or .xlsx) into a pandas DataFrame and generates a descriptive summary, including column statistics.
Optionally allows filtering rows via a pandas query string.
Args:
path: The local file path to the Excel file.
query: Optional pandas query expression to filter rows before summarizing (e.g., "age > 30").
"""
import pandas as pd
df = pd.read_excel(path)
if query: df = df.query(query)
return df.describe().to_string()
@tool
def analyser_serie_statistique(donnees: list[float]) -> str:
"""
Calculates essential descriptive statistics for a provided series of numerical data, such as mean, median, standard deviation, and range.
Args:
donnees: A list of floats representing the dataset to analyze.
"""
import numpy as np
arr = np.array(donnees)
return f"Moyenne: {np.mean(arr):.2f}, Écart-type: {np.std(arr):.2f}, Min: {np.min(arr)}, Max: {np.max(arr)}"
# ----------------------------------------------------------------------------
# SECTION 5: Maths & Chess
# ----------------------------------------------------------------------------
@tool
def resoudre_calcul_formel(expression: str, action: str, variable: str = "x") -> str:
"""
Performs formal mathematical computations such as solving equations, differentiation, integration, and simplification using sympy.
Args:
expression: The mathematical expression in Python syntax (e.g., "x**2 + 2*x - 3" or "x**2 - 4 = 0").
action: The mathematical operation to perform ('resoudre', 'deriver', 'integrer', or 'simplifier').
variable: The primary variable in the expression to operate on. Defaults to 'x'.
"""
import sympy as sp
v = sp.Symbol(variable)
e = sp.sympify(expression.split("=")[0]) if "=" in expression else sp.sympify(expression)
if action == "simplifier": return str(sp.simplify(e))
if action == "deriver": return str(sp.diff(e, v))
if action == "integrer": return str(sp.integrate(e, v))
return str(sp.solve(e, v))
@tool
def analyze_chess_position(fen: str) -> str:
"""
Analyzes a chess board state from a FEN (Forsyth-Edwards Notation) string.
Detects checks, checkmates, stalemates, lists legal moves, and scans for immediate 'Mate in 1' opportunities.
Args:
fen: The FEN string representing the current board state.
"""
import chess
board = chess.Board(fen)
moves = [board.san(m) for m in board.legal_moves]
return f"Turn: {'White' if board.turn else 'Black'}. Moves: {', '.join(moves)}"
@tool
def get_stockfish_evaluation(fen: str) -> str:
"""
Calls an external Chess API to get a deep engine evaluation (Stockfish 18) for a given FEN string.
It returns the absolute best move, tactical score, winning chances, and the expected continuation line.
Args:
fen: The FEN string representing the current board state to analyze.
"""
import requests
r = requests.post("https://chess-api.com/v1", json={"fen": fen, "depth": 12})
d = r.json()
return f"Best: {d.get('san')}, Eval: {d.get('eval')}" |