ingest_chunking.py 13.7 KB
"""长文档摄入的结构化分块器(纯函数,无 LLM 依赖)。

切块触发不分文件类型(由调用方按 raw_content 字符数判断),
切分锚点按来源格式路由:

- pdf / ppt / pptx:VLM 解析产物自带 ``## Page N`` 页标记,按页贪心装箱,页是原子单位;
- xlsx / xls:以 ``--- Sheet: xxx ---`` 为天然切点,超大 Sheet 按行组切并重复表头;
- md / txt / docx 及其他:按标题层级切,小节贪心合并连续兄弟;无标题退化为段落切分。

核心不变式:所有 chunk 的 [char_start, char_end) 首尾相接、不重叠不遗漏,
按序拼接 text 恰好还原全文——这是后续「页面认领块」覆盖审计成立的基础。
大表行组块需要重复的表头等补充上下文放在 context_prefix,不计入原文切片。
"""

from __future__ import annotations

import re
from dataclasses import dataclass, field
from typing import Any, Sequence

# 切块尺寸旋钮集中在 config.py(可 env 覆盖),此处按内部短名沿用,算法逻辑不变。
# CHUNK_TARGET_CHARS:贪心装箱收口点;CHUNK_MAX_CHARS:硬上限,超了才强制细分;
# PAGE_SOURCE_MAX_CHARS:单页认领原文上限,超限回喂 Planner 拆页。
from config import (
    INGEST_CHUNK_TARGET_CHARS as CHUNK_TARGET_CHARS,
    INGEST_CHUNK_MAX_CHARS as CHUNK_MAX_CHARS,
    INGEST_PAGE_SOURCE_MAX_CHARS as PAGE_SOURCE_MAX_CHARS,
)

_PAGE_MARKER_RE = re.compile(r"^## Page (\d+)\s*$")
_SHEET_MARKER_RE = re.compile(r"^--- Sheet: (.*) ---\s*$")
_HEADING_RE = re.compile(r"^(#{1,6})\s+(.*\S)\s*$")


@dataclass(frozen=True)
class DocChunk:
    chunk_id: int          # 从 1 编号
    heading_path: str      # 如 "价格疑虑 > 条目 11–条目 21" / "Page 12–25" / "Sheet: 报价表(第2段)"
    text: str              # 原文切片(逐字节等于 raw_content[char_start:char_end])
    char_start: int
    char_end: int
    context_prefix: str = ""  # 拼 prompt 时补在切片前的上下文(如续表重复的表头),不属于原文

    @property
    def prompt_text(self) -> str:
        return f"{self.context_prefix}{self.text}" if self.context_prefix else self.text


@dataclass
class _Atom:
    """不可再合并判定前的最小切分单元:一段连续原文 + 语义标签。"""
    start: int
    end: int
    label: str
    context_prefix: str = ""


def chunk_document(
    raw_content: str, file_format: str, stats: dict | None = None
) -> list[DocChunk]:
    """把整篇解析产物切成无缝覆盖的块序列。

    stats 为可选**只写出参**:传入 dict 时写回切块中间量
    (`atoms` 按锚点切出的原子数 → `atoms_after_subdivide` 细分后 → `chunks` 贪心装箱成的块数),
    供调用方打日志。不传则行为与返回值完全不变(保持本模块无日志依赖的纯函数性质)。
    """
    if stats is not None:
        stats.update({"atoms": 0, "atoms_after_subdivide": 0, "chunks": 0})
    if not raw_content:
        return []
    fmt = (file_format or "").lower().lstrip(".")
    if fmt in ("pdf", "ppt", "pptx"):
        atoms = _split_by_line_marker(raw_content, _PAGE_MARKER_RE, label_fmt="Page {0}")
    elif fmt in ("xlsx", "xls"):
        atoms = _split_by_line_marker(raw_content, _SHEET_MARKER_RE, label_fmt="Sheet: {0}")
    else:
        atoms = _split_by_headings(raw_content)
    if not atoms:
        atoms = [_Atom(0, len(raw_content), "")]
    atom_count = len(atoms)

    atoms = _subdivide_oversized(raw_content, atoms, excel=fmt in ("xlsx", "xls"))
    chunks = _pack_atoms(raw_content, atoms)
    _assert_seamless(raw_content, chunks)
    if stats is not None:
        stats.update({
            "atoms": atom_count,
            "atoms_after_subdivide": len(atoms),
            "chunks": len(chunks),
        })
    return chunks


def find_uncovered_chunks(
    chunks: Sequence[DocChunk], pages: Sequence[dict[str, Any]]
) -> list[DocChunk]:
    """全部块 − 所有页面 source_chunks 并集 = 没有任何 Writer 会读到的原文块。"""
    claimed: set[int] = set()
    for page in pages:
        for cid in page.get("source_chunks") or []:
            try:
                claimed.add(int(cid))
            except (TypeError, ValueError):
                continue
    return [c for c in chunks if c.chunk_id not in claimed]


