orchestrator.py 10.7 KB
from __future__ import annotations

import logging
import os
import re

from src.rag.core.config import RAG_PDF_VLM_PARSE
from src.rag.core.errors import PdfVlmParseError
from src.rag.ingestion.loaders.base import DocumentBlock, register_loader
from src.rag.ingestion.loaders.common import enrich_blocks
from src.rag.ingestion.loaders.pdf.engine import VlmParseStats, vlm_blocks_for_pages

logger = logging.getLogger(__name__)


class PdfLoader:
    extensions = {".pdf"}

    def load(self, path: str) -> list[DocumentBlock]:
        return load_pdf(path)


def load_pdf(path: str) -> list[DocumentBlock]:
    # 单一路线:整篇 PDF 全部走 VLM 整页转写(不再区分文本/表格/图片页)。
    # VLM 对这些图文混排的产品手册最稳:图片表格、跨页、数字逐字都能正确还原。
    filename = os.path.basename(path)
    total_pages = _page_count(path)
    logger.info("[RAG] 开始解析 PDF: %s(共 %d 页,全部走 VLM 整页转写)", filename, total_pages)
    if not RAG_PDF_VLM_PARSE:
        raise PdfVlmParseError(
            "PDF 解析需要整页 VLM,但 RAG_PDF_VLM_PARSE 已关闭",
            detail={"file": filename, "total_pages": total_pages},
        )

    blocks, stats = vlm_blocks_for_pages(path, list(range(1, total_pages + 1)))
    blocks = _dedupe_blocks(blocks)
    if not blocks:
        raise RuntimeError("PDF 未提取到可索引内容。")

    # 顺序是关键:续表拼接会写跨页 page_end,标题归一会串出 title_path,
    # 两者都必须在 enrich_blocks 之前跑完——enrich_blocks 全程 setdefault,不会覆盖它们。
    blocks.sort(key=lambda b: (b.page_number or 0, b.source_offset or 0))
    blocks = _stitch_continued_tables(blocks)
    _assign_headings(blocks)
    enrich_blocks(blocks, parse_method="vlm_markdown", source_page_count=total_pages)
    _attach_vlm_stats(blocks, stats)
    logger.info(
        "[RAG] PDF 解析完成: %s, 共 %d 个块;VLM 统计: 页=%d, tokens=%d, 用时=%dms",
        filename, len(blocks), stats.page_count, stats.total_tokens, stats.duration_ms,
    )
    return blocks


def _page_count(path: str) -> int:
    import fitz

    with fitz.open(path) as doc:
        return doc.page_count


def _stitch_continued_tables(blocks: list[DocumentBlock]) -> list[DocumentBlock]:
    """跨页表格拼接:VLM 在页尾给未结束的表打了 table_continues 标记,下一张表是其延续。"""
    result: list[DocumentBlock] = []
    i = 0
    while i < len(blocks):
        block = blocks[i]
        if block.block_type == "table" and block.metadata.get("table_continues"):
            j = i + 1
            if j < len(blocks) and blocks[j].block_type == "table":
                cont = blocks[j]
                block.text = _merge_table_markdown(block.text, cont.text)
                block.metadata["page_end"] = cont.page_number or block.metadata.get("page_end")
                block.metadata["continued_table"] = True
                block.metadata.pop("table_continues", None)
                # 续表本身可能再次续页:保留下一张表的标记到合并块上
                if cont.metadata.get("table_continues"):
                    block.metadata["table_continues"] = True
                blocks.pop(j)
                continue  # 不前移 i,继续尝试与再下一张表拼接
            block.metadata.pop("table_continues", None)
        result.append(block)
        i += 1
    return result


# ---------------------------------------------------------------------------
# Heading detection(VLM 已用 # 标好层级;此处仅对未标记段落按编号体系兜底识别)
# ---------------------------------------------------------------------------

def _detect_heading(text: str) -> tuple[int, str] | None:
    """按编号体系识别标题段落。Returns (level, text) or None。"""
    if len(text) > 100 or "\n" in text.strip():
        return None
    first = text.strip()
    if not first or _looks_like_table_residual(first):
        return None
    # Exclude footnotes and notes
    if re.match(r"^(说明|注|备注|注意|提示|参考|附注|PS|ps)[::·]", first):
        return None

    # Numeric heading: "1.2.3 Title"
    match = re.match(r"^(\d+(?:\.\d+){0,4})\s+(.{2,80})$", first)
    if match:
        return (match.group(1).count(".") + 1, first)

    # Chinese numeric heading: "一、Title" / "(一)Title"
    match = re.match(r"^[((]?[一二三四五六七八九十]+[))、..]\s*(.{2,80})$", first)
    if match:
        return (1, first)

    return None


def _canonical_heading_level(text: str, fallback_level: int) -> int:
    """按编号体系归一标题层级,消除逐页独立转写造成的同级章节层级漂移。

    “一、/二、/(三)”等中文数字一级章节 → 1;“1./1.2/1.2.3”按点分段数定级;
    其余无编号标题保留 VLM 给的 markdown 层级。
    """
    first = text.strip()
    if re.match(r"^[((]?[一二三四五六七八九十]+[))、..]", first):
        return 1
    match = re.match(r"^(\d+(?:\.\d+){0,4})", first)
    if match:
        return match.group(1).count(".") + 1
    return max(1, fallback_level)


