Datasets:
Download code/robohome/src/engine/source/packages/asset_registry/index.py from RoboParty/RoboHome: direct link, hf CLI and curl.
- Browser
- Download file 18.1 kB
-
https://huggingface.co/datasets/RoboParty/RoboHome/resolve/main/code/robohome/src/engine/source/packages/asset_registry/index.py
- Command line
-
hf download hf://datasets/RoboParty/RoboHome/code/robohome/src/engine/source/packages/asset_registry/index.py
-
curl -L -o index.py https://huggingface.co/datasets/RoboParty/RoboHome/resolve/main/code/robohome/src/engine/source/packages/asset_registry/index.py
18.1 kB
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| import math | |
| import re | |
| import sqlite3 | |
| import time | |
| from collections.abc import Sequence | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Any | |
| import numpy as np # type: ignore[import-not-found] | |
| from packages.asset_registry.admission import normalize_category | |
| from packages.asset_registry.embeddings import EmbeddingProvider | |
| from packages.asset_registry.models import AdmissionStatus, AssetKind, AssetRecord | |
| FTS_LIMIT = 100 | |
| ANN_LIMIT = 100 | |
| HNSW_M = 32 | |
| HNSW_EF_CONSTRUCTION = 200 | |
| HNSW_EF_SEARCH = 64 | |
| def _source_key(value: str) -> str: | |
| normalized = value.casefold() | |
| if "gazebo fuel" in normalized or "google scanned objects" in normalized: | |
| return "google scanned objects" | |
| return normalized | |
| def record_text(record: AssetRecord) -> str: | |
| return " ".join( | |
| value | |
| for value in ( | |
| record.display_name, | |
| record.normalized_category or record.category, | |
| record.description, | |
| " ".join(record.tags), | |
| " ".join(record.synonyms), | |
| " ".join(record.affordances), | |
| ) | |
| if value | |
| ) | |
| def _sha256(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def build_sqlite_index(records: Sequence[AssetRecord], path: Path) -> list[AssetRecord]: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| temporary = path.with_suffix(path.suffix + ".tmp") | |
| temporary.unlink(missing_ok=True) | |
| connection = sqlite3.connect(temporary) | |
| try: | |
| connection.executescript( | |
| """ | |
| PRAGMA journal_mode=OFF; | |
| PRAGMA synchronous=OFF; | |
| CREATE TABLE assets ( | |
| row_id INTEGER PRIMARY KEY, | |
| asset_id TEXT NOT NULL UNIQUE, | |
| asset_kind TEXT NOT NULL, | |
| normalized_category TEXT NOT NULL, | |
| source TEXT NOT NULL, | |
| admission_status TEXT NOT NULL, | |
| dimensions_json TEXT, | |
| dimension_confidence REAL, | |
| quality_tier TEXT NOT NULL, | |
| record_json TEXT NOT NULL | |
| ); | |
| CREATE VIRTUAL TABLE active_fts USING fts5( | |
| asset_id, display_name, normalized_category, description, | |
| tags, synonyms, affordances, content='' | |
| ); | |
| CREATE VIRTUAL TABLE cold_fts USING fts5( | |
| asset_id, display_name, normalized_category, description, | |
| tags, synonyms, affordances, exclusion_reasons, content='' | |
| ); | |
| CREATE INDEX assets_kind_status ON assets(asset_kind, admission_status); | |
| CREATE INDEX assets_category ON assets(normalized_category); | |
| """ | |
| ) | |
| active: list[AssetRecord] = [] | |
| for row_id, record in enumerate(records, start=1): | |
| status = record.admission_status or AdmissionStatus.COLD | |
| category = record.normalized_category or normalize_category(record.category) | |
| connection.execute( | |
| "INSERT INTO assets VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", | |
| ( | |
| row_id, | |
| record.asset_id, | |
| record.asset_kind.value, | |
| category, | |
| record.source, | |
| status.value, | |
| json.dumps(record.dimensions_m) if record.dimensions_m else None, | |
| record.dimension_confidence, | |
| record.quality_tier, | |
| record.model_dump_json(), | |
| ), | |
| ) | |
| fields = ( | |
| row_id, | |
| record.asset_id, | |
| record.display_name, | |
| category, | |
| record.description, | |
| " ".join(record.tags), | |
| " ".join(record.synonyms), | |
| " ".join(record.affordances), | |
| ) | |
| if status == AdmissionStatus.ACTIVE: | |
| connection.execute( | |
| """INSERT INTO active_fts( | |
| rowid, asset_id, display_name, normalized_category, description, | |
| tags, synonyms, affordances | |
| ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", | |
| fields, | |
| ) | |
| active.append(record) | |
| else: | |
| connection.execute( | |
| """INSERT INTO cold_fts( | |
| rowid, asset_id, display_name, normalized_category, description, | |
| tags, synonyms, affordances, exclusion_reasons | |
| ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""", | |
| (*fields, " ".join(record.exclusion_reasons)), | |
| ) | |
| connection.commit() | |
| finally: | |
| connection.close() | |
| temporary.replace(path) | |
| return active | |
| def build_faiss_index( | |
| records: Sequence[AssetRecord], | |
| path: Path, | |
| embedding_provider: EmbeddingProvider, | |
| *, | |
| sqlite_path: Path, | |
| ) -> None: | |
| try: | |
| import faiss # type: ignore[import-not-found] | |
| except ImportError as error: | |
| raise RuntimeError("faiss-cpu is required; install robothousegen[asset-index]") from error | |
| vectors = embedding_provider.encode_passages([record_text(record) for record in records]) | |
| if vectors.shape != (len(records), embedding_provider.dimension): | |
| raise ValueError("embedding provider returned an unexpected vector shape") | |
| base = faiss.IndexHNSWFlat(embedding_provider.dimension, HNSW_M, faiss.METRIC_INNER_PRODUCT) | |
| base.hnsw.efConstruction = HNSW_EF_CONSTRUCTION | |
| base.hnsw.efSearch = HNSW_EF_SEARCH | |
| index = faiss.IndexIDMap2(base) | |
| with sqlite3.connect(sqlite_path) as connection: | |
| row_by_asset_id = dict(connection.execute("SELECT asset_id, row_id FROM assets")) | |
| ids = np.asarray([row_by_asset_id[record.asset_id] for record in records], dtype=np.int64) | |
| index.add_with_ids(np.ascontiguousarray(vectors), ids) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| temporary = path.with_suffix(path.suffix + ".tmp") | |
| faiss.write_index(index, str(temporary)) | |
| temporary.replace(path) | |
| class AssetQuery: | |
| query: str | |
| asset_id: str | None = None | |
| normalized_category: str | None = None | |
| dimensions_m: tuple[float, float, float] | None = None | |
| asset_kind: AssetKind = AssetKind.OBJECT | |
| source_priority: tuple[str, ...] = () | |
| class RetrievalResult: | |
| record: AssetRecord | |
| score: float | |
| lexical_score: float | |
| semantic_score: float | |
| dimension_fit: float | |
| quality_score: float | |
| source_priority_score: float | |
| exact_id: bool | |
| exact_category: bool | |
| class HybridAssetIndex: | |
| def __init__( | |
| self, | |
| sqlite_path: Path, | |
| vector_path: Path | None = None, | |
| embedding_provider: EmbeddingProvider | None = None, | |
| ) -> None: | |
| started = time.perf_counter() | |
| uri = f"file:{sqlite_path.resolve()}?mode=ro&immutable=1" | |
| self._connection = sqlite3.connect(uri, uri=True, check_same_thread=False) | |
| self._connection.row_factory = sqlite3.Row | |
| self._embedding_provider = embedding_provider | |
| self._faiss: Any | None = None | |
| if vector_path is not None: | |
| if embedding_provider is None: | |
| raise ValueError("embedding_provider is required with vector_path") | |
| try: | |
| import faiss | |
| except ImportError as error: | |
| raise RuntimeError( | |
| "faiss-cpu is required; install robothousegen[asset-index]" | |
| ) from error | |
| self._faiss = faiss.read_index(str(vector_path)) | |
| base = self._faiss.index if hasattr(self._faiss, "index") else self._faiss | |
| if hasattr(base, "hnsw"): | |
| base.hnsw.efSearch = HNSW_EF_SEARCH | |
| self.load_time_ms = (time.perf_counter() - started) * 1000 | |
| self.query_latencies_ms: list[float] = [] | |
| self._query_vector_cache: dict[str, np.ndarray] = {} | |
| def close(self) -> None: | |
| self._connection.close() | |
| def __enter__(self) -> HybridAssetIndex: | |
| return self | |
| def __exit__(self, *_: object) -> None: | |
| self.close() | |
| def _fts_expression(value: str) -> str: | |
| terms = list( | |
| dict.fromkeys( | |
| re.findall( | |
| r"[^\W_]+", | |
| value.casefold().replace("_", " ").replace("-", " "), | |
| flags=re.UNICODE, | |
| ) | |
| ) | |
| ) | |
| return " OR ".join(f'"{term.replace(chr(34), chr(34) * 2)}"' for term in terms) | |
| def _lexical(self, query: AssetQuery, limit: int) -> dict[int, float]: | |
| expression = self._fts_expression(query.query) | |
| if not expression: | |
| return {} | |
| rows = self._connection.execute( | |
| """ | |
| SELECT rowid, bm25(active_fts) AS rank FROM active_fts | |
| WHERE active_fts MATCH ? ORDER BY rank LIMIT ? | |
| """, | |
| (expression, limit), | |
| ).fetchall() | |
| if not rows: | |
| return {} | |
| raw = [-float(row["rank"]) for row in rows] | |
| low, high = min(raw), max(raw) | |
| scale = high - low | |
| return { | |
| int(row["rowid"]): (score - low) / scale if scale > 1e-9 else 1.0 | |
| for row, score in zip(rows, raw, strict=True) | |
| } | |
| def _semantic_batch(self, queries: Sequence[AssetQuery], limit: int) -> list[dict[int, float]]: | |
| if self._faiss is None or self._embedding_provider is None: | |
| return [{} for _ in queries] | |
| # Preserve the full entity description for semantic retrieval. The | |
| # normalized category is used independently for exact-category ranking; | |
| # embedding only "desk" discards qualifiers such as "open wooden work" | |
| # and can rank semantically adjacent chairs above the requested table. | |
| keys = [query.query.strip() or query.normalized_category or "object" for query in queries] | |
| missing = list(dict.fromkeys(key for key in keys if key not in self._query_vector_cache)) | |
| if missing: | |
| vectors = self._embedding_provider.encode_queries(missing) | |
| self._query_vector_cache.update(zip(missing, vectors, strict=True)) | |
| matrix = np.ascontiguousarray(np.stack([self._query_vector_cache[key] for key in keys])) | |
| distances, identifiers = self._faiss.search(matrix, limit) | |
| return [ | |
| { | |
| int(identifier): max(0.0, min(1.0, (float(distance) + 1.0) / 2.0)) | |
| for distance, identifier in zip(row_distances, row_ids, strict=True) | |
| if identifier >= 0 | |
| } | |
| for row_distances, row_ids in zip(distances, identifiers, strict=True) | |
| ] | |
| def _dimension_fit( | |
| expected: tuple[float, float, float] | None, | |
| actual: tuple[float, float, float] | None, | |
| confidence: float | None, | |
| ) -> float: | |
| if expected is None or actual is None: | |
| return 0.5 | |
| direct = sum( | |
| abs(math.log(a / b)) for a, b in zip(actual, expected, strict=True) | |
| ) / 3 | |
| swapped = ( | |
| abs(math.log(actual[0] / expected[1])) | |
| + abs(math.log(actual[1] / expected[0])) | |
| + abs(math.log(actual[2] / expected[2])) | |
| ) / 3 | |
| fit = math.exp(-min(direct, swapped)) | |
| return fit * (confidence if confidence is not None else 0.2) | |
| def batch_search( | |
| self, | |
| queries: Sequence[AssetQuery], | |
| *, | |
| limit: int = 5, | |
| candidate_limit: int = FTS_LIMIT, | |
| ) -> list[list[RetrievalResult]]: | |
| semantic = self._semantic_batch(queries, min(candidate_limit, ANN_LIMIT)) | |
| all_results: list[list[RetrievalResult]] = [] | |
| for query, semantic_scores in zip(queries, semantic, strict=True): | |
| started = time.perf_counter() | |
| lexical_scores = self._lexical(query, min(candidate_limit, FTS_LIMIT)) | |
| candidate_ids = set(lexical_scores) | set(semantic_scores) | |
| exact_rows = self._connection.execute( | |
| """ | |
| SELECT row_id FROM assets WHERE admission_status = 'ACTIVE' | |
| AND (asset_id = ? OR normalized_category = ?) LIMIT 200 | |
| """, | |
| (query.asset_id or "", query.normalized_category or ""), | |
| ).fetchall() | |
| candidate_ids.update(int(row[0]) for row in exact_rows) | |
| if not candidate_ids: | |
| all_results.append([]) | |
| self.query_latencies_ms.append((time.perf_counter() - started) * 1000) | |
| continue | |
| placeholders = ",".join("?" for _ in candidate_ids) | |
| rows = self._connection.execute( | |
| f"SELECT * FROM assets WHERE row_id IN ({placeholders}) " | |
| "AND admission_status = 'ACTIVE' AND asset_kind = ?", | |
| (*sorted(candidate_ids), query.asset_kind.value), | |
| ).fetchall() | |
| source_rank = { | |
| _source_key(source): (len(query.source_priority) - index) | |
| / max(1, len(query.source_priority)) | |
| for index, source in enumerate(query.source_priority) | |
| } | |
| results = [] | |
| for row in rows: | |
| record = AssetRecord.model_validate_json(row["record_json"]) | |
| row_id = int(row["row_id"]) | |
| dimensions = ( | |
| tuple(json.loads(row["dimensions_json"])) | |
| if row["dimensions_json"] | |
| else None | |
| ) | |
| dimension_fit = self._dimension_fit( | |
| query.dimensions_m, dimensions, row["dimension_confidence"] | |
| ) | |
| quality = {"A": 1.0, "B": 0.66, "C": 0.33, "REJECTED": 0.0}[ | |
| row["quality_tier"] | |
| ] | |
| source_score = source_rank.get(_source_key(row["source"]), 0.0) | |
| lexical = lexical_scores.get(row_id, 0.0) | |
| semantic_score = semantic_scores.get(row_id, 0.0) | |
| score = ( | |
| 0.35 * lexical | |
| + 0.25 * semantic_score | |
| + 0.20 * dimension_fit | |
| + 0.10 * quality | |
| + 0.10 * source_score | |
| ) | |
| exact_id = bool(query.asset_id and query.asset_id == row["asset_id"]) | |
| exact_category = bool( | |
| query.normalized_category | |
| and query.normalized_category == row["normalized_category"] | |
| ) | |
| results.append( | |
| RetrievalResult( | |
| record=record, | |
| score=score, | |
| lexical_score=lexical, | |
| semantic_score=semantic_score, | |
| dimension_fit=dimension_fit, | |
| quality_score=quality, | |
| source_priority_score=source_score, | |
| exact_id=exact_id, | |
| exact_category=exact_category, | |
| ) | |
| ) | |
| results.sort( | |
| key=lambda item: ( | |
| not item.exact_id, | |
| not item.exact_category, | |
| -item.score, | |
| item.record.asset_id, | |
| ) | |
| ) | |
| all_results.append(results[:limit]) | |
| self.query_latencies_ms.append((time.perf_counter() - started) * 1000) | |
| return all_results | |
| def timing_report(self) -> dict[str, float | int]: | |
| values = sorted(self.query_latencies_ms) | |
| p95_index = max(0, math.ceil(len(values) * 0.95) - 1) | |
| return { | |
| "cold_load_ms": round(self.load_time_ms, 3), | |
| "hot_query_count": len(values), | |
| "hot_query_p95_ms": round(values[p95_index], 3) if values else 0.0, | |
| "hot_query_max_ms": round(max(values), 3) if values else 0.0, | |
| } | |
| def write_index_manifest( | |
| output_dir: Path, | |
| *, | |
| records: Sequence[AssetRecord], | |
| active_records: Sequence[AssetRecord], | |
| embedding_provider: EmbeddingProvider, | |
| build_duration_s: float, | |
| ) -> Path: | |
| sqlite_path = output_dir / "asset_index.sqlite3" | |
| vector_path = output_dir / "asset_vectors.faiss" | |
| by_kind = { | |
| kind.value: sum(record.asset_kind == kind for record in active_records) | |
| for kind in AssetKind | |
| } | |
| low_confidence = sum( | |
| record.dimensions_m is not None and (record.dimension_confidence or 0) < 0.5 | |
| for record in records | |
| ) | |
| payload = { | |
| "schema_version": "1.1", | |
| "catalog_records": len(records), | |
| "active_records": len(active_records), | |
| "cold_records": len(records) - len(active_records), | |
| "active_by_kind": by_kind, | |
| "low_confidence_dimension_records": low_confidence, | |
| "embedding_model": embedding_provider.model_name, | |
| "embedding_dimension": embedding_provider.dimension, | |
| "hnsw": { | |
| "M": HNSW_M, | |
| "efConstruction": HNSW_EF_CONSTRUCTION, | |
| "efSearch": HNSW_EF_SEARCH, | |
| "metric": "inner_product_cosine_normalized", | |
| }, | |
| "retrieval": { | |
| "lexical_top_k": FTS_LIMIT, | |
| "ann_top_k": ANN_LIMIT, | |
| "weights": { | |
| "lexical": 0.35, | |
| "semantic": 0.25, | |
| "dimension_fit": 0.20, | |
| "quality": 0.10, | |
| "source_priority": 0.10, | |
| }, | |
| }, | |
| "files": { | |
| sqlite_path.name: _sha256(sqlite_path), | |
| vector_path.name: _sha256(vector_path), | |
| }, | |
| "build_duration_s": round(build_duration_s, 3), | |
| } | |
| path = output_dir / "asset_index_manifest.json" | |
| path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8") | |
| return path | |