contracts.py
7.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
"""引擎层 metadata 契约:业务无关,对任何文档都成立。
分两层是本次重构的核心设计:
- **引擎层(本模块)**:来源、位置、内容类型、解析质量。PDF、Excel、代码库、
HR 文档都有这些维度,所以它们是固定字段——SQL 列 + Qdrant payload 固定部分。
- **业务标签层(ingestion/taxonomy.py)**:品牌、业务分类等,由 YAML 声明,
代码不认识任何具体维度名。加维度只改配置文件。
引擎层不认识"品牌"是什么,业务层不关心"第几页"——两边互不侵入。
"""
from __future__ import annotations
import logging
from typing import Any, Literal, TypedDict
from src.rag.core.config import RAG_META_STRICT
from src.rag.core.errors import RagStructuredError
logger = logging.getLogger(__name__)
# 版本号:契约变更时 bump,用于识别索引是哪套规则产出的
RAG_PARSER_VERSION = "rag-parser-v3"
RAG_CHUNKER_VERSION = "rag-chunker-v3"
# ---------------------------------------------------------------------------
# 受控取值域
# ---------------------------------------------------------------------------
ParseStatus = Literal["ok", "failed"]
# 单一词表。此前 loaders/common 用 normal/short/garbled/empty,PDF 用 ok/suspect_encoding/low_cjk,
# 而 parse_quality 是 Qdrant keyword 索引字段——两套词表意味着任何过滤都得同时知道两边。
ParseQuality = Literal["empty", "garbled", "low_cjk", "short", "normal"]
ContentRole = Literal["body", "heading", "table"]
BlockContentKind = Literal["text", "table", "slide_text"]
ChunkContentKind = Literal["text", "table", "mixed_table", "slide_text"]
ChunkingStrategy = Literal["text_window", "table_rows"]
_ENUMS: dict[str, frozenset[str]] = {
"parse_status": frozenset({"ok", "failed"}),
"parse_quality": frozenset({"empty", "garbled", "low_cjk", "short", "normal"}),
"content_role": frozenset({"body", "heading", "table"}),
"content_kind": frozenset({"text", "table", "mixed_table", "slide_text"}),
"chunking_strategy": frozenset({"text_window", "table_rows"}),
}
class BlockMeta(TypedDict, total=False):
"""loader 产出的块级 metadata(enrich_blocks 出口即完全体)。"""
parser_version: str
chunker_version: str
parse_method: str
parse_status: str
parse_quality: str
source_page_count: int
content_role: str
content_kind: str
heading_level: int
page_start: int
page_end: int
slide_number: int
sheet_name: str
row_start: int
row_end: int
section_path: list[str]
section_title: str
table_markdown: bool
table_header: list[str]
table_row_count: int
table_id: str
char_start: int
char_end: int
frontmatter: dict[str, Any]
class ChunkMeta(BlockMeta, total=False):
"""chunking 产出的片段级 metadata,落 DB metadata_json。"""
document_title: str
section_intro: str
chunking_strategy: str
block_types: list[str]
parse_methods: list[str]
table_ids: list[str]
overlap_prev_chars: int
overlap_next_chars: int
overlap_prev_rows: int
overlap_next_rows: int
table_context_lines: int
# 块级允许出现的键 = BlockMeta 声明 + 引擎内部临时键(编排阶段用完必须 pop)
_BLOCK_KEYS = frozenset(BlockMeta.__annotations__)
_BLOCK_TRANSIENT_KEYS = frozenset({"table_continues", "heading_marker_level", "table_index", "continued_table"})
_CHUNK_KEYS = frozenset(ChunkMeta.__annotations__)
# 文档级统计:只落 rag_documents,不进分片 metadata_json
DOC_LEVEL_STAT_KEYS = (
"parse_engine",
"vlm_page_count",
"vlm_total_tokens",
"vlm_input_tokens",
"vlm_output_tokens",
"vlm_image_tokens",
"vlm_duration_ms",
)
# ---------------------------------------------------------------------------
# Qdrant payload
# ---------------------------------------------------------------------------
# 引擎层进 payload 的字段。业务维度由 taxonomy.filterable_names() 动态追加。
PAYLOAD_CORE_FIELDS = (
"chunk_id",
"parent_chunk_id",
"file_id",
"document_id",
"status",
"source_name",
"chunk_index",
"page_start",
"page_end",
"section_title",
"content_kind",
)
# 只给真正会被过滤的字段建 keyword 索引。此前建了 16 个,其中 13 个从未被查询过——
# section_title 这种高基数字段建索引尤其烧内存。
KEYWORD_INDEX_CORE = ("status", "file_id", "document_id")
# ---------------------------------------------------------------------------
# 质量判定与校验
# ---------------------------------------------------------------------------
def quality_for_text(text: str) -> str:
"""按文本特征判定解析质量。唯一实现——此前 loaders/common 和 pdf_loader 各有一份。"""
stripped = (text or "").strip()
if not stripped:
return "empty"
total = max(len(stripped), 1)
if stripped.count("�") / total > 0.02:
return "garbled"
cjk = sum(1 for ch in stripped if "一" <= ch <= "鿿")
# 中文文档里几乎没有 CJK 字符,通常是 OCR/编码退化的信号
if total >= 40 and cjk / total < 0.05 and not stripped.isascii():
return "low_cjk"
if len(stripped) < 12:
return "short"
return "normal"
def _report(problems: list[str], where: str) -> None:
if not problems:
return
message = f"metadata 契约违约 @ {where}: " + "; ".join(problems)
if RAG_META_STRICT:
raise RagStructuredError(message, detail={"where": where, "problems": problems})
logger.warning("[RAG] %s", message)
def _check(meta: Any, allowed: frozenset[str], where: str, kind: str) -> None:
if not isinstance(meta, dict):
_report([f"metadata 不是 dict,实际是 {type(meta).__name__}"], where)
return
problems: list[str] = []
for key, value in meta.items():
if key not in allowed:
problems.append(f"未声明的键 {key!r}")
continue
domain = _ENUMS.get(key)
if domain is not None and value is not None and value not in domain:
problems.append(f"{key}={value!r} 不在取值域 {sorted(domain)}")
header = meta.get("table_header")
if header is not None and not isinstance(header, list):
# 此前 Excel/common 写 list、PDF/chunking 写 str,同一个 payload 字段两种类型
problems.append(f"table_header 必须是 list[str],实际是 {type(header).__name__}")
_report(problems, f"{kind}:{where}")
def validate_block_meta(meta: Any, *, where: str) -> None:
"""校验 loader 产出的块级 metadata。调用点:enrich_blocks 尾部。"""
_check(meta, _BLOCK_KEYS | _BLOCK_TRANSIENT_KEYS, where, "block")
def validate_chunk_meta(meta: Any, *, where: str) -> None:
"""校验 chunking 产出的片段级 metadata。业务标签由 taxonomy 自行校验,此处放行。"""
from src.rag.ingestion.taxonomy import load_taxonomy
dims = load_taxonomy().dimensions
label_keys = {d.name for d in dims} | {d.also_emit_as for d in dims if d.also_emit_as}
# 多命中时 taxonomy 会额外产出复数键(如 page_types),一并放行
label_keys |= {f"{name}s" for name in label_keys}
_check(meta, _CHUNK_KEYS | frozenset(label_keys), where, "chunk")