chunk.py 8.8 KB
"""按 token 分块,保留 Markdown 章节路径。

v1 的两个问题:
1. 按**字符**数切,对中英混排不准,且和模型上下文预算对不上。
2. "标题一变就强制 flush",导致一份 63KB 的需求文档被切成 79 块,其中大量
   只有一两行的碎片。碎片块既召回不准,又白白多花一次 LLM 抽取调用。

这里改成:按 token 累积;章节切换时只有在当前块已达 MIN_CHUNK_TOKENS 时才断开,
否则继续并入 —— 短小的子章节会自然地和相邻内容合并。表格与代码块不切断。
"""
from __future__ import annotations
import re

from ..core.llm import count_tokens

_HEADING_RE = re.compile(r"^(#{1,6})\s+(.*)$")
_FENCE_RE = re.compile(r"^\s*(```|~~~)")
_TABLE_ROW_RE = re.compile(r"^\s*\|.*\|\s*$")
# 中文句末标点优先,其次英文
_SENT_SPLIT = re.compile(r"(?<=[。!?;!?;\n])")


def _blocks(text: str) -> list[tuple[str, str, str]]:
    """把文本拆成 (heading_path, kind, block_text)。kind ∈ para|table|code。"""
    lines = text.splitlines()
    heading_stack: list[str] = []
    out: list[tuple[str, str, str]] = []
    buf: list[str] = []
    kind = "para"
    in_code = False
    in_table = False

    def flush():
        nonlocal buf, kind, in_table
        if buf:
            joined = "\n".join(buf).strip()
            if joined:
                out.append((" > ".join(h for h in heading_stack if h), kind, joined))
            buf = []
        kind = "para"
        in_table = False

    for line in lines:
        if _FENCE_RE.match(line):
            if in_code:
                buf.append(line)
                flush()
                in_code = False
            else:
                flush()
                in_code = True
                kind = "code"
                buf.append(line)
            continue
        if in_code:
            buf.append(line)
            continue

        stripped = line.strip()
        m = _HEADING_RE.match(stripped)
        if m:
            flush()
            level = len(m.group(1))
            title = m.group(2).strip()
            heading_stack = heading_stack[: level - 1]
            while len(heading_stack) < level - 1:
                heading_stack.append("")
            heading_stack.append(title)
            continue

        is_table_row = bool(_TABLE_ROW_RE.match(line))
        if is_table_row and not in_table:
            flush()
            in_table = True
            kind = "table"
        elif in_table and not is_table_row:
            flush()

        if stripped == "":
            if not in_table:
                flush()
            continue
        buf.append(line)
    if in_code and buf:
        flush()
    flush()
    return out


def _prefix_within(text: str, max_tokens: int) -> int:
    """二分出最长的、token 数不超过 max_tokens 的前缀长度(字符数)。"""
    lo, hi = 1, len(text)
    while lo < hi:
        mid = (lo + hi + 1) // 2
        if count_tokens(text[:mid]) <= max_tokens:
            lo = mid
        else:
            hi = mid - 1
    return lo


def _hard_split(text: str, max_tokens: int) -> list[str]:
    """无标点可切时按 token 预算硬切。必须按预算切,不能简单对半分 ——
    对半分只保证最后一片达标,前面几片仍然可能是预算的好几倍。"""
    out: list[str] = []
    rest = text
    while count_tokens(rest) > max_tokens:
        cut = _prefix_within(rest, max_tokens)
        out.append(rest[:cut])
        rest = rest[cut:]
    if rest:
        out.append(rest)
    return out


def _split_oversize(text: str, max_tokens: int) -> list[str]:
    """超长单块按句子边界切;切不动(无标点长串、一整张巨表)就按预算硬切。"""
    if count_tokens(text) <= max_tokens:
        return [text]
    units = [u for u in _SENT_SPLIT.split(text) if u]
    if len(units) <= 1:
        units = text.splitlines(keepends=True) or [text]

    pieces: list[str] = []
    cur = ""
    for u in units:
        # 单个 unit 自身就超限,先把它拆开再参与累积
        for part in (_hard_split(u, max_tokens) if count_tokens(u) > max_tokens else [u]):
            if cur and count_tokens(cur + part) > max_tokens:
                pieces.append(cur)
                cur = part
            else:
                cur += part
    if cur.strip():
        pieces.append(cur)
    return pieces


