Hobysenny commited on
Commit
e8579ca
·
verified ·
1 Parent(s): e3d0b13

Upload 9 files

Browse files
tools/describe_image_tool.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import os
3
+ from smolagents import Tool, ChatMessage, OpenAIServerModel
4
+ from dotenv import load_dotenv
5
+ from typing import List
6
+ GEMMA_API_KEY = os.getenv('GEMMA_API_KEY')
7
+
8
+ class DescribeImageTool(Tool):
9
+ """
10
+ Tool to analyze and describe any image using Gemma 4 Vision API.
11
+
12
+ Args:
13
+ image_path (str): Path to the image file.
14
+ description_type (str): Type of description to generate. Options:
15
+ - "general": General description of the image
16
+ - "detailed": Detailed analysis of the image
17
+ - "chess": Analysis of a chess position
18
+ - "text": Extract and describe text from the image
19
+ - "custom": Custom description based on user prompt
20
+
21
+ Returns:
22
+ str: Description of the image based on the requested type.
23
+ """
24
+
25
+ name = "describe_image"
26
+ description = "Analyzes and describes images using Gemma 4 multimodal capabilities."
27
+ inputs = {
28
+ "image_path": {"type": "string", "description": "Path to the image file"},
29
+ "description_type": {
30
+ "type": "string",
31
+ "description": "Type of description to generate (general, detailed, chess, text, custom)",
32
+ "nullable": True,
33
+ },
34
+ "custom_prompt": {
35
+ "type": "string",
36
+ "description": "Custom prompt for description (only used when description_type is 'custom')",
37
+ "nullable": True,
38
+ },
39
+ }
40
+ output_type = "string"
41
+
42
+ def __init__(self, *args, **kwargs):
43
+ super().__init__(*args, **kwargs)
44
+ # Configuration de l'accès à Gemma 4 (ex: via ton endpoint Ollama)
45
+ # Ajuste le model_id et l'api_key selon ton fichier config/variables d'environnement
46
+ self.model = OpenAIServerModel(
47
+ model_id='gemma4:31b-cloud',
48
+ api_base='https://ollama.com/v1',
49
+ api_key= GEMMA_API_KEY,
50
+ temperature=0.0,
51
+ max_tokens=2048,
52
+ timeout=180,
53
+
54
+ )
55
+
56
+ def encode_image(self, image_path: str) -> str:
57
+ """Encode image to base64 string."""
58
+ with open(image_path, "rb") as image_file:
59
+ return base64.b64encode(image_file.read()).decode("utf-8")
60
+
61
+ def get_prompt(self, description_type: str, custom_prompt: str = None) -> str:
62
+ """Get appropriate prompt based on description type."""
63
+ prompts = {
64
+ "general": "Provide a general description of this image. Focus on the main subjects, colors, and overall scene.",
65
+ "detailed": """Analyze this image in detail. Include:
66
+ 1. Main subjects and their relationships
67
+ 2. Colors, lighting, and composition
68
+ 3. Any text or symbols present
69
+ 4. Context or possible meaning
70
+ 5. Notable details or interesting elements""",
71
+ "chess": """Analyze this chess position and provide a detailed description including:
72
+ 1. List of pieces on the board for both white and black
73
+ 2. Whose turn it is to move
74
+ 3. Basic evaluation of the position
75
+ 4. Any immediate tactical opportunities or threats
76
+ 5. Suggested next moves with brief explanations""",
77
+ "text": "Extract and describe any text present in this image. If there are multiple pieces of text, organize them clearly.",
78
+ }
79
+ # Fallback de sécurité si description_type est None ou invalide
80
+ if not description_type:
81
+ description_type = "general"
82
+
83
+ return (
84
+ custom_prompt
85
+ if description_type == "custom"
86
+ else prompts.get(description_type, prompts["general"])
87
+ )
88
+
89
+ def forward(
90
+ self,
91
+ image_path: str,
92
+ description_type: str = "general",
93
+ custom_prompt: str = None,
94
+ ) -> str:
95
+ try:
96
+ if not os.path.exists(image_path):
97
+ return f"Error: Image file not found at {image_path}"
98
+
99
+ # 1. Encodage Base64
100
+ base64_image = self.encode_image(image_path)
101
+
102
+ # 2. Récupération du prompt de consigne
103
+ prompt = self.get_prompt(description_type, custom_prompt)
104
+
105
+ # 3. Préparation du payload compatible avec Gemma 4
106
+ payload = [
107
+ {"type": "text", "text": prompt},
108
+ {
109
+ "type": "image_url",
110
+ "image_url": {
111
+ "url": f"data:image/jpeg;base64,{base64_image}"
112
+ },
113
+ }
114
+ ]
115
+
116
+ # 4. Appel avec ChatMessage (propre à smolagents)
117
+ messages = [
118
+ ChatMessage(role="user", content=payload)
119
+ ]
120
+
121
+ response = self.model(messages)
122
+ return response.content
123
+
124
+ except Exception as e:
125
+ return f"Error analyzing image: {str(e)}"
tools/final_answer.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from typing import Any
3
+
4
+ from config import build_agent
5
+ from utils.logger import get_logger
6
+
7
+ logger = get_logger(__name__)
8
+
9
+ _reasoning_model = build_agent('gpt-oss:120b-cloud')
10
+ _formatting_model = build_agent('gpt-oss:120b-cloud')
11
+
12
+
13
+ def _extract_verdict(output: str) -> bool:
14
+ """Retourne True si le verdict final est PASS."""
15
+ if not output or not output.strip():
16
+ raise Exception("Evaluator model returned empty response.")
17
+
18
+ # Approche 1 : la dernière ligne contient exactement PASS ou FAIL
19
+ lines = output.strip().splitlines()
20
+ last_line = lines[-1].strip().upper()
21
+ if last_line in ("PASS", "FAIL"):
22
+ return last_line == "PASS"
23
+
24
+ # Approche 2 : chercher la dernière occurrence de PASS/FAIL en tant que mot
25
+ matches = list(re.finditer(r'\b(PASS|FAIL)\b', output))
26
+ if matches:
27
+ return matches[-1].group(1) == "PASS"
28
+
29
+ raise Exception(f"No clear PASS/FAIL verdict found in output:\n{output}")
30
+
31
+
32
+ def _run_judge(model: Any, prompt: str, label: str) -> bool:
33
+ messages = [{"role": "user", "content": [{"type": "text", "text": prompt}]}]
34
+
35
+ try:
36
+ output = str(model(messages).content)
37
+ except Exception as e:
38
+ logger.error(f"[{label}] Model call failed: {e}")
39
+ raise
40
+
41
+ logger.info(f"[{label}] Feedback:\n{output}")
42
+
43
+ try:
44
+ return _extract_verdict(output)
45
+ except Exception as e:
46
+ # Lève une exception avec le texte complet pour aider l'agent à comprendre l'échec
47
+ raise Exception(f"[{label}] {e}\nFull evaluator output:\n{output}")
48
+
49
+
50
+ def check_reasoning(final_answer, agent_memory, agent=None) -> bool:
51
+ prompt = f"""
52
+ Task & steps: {agent_memory.get_succinct_steps()}
53
+ Answer: {final_answer}
54
+
55
+ Evaluate if the final answer is factually correct AND properly derived from the source material.
56
+ For video questions, the answer must be based on direct analysis of the video content (frames/transcript), not on indirect web search results that may not correspond to the specific video.
57
+ If the agent merely searched the web and picked a number without video evidence, consider it a FAIL.
58
+ List reasons for PASS/FAIL, then final verdict: PASS or FAIL.
59
+ """
60
+ return _run_judge(_reasoning_model, prompt, "check_reasoning")
61
+
62
+
63
+ def ensure_formatting(final_answer, agent_memory, agent=None) -> bool:
64
+ prompt = f"""
65
+ Task & steps: {agent_memory.get_succinct_steps()}
66
+ FINAL ANSWER: {final_answer}
67
+
68
+ Evaluate format compliance:
69
+ - Answer type: number OR minimal words OR comma-separated list (no brackets).
70
+ - Number: no commas, no unit/% unless specified, Arabic digits (e.g., 9,3,1093).
71
+ - Currency: use symbol ($40.00) if asked.
72
+ - String: lowercase, no articles, no abbreviations, digits in words unless specified.
73
+ - List: elements follow number/string rules; no brackets; order as requested (alpha/asc).
74
+ - CRITICAL: If the task embeds a scale ("thousand X", "millions Y", "percentage"), the answer must already be in that unit (e.g., 17000h → 17 for "thousand hours"). If not, FAIL.
75
+ - If list order is specified (alphabetical/ascending), verify it matches. If not, FAIL.
76
+
77
+ List reasons, then final verdict on the LAST LINE: PASS or FAIL.
78
+ """
79
+ return _run_judge(_formatting_model, prompt, "ensure_formatting")
tools/get_answer.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import os
3
+ import shutil
4
+ from utils.logger import get_logger
5
+ from smolagents import Tool
6
+
7
+ logger = get_logger(__name__)
8
+
9
+ class GetTaskFileTool(Tool):
10
+ name = "get_task_file_tool"
11
+ description = "If a file_name is provided, download the file associated with a given task_id and return its absolute local path."
12
+ inputs = {
13
+ "task_id": {"type": "string", "description": "The unique task ID (required)"},
14
+ "file_name": {"type": "string", "description": "The exact name of the file to download or copy (required)"},
15
+ }
16
+ output_type = "string"
17
+
18
+ def __init__(self, **kwargs):
19
+ # CORRECTIF 1: Appel obligatoire de l'initialisation parente pour smolagents
20
+ super().__init__(**kwargs)
21
+ self.evaluation_api_base_url = "https://agents-course-unit4-scoring.hf.space"
22
+ self.directory_name = "downloads"
23
+ self.create_dir()
24
+
25
+ def forward(self, task_id: str, file_name: str) -> str:
26
+ target_path = os.path.join(self.directory_name, file_name)
27
+ try:
28
+ response = requests.get(f"{self.evaluation_api_base_url}/files/{task_id}", timeout=15)
29
+ response.raise_for_status()
30
+ with open(target_path, 'wb') as file:
31
+ file.write(response.content)
32
+ return os.path.abspath(target_path)
33
+ except Exception as e:
34
+ logger.warning(f"Échec du téléchargement pour la tâche {task_id}, tentative de récupération locale : {e}")
35
+
36
+ # Source locale présumée (ex: validation/ ou files/)
37
+ local_source = f"files/{file_name}"
38
+ if not os.path.exists(local_source):
39
+ # Fallback au cas où le dataset GAIA utilise l'arborescence complète
40
+ local_source = file_name
41
+
42
+ try:
43
+ shutil.copy2(local_source, target_path)
44
+ # CORRECTIF 2: Renvoie TOUJOURS le chemin absolu, même en mode secours
45
+ return os.path.abspath(target_path)
46
+ except Exception as copy_error:
47
+ return f"Erreur critique : Impossible de trouver le fichier local ou distant ({copy_error})"
48
+
49
+ def create_dir(self):
50
+ if not os.path.exists(self.directory_name):
51
+ os.makedirs(self.directory_name)
52
+ logger.info(f"Directory '{self.directory_name}' created successfully.")
53
+ else:
54
+ logger.debug(f"Directory '{self.directory_name}' already exists.")
tools/openai_speech_to_text_tool.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from smolagents import Tool
3
+ from faster_whisper import WhisperModel
4
+
5
+
6
+ class OpenAISpeechToTextTool(Tool):
7
+ """
8
+ Tool to convert speech to text using the high-performance local faster-whisper model.
9
+
10
+ Args:
11
+ audio_path (str): Path to the local audio file (.mp3, .wav, .m4a, etc.).
12
+
13
+ Returns:
14
+ str: Transcribed text from the audio file.
15
+ """
16
+
17
+ name = "transcribe_audio"
18
+ description = "Transcribes local audio files to text using high-precision faster-whisper."
19
+ inputs = {
20
+ "audio_path": {"type": "string", "description": "Path to the local audio file to transcribe"},
21
+ }
22
+ output_type = "string"
23
+
24
+ def __init__(self, *args, **kwargs):
25
+ super().__init__(*args, **kwargs)
26
+ # On charge le modèle large-v3 une seule fois au démarrage de l'agent.
27
+ # "int8" permet de garder une précision maximale tout en épargnant ta RAM sur CPU.
28
+ # Si tu as un GPU Nvidia disponible, tu peux mettre device="cuda" et compute_type="float16".
29
+ try:
30
+ self.model = WhisperModel("small", device="cpu", compute_type="int8")
31
+ except Exception as e:
32
+ # Sécurité si le chargement échoue au démarrage
33
+ self.model = None
34
+ print(f"Warning: Failed to load faster-whisper model: {e}")
35
+
36
+ def forward(self, audio_path: str) -> str:
37
+ if self.model is None:
38
+ return "Error: Whisper model was not initialized properly."
39
+
40
+ if not os.path.exists(audio_path):
41
+ return f"Error: Audio file not found at {audio_path}"
42
+
43
+ try:
44
+ # Transcription optimisée avec recherche par faisceaux
45
+ segments, info = self.model.transcribe(
46
+ audio_path,
47
+ beam_size=5,
48
+ best_of=5
49
+ )
50
+
51
+ # On regroupe les segments de texte décodés
52
+ transcription = [segment.text for segment in segments]
53
+ return " ".join(transcription).strip()
54
+
55
+ except Exception as e:
56
+ return f"Error transcribing audio: {str(e)}"
tools/read_file_tool.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from smolagents import Tool
2
+
3
+ class ReadFileTool(Tool):
4
+ """
5
+ Tool to read a file and return its content.
6
+
7
+ Args:
8
+ file_path (str): Path to the file to read.
9
+
10
+ Returns:
11
+ str: Content of the file or error message.
12
+ """
13
+
14
+ name = "read_file"
15
+ description = "Reads a file and returns its content"
16
+ inputs = {
17
+ "file_path": {"type": "string", "description": "Path to the file to read"},
18
+ }
19
+ output_type = "string"
20
+
21
+ def forward(self, file_path: str) -> str:
22
+ try:
23
+ with open(file_path, "r") as file:
24
+ return file.read()
25
+ except Exception as e:
26
+ return f"Error reading file: {str(e)}"
tools/table_extractor_tool.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from smolagents import Tool
2
+ import pandas as pd
3
+ from typing import Optional
4
+ import os
5
+
6
+ class TableExtractorTool(Tool):
7
+ """
8
+ Extracts tables from Excel (.xlsx, .xls) or CSV files and answers queries.
9
+ Auto-detects file type based on extension.
10
+ """
11
+ name = "table_extractor"
12
+ description = "Reads Excel/CSV files and answers questions about tabular data"
13
+ inputs = {
14
+ "file_path": {
15
+ "type": "string",
16
+ "description": "Path to Excel/CSV file"
17
+ },
18
+ "sheet_name": {
19
+ "type": "string",
20
+ "description": "Sheet name (Excel only, optional)",
21
+ "required": False,
22
+ "nullable": True
23
+ },
24
+ "query": {
25
+ "type": "string",
26
+ "description": "Question about the data (e.g., 'total sales')",
27
+ "required": False,
28
+ "nullable": True
29
+ }
30
+ }
31
+ output_type = "string"
32
+
33
+ def forward(self,
34
+ file_path: str,
35
+ sheet_name: Optional[str] = None,
36
+ query: Optional[str] = None) -> str:
37
+
38
+ try:
39
+ # Validate file exists
40
+ if not os.path.exists(file_path):
41
+ return f"Error: File not found at {file_path}"
42
+
43
+ # Read file based on extension
44
+ ext = os.path.splitext(file_path)[1].lower()
45
+
46
+ if ext in ('.xlsx', '.xls'):
47
+ df = self._read_excel(file_path, sheet_name)
48
+ elif ext == '.csv':
49
+ df = pd.read_csv(file_path)
50
+ else:
51
+ return f"Error: Unsupported file type {ext}"
52
+
53
+ if df.empty:
54
+ return "Error: No data found in file."
55
+
56
+ return self._answer_query(df, query) if query else df.to_string()
57
+
58
+ except Exception as e:
59
+ return f"Error processing file: {str(e)}"
60
+
61
+ def _read_excel(self, path: str, sheet_name: Optional[str]) -> pd.DataFrame:
62
+ """Read Excel file with sheet selection logic"""
63
+ if sheet_name:
64
+ return pd.read_excel(path, sheet_name=sheet_name)
65
+
66
+ # Auto-detect first non-empty sheet
67
+ sheets = pd.ExcelFile(path).sheet_names
68
+ for sheet in sheets:
69
+ df = pd.read_excel(path, sheet_name=sheet)
70
+ if not df.empty:
71
+ return df
72
+ return pd.DataFrame() # Return empty if all sheets are blank
73
+
74
+ def _answer_query(self, df: pd.DataFrame, query: str) -> str:
75
+ """Handles queries with pandas operations"""
76
+ query = query.lower()
77
+
78
+ try:
79
+ # SUM QUERIES (e.g., "total revenue")
80
+ if "total" in query or "sum" in query:
81
+ for col in df.select_dtypes(include='number').columns:
82
+ if col.lower() in query:
83
+ return f"Total {col}: {df[col].sum():.2f}"
84
+
85
+ # AVERAGE QUERIES (e.g., "average price")
86
+ elif "average" in query or "mean" in query:
87
+ for col in df.select_dtypes(include='number').columns:
88
+ if col.lower() in query:
89
+ return f"Average {col}: {df[col].mean():.2f}"
90
+
91
+ # FILTER QUERIES (e.g., "show sales > 1000")
92
+ elif ">" in query or "<" in query:
93
+ col = next((c for c in df.columns if c.lower() in query), None)
94
+ if col:
95
+ filtered = df.query(query.replace(col, f"`{col}`"))
96
+ return filtered.to_string()
97
+
98
+ # DEFAULT: Return full table with column names
99
+ return f"Data:\nColumns: {', '.join(df.columns)}\n\n{df.to_string()}"
100
+
101
+ except Exception as e:
102
+ return f"Query failed: {str(e)}\nAvailable columns: {', '.join(df.columns)}"
tools/tools.py ADDED
@@ -0,0 +1,449 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from smolagents import tool
3
+
4
+ # ----------------------------------------------------------------------------
5
+ # SECTION 1: Vision & Multimodal
6
+ # ----------------------------------------------------------------------------
7
+
8
+
9
+
10
+
11
+ @tool
12
+ def vision_tool(prompt: str, image_list: list) -> str:
13
+ """
14
+ Analyzes one or more images using a multimodal model to answer specific questions.
15
+ It processes image content and returns the model's text-based response.
16
+
17
+ Args:
18
+ prompt: The user question or task to perform on the images.
19
+ image_list: A list of PIL Image objects to be analyzed.
20
+ """
21
+ import io, base64, os
22
+ from smolagents import OpenAIServerModel
23
+ from PIL import Image
24
+
25
+ model = OpenAIServerModel(
26
+ model_id='gemma4:31b-cloud',
27
+ api_base='https://ollama.com/v1',
28
+ api_key=os.getenv('GEMMA_API_KEY'),
29
+ temperature=0.0,
30
+ max_tokens=2048,
31
+ )
32
+
33
+ payload = [{"type": "text", "text": prompt}]
34
+ for img in image_list:
35
+ try:
36
+ buffered = io.BytesIO()
37
+ img.save(buffered, format="JPEG")
38
+ b64_img = base64.b64encode(buffered.getvalue()).decode("utf-8")
39
+ payload.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64_img}"}})
40
+ except Exception as e:
41
+ return f"Error processing image: {str(e)}"
42
+
43
+ return model([{"role": "user", "content": payload}]).content
44
+
45
+ # ----------------------------------------------------------------------------
46
+ # SECTION 2: YouTube Pipeline (Tout-en-un pour la robustesse)
47
+ # ----------------------------------------------------------------------------
48
+ @tool
49
+ def ask_youtube_full_pipeline(url: str, question: str) -> str:
50
+ """
51
+ Downloads a YouTube video, extracts key frames at regular intervals, and uses a multimodal model to answer questions about the video's content.
52
+
53
+ Args:
54
+ url: The YouTube video URL to process.
55
+ question: The specific question to ask about the video content.
56
+ """
57
+ import os, re, tempfile, yt_dlp, imageio
58
+ from PIL import Image
59
+ from smolagents import OpenAIServerModel
60
+
61
+ # 1. Extraction ID interne
62
+ patterns = [r"v=([a-zA-Z0-9_-]{11})", r"youtu\.be/([a-zA-Z0-9_-]{11})"]
63
+ video_id = None
64
+
65
+ for pat in patterns:
66
+ match = re.search(pat, url)
67
+ if match:
68
+ video_id = match.group(1)
69
+ break
70
+
71
+ if not video_id:
72
+ return "Erreur: URL invalide."
73
+
74
+ with tempfile.TemporaryDirectory() as tmpdir:
75
+ # Configuration optimisée : légère (évite les timeouts) et robuste
76
+ ydl_opts = {
77
+ 'format': 'best[ext=mp4]/best', # Récupère un fichier MP4 direct déjà fusionné
78
+ 'outtmpl': os.path.join(tmpdir, 'downloaded_video.%(ext)s'),
79
+ 'quiet': True,
80
+ 'no_warnings': True
81
+ }
82
+
83
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
84
+ ydl.extract_info(url, download=True)
85
+
86
+ # CORRECTIF CRITIQUE : On liste le dossier pour trouver le fichier, peu importe son extension exacte
87
+ downloaded_files = os.listdir(tmpdir)
88
+ if not downloaded_files:
89
+ return "Erreur: Le téléchargement de la vidéo a échoué."
90
+
91
+ video_path = os.path.join(tmpdir, downloaded_files[0])
92
+
93
+ # Extraction des images via le chemin dynamique détecté
94
+ reader = imageio.get_reader(video_path, format='ffmpeg')
95
+ frames = [Image.fromarray(f) for i, f in enumerate(reader) if i % 60 == 0][:8]
96
+ reader.close()
97
+
98
+ # 2. Analyse VLM (Auto-contenu)
99
+ model = OpenAIServerModel(model_id='gemma4:31b-cloud', api_base='https://ollama.com/v1', api_key=os.getenv('GEMMA_API_KEY'))
100
+ import base64, io
101
+ payload = [{"type": "text", "text": question}]
102
+ for img in frames:
103
+ b = io.BytesIO()
104
+ img.save(b, format="JPEG")
105
+ payload.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64.b64encode(b.getvalue()).decode()}"}})
106
+
107
+ return model([{"role": "user", "content": payload}]).content
108
+ # ----------------------------------------------------------------------------
109
+ # SECTION 3: Fichiers & Audio
110
+ # ----------------------------------------------------------------------------
111
+ @tool
112
+ def read_pdf_file(file_path: str) -> str:
113
+ """
114
+ Reads the content of a PDF file, extracting all visible text page by page.
115
+
116
+ Args:
117
+ file_path: The absolute or relative path to the .pdf file that needs to be read.
118
+ """
119
+ import os
120
+ from pypdf import PdfReader
121
+
122
+ if not os.path.exists(file_path):
123
+ return f"Erreur : Le fichier au chemin '{file_path}' est introuvable."
124
+
125
+ try:
126
+ reader = PdfReader(file_path)
127
+ full_text = []
128
+
129
+ # Parcourir et extraire le texte de chaque page
130
+ for page_num, page in enumerate(reader.pages, start=1):
131
+ page_text = page.extract_text()
132
+ if page_text and page_text.strip():
133
+ full_text.append(f"\n--- [Page {page_num}] ---")
134
+ full_text.append(page_text.strip())
135
+
136
+ output = "\n".join(full_text)
137
+ return output if output.strip() else "Le document PDF semble vide ou ne contient que des images (scan)."
138
+
139
+ except Exception as e:
140
+ return f"Erreur lors de la lecture du fichier PDF : {str(e)}"
141
+
142
+ @tool
143
+ def read_docx_file(file_path: str) -> str:
144
+ """
145
+ Reads the content of a Word document (.docx file), extracting all text from paragraphs and tables.
146
+
147
+ Args:
148
+ file_path: The path to the .docx file that needs to be read.
149
+ """
150
+ import docx
151
+ import os
152
+
153
+ if not os.path.exists(file_path):
154
+ return f"Erreur : Le fichier au chemin '{file_path}' est introuvable."
155
+
156
+ try:
157
+ doc = docx.Document(file_path)
158
+ full_text = []
159
+
160
+ # 1. Extraction du texte des paragraphes classiques
161
+ for para in doc.paragraphs:
162
+ if para.text.strip():
163
+ full_text.append(para.text.strip())
164
+
165
+ # 2. Extraction du texte des tableaux (très fréquent dans GAIA)
166
+ for table in doc.tables:
167
+ full_text.append("\n--- [Tableau détecté] ---")
168
+ for row in table.rows:
169
+ row_text = [cell.text.strip() for cell in row.cells if cell.text.strip()]
170
+ if row_text:
171
+ # On sépare les colonnes par des barres verticales pour l'agent
172
+ full_text.append(" | ".join(row_text))
173
+ full_text.append("-------------------------\n")
174
+
175
+ # Renvoyer le tout proprement assemblé
176
+ output = "\n".join(full_text)
177
+ return output if output.strip() else "Le document est vide."
178
+
179
+ except Exception as e:
180
+ return f"Erreur lors de la lecture du fichier .docx : {str(e)}"
181
+
182
+
183
+ @tool
184
+ def file_from_url(url: str, save_as: str = "downloaded_file") -> str:
185
+ """
186
+ Downloads a file from a provided URL, determines its extension properly, and saves it.
187
+
188
+ Args:
189
+ url: The source URL of the file to download.
190
+ save_as: Optional filename to save the file as. If not provided, derives the name from the URL or headers.
191
+ """
192
+ import requests
193
+ import os
194
+ from urllib.parse import urlparse
195
+ import mimetypes
196
+
197
+ # 1. Utiliser un répertoire local dédié et contrôlé (comme ton dossier downloads)
198
+ download_dir = os.path.abspath("downloads")
199
+ os.makedirs(download_dir, exist_ok=True)
200
+
201
+ try:
202
+ with requests.get(url, stream=True, timeout=20) as r:
203
+ r.raise_for_status()
204
+
205
+ # 2. Détermination intelligente du nom et de l'extension
206
+ if save_as == "downloaded_file":
207
+ base_name = os.path.basename(urlparse(url).path)
208
+ if not base_name or "." not in base_name:
209
+ # Si l'URL est opaque, on regarde le Content-Type envoyé par le serveur
210
+ content_type = r.headers.get('content-type', '').split(';')[0]
211
+ ext = mimetypes.guess_extension(content_type) or ".txt"
212
+ base_name = f"downloaded_media_{int(os.path.getctime(download_dir))}{ext}"
213
+ save_as = base_name
214
+
215
+ file_path = os.path.join(download_dir, save_as)
216
+
217
+ # 3. Écriture par blocs (chunks)
218
+ with open(file_path, 'wb') as f:
219
+ for chunk in r.iter_content(chunk_size=8192):
220
+ if chunk:
221
+ f.write(chunk)
222
+
223
+ # Renvoie le chemin absolu impeccable pour tes autres sous-agents
224
+ return os.path.abspath(file_path)
225
+
226
+ except Exception as e:
227
+ return f"Erreur lors du téléchargement du fichier depuis l'URL : {str(e)}"
228
+
229
+ @tool
230
+ def transcribe_youtube(yt_url: str) -> str:
231
+ """
232
+ Downloads the audio from a YouTube video and performs speech-to-text transcription using the Groq cloud API (Whisper).
233
+ Useful for retrieving text content or answering questions based on video dialogue without local heavy models.
234
+
235
+ Args:
236
+ yt_url: The URL of the YouTube video to transcribe.
237
+ """
238
+ import os, tempfile, yt_dlp, requests
239
+
240
+ groq_api_key = os.getenv("GROQ_API_KEY")
241
+ if not groq_api_key:
242
+ return "Erreur : La variable d'environnement GROQ_API_KEY n'est pas configurée dans l'environnement."
243
+
244
+ with tempfile.TemporaryDirectory() as tmpdir:
245
+ # Téléchargement de l'audio uniquement
246
+ ydl_opts = {
247
+ "format": "bestaudio",
248
+ "outtmpl": os.path.join(tmpdir, "audio.%(ext)s"),
249
+ "quiet": True,
250
+ "postprocessors": [{"key": "FFmpegExtractAudio", "preferredcodec": "mp3"}]
251
+ }
252
+
253
+ try:
254
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
255
+ ydl.extract_info(yt_url, download=True)
256
+
257
+ audio_path = os.path.join(tmpdir, "audio.mp3")
258
+
259
+ # Appel API Groq Cloud (Whisper Large V3)
260
+ url = "https://api.groq.com/openai/v1/audio/transcriptions"
261
+ headers = {"Authorization": f"Bearer {groq_api_key}"}
262
+
263
+ with open(audio_path, 'rb') as f:
264
+ files = {"file": f}
265
+ data = {"model": "whisper-large-v3"}
266
+ response = requests.post(url, headers=headers, files=files, data=data)
267
+
268
+ if response.status_code != 200:
269
+ return f"Erreur API Groq : {response.text}"
270
+
271
+ return response.json().get("text", "")
272
+
273
+ except Exception as e:
274
+ return f"Erreur de traitement audio / API : {str(e)}"
275
+
276
+ @tool
277
+ def read_text_file(file_path: str) -> str:
278
+ """
279
+ Reads and returns the raw plain text content from a specified local file path.
280
+
281
+ Args:
282
+ file_path: The full local path to the text file.
283
+ """
284
+ with open(file_path, "r", encoding="utf-8") as f: return f.read()
285
+
286
+ # ----------------------------------------------------------------------------
287
+ # SECTION 4: OCR & Tabulaire
288
+ # ----------------------------------------------------------------------------
289
+ @tool
290
+ def extract_text_via_ocr(image_path: str) -> str:
291
+ """
292
+ Extracts text from an image using the cloud-based OCR.space API.
293
+ Returns the detected text found within the provided image path without heavy local dependencies.
294
+
295
+ Args:
296
+ image_path: The local path to the image file containing text.
297
+ """
298
+ import requests, os
299
+
300
+ # Utilisation de la clé publique 'helloworld' d'OCR.space si aucune clé n'est configurée
301
+ api_key = os.getenv("OCR_SPACE_API_KEY", "helloworld")
302
+
303
+ try:
304
+ with open(image_path, 'rb') as f:
305
+ response = requests.post(
306
+ 'https://api.ocr.space/parse/image',
307
+ files={'file': f},
308
+ data={'apikey': api_key, 'language': 'fra'}
309
+ )
310
+
311
+ result = response.json()
312
+ if result.get("IsErroredOnProcessing"):
313
+ return f"Erreur OCR.space : {result.get('ErrorMessage')}"
314
+
315
+ parsed_results = result.get('ParsedResults', [])
316
+ if not parsed_results:
317
+ return "Aucun texte détecté sur l'image."
318
+
319
+ return parsed_results[0].get('ParsedText', '')
320
+
321
+ except Exception as e:
322
+ return f"Erreur lors de l'appel API OCR : {str(e)}"
323
+
324
+ @tool
325
+ def summarize_csv_data(path: str, query: str = "") -> str:
326
+ """
327
+ Loads a CSV file into a pandas DataFrame and generates a descriptive summary, including column statistics.
328
+ Optionally allows filtering rows via a pandas query string.
329
+
330
+ Args:
331
+ path: The local file path to the CSV file.
332
+ query: Optional pandas query expression to filter rows before summarizing (e.g., "age > 30").
333
+ """
334
+ import pandas as pd
335
+ df = pd.read_csv(path)
336
+ if query: df = df.query(query)
337
+ return df.describe().to_string()
338
+
339
+ @tool
340
+ def calculer_probabilite_loi(loi: str, parametres: dict, valeur_k: float) -> str:
341
+ """
342
+ Calculates the exact or cumulative probability for a specified statistical distribution law (Normal or Binomial).
343
+
344
+ Args:
345
+ loi: The distribution type, either 'normale' or 'binomiale'.
346
+ parametres: Dictionary containing distribution parameters (e.g., {'moyenne': float, 'ecart_type': float} for Normal).
347
+ valeur_k: The value or bound for which the cumulative probability P(X <= k) is calculated.
348
+ """
349
+ # Import local obligatoire pour l'autonomie en sandbox
350
+ from scipy import stats
351
+
352
+ try:
353
+ if loi.lower() == "normale":
354
+ loc = parametres.get("moyenne", 0)
355
+ scale = parametres.get("ecart_type", 1)
356
+ prob = stats.norm.cdf(valeur_k, loc=loc, scale=scale)
357
+ return f"Pour une Loi Normale({loc}, {scale}), P(X <= {valeur_k}) = {prob:.6f}"
358
+
359
+ elif loi.lower() == "binomiale":
360
+ n = int(parametres.get("n", 1))
361
+ p = float(parametres.get("p", 0.5))
362
+ prob = stats.binom.cdf(valeur_k, n, p)
363
+ prob_exacte = stats.binom.pmf(valeur_k, n, p)
364
+ return (
365
+ f"Pour une Loi Binomiale(n={n}, p={p}) :\n"
366
+ f"- Probabilité exacte P(X = {valeur_k}) = {prob_exacte:.6f}\n"
367
+ f"- Probabilité cumulative P(X <= {valeur_k}) = {prob:.6f}"
368
+ )
369
+ else:
370
+ return "Loi non supportée. Utilisez 'normale' ou 'binomiale'."
371
+ except Exception as e:
372
+ return f"Erreur de paramètres : {str(e)}"
373
+
374
+ @tool
375
+ def summarize_excel_data(path: str, query: str = "") -> str:
376
+ """
377
+ Loads an Excel file (.xls or .xlsx) into a pandas DataFrame and generates a descriptive summary, including column statistics.
378
+ Optionally allows filtering rows via a pandas query string.
379
+
380
+ Args:
381
+ path: The local file path to the Excel file.
382
+ query: Optional pandas query expression to filter rows before summarizing (e.g., "age > 30").
383
+ """
384
+ import pandas as pd
385
+ df = pd.read_excel(path)
386
+ if query: df = df.query(query)
387
+ return df.describe().to_string()
388
+
389
+ @tool
390
+ def analyser_serie_statistique(donnees: list[float]) -> str:
391
+ """
392
+ Calculates essential descriptive statistics for a provided series of numerical data, such as mean, median, standard deviation, and range.
393
+
394
+ Args:
395
+ donnees: A list of floats representing the dataset to analyze.
396
+ """
397
+ import numpy as np
398
+ arr = np.array(donnees)
399
+ return f"Moyenne: {np.mean(arr):.2f}, Écart-type: {np.std(arr):.2f}, Min: {np.min(arr)}, Max: {np.max(arr)}"
400
+
401
+
402
+ # ----------------------------------------------------------------------------
403
+ # SECTION 5: Maths & Chess
404
+ # ----------------------------------------------------------------------------
405
+ @tool
406
+ def resoudre_calcul_formel(expression: str, action: str, variable: str = "x") -> str:
407
+ """
408
+ Performs formal mathematical computations such as solving equations, differentiation, integration, and simplification using sympy.
409
+
410
+ Args:
411
+ expression: The mathematical expression in Python syntax (e.g., "x**2 + 2*x - 3" or "x**2 - 4 = 0").
412
+ action: The mathematical operation to perform ('resoudre', 'deriver', 'integrer', or 'simplifier').
413
+ variable: The primary variable in the expression to operate on. Defaults to 'x'.
414
+ """
415
+ import sympy as sp
416
+ v = sp.Symbol(variable)
417
+ e = sp.sympify(expression.split("=")[0]) if "=" in expression else sp.sympify(expression)
418
+ if action == "simplifier": return str(sp.simplify(e))
419
+ if action == "deriver": return str(sp.diff(e, v))
420
+ if action == "integrer": return str(sp.integrate(e, v))
421
+ return str(sp.solve(e, v))
422
+
423
+ @tool
424
+ def analyze_chess_position(fen: str) -> str:
425
+ """
426
+ Analyzes a chess board state from a FEN (Forsyth-Edwards Notation) string.
427
+ Detects checks, checkmates, stalemates, lists legal moves, and scans for immediate 'Mate in 1' opportunities.
428
+
429
+ Args:
430
+ fen: The FEN string representing the current board state.
431
+ """
432
+ import chess
433
+ board = chess.Board(fen)
434
+ moves = [board.san(m) for m in board.legal_moves]
435
+ return f"Turn: {'White' if board.turn else 'Black'}. Moves: {', '.join(moves)}"
436
+
437
+ @tool
438
+ def get_stockfish_evaluation(fen: str) -> str:
439
+ """
440
+ Calls an external Chess API to get a deep engine evaluation (Stockfish 18) for a given FEN string.
441
+ It returns the absolute best move, tactical score, winning chances, and the expected continuation line.
442
+
443
+ Args:
444
+ fen: The FEN string representing the current board state to analyze.
445
+ """
446
+ import requests
447
+ r = requests.post("https://chess-api.com/v1", json={"fen": fen, "depth": 12})
448
+ d = r.json()
449
+ return f"Best: {d.get('san')}, Eval: {d.get('eval')}"
tools/youtube_transcription_tool.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from smolagents import Tool
3
+ from youtube_transcript_api import YouTubeTranscriptApi
4
+
5
+
6
+ class YouTubeTranscriptionTool(Tool):
7
+ """
8
+ Tool to fetch the transcript of a YouTube video given its URL.
9
+ Attempts to retrieve official or auto-generated subtitles instantly.
10
+
11
+ Args:
12
+ video_url (str): YouTube video URL.
13
+
14
+ Returns:
15
+ str: Transcript of the video as a single string.
16
+ """
17
+
18
+ name = "youtube_transcription"
19
+ description = "Fetches the transcript of a YouTube video given its URL"
20
+ inputs = {
21
+ "video_url": {"type": "string", "description": "YouTube video URL"},
22
+ }
23
+ output_type = "string"
24
+
25
+ def _extract_video_id(self, url: str) -> str:
26
+ """
27
+ Extracts the 11-character YouTube video ID from various URL formats.
28
+ Gathers classic watch, shared (youtu.be), embeds, and shorts formats.
29
+ """
30
+ pattern = r'(?:v=|\/embed\/|\/shorts\/|\/|be\/)([a-zA-Z0-9_-]{11})'
31
+ match = re.search(pattern, url)
32
+ if match:
33
+ return match.group(1)
34
+ # Fallback basique si l'expression régulière échoue
35
+ return url.strip().split("v=")[-1].split("&")[0]
36
+
37
+ def forward(self, video_url: str) -> str:
38
+ try:
39
+ video_id = self._extract_video_id(video_url)
40
+
41
+ # Récupération du transcript (tente de récupérer l'anglais et le français par défaut)
42
+ transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=['en', 'fr'])
43
+
44
+ return " ".join([entry["text"] for entry in transcript])
45
+
46
+ except Exception as e:
47
+ # On renvoie l'erreur sous forme de chaîne pour que l'agent comprenne qu'il doit
48
+ # basculer sur un plan B (comme ton outil de téléchargement audio + faster-whisper)
49
+ return (
50
+ f"Error fetching transcript via API: {str(e)}. "
51
+ "The video might not have subtitles enabled, or the API is rate-limited. "
52
+ "Please try downloading the audio and transcribing it instead."
53
+ )