fix: PyPDF2 → pdfplumber — сохраняет структуру таблиц в PDF
This commit is contained in:
+24
-10
@@ -1,6 +1,5 @@
|
|||||||
"""Parse service — PDF (PyPDF2), DOCX (python-docx), plain text fallback."""
|
"""Parse service — PDF (pdfplumber), DOCX (python-docx), plain text fallback."""
|
||||||
import io
|
import io
|
||||||
from PyPDF2 import PdfReader
|
|
||||||
|
|
||||||
|
|
||||||
def parse_file(filename, data):
|
def parse_file(filename, data):
|
||||||
@@ -20,15 +19,30 @@ def parse_file(filename, data):
|
|||||||
|
|
||||||
|
|
||||||
def _parse_pdf(data):
|
def _parse_pdf(data):
|
||||||
reader = PdfReader(io.BytesIO(data))
|
"""Parse PDF with pdfplumber — preserves table structure (unlike PyPDF2)."""
|
||||||
|
import pdfplumber
|
||||||
elements = []
|
elements = []
|
||||||
for page in reader.pages:
|
with pdfplumber.open(io.BytesIO(data)) as pdf:
|
||||||
text = page.extract_text()
|
for page in pdf.pages:
|
||||||
if text:
|
# Tables first — preserves column structure critical for specs
|
||||||
for line in text.split("\n"):
|
tables = page.extract_tables()
|
||||||
line = line.strip()
|
for table in tables:
|
||||||
if line:
|
if table:
|
||||||
elements.append({"type": "paragraph", "text": line, "style": ""})
|
rows = []
|
||||||
|
for row in table:
|
||||||
|
if row:
|
||||||
|
cells = [str(cell or "").strip() for cell in row]
|
||||||
|
if any(cells):
|
||||||
|
rows.append(cells)
|
||||||
|
if rows:
|
||||||
|
elements.append({"type": "table", "rows": rows})
|
||||||
|
# Remaining text as paragraphs
|
||||||
|
text = page.extract_text()
|
||||||
|
if text:
|
||||||
|
for line in text.split("\n"):
|
||||||
|
line = line.strip()
|
||||||
|
if line:
|
||||||
|
elements.append({"type": "paragraph", "text": line, "style": ""})
|
||||||
return {"status": "parsed", "element_count": len(elements), "elements": elements}
|
return {"status": "parsed", "element_count": len(elements), "elements": elements}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user