camelot для таблиц PDF (lattice+stream), fallback на pdfplumber, v1.27

This commit is contained in:
2026-06-17 20:26:59 +04:00
parent db8247448b
commit 7e3ea4bc4d
2 changed files with 45 additions and 7 deletions
+44 -6
View File
@@ -123,7 +123,15 @@ def _parse_doc(file_bytes: bytes) -> dict:
def _parse_pdf(file_bytes: bytes) -> dict:
result = {"elements": [], "errors": []}
import tempfile, os as _os
# Сохранить PDF во временный файл (camelot требует путь)
tmp_path = None
try:
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as tmp:
tmp.write(file_bytes)
tmp_path = tmp.name
import pdfplumber
with pdfplumber.open(io.BytesIO(file_bytes)) as pdf:
@@ -142,18 +150,48 @@ def _parse_pdf(file_bytes: bytes) -> dict:
"page": pn,
})
# Таблицы на странице
tables = page.extract_tables()
for tbl in tables:
if tbl:
# Таблицы — camelot (точнее), иначе pdfplumber
tables_found = False
try:
import camelot
# Сначала lattice (таблицы с рамками)
for flavor in ("lattice", "stream"):
try:
ctables = camelot.read_pdf(tmp_path, pages="all", flavor=flavor)
for ct in ctables:
rows = [list(ct.df.columns)] + ct.df.values.tolist()
result["elements"].append({
"type": "table",
"rows": tbl,
"page": pn,
"rows": rows,
"page": ct.page,
})
tables_found = True
except Exception:
pass
except ImportError:
result["errors"].append("camelot not installed, using pdfplumber")
except Exception as e:
result["errors"].append(f"camelot error: {e}")
# Fallback: pdfplumber таблицы если camelot ничего не нашёл
if not tables_found:
with pdfplumber.open(io.BytesIO(file_bytes)) as pdf:
for page in pdf.pages:
pn = page.page_number
tables = page.extract_tables()
for tbl in tables:
if tbl:
result["elements"].append({
"type": "table",
"rows": tbl,
"page": pn,
})
except Exception as e:
result["errors"].append(f"pdf parse error: {e}")
finally:
if tmp_path and _os.path.exists(tmp_path):
_os.unlink(tmp_path)
return result