ingest_contract.py
16.4 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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
from __future__ import annotations
import functools
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import yaml
CONTRACT_START = "<!-- INGEST_CONTRACT_START -->"
CONTRACT_END = "<!-- INGEST_CONTRACT_END -->"
# #5: Planner 每个 page 必须包含的字段
_PLANNER_PAGE_REQUIRED = ("type", "slug", "file_path", "title")
# 过滤维度的归属层级。
# 文档级(global_dims):一次摄入只描述一个体系、一个业务大类、一批岗位。
# 页面级(pages[].sub_business):子业务是页面固有属性——一个页面只讲一个子业务,
# 而一份文档常覆盖多个(如七大轻改产品)。放全局会把所有下游页面打成同一个值,
# 按 sub_business 过滤时漏召回。故由 Planner 逐页声明,缺失时回落到可见占位值。
_GLOBAL_DIMS = ("series", "brand", "business_category", "role")
_PAGE_DIMS = ("sub_business",)
@dataclass(frozen=True)
class IngestContract:
schema_version: str
required_fields: tuple[str, ...]
system_maintained_fields: tuple[str, ...]
canonical_types: dict[str, dict[str, Any]]
type_aliases: dict[str, str]
source_tracked_exclude: tuple[str, ...]
list_merge_fields: tuple[str, ...]
business_categories: tuple[str, ...]
sub_business_values: tuple[str, ...]
series_values: tuple[str, ...]
vehicle_brands: tuple[str, ...]
ecosystem_names: tuple[str, ...]
dim_defaults: dict[str, str] # #9: Planner 维度兜底默认值
prompt_text: str
def _default_schema_path() -> Path:
return Path(__file__).resolve().parents[2] / "skills" / "llm-ingest" / "references" / "schema.md"
def _extract_contract_yaml(schema_text: str) -> str:
if CONTRACT_START not in schema_text or CONTRACT_END not in schema_text:
raise ValueError("schema.md 缺少 INGEST_CONTRACT 标记")
block = schema_text.split(CONTRACT_START, 1)[1].split(CONTRACT_END, 1)[0].strip()
if block.startswith("```"):
lines = block.splitlines()
if lines and lines[0].startswith("```"):
lines = lines[1:]
if lines and lines[-1].strip() == "```":
lines = lines[:-1]
block = "\n".join(lines).strip()
return block
def _flatten_grouped_values(raw: dict[str, Any]) -> tuple[str, ...]:
"""展平 schema 中"分组 dict -> 值列表"结构(vehicle_brands / sub_business_values)。"""
out: list[str] = []
for values in raw.values():
if not isinstance(values, list):
continue
for item in values:
if item and item not in out:
out.append(str(item))
return tuple(out)
def _build_type_aliases(canonical_types: dict[str, dict[str, Any]]) -> dict[str, str]:
aliases: dict[str, str] = {}
for canonical, spec in canonical_types.items():
aliases[canonical] = canonical
for alias in spec.get("aliases", []) or []:
aliases[str(alias)] = canonical
return aliases
@functools.lru_cache(maxsize=None)
def load_ingest_contract(schema_path: str | None = None) -> IngestContract:
path = Path(schema_path) if schema_path else _default_schema_path()
schema_text = path.read_text(encoding="utf-8")
raw = yaml.safe_load(_extract_contract_yaml(schema_text)) or {}
canonical_types = raw.get("canonical_types") or {}
if not canonical_types:
raise ValueError("schema contract 缺少 canonical_types")
# #9: 解析 dim_defaults,不存在时使用空字典(代码内有硬编码兜底)
dim_defaults_raw = raw.get("dim_defaults") or {}
dim_defaults = {str(k): str(v) for k, v in dim_defaults_raw.items()}
return IngestContract(
schema_version=str(raw.get("schema_version") or "").strip(),
required_fields=tuple(raw.get("required_fields") or ()),
system_maintained_fields=tuple(raw.get("system_maintained_fields") or ()),
canonical_types=canonical_types,
type_aliases=_build_type_aliases(canonical_types),
source_tracked_exclude=tuple(raw.get("source_tracked_exclude") or ()),
list_merge_fields=tuple(raw.get("list_merge_fields") or ()),
business_categories=tuple(raw.get("business_categories") or ()),
sub_business_values=_flatten_grouped_values(raw.get("sub_business_values") or {}),
series_values=tuple(raw.get("series_values") or ()),
vehicle_brands=_flatten_grouped_values(raw.get("vehicle_brands") or {}),
ecosystem_names=tuple(raw.get("ecosystem_names") or ()),
dim_defaults=dim_defaults,
prompt_text=schema_text,
)
def current_schema_version() -> str:
return load_ingest_contract().schema_version
def canonicalize_type(raw_type: Any, contract: IngestContract | None = None) -> str:
value = str(raw_type or "").strip()
active_contract = contract or load_ingest_contract()
canonical = active_contract.type_aliases.get(value)
if not canonical:
raise ValueError(f"非法页面 type: {value}")
return canonical
def missing_required_extra(
metadata: dict[str, Any],
page_type: str,
contract: IngestContract | None = None,
) -> list[str]:
"""列出该 type 在公共 required_fields 之外、缺失的专属必填字段。
取值须**存在且非空**:`trigger:` 留空与没写同样无用,比公共字段的「仅存在」严一档。
page_type 必须是 canonical key(先过 `canonicalize_type`),否则查不到条目。
纯函数,便于单测。
"""
active_contract = contract or load_ingest_contract()
spec = active_contract.canonical_types.get(page_type) or {}
required_extra = spec.get("required_extra") or []
return [field for field in required_extra if _is_blank(metadata.get(field))]
def _is_blank(value: Any) -> bool:
if value is None:
return True
if isinstance(value, str):
return not value.strip()
if isinstance(value, (list, tuple, set, dict)):
return len(value) == 0
return False
def brand_baseline_set() -> set[str]:
return set(load_ingest_contract().vehicle_brands)
def ecosystem_name_set() -> set[str]:
return set(load_ingest_contract().ecosystem_names)
def sub_business_value_set() -> set[str]:
return set(load_ingest_contract().sub_business_values)
def build_source_ref(filename: str, file_format: Any = None) -> str:
"""构造 sources / field_sources 中使用的规范来源路径。
raw 文件按格式分子目录存放(`ware/raw/{format}/{filename}`,见 RAW_DIR 用法)。
只记 basename 会让 sources 指向不存在的路径,也无法区分不同子目录下的同名文件。
file_format 缺省时回落到扁平路径,保持对历史数据的兼容。
"""
name = str(filename or "").strip()
fmt = str(file_format or "").strip().lower().lstrip(".")
if fmt:
return f"ware/raw/{fmt}/{name}"
return f"ware/raw/{name}"
def is_placeholder_value(value: Any) -> bool:
"""判断是否为"没判断出来"的兜底占位值(如 未知系列(待确认)、品牌名(待审批))。"""
text = str(value or "").strip()
return text.startswith("未知") or text.endswith("(待确认)") or text.endswith("(待审批)")
def sanitize_series(
value: Any,
contract: IngestContract | None = None,
) -> tuple[str, str | None]:
"""校验并归一 series 取值。
硬约束:`ecosystem_names`(嘀加、广联数科)是合作生态品牌,不是品牌体系,
禁止作为 series;命中即回落 `通用品牌`,不中断摄入。
返回 (sanitized_series, warning_or_None)。纯函数,便于单测。
"""
active_contract = contract or load_ingest_contract()
text = str(value or "").strip()
if not text:
return text, None
if text in set(active_contract.ecosystem_names):
fallback = "通用品牌"
return fallback, (
f"series={text!r} 是合作生态品牌(ecosystem_names),不是品牌体系,"
f"已回落为 {fallback!r};{text} 应出现在 title、正文或 tags 中"
)
return text, None
def pick_series_for_path(value: Any, contract: IngestContract | None = None) -> str:
"""sources 页按 `ware/wiki/sources/{series}` 落盘,需从 series 取单值。
多来源合并后 series 可能是数组,取**首个非占位值**;全部为占位值时取首个。
"""
values = [str(v).strip() for v in as_value_list(value) if str(v or "").strip()]
if not values:
return ""
for item in values:
if not is_placeholder_value(item):
return item
return values[0]
def contract_prompt_text() -> str:
return load_ingest_contract().prompt_text
def as_value_list(value: Any) -> list[Any]:
if isinstance(value, list):
return list(value)
if value in (None, ""):
return []
return [value]
def merge_field_sources(
target_md: dict[str, Any],
new_md: dict[str, Any],
canonical_source: str,
contract: IngestContract | None = None,
) -> None:
active_contract = contract or load_ingest_contract()
exclude = set(active_contract.source_tracked_exclude)
list_fields = set(active_contract.list_merge_fields)
fs = target_md.get("field_sources", {}) or {}
for key, value in new_md.items():
if key in exclude:
continue
new_values = as_value_list(value)
if not new_values:
continue
is_list = key in list_fields or isinstance(value, list) or isinstance(target_md.get(key), list)
fs.setdefault(key, {})
for item in new_values:
fs[key].setdefault(item, [])
if canonical_source not in fs[key][item]:
fs[key][item].append(canonical_source)
if is_list:
merged = as_value_list(target_md.get(key))
for item in new_values:
if item not in merged:
merged.append(item)
target_md[key] = merged
elif target_md.get(key) in (None, ""):
target_md[key] = new_values[0]
target_md["field_sources"] = fs
def recompute_after_source_removal(
md: dict[str, Any],
removed_source: str,
contract: IngestContract | None = None,
) -> None:
active_contract = contract or load_ingest_contract()
list_fields = set(active_contract.list_merge_fields)
fs = md.get("field_sources", {}) or {}
for field, srcmap in list(fs.items()):
for item in list(srcmap.keys()):
if removed_source in srcmap.get(item, []):
srcmap[item] = [s for s in srcmap[item] if s != removed_source]
if not srcmap.get(item):
srcmap.pop(item, None)
surviving = list(srcmap.keys())
if not surviving:
fs.pop(field, None)
md.pop(field, None)
elif isinstance(md.get(field), list) or field in list_fields:
md[field] = surviving
elif md.get(field) not in surviving:
md[field] = surviving[0]
if fs:
md["field_sources"] = fs
else:
md.pop("field_sources", None)
def resolve_effective_dims(
page: dict[str, Any],
global_dims: dict[str, Any],
contract: IngestContract | None = None,
) -> tuple[dict[str, Any], list[str]]:
"""合成单个页面的生效过滤维度 = 文档级 global_dims + 页面级 sub_business。
`sub_business` 只从页面读(见 `_PAGE_DIMS`),不接受 global_dims 的值:
子业务是页面固有属性,全局默认值会静默污染所有下游页面。
页面未声明或取值越界时,回落到 `dim_defaults` 的可见占位值并告警——
宁可显式标记"未确认",也不要静默套用一个多半是错的默认值。
页面可声明单值或多值(sources 摘要页常跨多个子业务);
`sub_business` 本就是 `list_merge_fields` 之一,多值合法。
返回 (effective_dims, warnings)。纯函数,不做 IO、不写日志,便于单测。
"""
active_contract = contract or load_ingest_contract()
dims = {k: v for k, v in global_dims.items() if k not in _PAGE_DIMS}
warnings: list[str] = []
allowed = set(active_contract.sub_business_values)
fallback = active_contract.dim_defaults.get("sub_business", "未知子业务(待确认)")
slug = page.get("slug", "?")
raw = page.get("sub_business")
values = [str(v).strip() for v in as_value_list(raw) if str(v or "").strip()]
if not values:
dims["sub_business"] = fallback
warnings.append(
f"页面 {slug!r} 未声明 sub_business,回落占位值 {fallback!r};"
f"Planner 应为每个页面声明子业务"
)
return dims, warnings
accepted: list[str] = []
for value in values:
if allowed and value not in allowed:
warnings.append(
f"页面 {slug!r} 的 sub_business={value!r} 不在 schema contract 枚举内,已丢弃"
)
continue
if value not in accepted:
accepted.append(value)
if not accepted:
dims["sub_business"] = fallback
warnings.append(f"页面 {slug!r} 的 sub_business 无合法取值,回落占位值 {fallback!r}")
return dims, warnings
dims["sub_business"] = accepted[0] if len(accepted) == 1 else accepted
return dims, warnings
def validate_planner_output(
plan_data: dict,
*,
chunk_count: int | None = None,
require_sources: bool = True,
) -> tuple[dict, list[dict]]:
"""#5: 校验 Planner JSON 输出结构,返回 (global_dims, pages)。
格式不合规时抛 ValueError,让 Phase 1 直接终止或触发重试,
而非静默地将格式错误延迟到 Phase 2/3 才暴露。
chunk_count 非 None 时为长文档分块模式:每页必须认领非空且编号合法的
source_chunks(多页可认领同一块)。require_sources=False 用于覆盖补充轮
(该轮只补下游页面,不再重复规划 sources 摘要页)。
"""
if not isinstance(plan_data, dict):
raise ValueError(
f"Planner 输出必须是 JSON 对象,实际类型为 {type(plan_data).__name__}"
)
pages = plan_data.get("pages")
if not isinstance(pages, list) or len(pages) == 0:
raise ValueError(
f"Planner 输出的 pages 必须是非空数组,"
f"实际类型为 {type(pages).__name__ if pages is not None else 'null'}"
)
for i, page in enumerate(pages):
if not isinstance(page, dict):
raise ValueError(
f"pages[{i}] 必须是 JSON 对象,实际类型为 {type(page).__name__}"
)
missing = [f for f in _PLANNER_PAGE_REQUIRED if not page.get(f)]
if missing:
raise ValueError(
f"pages[{i}](slug={page.get('slug', '?')})缺少必填字段: {missing}"
)
# sources 摘要页在分块模式下不认领原文块(由下游成品页合成),豁免非空校验、允许空数组。
is_sources_page = str(page.get("type", "")).strip() in ("sources", "source")
if chunk_count is not None and not is_sources_page:
source_chunks = page.get("source_chunks")
if not isinstance(source_chunks, list) or not source_chunks:
raise ValueError(
f"pages[{i}](slug={page.get('slug', '?')})缺少非空的 source_chunks 数组"
f"(长文档分块模式下每页必须声明取材块编号)"
)
bad = [
c for c in source_chunks
if not (isinstance(c, int) or (isinstance(c, str) and c.isdigit()))
or not (1 <= int(c) <= chunk_count)
]
if bad:
raise ValueError(
f"pages[{i}](slug={page.get('slug', '?')})source_chunks 含非法块编号 {bad},"
f"合法范围为 1..{chunk_count} 的整数"
)
global_dims = plan_data.get("global_dims")
if global_dims is not None and not isinstance(global_dims, dict):
raise ValueError(
f"global_dims 必须是 JSON 对象或 null,实际类型为 {type(global_dims).__name__}"
)
# 必须包含至少 1 个 sources 类型页面(覆盖补充轮除外)
has_sources = any(
isinstance(p, dict) and str(p.get("type", "")).strip() in ("sources", "source")
for p in pages
)
if require_sources and not has_sources:
raise ValueError(
"Planner 规划必须包含至少 1 个 type=sources 的来源摘要页"
)
return global_dims or {}, pages