ingest_contract.py 8.32 KB
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")


@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, ...]
    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_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")

    # #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 ()),
        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 ()),
        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 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)


def validate_planner_output(plan_data: dict) -> tuple[dict, list[dict]]:
    """#5: 校验 Planner JSON 输出结构,返回 (global_dims, pages)。

    格式不合规时抛 ValueError,让 Phase 1 直接终止或触发重试,
    而非静默地将格式错误延迟到 Phase 2/3 才暴露。
    """
    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}"
            )

    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 not has_sources:
        raise ValueError(
            "Planner 规划必须包含至少 1 个 type=sources 的来源摘要页"
        )

    return global_dims or {}, pages