from fastapi import FastAPI, UploadFile, File import pdfplumber import docx import io import re app = FastAPI() # 🔥 CONFIGURACIÓN CLAVE MAX_PAGES = 3 MAX_CHARS = 15000 @app.post("/extract-text/") async def extract_text(file: UploadFile = File(...)): content = await file.read() filename = file.filename.lower() if filename.endswith(".pdf"): text = extract_pdf(content) elif filename.endswith(".docx"): text = extract_docx(content) else: return {"error": "Formato no soportado"} return {"text": clean_text(text)} # ✅ PDF (eficiente en memoria) def extract_pdf(content): text = "" with pdfplumber.open(io.BytesIO(content)) as pdf: pages = min(len(pdf.pages), MAX_PAGES) for i in range(pages): page = pdf.pages[i] extracted = page.extract_text() if extracted: text += extracted + "\n" # 🔥 cortar si ya es muy grande if len(text) > MAX_CHARS: break return text[:MAX_CHARS] # ✅ DOCX def extract_docx(content): doc = docx.Document(io.BytesIO(content)) text = "\n".join([p.text for p in doc.paragraphs]) return text[:MAX_CHARS] # ✅ Limpieza estándar def clean_text(text): text = re.sub(r'\n+', '\n', text) text = re.sub(r'\s+', ' ', text) return text.strip()