def _tail(text: str, overlap_tokens: int) -> str:
    """取末尾约 overlap_tokens 个 token 作为下一块的前文。"""
    if overlap_tokens <= 0 or not text:
        return ""
    lo, hi = 0, len(text)
    while lo < hi:
        mid = (lo + hi + 1) // 2
        if count_tokens(text[-mid:]) <= overlap_tokens:
            lo = mid
        else:
            hi = mid - 1
    return text[-lo:] if lo else ""


def _path(heading: str) -> list[str]:
    return [p for p in (heading or "").split(" > ") if p]


def _common_prefix(a: list[str], b: list[str]) -> list[str]:
    out = []
    for x, y in zip(a, b):
        if x != y:
            break
        out.append(x)
    return out


def _same_branch(a: str, b: str) -> bool:
    """两个章节是否同属一棵子树(至少共享顶层父节点)。

    只允许在同一分支内合并小节,跨大章节绝不合并 —— 否则 chunk 的 heading
    会退化成没有意义的根标题,引用溯源就失真了。
    """
    pa, pb = _path(a), _path(b)
    if not pa or not pb:
        return True
    return _common_prefix(pa, pb) == pa[:len(_common_prefix(pa, pb))] and bool(_common_prefix(pa, pb))


def chunk_text(text: str, doc_id: int, chunk_tokens: int = 600,
               overlap_tokens: int = 80, min_tokens: int = 120) -> list[dict]:
    """返回 [{"id","order","heading","text","tokens","doc_id","headings"}]。

    id 形如 `d3:c0` —— 带 doc_id 前缀。v1 用全局 `c0/c1`,多文档必然冲突。

    累积策略:贪心填到 chunk_tokens。章节切换时,只要**同属一棵子树**且预算还够
    就继续合并;chunk 的 heading 取其中所有小节的最长公共前缀。
    这样一份有 78 个小节、每节中位数才 167 token 的需求文档,不会像 v1 那样
    被切成 79 个碎片块(碎片既召回不准,又白白多花一次 LLM 抽取调用)。
    """
    blocks = _blocks(text)
    chunks: list[dict] = []
    order = 0
    cur_text = ""
    cur_headings: list[str] = []

    def chunk_heading() -> str:
        if not cur_headings:
            return ""
        if len(cur_headings) == 1:
            return cur_headings[0]
        prefix = _path(cur_headings[0])
        for h in cur_headings[1:]:
            prefix = _common_prefix(prefix, _path(h))
            if not prefix:
                break
        return " > ".join(prefix) if prefix else cur_headings[0]

    def emit():
        nonlocal order, cur_text, cur_headings
        t = cur_text.strip()
        if t:
            chunks.append({"id": f"d{doc_id}:c{order}", "order": order, "doc_id": doc_id,
                           "heading": chunk_heading(), "headings": list(cur_headings),
                           "text": t, "tokens": count_tokens(t)})
            order += 1
        cur_text = ""
        cur_headings = []

    for heading, _kind, block in blocks:
        for piece in _split_oversize(block, chunk_tokens):
            cur_tokens = count_tokens(cur_text)
            piece_tokens = count_tokens(piece)
            last_heading = cur_headings[-1] if cur_headings else heading
            crossing = bool(cur_text) and heading != last_heading

            over_budget = cur_tokens + piece_tokens > chunk_tokens
            # 跨章节合并的条件:要么当前块还太短撑不起一块,要么同属一棵子树且预算够
            may_merge = (cur_tokens < min_tokens) or (_same_branch(last_heading, heading)
                                                     and not over_budget)
            if cur_text and (over_budget or (crossing and not may_merge)):
                prev = cur_text
                prev_heads = list(cur_headings)
                emit()
                cur_text = _tail(prev, overlap_tokens)
                if cur_text:
                    cur_text += "\n"
                    # 带过来的重叠文本属于上一节,heading 沿用它,避免归属错位
                    cur_headings = prev_heads[-1:]
            if heading not in cur_headings:
                cur_headings.append(heading)
            cur_text += piece + "\n"
    emit()

    # 收尾:最后一块若过短,并进前一块(常见于文档末尾的一句话小节)
    if len(chunks) >= 2 and chunks[-1]["tokens"] < min_tokens:
        tail = chunks.pop()
        prev = chunks[-1]
        prev["text"] = prev["text"] + "\n" + tail["text"]
        prev["tokens"] = count_tokens(prev["text"])
        for h in tail["headings"]:
            if h not in prev["headings"]:
                prev["headings"].append(h)
    return chunks