def select_chunks(chunks: Sequence[DocChunk], chunk_ids: Sequence[Any]) -> list[DocChunk]:
    """按认领的 chunk_id 取块,保持原文顺序,容忍字符串数字与非法编号。"""
    wanted: set[int] = set()
    for cid in chunk_ids or []:
        try:
            wanted.add(int(cid))
        except (TypeError, ValueError):
            continue
    return [c for c in chunks if c.chunk_id in wanted]


def format_chunks_for_prompt(chunks: Sequence[DocChunk]) -> str:
    """Writer/补充轮用:按序拼接块原文,每块前标注编号与位置。"""
    parts = []
    for c in chunks:
        header = f"【块 {c.chunk_id}:{c.heading_path}】" if c.heading_path else f"【块 {c.chunk_id}】"
        parts.append(f"{header}\n{c.prompt_text.strip()}")
    return "\n\n".join(parts)


# ==================================================================================
# 第一步:按格式路由切出原子(页 / Sheet / 标题小节)
# ==================================================================================

def _line_spans(text: str) -> list[tuple[int, int]]:
    """每行的 [start, end) 偏移(end 含行尾换行符),保证无缝覆盖。"""
    spans = []
    pos = 0
    n = len(text)
    while pos < n:
        nl = text.find("\n", pos)
        end = n if nl == -1 else nl + 1
        spans.append((pos, end))
        pos = end
    return spans


def _split_by_line_marker(text: str, marker_re: re.Pattern, label_fmt: str) -> list[_Atom]:
    """按整行标记(## Page N / --- Sheet: x ---)切原子;标记行归属其后的原子。"""
    atoms: list[_Atom] = []
    cur_start = 0
    cur_label = ""
    for start, end in _line_spans(text):
        m = marker_re.match(text[start:end].rstrip("\n"))
        if m:
            if start > cur_start:
                atoms.append(_Atom(cur_start, start, cur_label))
            cur_start = start
            cur_label = label_fmt.format(m.group(1))
    if cur_start < len(text):
        atoms.append(_Atom(cur_start, len(text), cur_label))
    return atoms


def _split_by_headings(text: str) -> list[_Atom]:
    """按 ATX 标题切原子(每个标题到下一标题之间为一个原子),跳过代码围栏内的 #。

    heading_path 为标题栈面包屑(如 "价格疑虑 > 条目 3")。
    """
    atoms: list[_Atom] = []
    stack: list[tuple[int, str]] = []  # (level, title)
    cur_start = 0
    cur_label = ""
    in_fence = False
    for start, end in _line_spans(text):
        line = text[start:end].rstrip("\n")
        if line.lstrip().startswith("```"):
            in_fence = not in_fence
            continue
        if in_fence:
            continue
        m = _HEADING_RE.match(line)
        if not m:
            continue
        if start > cur_start:
            atoms.append(_Atom(cur_start, start, cur_label))
        level = len(m.group(1))
        title = m.group(2).strip()
        while stack and stack[-1][0] >= level:
            stack.pop()
        stack.append((level, title))
        cur_start = start
        cur_label = " > ".join(t for _, t in stack)
    if cur_start < len(text):
        atoms.append(_Atom(cur_start, len(text), cur_label))
    return atoms


# ==================================================================================
# 第二步:超限原子细分(段落切分 + 表格保护 / 大表行组切分带表头)
# ==================================================================================

def _subdivide_oversized(text: str, atoms: list[_Atom], *, excel: bool) -> list[_Atom]:
    out: list[_Atom] = []
    for atom in atoms:
        if atom.end - atom.start <= CHUNK_MAX_CHARS:
            out.append(atom)
        elif excel:
            out.extend(_split_excel_atom(text, atom))
        else:
            out.extend(_split_by_paragraphs(text, atom))
    return out


def _is_table_line(line: str) -> bool:
    return line.lstrip().startswith("|")


def _paragraph_units(text: str, start: int, end: int) -> list[tuple[int, int]]:
    """把 [start, end) 切成不可分割单元:连续表格行为一个单元(表格保护),
    其余按空行分段;单元区间无缝覆盖整段。"""
    units: list[tuple[int, int]] = []
    unit_start = start
    prev_kind = None  # "table" | "text" | "blank"
    for ls, le in _line_spans(text[start:end]):
        abs_s, abs_e = start + ls, start + le
        line = text[abs_s:abs_e].rstrip("\n")
        if _is_table_line(line):
            kind = "table"
        elif not line.strip():
            kind = "blank"
        else:
            kind = "text"
        # 段落边界:表格区 ↔ 非表格区切换,或空行后接新内容
        boundary = (
            prev_kind is not None
            and abs_s > unit_start
            and (
                (kind == "table") != (prev_kind == "table")
                if kind != "blank" and prev_kind != "blank"
                else (prev_kind == "blank" and kind != "blank")
            )
        )
        if boundary:
            units.append((unit_start, abs_s))
            unit_start = abs_s
        if kind != "blank" or prev_kind != "blank":
            prev_kind = kind
    if unit_start < end:
        units.append((unit_start, end))
    return units


