Mahynlo commited on
Commit
0abe794
·
1 Parent(s): 29ccd55

Soporte para archivos Excel y audio + mejoras en procesamiento de archivos

Browse files
Files changed (4) hide show
  1. agents.py +24 -7
  2. requirements.txt +1 -1
  3. test_answers.py +58 -0
  4. tools.py +60 -0
agents.py CHANGED
@@ -163,14 +163,15 @@ IMPORTANT: GAIA uses exact string matching. Be precise!"""
163
  if files and len(files) > 0:
164
  context_parts.append("\n📁 FILES PROVIDED:")
165
 
166
- from tools import read_image_text
167
  import requests
168
 
169
  for file_url in files:
170
  try:
171
- # Determinar tipo de archivo
172
- if any(ext in file_url.lower() for ext in ['.jpg', '.jpeg', '.png', '.gif', '.bmp']):
173
- # Procesar imagen con OCR
 
174
  if self.verbose:
175
  print(f" 📷 Procesando imagen: {file_url}")
176
  text = read_image_text(file_url)
@@ -180,8 +181,24 @@ IMPORTANT: GAIA uses exact string matching. Be precise!"""
180
  else:
181
  context_parts.append(f"\n⚠️ Could not extract text from image: {file_url}")
182
 
183
- elif any(ext in file_url.lower() for ext in ['.txt', '.csv', '.json', '.py', '.md']):
184
- # Procesar archivo de texto
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
  if self.verbose:
186
  print(f" 📄 Procesando archivo texto: {file_url}")
187
  response = requests.get(file_url, timeout=30)
@@ -191,7 +208,7 @@ IMPORTANT: GAIA uses exact string matching. Be precise!"""
191
  context_parts.append(f"{content}")
192
 
193
  else:
194
- # Solo mencionar archivo desconocido
195
  context_parts.append(f"\n📎 File available: {file_url}")
196
 
197
  except Exception as e:
 
163
  if files and len(files) > 0:
164
  context_parts.append("\n📁 FILES PROVIDED:")
165
 
166
+ from tools import read_image_text, read_excel_file, read_audio_file
167
  import requests
168
 
169
  for file_url in files:
170
  try:
171
+ file_lower = file_url.lower()
172
+
173
+ # Procesar imágenes con OCR
174
+ if any(ext in file_lower for ext in ['.jpg', '.jpeg', '.png', '.gif', '.bmp']):
175
  if self.verbose:
176
  print(f" 📷 Procesando imagen: {file_url}")
177
  text = read_image_text(file_url)
 
181
  else:
182
  context_parts.append(f"\n⚠️ Could not extract text from image: {file_url}")
183
 
184
+ # Procesar archivos Excel
185
+ elif any(ext in file_lower for ext in ['.xlsx', '.xls']):
186
+ if self.verbose:
187
+ print(f" 📊 Procesando Excel: {file_url}")
188
+ content = read_excel_file(file_url)
189
+ context_parts.append(f"\n📊 EXCEL DATA from {file_url}:")
190
+ context_parts.append(content)
191
+
192
+ # Procesar archivos de audio (limitado)
193
+ elif any(ext in file_lower for ext in ['.mp3', '.wav', '.ogg', '.m4a']):
194
+ if self.verbose:
195
+ print(f" 🎵 Detectado audio: {file_url}")
196
+ info = read_audio_file(file_url)
197
+ context_parts.append(f"\n🎵 AUDIO FILE:")
198
+ context_parts.append(info)
199
+
200
+ # Procesar archivos de texto
201
+ elif any(ext in file_lower for ext in ['.txt', '.csv', '.json', '.py', '.md']):
202
  if self.verbose:
203
  print(f" 📄 Procesando archivo texto: {file_url}")
204
  response = requests.get(file_url, timeout=30)
 
208
  context_parts.append(f"{content}")
209
 
210
  else:
211
+ # Archivo de tipo desconocido
212
  context_parts.append(f"\n📎 File available: {file_url}")
213
 
214
  except Exception as e:
requirements.txt CHANGED
@@ -7,6 +7,7 @@ google-generativeai>=0.8.0
7
 
8
  # Procesamiento de datos
9
  pandas>=2.0.0
 
10
  requests>=2.31.0
11
 
12
  # Procesamiento de imágenes (OCR)
@@ -15,4 +16,3 @@ pytesseract>=0.3.10
15
 
16
  # Variables de entorno
17
  python-dotenv>=1.0.0
18
-
 
7
 
8
  # Procesamiento de datos
9
  pandas>=2.0.0
10
+ openpyxl>=3.1.0 # Para leer archivos Excel
11
  requests>=2.31.0
12
 
13
  # Procesamiento de imágenes (OCR)
 
16
 
17
  # Variables de entorno
18
  python-dotenv>=1.0.0
 
test_answers.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Script para testear respuestas específicas y mejorar la precisión
3
+ """
4
+
5
+ # Respuestas del último run (15%)
6
+ respuestas_obtenidas = {
7
+ 1: "4", # Mercedes Sosa albums
8
+ 2: "4", # Bird species video
9
+ 3: "right", # Reversed text ✅ (probablemente correcta)
10
+ 4: "Ra1#", # Chess move
11
+ 5: "funkmonk", # Wikipedia dinosaur
12
+ 6: "b,e", # Math table ✅ (probablemente correcta)
13
+ 7: "indeed", # Teal'c quote ✅ (probablemente correcta)
14
+ 8: "silver", # Equine veterinarian
15
+ 9: "bell pepper,broccoli,celery,corn,green beans,lettuce,sweet potatoes,zucchini", # Botany list
16
+ 10: "cornstarch,lemon juice,salt,strawberries,sugar", # Pie ingredients
17
+ 11: "wojciech", # Polish actor
18
+ 12: "55", # Python code output
19
+ 13: "553", # Baseball at bats
20
+ 14: "21,22,23,24,25,26,27,28,29,30,31,32,33,34,35", # Homework pages
21
+ 15: "80GSFC21N0002", # NASA article
22
+ 16: "None", # Vietnamese specimens
23
+ 17: "HAI", # 1928 Olympics
24
+ 18: "Fujiwara,Ogasawara", # Baseball pitchers
25
+ 19: "$210.00", # Excel sales
26
+ 20: "dmitrij", # Malko Competition
27
+ }
28
+
29
+ # Patrones observados de posibles problemas:
30
+ problemas_potenciales = {
31
+ "Mayúsculas/minúsculas": [5, 7, 11, 17, 18, 20], # funkmonk vs FunkMonk, indeed vs Indeed
32
+ "Formato numérico": [1, 12, 13], # Números que podrían estar incorrectos
33
+ "Listas de items": [9, 10, 14, 18], # Listas que podrían tener orden o items incorrectos
34
+ "Formato especial": [15, 19], # Códigos NASA, moneda
35
+ "Análisis de archivos": [8, 12, 14, 19, 20], # Requieren leer archivos
36
+ }
37
+
38
+ print("=" * 60)
39
+ print("🔍 ANÁLISIS DE RESPUESTAS DEL ÚLTIMO RUN")
40
+ print("=" * 60)
41
+ print(f"\n✅ Correctas confirmadas: 3/20 (15%)")
42
+ print(f"🎯 Objetivo: 6/20 (30%)")
43
+ print(f"❌ Necesitamos mejorar: +3 respuestas correctas\n")
44
+
45
+ print("📋 CATEGORÍAS DE PROBLEMAS POTENCIALES:\n")
46
+
47
+ for categoria, preguntas in problemas_potenciales.items():
48
+ print(f" • {categoria}:")
49
+ print(f" Preguntas: {', '.join(map(str, preguntas))}")
50
+ respuestas = [respuestas_obtenidas[p] for p in preguntas]
51
+ print(f" Respuestas: {respuestas[:3]}..." if len(respuestas) > 3 else f" Respuestas: {respuestas}")
52
+ print()
53
+
54
+ print("\n💡 RECOMENDACIONES:")
55
+ print(" 1. Verificar case-sensitivity (mayúsculas/minúsculas)")
56
+ print(" 2. Mejorar procesamiento de archivos (especialmente audio/Excel)")
57
+ print(" 3. Validar formato de listas (orden alfabético vs orden original)")
58
+ print(" 4. Revisar precisión numérica en cálculos")
tools.py CHANGED
@@ -20,6 +20,66 @@ def read_image_text(url: str):
20
  print(f"❌ Error al leer imagen {url}: {e}")
