Start Agent-IA
This commit is contained in:
BIN
Python/pdf-extractor-api/__pycache__/main.cpython-314.pyc
Normal file
BIN
Python/pdf-extractor-api/__pycache__/main.cpython-314.pyc
Normal file
Binary file not shown.
63
Python/pdf-extractor-api/main.py
Normal file
63
Python/pdf-extractor-api/main.py
Normal file
@@ -0,0 +1,63 @@
|
||||
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()
|
||||
Reference in New Issue
Block a user