def _split_by_paragraphs(text: str, atom: _Atom) -> list[_Atom]:
    """超限原子按段落单元贪心装箱(表格单元不可切分)。"""
    units = _paragraph_units(text, atom.start, atom.end)
    pieces: list[_Atom] = []
    cur_start = atom.start
    cur_end = atom.start
    part_no = 1

    def close(next_start: int) -> None:
        nonlocal cur_start, cur_end, part_no
        if cur_end > cur_start:
            label = f"{atom.label}(第{part_no}段)" if atom.label else f"(第{part_no}段)"
            pieces.append(_Atom(cur_start, cur_end, label))
            part_no += 1
        cur_start = cur_end = next_start

    for us, ue in units:
        if cur_end > cur_start and (ue - cur_start) > CHUNK_TARGET_CHARS:
            close(us)
        cur_end = ue
    close(atom.end)
    return pieces


def _split_excel_atom(text: str, atom: _Atom) -> list[_Atom]:
    """超大 Sheet 按行组切:每个行组块的 context_prefix 重复 Sheet 标记 + 表头两行,
    保证块内自带列语义("表格不可切"规则对大表的正确特化)。"""
    body = text[atom.start:atom.end]
    lines = _line_spans(body)
    # 找到 markdown 表格的表头两行(首个表格行 + 其后的分隔行)
    header_prefix = ""
    header_end_idx = -1
    for i, (ls, le) in enumerate(lines):
        if _is_table_line(body[ls:le]):
            if i + 1 < len(lines) and _is_table_line(body[lines[i + 1][0]:lines[i + 1][1]]):
                header_prefix = body[ls:lines[i + 1][1]]
                header_end_idx = i + 1
            break
    if header_end_idx == -1:
        # 非表格型超大 Sheet,退化段落切分
        return _split_by_paragraphs(text, atom)

    sheet_tag = f"{atom.label}\n" if atom.label else ""
    pieces: list[_Atom] = []
    cur_start = atom.start
    part_no = 1
    # 表头及其之前的内容归第一块,后续行组从表头后开始装箱
    for i in range(header_end_idx + 1, len(lines)):
        ls, _le = lines[i]
        abs_s = atom.start + ls
        if abs_s - cur_start > CHUNK_TARGET_CHARS:
            prefix = "" if part_no == 1 else f"{sheet_tag}(续表,表头如下)\n{header_prefix}"
            pieces.append(_Atom(cur_start, abs_s, f"{atom.label}(第{part_no}段)", prefix))
            part_no += 1
            cur_start = abs_s
    prefix = "" if part_no == 1 else f"{sheet_tag}(续表,表头如下)\n{header_prefix}"
    pieces.append(_Atom(cur_start, atom.end, f"{atom.label}(第{part_no}段)", prefix))
    return pieces


# ==================================================================================
# 第三步:贪心装箱成块
# ==================================================================================

def _pack_atoms(text: str, atoms: list[_Atom]) -> list[DocChunk]:
    chunks: list[DocChunk] = []
    group: list[_Atom] = []

    def close() -> None:
        if not group:
            return
        start, end = group[0].start, group[-1].end
        first, last = group[0].label, group[-1].label
        if first and last and first != last:
            label = f"{first}–{last}"
        else:
            label = first or last
        chunks.append(DocChunk(
            chunk_id=len(chunks) + 1,
            heading_path=label,
            text=text[start:end],
            char_start=start,
            char_end=end,
            context_prefix=group[0].context_prefix,
        ))
        group.clear()

    for atom in atoms:
        # 带补充前缀的原子(大表行组)必须开新块,避免表头前缀落到块中间
        if group and (
            atom.context_prefix
            or atom.end - group[0].start > CHUNK_TARGET_CHARS
        ):
            close()
        group.append(atom)
    close()
    return chunks


def _assert_seamless(text: str, chunks: list[DocChunk]) -> None:
    """无缝不变式:块区间首尾相接且覆盖全文。违反说明分块器有 bug,宁可炸掉也不静默丢文。"""
    pos = 0
    for c in chunks:
        if c.char_start != pos or c.text != text[c.char_start:c.char_end]:
            raise AssertionError(
                f"分块不连续:chunk_id={c.chunk_id} 期望起点 {pos},实际 [{c.char_start}, {c.char_end})"
            )
        pos = c.char_end
    if pos != len(text):
        raise AssertionError(f"分块未覆盖全文:终点 {pos} != 全文长度 {len(text)}")