def _update_headings(headings: list[str], heading: tuple[int, str]) -> list[str]:
    level, text = heading
    next_headings = list(headings[: max(0, level - 1)])
    next_headings.append(text)
    return next_headings


def _assign_headings(blocks: list[DocumentBlock]) -> None:
    headings: list[str] = []
    for block in blocks:
        if block.block_type == "paragraph":
            # VLM 路径已显式标记 heading(任意文案);但逐页独立转写会让同级章节的 # 层级
            # 不一致(如“二、”在某页是 #、“三、”在另一页是 ##),导致 title_path 串成
            # “二 / 三”。这里按编号体系归一层级,保证全局章节结构一致。
            if block.metadata.get("content_role") == "heading" and block.metadata.get("heading_marker_level"):
                level = _canonical_heading_level(block.text.strip(), int(block.metadata.pop("heading_marker_level")))
                block.metadata["heading_level"] = level
                heading = (level, block.text.strip())
            else:
                heading = _detect_heading(block.text)
            if heading:
                headings = _update_headings(headings, heading)
                block.metadata["content_role"] = "heading"
                block.metadata["heading_level"] = heading[0]
            else:
                block.metadata.setdefault("content_role", "body")
        elif block.block_type == "table":
            pass  # Tables inherit headings from surrounding paragraphs
        # section_title / section_path 交给 enrich_blocks 从 title_path 统一生成,
        # 避免两处各写一份。table_header 同理——统一走 common.markdown_table_header(list[str])。
        block.title_path = " / ".join(headings)
        if block.block_type == "table":
            block.metadata["content_role"] = "table"
            block.metadata["table_id"] = f"p{block.page_number}_t{(block.metadata.get('table_index', 0)) + 1}"
            if block.title_path:
                block.title_path += f" / P{block.page_number} 表{(block.metadata.get('table_index', 0)) + 1}"
            else:
                block.title_path = f"P{block.page_number} 表{(block.metadata.get('table_index', 0)) + 1}"


# ---------------------------------------------------------------------------
# Deduplication
# ---------------------------------------------------------------------------

def _dedupe_blocks(blocks: list[DocumentBlock]) -> list[DocumentBlock]:
    seen_tables: set[tuple[int | None, str]] = set()
    deduped: list[DocumentBlock] = []
    for block in blocks:
        if block.block_type == "table":
            signature = (block.page_number, _table_signature(block.text))
            if signature in seen_tables:
                continue
            seen_tables.add(signature)
        deduped.append(block)
    return deduped


def _table_signature(text: str) -> str:
    return re.sub(r"\s+", "", text or "").lower()


# ---------------------------------------------------------------------------
# Cross-page table merging(供 _stitch_continued_tables 拼接 VLM 续表)
# ---------------------------------------------------------------------------

def _merge_table_markdown(previous: str, current: str) -> str:
    previous_rows = _table_rows(previous)
    current_rows = _table_rows(current)
    if len(current_rows) <= 2:
        return previous
    if current_rows[0] == previous_rows[0]:
        return "\n".join([*previous_rows, *current_rows[2:]])
    else:
        return "\n".join([*previous_rows, current_rows[0], *current_rows[2:]])


# ---------------------------------------------------------------------------
# Table utility
# ---------------------------------------------------------------------------

def _table_rows(markdown: str) -> list[str]:
    return [line.strip() for line in markdown.splitlines() if line.strip().startswith("|")]




# ---------------------------------------------------------------------------
# Text helpers
# ---------------------------------------------------------------------------

def _looks_like_table_residual(text: str) -> bool:
    compact = re.sub(r"\s+", "", text)
    return len(compact) <= 2


# ---------------------------------------------------------------------------
# Loader metadata
# ---------------------------------------------------------------------------

# 文档级 VLM 统计键(每个块都带同一份值,便于 service 落库;切块时会被剥离,不污染分片)
VLM_STAT_KEYS = (
    "parse_engine", "vlm_page_count", "vlm_total_tokens",
    "vlm_input_tokens", "vlm_output_tokens", "vlm_image_tokens", "vlm_duration_ms",
)


def _attach_vlm_stats(blocks: list[DocumentBlock], stats: VlmParseStats) -> None:
    """只写文档级 VLM 统计。其余引擎层字段由 enrich_blocks 统一补齐。"""
    doc_stats = {
        "parse_engine": "vlm",
        "vlm_page_count": stats.page_count,
        "vlm_total_tokens": stats.total_tokens,
        "vlm_input_tokens": stats.input_tokens,
        "vlm_output_tokens": stats.output_tokens,
        "vlm_image_tokens": stats.image_tokens,
        "vlm_duration_ms": stats.duration_ms,
    }
    for block in blocks:
        for key, value in doc_stats.items():
            block.metadata.setdefault(key, value)


def doc_vlm_stats(blocks: list[DocumentBlock]) -> dict[str, int]:
    """从解析出的 blocks 里取出文档级 VLM 统计(token/页数/耗时),供 service 落库。"""
    for block in blocks:
        if block.metadata.get("parse_engine") == "vlm":
            return {key: block.metadata.get(key) for key in VLM_STAT_KEYS}
    return {}




register_loader(PdfLoader())