21
  return ""
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  def web_search(query: str):
24
  """Simula búsqueda web (puedes mejorarla con Wikipedia API)."""
25
  return f"(Simulación de búsqueda web para '{query}')"
 
20
  print(f"❌ Error al leer imagen {url}: {e}")
21
  return ""
22
 
23
+
24
+ def read_excel_file(url: str):
25
+ """
26
+ Lee un archivo Excel y lo convierte a texto estructurado.
27
+ Útil para preguntas GAIA que requieren análisis de datos.
28
+ """
29
+ try:
30
+ import pandas as pd
31
+
32
+ response = requests.get(url, timeout=30)
33
+ response.raise_for_status()
34
+
35
+ # Leer Excel con pandas
36
+ df = pd.read_excel(BytesIO(response.content), sheet_name=None) # Todas las hojas
37
+
38
+ result = []
39
+ for sheet_name, data in df.items():
40
+ result.append(f"\n📊 Sheet: {sheet_name}")
41
+ # Convertir a string con formato tabular (primeras 50 filas)
42
+ result.append(data.head(50).to_string(index=False))
43
+
44
+ # Si hay más filas, indicarlo
45
+ if len(data) > 50:
46
+ result.append(f"\n... ({len(data) - 50} more rows)")
47
+
48
+ return "\n".join(result)
49
+ except ImportError:
50
+ return "ERROR: pandas/openpyxl not installed for Excel processing"
51
+ except Exception as e:
52
+ print(f"❌ Error al leer Excel {url}: {e}")
53
+ return f"ERROR reading Excel: {str(e)}"
54
+
55
+
56
+ def read_audio_file(url: str):
57
+ """
58
+ Intenta procesar archivos de audio.
59
+ Nota: Transcripción de audio es compleja y requiere APIs externas.
60
+ Por ahora, solo indicamos que el archivo existe.
61
+ """
62
+ try:
63
+ response = requests.head(url, timeout=10)
64
+ response.raise_for_status()
65
+
66
+ # Obtener información del archivo
67
+ content_type = response.headers.get('Content-Type', 'unknown')
68
+ content_length = response.headers.get('Content-Length', 'unknown')
69
+
70
+ return f"""⚠️ AUDIO FILE DETECTED: {url}
71
+ Content-Type: {content_type}
72
+ Size: {content_length} bytes
73
+
74
+ NOTE: Audio transcription requires external API (e.g., Whisper, Google Speech-to-Text).
75
+ This agent cannot directly process audio content.
76
+ Try to answer based on the question context."""
77
+
78
+ except Exception as e:
79
+ print(f"❌ Error al verificar audio {url}: {e}")
80
+ return f"ERROR accessing audio file: {str(e)}"
81
+
82
+
83
  def web_search(query: str):
84
  """Simula búsqueda web (puedes mejorarla con Wikipedia API)."""
85
  return f"(Simulación de búsqueda web para '{query}')"