ingest_contract.py
6.1 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
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 -->"
@dataclass(frozen=True)
class IngestContract:
schema_version: str
required_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, ...]
vehicle_brands: tuple[str, ...]
ecosystem_names: tuple[str, ...]
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_vehicle_brands(raw: dict[str, Any]) -> tuple[str, ...]:
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")
return IngestContract(
schema_version=str(raw.get("schema_version") or "").strip(),
required_fields=tuple(raw.get("required_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 ()),
vehicle_brands=_flatten_vehicle_brands(raw.get("vehicle_brands") or {}),
ecosystem_names=tuple(raw.get("ecosystem_names") or ()),
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 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 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)