ingest_contract.py 6.1 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 -->"


@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)