diff --git a/etl/extractors/__init__.py b/etl/extractors/__init__.py index 048d100..e778814 100644 --- a/etl/extractors/__init__.py +++ b/etl/extractors/__init__.py @@ -18,6 +18,11 @@ 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 +# Порог «подозрительно мало строк на страницу» — ниже него PDF добираем через Vision. +_VISION_MIN_ROWS_PER_PAGE = 12 +# Документы крупнее не отправляем в Vision (экономия времени и квоты). +_VISION_MAX_PAGES = 40 + def extract(path: str, use_vision: bool = True) -> ParsedDocument: """Разобрать один файл прайса в структурированный ParsedDocument. @@ -61,18 +66,33 @@ def extract(path: str, use_vision: bool = True) -> ParsedDocument: 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 + # Трудные PDF добираем через Gemini Vision: скан, битый слой, нулевой или + # подозрительно низкий выход строк (мисматч колонок на испорченной вёрстке). + # Большие документы пропускаем ради экономии — это фиксируется в логе, не молча. + if use_vision and fmt == "pdf" and os.environ.get("GEMINI_API_KEY"): + pages = readers.pdf_page_count(path) + low_yield = pages > 0 and len(doc.rows) < pages * _VISION_MIN_ROWS_PER_PAGE + if doc.file_format == "scan_pdf" or not doc.rows or low_yield: + if pages > _VISION_MAX_PAGES: + doc.parse_log.append( + f"Vision пропущен: {pages} стр. больше лимита {_VISION_MAX_PAGES}" + ) + else: + 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}") + vision_rows = extract_with_vision(path, max_pages=_VISION_MAX_PAGES) + if len(vision_rows) > len(doc.rows): + # Vision полнее нативного разбора — заменяем, а не дублируем. + doc.rows = vision_rows + doc.file_format = "scan_pdf" + doc.parse_log.append(f"Vision: {len(vision_rows)} позиций (заменил разбор)") + else: + 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("позиции не извлечены") diff --git a/etl/extractors/grid.py b/etl/extractors/grid.py index d657248..9e11a6f 100644 --- a/etl/extractors/grid.py +++ b/etl/extractors/grid.py @@ -97,16 +97,23 @@ def _assign_columns(grid: Grid, header_idx: int): price_cols[c] = fallback.pop(0) if fallback else f"extra_{c}" # --- колонка названия: явный заголовок, иначе самая кириллическая --- + # Колонки кода/индекса исключаем заранее: иначе ключ «услуг» из _NAME_KEYS ловит + # заголовок «Код услуги» и колонка кодов ошибочно становится колонкой названий. + def _is_code_or_index(c: int) -> bool: + return any(k in header[c].lower() for k in _CODE_HEADER_KEYS + _INDEX_HEADER_KEYS) + name_col = next( ( c for c in range(ncol) - if c not in price_cols and any(k in header[c].lower() for k in _NAME_KEYS) + if c not in price_cols + and not _is_code_or_index(c) + and any(k in header[c].lower() for k in _NAME_KEYS) ), None, ) if name_col is None: - candidates = [c for c in range(ncol) if c not in price_cols] + candidates = [c for c in range(ncol) if c not in price_cols and not _is_code_or_index(c)] name_col = max(candidates, key=lambda c: _cyrillic_score(sample, c)) if candidates else 0 # --- колонка кода: заголовок «Код»/«тарификатор» или код-подобные значения --- diff --git a/etl/extractors/readers.py b/etl/extractors/readers.py index ad34f6c..40c9a77 100644 --- a/etl/extractors/readers.py +++ b/etl/extractors/readers.py @@ -127,6 +127,14 @@ def pdf_grids(path: str) -> tuple[list[Grid], str]: return [grid], "\n".join(texts) +def pdf_page_count(path: str) -> int: + """Число страниц PDF — нужно для оценки выхода строк и стоимости Vision.""" + import pdfplumber + + with pdfplumber.open(path) as pdf: + return len(pdf.pages) + + def is_garbled(text: str, min_letters: int = 200) -> bool: """Битый текстовый слой: мало кириллицы или много латиницы-мусора. diff --git a/etl/extractors/vision.py b/etl/extractors/vision.py index bc2fe6f..d5f19b0 100644 --- a/etl/extractors/vision.py +++ b/etl/extractors/vision.py @@ -70,8 +70,14 @@ def _parse_response(text: str) -> list[RawRow]: return rows -def extract_with_vision(path: str, max_pages: int = 12, dpi: int = 140) -> list[RawRow]: - """Извлечь позиции из PDF через Gemini Vision. Возвращает список RawRow.""" +def extract_with_vision(path: str, max_pages: int = 40, dpi: int = 140) -> list[RawRow]: + """Извлечь позиции из PDF через Gemini Vision. Возвращает список RawRow. + + Страницы распознаются по одной. При превышении квоты (429) делается пауза и + повтор — большой документ не должен срываться из-за лимита запросов в минуту. + """ + import time + api_key = os.environ.get("GEMINI_API_KEY") if not api_key: raise RuntimeError("нет GEMINI_API_KEY в окружении") @@ -85,10 +91,17 @@ def extract_with_vision(path: str, max_pages: int = 12, dpi: int = 140) -> list[ rows: list[RawRow] = [] for png in _render_pages(path, max_pages, dpi): - response = client.models.generate_content( - model=model, - contents=[types.Part.from_bytes(data=png, mime_type="image/png"), _PROMPT], - config=config, - ) - rows.extend(_parse_response(response.text)) + part = types.Part.from_bytes(data=png, mime_type="image/png") + for attempt in range(6): + try: + response = client.models.generate_content( + model=model, contents=[part, _PROMPT], config=config + ) + rows.extend(_parse_response(response.text)) + break + except Exception as exc: # пауза и повтор при превышении квоты (429) + if ("RESOURCE_EXHAUSTED" in str(exc) or "429" in str(exc)) and attempt < 5: + time.sleep(15) + continue + raise return rows diff --git a/infra/deploy/Caddyfile b/infra/deploy/Caddyfile index f93f81e..b4e105b 100644 --- a/infra/deploy/Caddyfile +++ b/infra/deploy/Caddyfile @@ -15,6 +15,10 @@ med.secondbrain.tools { root * /srv file_server } + handle /day2* { + root * /srv + file_server + } handle { root * /web file_server diff --git a/pitch/day2/index.html b/pitch/day2/index.html new file mode 100644 index 0000000..4e54e8e --- /dev/null +++ b/pitch/day2/index.html @@ -0,0 +1,182 @@ + + +
+ + + +