from __future__ import annotations import asyncio import json import queue import threading import time import uuid from collections import Counter from datetime import datetime, timezone from typing import Any import numpy as np from fastapi import APIRouter, HTTPException, Request, Response from fastapi.responses import StreamingResponse from app.config import MAX_CONCURRENT_INDEX_JOBS from app.engine.bm25 import MultiFieldBM25Index, tokenize_with_spans from app.engine.diagnostics import cluster_embeddings_2d, compute_corpus_diagnostics from app.engine.embedder import TokenTelemetry, embedder_cache from app.engine.facets import compute_crossfilter_facets from app.engine.hardware import detect_hardware from app.engine.ingest import load_hf_slice from app.schemas import ( DocumentDetail, FacetQueryRequest, FacetQueryResponse, IndexPrecomputedMetadata, IndexRunRequest, LassoRequest, LassoResponse, PrepareSliceRequest, PrepareSliceResponse, ReclusterRequest, RunManifest, ) from app.storage.project_store import project_store router = APIRouter(prefix="/api/projects", tags=["projects"]) _INDEX_SEMAPHORE = threading.Semaphore(max(1, MAX_CONCURRENT_INDEX_JOBS)) def _point_in_polygon(pts: np.ndarray, poly: list[list[float]]) -> np.ndarray: """Vectorized ray-casting point-in-polygon check for lasso selection.""" n_pts = len(pts) inside = np.zeros(n_pts, dtype=bool) m = len(poly) if m < 3: return inside x = pts[:, 0].astype(np.float64, copy=False) y = pts[:, 1].astype(np.float64, copy=False) j = m - 1 for i in range(m): xi, yi = float(poly[i][0]), float(poly[i][1]) xj, yj = float(poly[j][0]), float(poly[j][1]) crosses = (yi > y) != (yj > y) if np.any(crosses): dy = yj - yi x_intersect = (xj - xi) * (y[crosses] - yi) / dy + xi inside[crosses] ^= x[crosses] < x_intersect j = i return inside @router.get("", response_model=list[RunManifest]) def list_projects(): return project_store.list_runs() @router.get("/{run_id}", response_model=RunManifest) def get_project(run_id: str): try: return project_store.load_run(run_id).manifest except FileNotFoundError as exc: raise HTTPException(status_code=404, detail=str(exc)) from exc @router.delete("/{run_id}") def delete_project(run_id: str): project_store.delete_run(run_id) return {"deleted": run_id} @router.get("/{run_id}/atlas-binary") def get_atlas_binary(run_id: str): try: run = project_store.load_run(run_id) except FileNotFoundError as exc: raise HTTPException(status_code=404, detail=str(exc)) from exc return Response( content=run.atlas_binary, media_type="application/octet-stream", headers={ "X-Ostra-Doc-Count": str(run.manifest.doc_count), "X-Ostra-Stride-Floats": "8", "Cache-Control": "public, max-age=3600", }, ) @router.get("/{run_id}/docs/{doc_id}", response_model=DocumentDetail) def get_document_detail(run_id: str, doc_id: int): try: run = project_store.load_run(run_id) except FileNotFoundError as exc: raise HTTPException(status_code=404, detail=str(exc)) from exc n = len(run.indexed_texts) if doc_id < 0 or doc_id >= n: raise HTTPException(status_code=404, detail=f"doc_id {doc_id} out of range [0, {n - 1}]") cid = int(run.cluster_ids[doc_id]) neighbors = [] for k_idx in range(min(8, run.nn_indices.shape[1])): nid = int(run.nn_indices[doc_id, k_idx]) neighbors.append( { "doc_id": nid, "cosine": round(float(run.nn_cosines[doc_id, k_idx]), 4), "title_preview": run.doc_title_preview(nid), "label": run.labels[nid] if run.labels is not None else None, } ) return DocumentDetail( doc_id=doc_id, indexed_text=run.indexed_texts[doc_id], fields={f: vals[doc_id] for f, vals in run.docs_by_field.items()}, metadata={mf: vals[doc_id] for mf, vals in run.metadata_by_field.items()}, label=run.labels[doc_id] if run.labels is not None else None, cluster_id=cid, cluster_label=run.cluster_label_map.get(cid, "Unclustered"), x=round(float(run.coords_2d[doc_id, 0]), 5), y=round(float(run.coords_2d[doc_id, 1]), 5), token_count=int(run.token_counts[doc_id]), max_seq_len=run.manifest.health.max_seq_len, is_truncated=bool(run.is_truncated[doc_id]), truncation_ratio=round(float(run.truncation_ratio[doc_id]), 4), truncated_char_offset=run.truncated_char_offsets[doc_id], subword_fertility=round(float(run.subword_fertility[doc_id]), 3), hubness_nk=int(run.hubness_nk[doc_id]), purity=round(float(run.purity[doc_id]), 4), is_near_dup=bool(run.is_near_dup[doc_id]), neighbors=neighbors, ) @router.post("/{run_id}/lasso", response_model=LassoResponse) def inspect_lasso(run_id: str, req: LassoRequest): try: run = project_store.load_run(run_id) except FileNotFoundError as exc: raise HTTPException(status_code=404, detail=str(exc)) from exc mask = _point_in_polygon(run.coords_2d, req.polygon) doc_ids = np.flatnonzero(mask).tolist() if not doc_ids: return LassoResponse( count=0, doc_ids=[], top_terms=[], truncation_rate=0.0, avg_hubness=0.0, label_distribution={}, sample_docs=[], ) term_counts: Counter[str] = Counter() for did in doc_ids[:400]: for raw, _, _, _ in tokenize_with_spans(run.indexed_texts[did]): if len(raw) >= 3 and not raw.isdigit(): term_counts[raw.lower()] += 1 top_terms = [t for t, _ in term_counts.most_common(8)] trunc_rate = float(run.is_truncated[doc_ids].mean()) avg_hub = float(run.hubness_nk[doc_ids].mean()) lbl_dist: dict[str, int] = {} if run.labels is not None: c_lbl = Counter(run.labels[did] for did in doc_ids) lbl_dist = dict(c_lbl.most_common(10)) sample_docs = [ { "doc_id": did, "title_preview": run.doc_title_preview(did), "label": run.labels[did] if run.labels is not None else None, "hubness_nk": int(run.hubness_nk[did]), "is_truncated": bool(run.is_truncated[did]), } for did in doc_ids[:25] ] return LassoResponse( count=len(doc_ids), doc_ids=doc_ids, top_terms=top_terms, truncation_rate=round(trunc_rate, 4), avg_hubness=round(avg_hub, 2), label_distribution=lbl_dist, sample_docs=sample_docs, ) @router.post("/{run_id}/facets", response_model=FacetQueryResponse) def query_facets(run_id: str, req: FacetQueryRequest): try: run = project_store.load_run(run_id) except FileNotFoundError as exc: raise HTTPException(status_code=404, detail=str(exc)) from exc return compute_crossfilter_facets(run, req) @router.post("/{run_id}/recluster", response_model=RunManifest) def recluster_project(run_id: str, req: ReclusterRequest): """Live sub-50ms re-clustering at Coarse / Balanced / Fine / Pinpoint granularity or drill-down split.""" try: run = project_store.load_run(run_id) except FileNotFoundError as exc: raise HTTPException(status_code=404, detail=str(exc)) from exc cluster_ids, clusters = cluster_embeddings_2d( coords_2d=run.coords_2d, texts=run.indexed_texts, embeddings=run.embeddings, granularity=req.granularity, existing_cluster_ids=run.cluster_ids if req.focus_cluster_id is not None else None, focus_cluster_id=req.focus_cluster_id, sub_clusters=req.sub_clusters, ) return project_store.update_run_clusters(run_id, cluster_ids, clusters) @router.post("/index") async def index_hf_dataset_stream(req: IndexRunRequest): """Stream real-time SSE indexing progress: HF ingest -> Tokenize/Embed -> BM25 -> Diagnostics.""" q: queue.Queue[dict[str, Any] | None] = queue.Queue() def emit(event: str, payload: dict[str, Any]) -> None: q.put({"event": event, "data": payload}) def worker() -> None: acquired = False try: hw = detect_hardware() effective_max_rows = min(req.max_rows, hw.max_rows_limit) effective_batch_size = min(req.batch_size, hw.default_batch_size) if (hw.is_hf_space and not hw.cuda_available) else req.batch_size if not _INDEX_SEMAPHORE.acquire(blocking=False): emit( "progress", { "stage": "queue", "message": "Another indexing job is running on this Space — waiting for slot…", "percent": 2.0, }, ) _INDEX_SEMAPHORE.acquire() acquired = True t_start = time.perf_counter() emit( "progress", { "stage": "ingest", "message": f"Streaming up to {effective_max_rows:,} rows from {req.dataset_id}…", "percent": 5.0, }, ) sliced = load_hf_slice( dataset_id=req.dataset_id.strip(), config=req.config, split=req.split, max_rows=effective_max_rows, dense_fields=req.dense_fields, dense_template=req.dense_template, bm25_fields=req.bm25_fields, metadata_fields=req.metadata_fields, label_field=req.label_field, ) indexed_texts: list[str] = sliced["indexed_texts"] n_docs = len(indexed_texts) if n_docs < 5: raise ValueError( f"Only {n_docs} non-empty documents found with template '{req.dense_template}'." ) emit( "progress", { "stage": "model_load", "message": f"Loading embedding model {req.model_id}…", "percent": 14.0, "doc_count": n_docs, }, ) embedder = embedder_cache.get( model_id=req.model_id.strip(), preferred_device=req.preferred_device, max_seq_len_override=req.max_seq_len, ) emit( "progress", { "stage": "tokenize", "message": f"Auditing tokenization & silent truncation on {n_docs:,} docs…", "percent": 20.0, "device": embedder.device_label, "backend": embedder.backend_name, }, ) telemetry = embedder.inspect_truncation_and_fertility( indexed_texts, prefix=req.doc_prefix ) trunc_so_far = int(telemetry.is_truncated.sum()) emit( "progress", { "stage": "embed", "message": f"Embedding {n_docs:,} docs on {embedder.device_label}…", "percent": 25.0, "done": 0, "total": n_docs, "truncated_count": trunc_so_far, "device": embedder.device_label, "backend": embedder.backend_name, }, ) t_embed0 = time.perf_counter() def on_embed_progress(done: int, total: int, rate: float) -> None: pct = 25.0 + 43.0 * (done / max(total, 1)) emit( "progress", { "stage": "embed", "message": f"Embedded {done:,}/{total:,} docs ({rate:.0f} docs/s)", "percent": round(pct, 1), "done": done, "total": total, "docs_per_sec": round(rate, 1), "truncated_count": trunc_so_far, "device": embedder.device_label, "backend": embedder.backend_name, }, ) embeddings = embedder.encode_corpus( indexed_texts, prefix=req.doc_prefix, batch_size=effective_batch_size, progress_cb=on_embed_progress, ) embed_seconds = max(time.perf_counter() - t_embed0, 1e-4) docs_per_sec = n_docs / embed_seconds emit( "progress", { "stage": "bm25", "message": f"Building multi-field sparse BM25 index ({', '.join(req.bm25_fields)})…", "percent": 72.0, "truncated_count": trunc_so_far, "device": embedder.device_label, }, ) bm25 = MultiFieldBM25Index.build( docs_by_field=sliced["docs_by_field"], fields=req.bm25_fields, ) def on_diag_progress(msg: str, frac: float) -> None: emit( "progress", { "stage": "diagnostics", "message": msg, "percent": round(75.0 + 20.0 * frac, 1), "truncated_count": trunc_so_far, "device": embedder.device_label, }, ) diag = compute_corpus_diagnostics( embeddings=embeddings, texts=indexed_texts, telemetry=telemetry, labels=sliced["labels"], use_umap=True, progress_cb=on_diag_progress, ) run_id = f"run_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}" short_ds = req.dataset_id.split("/")[-1] short_mod = req.model_id.split("/")[-1] run_name = req.run_name.strip() if req.run_name and req.run_name.strip() else f"{short_ds} · {short_mod}" initial_weights = { f: float(req.bm25_initial_weights.get(f, 1.0)) for f in req.bm25_fields } manifest = RunManifest( run_id=run_id, run_name=run_name, created_at=datetime.now(timezone.utc).isoformat(), dataset_id=req.dataset_id.strip(), config=req.config, split=req.split, max_rows=effective_max_rows, doc_count=n_docs, dense_fields=req.dense_fields, dense_template=req.dense_template, bm25_fields=req.bm25_fields, bm25_initial_weights=initial_weights, metadata_fields=sliced["all_meta_fields"], label_field=req.label_field, model_id=req.model_id.strip(), doc_prefix=req.doc_prefix, query_prefix=req.query_prefix, backend_used=embedder.backend_name, device_label=embedder.device_label, embed_seconds=round(embed_seconds, 2), docs_per_sec=round(docs_per_sec, 1), health=diag.health, clusters=diag.clusters, contours=diag.contours, coord_bounds=diag.coord_bounds, ) emit( "progress", { "stage": "save", "message": "Persisting Parquet + binary Atlas cache to .ostra/…", "percent": 97.0, }, ) loaded = project_store.save_run( manifest=manifest, embeddings=embeddings, diag=diag, telemetry=telemetry, bm25=bm25, indexed_texts=indexed_texts, docs_by_field=sliced["docs_by_field"], metadata_by_field=sliced["metadata_by_field"], labels=sliced["labels"], ) emit( "complete", { "run_id": loaded.manifest.run_id, "elapsed_seconds": round(time.perf_counter() - t_start, 2), "manifest": loaded.manifest.model_dump(), }, ) except Exception as exc: emit("error", {"message": str(exc)}) finally: if acquired: _INDEX_SEMAPHORE.release() q.put(None) threading.Thread(target=worker, daemon=True).start() def _next_event() -> dict[str, Any] | None | str: try: return q.get(timeout=10.0) except queue.Empty: return "__keepalive__" async def event_generator(): while True: item = await asyncio.to_thread(_next_event) if item == "__keepalive__": # Prevent HF Spaces reverse proxy idle timeouts during model download / UMAP yield ": keepalive\n\n" continue if item is None: break yield f"event: {item['event']}\ndata: {json.dumps(item['data'])}\n\n" return StreamingResponse( event_generator(), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no", }, ) @router.post("/prepare-slice", response_model=PrepareSliceResponse) def prepare_hf_slice_for_client(req: PrepareSliceRequest): """ Stream & format an HF dataset slice so the browser can compute dense embeddings locally on the user's GPU (WebGPU/Metal) or CPU (WASM) with zero server GPU/CPU load. """ hw = detect_hardware() # Browser WebGPU/WASM handles heavier slices cleanly even on CPU Basic HF Spaces client_row_cap = 5000 if hw.is_hf_space else max(hw.max_rows_limit, 5000) effective_max_rows = min(req.max_rows, client_row_cap) try: sliced = load_hf_slice( dataset_id=req.dataset_id.strip(), config=req.config, split=req.split, max_rows=effective_max_rows, dense_fields=req.dense_fields, dense_template=req.dense_template, bm25_fields=req.bm25_fields, metadata_fields=req.metadata_fields, label_field=req.label_field, ) except Exception as exc: raise HTTPException( status_code=400, detail=f"Failed to stream Hugging Face dataset '{req.dataset_id}': {exc}", ) from exc n_docs = len(sliced["indexed_texts"]) if n_docs < 5: raise HTTPException( status_code=400, detail=f"Only {n_docs} non-empty documents found with template '{req.dense_template}'.", ) return PrepareSliceResponse( doc_count=n_docs, indexed_texts=sliced["indexed_texts"], docs_by_field=sliced["docs_by_field"], metadata_by_field=sliced["metadata_by_field"], labels=sliced["labels"], all_text_fields=sliced["all_text_fields"], all_meta_fields=sliced["all_meta_fields"], ) def _telemetry_from_precomputed( meta: IndexPrecomputedMetadata, indexed_texts: list[str], ) -> TokenTelemetry: n_docs = len(indexed_texts) t = meta.telemetry if ( t is not None and len(t.token_counts) == n_docs and len(t.is_truncated) == n_docs and len(t.truncation_ratio) == n_docs and len(t.truncated_char_offsets) == n_docs and len(t.subword_fertility) == n_docs ): return TokenTelemetry( token_counts=np.asarray(t.token_counts, dtype=np.int32), is_truncated=np.asarray(t.is_truncated, dtype=bool), truncation_ratio=np.asarray(t.truncation_ratio, dtype=np.float32), truncated_char_offsets=list(t.truncated_char_offsets), subword_fertility=np.asarray(t.subword_fertility, dtype=np.float32), max_seq_len=max(int(t.max_seq_len), 32), ) # Lightweight fallback if client omitted token telemetry max_seq = 512 token_counts = np.empty(n_docs, dtype=np.int32) is_truncated = np.zeros(n_docs, dtype=bool) truncation_ratio = np.zeros(n_docs, dtype=np.float32) truncated_offsets: list[int | None] = [None] * n_docs subword_fertility = np.ones(n_docs, dtype=np.float32) for i, text in enumerate(indexed_texts): est = max(1, int(round(len(text.split()) * 1.3)) + 2) token_counts[i] = est if est > max_seq: is_truncated[i] = True truncation_ratio[i] = float((est - max_seq) / est) truncated_offsets[i] = int(len(text) * (max_seq / est)) return TokenTelemetry( token_counts=token_counts, is_truncated=is_truncated, truncation_ratio=truncation_ratio, truncated_char_offsets=truncated_offsets, subword_fertility=subword_fertility, max_seq_len=max_seq, ) @router.post("/index-precomputed") async def index_precomputed_embeddings_stream(request: Request): """ Finalize a run whose dense embeddings were computed on the user's device (WebGPU Metal/GPU or Browser WASM CPU): builds BM25, corpus diagnostics, UMAP 2D, and persists Parquet/Atlas cache without ever loading embedding weights on the Space server. Supports both: 1. Raw binary `application/octet-stream` framed as: [4-byte little-endian uint32 metadata_byte_len][UTF-8 metadata JSON][float32 embeddings] (bypasses multipart parsers & part-size limits completely) 2. `multipart/form-data` (`metadata` file or string + `embeddings` file) with 1 GB part limit. """ content_type = (request.headers.get("content-type") or "").lower() if content_type.startswith("application/octet-stream"): body = await request.body() if len(body) < 4: raise HTTPException(status_code=400, detail="Truncated binary payload.") meta_len = int.from_bytes(body[:4], "little") if meta_len <= 0 or 4 + meta_len > len(body): raise HTTPException(status_code=400, detail="Invalid binary metadata header length.") meta_payload: bytes | str = body[4 : 4 + meta_len] raw_bytes = body[4 + meta_len :] else: form = await request.form(max_part_size=1024 * 1024 * 1024) raw_meta = form.get("metadata") embeddings = form.get("embeddings") if raw_meta is None: raise HTTPException(status_code=400, detail="Missing 'metadata' part.") if embeddings is None or not hasattr(embeddings, "read"): raise HTTPException(status_code=400, detail="Missing 'embeddings' file part.") meta_payload = await raw_meta.read() if hasattr(raw_meta, "read") else raw_meta raw_bytes = await embeddings.read() try: meta = IndexPrecomputedMetadata.model_validate_json(meta_payload) except Exception as exc: raise HTTPException(status_code=400, detail=f"Invalid metadata payload: {exc}") from exc n_docs = len(meta.indexed_texts) dim = int(meta.embedding_dim) expected_bytes = n_docs * dim * 4 if n_docs < 5: raise HTTPException(status_code=400, detail="At least 5 documents are required.") if len(raw_bytes) != expected_bytes: raise HTTPException( status_code=400, detail=f"Embedding buffer size mismatch: got {len(raw_bytes)} bytes, expected {expected_bytes} ({n_docs}x{dim} float32).", ) vecs = np.frombuffer(raw_bytes, dtype=np.float32).reshape(n_docs, dim).copy() if not np.all(np.isfinite(vecs)): raise HTTPException(status_code=400, detail="Embeddings contain NaN or Inf values.") norms = np.linalg.norm(vecs, axis=1, keepdims=True) vecs = (vecs / np.maximum(norms, 1e-12)).astype(np.float32) q: queue.Queue[dict[str, Any] | None] = queue.Queue() def emit(event: str, payload: dict[str, Any]) -> None: q.put({"event": event, "data": payload}) def worker() -> None: try: t_start = time.perf_counter() telemetry = _telemetry_from_precomputed(meta, meta.indexed_texts) trunc_so_far = int(telemetry.is_truncated.sum()) emit( "progress", { "stage": "bm25", "message": f"Building multi-field sparse BM25 index ({', '.join(meta.bm25_fields)})…", "percent": 74.0, "truncated_count": trunc_so_far, "device": meta.device_label, }, ) bm25 = MultiFieldBM25Index.build( docs_by_field=meta.docs_by_field, fields=meta.bm25_fields, ) def on_diag_progress(msg: str, frac: float) -> None: emit( "progress", { "stage": "diagnostics", "message": msg, "percent": round(77.0 + 18.0 * frac, 1), "truncated_count": trunc_so_far, "device": meta.device_label, }, ) diag = compute_corpus_diagnostics( embeddings=vecs, texts=meta.indexed_texts, telemetry=telemetry, labels=meta.labels, use_umap=True, progress_cb=on_diag_progress, ) run_id = f"run_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}" short_ds = meta.dataset_id.split("/")[-1] short_mod = meta.model_id.split("/")[-1] run_name = ( meta.run_name.strip() if meta.run_name and meta.run_name.strip() else f"{short_ds} · {short_mod}" ) initial_weights = { f: float(meta.bm25_initial_weights.get(f, 1.0)) for f in meta.bm25_fields } all_meta_fields = meta.all_meta_fields or list(meta.metadata_by_field.keys()) manifest = RunManifest( run_id=run_id, run_name=run_name, created_at=datetime.now(timezone.utc).isoformat(), dataset_id=meta.dataset_id.strip(), config=meta.config, split=meta.split, max_rows=meta.max_rows, doc_count=n_docs, dense_fields=meta.dense_fields, dense_template=meta.dense_template, bm25_fields=meta.bm25_fields, bm25_initial_weights=initial_weights, metadata_fields=all_meta_fields, label_field=meta.label_field, model_id=meta.model_id.strip(), doc_prefix=meta.doc_prefix, query_prefix=meta.query_prefix, backend_used=meta.backend_used, device_label=meta.device_label, embed_seconds=round(max(meta.embed_seconds, 0.01), 2), docs_per_sec=round(meta.docs_per_sec, 1), health=diag.health, clusters=diag.clusters, contours=diag.contours, coord_bounds=diag.coord_bounds, ) emit( "progress", { "stage": "save", "message": "Persisting Parquet + binary Atlas cache…", "percent": 97.0, "device": meta.device_label, }, ) loaded = project_store.save_run( manifest=manifest, embeddings=vecs, diag=diag, telemetry=telemetry, bm25=bm25, indexed_texts=meta.indexed_texts, docs_by_field=meta.docs_by_field, metadata_by_field=meta.metadata_by_field, labels=meta.labels, ) emit( "complete", { "run_id": loaded.manifest.run_id, "elapsed_seconds": round(time.perf_counter() - t_start, 2), "manifest": loaded.manifest.model_dump(), }, ) except Exception as exc: emit("error", {"message": str(exc)}) finally: q.put(None) threading.Thread(target=worker, daemon=True).start() def _next_event() -> dict[str, Any] | None | str: try: return q.get(timeout=10.0) except queue.Empty: return "__keepalive__" async def event_generator(): while True: item = await asyncio.to_thread(_next_event) if item == "__keepalive__": yield ": keepalive\n\n" continue if item is None: break yield f"event: {item['event']}\ndata: {json.dumps(item['data'])}\n\n" return StreamingResponse( event_generator(), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no", }, )