feat(etl): извлечение прайсов по форматам (xlsx/xls/docx/pdf) и распознавание сложных страниц через Gemini Vision
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
"""Диспетчер извлечения: путь к файлу → ParsedDocument.
|
||||
|
||||
Определяет формат, читает файл в сетки и прогоняет их через общий грид-экстрактор.
|
||||
PDF с битым текстовым слоем помечается как scan_pdf — его добирает путь через Vision.
|
||||
Любой сбой чтения логируется, но не роняет обработку остального архива.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
from contracts.models import ParsedDocument # noqa: E402
|
||||
from etl.extractors import readers # noqa: E402
|
||||
from etl.extractors.grid import extract_rows_from_grid # noqa: E402
|
||||
|
||||
|
||||
def extract(path: str, use_vision: bool = True) -> ParsedDocument:
|
||||
"""Разобрать один файл прайса в структурированный ParsedDocument.
|
||||
|
||||
use_vision=False отключает добор через Gemini Vision (быстрый прогон без
|
||||
обращений к API), даже если ключ задан.
|
||||
"""
|
||||
name = Path(path).name
|
||||
fmt = readers.detect_format(path)
|
||||
doc = ParsedDocument(
|
||||
file_name=name, file_format=fmt, partner_name=readers.partner_from_name(name)
|
||||
)
|
||||
|
||||
year = readers.year_from_name(name)
|
||||
if year:
|
||||
doc.effective_date = date(year, 1, 1)
|
||||
|
||||
try:
|
||||
if fmt == "xlsx":
|
||||
grids, text = readers.xlsx_grids(path)
|
||||
elif fmt == "xls":
|
||||
grids, text = readers.xls_grids(path)
|
||||
elif fmt == "docx":
|
||||
grids, text = readers.docx_grids(path)
|
||||
elif fmt == "pdf":
|
||||
grids, text = readers.pdf_grids(path)
|
||||
if readers.is_garbled(text):
|
||||
doc.file_format = "scan_pdf"
|
||||
doc.parse_log.append("битый текстовый слой — требуется распознавание (Vision)")
|
||||
else:
|
||||
doc.parse_log.append(f"неизвестный формат: {fmt}")
|
||||
return doc
|
||||
except Exception as exc: # noqa: BLE001 — сбой чтения логируем, конвейер не роняем
|
||||
doc.parse_log.append(f"ошибка чтения: {type(exc).__name__}: {exc}")
|
||||
return doc
|
||||
|
||||
doc.raw_content = text[:200_000]
|
||||
for grid in grids:
|
||||
try:
|
||||
doc.rows.extend(extract_rows_from_grid(grid))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
doc.parse_log.append(f"ошибка разбора таблицы: {type(exc).__name__}: {exc}")
|
||||
|
||||
# Трудные PDF (скан, битый слой, нулевой разбор) добираем через Gemini Vision.
|
||||
needs_vision = use_vision and fmt == "pdf" and (doc.file_format == "scan_pdf" or not doc.rows)
|
||||
if needs_vision and os.environ.get("GEMINI_API_KEY"):
|
||||
try:
|
||||
from etl.extractors.vision import extract_with_vision
|
||||
|
||||
vision_rows = extract_with_vision(path)
|
||||
doc.rows.extend(vision_rows)
|
||||
doc.file_format = "scan_pdf"
|
||||
doc.parse_log.append(f"Vision добрал {len(vision_rows)} позиций")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
doc.parse_log.append(f"Vision не сработал: {type(exc).__name__}: {exc}")
|
||||
|
||||
if not doc.rows:
|
||||
doc.parse_log.append("позиции не извлечены")
|
||||
return doc
|
||||
Reference in New Issue
Block a user