Datasets:
Download sources/date-head/src/compact_fact_extraction/graph/retrieval.py from Monyzik/compactfact-training-data: direct link, hf CLI and curl.
- Browser
- Download file 21.9 kB
-
https://huggingface.co/datasets/Monyzik/compactfact-training-data/resolve/main/sources/date-head/src/compact_fact_extraction/graph/retrieval.py
- Command line
-
hf download hf://datasets/Monyzik/compactfact-training-data/sources/date-head/src/compact_fact_extraction/graph/retrieval.py
-
curl -L -o retrieval.py https://huggingface.co/datasets/Monyzik/compactfact-training-data/resolve/main/sources/date-head/src/compact_fact_extraction/graph/retrieval.py
21.9 kB
| """Conservative, local retrieval over a versioned static domain graph. | |
| SQLite FTS5 supplies candidate ranking; exact names and reviewed aliases take | |
| precedence. The score is a ranking heuristic, never a probability of truth. | |
| No transcript, network service, embedding model or LLM is needed here. | |
| """ | |
| from __future__ import annotations | |
| from collections import defaultdict | |
| from contextlib import closing | |
| from copy import deepcopy | |
| from difflib import SequenceMatcher | |
| import hashlib | |
| import json | |
| import os | |
| from pathlib import Path | |
| import re | |
| import sqlite3 | |
| import tempfile | |
| import unicodedata | |
| from .builder import validate_graph | |
| INDEX_VERSION = "1.0" | |
| CONFIG = { | |
| "normalization": "nfkc-casefold-yo-preserve-plus-digits-negation-v1", | |
| "fts_tokenizer": "unicode61 remove_diacritics 2", | |
| "lexical_min_query_coverage": 0.75, | |
| "fuzzy_min_similarity": 0.82, | |
| "max_context_nodes": 64, | |
| "max_global_rules": 24, | |
| "max_results": 20, | |
| "unknown_context": "category_and_rules_if_category_known", | |
| } | |
| MODES = frozenset({"flat", "enriched_flat", "graph"}) | |
| STOP_WORDS = frozenset({"у", "меня", "мне", "мой", "моя", "моего", "в", "на", "с", "со", "и", "а", "это", "этот", "эта", "пожалуйста", "тариф", "услуга", "устройство"}) | |
| NEGATION_WORDS = frozenset({"не", "нет", "без", "нельзя", "никогда"}) | |
| class IndexVersionError(ValueError): | |
| """The persisted index does not match this graph or retrieval configuration.""" | |
| def _json(value: object) -> str: | |
| return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) | |
| def _digest(value: object) -> str: | |
| return hashlib.sha256(_json(value).encode("utf-8")).hexdigest() | |
| def normalize(text: str) -> str: | |
| """Keep discriminating signs, numbers and negative words in the exact key.""" | |
| text = unicodedata.normalize("NFKC", text).casefold().replace("ё", "е") | |
| text = re.sub(r"[^\w+\-]+", " ", text, flags=re.UNICODE) | |
| return " ".join(text.split()) | |
| def _tokens(text: str) -> list[str]: | |
| return re.findall(r"[^\W_]+", normalize(text), flags=re.UNICODE) | |
| def _compatible(query: str, candidate: str) -> bool: | |
| """Do not silently erase a denial, a tariff suffix or a model number.""" | |
| q, c = set(_tokens(query)), set(_tokens(candidate)) | |
| if q & NEGATION_WORDS != c & NEGATION_WORDS: | |
| return False | |
| if query.count("+") != candidate.count("+"): | |
| return False | |
| return set(re.findall(r"\d+", query)) == set(re.findall(r"\d+", candidate)) | |
| def _documents(graph: dict) -> list[dict]: | |
| nodes = {node["id"]: node for node in graph["nodes"]} | |
| aliases: dict[str, list[dict]] = defaultdict(list) | |
| groups: dict[str, list[dict]] = defaultdict(list) | |
| for edge in graph["edges"]: | |
| if edge["relation"] == "alias_of" and nodes[edge["source"]]["kind"] == "alias": | |
| source = nodes[edge["source"]] | |
| aliases[edge["target"]].append({"id": source["id"], "label": source["label"]}) | |
| if edge["relation"] == "groups_value" and nodes[edge["source"]]["kind"] == "concept_group": | |
| source = nodes[edge["source"]] | |
| groups[edge["target"]].append({"id": source["id"], "label": source["label"]}) | |
| return [ | |
| { | |
| "node_id": node["id"], "label": node["label"], "canonical": normalize(node["label"]), | |
| "category": node["properties"].get("category", ""), | |
| "aliases": sorted(aliases[node["id"]], key=lambda item: item["id"]), | |
| "groups": sorted(groups[node["id"]], key=lambda item: item["id"]), | |
| } | |
| for node in sorted(graph["nodes"], key=lambda item: item["id"]) | |
| if node["kind"] in {"catalog_value", "example"} | |
| ] | |
| def build_index(graph: dict, path: Path) -> dict: | |
| """Atomically replace one SQLite artifact and return a portable manifest.""" | |
| validate_graph(graph) | |
| path = Path(path) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| documents = _documents(graph) | |
| manifest = { | |
| "index_version": INDEX_VERSION, "graph_id": graph["graph_id"], | |
| "config": deepcopy(CONFIG), "config_hash": _digest(CONFIG), | |
| "document_count": len(documents), "corpus_hash": _digest(documents), | |
| } | |
| fd, temporary = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent) | |
| os.close(fd) | |
| try: | |
| with closing(sqlite3.connect(temporary)) as connection: | |
| connection.execute("CREATE TABLE metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL)") | |
| connection.execute("CREATE TABLE documents (node_id TEXT PRIMARY KEY, category TEXT NOT NULL, payload TEXT NOT NULL)") | |
| try: | |
| connection.execute("CREATE VIRTUAL TABLE flat_fts USING fts5(node_id UNINDEXED, label, tokenize='unicode61 remove_diacritics 2')") | |
| connection.execute("CREATE VIRTUAL TABLE enriched_fts USING fts5(node_id UNINDEXED, label, aliases, groups_text, tokenize='unicode61 remove_diacritics 2')") | |
| except sqlite3.OperationalError as exc: | |
| raise ValueError("SQLite with FTS5 support is required to build the domain index") from exc | |
| connection.execute("INSERT INTO metadata VALUES (?, ?)", ("manifest", _json(manifest))) | |
| for item in documents: | |
| connection.execute("INSERT INTO documents VALUES (?, ?, ?)", (item["node_id"], item["category"], _json(item))) | |
| connection.execute("INSERT INTO flat_fts VALUES (?, ?)", (item["node_id"], item["canonical"])) | |
| connection.execute("INSERT INTO enriched_fts VALUES (?, ?, ?, ?)", ( | |
| item["node_id"], item["canonical"], | |
| " ".join(normalize(a["label"]) for a in item["aliases"]), | |
| " ".join(normalize(g["label"]) for g in item["groups"]), | |
| )) | |
| connection.commit() | |
| index_hash = hashlib.sha256(Path(temporary).read_bytes()).hexdigest() | |
| os.replace(temporary, path) | |
| return {**manifest, "index_hash": index_hash} | |
| finally: | |
| if os.path.exists(temporary): | |
| os.unlink(temporary) | |
| class DomainRetriever: | |
| """Thread-safe reader: each search opens its own read-only SQLite connection.""" | |
| def __init__(self, graph: dict, index_path: Path): | |
| validate_graph(graph) | |
| self.graph = deepcopy(graph) | |
| self.path = Path(index_path).resolve() | |
| self.nodes = {node["id"]: node for node in self.graph["nodes"]} | |
| self.edges = self.graph["edges"] | |
| self.adjacency: dict[str, list[dict]] = defaultdict(list) | |
| for edge in self.edges: | |
| self.adjacency[edge["source"]].append(edge) | |
| self.adjacency[edge["target"]].append(edge) | |
| self.documents = _documents(self.graph) | |
| self.docs_by_id = {item["node_id"]: item for item in self.documents} | |
| self.categories = {item["category"] for item in self.documents} | |
| with closing(self._connect()) as connection: | |
| manifest = self._check_manifest(connection) | |
| try: | |
| actual = [json.loads(row[0]) for row in connection.execute("SELECT payload FROM documents ORDER BY node_id")] | |
| flat_rows = connection.execute("SELECT node_id, label FROM flat_fts ORDER BY node_id").fetchall() | |
| enriched_rows = connection.execute("SELECT node_id, label, aliases, groups_text FROM enriched_fts ORDER BY node_id").fetchall() | |
| except (sqlite3.Error, ValueError, TypeError) as exc: | |
| raise IndexVersionError("Invalid domain index contents; rebuild the index") from exc | |
| if actual != self.documents or manifest.get("corpus_hash") != _digest(actual): | |
| raise IndexVersionError("Index documents do not match graph contents; rebuild the index") | |
| expected_flat = [(item["node_id"], item["canonical"]) for item in self.documents] | |
| expected_enriched = [( | |
| item["node_id"], item["canonical"], | |
| " ".join(normalize(alias["label"]) for alias in item["aliases"]), | |
| " ".join(normalize(group["label"]) for group in item["groups"]), | |
| ) for item in self.documents] | |
| if flat_rows != expected_flat or enriched_rows != expected_enriched: | |
| raise IndexVersionError("FTS index contents do not match the graph; rebuild the index") | |
| self.manifest = manifest | |
| def _connect(self) -> sqlite3.Connection: | |
| if not self.path.is_file(): | |
| raise IndexVersionError(f"Domain index not found: {self.path}; build it first") | |
| try: | |
| return sqlite3.connect(self.path.as_uri() + "?mode=ro", uri=True, timeout=5) | |
| except sqlite3.Error as exc: | |
| raise IndexVersionError("Cannot open domain index read-only; rebuild it") from exc | |
| def _check_manifest(self, connection: sqlite3.Connection) -> dict: | |
| try: | |
| record = connection.execute("SELECT value FROM metadata WHERE key='manifest'").fetchone() | |
| manifest = json.loads(record[0]) if record else {} | |
| except (sqlite3.Error, ValueError, TypeError) as exc: | |
| raise IndexVersionError("Invalid domain index manifest; rebuild it") from exc | |
| if not isinstance(manifest, dict): | |
| raise IndexVersionError("Invalid domain index manifest; rebuild it") | |
| expected = {"index_version": INDEX_VERSION, "graph_id": self.graph["graph_id"], "config_hash": _digest(CONFIG)} | |
| for key, value in expected.items(): | |
| if manifest.get(key) != value: | |
| raise IndexVersionError(f"Domain index {key} mismatch; rebuild it for this graph/configuration") | |
| if manifest.get("config") != CONFIG: | |
| raise IndexVersionError("Domain index configuration mismatch; rebuild it") | |
| return manifest | |
| def _forms(self, item: dict, mode: str, *, groups: bool = False) -> list[tuple[str, str]]: | |
| forms = [("exact", item["label"])] | |
| if mode != "flat": | |
| forms.extend(("alias", a["label"]) for a in item["aliases"]) | |
| if groups: | |
| forms.extend(("group", g["label"]) for g in item["groups"]) | |
| return forms | |
| def search(self, query: str, category: str | None = None, limit: int = 8, mode: str = "graph") -> dict: | |
| if not isinstance(query, str) or len(query) > 2000: | |
| raise ValueError("query must be a string of at most 2000 characters") | |
| if mode not in MODES: | |
| raise ValueError("mode must be flat, enriched_flat or graph") | |
| if category is not None and category not in self.categories: | |
| raise ValueError(f"Unknown catalogue category: {category}") | |
| if type(limit) is not int or not 1 <= limit <= CONFIG["max_results"]: | |
| raise ValueError(f"limit must be between 1 and {CONFIG['max_results']}") | |
| normalized = normalize(query) | |
| documents = [item for item in self.documents if category is None or item["category"] == category] | |
| ranked: dict[str, tuple[float, str, str, str]] = {} | |
| # Check version on every request, including exact/OOV requests. Atomic | |
| # replacement by another process must not mix an old graph with a new DB. | |
| with closing(self._connect()) as connection: | |
| self._check_manifest(connection) | |
| if normalized: | |
| for item in documents: | |
| for kind, form in self._forms(item, mode): | |
| if normalized == normalize(form): | |
| score = 1.0 if kind == "exact" else 0.98 | |
| candidate = (score, kind, form, "Точное название" if kind == "exact" else "Проверенный вариант названия; возможна неоднозначность") | |
| if score > ranked.get(item["node_id"], (0,))[0]: | |
| ranked[item["node_id"]] = candidate | |
| # Exact matches retain ambiguity but do not silently widen to near | |
| # tariffs, suffixed names or other objects. | |
| if not ranked and normalized: | |
| qtokens = [token for token in _tokens(query) if token not in STOP_WORDS] | |
| if qtokens: | |
| expression = " OR ".join('"' + token + '"' for token in dict.fromkeys(qtokens)) | |
| table = "flat_fts" if mode == "flat" else "enriched_fts" | |
| try: | |
| category_filter = " AND documents.category = ?" if category is not None else "" | |
| parameters = (expression, category) if category is not None else (expression,) | |
| rows = connection.execute( | |
| f"SELECT {table}.node_id, bm25({table}) FROM {table} " | |
| f"JOIN documents ON documents.node_id = {table}.node_id " | |
| f"WHERE {table} MATCH ?{category_filter} " | |
| f"ORDER BY bm25({table}), {table}.node_id LIMIT 150", | |
| parameters, | |
| ).fetchall() | |
| except sqlite3.Error as exc: | |
| raise IndexVersionError("Cannot query FTS index; rebuild it") from exc | |
| eligible = {item["node_id"]: item for item in documents} | |
| for rank, (node_id, _) in enumerate(rows): | |
| item = eligible.get(node_id) | |
| if item is None or not _compatible(normalized, item["canonical"]): | |
| continue | |
| for form_kind, form in self._forms(item, mode, groups=True): | |
| ftokens = set(_tokens(form)) - STOP_WORDS | |
| overlap = len(set(qtokens) & ftokens) | |
| coverage = overlap / len(set(qtokens)) | |
| if coverage < CONFIG["lexical_min_query_coverage"]: | |
| continue | |
| precision = overlap / max(1, len(ftokens)) | |
| score = 0.55 + 0.25 * coverage + 0.08 * precision + 0.04 / (rank + 1) | |
| if form_kind == "group": | |
| score -= 0.1 | |
| reason = "Совпадение слов в группе понятий" if form_kind == "group" else "Лексическое совпадение; кандидаты ранжированы BM25" | |
| if score > ranked.get(node_id, (0,))[0]: | |
| ranked[node_id] = (score, "lexical", form, reason) | |
| # Conservative spelling fallback only when lexical retrieval | |
| # found nothing. The explicit unknown result is preferable to | |
| # returning a weak nearest neighbour for every arbitrary query. | |
| if not ranked and len(normalized) >= 4: | |
| for item in documents: | |
| if not _compatible(normalized, item["canonical"]): | |
| continue | |
| for _, form in self._forms(item, mode): | |
| canonical = normalize(form) | |
| similarity = SequenceMatcher(None, normalized, canonical).ratio() | |
| if similarity < CONFIG["fuzzy_min_similarity"]: | |
| continue | |
| qgrams, fgrams = _trigrams(normalized), _trigrams(canonical) | |
| dice = 2 * len(qgrams & fgrams) / max(1, len(qgrams) + len(fgrams)) | |
| score = 0.55 + 0.25 * similarity + 0.07 * dice | |
| if score > ranked.get(item["node_id"], (0,))[0]: | |
| ranked[item["node_id"]] = (score, "fuzzy", form, "Близкое написание; кандидат требует проверки по реплике") | |
| ordering = sorted(ranked, key=lambda node_id: (-ranked[node_id][0], normalize(self.nodes[node_id]["label"]), node_id)) | |
| hits = [] | |
| for node_id in ordering[:limit]: | |
| node = self.nodes[node_id] | |
| score, match_type, matched_text, reason = ranked[node_id] | |
| match_provenance = deepcopy(node["provenance"]) | |
| for alias in self.docs_by_id[node_id]["aliases"]: | |
| if alias["label"] == matched_text: | |
| for reference in self.nodes[alias["id"]]["provenance"]: | |
| if reference not in match_provenance: | |
| match_provenance.append(deepcopy(reference)) | |
| hits.append({ | |
| "id": node_id, "node_id": node_id, "label": node["label"], "kind": node["kind"], | |
| "category": node["properties"].get("category"), "score": round(score, 6), | |
| "match_type": match_type, "match_reason": reason, "matched_text": matched_text, | |
| "provenance": match_provenance, | |
| }) | |
| warnings = [] | |
| if len(ordering) > limit: | |
| warnings.append(f"Найдено кандидатов: {len(ordering)}; показано {limit}. Это не полный перечень соответствий.") | |
| if len(hits) > 1 and all(hit["match_type"] in {"exact", "alias"} for hit in hits): | |
| warnings.append("Название неоднозначно: кандидаты не объединены и не считаются фактами клиента.") | |
| context, context_warnings = self._context(hits, mode, category) | |
| return { | |
| "query": query, "category": category, "mode": mode, | |
| "graph_id": self.graph["graph_id"], "index_version": INDEX_VERSION, | |
| "unknown": not hits, "hits": hits, "context": context, | |
| "warnings": warnings + context_warnings, | |
| } | |
| def _context(self, hits: list[dict], mode: str, category: str | None = None) -> tuple[dict, list[str]]: | |
| selected = {hit["node_id"] for hit in hits} | |
| seed_ids = set(selected) | |
| attributes = set() | |
| if mode != "flat": | |
| # An open value can still use its known attribute's template and | |
| # rules. A category is context, never an invented canonical match. | |
| if not hits and category is not None: | |
| selected.add(f"category:{category}") | |
| # Reverse category membership / aliases / groups only. Never walk | |
| # from a category or group to all of its sibling values. | |
| for node_id in sorted(seed_ids): | |
| for edge in self.adjacency[node_id]: | |
| other = edge["source"] if edge["target"] == node_id else edge["target"] | |
| if edge["relation"] in {"contains_value", "groups_value", "alias_of", "has_example"}: | |
| if self.nodes[other]["kind"] != "source": | |
| selected.add(other) | |
| if self.nodes[other]["kind"] == "attribute": | |
| attributes.add(other) | |
| for node_id in sorted(selected): | |
| if self.nodes[node_id]["kind"] != "category": | |
| continue | |
| for edge in self.adjacency[node_id]: | |
| if edge["relation"] == "uses_catalog" and edge["target"] == node_id: | |
| selected.add(edge["source"]) | |
| if self.nodes[edge["source"]]["kind"] == "attribute": | |
| attributes.add(edge["source"]) | |
| for node_id in sorted(selected): | |
| if self.nodes[node_id]["kind"] != "entity_type": | |
| continue | |
| for edge in self.adjacency[node_id]: | |
| if edge["relation"] == "describes_entity" and edge["target"] == node_id: | |
| attributes.add(edge["source"]) | |
| selected.add(edge["source"]) | |
| for attribute in sorted(attributes): | |
| for edge in self.adjacency[attribute]: | |
| if edge["relation"] in {"applies_to", "template_for"} and edge["target"] == attribute: | |
| selected.add(edge["source"]) | |
| if edge["relation"] == "describes_entity" and edge["source"] == attribute: | |
| selected.add(edge["target"]) | |
| # Priority: actual hits, their attribute/template/rules, then navigation. | |
| priority = {"attribute": 0, "template": 1, "rule": 2, "entity_type": 3, "alias": 4, "concept_group": 5, "category": 6} | |
| remaining = sorted(selected - seed_ids, key=lambda node_id: (priority.get(self.nodes[node_id]["kind"], 9), node_id)) | |
| ordered = [hit["node_id"] for hit in hits] + remaining | |
| bounded = ordered[: CONFIG["max_context_nodes"]] | |
| warnings = ["Контекст ограничен; часть дополнительных узлов не включена."] if len(ordered) > len(bounded) else [] | |
| selected = set(bounded) | |
| global_rules = sorted( | |
| node["id"] for node in self.graph["nodes"] | |
| if mode != "flat" and (hits or category is not None) and node["kind"] == "rule" and node["properties"].get("scope") == "global" | |
| )[: CONFIG["max_global_rules"]] | |
| edges = [deepcopy(edge) for edge in self.edges if mode == "graph" and edge["source"] in selected and edge["target"] in selected] | |
| return { | |
| "node_ids": bounded, "edge_ids": [edge["id"] for edge in edges], | |
| "global_rule_ids": global_rules, "nodes": [deepcopy(self.nodes[node_id]) for node_id in bounded], | |
| "global_rules": [deepcopy(self.nodes[node_id]) for node_id in global_rules], "edges": edges, | |
| "sources": [{key: source[key] for key in ("id", "path", "sha256")} for source in self.graph["sources"]], | |
| }, warnings | |
| def _trigrams(text: str) -> set[str]: | |
| padded = " " + text + " " | |
| return {padded[index:index + 3] for index in range(max(1, len(padded) - 2))} | |