Spaces:
Paused
Paused
Deploy Sensorflow Studio
Browse filesFiles changed (26)
- app_backend.py+4
- sensorflow/raremine/__init__.pyAdded+9
- sensorflow/raremine/api.pyAdded+410
- sensorflow/raremine/curator_metrics.pyAdded+185
- sensorflow/raremine/dedup.pyAdded+176
- sensorflow/raremine/lineage.pyAdded+134
- sensorflow/raremine/miner.pyAdded+591
- sensorflow/raremine/models.pyAdded+461
- sensorflow/raremine/pipeline.pyAdded+189
- sensorflow/raremine/quantval.pyAdded+119
- sensorflow/raremine/scenes.pyAdded+500
- sensorflow/raremine/tracks.pyAdded+102
- src/App.tsx+5
- src/components/help/HelpMenu.tsx+2
- src/components/raremine/CandidateCard.tsxAdded+411
- src/components/raremine/ConfidenceGauges.tsxAdded+65
- src/components/raremine/CoverageQualityTab.tsxAdded+271
- src/components/raremine/SceneCanvas.tsxAdded+94
- src/components/raremine/TrackStrip.tsxAdded+93
- src/components/raremine/shared.tsxAdded+96
- src/content/glossary.ts+21
- src/content/pageHelp.ts+12
- src/context/LabelEvalContext.tsx+2
- src/pages/raremine/RareMinePage.tsxAdded+243
- src/services/raremine.tsAdded+108
- src/types/raremine.tsAdded+268
1483 unmodified lines1484148514861487148814891483 unmodified linesfrom sensorflow.rca.api import router as rca_routerapp.include_router(rca_router)# Mount static folderstatic_dir = Path(__file__).parent / "static"if static_dir.exists():1483 unmodified lines14841485148614871488148914901491149214931483 unmodified linesfrom sensorflow.rca.api import router as rca_routerapp.include_router(rca_router)# Multimodal rare-event mining & perception QA (costumed-pedestrian miner).from sensorflow.raremine.api import router as raremine_routerapp.include_router(raremine_router)# Mount static folderstatic_dir = Path(__file__).parent / "static"if static_dir.exists():
123456789"""Multimodal rare-event mining & perception QA for costumed pedestrians.
Core separation of powers (never collapsed into one judgment): - the MINER proposes candidates from available sensor evidence only; - AUTOMATED VALIDATION measures them against ground truth when present; - HUMAN validation confirms or rejects; - STATISTICS (curator metrics) determine how good the mining is; - TRAINING usage is a governed decision with an explicit leakage guard."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410"""FastAPI router for the rare-event miner (included by app_backend).
All state persists under runs/raremine/. The optional LLM narrative followsthe sensorflow.evaluation.copilot pattern: try local Ollama, always fall backto a deterministic evidence-derived analysis so nothing requires a model."""
from __future__ import annotations
import jsonfrom typing import Any, Dict, List, Optional
import httpxfrom fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModel, Field
from sensorflow.raremine import curator_metrics, dedup as dedup_mod, lineage as lineage_modfrom sensorflow.raremine import pipeline as pipe_modfrom sensorflow.raremine import quantval, scenes as scenes_modfrom sensorflow.raremine.lineage import LeakageErrorfrom sensorflow.raremine.models import DESTINATIONS, get_store
router = APIRouter(prefix="/api/raremine")
class GenerateScenesRequest(BaseModel): n: int = Field(60, ge=10, le=2000) seed: int = 7
class MineRequest(BaseModel): bank_id: Optional[str] = None config: Dict[str, Any] = Field(default_factory=dict) diversity_budget: int = Field(12, ge=1, le=200)
class ReviewRequest(BaseModel): action: str # approve | reject note: str = "" reviewer: str = "human-reviewer" destination: Optional[str] = None
class OverrideRequest(BaseModel): track_candidate_id: str actor: str reason: str
class PromoteRequest(BaseModel): track_candidate_id: str curator: str = "human-curator"
def _bank_or_404(bank_id: Optional[str] = None): store = get_store() if bank_id: bank = store.get("banks", bank_id) if bank is None: raise HTTPException(404, f"unknown scene bank {bank_id}") return bank banks = store.all("banks") if not banks: raise HTTPException(404, "no scene bank generated yet") return sorted(banks, key=lambda b: b.created_at)[-1]
def _tc_or_404(track_candidate_id: str): tc = get_store().get("track_candidates", track_candidate_id) if tc is None: raise HTTPException(404, f"unknown track candidate {track_candidate_id}") return tc
def _tc_summary(tc) -> Dict[str, Any]: rep = tc.representative return { "track_candidate_id": tc.track_candidate_id, "sequence_id": tc.sequence_id, "track_id": tc.track_id, "frame_count": tc.frame_count, "duration_frames": tc.duration_frames, "stage": tc.stage, "destination": tc.destination, "diversity_selected": tc.diversity_selected, "duplicate_of": tc.duplicate_of, "max_difficulty": tc.max_difficulty, "max_visibility": tc.max_visibility, "representative_frames": tc.representative_frames.model_dump(), "auto_validation": tc.auto_validation, "human_validation": tc.human_validation, "candidate": rep.model_dump(), }
# ------------------------------------------------------------------ scene bank
@router.post("/scenes/generate")def generate_scenes(req: GenerateScenesRequest): store = get_store() bank = scenes_mod.generate_scene_bank(store, n_scenes=req.n, seed=req.seed) return {"status": "ok", "bank": bank.model_dump()}
@router.get("/status")def status(): store = get_store() banks = sorted(store.all("banks"), key=lambda b: b.created_at) runs = sorted(store.all("runs"), key=lambda r: r.created_at) tcs = store.all("track_candidates") priority_hist: Dict[str, int] = {} for t in tcs: if t.duplicate_of is None and t.representative.edge_case_detected: p = t.representative.curation_priority priority_hist[p] = priority_hist.get(p, 0) + 1 return { "bank": banks[-1].model_dump() if banks else None, "last_run": runs[-1].model_dump() if runs else None, "num_track_candidates": len([t for t in tcs if t.duplicate_of is None]), "num_detected": sum(1 for t in tcs if t.duplicate_of is None and t.representative.edge_case_detected), "priority_histogram": priority_hist, "dedup_report": (store.meta.get("last_run") or {}).get("dedup_report"), "diversity_report": (store.meta.get("last_run") or {}).get("diversity_report"), }
# ------------------------------------------------------------------ mining
@router.post("/mine")def mine(req: MineRequest): store = get_store() bank = _bank_or_404(req.bank_id) run = pipe_mod.run_full_pipeline(store, bank.bank_id, config=req.config or None, diversity_budget=req.diversity_budget) return {"status": "ok", "run": run.model_dump(), "dedup_report": store.meta["last_run"]["dedup_report"], "diversity_report": store.meta["last_run"]["diversity_report"]}
@router.get("/candidates")def list_candidates(priority: Optional[str] = None, status: Optional[str] = None, costume: Optional[str] = None, difficulty: Optional[str] = None, detected_only: bool = True, bank_id: Optional[str] = None): store = get_store() bank = _bank_or_404(bank_id) items = pipe_mod.review_queue(store, bank.bank_id, priority=priority, status=status, costume=costume, difficulty=difficulty) if detected_only: items = [t for t in items if t.representative.edge_case_detected] return {"count": len(items), "candidates": [_tc_summary(t) for t in items]}
@router.get("/candidates/{track_candidate_id}")def get_candidate(track_candidate_id: str): store = get_store() tc = _tc_or_404(track_candidate_id) frames = [store.get("candidates", cid) for cid in tc.frame_candidate_ids] rec = lineage_mod.get_lineage(store, track_candidate_id) return { **_tc_summary(tc), "frame_candidates": [f.model_dump() for f in frames if f is not None], "lineage": rec.model_dump() if rec else None, }
@router.get("/candidates/{track_candidate_id}/scene")def candidate_scene(track_candidate_id: str, scene_id: Optional[str] = None): """Schematic scene data for the BEV/2D canvas: object positions + bboxes, with the candidate object flagged. GT overlay only when GT is available.""" store = get_store() tc = _tc_or_404(track_candidate_id) sid = scene_id or tc.representative.scene_id scene = store.get("scenes", sid) if scene is None: raise HTTPException(404, f"unknown scene {sid}") objects = [] for obj in scene.objects: entry = { "object_id": obj.object_id, "is_candidate": obj.track_id == tc.track_id, "position": obj.position, "distance_m": obj.distance_m, "bbox_2d": obj.bbox_2d, "context": obj.context, } if scene.modalities.get("gt_annotations"): gt = next((g for g in scene.gt_boxes if g.object_id == obj.object_id), None) entry["gt"] = gt.model_dump() if gt else None objects.append(entry) preds = [p.model_dump(exclude={"planted_failure", "iou_with_gt"}) for p in scene.baseline_predictions] if scene.modalities.get("baseline_predictions") else None return { "scene_id": scene.scene_id, "sequence_id": scene.sequence_id, "frame_index": scene.frame_index, "lighting": scene.lighting, "weather": scene.weather, "modalities": scene.modalities, "objects": objects, "baseline_predictions": preds, }
@router.get("/tracks")def tracks_view(bank_id: Optional[str] = None): store = get_store() bank = _bank_or_404(bank_id) tcs = [t for t in store.where("track_candidates", bank_id=bank.bank_id) if t.duplicate_of is None and t.frame_count > 1] tcs.sort(key=lambda t: -t.frame_count) out = [] for t in tcs: frames = [store.get("candidates", cid) for cid in t.frame_candidate_ids] out.append({ **_tc_summary(t), "frames": [{ "candidate_id": f.candidate_id, "scene_id": f.scene_id, "frame_index": f.frame_index, "edge_case_detected": f.edge_case_detected, "confidence_rare_event": f.confidence_rare_event, "evidence_quality": f.evidence_quality, "perception_difficulty": f.perception_difficulty, "failure_observed": bool(f.observed_model_behavior and f.observed_model_behavior.failure_observed), } for f in frames if f is not None], }) return {"count": len(out), "tracks": out}
@router.get("/dedup/report")def dedup_report(): store = get_store() report = (store.meta.get("last_run") or {}).get("dedup_report") if report is None: raise HTTPException(404, "no mining run yet") return report
@router.get("/diversity/report")def diversity_report(): store = get_store() report = (store.meta.get("last_run") or {}).get("diversity_report") if report is None: raise HTTPException(404, "no mining run yet") return report
# ------------------------------------------------------------------ review + governance
@router.post("/review/{track_candidate_id}")def review(track_candidate_id: str, req: ReviewRequest): store = get_store() _tc_or_404(track_candidate_id) if req.destination is not None and req.destination not in DESTINATIONS: raise HTTPException(400, f"invalid destination {req.destination}") try: tc = pipe_mod.human_review(store, track_candidate_id, req.action, note=req.note, reviewer=req.reviewer, destination=req.destination) except LeakageError as e: raise HTTPException(403, str(e)) except ValueError as e: raise HTTPException(400, str(e)) rec = lineage_mod.get_lineage(store, track_candidate_id) return {"status": "ok", **_tc_summary(tc), "lineage": rec.model_dump() if rec else None}
@router.post("/governance/promote-training")def promote_training(req: PromoteRequest): """Attempt to route an example to TRAINING_CANDIDATE. Protected evaluation examples are refused (403) unless a governance override exists.""" store = get_store() _tc_or_404(req.track_candidate_id) try: rec = lineage_mod.promote_to_training(store, req.track_candidate_id, curator=req.curator) except LeakageError as e: raise HTTPException(403, str(e)) store.save() return {"status": "ok", "lineage": rec.model_dump()}
@router.post("/governance/override")def governance_override(req: OverrideRequest): store = get_store() _tc_or_404(req.track_candidate_id) try: rec = lineage_mod.governance_override(store, req.track_candidate_id, actor=req.actor, reason=req.reason) except ValueError as e: raise HTTPException(400, str(e)) store.save() return {"status": "ok", "lineage": rec.model_dump()}
@router.get("/destinations")def destinations(bank_id: Optional[str] = None): store = get_store() bank = _bank_or_404(bank_id) return pipe_mod.destinations_report(store, bank.bank_id)
@router.get("/lineage/{track_candidate_id}")def lineage(track_candidate_id: str): store = get_store() _tc_or_404(track_candidate_id) rec = lineage_mod.get_lineage(store, track_candidate_id) if rec is None: raise HTTPException(404, "no lineage record") return rec.model_dump()
@router.get("/lineage")def lineage_all(bank_id: Optional[str] = None): store = get_store() bank = _bank_or_404(bank_id) return lineage_mod.lineage_report(store, bank.bank_id)
# ------------------------------------------------------------------ reports
@router.get("/reports/quantval")def quantval_report(bank_id: Optional[str] = None): store = get_store() bank = _bank_or_404(bank_id) return quantval.quantitative_report(store, bank.bank_id)
@router.get("/reports/curator")def curator_report(bank_id: Optional[str] = None): store = get_store() bank = _bank_or_404(bank_id) return curator_metrics.curator_report(store, bank.bank_id)
@router.get("/reports/improvement")def improvement(bank_id: Optional[str] = None): store = get_store() bank = _bank_or_404(bank_id) return curator_metrics.improvement_report(store, bank.bank_id)
# ------------------------------------------------------------------ optional LLM narrative
def _deterministic_narrative(summary: Dict[str, Any]) -> str: c = summary["candidate"] lines = [f"# Candidate {summary['track_candidate_id']}", ""] lines.append(f"Proposed event: {c['event_type']} " f"({', '.join(c['costume_type']) or 'costume family undetermined'})") lines.append("") lines.append("## Separate confidences (never combined)") lines.append(f"- human identity: {c['confidence_human_identity']:.2f}") lines.append(f"- costume present: {c['confidence_costume']:.2f}") lines.append(f"- rare event: {c['confidence_rare_event']:.2f}") lines.append("") lines.append("## Evidence") for ev in c["visual_evidence"] + c["human_identity_evidence"]: lines.append(f"- [{ev['modality']}] {ev['description']}") lines.append("") lines.append("## Alternative hypotheses") for a in c["alternative_hypotheses"]: lines.append(f"- {a['hypothesis']} ({a['status']}, {a['confidence']:.2f}): {a['reason']}") lines.append("") lines.append(f"Priority {c['curation_priority']}: {c['priority_reason']}") lines.append("") lines.append("_This is a PROPOSAL derived from sensor evidence rules. It is not ground " "truth; validation measures it, humans confirm it, statistics decide its " "importance, and training usage is governed separately._") return "\n".join(lines)
@router.post("/candidates/{track_candidate_id}/explain")def explain_candidate(track_candidate_id: str): """Copilot-pattern narrative: local Ollama when reachable, deterministic evidence-based analysis otherwise. Advisory only.""" tc = _tc_or_404(track_candidate_id) summary = _tc_summary(tc) offline = _deterministic_narrative(summary) try: from sensorflow.evaluation.copilot import OLLAMA_ENDPOINTS # read-only reuse except Exception: OLLAMA_ENDPOINTS = [] prompt = ( "You are an advisory perception-QA copilot. A rule-based miner proposed this " "rare-event candidate (costumed pedestrian). Explain the evidence and risks; do NOT " "change any confidences or decisions.\n\nCANDIDATE (JSON):\n" + json.dumps(summary["candidate"], indent=2)[:6000] ) for ep in OLLAMA_ENDPOINTS: try: res = httpx.post(ep["url"], json={ "model": ep["model"], "messages": [{"role": "user", "content": prompt}], "stream": False, }, timeout=15.0) if res.status_code == 200: text = res.json().get("message", {}).get("content", "") if text: return {"status": "ok", "provider": ep["url"], "analysis": text} except Exception: continue return {"status": "ok", "provider": "offline_deterministic", "analysis": offline}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185"""Curator-quality statistics: how good is the MINER, measured against theplanted ground truth. Statistics determine importance — not the miner itself.
- mining precision / recall / false-discovery rate at track level - confidence calibration (binned reliability: stated confidence vs truth) - curation yield (validated / reviewed) - model-value (curated examples that expose a real baseline failure) - recurring-miss analysis -> improvement report feeding the next run config"""
from __future__ import annotations
from typing import Any, Dict, List, Optional, Tuple
from sensorflow.raremine.models import RareMineStore, Scene, SceneObject, TrackCandidate
CAL_BINS = [(0.0, 0.2), (0.2, 0.4), (0.4, 0.6), (0.6, 0.8), (0.8, 1.01)]
def _truth_by_track(store: RareMineStore, bank_id: str) -> Dict[Tuple[str, str], SceneObject]: """Planted truth per (sequence, track): the frame-0 object.""" truth: Dict[Tuple[str, str], SceneObject] = {} for scene in store.where("scenes", bank_id=bank_id): if scene.near_duplicate_of is not None: continue for obj in scene.objects: key = (scene.sequence_id, obj.track_id) if key not in truth: truth[key] = obj return truth
def _track_candidates(store: RareMineStore, bank_id: str) -> List[TrackCandidate]: return [t for t in store.where("track_candidates", bank_id=bank_id) if t.duplicate_of is None]
def curator_report(store: RareMineStore, bank_id: str) -> Dict[str, Any]: truth = _truth_by_track(store, bank_id) tcs = _track_candidates(store, bank_id)
tp = fp = fn = tn = 0 calibration = [{"bin": f"{lo:.1f}-{hi:.1f}", "n": 0, "true": 0} for lo, hi in CAL_BINS] proposed_tracks = set()
for tc in tcs: key = (tc.sequence_id, tc.track_id) proposed_tracks.add(key) obj = truth.get(key) truly_rare = obj is not None and obj.truth_kind == "costumed_pedestrian" detected = tc.representative.edge_case_detected if detected and truly_rare: tp += 1 elif detected and not truly_rare: fp += 1 elif not detected and truly_rare: fn += 1 else: tn += 1 conf = tc.representative.confidence_rare_event for i, (lo, hi) in enumerate(CAL_BINS): if lo <= conf < hi: calibration[i]["n"] += 1 calibration[i]["true"] += int(truly_rare) break
# planted positives the miner never even surfaced as track candidates for key, obj in truth.items(): if obj.truth_kind == "costumed_pedestrian" and key not in proposed_tracks: fn += 1
total_planted = sum(1 for o in truth.values() if o.truth_kind == "costumed_pedestrian") precision = round(tp / (tp + fp), 4) if (tp + fp) else None recall = round(tp / (tp + fn), 4) if (tp + fn) else None fdr = round(fp / (tp + fp), 4) if (tp + fp) else None
for row in calibration: row["observed_rate"] = round(row["true"] / row["n"], 3) if row["n"] else None
# curation yield + model value over human-reviewed examples reviewed = [t for t in tcs if t.human_validation is not None] approved = [t for t in reviewed if t.human_validation.get("action") == "approve"] curated_failure = 0 for t in approved: if _exposes_planted_failure(store, t): curated_failure += 1 return { "confusion": {"tp": tp, "fp": fp, "fn": fn, "tn": tn}, "planted_positives": total_planted, "mining_precision": precision, "mining_recall": recall, "false_discovery_rate": fdr, "calibration": calibration, "curation_yield": { "reviewed": len(reviewed), "approved": len(approved), "yield": round(len(approved) / len(reviewed), 3) if reviewed else None, }, "model_value": { "curated": len(approved), "expose_model_failure": curated_failure, "fraction": round(curated_failure / len(approved), 3) if approved else None, }, }
def _exposes_planted_failure(store: RareMineStore, tc: TrackCandidate) -> bool: for scene in store.where("scenes", sequence_id=tc.sequence_id): for pred in scene.baseline_predictions: if pred.planted_failure: return True # FALSE_NEGATIVE plants remove the prediction entirely if scene.modalities.get("baseline_predictions"): covered = {p.object_id for p in scene.baseline_predictions} for obj in scene.objects: if obj.track_id == tc.track_id and obj.object_id not in covered: return True return False
def improvement_report(store: RareMineStore, bank_id: str) -> Dict[str, Any]: """Recurring-miss analysis: what the miner misses or over-fires on, plus a config for the next run. Continuous-learning loop, statistics-driven.""" truth = _truth_by_track(store, bank_id) tcs = {(t.sequence_id, t.track_id): t for t in _track_candidates(store, bank_id)}
missed: List[Dict[str, Any]] = [] overfired: List[Dict[str, Any]] = [] for key, obj in truth.items(): tc = tcs.get(key) detected = tc is not None and tc.representative.edge_case_detected if obj.truth_kind == "costumed_pedestrian" and not detected: missed.append({ "sequence_id": key[0], "costume_type": obj.truth_costume_type, "silhouette": obj.truth_silhouette_deviation, "occlusion_env": obj.truth_occlusion_env, "context": obj.context, "reason": ("below confidence thresholds" if tc is not None else "never surfaced as a candidate"), "miner_confidence": tc.representative.confidence_rare_event if tc else None, }) elif obj.truth_kind == "confounder" and detected and \ tc.representative.confidence_rare_event >= 0.5: overfired.append({ "sequence_id": key[0], "confounder_type": obj.truth_costume_type, "context": obj.context, "miner_confidence": tc.representative.confidence_rare_event, })
def _group(rows: List[Dict], field: str) -> Dict[str, int]: out: Dict[str, int] = {} for r in rows: k = str(r.get(field)) out[k] = out.get(k, 0) + 1 return out
# translate recurring misses into next-run sensitivity boosts boost: Dict[str, float] = {} for ct, n in _group(missed, "costume_type").items(): if ct != "None" and n >= 1: boost[ct] = round(min(0.05 * n, 0.15), 3)
next_config: Dict[str, Any] = {"sensitivity_boost": boost} if overfired: next_config["rare_event_threshold"] = 0.5 # tighten when over-firing
return { "recurring_misses": { "total": len(missed), "by_costume_type": _group(missed, "costume_type"), "by_occlusion": _group(missed, "occlusion_env"), "by_context": _group(missed, "context"), "examples": missed[:20], }, "over_fires": { "total": len(overfired), "by_confounder_type": _group(overfired, "confounder_type"), "examples": overfired[:20], }, "next_run_config": next_config, "note": "feed next_run_config into the next mining run; boosts raise " "sensitivity for costume families the miner recurrently missed", }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176"""Near-duplicate detection + diversity-aware selection.
Dedup: track candidates describing the same physical event (same signature ofcostume family x context x lighting x weather x quantized location, acrossframes and across drives) collapse into one representative; the rest arearchived as duplicates.
Diversity selection: within a budget, greedily maximize coverage of thefailure surface (costume x lighting x weather x occlusion x distance xcontext cells) instead of taking the raw top-k by priority. Selectionoptimizes failure-surface coverage, not candidate count."""
from __future__ import annotations
from typing import Dict, List, Optional, Tuple
from sensorflow.raremine.models import RareMineStore, TrackCandidate
PRIORITY_ORDER = ["LOW", "MEDIUM", "HIGH", "CRITICAL"]QUALITY_ORDER = ["LOW", "MEDIUM", "HIGH"]
COVERAGE_DIMS = ["costume", "lighting", "weather", "occlusion", "distance_bin", "context"]
def _distance_bin(d: float) -> str: return "near" if d < 15 else "mid" if d < 35 else "far"
def _signature(tc: TrackCandidate) -> Tuple: rep = tc.representative costume = rep.costume_type[0] if rep.costume_type else "unknown" loc = rep.location return ( costume, loc.get("context"), loc.get("lighting"), loc.get("weather"), _distance_bin(float(loc.get("distance_m", 0.0))), rep.silhouette_deviation, )
def _cells(tc: TrackCandidate) -> Dict[str, str]: rep = tc.representative loc = rep.location return { "costume": rep.costume_type[0] if rep.costume_type else "unknown", "lighting": str(loc.get("lighting")), "weather": str(loc.get("weather")), "occlusion": rep.occlusion_level, "distance_bin": _distance_bin(float(loc.get("distance_m", 0.0))), "context": str(loc.get("context")), }
def _pair_cells(tc: TrackCandidate) -> set: """Coverage cells: all (dim_a x dim_b) pairs the candidate occupies.""" cells = _cells(tc) out = set() dims = COVERAGE_DIMS for i in range(len(dims)): for j in range(i + 1, len(dims)): out.add((dims[i], cells[dims[i]], dims[j], cells[dims[j]])) return out
def _quality_key(tc: TrackCandidate) -> Tuple: rep = tc.representative return (PRIORITY_ORDER.index(rep.curation_priority), QUALITY_ORDER.index(rep.evidence_quality), rep.confidence_rare_event, tc.frame_count)
def deduplicate(store: RareMineStore, bank_id: str, run_id: str = "") -> Dict: """Collapse same-event track candidates; mark the losers as duplicates.""" tracks = [t for t in store.where("track_candidates", bank_id=bank_id) if (not run_id or t.run_id == run_id) and t.representative.edge_case_detected] groups: Dict[Tuple, List[TrackCandidate]] = {} for t in tracks: groups.setdefault(_signature(t), []).append(t)
kept, duplicates = [], [] for sig, members in sorted(groups.items(), key=lambda kv: str(kv[0])): members.sort(key=_quality_key, reverse=True) keeper = members[0] keeper.stage = "DEDUPLICATED" store.put("track_candidates", keeper) kept.append(keeper) for dupe in members[1:]: dupe.stage = "ARCHIVED" dupe.duplicate_of = keeper.track_candidate_id store.put("track_candidates", dupe) duplicates.append(dupe)
store.audit("dedup", "MiningRun", run_id or bank_id, f"{len(kept)} kept, {len(duplicates)} duplicates archived") return { "groups": len(groups), "kept": len(kept), "duplicates_archived": len(duplicates), "dedup_savings": len(duplicates), "signatures": [ {"signature": {"costume": s[0], "context": s[1], "lighting": s[2], "weather": s[3], "distance_bin": s[4], "silhouette": s[5]}, "members": len(m), "kept": m[0].track_candidate_id} for s, m in sorted(groups.items(), key=lambda kv: -len(kv[1])) ], }
def coverage_score(selected: List[TrackCandidate], universe: List[TrackCandidate]) -> float: """Fraction of occupied failure-surface cells covered by the selection.""" all_cells = set() for t in universe: all_cells |= _pair_cells(t) if not all_cells: return 0.0 got = set() for t in selected: got |= _pair_cells(t) return round(len(got & all_cells) / len(all_cells), 4)
def select_diverse(store: RareMineStore, bank_id: str, budget: int = 12, run_id: str = "") -> Dict: """Greedy max-coverage selection over deduplicated candidates, with the naive top-k-by-priority baseline for comparison.""" pool = [t for t in store.where("track_candidates", bank_id=bank_id) if (not run_id or t.run_id == run_id) and t.stage == "DEDUPLICATED"] pool.sort(key=_quality_key, reverse=True) budget = min(budget, len(pool))
naive = pool[:budget]
selected: List[TrackCandidate] = [] covered: set = set() remaining = list(pool) while len(selected) < budget and remaining: best: Optional[TrackCandidate] = None best_gain = (-1, ()) for t in remaining: gain = len(_pair_cells(t) - covered) key = (gain, _quality_key(t)) if key > best_gain: best_gain = key best = t assert best is not None selected.append(best) covered |= _pair_cells(best) remaining.remove(best)
for t in pool: t.diversity_selected = t in selected store.put("track_candidates", t)
matrix: Dict[str, Dict[str, int]] = {} for t in selected: cells = _cells(t) row = matrix.setdefault(cells["costume"], {}) for dim in ("lighting", "weather", "occlusion", "context"): key = f"{dim}:{cells[dim]}" row[key] = row.get(key, 0) + 1
return { "budget": budget, "pool_size": len(pool), "selected_ids": [t.track_candidate_id for t in selected], "coverage_selected": coverage_score(selected, pool), "coverage_naive_topk": coverage_score(naive, pool), "coverage_matrix": matrix, "note": "selection maximizes failure-surface coverage " "(costume x lighting x weather x occlusion x distance x context), " "not raw candidate count", }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134"""Lineage + governance: who curated what, where it may be used, and theleakage guard that makes silent eval->training promotion impossible.
Rules: - every track candidate that survives dedup gets a LineageRecord; - destinations in PROTECTED_EVAL_DESTINATIONS set protected_evaluation=True and FORCE training_eligible=False; - promoting a protected example to training raises LeakageError unless an explicit governance override (who + why, audited) exists; - unvalidated candidates can never become training-eligible at all."""
from __future__ import annotations
from typing import Dict, Optional
from sensorflow.raremine.models import ( PROTECTED_EVAL_DESTINATIONS, LineageRecord, RareMineStore, TrackCandidate, new_id, now_iso,)
class LeakageError(RuntimeError): """Raised on any attempt to silently move a protected evaluation example into training."""
def create_lineage(store: RareMineStore, tc: TrackCandidate, dataset_version: str = "scenebank-v1") -> LineageRecord: rec = LineageRecord( lineage_id=new_id("lin"), track_candidate_id=tc.track_candidate_id, source_frame_id=tc.representative.scene_id, source_sequence_id=tc.sequence_id, dataset_version=dataset_version, destination=tc.destination, ) _apply_destination_rules(rec, tc.destination) store.put("lineage", rec) return rec
def get_lineage(store: RareMineStore, track_candidate_id: str) -> Optional[LineageRecord]: recs = store.where("lineage", track_candidate_id=track_candidate_id) return recs[0] if recs else None
def _apply_destination_rules(rec: LineageRecord, destination: str) -> None: rec.destination = destination if destination in PROTECTED_EVAL_DESTINATIONS: rec.protected_evaluation = True rec.evaluation_eligible = True rec.training_eligible = False # leakage guard: unconditional elif destination in ("RARE_EVENT_DATASET", "HARD_EXAMPLE_DATASET"): rec.evaluation_eligible = True elif destination == "TRAINING_CANDIDATE": rec.evaluation_eligible = False
def set_destination(store: RareMineStore, tc: TrackCandidate, destination: str, curator: str = "raremine-pipeline") -> LineageRecord: """The ONLY path that changes an example's destination. TRAINING_CANDIDATE is refused here unless validation approved it AND it is not protected.""" rec = get_lineage(store, tc.track_candidate_id) if rec is None: rec = create_lineage(store, tc) if destination == "TRAINING_CANDIDATE": if rec.validation_status != "APPROVED": raise LeakageError( "unverified candidates never route to training: candidate " f"{tc.track_candidate_id} has validation_status={rec.validation_status}") if rec.protected_evaluation and not rec.governance_overrides: raise LeakageError( f"candidate {tc.track_candidate_id} belongs to a protected evaluation set " "(training_eligible=false); promoting it requires an explicit governance " "override recording who and why") _apply_destination_rules(rec, destination) if destination == "TRAINING_CANDIDATE": rec.training_eligible = True # only reachable via the guarded path above rec.curator = curator rec.curation_timestamp = now_iso() store.put("lineage", rec) tc.destination = destination store.put("track_candidates", tc) store.audit("destination_set", "TrackCandidate", tc.track_candidate_id, f"-> {destination}", actor=curator) return rec
def governance_override(store: RareMineStore, track_candidate_id: str, actor: str, reason: str) -> LineageRecord: """Explicitly recorded exception allowing a protected eval example to be considered for training. Requires who + why; fully audited.""" if not actor.strip() or not reason.strip(): raise ValueError("governance override requires a named actor and a reason") rec = get_lineage(store, track_candidate_id) if rec is None: raise KeyError(f"no lineage for {track_candidate_id}") rec.governance_overrides.append( {"actor": actor, "reason": reason, "timestamp": now_iso()}) store.put("lineage", rec) store.audit("governance_override", "TrackCandidate", track_candidate_id, f"reason: {reason}", actor=actor) return rec
def promote_to_training(store: RareMineStore, track_candidate_id: str, curator: str = "raremine-pipeline") -> LineageRecord: tc = store.get("track_candidates", track_candidate_id) if tc is None: raise KeyError(f"unknown track candidate {track_candidate_id}") return set_destination(store, tc, "TRAINING_CANDIDATE", curator=curator)
def lineage_report(store: RareMineStore, bank_id: str) -> Dict: tcs = {t.track_candidate_id: t for t in store.where("track_candidates", bank_id=bank_id)} rows = [] for rec in store.all("lineage"): if rec.track_candidate_id not in tcs: continue rows.append(rec.model_dump()) by_destination: Dict[str, int] = {} for r in rows: by_destination[r["destination"]] = by_destination.get(r["destination"], 0) + 1 return { "records": sorted(rows, key=lambda r: r["track_candidate_id"]), "by_destination": by_destination, "protected_count": sum(1 for r in rows if r["protected_evaluation"]), "training_eligible_count": sum(1 for r in rows if r["training_eligible"]), }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591"""Rule-based rare-event candidate proposer (the deterministic default).
The miner PROPOSES; it never validates, never grades, never decides trainingusage. Hard rules enforced here:
- consumes ONLY modalities flagged available on the scene — every evidence item carries its source modality and is checked against the scene flags; - three SEPARATE confidences (human identity, costume, rare event); - temporal validation is NOT_AVAILABLE on single frames — motion is never invented; - observed model behavior is populated ONLY when baseline predictions were supplied, and is kept strictly separate from the predicted failure mode; - unverified candidates are never routed to TRAINING_CANDIDATE.
An optional LLM/VLM narrative (Ollama, copilot pattern) is exposed at the APIlayer; mining itself always runs deterministically without any model."""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from sensorflow.raremine.models import ( EVIDENCE_MODALITIES, Candidate, AlternativeHypothesis, Evidence, ObservedModelBehavior, RareMineStore, Scene, SceneObject, TemporalValidation, new_id,)
SIL_ORDER = ["LOW", "MODERATE", "HIGH", "EXTREME"]OCC_ORDER = ["NONE", "PARTIAL", "HEAVY", "EXTREME"]DIFF_ORDER = ["EASY", "MODERATE", "HARD", "EXTREME"]PRIORITY_ORDER = ["LOW", "MEDIUM", "HIGH", "CRITICAL"]
# texture -> plausible costume families (the miner's taxonomy inference)TEXTURE_TO_COSTUME = { "fur": ["mascot", "animal"], "vinyl": ["inflatable"], "metallic": ["robot_armor"], "fabric": ["character", "oversized"], "cardboard": ["large_prop"],}
MANUFACTURED_TEXTURES = {"fiberglass", "plastic", "flat_print"}
DEFAULT_CONFIG: Dict[str, Any] = { "rare_event_threshold": 0.45, "min_human_identity": 0.30, "min_costume": 0.35, # additive rare-confidence boost per inferred costume family, fed back by # the improvement report of a previous run "sensitivity_boost": {}, "insufficient_visibility": 0.15,}
def _clamp(x: float, lo: float = 0.0, hi: float = 0.98) -> float: return round(max(lo, min(hi, x)), 3)
class _EvidenceCollector: """Evidence sink that HARD-ENFORCES modality discipline: any attempt to record evidence from a modality the scene does not provide raises."""
def __init__(self, scene: Scene): self.available = {m for m, on in scene.modalities.items() if on} self.items: List[Evidence] = []
def add(self, modality: str, description: str) -> None: if modality not in EVIDENCE_MODALITIES: raise ValueError(f"{modality} is not an evidence modality") if modality not in self.available: raise ValueError( f"modality discipline violation: evidence from unavailable modality '{modality}'") self.items.append(Evidence(modality=modality, description=description))
def validate_candidate_modalities(candidate: Candidate, scene: Scene) -> None: """Final guard called before persisting any candidate.""" available = {m for m, on in scene.modalities.items() if on} for ev in candidate.visual_evidence + candidate.human_identity_evidence: if ev.modality not in available: raise ValueError( f"candidate {candidate.candidate_id} cites absent modality {ev.modality}") if candidate.temporal_validation.available and not scene.modalities.get("temporal_sequence"): raise ValueError("temporal validation claimed without temporal_sequence modality") if candidate.observed_model_behavior is not None and not scene.modalities.get("baseline_predictions"): raise ValueError("observed model behavior without baseline predictions")
# ------------------------------------------------------------------ sub-analyses
def _analyze_human_identity(obj: SceneObject, ev: _EvidenceCollector, identity_ev: List[Evidence]) -> float: obs = obj.observables score = 0.15
rgb = obs.get("rgb") if rgb: if rgb["face_visible"]: score += 0.25 identity_ev.append(Evidence(modality="rgb", description="partial human face visible")) if rgb["skin_visible"]: score += 0.15 identity_ev.append(Evidence(modality="rgb", description="exposed skin visible at costume seam")) if rgb["limbs_visible"]: score += 0.12 identity_ev.append(Evidence(modality="rgb", description="articulated limb structure visible")) if rgb["flat_appearance"]: score -= 0.22 ev.add("rgb", "flat printed appearance — inconsistent with a physical person")
temporal = obs.get("temporal_sequence") if temporal: if temporal["articulated_motion"]: score += 0.25 identity_ev.append(Evidence( modality="temporal_sequence", description=f"articulated body motion across {temporal['frames_observed']} frames")) if temporal["gait_periodicity"] > 0.5: score += 0.15 identity_ev.append(Evidence( modality="temporal_sequence", description=f"periodic gait signature (periodicity {temporal['gait_periodicity']:.2f})")) if temporal["displacement_m"] > 0.5: score += 0.08 identity_ev.append(Evidence( modality="temporal_sequence", description=f"self-propelled displacement of {temporal['displacement_m']:.1f} m")) if temporal["stationary"] and not temporal["articulated_motion"]: score -= 0.12 ev.add("temporal_sequence", "object fully static with no articulation across sequence") if temporal.get("sway_only"): score -= 0.1 ev.add("temporal_sequence", "sway without displacement — consistent with a tethered object")
pc = obs.get("point_cloud") if pc: if pc["cluster_shape"] == "humanoid": score += 0.08 identity_ev.append(Evidence(modality="point_cloud", description="LiDAR cluster has humanoid proportions")) if pc["pedestal_detected"]: score -= 0.28 ev.add("point_cloud", "mounting pedestal detected under object") if pc["cluster_shape"] == "flat_panel": score -= 0.2 ev.add("point_cloud", "flat panel geometry — no human volume")
mc = obs.get("multi_camera") if mc and not mc["parallax_consistent_3d"]: score -= 0.2 ev.add("multi_camera", "parallax inconsistent with a 3D physical object (planar surface)")
li = obs.get("lidar_intensity") if li: if li["retroreflective"]: score -= 0.12 ev.add("lidar_intensity", "retroreflective return typical of signage") if li["intensity_uniform"]: score -= 0.06 ev.add("lidar_intensity", "uniform intensity typical of manufactured surfaces")
return _clamp(score)
def _analyze_costume(obj: SceneObject, ev: _EvidenceCollector) -> tuple[float, List[str], List[str]]: """Returns (costume confidence, inferred costume types, unusual geometry).""" obs = obj.observables score = 0.05 inferred: List[str] = [] geometry: List[str] = []
rgb = obs.get("rgb") sil = rgb["silhouette_deviation_observed"] if rgb else "LOW" if rgb: score += {"LOW": 0.0, "MODERATE": 0.25, "HIGH": 0.45, "EXTREME": 0.6}[sil] if sil != "LOW": ev.add("rgb", f"silhouette deviates {sil} from human reference shape") geometry.append(f"{sil.lower()} silhouette deviation from canonical human outline") texture = rgb["texture"] if texture in TEXTURE_TO_COSTUME: score += 0.15 inferred = list(TEXTURE_TO_COSTUME[texture]) ev.add("rgb", f"surface texture '{texture}' consistent with {'/'.join(inferred)} costume") if rgb["bulky_shape"]: score += 0.1 geometry.append("bulk exceeding normal human body envelope") ev.add("rgb", "bulky non-anatomical body envelope")
pc = obs.get("point_cloud") if pc: if pc["cluster_shape"] == "bulky_blob": score += 0.1 geometry.append("LiDAR cluster volume inconsistent with human body") ev.add("point_cloud", "oversized LiDAR cluster volume for a pedestrian-height object") if pc["height_m"] > 2.2: geometry.append(f"height {pc['height_m']:.1f} m above normal pedestrian range") ev.add("point_cloud", f"object height {pc['height_m']:.1f} m exceeds typical pedestrian height")
fv = obs.get("fusion_view") if fv and not fv["camera_lidar_agree"]: score += 0.05 ev.add("fusion_view", "camera and LiDAR classify object shape differently — ambiguous geometry")
lp = obs.get("lidar_projection") if lp and not lp["projected_height_plausible_human"]: geometry.append("projected extent outside plausible human range") ev.add("lidar_projection", "projected object extent outside plausible human range")
return _clamp(score), inferred, geometry
def _alternative_hypotheses(obj: SceneObject, scene: Scene, human_conf: float) -> List[AlternativeHypothesis]: obs = obj.observables rgb = obs.get("rgb") or {} pc = obs.get("point_cloud") or {} temporal = obs.get("temporal_sequence") mc = obs.get("multi_camera") li = obs.get("lidar_intensity") or {} alts: List[AlternativeHypothesis] = []
def motion_rejects(name: str) -> Optional[AlternativeHypothesis]: """Static-object hypotheses die when articulated motion is observed.""" if temporal and temporal["articulated_motion"]: return AlternativeHypothesis( hypothesis=name, confidence=0.05, status="REJECTED", reason=f"articulated motion observed across {temporal['frames_observed']} frames " "rules out a static object") return None
static_context = obj.context == "event_area" stationary = bool(temporal and temporal["stationary"]) texture = rgb.get("texture", "")
# statue — actively considered whenever context or rigidity suggests it statue_cues = sum([ bool(pc.get("pedestal_detected")), stationary, texture == "fiberglass", bool(static_context)]) if statue_cues or texture in MANUFACTURED_TEXTURES or static_context or temporal is None: rej = motion_rejects("mascot_statue") if rej: alts.append(rej) else: conf = _clamp(0.15 + 0.2 * statue_cues, hi=0.9) reason = ("no temporal data — cannot rule out a static replica" if temporal is None else f"{statue_cues} static-object cue(s): " + ", ".join(c for c, on in [ ("pedestal", pc.get("pedestal_detected")), ("stationary", stationary), ("fiberglass surface", texture == "fiberglass"), ("event-area context", static_context)] if on)) alts.append(AlternativeHypothesis( hypothesis="mascot_statue", confidence=conf, status="RETAINED", reason=reason))
# mannequin if texture == "plastic" or pc.get("pedestal_detected") or (temporal is None and human_conf < 0.6): rej = motion_rejects("mannequin") alts.append(rej or AlternativeHypothesis( hypothesis="mannequin", confidence=_clamp(0.2 + (0.25 if texture == "plastic" else 0.0) + (0.2 if pc.get("pedestal_detected") else 0.0), hi=0.85), status="RETAINED", reason="rigid humanoid form cannot be distinguished from a display mannequin " "with the available evidence"))
# inflatable decoration (vs an inflatable costume with a person inside) if texture == "vinyl": if temporal and temporal["displacement_m"] > 0.5: alts.append(AlternativeHypothesis( hypothesis="inflatable_decoration", confidence=0.08, status="REJECTED", reason=f"self-propelled displacement of {temporal['displacement_m']:.1f} m — " "tethered decorations do not translate")) else: sway = bool(temporal and temporal.get("sway_only")) alts.append(AlternativeHypothesis( hypothesis="inflatable_decoration", confidence=_clamp(0.35 + (0.3 if sway else 0.0) + (0.15 if temporal is None else 0.0), hi=0.9), status="RETAINED", reason="vinyl inflatable without observed self-propulsion — could be an anchored " "decoration rather than a person in an inflatable costume"))
# advertisement / sign (flat objects) flat = rgb.get("flat_appearance") or pc.get("cluster_shape") == "flat_panel" \ or (mc is not None and not mc["parallax_consistent_3d"]) or li.get("retroreflective") if flat: confirmed_3d = (pc and pc.get("cluster_shape") in ("humanoid", "bulky_blob")) or \ (mc is not None and mc["parallax_consistent_3d"]) if confirmed_3d: alts.append(AlternativeHypothesis( hypothesis="roadside_advertisement", confidence=0.1, status="REJECTED", reason="3D volume confirmed by parallax/LiDAR — not a printed surface")) else: alts.append(AlternativeHypothesis( hypothesis="roadside_advertisement", confidence=0.6, status="RETAINED", reason="flat appearance with no confirmed 3D volume — likely printed figure"))
# plain pedestrian (not a rare event at all) sil = rgb.get("silhouette_deviation_observed", "LOW") if sil in ("LOW", "MODERATE"): alts.append(AlternativeHypothesis( hypothesis="normal_pedestrian", confidence=_clamp(0.7 if sil == "LOW" else 0.3, hi=0.9), status="RETAINED" if sil == "LOW" else "RETAINED", reason="silhouette deviation is limited — could be bulky clothing rather than a costume")) else: alts.append(AlternativeHypothesis( hypothesis="normal_pedestrian", confidence=0.08, status="REJECTED", reason=f"{sil} silhouette deviation exceeds what ordinary clothing produces"))
return alts
def _temporal_validation(scene: Scene, obj: SceneObject) -> TemporalValidation: if not scene.modalities.get("temporal_sequence"): # single frame: never invent motion return TemporalValidation(available=False, status="NOT_AVAILABLE", evidence=[]) t = obj.observables.get("temporal_sequence") or {} evidence = [] if t.get("articulated_motion"): evidence.append(f"articulated motion over {t.get('frames_observed', 0)} frames") if t.get("gait_periodicity", 0) > 0.5: evidence.append(f"gait periodicity {t['gait_periodicity']:.2f}") if t.get("displacement_m", 0) > 0.5: evidence.append(f"net displacement {t['displacement_m']:.1f} m") if evidence: return TemporalValidation(available=True, status="VALIDATED", evidence=evidence) return TemporalValidation(available=True, status="INCONCLUSIVE", evidence=["no articulation or displacement observed across sequence"])
def _observed_behavior(scene: Scene, obj: SceneObject, human_conf: float) -> Optional[ObservedModelBehavior]: """OBSERVED failures only — populated iff predictions were supplied.""" if not scene.modalities.get("baseline_predictions"): return None pred = next((p for p in scene.baseline_predictions if p.object_id == obj.object_id), None) behavior = ObservedModelBehavior() if pred is None: behavior.failure_observed = True behavior.failure_modes = ["FALSE_NEGATIVE"] behavior.details = ["baseline model emitted no detection at this object's location"] return behavior if pred.predicted_class != "pedestrian" and human_conf >= 0.3: behavior.failure_observed = True behavior.failure_modes.append(f"MISCLASSIFICATION_{pred.predicted_class.upper()}") behavior.details.append( f"model classified object as '{pred.predicted_class}' despite human-identity evidence") if pred.confidence < 0.35: behavior.failure_observed = True behavior.failure_modes.append("LOW_CONFIDENCE") behavior.details.append(f"detection confidence {pred.confidence:.2f} below reliable range") if pred.localization_offset_m > 1.0: behavior.failure_observed = True behavior.failure_modes.append("LOCALIZATION_ERROR") behavior.details.append( f"predicted box offset {pred.localization_offset_m:.1f} m from sensed object cluster") if not pred.track_stable: behavior.failure_observed = True behavior.failure_modes.append("TRACKING_FAILURE") behavior.details.append("track identity unstable across the observed sequence") if not behavior.failure_observed: behavior.details = [f"model detected 'pedestrian' at confidence {pred.confidence:.2f} — no failure observed"] return behavior
def _difficulty(obj: SceneObject, scene: Scene, sil: str, occ: str) -> tuple[str, List[str]]: basis: List[str] = [] score = SIL_ORDER.index(sil) basis.append(f"silhouette deviation {sil}") score += OCC_ORDER.index(occ) if occ != "NONE": basis.append(f"occlusion {occ}") if obj.distance_m > 35: score += 1 basis.append(f"long range ({obj.distance_m:.0f} m)") if scene.lighting == "night": score += 1 basis.append("night lighting") if scene.weather in ("rain", "fog"): score += 1 basis.append(f"{scene.weather} degrades sensing") level = DIFF_ORDER[min(3, score // 2)] return level, basis
# ------------------------------------------------------------------ main entry
def propose_for_object(scene: Scene, obj: SceneObject, config: Optional[Dict[str, Any]] = None, run_id: str = "") -> Candidate: cfg = {**DEFAULT_CONFIG, **(config or {})} ev = _EvidenceCollector(scene) identity_ev: List[Evidence] = []
human_conf = _analyze_human_identity(obj, ev, identity_ev) costume_conf, inferred_types, geometry = _analyze_costume(obj, ev) alts = _alternative_hypotheses(obj, scene, human_conf) temporal = _temporal_validation(scene, obj)
rgb = obj.observables.get("rgb") or {} sil = rgb.get("silhouette_deviation_observed", "LOW") visibility = rgb.get("visibility", 0.5)
# occlusion: level from visibility, source from costume bulk vs environment occ_level = "NONE" if visibility > 0.75 else "PARTIAL" if visibility > 0.5 \ else "HEAVY" if visibility > 0.25 else "EXTREME" bulky = bool(rgb.get("bulky_shape")) if occ_level == "NONE": occ_source = "NONE" elif bulky and visibility < 0.5: occ_source = "COMBINED" elif bulky: occ_source = "COSTUME_INDUCED" else: occ_source = "ENVIRONMENTAL"
# rare-event confidence: requires BOTH a human and a costume — combined but # reported separately; discounted by the strongest retained alternative. rare = min(human_conf, costume_conf) * (0.75 + 0.25 * max(human_conf, costume_conf)) strongest_alt = max((a.confidence for a in alts if a.status == "RETAINED" and a.hypothesis != "normal_pedestrian"), default=0.0) rare *= (1.0 - 0.45 * strongest_alt) for fam in inferred_types: rare += float(cfg["sensitivity_boost"].get(fam, 0.0)) rare = _clamp(rare)
# evidence quality from breadth of corroborating modalities + visibility n_modalities = len({e.modality for e in ev.items + identity_ev}) quality = "HIGH" if (n_modalities >= 3 and visibility > 0.5) else \ "MEDIUM" if n_modalities >= 2 else "LOW"
insufficient = visibility < cfg["insufficient_visibility"] or n_modalities == 0 detected = (not insufficient and rare >= cfg["rare_event_threshold"] and costume_conf >= cfg["min_costume"] and human_conf >= cfg["min_human_identity"])
difficulty, diff_basis = _difficulty(obj, scene, sil, occ_level) behavior = _observed_behavior(scene, obj, human_conf)
# predicted failure mode — the miner's forecast, independent of any model predicted_failure: Optional[str] = None if detected: if sil == "EXTREME": predicted_failure = "MISCLASSIFICATION_BACKGROUND" if occ_level in ("HEAVY", "EXTREME") \ else "MISCLASSIFICATION_ANIMAL" if "animal" in inferred_types or "mascot" in inferred_types \ else "FALSE_NEGATIVE" elif occ_level in ("HEAVY", "EXTREME"): predicted_failure = "FALSE_NEGATIVE" elif scene.lighting == "night" or obj.distance_m > 35: predicted_failure = "LOW_CONFIDENCE" elif sil in ("HIGH", "MODERATE"): predicted_failure = "LOW_CONFIDENCE"
# priority: rarity x difficulty x impact x safety relevance (qualitative) safety_context = obj.context in ("crosswalk", "road_edge") observed_failure = bool(behavior and behavior.failure_observed) reasons: List[str] = [] if detected: reasons.append("costumed-pedestrian events are rare in the fleet distribution") reasons.append(f"perception difficulty {difficulty} ({'; '.join(diff_basis)})") if observed_failure: reasons.append("baseline model failure OBSERVED on this example: " + ", ".join(behavior.failure_modes)) # type: ignore[union-attr] elif predicted_failure: reasons.append(f"failure PREDICTED (not observed): {predicted_failure}") if safety_context: reasons.append(f"safety-relevant location: {obj.context} in the vehicle path") if observed_failure and sil == "EXTREME" and safety_context: priority = "CRITICAL" elif observed_failure or (detected and sil == "EXTREME" and safety_context): priority = "HIGH" elif detected and (DIFF_ORDER.index(difficulty) >= 2 or safety_context): priority = "MEDIUM" if not safety_context else "HIGH" elif detected: priority = "MEDIUM" if DIFF_ORDER.index(difficulty) >= 1 else "LOW" else: priority = "LOW" reasons = ["not a confirmed rare-event candidate"]
# destination — a RECOMMENDATION only; never TRAINING_CANDIDATE pre-validation if not detected: destination = "REVIEW_QUEUE" if (insufficient and costume_conf >= 0.3) else "NO_ACTION" elif priority == "CRITICAL": destination = "SAFETY_CRITICAL_EVALUATION_SET" elif observed_failure: destination = "REGRESSION_EVALUATION_SET" if rare >= 0.6 else "HARD_EXAMPLE_DATASET" elif rare >= 0.6 and quality == "HIGH": destination = "RARE_EVENT_DATASET" else: destination = "REVIEW_QUEUE"
requires_human = detected or (insufficient and costume_conf >= 0.3) or \ (strongest_alt >= 0.4 and costume_conf >= 0.3) if detected: hv_reason = "miner proposals are hypotheses; dataset admission requires human/GT confirmation" if strongest_alt >= 0.4: hv_reason += " — a static-object alternative hypothesis remains plausible" elif requires_human: hv_reason = "ambiguous evidence: retained alternative hypotheses need human adjudication" else: hv_reason = ""
visible_features = [d.description for d in identity_ev if d.modality == "rgb"] occluded_features = [] if not rgb.get("face_visible", False): occluded_features.append("face (covered or not visible)") if not rgb.get("skin_visible", False): occluded_features.append("skin") if not rgb.get("limbs_visible", False): occluded_features.append("limb articulation points")
cand = Candidate( candidate_id=new_id("cand"), bank_id=scene.bank_id, scene_id=scene.scene_id, sequence_id=scene.sequence_id, object_id=obj.object_id, track_id=obj.track_id, frame_index=scene.frame_index, run_id=run_id, edge_case_detected=detected, insufficient_visual_evidence=insufficient, event_type="costumed_pedestrian" if detected else "none", costume_type=inferred_types if detected else [], confidence_human_identity=human_conf, confidence_costume=costume_conf, confidence_rare_event=rare, visual_evidence=ev.items, human_identity_evidence=identity_ev, alternative_hypotheses=alts, silhouette_deviation=sil, # type: ignore[arg-type] occlusion_level=occ_level, # type: ignore[arg-type] occlusion_source=occ_source, # type: ignore[arg-type] visible_human_features=visible_features, occluded_human_features=occluded_features, unusual_geometry=geometry, temporal_validation=temporal, location={"context": obj.context, "distance_m": obj.distance_m, "position": obj.position, "lighting": scene.lighting, "weather": scene.weather}, perception_difficulty=difficulty, # type: ignore[arg-type] difficulty_evidence=diff_basis, observed_model_behavior=behavior, predicted_failure_mode=predicted_failure, curation_priority=priority, # type: ignore[arg-type] priority_reason="; ".join(reasons), recommended_dataset_destination=destination, requires_human_validation=requires_human, human_validation_reason=hv_reason, evidence_quality=quality, # type: ignore[arg-type] ) validate_candidate_modalities(cand, scene) return cand
def mine_scene(scene: Scene, config: Optional[Dict[str, Any]] = None, run_id: str = "") -> List[Candidate]: """Propose candidates for one scene, ranked within the scene.""" candidates = [propose_for_object(scene, obj, config, run_id) for obj in scene.objects] ranked = sorted( candidates, key=lambda c: (PRIORITY_ORDER.index(c.curation_priority), c.confidence_rare_event), reverse=True) for i, c in enumerate(ranked): c.rank_in_scene = i + 1 return ranked
def run_mining(store: RareMineStore, bank_id: str, config: Optional[Dict[str, Any]] = None, run_id: str = "") -> List[Candidate]: scenes = store.where("scenes", bank_id=bank_id) scenes.sort(key=lambda s: (s.sequence_id, s.frame_index, s.scene_id)) out: List[Candidate] = [] for scene in scenes: for cand in mine_scene(scene, config, run_id): store.put("candidates", cand) out.append(cand) return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461"""Pydantic data model + JSON-backed store for the rare-event miner.
Follows the record/store pattern of sensorflow.evaluation.records (thread-safein-memory collections with JSON persistence under runs/raremine/), and thelineage/report shapes of sensorflow.megaeval."""
from __future__ import annotations
import jsonimport threadingimport uuidfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Dict, List, Literal, Optional
from pydantic import BaseModel, Field
STORE_DIR = Path("runs/raremine")
# ------------------------------------------------------------------ vocabularies
COSTUME_TYPES = [ "mascot", "inflatable", "animal", "character", "robot_armor", "oversized", "large_prop",]
CONFOUNDER_TYPES = [ "mascot_statue", "inflatable_decoration", "roadside_advertisement", "mannequin", "sign", "construction_object",]
MODALITIES = [ "rgb", "multi_camera", "lidar_projection", "lidar_intensity", "point_cloud", "fusion_view", "temporal_sequence", "baseline_predictions", "gt_annotations",]
# Modalities that may carry visual/sensor evidence (predictions & GT are data# availability flags, not evidence sources for the proposer).EVIDENCE_MODALITIES = [ "rgb", "multi_camera", "lidar_projection", "lidar_intensity", "point_cloud", "fusion_view", "temporal_sequence",]
SilhouetteDeviation = Literal["LOW", "MODERATE", "HIGH", "EXTREME"]OcclusionLevel = Literal["NONE", "PARTIAL", "HEAVY", "EXTREME"]OcclusionSource = Literal["NONE", "COSTUME_INDUCED", "ENVIRONMENTAL", "COMBINED"]Difficulty = Literal["EASY", "MODERATE", "HARD", "EXTREME"]Priority = Literal["LOW", "MEDIUM", "HIGH", "CRITICAL"]EvidenceQuality = Literal["LOW", "MEDIUM", "HIGH"]
LIGHTING = ["day", "night"]WEATHER = ["clear", "rain", "fog"]CONTEXTS = ["sidewalk", "crosswalk", "road_edge", "event_area"]SAFETY_CONTEXTS = {"crosswalk", "road_edge"}
FAILURE_MODES = [ "FALSE_NEGATIVE", "MISCLASSIFICATION_VEHICLE", "MISCLASSIFICATION_ANIMAL", "MISCLASSIFICATION_BACKGROUND", "LOCALIZATION_ERROR", "LOW_CONFIDENCE", "TRACKING_FAILURE",]
DESTINATIONS = [ "NO_ACTION", "REVIEW_QUEUE", "RARE_EVENT_DATASET", "HARD_EXAMPLE_DATASET", "REGRESSION_EVALUATION_SET", "SAFETY_CRITICAL_EVALUATION_SET", "TRAINING_CANDIDATE",]
# Anything landing in these sets is protected: leakage into training requires# an explicit, audited governance override.PROTECTED_EVAL_DESTINATIONS = { "REGRESSION_EVALUATION_SET", "SAFETY_CRITICAL_EVALUATION_SET",}
STAGES = [ "RAW", "MINED", "DEDUPLICATED", "AUTO_VALIDATED", "HUMAN_VALIDATED", "CURATED", "ARCHIVED",]
def now_iso() -> str: return datetime.now(timezone.utc).isoformat()
def new_id(prefix: str) -> str: return f"{prefix}-{uuid.uuid4().hex[:10]}"
# ------------------------------------------------------------------ scene bank
class SceneObject(BaseModel): """One object in a scene. `truth_*` fields are the planted ground truth used ONLY by validation/statistics — the miner consumes `observables`."""
object_id: str track_id: str = "" # planted truth (hidden from the miner) truth_kind: Literal["normal_pedestrian", "costumed_pedestrian", "confounder"] truth_costume_type: Optional[str] = None # COSTUME_TYPES or CONFOUNDER_TYPES truth_silhouette_deviation: SilhouetteDeviation = "LOW" truth_occlusion_env: OcclusionLevel = "NONE" truth_occlusion_costume: OcclusionLevel = "NONE" truth_is_moving: bool = True # shared scene-truth attributes (also observable) distance_m: float = 15.0 context: str = "sidewalk" # schematic geometry for the UI (BEV metres + normalized 2D bbox) position: List[float] = Field(default_factory=lambda: [10.0, 0.0]) bbox_2d: List[float] = Field(default_factory=lambda: [0.4, 0.4, 0.1, 0.25]) # per-modality observable features; keys MUST be available scene modalities observables: Dict[str, Dict[str, Any]] = Field(default_factory=dict)
class BaselinePrediction(BaseModel): prediction_id: str object_id: Optional[str] = None # None => spurious detection predicted_class: str = "pedestrian" # vehicle | animal | background | none confidence: float = 0.9 # offset between predicted box and the sensed object cluster (observable) localization_offset_m: float = 0.1 track_stable: bool = True # truth-only fields, used by quantitative validation — never by the miner iou_with_gt: Optional[float] = None planted_failure: Optional[str] = None
class GtBox(BaseModel): object_id: str class_name: str = "pedestrian" is_costumed: bool = False costume_type: Optional[str] = None
class Scene(BaseModel): scene_id: str bank_id: str sequence_id: str frame_index: int = 0 lighting: str = "day" weather: str = "clear" modalities: Dict[str, bool] = Field(default_factory=dict) objects: List[SceneObject] = Field(default_factory=list) baseline_predictions: List[BaselinePrediction] = Field(default_factory=list) gt_boxes: List[GtBox] = Field(default_factory=list) near_duplicate_of: Optional[str] = None # scene_id of the original frame
class SceneBank(BaseModel): bank_id: str seed: int = 7 created_at: str = Field(default_factory=now_iso) num_scenes: int = 0 num_sequences: int = 0 num_planted_rare: int = 0 # track-level planted costumed pedestrians num_confounders: int = 0 generation_params: Dict[str, Any] = Field(default_factory=dict)
# ------------------------------------------------------------------ candidates
class Evidence(BaseModel): modality: str # one of EVIDENCE_MODALITIES description: str
class AlternativeHypothesis(BaseModel): hypothesis: str confidence: float status: Literal["RETAINED", "REJECTED"] reason: str
class TemporalValidation(BaseModel): available: bool = False status: Literal["VALIDATED", "NOT_AVAILABLE", "INCONCLUSIVE"] = "NOT_AVAILABLE" evidence: List[str] = Field(default_factory=list)
class ObservedModelBehavior(BaseModel): """ONLY populated when baseline predictions were supplied for the scene. Strictly separated from `predicted_failure_mode` (the miner's forecast)."""
failure_observed: bool = False failure_modes: List[str] = Field(default_factory=list) details: List[str] = Field(default_factory=list)
class Candidate(BaseModel): candidate_id: str bank_id: str scene_id: str sequence_id: str object_id: str track_id: str = "" frame_index: int = 0 run_id: str = ""
edge_case_detected: bool = False insufficient_visual_evidence: bool = False event_type: str = "none" # costumed_pedestrian | none costume_type: List[str] = Field(default_factory=list)
# THREE separate confidences — never collapsed into one number. confidence_human_identity: float = 0.0 confidence_costume: float = 0.0 confidence_rare_event: float = 0.0
visual_evidence: List[Evidence] = Field(default_factory=list) human_identity_evidence: List[Evidence] = Field(default_factory=list) alternative_hypotheses: List[AlternativeHypothesis] = Field(default_factory=list)
silhouette_deviation: SilhouetteDeviation = "LOW" occlusion_level: OcclusionLevel = "NONE" occlusion_source: OcclusionSource = "NONE" visible_human_features: List[str] = Field(default_factory=list) occluded_human_features: List[str] = Field(default_factory=list) unusual_geometry: List[str] = Field(default_factory=list)
temporal_validation: TemporalValidation = Field(default_factory=TemporalValidation) location: Dict[str, Any] = Field(default_factory=dict)
perception_difficulty: Difficulty = "EASY" difficulty_evidence: List[str] = Field(default_factory=list)
observed_model_behavior: Optional[ObservedModelBehavior] = None predicted_failure_mode: Optional[str] = None
curation_priority: Priority = "LOW" priority_reason: str = "" recommended_dataset_destination: str = "NO_ACTION" requires_human_validation: bool = False human_validation_reason: str = "" evidence_quality: EvidenceQuality = "LOW" rank_in_scene: int = 1
class RepresentativeFrames(BaseModel): best_evidence: Optional[str] = None # scene_id worst_case: Optional[str] = None model_failure: Optional[str] = None minimal_set: List[str] = Field(default_factory=list)
class TrackCandidate(BaseModel): """One consolidated candidate per (sequence, track): the unit that flows through the validation pipeline."""
track_candidate_id: str bank_id: str run_id: str = "" sequence_id: str track_id: str object_id: str frame_count: int = 1 duration_frames: int = 1 frame_candidate_ids: List[str] = Field(default_factory=list) representative: Candidate # highest-evidence frame-level proposal representative_frames: RepresentativeFrames = Field(default_factory=RepresentativeFrames) max_visibility: EvidenceQuality = "LOW" max_difficulty: Difficulty = "EASY"
# lifecycle stage: str = "MINED" duplicate_of: Optional[str] = None diversity_selected: bool = False auto_validation: Optional[Dict[str, Any]] = None human_validation: Optional[Dict[str, Any]] = None destination: str = "REVIEW_QUEUE"
class LineageRecord(BaseModel): lineage_id: str track_candidate_id: str source_frame_id: str source_sequence_id: str dataset_version: str = "scenebank-v1" curation_timestamp: str = Field(default_factory=now_iso) curator: str = "raremine-pipeline" validation_status: str = "PENDING" # PENDING | AUTO_COHERENT | AUTO_INCOHERENT | APPROVED | REJECTED training_eligible: bool = False evaluation_eligible: bool = False protected_evaluation: bool = False destination: str = "REVIEW_QUEUE" governance_overrides: List[Dict[str, str]] = Field(default_factory=list)
class MiningRun(BaseModel): run_id: str bank_id: str created_at: str = Field(default_factory=now_iso) config: Dict[str, Any] = Field(default_factory=dict) num_frame_candidates: int = 0 num_track_candidates: int = 0 num_duplicates: int = 0 num_diversity_selected: int = 0
class AuditEvent(BaseModel): event_id: str timestamp: str = Field(default_factory=now_iso) actor: str = "system" action: str = "" entity_type: str = "" entity_id: str = "" detail: str = ""
# ------------------------------------------------------------------ store
_COLLECTIONS = { "banks": SceneBank, "scenes": Scene, "runs": MiningRun, "candidates": Candidate, "track_candidates": TrackCandidate, "lineage": LineageRecord, "audit_events": AuditEvent,}
_KEY_FIELDS = { "banks": "bank_id", "scenes": "scene_id", "runs": "run_id", "candidates": "candidate_id", "track_candidates": "track_candidate_id", "lineage": "lineage_id", "audit_events": "event_id",}
class RareMineStore: """Thread-safe in-memory store with JSON persistence (EvalStore pattern)."""
def __init__(self, base_dir: Path = STORE_DIR): self.base_dir = Path(base_dir) self.lock = threading.RLock() self.collections: Dict[str, Dict[str, BaseModel]] = {c: {} for c in _COLLECTIONS} self.meta: Dict[str, Any] = {} self._load()
def _path(self) -> Path: return self.base_dir / "store.json"
def _load(self) -> None: path = self._path() if not path.exists(): return try: with open(path) as f: raw = json.load(f) except Exception: return with self.lock: for name, model_cls in _COLLECTIONS.items(): parsed: Dict[str, BaseModel] = {} for key, payload in raw.get(name, {}).items(): try: parsed[key] = model_cls.model_validate(payload) except Exception: continue self.collections[name] = parsed self.meta = raw.get("_meta", {})
def save(self) -> None: with self.lock: payload = { name: {k: v.model_dump() for k, v in items.items()} for name, items in self.collections.items() } payload["_meta"] = self.meta self.base_dir.mkdir(parents=True, exist_ok=True) tmp = self._path().with_suffix(".tmp") with open(tmp, "w") as f: json.dump(payload, f) tmp.replace(self._path())
def put(self, collection: str, item: BaseModel) -> None: key = getattr(item, _KEY_FIELDS[collection]) with self.lock: self.collections[collection][key] = item
def get(self, collection: str, key: str) -> Optional[Any]: with self.lock: return self.collections[collection].get(key)
def all(self, collection: str) -> List[Any]: with self.lock: return list(self.collections[collection].values())
def where(self, collection: str, **filters: Any) -> List[Any]: with self.lock: items = list(self.collections[collection].values()) return [it for it in items if all(getattr(it, k, None) == v for k, v in filters.items())]
def clear(self, collection: str) -> None: with self.lock: self.collections[collection] = {}
def audit(self, action: str, entity_type: str, entity_id: str, detail: str = "", actor: str = "system") -> None: self.put("audit_events", AuditEvent( event_id=new_id("rmaudit"), actor=actor, action=action, entity_type=entity_type, entity_id=entity_id, detail=detail))
_STORE: Optional[RareMineStore] = None_STORE_LOCK = threading.Lock()
def get_store() -> RareMineStore: global _STORE with _STORE_LOCK: if _STORE is None: _STORE = RareMineStore() return _STORE
def reset_store(base_dir: Optional[Path] = None) -> RareMineStore: """Used by tests to get a fresh isolated store.""" global _STORE with _STORE_LOCK: _STORE = RareMineStore(base_dir or STORE_DIR) return _STORE123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189"""Staged validation pipeline + review queue.
Lifecycle: Raw -> Mined -> Deduplicated -> Automated Validation ->Human/GT Validation -> Curated (Evaluation Set | Training Candidate),with an Archive for rejections.
The automated stage MEASURES candidate coherence against planted ground truthwhere available; it never approves for training. Human validation is modeledas an explicit API action (approve/reject with a note). CRITICAL candidatessurface at the top of the review queue; there is no clean hook to push foreignentities into sensorflow.evaluation's ReviewTask queue (its tasks are keyed toannotation/frame/dataset ids of that platform), so the miner exposes its ownqueue instead — noted integration gap."""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from sensorflow.raremine import dedup as dedup_modfrom sensorflow.raremine import lineage as lineage_modfrom sensorflow.raremine import miner as miner_modfrom sensorflow.raremine import tracks as tracks_modfrom sensorflow.raremine.models import ( MiningRun, RareMineStore, TrackCandidate, new_id, now_iso,)
PRIORITY_ORDER = ["LOW", "MEDIUM", "HIGH", "CRITICAL"]
def run_full_pipeline(store: RareMineStore, bank_id: str, config: Optional[Dict[str, Any]] = None, diversity_budget: int = 12) -> MiningRun: """Mine -> consolidate -> dedup -> diversity -> auto-validate -> lineage.""" bank = store.get("banks", bank_id) if bank is None: raise KeyError(f"unknown scene bank {bank_id}") run_id = new_id("rmrun") # a fresh run replaces previous mining products for the bank store.clear("candidates") store.clear("track_candidates") store.clear("lineage")
frame_cands = miner_mod.run_mining(store, bank_id, config, run_id=run_id) track_cands = tracks_mod.consolidate_tracks(store, bank_id, run_id=run_id) dedup_report = dedup_mod.deduplicate(store, bank_id, run_id=run_id) diversity_report = dedup_mod.select_diverse(store, bank_id, budget=diversity_budget, run_id=run_id)
validated = 0 for tc in store.where("track_candidates", bank_id=bank_id): if tc.stage != "DEDUPLICATED": continue auto_validate(store, tc) validated += 1
run = MiningRun( run_id=run_id, bank_id=bank_id, config=config or {}, num_frame_candidates=len(frame_cands), num_track_candidates=len(track_cands), num_duplicates=dedup_report["duplicates_archived"], num_diversity_selected=len(diversity_report["selected_ids"]), ) store.meta["last_run"] = { "run_id": run_id, "bank_id": bank_id, "dedup_report": dedup_report, "diversity_report": diversity_report, "auto_validated": validated, "finished_at": now_iso(), } store.put("runs", run) store.audit("mining_run", "MiningRun", run_id, f"{len(frame_cands)} frame candidates -> {len(track_cands)} tracks, " f"{dedup_report['duplicates_archived']} duplicates archived") store.save() return run
def auto_validate(store: RareMineStore, tc: TrackCandidate) -> Dict[str, Any]: """AUTOMATED validation: measure the proposal against ground truth when the scene provides it. Records coherence — it does not confirm importance.""" rep = tc.representative scene = store.get("scenes", rep.scene_id) result: Dict[str, Any] = {"checked_at": now_iso()} if scene is None or not scene.modalities.get("gt_annotations"): result["status"] = "NO_GT" result["detail"] = "no ground-truth annotations available for this scene" else: gt = next((g for g in scene.gt_boxes if g.object_id == rep.object_id), None) if gt is None: result["status"] = "AUTO_INCOHERENT" result["detail"] = "candidate object has no ground-truth counterpart" else: truly_rare = gt.class_name == "pedestrian" and gt.is_costumed coherent = rep.edge_case_detected == truly_rare result["status"] = "AUTO_COHERENT" if coherent else "AUTO_INCOHERENT" result["gt_class"] = gt.class_name result["gt_is_costumed"] = gt.is_costumed result["gt_costume_type"] = gt.costume_type result["detail"] = ( "proposal agrees with ground truth" if coherent else f"proposal ({'detected' if rep.edge_case_detected else 'rejected'}) disagrees " f"with GT (class={gt.class_name}, costumed={gt.is_costumed})") tc.auto_validation = result tc.stage = "AUTO_VALIDATED" store.put("track_candidates", tc) rec = lineage_mod.create_lineage(store, tc) rec.validation_status = result["status"] store.put("lineage", rec) return result
def review_queue(store: RareMineStore, bank_id: str, priority: Optional[str] = None, status: Optional[str] = None, costume: Optional[str] = None, difficulty: Optional[str] = None) -> List[TrackCandidate]: """Ranked review queue over post-dedup candidates (CRITICAL first).""" items = [t for t in store.where("track_candidates", bank_id=bank_id) if t.stage not in ("ARCHIVED",) and t.duplicate_of is None] if priority: items = [t for t in items if t.representative.curation_priority == priority] if status: items = [t for t in items if t.stage == status] if costume: items = [t for t in items if costume in t.representative.costume_type] if difficulty: items = [t for t in items if t.representative.perception_difficulty == difficulty] items.sort(key=lambda t: (PRIORITY_ORDER.index(t.representative.curation_priority), t.representative.confidence_rare_event), reverse=True) return items
def human_review(store: RareMineStore, track_candidate_id: str, action: str, note: str = "", reviewer: str = "human-reviewer", destination: Optional[str] = None) -> TrackCandidate: """HUMAN validation: approve into a destination or reject to the archive.""" tc = store.get("track_candidates", track_candidate_id) if tc is None: raise KeyError(f"unknown track candidate {track_candidate_id}") if action not in ("approve", "reject"): raise ValueError("action must be approve|reject") rec = lineage_mod.get_lineage(store, track_candidate_id) or lineage_mod.create_lineage(store, tc) tc.human_validation = {"action": action, "note": note, "reviewer": reviewer, "reviewed_at": now_iso()} if action == "approve": rec.validation_status = "APPROVED" store.put("lineage", rec) target = destination or tc.representative.recommended_dataset_destination if target in ("NO_ACTION", "REVIEW_QUEUE"): target = "RARE_EVENT_DATASET" lineage_mod.set_destination(store, tc, target, curator=reviewer) tc.stage = "CURATED" else: rec.validation_status = "REJECTED" rec.training_eligible = False rec.evaluation_eligible = False store.put("lineage", rec) tc.stage = "ARCHIVED" tc.destination = "NO_ACTION" store.put("track_candidates", tc) store.audit(f"human_{action}", "TrackCandidate", track_candidate_id, note, actor=reviewer) store.save() return tc
def destinations_report(store: RareMineStore, bank_id: str) -> Dict[str, Any]: tcs = [t for t in store.where("track_candidates", bank_id=bank_id) if t.duplicate_of is None] buckets: Dict[str, List[Dict]] = {} for t in tcs: rec = lineage_mod.get_lineage(store, t.track_candidate_id) buckets.setdefault(t.destination, []).append({ "track_candidate_id": t.track_candidate_id, "stage": t.stage, "priority": t.representative.curation_priority, "costume_type": t.representative.costume_type, "lineage": rec.model_dump() if rec else None, }) return {"destinations": buckets, "counts": {k: len(v) for k, v in buckets.items()}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119"""Quantitative validation: for candidates with model outputs, compute theOBSERVED difficulty from actual baseline behavior and compare it with theminer's PREDICTED difficulty (agreement matrix).
Observed metrics per track candidate: mean baseline confidence, per-examplecorrectness, localization quality (IoU), miss rate, class confusion, trackstability. Predicted difficulty comes from the miner and is never edited here— this stage only measures."""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from sensorflow.raremine.models import RareMineStore, TrackCandidate
DIFF_ORDER = ["EASY", "MODERATE", "HARD", "EXTREME"]
def _track_object_ids(store: RareMineStore, tc: TrackCandidate) -> List[tuple]: """(scene, object) pairs across the track's frames.""" out = [] for scene in store.where("scenes", sequence_id=tc.sequence_id): for obj in scene.objects: if obj.track_id == tc.track_id: out.append((scene, obj)) return out
def observed_metrics(store: RareMineStore, tc: TrackCandidate) -> Optional[Dict[str, Any]]: """None when no baseline predictions exist anywhere on the track.""" pairs = [(s, o) for s, o in _track_object_ids(store, tc) if s.modalities.get("baseline_predictions")] if not pairs: return None confidences: List[float] = [] ious: List[float] = [] misses = 0 confusion: Dict[str, int] = {} unstable = 0 correct = 0 for scene, obj in pairs: pred = next((p for p in scene.baseline_predictions if p.object_id == obj.object_id), None) if pred is None: misses += 1 continue confidences.append(pred.confidence) if pred.iou_with_gt is not None: ious.append(pred.iou_with_gt) if pred.predicted_class != "pedestrian": confusion[pred.predicted_class] = confusion.get(pred.predicted_class, 0) + 1 else: correct += 1 if not pred.track_stable: unstable += 1 n = len(pairs) mean_conf = round(sum(confidences) / len(confidences), 3) if confidences else 0.0 mean_iou = round(sum(ious) / len(ious), 3) if ious else None miss_rate = round(misses / n, 3) confused_rate = round(sum(confusion.values()) / n, 3) stability = round(1.0 - unstable / max(n - misses, 1), 3)
# observed difficulty grade from measured behavior if miss_rate > 0.5 or confused_rate > 0.5: grade = "EXTREME" elif miss_rate > 0.0 or confusion or unstable: grade = "HARD" elif mean_conf < 0.4 or (mean_iou is not None and mean_iou < 0.5): grade = "MODERATE" if mean_conf >= 0.25 else "HARD" else: grade = "EASY"
return { "frames_with_predictions": n, "mean_baseline_confidence": mean_conf, "mean_iou": mean_iou, "miss_rate": miss_rate, "class_confusion": confusion, "confused_rate": confused_rate, "track_stability": stability, "per_example_correct": correct, "observed_difficulty": grade, "exposes_model_failure": miss_rate > 0 or bool(confusion) or unstable > 0 or mean_conf < 0.35 or (mean_iou is not None and mean_iou < 0.5), }
def quantitative_report(store: RareMineStore, bank_id: str) -> Dict[str, Any]: tcs = [t for t in store.where("track_candidates", bank_id=bank_id) if t.duplicate_of is None and t.representative.edge_case_detected] rows = [] matrix: Dict[str, Dict[str, int]] = {d: {d2: 0 for d2 in DIFF_ORDER} for d in DIFF_ORDER} agree = 0 with_obs = 0 for tc in sorted(tcs, key=lambda t: t.track_candidate_id): obs = observed_metrics(store, tc) predicted = tc.representative.perception_difficulty row = { "track_candidate_id": tc.track_candidate_id, "costume_type": tc.representative.costume_type, "predicted_difficulty": predicted, "observed": obs, } if obs is not None: with_obs += 1 matrix[predicted][obs["observed_difficulty"]] += 1 if abs(DIFF_ORDER.index(predicted) - DIFF_ORDER.index(obs["observed_difficulty"])) <= 1: agree += 1 rows.append(row) return { "candidates_evaluated": len(rows), "with_model_outputs": with_obs, "agreement_matrix": matrix, "within_one_level_agreement": round(agree / with_obs, 3) if with_obs else None, "rows": rows, "note": "predicted difficulty is the miner's forecast; observed difficulty is " "measured from actual baseline model behavior — they are compared, " "never merged", }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500"""Deterministic synthetic multimodal scene bank.
Generates driving scenes with per-scene modality availability flags and threeobject populations:
- normal pedestrians (should never become rare-event candidates), - PLANTED costumed pedestrians across the full costume taxonomy, - CONFOUNDERS (statues, decorations, ads, mannequins, signs, construction objects) that must NOT become confident candidates.
Objects expose per-modality `observables` derived from the planted truth withseeded noise; the miner consumes ONLY those observables, never the truth.Sequences include multi-frame tracks (5-20 frames), near-duplicate frames, andscenes whose baseline model predictions contain planted real failures."""
from __future__ import annotations
import randomfrom typing import Any, Dict, List, Optional, Tuple
from sensorflow.raremine.models import ( CONFOUNDER_TYPES, COSTUME_TYPES, CONTEXTS, LIGHTING, WEATHER, BaselinePrediction, GtBox, RareMineStore, Scene, SceneBank, SceneObject, new_id,)
SIL_LEVELS = ["LOW", "MODERATE", "HIGH", "EXTREME"]OCC_LEVELS = ["NONE", "PARTIAL", "HEAVY", "EXTREME"]
# How strongly each costume type distorts a human silhouette (typical range).COSTUME_SILHOUETTE = { "mascot": ("HIGH", "EXTREME"), "inflatable": ("EXTREME", "EXTREME"), "animal": ("HIGH", "EXTREME"), "character": ("MODERATE", "HIGH"), "robot_armor": ("HIGH", "EXTREME"), "oversized": ("MODERATE", "HIGH"), "large_prop": ("HIGH", "EXTREME"),}
COSTUME_TEXTURE = { "mascot": "fur", "inflatable": "vinyl", "animal": "fur", "character": "fabric", "robot_armor": "metallic", "oversized": "fabric", "large_prop": "cardboard",}
CONFOUNDER_TEXTURE = { "mascot_statue": "fiberglass", "inflatable_decoration": "vinyl", "roadside_advertisement": "flat_print", "mannequin": "plastic", "sign": "flat_print", "construction_object": "plastic",}
FAILURE_CYCLE = [ "FALSE_NEGATIVE", "MISCLASSIFICATION_VEHICLE", "MISCLASSIFICATION_ANIMAL", "MISCLASSIFICATION_BACKGROUND", "LOCALIZATION_ERROR", "LOW_CONFIDENCE", "TRACKING_FAILURE",]
def _level_ge(level: str, floor: str, scale: List[str]) -> bool: return scale.index(level) >= scale.index(floor)
def _combine_occ(a: str, b: str) -> str: return OCC_LEVELS[max(OCC_LEVELS.index(a), OCC_LEVELS.index(b))]
# ------------------------------------------------------------------ observables
def _rgb_observables(rng: random.Random, obj: SceneObject, lighting: str) -> Dict[str, Any]: """What a single RGB camera would plausibly report about this object.""" occ = _combine_occ(obj.truth_occlusion_env, obj.truth_occlusion_costume) vis_penalty = {"NONE": 0.0, "PARTIAL": 0.25, "HEAVY": 0.55, "EXTREME": 0.8}[occ] vis_penalty += 0.15 if lighting == "night" else 0.0 vis_penalty += min(obj.distance_m / 120.0, 0.3) visibility = max(0.05, 1.0 - vis_penalty + rng.uniform(-0.05, 0.05))
kind = obj.truth_kind if kind == "normal_pedestrian": face = visibility > 0.35 skin = visibility > 0.3 limbs = visibility > 0.25 sil = "LOW" texture = "fabric" bulky = False elif kind == "costumed_pedestrian": ct = obj.truth_costume_type or "mascot" # face/skin peeking through costume seams — rarer for full-body suits face = visibility > 0.55 and ct in ("character", "oversized") and rng.random() < 0.7 skin = visibility > 0.5 and rng.random() < (0.55 if ct in ("character", "oversized") else 0.2) limbs = visibility > 0.3 and rng.random() < 0.8 sil = obj.truth_silhouette_deviation texture = COSTUME_TEXTURE[ct] bulky = sil in ("HIGH", "EXTREME") else: # confounder ct = obj.truth_costume_type or "sign" face = ct == "mannequin" and visibility > 0.5 skin = False limbs = ct in ("mannequin", "mascot_statue") and visibility > 0.4 sil = obj.truth_silhouette_deviation texture = CONFOUNDER_TEXTURE[ct] bulky = ct in ("mascot_statue", "inflatable_decoration")
return { "visibility": round(visibility, 3), "silhouette_deviation_observed": sil, "face_visible": bool(face), "skin_visible": bool(skin), "limbs_visible": bool(limbs), "texture": texture, "bulky_shape": bool(bulky), "flat_appearance": texture == "flat_print", }
def _point_cloud_observables(rng: random.Random, obj: SceneObject) -> Dict[str, Any]: kind = obj.truth_kind ct = obj.truth_costume_type or "" points = max(6, int(1400 / max(obj.distance_m, 4.0) + rng.uniform(-8, 8))) if kind == "normal_pedestrian": shape = "humanoid" pedestal = False elif kind == "costumed_pedestrian": shape = "bulky_blob" if obj.truth_silhouette_deviation in ("HIGH", "EXTREME") else "humanoid" pedestal = False else: shape = {"roadside_advertisement": "flat_panel", "sign": "flat_panel", "construction_object": "rigid_geometric"}.get(ct, "rigid_geometric") if ct in ("mascot_statue", "mannequin"): shape = "humanoid" if rng.random() < 0.4 else "rigid_geometric" pedestal = ct in ("mascot_statue", "mannequin") and rng.random() < 0.75 return {"point_count": points, "cluster_shape": shape, "pedestal_detected": bool(pedestal), "height_m": round(rng.uniform(1.5, 2.6) if kind != "confounder" or ct != "sign" else rng.uniform(0.8, 1.4), 2)}
def _temporal_observables(rng: random.Random, obj: SceneObject, frame_count: int) -> Dict[str, Any]: kind = obj.truth_kind moving = obj.truth_is_moving if kind == "confounder": articulated = False gait = 0.0 displacement = round(rng.uniform(0.0, 0.05), 3) # tethered inflatables sway without displacing sway = obj.truth_costume_type == "inflatable_decoration" else: articulated = moving and rng.random() < 0.92 gait = round(rng.uniform(0.6, 0.95), 3) if moving else round(rng.uniform(0.0, 0.15), 3) displacement = round(rng.uniform(1.0, 8.0), 2) if moving else round(rng.uniform(0.0, 0.2), 2) sway = False return { "frames_observed": frame_count, "articulated_motion": bool(articulated), "gait_periodicity": gait, "displacement_m": displacement, "stationary": displacement < 0.3, "sway_only": bool(sway), }
def _build_observables(rng: random.Random, obj: SceneObject, scene_modalities: Dict[str, bool], lighting: str, frame_count: int) -> Dict[str, Dict[str, Any]]: obs: Dict[str, Dict[str, Any]] = {} if scene_modalities.get("rgb"): obs["rgb"] = _rgb_observables(rng, obj, lighting) if scene_modalities.get("multi_camera"): obs["multi_camera"] = { "views_confirming": rng.randint(1, 3), "parallax_consistent_3d": obj.truth_costume_type not in ("roadside_advertisement", "sign") or rng.random() < 0.15, } if scene_modalities.get("point_cloud"): obs["point_cloud"] = _point_cloud_observables(rng, obj) if scene_modalities.get("lidar_projection"): obs["lidar_projection"] = { "camera_lidar_extent_agree": rng.random() < 0.9, "projected_height_plausible_human": 1.4 <= (obs.get("point_cloud", {}).get("height_m") or rng.uniform(1.5, 2.4)) <= 2.7, } if scene_modalities.get("lidar_intensity"): obs["lidar_intensity"] = { "retroreflective": obj.truth_costume_type in ("sign", "roadside_advertisement") and rng.random() < 0.8, "intensity_uniform": obj.truth_kind == "confounder" and rng.random() < 0.7, } if scene_modalities.get("fusion_view"): obs["fusion_view"] = { "camera_lidar_agree": rng.random() < (0.65 if obj.truth_kind == "costumed_pedestrian" else 0.9), } if scene_modalities.get("temporal_sequence"): obs["temporal_sequence"] = _temporal_observables(rng, obj, frame_count) return obs
# ------------------------------------------------------------------ predictions / GT
def _plant_predictions(rng: random.Random, scene: Scene, failure_for: Dict[str, str]) -> None: for obj in scene.objects: failure = failure_for.get(obj.track_id) if failure == "FALSE_NEGATIVE": continue # model emits nothing for this object pred = BaselinePrediction( prediction_id=new_id("pred"), object_id=obj.object_id, predicted_class="pedestrian", confidence=round(rng.uniform(0.75, 0.97), 3), localization_offset_m=round(rng.uniform(0.02, 0.3), 3), iou_with_gt=round(rng.uniform(0.72, 0.92), 3), track_stable=True, planted_failure=failure, ) if failure == "MISCLASSIFICATION_VEHICLE": pred.predicted_class = "vehicle" elif failure == "MISCLASSIFICATION_ANIMAL": pred.predicted_class = "animal" elif failure == "MISCLASSIFICATION_BACKGROUND": pred.predicted_class = "background" elif failure == "LOCALIZATION_ERROR": pred.localization_offset_m = round(rng.uniform(1.4, 3.2), 3) pred.iou_with_gt = round(rng.uniform(0.05, 0.32), 3) elif failure == "LOW_CONFIDENCE": pred.confidence = round(rng.uniform(0.08, 0.28), 3) elif failure == "TRACKING_FAILURE": pred.track_stable = False scene.baseline_predictions.append(pred)
def _plant_gt(scene: Scene) -> None: for obj in scene.objects: if obj.truth_kind == "confounder": cls = {"roadside_advertisement": "advertisement", "sign": "sign", "construction_object": "construction_object", "mascot_statue": "statue", "mannequin": "mannequin", "inflatable_decoration": "decoration"}.get(obj.truth_costume_type or "", "static_object") scene.gt_boxes.append(GtBox(object_id=obj.object_id, class_name=cls)) else: scene.gt_boxes.append(GtBox( object_id=obj.object_id, class_name="pedestrian", is_costumed=obj.truth_kind == "costumed_pedestrian", costume_type=obj.truth_costume_type))
# ------------------------------------------------------------------ event templates
def _make_object(rng: random.Random, kind: str, costume_type: Optional[str], context: str, track_id: str, moving: bool, distance: Optional[float] = None, sil: Optional[str] = None, occ_env: Optional[str] = None) -> SceneObject: if kind == "costumed_pedestrian": lo, hi = COSTUME_SILHOUETTE[costume_type or "mascot"] sil = sil or rng.choice(SIL_LEVELS[SIL_LEVELS.index(lo):SIL_LEVELS.index(hi) + 1]) occ_costume = rng.choice(["NONE", "PARTIAL", "PARTIAL", "HEAVY"]) elif kind == "confounder": sil = sil or rng.choice(["MODERATE", "HIGH", "EXTREME"]) occ_costume = "NONE" else: sil = "LOW" occ_costume = "NONE" d = distance if distance is not None else round(rng.uniform(6, 55), 1) lateral = rng.uniform(-8, 8) return SceneObject( object_id=new_id("obj"), track_id=track_id, truth_kind=kind, # type: ignore[arg-type] truth_costume_type=costume_type, truth_silhouette_deviation=sil, # type: ignore[arg-type] truth_occlusion_env=occ_env or rng.choice(["NONE", "NONE", "PARTIAL", "HEAVY"]), # type: ignore[arg-type] truth_occlusion_costume=occ_costume, # type: ignore[arg-type] truth_is_moving=moving, distance_m=d, context=context, position=[round(d, 1), round(lateral, 1)], bbox_2d=[round(0.5 + lateral / 40.0, 3), round(0.45 + rng.uniform(-0.05, 0.05), 3), round(max(0.03, 2.2 / d), 3), round(max(0.06, 5.0 / d), 3)], )
def _modality_flags(rng: random.Random, multi_frame: bool, with_predictions: bool, with_gt: bool, lidar: Optional[bool] = None) -> Dict[str, bool]: has_lidar = lidar if lidar is not None else rng.random() < 0.7 return { "rgb": True, "multi_camera": rng.random() < 0.6, "lidar_projection": has_lidar and rng.random() < 0.85, "lidar_intensity": has_lidar and rng.random() < 0.6, "point_cloud": has_lidar, "fusion_view": has_lidar and rng.random() < 0.7, "temporal_sequence": multi_frame, "baseline_predictions": with_predictions, "gt_annotations": with_gt, }
def generate_scene_bank(store: RareMineStore, n_scenes: int = 60, seed: int = 7) -> SceneBank: """Deterministic bank: ~n_scenes frames spread across event sequences.""" rng = random.Random(seed) bank_id = f"bank-{seed}-{n_scenes}" # wipe any previous bank content for a clean regeneration for coll in ("scenes", "candidates", "track_candidates", "lineage", "runs"): store.clear(coll) for b in store.all("banks"): pass # keep history of bank metadata; scenes are rebuilt
scenes: List[Scene] = [] seq_counter = 0 planted_rare = 0 confounders = 0
def next_seq() -> str: nonlocal seq_counter seq_counter += 1 return f"seq-{seed}-{seq_counter:03d}"
def add_sequence(objects_spec: List[Tuple[str, Optional[str], bool]], context: str, lighting: str, weather: str, n_frames: int, with_predictions: bool, with_gt: bool, failure_for_kind: Optional[str] = None, lidar: Optional[bool] = None, near_dupe_frames: int = 0, sil: Optional[str] = None, distance: Optional[float] = None, occ_env: Optional[str] = None) -> None: nonlocal planted_rare, confounders seq_id = next_seq() modalities = _modality_flags(rng, n_frames > 1, with_predictions, with_gt, lidar=lidar) objs: List[SceneObject] = [] failure_for: Dict[str, str] = {} for kind, ct, moving in objects_spec: track_id = new_id("trk") obj = _make_object(rng, kind, ct, context, track_id, moving, sil=sil if kind == "costumed_pedestrian" else None, distance=distance if kind == "costumed_pedestrian" else None, occ_env=occ_env if kind == "costumed_pedestrian" else None) objs.append(obj) if kind == "costumed_pedestrian": planted_rare += 1 if failure_for_kind: failure_for[track_id] = failure_for_kind elif kind == "confounder": confounders += 1
base_scene_id = None for fi in range(n_frames): scene = Scene( scene_id=new_id("scene"), bank_id=bank_id, sequence_id=seq_id, frame_index=fi, lighting=lighting, weather=weather, modalities=dict(modalities), ) frame_objs = [] for obj in objs: o = obj.model_copy(deep=True) o.object_id = f"{obj.object_id}-f{fi}" if obj.truth_is_moving: o.position = [round(obj.position[0] - 0.4 * fi, 1), obj.position[1]] o.distance_m = max(3.0, round(obj.distance_m - 0.4 * fi, 1)) o.observables = _build_observables(rng, o, modalities, lighting, n_frames) frame_objs.append(o) scene.objects = frame_objs if with_gt: _plant_gt(scene) if with_predictions: _plant_predictions(rng, scene, failure_for) if fi == 0: base_scene_id = scene.scene_id scenes.append(scene)
# explicit near-duplicate copies of the first frame (same event/drive) for _ in range(near_dupe_frames): dupe = scenes[-n_frames].model_copy(deep=True) dupe.scene_id = new_id("scene") dupe.near_duplicate_of = base_scene_id scenes.append(dupe)
# --- 1) one long multi-frame track per costume type (full taxonomy), # alternating planted model failures and no-model scenes for i, ct in enumerate(COSTUME_TYPES): n_frames = [20, 12, 8, 5, 15, 7, 10][i % 7] with_preds = i % 3 != 2 # every third costume track has no model outputs failure = FAILURE_CYCLE[i % len(FAILURE_CYCLE)] if with_preds else None add_sequence( [("costumed_pedestrian", ct, True), ("normal_pedestrian", None, True)], context=CONTEXTS[i % len(CONTEXTS)], lighting=LIGHTING[i % 2], weather=WEATHER[i % 3], n_frames=n_frames, with_predictions=with_preds, with_gt=True, failure_for_kind=failure, )
# --- 2) single-frame costumed sightings (temporal NOT available) for i, ct in enumerate(COSTUME_TYPES): add_sequence( [("costumed_pedestrian", ct, i % 2 == 0)], context=CONTEXTS[(i + 1) % len(CONTEXTS)], lighting=LIGHTING[(i + 1) % 2], weather=WEATHER[(i + 1) % 3], n_frames=1, with_predictions=i % 2 == 0, with_gt=i % 2 == 0, failure_for_kind="LOW_CONFIDENCE" if i % 2 == 0 else None, )
# --- 3) confounders (every type), mostly static, some in event areas for i, ct in enumerate(CONFOUNDER_TYPES): add_sequence( [("confounder", ct, False)], context="event_area" if i % 2 == 0 else CONTEXTS[i % len(CONTEXTS)], lighting=LIGHTING[i % 2], weather="clear", n_frames=6 if i % 2 == 0 else 1, with_predictions=False, with_gt=True, )
# --- 4) a safety-critical CRITICAL exemplar: EXTREME inflatable at a # crosswalk at night with an observed FALSE_NEGATIVE add_sequence( [("costumed_pedestrian", "inflatable", True)], context="crosswalk", lighting="night", weather="clear", n_frames=8, with_predictions=True, with_gt=True, failure_for_kind="FALSE_NEGATIVE", lidar=True, sil="EXTREME", distance=9.0, occ_env="PARTIAL", ) # ... and an easy fully-visible day case for priority-ordering contrast add_sequence( [("costumed_pedestrian", "character", True)], context="sidewalk", lighting="day", weather="clear", n_frames=6, with_predictions=True, with_gt=True, failure_for_kind=None, lidar=True, sil="HIGH", distance=12.0, occ_env="NONE", )
# --- 5) near-duplicate drives: same mascot event repeated (dedup fodder) for _ in range(3): add_sequence( [("costumed_pedestrian", "mascot", True)], context="event_area", lighting="day", weather="clear", n_frames=5, with_predictions=True, with_gt=True, failure_for_kind="MISCLASSIFICATION_ANIMAL", near_dupe_frames=2, sil="HIGH", distance=18.0, )
# --- 6) a scene with NO lidar at all (modality-discipline fodder) add_sequence( [("costumed_pedestrian", "robot_armor", True), ("normal_pedestrian", None, True)], context="road_edge", lighting="night", weather="rain", n_frames=1, with_predictions=False, with_gt=False, lidar=False, )
# --- 7) normal-pedestrian-only filler up to ~n_scenes frames while len(scenes) < n_scenes: add_sequence( [("normal_pedestrian", None, True), ("normal_pedestrian", None, rng.random() < 0.5)], context=rng.choice(CONTEXTS), lighting=rng.choice(LIGHTING), weather=rng.choice(WEATHER), n_frames=1, with_predictions=rng.random() < 0.5, with_gt=rng.random() < 0.5, )
bank = SceneBank( bank_id=bank_id, seed=seed, num_scenes=len(scenes), num_sequences=seq_counter, num_planted_rare=planted_rare, num_confounders=confounders, generation_params={"n_scenes": n_scenes, "seed": seed}, ) store.put("banks", bank) for s in scenes: store.put("scenes", s) store.audit("scene_bank_generated", "SceneBank", bank_id, f"{len(scenes)} scenes, {seq_counter} sequences, " f"{planted_rare} planted rare, {confounders} confounders") store.save() return bank123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""Track-level consolidation: N frame-level proposals of the same physicalevent become ONE track candidate with representative frames.
Representative frames: - best_evidence: frame with the strongest evidence quality / rare confidence - worst_case: hardest frame (max difficulty, min visibility) - model_failure: a frame where a baseline failure was actually observed - minimal_set: the deduplicated union of the above (the recommended frames to curate — never the whole track)"""
from __future__ import annotations
from typing import Dict, List
from sensorflow.raremine.models import ( Candidate, RareMineStore, RepresentativeFrames, TrackCandidate, new_id,)
DIFF_ORDER = ["EASY", "MODERATE", "HARD", "EXTREME"]QUALITY_ORDER = ["LOW", "MEDIUM", "HIGH"]PRIORITY_ORDER = ["LOW", "MEDIUM", "HIGH", "CRITICAL"]
def _evidence_score(c: Candidate) -> float: return QUALITY_ORDER.index(c.evidence_quality) + c.confidence_rare_event
def _hardness_score(c: Candidate) -> float: occ = ["NONE", "PARTIAL", "HEAVY", "EXTREME"].index(c.occlusion_level) return DIFF_ORDER.index(c.perception_difficulty) * 2 + occ
def consolidate_tracks(store: RareMineStore, bank_id: str, run_id: str = "") -> List[TrackCandidate]: """Group frame candidates by (sequence, track) into track candidates.""" frame_cands = [c for c in store.where("candidates", bank_id=bank_id) if not run_id or c.run_id == run_id] groups: Dict[str, List[Candidate]] = {} for c in frame_cands: groups.setdefault(f"{c.sequence_id}:{c.track_id}", []).append(c)
out: List[TrackCandidate] = [] for key, cands in sorted(groups.items()): cands.sort(key=lambda c: c.frame_index) detected = [c for c in cands if c.edge_case_detected] # a track is a candidate if ANY frame proposed it; representative is the # best-evidence detected frame (or best overall for rejected tracks) pool = detected or cands best = max(pool, key=_evidence_score) worst = max(pool, key=_hardness_score) failure_frames = [c for c in pool if c.observed_model_behavior and c.observed_model_behavior.failure_observed] failure = max(failure_frames, key=_evidence_score) if failure_frames else None
minimal: List[str] = [] for c in [best, worst, failure]: if c is not None and c.scene_id not in minimal: minimal.append(c.scene_id)
max_diff = max(pool, key=lambda c: DIFF_ORDER.index(c.perception_difficulty)) max_vis = max(pool, key=lambda c: QUALITY_ORDER.index(c.evidence_quality))
# the representative carries the track-level judgment: max priority # across frames, an observed failure from ANY frame rep = best.model_copy(deep=True) rep.curation_priority = max( (c.curation_priority for c in pool), key=PRIORITY_ORDER.index) if failure is not None and (rep.observed_model_behavior is None or not rep.observed_model_behavior.failure_observed): rep.observed_model_behavior = failure.observed_model_behavior rep.recommended_dataset_destination = failure.recommended_dataset_destination rep.priority_reason = failure.priority_reason
tc = TrackCandidate( track_candidate_id=new_id("tcand"), bank_id=bank_id, run_id=run_id, sequence_id=cands[0].sequence_id, track_id=cands[0].track_id, object_id=best.object_id, frame_count=len(cands), duration_frames=cands[-1].frame_index - cands[0].frame_index + 1, frame_candidate_ids=[c.candidate_id for c in cands], representative=rep, representative_frames=RepresentativeFrames( best_evidence=best.scene_id, worst_case=worst.scene_id, model_failure=failure.scene_id if failure else None, minimal_set=minimal, ), max_visibility=max_vis.evidence_quality, max_difficulty=max_diff.perception_difficulty, stage="MINED", destination=rep.recommended_dataset_destination, ) store.put("track_candidates", tc) out.append(tc) return out15 unmodified lines16171819202126 unmodified lines48495051525311 unmodified lines65666768697017 unmodified lines888990919293199 unmodified lines29329429529629729815 unmodified linesDatabase,Tag,Radar,ShieldCheck,TrendingDown,Microscope,26 unmodified linesimport LegacyStudioPage from './pages/LegacyStudioPage';import CommandCenterPage from './pages/CommandCenterPage';import RootCauseLabPage from './pages/rca/RootCauseLabPage';import PageIntro from './components/help/PageIntro';import HelpMenu from './components/help/HelpMenu';11 unmodified lines{ id: 'datasets', label: 'Datasets', icon: <Database size={18} /> },{ id: 'label-generation', label: 'Label Generation', icon: <Tag size={18} /> },{ id: 'rare-events', label: 'Rare Events', icon: <Radar size={18} /> },{ id: 'quality', label: 'Quality Engine', icon: <ShieldCheck size={18} /> },{ id: 'regression', label: 'Regression', icon: <TrendingDown size={18} /> },{ id: 'rca', label: 'Root Cause Lab', icon: <Microscope size={18} /> },17 unmodified linesdatasets: 'Datasets','label-generation': 'Label Generation','rare-events': 'Rare Event Detection',quality: 'Quality Engine',regression: 'Regression Tracking',rca: 'Root Cause Lab',199 unmodified lines{page === 'datasets' ? <DatasetsPage /> : null}{page === 'label-generation' ? <LabelGenerationPage /> : null}{page === 'rare-events' ? <RareEventDashboard /> : null}{page === 'quality' ? <QualityEnginePage /> : null}{page === 'regression' ? <RegressionPage /> : null}{page === 'rca' ? <RootCauseLabPage /> : null}15 unmodified lines1617181920212226 unmodified lines4950515253545511 unmodified lines6768697071727317 unmodified lines91929394959697199 unmodified lines29729829930030130230315 unmodified linesDatabase,Tag,Radar,Pickaxe,ShieldCheck,TrendingDown,Microscope,26 unmodified linesimport LegacyStudioPage from './pages/LegacyStudioPage';import CommandCenterPage from './pages/CommandCenterPage';import RootCauseLabPage from './pages/rca/RootCauseLabPage';import RareMinePage from './pages/raremine/RareMinePage';import PageIntro from './components/help/PageIntro';import HelpMenu from './components/help/HelpMenu';11 unmodified lines{ id: 'datasets', label: 'Datasets', icon: <Database size={18} /> },{ id: 'label-generation', label: 'Label Generation', icon: <Tag size={18} /> },{ id: 'rare-events', label: 'Rare Events', icon: <Radar size={18} /> },{ id: 'raremine', label: 'Rare-Event Miner', icon: <Pickaxe size={18} /> },{ id: 'quality', label: 'Quality Engine', icon: <ShieldCheck size={18} /> },{ id: 'regression', label: 'Regression', icon: <TrendingDown size={18} /> },{ id: 'rca', label: 'Root Cause Lab', icon: <Microscope size={18} /> },17 unmodified linesdatasets: 'Datasets','label-generation': 'Label Generation','rare-events': 'Rare Event Detection',raremine: 'Rare-Event Miner (Costumed Pedestrians)',quality: 'Quality Engine',regression: 'Regression Tracking',rca: 'Root Cause Lab',199 unmodified lines{page === 'datasets' ? <DatasetsPage /> : null}{page === 'label-generation' ? <LabelGenerationPage /> : null}{page === 'rare-events' ? <RareEventDashboard /> : null}{page === 'raremine' ? <RareMinePage /> : null}{page === 'quality' ? <QualityEnginePage /> : null}{page === 'regression' ? <RegressionPage /> : null}{page === 'rca' ? <RootCauseLabPage /> : null}
172 unmodified lines17317417517617717814 unmodified lines193194195196197198172 unmodified lines'datasets','label-generation','rare-events','quality','regression','rca',14 unmodified linesdatasets: 'Datasets','label-generation': 'Label Generation','rare-events': 'Rare Events',quality: 'Quality Engine',regression: 'Regression',rca: 'Root Cause Lab',172 unmodified lines17317417517617717817914 unmodified lines194195196197198199200172 unmodified lines'datasets','label-generation','rare-events','raremine','quality','regression','rca',14 unmodified linesdatasets: 'Datasets','label-generation': 'Label Generation','rare-events': 'Rare Events',raremine: 'Rare-Event Miner',quality: 'Quality Engine',regression: 'Regression',rca: 'Root Cause Lab',
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411/** * Review-queue card for one track-level candidate: schematic scene, the three * separate confidence gauges, modality-tagged evidence, alternative hypotheses * with retained/rejected reasons, observed vs predicted failure (kept strictly * apart), approve/reject with note, and the lineage/governance panel. */import { useEffect, useState } from 'react';import Box from '@mui/material/Box';import Button from '@mui/material/Button';import Card from '@mui/material/Card';import CardContent from '@mui/material/CardContent';import Chip from '@mui/material/Chip';import Collapse from '@mui/material/Collapse';import Dialog from '@mui/material/Dialog';import DialogActions from '@mui/material/DialogActions';import DialogContent from '@mui/material/DialogContent';import DialogTitle from '@mui/material/DialogTitle';import MenuItem from '@mui/material/MenuItem';import TextField from '@mui/material/TextField';import Typography from '@mui/material/Typography';import { CheckCircle2, ChevronDown, ChevronUp, ShieldAlert, XCircle } from 'lucide-react';import type { LineageRecord, SceneView, TrackCandidateSummary } from '../../types/raremine';import { getCandidateScene, getCandidate, governanceOverride, promoteToTraining, reviewCandidate,} from '../../services/raremine';import ConfidenceGauges from './ConfidenceGauges';import SceneCanvas from './SceneCanvas';import { DifficultyChip, PriorityChip, SectionLabel } from './shared';
const DESTINATIONS = [ 'RARE_EVENT_DATASET', 'HARD_EXAMPLE_DATASET', 'REGRESSION_EVALUATION_SET', 'SAFETY_CRITICAL_EVALUATION_SET',];
function EvidenceList({ items }: { items: { modality: string; description: string }[] }) { if (!items.length) { return ( <Typography variant="caption" sx={{ color: '#5c6a76' }}> none recorded </Typography> ); } return ( <Box component="ul" sx={{ m: 0, pl: 2 }}> {items.map((e, i) => ( <Typography key={i} component="li" variant="body2" sx={{ color: '#c3ccd5', fontSize: 12.5 }}> <Box component="span" sx={{ color: '#4fc3f7', fontFamily: 'monospace', fontSize: 11 }}> [{e.modality}] </Box>{' '} {e.description} </Typography> ))} </Box> );}
function LineagePanel({ lineage, onOverride, onPromote, busy,}: { lineage: LineageRecord; onOverride: () => void; onPromote: () => void; busy: boolean;}) { return ( <Box sx={{ p: 1.5, bgcolor: '#10151b', border: '1px solid #232a31', borderRadius: 1 }}> <SectionLabel>Lineage & governance</SectionLabel> <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.75, mb: 1 }}> <Chip size="small" label={`validation: ${lineage.validation_status}`} sx={{ bgcolor: '#232a31', fontSize: 11 }} /> <Chip size="small" label={`training ${lineage.training_eligible ? 'ELIGIBLE' : 'NOT eligible'}`} sx={{ bgcolor: lineage.training_eligible ? '#1b5e20' : '#37474f', color: '#fff', fontSize: 11, }} /> <Chip size="small" label={`evaluation ${lineage.evaluation_eligible ? 'eligible' : 'not eligible'}`} sx={{ bgcolor: '#232a31', fontSize: 11 }} /> {lineage.protected_evaluation ? ( <Chip size="small" icon={<ShieldAlert size={13} />} label="PROTECTED EVAL SET" sx={{ bgcolor: '#4a148c', color: '#fff', fontSize: 11 }} /> ) : null} </Box> <Typography variant="caption" sx={{ color: '#5c6a76', display: 'block' }}> source frame {lineage.source_frame_id} · sequence {lineage.source_sequence_id} · {lineage.dataset_version} · curator {lineage.curator} · {new Date(lineage.curation_timestamp).toLocaleString()} </Typography> {lineage.governance_overrides.length ? ( <Typography variant="caption" sx={{ color: '#ffb74d', display: 'block', mt: 0.5 }}> override on record: {lineage.governance_overrides[0].actor} — “{lineage.governance_overrides[0].reason}” </Typography> ) : null} {lineage.validation_status === 'APPROVED' ? ( <Box sx={{ display: 'flex', gap: 1, mt: 1 }}> <Button size="small" variant="outlined" color="warning" disabled={busy} onClick={onPromote}> Promote to training </Button> {lineage.protected_evaluation && !lineage.governance_overrides.length ? ( <Button size="small" color="secondary" disabled={busy} onClick={onOverride}> Request governance override… </Button> ) : null} </Box> ) : null} </Box> );}
export default function CandidateCard({ summary, onChanged,}: { summary: TrackCandidateSummary; onChanged: () => void;}) { const c = summary.candidate; const [scene, setScene] = useState<SceneView | null>(null); const [lineage, setLineage] = useState<LineageRecord | null>(null); const [expanded, setExpanded] = useState(false); const [note, setNote] = useState(''); const [destination, setDestination] = useState( DESTINATIONS.includes(c.recommended_dataset_destination) ? c.recommended_dataset_destination : 'RARE_EVENT_DATASET' ); const [busy, setBusy] = useState(false); const [error, setError] = useState<string | null>(null); const [overrideOpen, setOverrideOpen] = useState(false); const [overrideActor, setOverrideActor] = useState(''); const [overrideReason, setOverrideReason] = useState('');
useEffect(() => { getCandidateScene(summary.track_candidate_id).then(setScene).catch(() => setScene(null)); getCandidate(summary.track_candidate_id) .then((d) => setLineage(d.lineage)) .catch(() => undefined); }, [summary.track_candidate_id, summary.stage, summary.destination]);
const act = async (fn: () => Promise<unknown>) => { setBusy(true); setError(null); try { await fn(); const d = await getCandidate(summary.track_candidate_id); setLineage(d.lineage); onChanged(); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setBusy(false); } };
const decided = summary.human_validation !== null; const behavior = c.observed_model_behavior;
return ( <Card sx={{ bgcolor: '#141a20', border: '1px solid #232a31' }}> <CardContent sx={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}> {/* left: schematic scene */} <Box sx={{ flexShrink: 0 }}> {scene ? ( <SceneCanvas scene={scene} /> ) : ( <Box sx={{ width: 300, height: 260, bgcolor: '#0d1117', borderRadius: 1 }} /> )} </Box>
{/* right: judgment */} <Box sx={{ flex: 1, minWidth: 320 }}> <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, flexWrap: 'wrap', mb: 1 }}> <PriorityChip value={c.curation_priority} /> <DifficultyChip value={c.perception_difficulty} /> <Chip size="small" label={`silhouette ${c.silhouette_deviation}`} sx={{ bgcolor: '#232a31', fontSize: 10.5, height: 20 }} /> <Chip size="small" label={`occlusion ${c.occlusion_level} (${c.occlusion_source.toLowerCase().replace(/_/g, ' ')})`} sx={{ bgcolor: '#232a31', fontSize: 10.5, height: 20 }} /> <Chip size="small" label={`evidence ${c.evidence_quality}`} sx={{ bgcolor: '#232a31', fontSize: 10.5, height: 20 }} /> {summary.frame_count > 1 ? ( <Chip size="small" label={`track · ${summary.frame_count} frames`} sx={{ bgcolor: '#0d47a1', color: '#90caf9', fontSize: 10.5, height: 20 }} /> ) : ( <Chip size="small" label="single frame" sx={{ bgcolor: '#232a31', fontSize: 10.5, height: 20 }} /> )} {summary.stage === 'CURATED' ? ( <Chip size="small" icon={<CheckCircle2 size={13} />} label={summary.destination} sx={{ bgcolor: '#1b5e20', color: '#fff', fontSize: 10.5, height: 20 }} /> ) : null} {summary.stage === 'ARCHIVED' ? ( <Chip size="small" icon={<XCircle size={13} />} label="rejected" sx={{ bgcolor: '#5d1616', color: '#fff', fontSize: 10.5, height: 20 }} /> ) : null} </Box>
<Typography variant="subtitle2" sx={{ fontWeight: 700, mb: 0.25 }}> {c.event_type === 'costumed_pedestrian' ? `Costumed pedestrian — ${c.costume_type.join(' / ') || 'family undetermined'}` : 'No confirmed edge case'} <Typography component="span" variant="caption" sx={{ color: '#5c6a76', ml: 1, fontFamily: 'monospace' }}> {summary.track_candidate_id} </Typography> </Typography> <Typography variant="caption" sx={{ color: '#8a949e', display: 'block', mb: 1 }}> {c.location.context} · {c.location.distance_m?.toFixed(0)} m · {c.location.lighting} · {c.location.weather} · recommended → <b>{c.recommended_dataset_destination}</b> </Typography>
<Box sx={{ maxWidth: 380, mb: 1 }}> <ConfidenceGauges candidate={c} /> </Box>
{/* observed vs predicted — strictly separated */} <Box sx={{ display: 'flex', gap: 1.5, flexWrap: 'wrap', mb: 1 }}> <Box sx={{ flex: '1 1 240px', p: 1, bgcolor: '#10151b', borderRadius: 1, border: '1px solid #232a31' }}> <SectionLabel>Observed model behavior (measured)</SectionLabel> {behavior === null ? ( <Typography variant="caption" sx={{ color: '#5c6a76' }}> NOT AVAILABLE — no baseline predictions were supplied for this scene. Nothing is inferred. </Typography> ) : behavior.failure_observed ? ( <> <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap', mb: 0.5 }}> {behavior.failure_modes.map((m) => ( <Chip key={m} size="small" label={m} sx={{ bgcolor: '#5d1616', color: '#ff8a80', fontSize: 10, height: 18 }} /> ))} </Box> {behavior.details.map((d, i) => ( <Typography key={i} variant="caption" sx={{ color: '#c3ccd5', display: 'block' }}> {d} </Typography> ))} </> ) : ( <Typography variant="caption" sx={{ color: '#66bb6a' }}> {behavior.details[0] ?? 'no failure observed'} </Typography> )} </Box> <Box sx={{ flex: '1 1 240px', p: 1, bgcolor: '#10151b', borderRadius: 1, border: '1px solid #232a31' }}> <SectionLabel>Predicted failure (miner forecast)</SectionLabel> <Typography variant="caption" sx={{ color: c.predicted_failure_mode ? '#ffb74d' : '#5c6a76' }}> {c.predicted_failure_mode ?? 'no failure predicted'} </Typography> <Typography variant="caption" sx={{ color: '#5c6a76', display: 'block', mt: 0.5 }}> A forecast from evidence rules — kept separate from measured behavior on the left. </Typography> </Box> </Box>
<Button size="small" onClick={() => setExpanded((v) => !v)} endIcon={expanded ? <ChevronUp size={13} /> : <ChevronDown size={13} />} sx={{ textTransform: 'none', color: '#8a949e', fontSize: 12, mb: 0.5 }} > Evidence, alternative hypotheses & lineage </Button> <Collapse in={expanded} unmountOnExit> <Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap', mb: 1 }}> <Box sx={{ flex: '1 1 260px' }}> <SectionLabel>Visual evidence</SectionLabel> <EvidenceList items={c.visual_evidence} /> <Box sx={{ mt: 1 }}> <SectionLabel>Human-identity evidence</SectionLabel> <EvidenceList items={c.human_identity_evidence} /> </Box> <Box sx={{ mt: 1 }}> <SectionLabel>Temporal validation</SectionLabel> <Typography variant="caption" sx={{ color: c.temporal_validation.available ? '#c3ccd5' : '#5c6a76' }}> {c.temporal_validation.status} {c.temporal_validation.evidence.length ? ` — ${c.temporal_validation.evidence.join('; ')}` : ''} </Typography> </Box> </Box> <Box sx={{ flex: '1 1 260px' }}> <SectionLabel>Alternative hypotheses</SectionLabel> {c.alternative_hypotheses.map((a, i) => ( <Box key={i} sx={{ mb: 0.75 }}> <Typography variant="body2" sx={{ fontSize: 12.5, color: a.status === 'RETAINED' ? '#ffb74d' : '#5c6a76' }}> <b>{a.hypothesis}</b> · {a.status} · {(a.confidence * 100).toFixed(0)}% </Typography> <Typography variant="caption" sx={{ color: '#8a949e' }}> {a.reason} </Typography> </Box> ))} <SectionLabel>Priority reasoning</SectionLabel> <Typography variant="caption" sx={{ color: '#c3ccd5' }}> {c.priority_reason} </Typography> </Box> </Box> {lineage ? ( <LineagePanel lineage={lineage} busy={busy} onPromote={() => act(() => promoteToTraining(summary.track_candidate_id))} onOverride={() => setOverrideOpen(true)} /> ) : null} </Collapse>
{/* review actions */} {!decided ? ( <Box sx={{ display: 'flex', gap: 1, alignItems: 'center', flexWrap: 'wrap', mt: 1 }}> <TextField size="small" placeholder="review note…" value={note} onChange={(e) => setNote(e.target.value)} sx={{ width: 220 }} /> <TextField size="small" select label="destination" value={destination} onChange={(e) => setDestination(e.target.value)} sx={{ width: 250 }} > {DESTINATIONS.map((d) => ( <MenuItem key={d} value={d}> {d} </MenuItem> ))} </TextField> <Button size="small" variant="contained" color="success" disabled={busy} startIcon={<CheckCircle2 size={14} />} onClick={() => act(() => reviewCandidate(summary.track_candidate_id, 'approve', note, destination))} > Approve </Button> <Button size="small" variant="outlined" color="error" disabled={busy} startIcon={<XCircle size={14} />} onClick={() => act(() => reviewCandidate(summary.track_candidate_id, 'reject', note))} > Reject </Button> </Box> ) : null} {error ? ( <Typography variant="caption" sx={{ color: '#ff8a80', display: 'block', mt: 0.5 }}> {error} </Typography> ) : null} </Box> </CardContent>
{/* governance override confirmation */} <Dialog open={overrideOpen} onClose={() => setOverrideOpen(false)}> <DialogTitle>Governance override</DialogTitle> <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 1.5, minWidth: 380, pt: '10px !important' }}> <Typography variant="body2" sx={{ color: '#aab4be' }}> This example belongs to a <b>protected evaluation set</b>. Releasing it for training risks leaking evaluation data into the model. The override is recorded permanently with your name and reason. </Typography> <TextField size="small" label="your name (actor)" value={overrideActor} onChange={(e) => setOverrideActor(e.target.value)} /> <TextField size="small" label="reason" multiline minRows={2} value={overrideReason} onChange={(e) => setOverrideReason(e.target.value)} /> </DialogContent> <DialogActions> <Button onClick={() => setOverrideOpen(false)}>Cancel</Button> <Button color="warning" variant="contained" disabled={!overrideActor.trim() || !overrideReason.trim() || busy} onClick={() => act(async () => { await governanceOverride(summary.track_candidate_id, overrideActor, overrideReason); setOverrideOpen(false); }) } > Record override </Button> </DialogActions> </Dialog> </Card> );}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465/** * The three SEPARATE miner confidences. They are never combined into a single * score anywhere in the system; this component renders them side by side to * make that separation visible. */import Box from '@mui/material/Box';import LinearProgress from '@mui/material/LinearProgress';import Tooltip from '@mui/material/Tooltip';import Typography from '@mui/material/Typography';import type { Candidate } from '../../types/raremine';
const GAUGES: { key: keyof Candidate; label: string; tip: string; color: string }[] = [ { key: 'confidence_human_identity', label: 'Human identity', tip: 'Confidence that a real human is present (face/skin/limbs, gait, humanoid LiDAR shape). Independent of what they wear.', color: '#4fc3f7', }, { key: 'confidence_costume', label: 'Costume present', tip: 'Confidence that a silhouette-distorting covering is present. A statue can score high here while human identity stays low.', color: '#ab47bc', }, { key: 'confidence_rare_event', label: 'Rare event', tip: 'Confidence that this is a genuine costumed-pedestrian rare event — requires BOTH axes and is discounted by retained alternative hypotheses.', color: '#fb8c00', },];
export default function ConfidenceGauges({ candidate }: { candidate: Candidate }) { return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.75 }}> {GAUGES.map((g) => { const v = candidate[g.key] as number; return ( <Tooltip key={g.key} title={g.tip} placement="top" arrow> <Box> <Box sx={{ display: 'flex', justifyContent: 'space-between' }}> <Typography variant="caption" sx={{ color: '#8a949e', fontSize: 11 }}> {g.label} </Typography> <Typography variant="caption" sx={{ color: g.color, fontWeight: 700, fontFamily: 'monospace' }}> {(v * 100).toFixed(0)}% </Typography> </Box> <LinearProgress variant="determinate" value={v * 100} sx={{ height: 7, borderRadius: 4, bgcolor: '#1c242d', '& .MuiLinearProgress-bar': { bgcolor: g.color, borderRadius: 4 }, }} /> </Box> </Tooltip> ); })} </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271/** * Coverage & curator-quality tab: diversity coverage matrix, confidence * calibration reliability chart, precision/recall/yield/model-value cards and * the recurring-miss improvement report. */import { useEffect, useState } from 'react';import Box from '@mui/material/Box';import Card from '@mui/material/Card';import CardContent from '@mui/material/CardContent';import Chip from '@mui/material/Chip';import Table from '@mui/material/Table';import TableBody from '@mui/material/TableBody';import TableCell from '@mui/material/TableCell';import TableHead from '@mui/material/TableHead';import TableRow from '@mui/material/TableRow';import Typography from '@mui/material/Typography';import type { CuratorReport, DiversityReport, ImprovementReport, QuantvalReport } from '../../types/raremine';import { getCuratorReport, getDiversityReport, getImprovementReport, getQuantvalReport,} from '../../services/raremine';import { Explainer, SectionLabel } from './shared';
function MetricCard({ label, value, sub }: { label: string; value: string; sub?: string }) { return ( <Card sx={{ bgcolor: '#141a20', border: '1px solid #232a31', flex: '1 1 160px', minWidth: 150 }}> <CardContent sx={{ py: 1.5, '&:last-child': { pb: 1.5 } }}> <Typography variant="caption" sx={{ color: '#8a949e' }}> {label} </Typography> <Typography variant="h5" sx={{ fontWeight: 800, color: '#4fc3f7' }}> {value} </Typography> {sub ? ( <Typography variant="caption" sx={{ color: '#5c6a76' }}> {sub} </Typography> ) : null} </CardContent> </Card> );}
function CalibrationChart({ report }: { report: CuratorReport }) { const bins = report.calibration; const W = 320; const H = 180; const pad = 34; const bw = (W - pad - 10) / bins.length; return ( <svg width={W} height={H} style={{ background: '#0d1117', borderRadius: 6, border: '1px solid #232a31' }}> {/* perfect-calibration diagonal */} <line x1={pad} y1={H - pad} x2={W - 10} y2={10} stroke="#37474f" strokeDasharray="4 4" /> {[0, 0.5, 1].map((v) => ( <g key={v}> <text x={4} y={H - pad - v * (H - pad - 10) + 4} fill="#5c6a76" fontSize={9}> {(v * 100).toFixed(0)}% </text> </g> ))} {bins.map((b, i) => { const x = pad + i * bw; if (!b.n) { return ( <text key={b.bin} x={x + bw / 2} y={H - pad + 12} fill="#37474f" fontSize={9} textAnchor="middle"> {b.bin} </text> ); } const h = (b.observed_rate ?? 0) * (H - pad - 10); return ( <g key={b.bin}> <rect x={x + 3} y={H - pad - h} width={bw - 6} height={h} fill="#4fc3f7" opacity={0.75} rx={2} /> <text x={x + bw / 2} y={H - pad - h - 4} fill="#c3ccd5" fontSize={9} textAnchor="middle"> {((b.observed_rate ?? 0) * 100).toFixed(0)}% (n={b.n}) </text> <text x={x + bw / 2} y={H - pad + 12} fill="#8a949e" fontSize={9} textAnchor="middle"> {b.bin} </text> </g> ); })} <text x={W / 2} y={H - 6} fill="#5c6a76" fontSize={9} textAnchor="middle"> stated rare-event confidence → observed true rate (vs planted truth) </text> </svg> );}
function CoverageMatrix({ report }: { report: DiversityReport }) { const costumes = Object.keys(report.coverage_matrix).sort(); const conditions = Array.from( new Set(costumes.flatMap((c) => Object.keys(report.coverage_matrix[c]))) ).sort(); if (!costumes.length) { return ( <Typography variant="caption" sx={{ color: '#5c6a76' }}> No diversity selection yet — run mining first. </Typography> ); } return ( <Box sx={{ overflowX: 'auto' }}> <Table size="small" sx={{ '& td, & th': { borderColor: '#232a31', fontSize: 11, py: 0.4 } }}> <TableHead> <TableRow> <TableCell sx={{ color: '#8a949e' }}>costume ↓ / condition →</TableCell> {conditions.map((cond) => ( <TableCell key={cond} sx={{ color: '#8a949e', whiteSpace: 'nowrap' }}> {cond.replace(':', ': ')} </TableCell> ))} </TableRow> </TableHead> <TableBody> {costumes.map((cost) => ( <TableRow key={cost}> <TableCell sx={{ color: '#c3ccd5', fontWeight: 700 }}>{cost}</TableCell> {conditions.map((cond) => { const n = report.coverage_matrix[cost][cond] ?? 0; return ( <TableCell key={cond} sx={{ bgcolor: n ? 'rgba(79,195,247,0.14)' : undefined, color: n ? '#4fc3f7' : '#37474f' }}> {n || '·'} </TableCell> ); })} </TableRow> ))} </TableBody> </Table> </Box> );}
export default function CoverageQualityTab({ refreshKey }: { refreshKey: number }) { const [curator, setCurator] = useState<CuratorReport | null>(null); const [diversity, setDiversity] = useState<DiversityReport | null>(null); const [quant, setQuant] = useState<QuantvalReport | null>(null); const [improvement, setImprovement] = useState<ImprovementReport | null>(null);
useEffect(() => { getCuratorReport().then(setCurator).catch(() => setCurator(null)); getDiversityReport().then(setDiversity).catch(() => setDiversity(null)); getQuantvalReport().then(setQuant).catch(() => setQuant(null)); getImprovementReport().then(setImprovement).catch(() => setImprovement(null)); }, [refreshKey]);
const pct = (v: number | null | undefined) => (v === null || v === undefined ? '—' : `${(v * 100).toFixed(1)}%`);
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> <Explainer> This tab measures the MINER, not the scenes: because rare events are planted synthetically, ground truth is known and mining precision/recall are exact. Calibration compares the miner's stated confidence with how often it was actually right — a well-calibrated 80% bin should be right about 80% of the time. None of these statistics change any candidate; they feed the improvement loop for the next run. </Explainer>
{curator ? ( <Box sx={{ display: 'flex', gap: 1.5, flexWrap: 'wrap' }}> <MetricCard label="Mining precision" value={pct(curator.mining_precision)} sub={`FDR ${pct(curator.false_discovery_rate)}`} /> <MetricCard label="Mining recall" value={pct(curator.mining_recall)} sub={`${curator.confusion.tp}/${curator.planted_positives} planted events found`} /> <MetricCard label="Curation yield" value={pct(curator.curation_yield.yield)} sub={`${curator.curation_yield.approved}/${curator.curation_yield.reviewed} reviewed approved`} /> <MetricCard label="Model value" value={pct(curator.model_value.fraction)} sub={`${curator.model_value.expose_model_failure}/${curator.model_value.curated} curated expose a real failure`} /> {quant ? ( <MetricCard label="Difficulty agreement" value={pct(quant.within_one_level_agreement)} sub={`predicted vs observed, ${quant.with_model_outputs} tracks with model outputs`} /> ) : null} </Box> ) : null}
<Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}> <Box sx={{ flex: '1 1 340px' }}> <SectionLabel>Confidence calibration (reliability)</SectionLabel> {curator ? <CalibrationChart report={curator} /> : null} </Box> <Box sx={{ flex: '2 1 480px' }}> <SectionLabel>Diversity coverage matrix (selected examples)</SectionLabel> {diversity ? ( <> <Box sx={{ display: 'flex', gap: 1, mb: 1 }}> <Chip size="small" label={`coverage (diverse): ${pct(diversity.coverage_selected)}`} sx={{ bgcolor: '#1b5e20', color: '#fff' }} /> <Chip size="small" label={`coverage (naive top-k): ${pct(diversity.coverage_naive_topk)}`} sx={{ bgcolor: '#37474f', color: '#fff' }} /> <Chip size="small" label={`budget ${diversity.budget} of ${diversity.pool_size}`} sx={{ bgcolor: '#232a31' }} /> </Box> <CoverageMatrix report={diversity} /> </> ) : null} </Box> </Box>
{quant ? ( <Box> <SectionLabel>Predicted vs observed difficulty (agreement matrix)</SectionLabel> <Table size="small" sx={{ maxWidth: 480, '& td, & th': { borderColor: '#232a31', fontSize: 11.5, py: 0.4 } }}> <TableHead> <TableRow> <TableCell sx={{ color: '#8a949e' }}>predicted ↓ / observed →</TableCell> {['EASY', 'MODERATE', 'HARD', 'EXTREME'].map((d) => ( <TableCell key={d} sx={{ color: '#8a949e' }}> {d} </TableCell> ))} </TableRow> </TableHead> <TableBody> {Object.entries(quant.agreement_matrix).map(([pred, row]) => ( <TableRow key={pred}> <TableCell sx={{ color: '#c3ccd5', fontWeight: 700 }}>{pred}</TableCell> {['EASY', 'MODERATE', 'HARD', 'EXTREME'].map((obs) => ( <TableCell key={obs} sx={{ color: row[obs] ? '#4fc3f7' : '#37474f', bgcolor: pred === obs && row[obs] ? 'rgba(102,187,106,0.12)' : undefined, }} > {row[obs] || '·'} </TableCell> ))} </TableRow> ))} </TableBody> </Table> </Box> ) : null}
{improvement ? ( <Box sx={{ p: 1.5, bgcolor: '#141a20', border: '1px solid #232a31', borderRadius: 1 }}> <SectionLabel>Recurring-miss improvement report (feeds the next run)</SectionLabel> <Typography variant="body2" sx={{ color: '#c3ccd5', fontSize: 12.5, mb: 0.5 }}> {improvement.recurring_misses.total} planted event(s) missed —{' '} {Object.entries(improvement.recurring_misses.by_costume_type) .map(([k, v]) => `${k}: ${v}`) .join(', ') || 'none'} . Over-fires on confounders: {improvement.over_fires.total}. </Typography> <Typography variant="caption" sx={{ color: '#8a949e', display: 'block', mb: 0.5 }}> Suggested next-run sensitivity boosts:{' '} {Object.entries(improvement.next_run_config.sensitivity_boost) .map(([k, v]) => `${k} +${v}`) .join(', ') || 'none'} {improvement.next_run_config.rare_event_threshold ? ` · tighten rare-event threshold to ${improvement.next_run_config.rare_event_threshold}` : ''} </Typography> <Typography variant="caption" sx={{ color: '#5c6a76' }}> Use “Re-mine with improvements” on the Mining Run panel to apply this configuration. </Typography> </Box> ) : null} </Box> );}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394/** * Schematic BEV rendering of a scene from metadata: ego vehicle at the bottom, * forward distance up the canvas, lateral offset across. The mined candidate * object is highlighted with a bounding ring; other objects are gray. This is * a schematic — no imagery exists, only the generator's object metadata. */import Box from '@mui/material/Box';import Typography from '@mui/material/Typography';import type { SceneView } from '../../types/raremine';
const W = 300;const H = 260;const MAX_FORWARD = 60; // metres shownconst MAX_LATERAL = 14;
function projX(lateral: number): number { return W / 2 + (lateral / MAX_LATERAL) * (W / 2 - 16);}
function projY(forward: number): number { return H - 26 - (Math.min(forward, MAX_FORWARD) / MAX_FORWARD) * (H - 50);}
export default function SceneCanvas({ scene }: { scene: SceneView }) { return ( <Box> <svg width={W} height={H} style={{ background: '#0d1117', borderRadius: 6, border: '1px solid #232a31' }}> {/* road corridor */} <rect x={W / 2 - 42} y={0} width={84} height={H} fill="#161d24" /> <line x1={W / 2} y1={0} x2={W / 2} y2={H} stroke="#2c3640" strokeDasharray="6 6" /> {/* range rings */} {[15, 30, 45].map((d) => ( <g key={d}> <line x1={10} y1={projY(d)} x2={W - 10} y2={projY(d)} stroke="#1c242d" /> <text x={12} y={projY(d) - 3} fill="#4a5560" fontSize={9}> {d} m </text> </g> ))} {/* ego vehicle */} <rect x={W / 2 - 9} y={H - 24} width={18} height={20} rx={3} fill="#4fc3f7" opacity={0.9} /> <text x={W / 2} y={H - 8} fill="#4fc3f7" fontSize={9} textAnchor="middle"> EGO </text> {/* objects */} {scene.objects.map((o) => { const forward = o.position[0] ?? o.distance_m; const lateral = o.position[1] ?? 0; const x = projX(lateral); const y = projY(forward); const r = Math.max(5, 11 - forward / 8); return ( <g key={o.object_id}> {o.is_candidate ? ( <> <rect x={x - r - 5} y={y - r - 5} width={(r + 5) * 2} height={(r + 5) * 2} fill="none" stroke="#e53935" strokeWidth={1.6} strokeDasharray="4 3" rx={3} /> <circle cx={x} cy={y} r={r} fill="#e53935" opacity={0.85} /> <text x={x} y={y - r - 9} fill="#e53935" fontSize={9.5} fontWeight={700} textAnchor="middle"> CANDIDATE {forward.toFixed(0)} m </text> </> ) : ( <circle cx={x} cy={y} r={r} fill="#5c6a76" opacity={0.8} /> )} {o.gt ? ( <text x={x} y={y + r + 10} fill="#66bb6a" fontSize={8} textAnchor="middle"> GT: {o.gt.class_name} {o.gt.is_costumed ? ' (costumed)' : ''} </text> ) : null} </g> ); })} </svg> <Typography variant="caption" sx={{ color: '#5c6a76', display: 'block', mt: 0.5 }}> {scene.lighting} · {scene.weather} · frame {scene.frame_index} · modalities:{' '} {Object.entries(scene.modalities) .filter(([, on]) => on) .map(([m]) => m) .join(', ')} </Typography> </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293/** * Frame strip for a multi-frame track candidate: one tile per frame with the * representative frames marked (best evidence / worst case / model failure). */import Box from '@mui/material/Box';import Chip from '@mui/material/Chip';import Tooltip from '@mui/material/Tooltip';import Typography from '@mui/material/Typography';import { Award, CloudRainWind, ShieldAlert } from 'lucide-react';import type { TrackView } from '../../types/raremine';import { DIFFICULTY_COLORS, PriorityChip } from './shared';
export default function TrackStrip({ track }: { track: TrackView }) { const rf = track.representative_frames; const c = track.candidate; return ( <Box sx={{ p: 1.5, bgcolor: '#141a20', border: '1px solid #232a31', borderRadius: 1 }}> <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, flexWrap: 'wrap', mb: 1 }}> <PriorityChip value={c.curation_priority} /> <Typography variant="subtitle2" sx={{ fontWeight: 700 }}> {c.costume_type.join(' / ') || 'no confirmed edge case'} · {track.frame_count} frames </Typography> <Typography variant="caption" sx={{ color: '#5c6a76', fontFamily: 'monospace' }}> {track.sequence_id} </Typography> <Chip size="small" label={`max difficulty ${track.max_difficulty}`} sx={{ bgcolor: '#232a31', fontSize: 10.5, height: 20 }} /> <Chip size="small" label={`max visibility ${track.max_visibility}`} sx={{ bgcolor: '#232a31', fontSize: 10.5, height: 20 }} /> <Chip size="small" label={`minimal set: ${rf.minimal_set.length} frame(s)`} sx={{ bgcolor: '#0d47a1', color: '#90caf9', fontSize: 10.5, height: 20 }} /> </Box> <Box sx={{ display: 'flex', gap: 0.5, overflowX: 'auto', pb: 0.5 }}> {track.frames.map((f) => { const markers = []; if (f.scene_id === rf.best_evidence) markers.push('best evidence'); if (f.scene_id === rf.worst_case) markers.push('worst case'); if (f.scene_id === rf.model_failure) markers.push('model failure'); const marked = markers.length > 0; return ( <Tooltip key={f.candidate_id} arrow title={`frame ${f.frame_index} · rare ${(f.confidence_rare_event * 100).toFixed(0)}% · ${f.perception_difficulty}${ f.failure_observed ? ' · baseline failure observed' : '' }${marked ? ` · ${markers.join(', ')}` : ''}`} > <Box sx={{ minWidth: 34, height: 46, borderRadius: 0.75, border: marked ? '2px solid #4fc3f7' : '1px solid #232a31', bgcolor: '#0d1117', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'space-between', p: 0.4, flexShrink: 0, }} > <Box sx={{ width: '100%', height: 7, borderRadius: 0.5, bgcolor: DIFFICULTY_COLORS[f.perception_difficulty] ?? '#37474f', opacity: f.edge_case_detected ? 1 : 0.25, }} /> <Box sx={{ display: 'flex', gap: 0.2 }}> {f.scene_id === rf.best_evidence ? <Award size={11} color="#66bb6a" /> : null} {f.scene_id === rf.worst_case ? <CloudRainWind size={11} color="#fb8c00" /> : null} {f.scene_id === rf.model_failure ? <ShieldAlert size={11} color="#e53935" /> : null} </Box> <Typography variant="caption" sx={{ fontSize: 8.5, color: '#5c6a76', lineHeight: 1 }}> {f.frame_index} </Typography> </Box> </Tooltip> ); })} </Box> <Typography variant="caption" sx={{ color: '#5c6a76' }}> Legend: <Award size={10} color="#66bb6a" /> best evidence · <CloudRainWind size={10} color="#fb8c00" /> worst case · <ShieldAlert size={10} color="#e53935" /> observed model failure. Bar color = per-frame difficulty. The recommended curation set is the marked frames only — never all {track.frame_count} near-identical frames. </Typography> </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596import type { ReactNode } from 'react';import Box from '@mui/material/Box';import Chip from '@mui/material/Chip';import Typography from '@mui/material/Typography';
export const PRIORITY_COLORS: Record<string, string> = { CRITICAL: '#e53935', HIGH: '#fb8c00', MEDIUM: '#fdd835', LOW: '#78909c',};
export const DIFFICULTY_COLORS: Record<string, string> = { EXTREME: '#e53935', HARD: '#fb8c00', MODERATE: '#fdd835', EASY: '#66bb6a',};
export function PriorityChip({ value }: { value: string }) { return ( <Chip size="small" label={value} sx={{ bgcolor: PRIORITY_COLORS[value] ?? '#78909c', color: value === 'MEDIUM' ? '#1a1a1a' : '#fff', fontWeight: 700, fontSize: 10.5, height: 20, }} /> );}
export function DifficultyChip({ value }: { value: string }) { return ( <Chip size="small" variant="outlined" label={`difficulty ${value}`} sx={{ borderColor: DIFFICULTY_COLORS[value] ?? '#78909c', color: DIFFICULTY_COLORS[value] ?? '#78909c', fontWeight: 700, fontSize: 10.5, height: 20, }} /> );}
export function SectionLabel({ children }: { children: ReactNode }) { return ( <Typography variant="caption" sx={{ color: '#4fc3f7', fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.6, display: 'block', mb: 0.5 }} > {children} </Typography> );}
/** Plain-language explainer used at the top of each view. */export function Explainer({ children }: { children: ReactNode }) { return ( <Box sx={{ p: 1.5, bgcolor: '#141a20', border: '1px solid #232a31', borderLeft: '3px solid #4fc3f7', borderRadius: 1, mb: 2, }} > <Typography variant="body2" sx={{ color: '#aab4be', fontSize: 12.5, lineHeight: 1.6 }}> {children} </Typography> </Box> );}
export function StatChip({ label, value, color }: { label: string; value: ReactNode; color?: string }) { return ( <Chip size="small" label={ <span> <b>{value}</b> {label} </span> } sx={{ bgcolor: '#232a31', color: color ?? '#e0e6ec', fontSize: 12, height: 24 }} /> );}653 unmodified lines654655656657658659653 unmodified linesshort: 'Running a candidate model on live traffic without acting on its output.',detail: 'The candidate scores real production inputs in parallel with the incumbent; outcomes are compared post-hoc. Sensitive to sampling bias, serving-config differences and provisional labels — which is why the Root Cause Lab audits the shadow pipeline before trusting its number.',},};export type GlossaryKey = keyof typeof GLOSSARY;653 unmodified lines654655656657658659660661662663664665666667668669670671672673674675676677678679680653 unmodified linesshort: 'Running a candidate model on live traffic without acting on its output.',detail: 'The candidate scores real production inputs in parallel with the incumbent; outcomes are compared post-hoc. Sensitive to sampling bias, serving-config differences and provisional labels — which is why the Root Cause Lab audits the shadow pipeline before trusting its number.',},// ------------------------------------------------- rare-event mining (raremine)costumed_pedestrian: {term: 'Costumed pedestrian',category: 'Anomaly & rarity',short: 'A person whose costume distorts the human silhouette a detector relies on.',detail: 'Mascot / inflatable / animal / character / robot-armor / oversized / large-prop costumes break silhouette, texture and proportion priors, causing misses or misclassification (vehicle, animal, background). The Rare-Event Miner keeps three SEPARATE confidences: a human is present, a costume is present, and the combination is a rare event.',caveat: 'Confounders (mascot statues, inflatable decorations, printed figures, mannequins) look identical in one frame — only motion, 3D volume, or human validation separates them.',},leakage_guard: {term: 'Leakage guard',category: 'Operations',short: 'Examples in protected evaluation sets can never silently become training data.',detail: 'Anything routed to a REGRESSION or SAFETY_CRITICAL evaluation set gets training_eligible=false in its lineage. Promoting such an example to training requires an explicit governance override recording who and why, which is permanently audited.',},mining_calibration: {term: 'Mining calibration',category: 'Anomaly & rarity',short: 'Whether the miner\u2019s stated confidence matches how often it is right.',detail: 'Candidates are binned by stated rare-event confidence; within each bin, the observed rate of true (planted) rare events is measured. A calibrated miner\u2019s 80% bin is right about 80% of the time — over-confident bins mean stated confidence cannot be trusted for triage ordering.',},};export type GlossaryKey = keyof typeof GLOSSARY;
78 unmodified lines79808182838478 unmodified linesdataFlow:'Feature vectors come from evaluated labels. Flagged candidates flow into Triage (ANOMALY reason) and the Human Review queue; confirmed rare events are prioritized into Training datasets — the flywheel\u2019s scarcest fuel.',},quality: {subtitle:'GT-free structural validation: geometry, sensor-consistency and plausibility checks that run on every label — no reference truth required.',78 unmodified lines79808182838485868788899091929394959678 unmodified linesdataFlow:'Feature vectors come from evaluated labels. Flagged candidates flow into Triage (ANOMALY reason) and the Human Review queue; confirmed rare events are prioritized into Training datasets — the flywheel\u2019s scarcest fuel.',},raremine: {subtitle:'Multimodal miner for costumed pedestrians (mascots, inflatables, character suits…) whose distorted silhouettes expose perception weaknesses — proposals, never verdicts.',purpose:'Costumed pedestrians are the canonical hard rare event: a person whose silhouette no longer looks human. This page runs a deterministic rule-based proposer over a synthetic multimodal scene bank, consolidates multi-frame tracks, removes near-duplicates, and routes candidates through automated + human validation into governed dataset destinations. The separation is strict: the miner proposes, validation measures, humans confirm, statistics judge the miner, and training usage is a governed decision.',reading:'Each candidate card shows THREE separate confidences (human present / costume present / rare event) — never one collapsed score — plus modality-tagged evidence (the miner cannot cite sensors the scene lacks), alternative hypotheses it kept alive (statue? mannequin? decoration?), and observed model behavior kept strictly apart from the miner\u2019s predicted failure. The track view collapses a 20-frame walk into one event with representative frames. Coverage & curator quality measures the miner itself against the planted truth: precision, recall, calibration, yield and model-value.',actions:'Generate a scene bank (n, seed), run the miner, filter and review candidates (approve into a dataset destination or reject with a note), inspect lineage and training/eval eligibility, record a governance override to release a protected eval example for training, and re-mine with the improvement report\u2019s suggested config.',dataFlow:'Scene banks are synthetic and deterministic (planted rare events + confounders give exact ground truth). Approved candidates land in rare-event / hard-example / protected evaluation sets with full lineage; the leakage guard forces training_eligible=false for protected eval sets unless an explicit, audited override exists. Curator metrics feed the next mining run\u2019s configuration.',},quality: {subtitle:'GT-free structural validation: geometry, sensor-consistency and plausibility checks that run on every label — no reference truth required.',
16 unmodified lines17181920212213 unmodified lines36373839404116 unmodified lines| 'audit'| 'pipeline'| 'rca'| 'ssam'| 'legacy';13 unmodified lines'audit','pipeline','rca','ssam','legacy',];16 unmodified lines1718192021222313 unmodified lines3738394041424316 unmodified lines| 'audit'| 'pipeline'| 'rca'| 'raremine'| 'ssam'| 'legacy';13 unmodified lines'audit','pipeline','rca','raremine','ssam','legacy',];
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243/** * Rare-Event Miner: multimodal mining + perception QA for costumed * pedestrians. Four views: mining run panel, candidate review queue, * track view, and coverage & curator-quality statistics. */import { useCallback, useEffect, useState } from 'react';import Box from '@mui/material/Box';import Button from '@mui/material/Button';import CircularProgress from '@mui/material/CircularProgress';import MenuItem from '@mui/material/MenuItem';import Tab from '@mui/material/Tab';import Tabs from '@mui/material/Tabs';import TextField from '@mui/material/TextField';import Typography from '@mui/material/Typography';import { Pickaxe, RefreshCcw } from 'lucide-react';import type { StatusResponse, TrackCandidateSummary, TrackView } from '../../types/raremine';import { generateScenes, getImprovementReport, getStatus, getTracks, listCandidates, runMining,} from '../../services/raremine';import CandidateCard from '../../components/raremine/CandidateCard';import CoverageQualityTab from '../../components/raremine/CoverageQualityTab';import TrackStrip from '../../components/raremine/TrackStrip';import { Explainer, StatChip, PriorityChip } from '../../components/raremine/shared';
const PRIORITIES = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW'];const COSTUMES = ['mascot', 'inflatable', 'animal', 'character', 'robot_armor', 'oversized', 'large_prop'];const DIFFICULTIES = ['EXTREME', 'HARD', 'MODERATE', 'EASY'];
export default function RareMinePage() { const [tab, setTab] = useState(0); const [status, setStatus] = useState<StatusResponse | null>(null); const [candidates, setCandidates] = useState<TrackCandidateSummary[]>([]); const [tracks, setTracks] = useState<TrackView[]>([]); const [nScenes, setNScenes] = useState(60); const [seed, setSeed] = useState(7); const [busy, setBusy] = useState<string | null>(null); const [error, setError] = useState<string | null>(null); const [refreshKey, setRefreshKey] = useState(0); const [fPriority, setFPriority] = useState(''); const [fCostume, setFCostume] = useState(''); const [fDifficulty, setFDifficulty] = useState('');
const refresh = useCallback(() => { getStatus().then(setStatus).catch(() => setStatus(null)); listCandidates({ priority: fPriority || undefined, costume: fCostume || undefined, difficulty: fDifficulty || undefined, }) .then((r) => setCandidates(r.candidates)) .catch(() => setCandidates([])); getTracks() .then((r) => setTracks(r.tracks)) .catch(() => setTracks([])); setRefreshKey((k) => k + 1); }, [fPriority, fCostume, fDifficulty]);
useEffect(() => { refresh(); }, [refresh]);
const run = async (label: string, fn: () => Promise<unknown>) => { setBusy(label); setError(null); try { await fn(); refresh(); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setBusy(null); } };
const mineAll = () => run('mine', async () => { await generateScenes(nScenes, seed); await runMining(); });
const remineImproved = () => run('remine', async () => { const imp = await getImprovementReport(); await runMining(12, imp.next_run_config as Record<string, unknown>); });
const hist = status?.priority_histogram ?? {};
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}> {/* ---- mining run panel */} <Box sx={{ p: 1.5, bgcolor: '#141a20', border: '1px solid #232a31', borderRadius: 1 }}> <Box sx={{ display: 'flex', gap: 1.5, alignItems: 'center', flexWrap: 'wrap' }}> <TextField size="small" label="scenes (n)" type="number" value={nScenes} onChange={(e) => setNScenes(Number(e.target.value) || 60)} sx={{ width: 110 }} /> <TextField size="small" label="seed" type="number" value={seed} onChange={(e) => setSeed(Number(e.target.value) || 7)} sx={{ width: 90 }} /> <Button variant="contained" size="small" disabled={busy !== null} startIcon={busy === 'mine' ? <CircularProgress size={14} /> : <Pickaxe size={15} />} onClick={mineAll} > Generate bank + run miner </Button> <Button variant="outlined" size="small" disabled={busy !== null || !status?.last_run} startIcon={busy === 'remine' ? <CircularProgress size={14} /> : <RefreshCcw size={14} />} onClick={remineImproved} > Re-mine with improvements </Button> {error ? ( <Typography variant="caption" sx={{ color: '#ff8a80' }}> {error} </Typography> ) : null} </Box> {status?.bank ? ( <Box sx={{ display: 'flex', gap: 0.75, flexWrap: 'wrap', mt: 1.25, alignItems: 'center' }}> <StatChip value={status.bank.num_scenes} label="scenes" /> <StatChip value={status.bank.num_sequences} label="sequences" /> <StatChip value={status.last_run?.num_frame_candidates ?? 0} label="frame proposals" /> <StatChip value={status.num_detected} label="track candidates" /> <StatChip value={status.dedup_report?.dedup_savings ?? 0} label="duplicates removed" color="#66bb6a" /> <StatChip value={status.last_run?.num_diversity_selected ?? 0} label="diversity-selected" /> <Box sx={{ display: 'flex', gap: 0.5, alignItems: 'center', ml: 1 }}> {PRIORITIES.map((p) => hist[p] ? ( <Box key={p} sx={{ display: 'flex', alignItems: 'center', gap: 0.25 }}> <PriorityChip value={p} /> <Typography variant="caption" sx={{ color: '#c3ccd5', fontWeight: 700 }}> {hist[p]} </Typography> </Box> ) : null )} </Box> </Box> ) : ( <Typography variant="caption" sx={{ color: '#5c6a76', display: 'block', mt: 1 }}> No scene bank yet — generate one to start mining. </Typography> )} </Box>
<Tabs value={tab} onChange={(_, v) => setTab(v)} sx={{ borderBottom: '1px solid #232a31', minHeight: 38 }}> <Tab label={`Review queue (${candidates.length})`} sx={{ minHeight: 38, textTransform: 'none' }} /> <Tab label={`Tracks (${tracks.length})`} sx={{ minHeight: 38, textTransform: 'none' }} /> <Tab label="Coverage & curator quality" sx={{ minHeight: 38, textTransform: 'none' }} /> </Tabs>
{tab === 0 ? ( <Box> <Explainer> Every card is a PROPOSAL from the rule-based miner — not ground truth. The miner only claims what its available sensors support: three separate confidences (a human is present / a costume is present / this is a rare event), modality-tagged evidence, and alternative hypotheses it could not rule out. Automated validation has already measured each proposal against ground truth where available; your approve/reject is the human-validation stage. Approving routes the example to a dataset destination with full lineage — training eligibility stays governed separately. </Explainer> <Box sx={{ display: 'flex', gap: 1, mb: 1.5, flexWrap: 'wrap' }}> <TextField size="small" select label="priority" value={fPriority} onChange={(e) => setFPriority(e.target.value)} sx={{ width: 140 }}> <MenuItem value="">all</MenuItem> {PRIORITIES.map((p) => ( <MenuItem key={p} value={p}> {p} </MenuItem> ))} </TextField> <TextField size="small" select label="costume" value={fCostume} onChange={(e) => setFCostume(e.target.value)} sx={{ width: 150 }}> <MenuItem value="">all</MenuItem> {COSTUMES.map((p) => ( <MenuItem key={p} value={p}> {p} </MenuItem> ))} </TextField> <TextField size="small" select label="difficulty" value={fDifficulty} onChange={(e) => setFDifficulty(e.target.value)} sx={{ width: 140 }}> <MenuItem value="">all</MenuItem> {DIFFICULTIES.map((p) => ( <MenuItem key={p} value={p}> {p} </MenuItem> ))} </TextField> </Box> <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}> {candidates.map((c) => ( <CandidateCard key={c.track_candidate_id} summary={c} onChanged={refresh} /> ))} {!candidates.length ? ( <Typography variant="body2" sx={{ color: '#5c6a76' }}> No candidates match — run mining or clear filters. </Typography> ) : null} </Box> </Box> ) : null}
{tab === 1 ? ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}> <Explainer> Multi-frame sightings of one physical event consolidate into ONE track-level candidate — a 20-frame mascot walk is one rare event, not twenty. Each strip shows per-frame difficulty and marks the representative frames (best evidence, worst case, observed model failure): the minimal set worth curating. </Explainer> {tracks.map((t) => ( <TrackStrip key={t.track_candidate_id} track={t} /> ))} {!tracks.length ? ( <Typography variant="body2" sx={{ color: '#5c6a76' }}> No multi-frame tracks yet — run mining first. </Typography> ) : null} </Box> ) : null}
{tab === 2 ? <CoverageQualityTab refreshKey={refreshKey} /> : null} </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108/** * Typed fetch wrappers for the rare-event miner API (/api/raremine). * Mirrors the style of services/megaeval.ts. */import type { CandidateDetail, CandidatesResponse, CuratorReport, DedupReport, DestinationsResponse, DiversityReport, ImprovementReport, LineageRecord, QuantvalReport, SceneView, StatusResponse, TrackView,} from '../types/raremine';
async function handle<T>(res: Response): Promise<T> { if (!res.ok) { const body = await res.text().catch(() => ''); throw new Error(`API ${res.status}: ${body || res.statusText}`); } return res.json() as Promise<T>;}
const JSON_HEADERS = { 'Content-Type': 'application/json' };
function get<T>(url: string): Promise<T> { return fetch(url).then((res) => handle<T>(res));}
function post<T>(url: string, body?: unknown): Promise<T> { return fetch(url, { method: 'POST', headers: JSON_HEADERS, body: body === undefined ? undefined : JSON.stringify(body), }).then((res) => handle<T>(res));}
export const getStatus = () => get<StatusResponse>('/api/raremine/status');
export const generateScenes = (n: number, seed: number) => post<{ status: string; bank: StatusResponse['bank'] }>('/api/raremine/scenes/generate', { n, seed });
export const runMining = (diversityBudget = 12, config: Record<string, unknown> = {}) => post<{ status: string; run: StatusResponse['last_run']; dedup_report: DedupReport; diversity_report: DiversityReport }>( '/api/raremine/mine', { diversity_budget: diversityBudget, config } );
export const listCandidates = (filters: { priority?: string; status?: string; costume?: string; difficulty?: string; detected_only?: boolean;} = {}) => { const params = new URLSearchParams(); for (const [k, v] of Object.entries(filters)) { if (v !== undefined && v !== '') params.set(k, String(v)); } const qs = params.toString(); return get<CandidatesResponse>(`/api/raremine/candidates${qs ? `?${qs}` : ''}`);};
export const getCandidate = (id: string) => get<CandidateDetail>(`/api/raremine/candidates/${encodeURIComponent(id)}`);
export const getCandidateScene = (id: string, sceneId?: string) => get<SceneView>( `/api/raremine/candidates/${encodeURIComponent(id)}/scene${sceneId ? `?scene_id=${encodeURIComponent(sceneId)}` : ''}` );
export const getTracks = () => get<{ count: number; tracks: TrackView[] }>('/api/raremine/tracks');
export const reviewCandidate = (id: string, action: 'approve' | 'reject', note: string, destination?: string) => post<CandidateDetail & { lineage: LineageRecord | null }>(`/api/raremine/review/${encodeURIComponent(id)}`, { action, note, destination: destination ?? null, });
export const promoteToTraining = (trackCandidateId: string, curator = 'ui-curator') => post<{ status: string; lineage: LineageRecord }>('/api/raremine/governance/promote-training', { track_candidate_id: trackCandidateId, curator, });
export const governanceOverride = (trackCandidateId: string, actor: string, reason: string) => post<{ status: string; lineage: LineageRecord }>('/api/raremine/governance/override', { track_candidate_id: trackCandidateId, actor, reason, });
export const getDestinations = () => get<DestinationsResponse>('/api/raremine/destinations');export const getDedupReport = () => get<DedupReport>('/api/raremine/dedup/report');export const getDiversityReport = () => get<DiversityReport>('/api/raremine/diversity/report');export const getQuantvalReport = () => get<QuantvalReport>('/api/raremine/reports/quantval');export const getCuratorReport = () => get<CuratorReport>('/api/raremine/reports/curator');export const getImprovementReport = () => get<ImprovementReport>('/api/raremine/reports/improvement');
export const explainCandidate = (id: string) => post<{ status: string; provider: string; analysis: string }>( `/api/raremine/candidates/${encodeURIComponent(id)}/explain` );123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268/** Types for the rare-event miner API (/api/raremine). */
export type Priority = 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';export type Difficulty = 'EASY' | 'MODERATE' | 'HARD' | 'EXTREME';export type EvidenceQuality = 'LOW' | 'MEDIUM' | 'HIGH';
export interface Evidence { modality: string; description: string;}
export interface AlternativeHypothesis { hypothesis: string; confidence: number; status: 'RETAINED' | 'REJECTED'; reason: string;}
export interface TemporalValidation { available: boolean; status: 'VALIDATED' | 'NOT_AVAILABLE' | 'INCONCLUSIVE'; evidence: string[];}
export interface ObservedModelBehavior { failure_observed: boolean; failure_modes: string[]; details: string[];}
export interface Candidate { candidate_id: string; scene_id: string; sequence_id: string; object_id: string; track_id: string; frame_index: number; edge_case_detected: boolean; insufficient_visual_evidence: boolean; event_type: string; costume_type: string[]; confidence_human_identity: number; confidence_costume: number; confidence_rare_event: number; visual_evidence: Evidence[]; human_identity_evidence: Evidence[]; alternative_hypotheses: AlternativeHypothesis[]; silhouette_deviation: string; occlusion_level: string; occlusion_source: string; visible_human_features: string[]; occluded_human_features: string[]; unusual_geometry: string[]; temporal_validation: TemporalValidation; location: { context?: string; distance_m?: number; position?: number[]; lighting?: string; weather?: string }; perception_difficulty: Difficulty; difficulty_evidence: string[]; observed_model_behavior: ObservedModelBehavior | null; predicted_failure_mode: string | null; curation_priority: Priority; priority_reason: string; recommended_dataset_destination: string; requires_human_validation: boolean; human_validation_reason: string; evidence_quality: EvidenceQuality; rank_in_scene: number;}
export interface RepresentativeFrames { best_evidence: string | null; worst_case: string | null; model_failure: string | null; minimal_set: string[];}
export interface LineageRecord { lineage_id: string; track_candidate_id: string; source_frame_id: string; source_sequence_id: string; dataset_version: string; curation_timestamp: string; curator: string; validation_status: string; training_eligible: boolean; evaluation_eligible: boolean; protected_evaluation: boolean; destination: string; governance_overrides: { actor: string; reason: string; timestamp: string }[];}
export interface TrackCandidateSummary { track_candidate_id: string; sequence_id: string; track_id: string; frame_count: number; duration_frames: number; stage: string; destination: string; diversity_selected: boolean; duplicate_of: string | null; max_difficulty: Difficulty; max_visibility: EvidenceQuality; representative_frames: RepresentativeFrames; auto_validation: { status: string; detail?: string } | null; human_validation: { action: string; note: string; reviewer: string } | null; candidate: Candidate;}
export interface TrackFrame { candidate_id: string; scene_id: string; frame_index: number; edge_case_detected: boolean; confidence_rare_event: number; evidence_quality: EvidenceQuality; perception_difficulty: Difficulty; failure_observed: boolean;}
export interface TrackView extends TrackCandidateSummary { frames: TrackFrame[];}
export interface SceneObjectView { object_id: string; is_candidate: boolean; position: number[]; distance_m: number; bbox_2d: number[]; context: string; gt?: { class_name: string; is_costumed: boolean; costume_type: string | null } | null;}
export interface SceneView { scene_id: string; sequence_id: string; frame_index: number; lighting: string; weather: string; modalities: Record<string, boolean>; objects: SceneObjectView[]; baseline_predictions: | { prediction_id: string; object_id: string | null; predicted_class: string; confidence: number }[] | null;}
export interface BankInfo { bank_id: string; seed: number; num_scenes: number; num_sequences: number; num_planted_rare: number; num_confounders: number;}
export interface MiningRunInfo { run_id: string; bank_id: string; num_frame_candidates: number; num_track_candidates: number; num_duplicates: number; num_diversity_selected: number;}
export interface DedupReport { groups: number; kept: number; duplicates_archived: number; dedup_savings: number; signatures: { signature: Record<string, string>; members: number; kept: string }[];}
export interface DiversityReport { budget: number; pool_size: number; selected_ids: string[]; coverage_selected: number; coverage_naive_topk: number; coverage_matrix: Record<string, Record<string, number>>; note: string;}
export interface StatusResponse { bank: BankInfo | null; last_run: MiningRunInfo | null; num_track_candidates: number; num_detected: number; priority_histogram: Record<string, number>; dedup_report: DedupReport | null; diversity_report: DiversityReport | null;}
export interface CandidatesResponse { count: number; candidates: TrackCandidateSummary[];}
export interface CandidateDetail extends TrackCandidateSummary { frame_candidates: Candidate[]; lineage: LineageRecord | null;}
export interface CalibrationBin { bin: string; n: number; true: number; observed_rate: number | null;}
export interface CuratorReport { confusion: { tp: number; fp: number; fn: number; tn: number }; planted_positives: number; mining_precision: number | null; mining_recall: number | null; false_discovery_rate: number | null; calibration: CalibrationBin[]; curation_yield: { reviewed: number; approved: number; yield: number | null }; model_value: { curated: number; expose_model_failure: number; fraction: number | null };}
export interface QuantvalReport { candidates_evaluated: number; with_model_outputs: number; agreement_matrix: Record<string, Record<string, number>>; within_one_level_agreement: number | null; rows: { track_candidate_id: string; costume_type: string[]; predicted_difficulty: Difficulty; observed: { frames_with_predictions: number; mean_baseline_confidence: number; mean_iou: number | null; miss_rate: number; class_confusion: Record<string, number>; track_stability: number; observed_difficulty: Difficulty; exposes_model_failure: boolean; } | null; }[]; note: string;}
export interface ImprovementReport { recurring_misses: { total: number; by_costume_type: Record<string, number>; by_occlusion: Record<string, number>; by_context: Record<string, number>; examples: Record<string, unknown>[]; }; over_fires: { total: number; by_confounder_type: Record<string, number>; examples: Record<string, unknown>[]; }; next_run_config: { sensitivity_boost: Record<string, number>; rare_event_threshold?: number }; note: string;}
export interface DestinationsResponse { destinations: Record< string, { track_candidate_id: string; stage: string; priority: Priority; costume_type: string[]; lineage: LineageRecord | null }[] >; counts: Record<string, number>;}app_backend.py+4
sensorflow/raremine/__init__.pyAdded+9
sensorflow/raremine/api.pyAdded+410
sensorflow/raremine/curator_metrics.pyAdded+185
sensorflow/raremine/dedup.pyAdded+176
sensorflow/raremine/lineage.pyAdded+134
sensorflow/raremine/miner.pyAdded+591
sensorflow/raremine/models.pyAdded+461
sensorflow/raremine/pipeline.pyAdded+189
sensorflow/raremine/quantval.pyAdded+119
sensorflow/raremine/scenes.pyAdded+500
sensorflow/raremine/tracks.pyAdded+102
src/App.tsx+5
src/components/help/HelpMenu.tsx+2
src/components/raremine/CandidateCard.tsxAdded+411
src/components/raremine/ConfidenceGauges.tsxAdded+65
src/components/raremine/CoverageQualityTab.tsxAdded+271
src/components/raremine/SceneCanvas.tsxAdded+94
src/components/raremine/TrackStrip.tsxAdded+93
src/components/raremine/shared.tsxAdded+96
src/content/glossary.ts+21
src/content/pageHelp.ts+12
src/context/LabelEvalContext.tsx+2
src/pages/raremine/RareMinePage.tsxAdded+243
src/services/raremine.tsAdded+108
src/types/raremine.tsAdded+268