File size: 14,091 Bytes
b7934cd | 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 | """
Document Processor - Extracts text from PDF, DOCX, TXT, and IMAGES (via Groq Vision).
Supports scanned PDFs and photos of documents.
"""
import os
import base64
from typing import List
class DocumentProcessor:
"""Process various document formats and extract text for RAG indexing."""
SUPPORTED_FORMATS = [".pdf", ".txt", ".docx", ".doc", ".jpg", ".jpeg", ".png", ".webp"]
IMAGE_FORMATS = [".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp"]
@staticmethod
def extract_text(file_path: str, groq_api_key: str = None) -> str:
"""Extract text from a file based on its extension.
For images and scanned PDFs, uses Groq Vision API.
"""
ext = os.path.splitext(file_path)[1].lower()
if ext in DocumentProcessor.IMAGE_FORMATS:
if not groq_api_key:
raise ValueError("Se necesita API key de Groq para procesar imágenes")
return DocumentProcessor._extract_image(file_path, groq_api_key)
elif ext == ".pdf":
return DocumentProcessor._extract_pdf(file_path, groq_api_key)
elif ext == ".txt":
return DocumentProcessor._extract_txt(file_path)
elif ext in [".docx", ".doc"]:
return DocumentProcessor._extract_docx(file_path)
else:
raise ValueError(f"Formato no soportado: {ext}")
@staticmethod
def _extract_image(file_path: str, groq_api_key: str) -> str:
"""Extract text from an image using Groq Vision (Llama 4 Scout)."""
try:
from groq import Groq
# Read and encode image
with open(file_path, "rb") as f:
image_data = f.read()
base64_image = base64.b64encode(image_data).decode("utf-8")
# Detect MIME type
ext = os.path.splitext(file_path)[1].lower()
mime_map = {
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".webp": "image/webp",
".gif": "image/gif",
".bmp": "image/bmp",
}
mime_type = mime_map.get(ext, "image/jpeg")
# Call Groq Vision API
client = Groq(api_key=groq_api_key)
response = client.chat.completions.create(
model="meta-llama/llama-4-scout-17b-16e-instruct",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": (
"Extraé TODO el texto de esta imagen de documento exactamente como aparece. "
"Incluí todos los detalles: nombres, fechas, experiencia laboral, educación, "
"habilidades, idiomas, certificaciones, datos de contacto, y cualquier otra "
"información. Mantené la estructura original. Si hay tablas, extraé el contenido. "
"Respondé SOLO con el texto extraído, sin comentarios adicionales."
),
},
{
"type": "image_url",
"image_url": {
"url": f"data:{mime_type};base64,{base64_image}"
},
},
],
}
],
max_tokens=4096,
temperature=0.1,
)
text = response.choices[0].message.content
if text and text.strip():
return text.strip()
else:
raise ValueError("No se pudo extraer texto de la imagen")
except ImportError:
raise ValueError("Instala el paquete 'groq': pip install groq")
except Exception as e:
if "groq" in str(type(e).__module__).lower():
raise ValueError(f"Error de Groq Vision API: {e}")
raise ValueError(f"Error procesando imagen: {e}")
@staticmethod
def _extract_pdf(file_path: str, groq_api_key: str = None) -> str:
"""Extract text from PDF. Tries 3 methods + Vision API for scanned PDFs."""
text = ""
# Method 1: PyPDF (fast, works with text PDFs)
try:
from pypdf import PdfReader
reader = PdfReader(file_path)
for page in reader.pages:
page_text = page.extract_text()
if page_text:
text += page_text + "\n"
if text.strip() and len(text.strip()) > 50:
return text.strip()
except Exception:
pass
# Method 2: pdfplumber (better with complex layouts)
try:
import pdfplumber
text = ""
with pdfplumber.open(file_path) as pdf:
for page in pdf.pages:
page_text = page.extract_text()
if page_text:
text += page_text + "\n"
# Also try extracting tables
try:
tables = page.extract_tables()
for table in tables:
for row in table:
if row:
row_text = " | ".join(
str(cell).strip() for cell in row if cell
)
if row_text:
text += row_text + "\n"
except Exception:
pass
if text.strip() and len(text.strip()) > 50:
return text.strip()
except Exception:
pass
# Method 3: PyMuPDF / fitz (handles more PDF types)
try:
import fitz
doc = fitz.open(file_path)
fitz_text = ""
for page in doc:
page_text = page.get_text()
if page_text:
fitz_text += page_text + "\n"
doc.close()
if fitz_text.strip() and len(fitz_text.strip()) > 50:
return fitz_text.strip()
except Exception:
pass
# Method 4: Vision AI - render PDF pages as images and read with Llama Vision
if groq_api_key:
try:
return DocumentProcessor._extract_pdf_via_vision(
file_path, groq_api_key
)
except Exception as vision_err:
# If vision also fails, give detailed error
pass
# Last resort
if text.strip():
return text.strip()
raise ValueError(
"No se pudo extraer texto del PDF. "
"Puede ser un PDF escaneado. Intenta subir una imagen/captura del documento."
)
@staticmethod
def _extract_pdf_via_vision(file_path: str, groq_api_key: str) -> str:
"""Extract text from a scanned PDF by converting pages to images and using Vision."""
try:
# Try using fitz (PyMuPDF) to convert PDF pages to images
import fitz # PyMuPDF
doc = fitz.open(file_path)
all_text = []
for page_num in range(min(len(doc), 5)): # Max 5 pages
page = doc[page_num]
# Render page as image
mat = fitz.Matrix(2, 2) # 2x zoom for better quality
pix = page.get_pixmap(matrix=mat)
img_bytes = pix.tobytes("png")
# Use Vision API
base64_image = base64.b64encode(img_bytes).decode("utf-8")
from groq import Groq
client = Groq(api_key=groq_api_key)
response = client.chat.completions.create(
model="meta-llama/llama-4-scout-17b-16e-instruct",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": (
f"Página {page_num + 1}. Extraé TODO el texto de esta página "
"exactamente como aparece. Incluí todos los detalles. "
"Respondé SOLO con el texto extraído."
),
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{base64_image}"
},
},
],
}
],
max_tokens=4096,
temperature=0.1,
)
page_text = response.choices[0].message.content
if page_text and page_text.strip():
all_text.append(page_text.strip())
doc.close()
if all_text:
return "\n\n".join(all_text)
except ImportError:
# PyMuPDF not installed, try converting via PIL
pass
except Exception:
pass
# If PyMuPDF conversion failed, try reading the raw PDF as image
# (some PDFs are essentially single-page images)
try:
with open(file_path, "rb") as f:
pdf_bytes = f.read()
base64_pdf = base64.b64encode(pdf_bytes).decode("utf-8")
from groq import Groq
client = Groq(api_key=groq_api_key)
response = client.chat.completions.create(
model="meta-llama/llama-4-scout-17b-16e-instruct",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": (
"Extraé TODO el texto de este documento. "
"Incluí nombres, fechas, experiencia, skills. "
"Respondé SOLO con el texto extraído."
),
},
{
"type": "image_url",
"image_url": {
"url": f"data:application/pdf;base64,{base64_pdf}"
},
},
],
}
],
max_tokens=4096,
temperature=0.1,
)
text = response.choices[0].message.content
if text and text.strip():
return text.strip()
except Exception:
pass
raise ValueError("No se pudo extraer texto del PDF escaneado")
@staticmethod
def _extract_txt(file_path: str) -> str:
"""Extract text from a plain text file."""
encodings = ["utf-8", "latin-1", "cp1252"]
for encoding in encodings:
try:
with open(file_path, "r", encoding=encoding) as f:
return f.read().strip()
except (UnicodeDecodeError, UnicodeError):
continue
raise ValueError("No se pudo leer el archivo de texto")
@staticmethod
def _extract_docx(file_path: str) -> str:
"""Extract text from a Word document."""
try:
from docx import Document
doc = Document(file_path)
paragraphs = []
for para in doc.paragraphs:
if para.text.strip():
paragraphs.append(para.text.strip())
# Also extract from tables
for table in doc.tables:
for row in table.rows:
row_text = " | ".join(
cell.text.strip() for cell in row.cells if cell.text.strip()
)
if row_text:
paragraphs.append(row_text)
return "\n".join(paragraphs)
except Exception as e:
raise ValueError(f"No se pudo leer el archivo DOCX: {e}")
@staticmethod
def chunk_text(
text: str, chunk_size: int = 400, overlap: int = 80
) -> List[str]:
"""Split text into overlapping chunks for embedding."""
if not text or not text.strip():
return []
paragraphs = [p.strip() for p in text.split("\n") if p.strip()]
full_text = "\n".join(paragraphs)
words = full_text.split()
if len(words) <= chunk_size:
return [full_text]
chunks = []
start = 0
while start < len(words):
end = min(start + chunk_size, len(words))
chunk = " ".join(words[start:end])
if chunk.strip():
chunks.append(chunk.strip())
if end >= len(words):
break
start += chunk_size - overlap
return chunks
@staticmethod
def extract_key_info(text: str) -> dict:
"""Extract basic key information from document text."""
info = {
"has_email": False,
"has_phone": False,
"word_count": len(text.split()),
"line_count": len(text.split("\n")),
}
import re
if re.search(r"[\w.+-]+@[\w-]+\.[\w.-]+", text):
info["has_email"] = True
if re.search(r"[\+]?[\d\s\-\(\)]{7,15}", text):
info["has_phone"] = True
return info
|