Datasets:
File size: 18,135 Bytes
8ca7ba0 | 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 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 | 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)
@dataclass(frozen=True, slots=True)
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, ...] = ()
@dataclass(frozen=True, slots=True)
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()
@staticmethod
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)
]
@staticmethod
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
|