Spaces:
Paused
Paused
Deploy Sensorflow Studio from master (PR #12 pipeline frame browser)
Browse filesFiles changed (18)
- app_backend.py+216-760
- infer.py+1-1
- sensorflow/adapters/a2d2_adapter.py+40-2
- sensorflow/adapters/alpamayo_adapter.py+41-6
- sensorflow/adapters/stub_images.pyAdded+83
- sensorflow/adapters/vendor_media.pyAdded+103
- sensorflow/adapters/waymo_adapter.py+44-6
- sensorflow/dataset_load_service.pyAdded+246
- sensorflow/help/knowledge.py+3-47
- sensorflow/help/matcher.py-8
- sensorflow/pipeline_artifacts.py+38-21
- src/components/help/HelpChatbot.tsx+4-3
- static/app.js+173-540
- static/index.html+68-95
- static/style.css-205
- tests/test_help/test_matcher.py-16
- tests/test_pipeline/test_api_pipeline.py+11-1
- tests/test_pipeline/test_pipeline_browse.py+99
4 unmodified lines56789101112131415161718192021222324252627286 unmodified lines35363738394041424364 unmodified lines1081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423431 unmodified line3453463473483493503513523533543553563573583593603612 unmodified lines3643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424431 unmodified line4454464474484494504514524534544554564574584594604614624634644654666 unmodified lines4734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087094 unmodified lines714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859477 unmodified lines1337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385427 unmodified lines181318141815181618171818181918201821182216 unmodified lines18391840184118421843184418451846184718485 unmodified lines18541855185618571858185918608 unmodified lines1869187018711872187318743 unmodified lines18781879188018811882188316 unmodified lines19001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819394 unmodified lines194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420354 unmodified linesimport subprocessimport signalfrom pathlib import Pathfrom typing import List, Optional, Any, Dictfrom pydantic import BaseModelimport httpxfrom fastapi import FastAPI, HTTPException, Queryfrom fastapi.staticfiles import StaticFilesfrom fastapi.responses import FileResponse, PlainTextResponseapp = FastAPI(title="Sensorflow Studio Backend")# State trackingACTIVE_TRAIN_PROC: Optional[subprocess.Popen] = NoneACTIVE_TRAIN_EXECUTION_ID: Optional[str] = NoneTRAINING_LOGS_ACCUMULATED = ""TRAINING_LOSSES: List[float] = []TOTAL_EPOCHS = 10CURRENT_EPOCH = 0LAST_TRAIN_EXIT_CODE: Optional[int] = NoneLAST_TRAIN_COMMAND: Optional[List[str]] = None# ConfigurationCONFIG_PATH = Path("runs/studio_config.json")6 unmodified linesmodel_type: str = "yolov8"pipeline_mode: str = "3d"sam_checkpoint: str = "models/sam_vit_b.pth"vendors: List[str] = ["alpamayo", "waymo", "a2d2"]gate_thresholds_path: str = "runs/pipeline/gate_thresholds.json"sequence_id: str = "seq_001"class TrainParams(BaseModel):model: str = "yolov8n.pt"64 unmodified lines@app.get("/api/precheck")def precheck():"""Script verification — existence alone is NOT success."""from sensorflow.execution_ops import verify_scriptreports = {"train.py": verify_script("train.py"),"infer.py": verify_script("infer.py"),"autograder.py": verify_script("autograder.py"),}all_ok = all(r.get("exists") and r.get("syntax_valid") and r.get("dry_run_ok")for r in reports.values())any_missing = any(not r.get("exists") for r in reports.values())return {"status": "ok" if all_ok else ("warning" if not any_missing else "failed"),"message": ("Scripts exist, syntax-valid, and --help dry-run succeeded."if all_okelse "Script verification incomplete — see reports (file Found alone is not enough)."),"scripts": reports,"verified": all_ok,}@app.get("/api/health")def health():from sensorflow.execution_ops import backend_healthfrom sensorflow.execution_ledger import get_strict_modepayload = backend_health()payload["strict_mode"] = get_strict_mode()payload["backend_connected"] = Truereturn payload@app.get("/api/strict-mode")def get_strict_mode_api():from sensorflow.execution_ledger import get_strict_modereturn {"enabled": get_strict_mode()}@app.post("/api/strict-mode")def set_strict_mode_api(params: dict):from sensorflow.execution_ledger import set_strict_modeenabled = bool(params.get("enabled", False))return set_strict_mode(enabled)@app.get("/api/executions")def list_executions_api(operation: Optional[str] = None,status: Optional[str] = None,limit: int = Query(50, ge=1, le=500),):from sensorflow.execution_ledger import list_executionsreturn {"status": "ok", "executions": list_executions(operation=operation, status=status, limit=limit)}@app.get("/api/executions/{execution_id}")def get_execution_api(execution_id: str):from sensorflow.execution_ledger import load_executiontry:return load_execution(execution_id)except FileNotFoundError:raise HTTPException(status_code=404, detail=f"Execution not found: {execution_id}")@app.get("/api/executions/{execution_id}/log")def get_execution_log_api(execution_id: str):from sensorflow.execution_ledger import get_log_text, load_executiontry:load_execution(execution_id)except FileNotFoundError:raise HTTPException(status_code=404, detail=f"Execution not found: {execution_id}")return PlainTextResponse(get_log_text(execution_id) or "(no log lines)")@app.post("/api/yaml/validate")def validate_yaml_api(params: dict):from sensorflow.execution_ops import validate_yaml_semanticsfrom sensorflow.execution_ledger import create_execution, mark_running, finalizepath = params.get("path") or params.get("yaml_path") or "coco8.yaml"record = create_execution("yaml_validate",configuration_snapshot={"yaml_path": path},input_artifacts=[path],)mark_running(record["execution_id"])report = validate_yaml_semantics(path)final = finalize(record["execution_id"],report.get("status") or "FAILED",metrics={"class_count": report.get("class_count"),"image_counts": report.get("image_counts"),"label_counts": report.get("label_counts"),},errors=report.get("errors"),warnings=report.get("warnings"),output_artifacts=[{"path": path, "hash": report.get("content_hash")}],process_invoked=False,outputs_valid=report.get("status") == "SUCCEEDED",)report["execution_id"] = final["execution_id"]report["execution"] = {"execution_id": final["execution_id"],"status": final["status"],"verified": final.get("verified"),"duration_ms": final.get("duration_ms"),}return report@app.get("/api/scripts/verify")def scripts_verify_api():from sensorflow.execution_ops import verify_scriptreturn {"status": "ok","scripts": {"train.py": verify_script("train.py"),"infer.py": verify_script("infer.py"),"autograder.py": verify_script("autograder.py"),},}@app.post("/api/dataset/load")def dataset_load(params: dict):"""Real Load & Preprocess with discovery evidence (not catalog KPIs)."""from sensorflow.execution_ops import load_and_preprocessfrom sensorflow.execution_ledger import create_execution, mark_running, finalizesource_path = params.get("source_path") or load_config().source_pathyaml_path = params.get("yaml_path") or load_config().yaml_pathdataset_type = params.get("dataset_type") or load_config().dataset_typerecord = create_execution("dataset_load",configuration_snapshot={"source_path": source_path,"yaml_path": yaml_path,"dataset_type": dataset_type,},input_artifacts=[source_path, yaml_path],)mark_running(record["execution_id"])result = load_and_preprocess(source_path, yaml_path=yaml_path, dataset_type=dataset_type)disc = result["discovery"]final = finalize(record["execution_id"],result["status"],records_discovered=disc.get("images_discovered", 0),records_processed=disc.get("images_discovered", 0),records_succeeded=disc.get("images_readable", 0),records_failed=disc.get("images_corrupt", 0),metrics=result["metrics"],errors=disc.get("errors"),warnings=disc.get("warnings"),output_artifacts=[{"path": result["manifest_path"], "kind": "load_manifest"}],process_invoked=False,outputs_valid=disc.get("images_readable", 0) > 0 and result["status"] in ("SUCCEEDED","PARTIAL_SUCCESS",),)return {"status": final["status"],"execution_id": final["execution_id"],"verified": final.get("verified"),"duration_ms": final.get("duration_ms"),"message": (f"Loaded {disc.get('images_readable', 0)}/{disc.get('images_discovered', 0)} images "f"from {source_path}"if disc.get("images_readable")else f"FAILED: 0 images loaded from {source_path}"),"discovery": disc,"metrics": result["metrics"],"yaml_validation": result.get("yaml_validation"),"reconciliation": result.get("reconciliation"),"manifest_path": result.get("manifest_path"),"catalog_only": False,"browsable": bool(result["metrics"].get("browsable")),"events": final.get("events"),}@app.post("/api/train/start")def start_train(params: TrainParams):global ACTIVE_TRAIN_PROC, ACTIVE_TRAIN_EXECUTION_ID, TRAINING_LOGS_ACCUMULATEDglobal TRAINING_LOSSES, TOTAL_EPOCHS, CURRENT_EPOCH, LAST_TRAIN_EXIT_CODE, LAST_TRAIN_COMMANDfrom sensorflow.execution_ledger import create_execution, mark_running, finalizeif ACTIVE_TRAIN_PROC and ACTIVE_TRAIN_PROC.poll() is None:raise HTTPException(status_code=400, detail="Training is already running.")weights_path = Path(params.model)# Allow ultralytics named weights (e.g. yolov8n.pt) that may download; still record pathyaml_path = Path(params.data)if not yaml_path.exists():record = create_execution("training",configuration_snapshot=params.dict(),input_artifacts=[params.data, params.model],)finalize(record["execution_id"],"FAILED",errors=[f"Dataset YAML not found: {params.data}"],process_invoked=False,outputs_valid=False,)raise HTTPException(status_code=400,detail={"message": f"Dataset YAML not found: {params.data}", "execution_id": record["execution_id"]},)TRAINING_LOGS_ACCUMULATED = f"Starting YOLO training with base model {params.model}...\n"TRAINING_LOSSES = []TOTAL_EPOCHS = params.epochsCURRENT_EPOCH = 0LAST_TRAIN_EXIT_CODE = Nonecmd = [sys.executable, "train.py",1 unmodified line"--batch", str(params.batch),"--device", params.device,"--model", params.model,"--data", params.data,]LAST_TRAIN_COMMAND = cmdrecord = create_execution("training",configuration_snapshot=params.dict(),input_artifacts=[params.data, params.model],command=cmd,)ACTIVE_TRAIN_EXECUTION_ID = record["execution_id"]try:ACTIVE_TRAIN_PROC = subprocess.Popen(2 unmodified linesstderr=subprocess.STDOUT,text=True,bufsize=1,preexec_fn=os.setsid if os.name != "nt" else None,)except Exception as e:finalize(record["execution_id"],"FAILED",errors=[f"Failed to spawn training process: {e}"],process_invoked=False,outputs_valid=False,)ACTIVE_TRAIN_EXECUTION_ID = Noneraise HTTPException(status_code=500, detail=f"Failed to spawn training process: {str(e)}")mark_running(record["execution_id"], process_id=ACTIVE_TRAIN_PROC.pid)return {"status": "started","execution_id": record["execution_id"],"process_id": ACTIVE_TRAIN_PROC.pid,"command": cmd,}@app.post("/api/train/stop")def stop_train():global ACTIVE_TRAIN_PROC, ACTIVE_TRAIN_EXECUTION_ID, LAST_TRAIN_EXIT_CODEfrom sensorflow.execution_ledger import finalize, append_logif not ACTIVE_TRAIN_PROC or ACTIVE_TRAIN_PROC.poll() is not None:return {"status": "not_running", "execution_id": ACTIVE_TRAIN_EXECUTION_ID}exec_id = ACTIVE_TRAIN_EXECUTION_IDtry:if os.name != "nt":os.killpg(os.getpgid(ACTIVE_TRAIN_PROC.pid), signal.SIGTERM)else:ACTIVE_TRAIN_PROC.terminate()ACTIVE_TRAIN_PROC.wait(timeout=3)except Exception:try:ACTIVE_TRAIN_PROC.kill()except Exception:passLAST_TRAIN_EXIT_CODE = ACTIVE_TRAIN_PROC.poll()if exec_id:append_log(exec_id, "Training terminated by user")finalize(exec_id,"CANCELLED",exit_code=LAST_TRAIN_EXIT_CODE,process_invoked=True,outputs_valid=False,errors=["Cancelled by user"],)ACTIVE_TRAIN_PROC = Nonereturn {"status": "stopped", "execution_id": exec_id, "exit_code": LAST_TRAIN_EXIT_CODE}@app.get("/api/train/status")def get_train_status():global ACTIVE_TRAIN_PROC, ACTIVE_TRAIN_EXECUTION_ID, TRAINING_LOGS_ACCUMULATEDglobal TRAINING_LOSSES, CURRENT_EPOCH, TOTAL_EPOCHS, LAST_TRAIN_EXIT_CODE, LAST_TRAIN_COMMANDfrom sensorflow.execution_ledger import append_log, finalize, sha256_filefrom sensorflow.execution_ops import artifact_inforunning = Falsejust_finished = Falseexit_code = LAST_TRAIN_EXIT_CODEif ACTIVE_TRAIN_PROC:import selectif ACTIVE_TRAIN_PROC.poll() is None:running = Truewhile True:r, _, _ = select.select([ACTIVE_TRAIN_PROC.stdout], [], [], 0.02)if ACTIVE_TRAIN_PROC.stdout in r:1 unmodified lineif not line:breakTRAINING_LOGS_ACCUMULATED += lineif ACTIVE_TRAIN_EXECUTION_ID:try:append_log(ACTIVE_TRAIN_EXECUTION_ID, line.rstrip())except Exception:passif "epoch" in line.lower() or "/" in line:try:parts = line.split()if len(parts) >= 3 and "/" in parts[0]:ep_part = parts[0].split("/")epoch_num = int(ep_part[0])CURRENT_EPOCH = epoch_numfor p in parts[2:]:try:val = float(p)if 0.0 < val < 10.0:if len(TRAINING_LOSSES) < epoch_num:TRAINING_LOSSES.append(val)else:6 unmodified lineselse:breakelse:remaining = ACTIVE_TRAIN_PROC.stdout.read()if remaining:TRAINING_LOGS_ACCUMULATED += remainingexit_code = ACTIVE_TRAIN_PROC.poll()LAST_TRAIN_EXIT_CODE = exit_codejust_finished = TrueACTIVE_TRAIN_PROC = Noneprogress = 0.0if TOTAL_EPOCHS > 0 and CURRENT_EPOCH > 0:progress = min(1.0, float(CURRENT_EPOCH) / float(TOTAL_EPOCHS))elif not running and exit_code == 0 and CURRENT_EPOCH > 0:progress = 1.0# Never invent progress=1.0 on failure or empty parsecheckpoint = Path("runs/detect/coco_finetuned/weights/best.pt")ckpt_info = artifact_info(checkpoint) if checkpoint.exists() else {"path": str(checkpoint), "exists": False}if just_finished and ACTIVE_TRAIN_EXECUTION_ID:status = "SUCCEEDED" if exit_code == 0 else "FAILED"if exit_code is None:status = "FAILED"finalize(ACTIVE_TRAIN_EXECUTION_ID,status,exit_code=exit_code,metrics={"epochs_requested": TOTAL_EPOCHS,"epochs_observed": CURRENT_EPOCH,"losses_parsed": len(TRAINING_LOSSES),"losses": TRAINING_LOSSES,"checkpoint": ckpt_info,},output_artifacts=[ckpt_info] if ckpt_info.get("exists") else [],process_invoked=True,outputs_valid=bool(ckpt_info.get("exists")) and exit_code == 0,errors=[] if exit_code == 0 else [f"Training exit_code={exit_code}"],)return {"running": running,"progress": progress,"logs": TRAINING_LOGS_ACCUMULATED[-20000:],"losses": TRAINING_LOSSES, # only real parsed losses — never fabricated"losses_fabricated": False,"exit_code": exit_code,"process_id": None if not running else (ACTIVE_TRAIN_PROC.pid if ACTIVE_TRAIN_PROC else None),"command": LAST_TRAIN_COMMAND,"execution_id": ACTIVE_TRAIN_EXECUTION_ID,"epochs_observed": CURRENT_EPOCH,"epochs_requested": TOTAL_EPOCHS,"checkpoint": ckpt_info,"status": ("RUNNING" if running else ("SUCCEEDED" if exit_code == 0 else ("FAILED" if exit_code not in (None, 0) else "NOT_EXECUTED"))),}@app.post("/api/infer/run")def run_infer(params: InferParams):from sensorflow.execution_ledger import create_execution, mark_running, finalize, append_logfrom sensorflow.execution_ops import discover_images, artifact_infoweights = Path(params.weights)source = Path(params.source)out_dir = Path("runs/infer")record = create_execution("inference",configuration_snapshot=params.dict(),input_artifacts=[params.source, params.weights],command=[sys.executable, "infer.py","--source", params.source,"--weights", params.weights,"--conf", str(params.conf),"--iou", str(params.iou),"--output", "runs/infer",],)if not weights.exists() and not str(params.weights).endswith(".pt"):finalize(record["execution_id"],"FAILED",errors=[f"Model checkpoint not found: {params.weights}"],process_invoked=False,outputs_valid=False,)raise HTTPException(status_code=400,detail={"message": f"Model checkpoint not found: {params.weights}", "execution_id": record["execution_id"]},)if not weights.exists():# Named ultralytics weight may auto-download; still warn if missing before runpassdiscovery = discover_images(params.source)if discovery["images_discovered"] == 0:finalize(record["execution_id"],"FAILED",records_discovered=0,records_processed=0,records_succeeded=0,records_failed=0,errors=[f"No images found at source: {params.source}"],metrics={"images_discovered": 0},process_invoked=False,outputs_valid=False,)return {"status": "FAILED","execution_id": record["execution_id"],"images": [],"records_discovered": 0,"records_succeeded": 0,"records_failed": 0,"message": f"No images found at source: {params.source}","model": params.weights,"checkpoint": artifact_info(weights),}if not weights.exists():finalize(record["execution_id"],"FAILED",errors=[f"Missing model checkpoint: {params.weights}"],records_discovered=discovery["images_discovered"],process_invoked=False,outputs_valid=False,)raise HTTPException(status_code=400,detail={"message": f"Missing model checkpoint: {params.weights}","execution_id": record["execution_id"],},)cmd = record["command"]mark_running(record["execution_id"])try:res = subprocess.run(cmd, capture_output=True, text=True)except Exception as e:finalize(record["execution_id"],"FAILED",errors=[str(e)],process_invoked=True,outputs_valid=False,)raise HTTPException(status_code=500, detail=f"Inference failed to start: {e}")if res.stdout:append_log(record["execution_id"], res.stdout[-4000:])if res.stderr:append_log(record["execution_id"], res.stderr[-2000:])images = []if out_dir.exists():images = [f.name for f in out_dir.glob("annotated_*") if f.is_file()]preds_path = out_dir / "predictions.json"pred_count = 0if preds_path.exists():try:pred_count = len(json.loads(preds_path.read_text()))except Exception:pred_count = 0succeeded = len(images)failed = max(0, discovery["images_discovered"] - succeeded)if res.returncode != 0:status = "FAILED"elif succeeded == 0:status = "FAILED"elif failed > 0:status = "PARTIAL_SUCCESS"else:status = "SUCCEEDED"final = finalize(record["execution_id"],status,exit_code=res.returncode,records_discovered=discovery["images_discovered"],records_processed=discovery["images_discovered"],records_succeeded=succeeded,records_failed=failed,metrics={"model": params.weights,"checkpoint": artifact_info(weights),"inference_calls": discovery["images_discovered"],"predictions_generated": pred_count,"annotated_images": succeeded,"conf": params.conf,"iou": params.iou,"output_dir": str(out_dir),},output_artifacts=[{"path": str(out_dir), "kind": "infer_dir"},artifact_info(preds_path),],errors=[] if res.returncode == 0 else [res.stderr or res.stdout or "infer non-zero exit"],process_invoked=True,outputs_valid=succeeded > 0 and res.returncode == 0,)return {"status": final["status"],"execution_id": final["execution_id"],"verified": final.get("verified"),"duration_ms": final.get("duration_ms"),"images": sorted(images),"model": params.weights,"checkpoint": artifact_info(weights),"records_discovered": discovery["images_discovered"],"records_processed": discovery["images_discovered"],"records_succeeded": succeeded,"records_failed": failed,"inference_calls": discovery["images_discovered"],"predictions_generated": pred_count,"output_dir": str(out_dir),"exit_code": res.returncode,"process_id": None,"command": cmd,}@app.get("/api/images/{filename}")def serve_image(filename: str):4 unmodified lines@app.get("/api/grade")def grade_predictions():from sensorflow.execution_ledger import create_execution, mark_running, finalizefrom sensorflow.execution_ops import artifact_infopredictions_file = Path("runs/infer/predictions.json")record = create_execution("auto_grader",configuration_snapshot={"predictions": str(predictions_file)},input_artifacts=[str(predictions_file)],command=[sys.executable, "autograder.py", "--predictions", str(predictions_file)],)if not predictions_file.exists():final = finalize(record["execution_id"],"NOT_EXECUTED",errors=["predictions.json missing — run Auto-Labeler Inference first"],process_invoked=False,outputs_valid=False,warnings=["Grader not executed: no predictions artifact"],)return {"status": "NOT_EXECUTED","execution_id": final["execution_id"],"total_predictions": 0,"total_images": 0,"quality_score": None,"metrics": {},"issues": [{"severity": "WARNING","type": "Missing predictions","description": "No predictions.json — grader was NOT executed.","recommendation": "Run Auto-Labeler Inference first.",}],"message": "NOT_EXECUTED: missing predictions artifact",}mark_running(record["execution_id"])cmd = record["command"]try:res = subprocess.run(cmd, capture_output=True, text=True)except Exception as e:finalize(record["execution_id"],"FAILED",errors=[str(e)],process_invoked=True,outputs_valid=False,)raise HTTPException(status_code=500, detail=f"Autograder failed to start: {e}")report_file = Path("runs/infer/quality_report.json")if res.returncode != 0 or not report_file.exists():finalize(record["execution_id"],"FAILED",exit_code=res.returncode,errors=[res.stderr or res.stdout or "grader produced no report"],process_invoked=True,outputs_valid=False,)raise HTTPException(status_code=500,detail={"message": f"Autograder failed: {res.stderr}","execution_id": record["execution_id"],},)with open(report_file, "r") as f:report_data = json.load(f)issues = []for issue_type, count in report_data.get("issue_summary", {}).items():if count > 0:severity = "WARNING" if issue_type in ["low_confidence", "overlapping_different_class"] else "INFO"desc = f"Found {count} occurrences of {issue_type.replace('_', ' ')}."rec = "Retrain model with more samples or tune confidence threshold."if issue_type == "small_detection":rec = "Verify that extremely small bounding boxes are correct."elif issue_type == "class_imbalance":rec = "Balance class frequency in dataset to prevent bias."issues.append({"severity": severity,"type": issue_type.upper().replace("_", " "),"description": desc,"recommendation": rec,})for rec in report_data.get("recommendations", []):issues.append({"severity": "INFO","type": "RECOMMENDATION","description": rec,"recommendation": "Review annotation guidelines.",})metrics = {"total_predictions": report_data.get("total_predictions", 0),"total_images": report_data.get("total_images", 0),"quality_score": report_data.get("quality_score"),"issue_summary": report_data.get("issue_summary", {}),"precision": report_data.get("precision"),"recall": report_data.get("recall"),"f1": report_data.get("f1"),"mAP": report_data.get("mAP"),"tp": report_data.get("tp"),"fp": report_data.get("fp"),"fn": report_data.get("fn"),"per_class": report_data.get("per_class"),}# Strip Nones so UI only shows grader-provided metricsmetrics = {k: v for k, v in metrics.items() if v is not None}final = finalize(record["execution_id"],"SUCCEEDED",exit_code=res.returncode,records_discovered=metrics.get("total_images", 0),records_processed=metrics.get("total_images", 0),records_succeeded=metrics.get("total_images", 0),metrics=metrics,output_artifacts=[artifact_info(report_file), artifact_info(predictions_file)],process_invoked=True,outputs_valid=True,)return {"status": final["status"],"execution_id": final["execution_id"],"verified": final.get("verified"),"duration_ms": final.get("duration_ms"),"total_predictions": metrics.get("total_predictions", 0),"total_images": metrics.get("total_images", 0),"quality_score": metrics.get("quality_score"),"metrics": metrics,"issues": issues,"message": "Grader completed from predictions.json",}@app.post("/api/export")def export_weights(params: ExportParams):477 unmodified lines@app.post("/api/dataset/preprocess")def preprocess_dataset(params: dict):"""Catalog-only path kept for backward compatibility.Prefer POST /api/dataset/load for real discovery evidence.If source_path is provided, delegates to real load."""if params.get("source_path") or params.get("real_load"):return dataset_load(params)dataset_type = params.get("dataset_type", "local")meta = dict(DATASET_METADATA_STORE.get(dataset_type, DATASET_METADATA_STORE["local"]))meta["browsable"] = Falsemeta["catalog_only"] = Truemeta["browse_hint"] = ("Catalog metadata only — NOT disk load. Use Load & Preprocess or ""Validate & Browse Images Path for verifiable counts.")from sensorflow.execution_ledger import create_execution, finalizerecord = create_execution("dataset_catalog_metadata",configuration_snapshot={"dataset_type": dataset_type},status="QUEUED",)finalize(record["execution_id"],"NOT_EXECUTED",warnings=["Catalog metadata echo only — no discovery/decode ran"],metrics={"catalog_only": True, "ingestion_pct_is_catalog": True},process_invoked=False,outputs_valid=False,)return {"status": "NOT_EXECUTED","execution_id": record["execution_id"],"message": (f"Catalog metadata for {meta['name']} — not the same as loading "f"browsable frames. Use Load & Preprocess for real evidence."),"dataset_type": dataset_type,"total_frames": None,"browsable": False,"catalog_only": True,"metadata": meta,}@app.post("/api/dataset/save-pipeline-tools")427 unmodified lines# -----------------------------------------------------------------------class IngestParams(BaseModel):vendors: List[str] = ["alpamayo", "waymo", "a2d2"]sequence_id: str = "seq_001"source_path: Optional[str] = Nonemax_frames: Optional[int] = Noneclass AutoLabelParams(BaseModel):sequence_id: str = "seq_001"16 unmodified linesfrom sensorflow.dataset_fusion_engine import DatasetFusionEngineconfig = load_config()source_path = params.source_path if params.source_path is not None else config.source_pathtry:engine = DatasetFusionEngine()sequence = engine.ingest(params.vendors,params.sequence_id,source_path=source_path,max_frames=params.max_frames,5 unmodified linesraise HTTPException(status_code=500, detail=f"Ingest failed: {str(e)}")config.sequence_id = params.sequence_idconfig.vendors = params.vendorsif params.source_path is not None:config.source_path = params.source_pathwith open(CONFIG_PATH, "w") as f:8 unmodified lines"frames": frame_count,"demo_stub": demo_stub,"vendor": sequence.vendor,"source_path": source_path,"message": (f"demo stub: {frame_count} frames"3 unmodified lines}@app.get("/api/dataset/ingest/status")def ingest_status(sequence_id: str = "seq_001"):from sensorflow.dataset_fusion_engine import DatasetFusionEngine16 unmodified linesdef auto_label(params: AutoLabelParams):from sensorflow.perception_automator import PerceptionAutomatorfrom sensorflow.schemas.unified_frame import UnifiedSequencefrom sensorflow.execution_ledger import create_execution, mark_running, finalizefrom sensorflow.execution_ops import artifact_infomanifest = Path("runs/pipeline") / params.sequence_id / "manifest.json"record = create_execution("auto_label_3d",configuration_snapshot=params.dict(),input_artifacts=[str(manifest), params.sam_checkpoint],)if not manifest.exists():finalize(record["execution_id"],"FAILED",errors=["Manifest not found. Run ingest first."],process_invoked=False,outputs_valid=False,)raise HTTPException(status_code=400,detail={"message": "Manifest not found. Run ingest first.", "execution_id": record["execution_id"]},)ckpt = Path(params.sam_checkpoint)sam_ran = Falsemodel_name = "sam_vit_b" if not params.no_sam else "none (no_sam)"if params.no_sam:warnings = ["no_sam=true — SAM not invoked; proposals may be GT/synthetic fallback"]elif not ckpt.exists():warnings = [f"SAM checkpoint missing: {params.sam_checkpoint} — model will not run"]else:warnings = []mark_running(record["execution_id"])try:sequence = UnifiedSequence.load(manifest)expected_frames = len(sequence.frames)4 unmodified linesuse_sam=not params.no_sam,)automator.run_sequence(sequence, output_dir)sam_ran = bool(getattr(automator, "use_sam", False) and automator._mask_generator is not None)except Exception as e:finalize(record["execution_id"],"FAILED",errors=[str(e)],process_invoked=False,outputs_valid=False,)raise HTTPException(status_code=500,detail={"message": f"Auto-label failed: {str(e)}", "execution_id": record["execution_id"]},)proposals_dir = manifest.parent / "proposals"proposal_files = list(proposals_dir.glob("*.json")) if proposals_dir.exists() else []num_frames = len(proposal_files)pred_count = 0for pf in proposal_files:try:data = json.loads(pf.read_text())if isinstance(data, list):pred_count += len(data)elif isinstance(data, dict):pred_count += len(data.get("proposals") or data.get("objects") or [])except Exception:passdemo_stub = bool(sequence.taxonomy_manifest.get("demo_stub"))if params.no_sam or not sam_ran:status = "NOT_EXECUTED" if num_frames == 0 else "PARTIAL_SUCCESS"if params.no_sam:warnings.append("Model not run (no_sam); do not treat as SAM SUCCESS")elif not sam_ran:warnings.append("SAM unavailable — fallback proposals only")elif num_frames == 0:status = "FAILED"elif num_frames < expected_frames:status = "PARTIAL_SUCCESS"else:status = "SUCCEEDED"final = finalize(record["execution_id"],status,records_discovered=expected_frames,records_processed=num_frames,records_succeeded=num_frames,records_failed=max(0, expected_frames - num_frames),metrics={"model": model_name,"checkpoint": artifact_info(ckpt),"sam_ran": sam_ran,"no_sam": params.no_sam,"frames_expected": expected_frames,"frames_processed": num_frames,"predictions_generated": pred_count,"inference_calls": num_frames if sam_ran else 0,"output_dir": str(proposals_dir),"demo_stub": demo_stub,},output_artifacts=[{"path": str(proposals_dir), "kind": "proposals_dir", "files": num_frames}],warnings=warnings,process_invoked=sam_ran,outputs_valid=num_frames > 0,)return {"status": final["status"],"execution_id": final["execution_id"],"verified": final.get("verified"),"duration_ms": final.get("duration_ms"),"proposals_dir": str(proposals_dir),"frames_processed": num_frames,"frames_expected": expected_frames,"predictions_generated": pred_count,"inference_calls": num_frames if sam_ran else 0,"model": model_name,"checkpoint": artifact_info(ckpt),"sam_ran": sam_ran,"demo_stub": demo_stub,"message": (f"{'NOT_EXECUTED / fallback' if not sam_ran else 'SAM'}: "f"processed {num_frames}/{expected_frames} frames, {pred_count} predictions → {proposals_dir}"),"events": final.get("events"),}4 unmodified lines56789101112131415161718192021222324256 unmodified lines3233343536373839404142434464 unmodified lines1091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401 unmodified line1421431441451461471481492 unmodified lines1521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981 unmodified line2002012022032042052062072082092102112122132142152162172182192202212226 unmodified lines2292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812824 unmodified lines287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362477 unmodified lines840841842843844845846847848849850851852853854855856857858859860861862863864865866867427 unmodified lines12951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131816 unmodified lines1335133613371338133913401341134213431344134513461347134813491350135113521353135413555 unmodified lines13611362136313641365136613678 unmodified lines137613771378137913801381138213833 unmodified lines13871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143716 unmodified lines145414551456145714581459146014611462146314644 unmodified lines146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014914 unmodified linesimport subprocessimport signalfrom pathlib import Pathfrom typing import List, Optionalfrom pydantic import BaseModelimport httpxfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.staticfiles import StaticFilesfrom fastapi.responses import FileResponseapp = FastAPI(title="Sensorflow Studio Backend")# State trackingACTIVE_TRAIN_PROC: Optional[subprocess.Popen] = NoneTRAINING_LOGS_ACCUMULATED = ""TRAINING_LOSSES: List[float] = []TOTAL_EPOCHS = 10CURRENT_EPOCH = 0# ConfigurationCONFIG_PATH = Path("runs/studio_config.json")6 unmodified linesmodel_type: str = "yolov8"pipeline_mode: str = "3d"sam_checkpoint: str = "models/sam_vit_b.pth"vendors: List[str] = ["alpamayo"]gate_thresholds_path: str = "runs/pipeline/gate_thresholds.json"sequence_id: str = "seq_001"waymo_root: Optional[str] = Nonealpamayo_root: Optional[str] = Nonea2d2_root: Optional[str] = Noneallow_stub: bool = Trueclass TrainParams(BaseModel):model: str = "yolov8n.pt"64 unmodified lines@app.get("/api/precheck")def precheck():# Verify scripts are presenttrain_exists = Path("train.py").exists()infer_exists = Path("infer.py").exists()grader_exists = Path("autograder.py").exists()if not (train_exists and infer_exists and grader_exists):return {"status": "warning","message": "Some scripts are missing in the current folder. Please verify train.py, infer.py, and autograder.py exist."}return {"status": "success","message": "All workspace training and inference scripts are verified."}@app.post("/api/train/start")def start_train(params: TrainParams):global ACTIVE_TRAIN_PROC, TRAINING_LOGS_ACCUMULATED, TRAINING_LOSSES, TOTAL_EPOCHS, CURRENT_EPOCHif ACTIVE_TRAIN_PROC and ACTIVE_TRAIN_PROC.poll() is None:raise HTTPException(status_code=400, detail="Training is already running.")# Reset logs & statsTRAINING_LOGS_ACCUMULATED = f"Starting YOLO training with base model {params.model}...\n"TRAINING_LOSSES = []TOTAL_EPOCHS = params.epochsCURRENT_EPOCH = 0cmd = [sys.executable, "train.py",1 unmodified line"--batch", str(params.batch),"--device", params.device,"--model", params.model,"--data", params.data]try:ACTIVE_TRAIN_PROC = subprocess.Popen(2 unmodified linesstderr=subprocess.STDOUT,text=True,bufsize=1,preexec_fn=os.setsid if os.name != 'nt' else None)except Exception as e:raise HTTPException(status_code=500, detail=f"Failed to spawn training process: {str(e)}")return {"status": "started"}@app.post("/api/train/stop")def stop_train():global ACTIVE_TRAIN_PROCif not ACTIVE_TRAIN_PROC or ACTIVE_TRAIN_PROC.poll() is not None:return {"status": "not_running"}try:if os.name != 'nt':os.killpg(os.getpgid(ACTIVE_TRAIN_PROC.pid), signal.SIGTERM)else:ACTIVE_TRAIN_PROC.terminate()ACTIVE_TRAIN_PROC.wait(timeout=3)except Exception as e:# Fallback to simple killtry:ACTIVE_TRAIN_PROC.kill()except Exception:passreturn {"status": "stopped"}@app.get("/api/train/status")def get_train_status():global ACTIVE_TRAIN_PROC, TRAINING_LOGS_ACCUMULATED, TRAINING_LOSSES, CURRENT_EPOCH, TOTAL_EPOCHSrunning = Falseif ACTIVE_TRAIN_PROC:# Read new output line by line (non-blocking)# Use select or set standard output stream non-blocking if needed, or read from stdout.# To avoid blocking, we read line-by-line if there is data.import selectif ACTIVE_TRAIN_PROC.poll() is None:running = True# Read available outputswhile True:r, _, _ = select.select([ACTIVE_TRAIN_PROC.stdout], [], [], 0.02)if ACTIVE_TRAIN_PROC.stdout in r:1 unmodified lineif not line:breakTRAINING_LOGS_ACCUMULATED += line# Parse epoch loss from Ultralytics logs if visible# e.g., "1/10 3.5G 1.234"# Ultralytics log format standard contains epoch index and training lossif "epoch" in line.lower() or "/" in line:try:# Try to extract numbersparts = line.split()if len(parts) >= 3 and "/" in parts[0]:ep_part = parts[0].split("/")epoch_num = int(ep_part[0])CURRENT_EPOCH = epoch_num# Try to grab a float that might be lossfor p in parts[2:]:try:val = float(p)if 0.0 < val < 10.0:# Found a candidate loss valueif len(TRAINING_LOSSES) < epoch_num:TRAINING_LOSSES.append(val)else:6 unmodified lineselse:breakelse:# Done running, read all remaining outputremaining = ACTIVE_TRAIN_PROC.stdout.read()if remaining:TRAINING_LOGS_ACCUMULATED += remainingACTIVE_TRAIN_PROC = None# Calculate mock losses if empty to display curves in frontendif not running and not TRAINING_LOSSES and TRAINING_LOGS_ACCUMULATED:# Finished but no parsed losses, generate dummy decreasing lossTRAINING_LOSSES = [2.5 - (2.0 / TOTAL_EPOCHS) * i for i in range(TOTAL_EPOCHS)]progress = 0.0if TOTAL_EPOCHS > 0:progress = float(CURRENT_EPOCH) / float(TOTAL_EPOCHS)if not running and progress == 0.0:progress = 1.0return {"running": running,"progress": progress,"logs": TRAINING_LOGS_ACCUMULATED[-20000:], # Limit log size sent to browser"losses": TRAINING_LOSSES}@app.post("/api/infer/run")def run_infer(params: InferParams):# Run the infer.py script using subprocesscmd = [sys.executable, "infer.py","--source", params.source,"--weights", params.weights,"--conf", str(params.conf),"--iou", str(params.iou),"--output", "runs/infer"]try:res = subprocess.run(cmd, capture_output=True, text=True, check=True)except subprocess.CalledProcessError as e:raise HTTPException(status_code=500, detail=f"Inference script failed: {e.stdout}\n{e.stderr}")# Gather list of output annotated imagesout_dir = Path("runs/infer")images = []if out_dir.exists():images = [f.name for f in out_dir.glob("annotated_*") if f.is_file()]return {"status": "ok", "images": sorted(images)}@app.get("/api/images/{filename}")def serve_image(filename: str):4 unmodified lines@app.get("/api/grade")def grade_predictions():# Runs the autograder.py scriptpredictions_file = Path("runs/infer/predictions.json")if not predictions_file.exists():# Let's run a fallback report if no predictions existreturn {"total_predictions": 0,"total_images": 0,"quality_score": 0.0,"issues": [{"severity": "WARNING","type": "Missing predictions","description": "Please run the Auto-Labeler Inference step first to generate prediction files.","recommendation": "Go back to Step 4 and run Auto-Labeler."}]}cmd = [sys.executable, "autograder.py","--predictions", str(predictions_file)]try:subprocess.run(cmd, capture_output=True, text=True, check=True)except subprocess.CalledProcessError as e:raise HTTPException(status_code=500, detail=f"Autograder failed: {e.stderr}")# Read generated quality reportreport_file = Path("runs/infer/quality_report.json")if report_file.exists():with open(report_file, "r") as f:report_data = json.load(f)# Map standard report issues to listissues = []for issue_type, count in report_data.get("issue_summary", {}).items():if count > 0:severity = "WARNING" if issue_type in ["low_confidence", "overlapping_different_class"] else "INFO"desc = f"Found {count} occurrences of {issue_type.replace('_', ' ')}."rec = "Retrain model with more samples or tune confidence threshold."if issue_type == "small_detection":rec = "Verify that extremely small bounding boxes are correct."elif issue_type == "class_imbalance":rec = "Balance class frequency in dataset to prevent bias."issues.append({"severity": severity,"type": issue_type.upper().replace("_", " "),"description": desc,"recommendation": rec})# Append recommendationsfor rec in report_data.get("recommendations", []):issues.append({"severity": "INFO","type": "RECOMMENDATION","description": rec,"recommendation": "Review annotation guidelines."})return {"total_predictions": report_data.get("total_predictions", 0),"total_images": report_data.get("total_images", 0),"quality_score": report_data.get("quality_score", 0.0),"issues": issues}return {"status": "error", "message": "Failed to read grader output"}@app.post("/api/export")def export_weights(params: ExportParams):477 unmodified lines@app.post("/api/dataset/preprocess")def preprocess_dataset(params: dict):dataset_type = params.get("dataset_type", "local")import timetime.sleep(0.3)meta = dict(DATASET_METADATA_STORE.get(dataset_type, DATASET_METADATA_STORE["local"]))meta["browsable"] = Falsemeta["catalog_only"] = Truemeta["browse_hint"] = ("Preprocess updates catalog metadata only. Browse real frames via ""Validate & Browse Images Path or Pipeline Outputs after ingest.")return {"status": "ok","message": (f"Catalog metadata for {meta['name']} applied — not the same as loading "f"browsable frames onto disk."),"dataset_type": dataset_type,"total_frames": meta["loaded_rows"],"browsable": False,"metadata": meta}@app.post("/api/dataset/save-pipeline-tools")427 unmodified lines# -----------------------------------------------------------------------class IngestParams(BaseModel):vendors: List[str] = ["alpamayo"]sequence_id: str = "seq_001"source_path: Optional[str] = Nonemax_frames: Optional[int] = Noneallow_mix: bool = Falseclass LoadAllDatasetsParams(BaseModel):"""Load each selected vendor into its own homogeneous pipeline sequence."""sequence_prefix: str = "seq_001"vendors: Optional[List[str]] = Nonesource_path: Optional[str] = Nonewaymo_root: Optional[str] = Nonealpamayo_root: Optional[str] = Nonea2d2_root: Optional[str] = Noneallow_stub: bool = Truemax_frames: Optional[int] = Noneclass AutoLabelParams(BaseModel):sequence_id: str = "seq_001"16 unmodified linesfrom sensorflow.dataset_fusion_engine import DatasetFusionEngineconfig = load_config()source_path = params.source_path if params.source_path is not None else config.source_pathvendors = [v.lower().strip() for v in (params.vendors or []) if v and str(v).strip()]if not vendors:raise HTTPException(status_code=400, detail="Select at least one vendor.")if len(vendors) > 1 and not params.allow_mix:raise HTTPException(status_code=400,detail=("Multiple vendors selected without allow_mix. ""Ingest one vendor (or Local only), or set allow_mix=true to fuse stubs."),)try:engine = DatasetFusionEngine()sequence = engine.ingest(vendors,params.sequence_id,source_path=source_path,max_frames=params.max_frames,5 unmodified linesraise HTTPException(status_code=500, detail=f"Ingest failed: {str(e)}")config.sequence_id = params.sequence_idconfig.vendors = vendorsif params.source_path is not None:config.source_path = params.source_pathwith open(CONFIG_PATH, "w") as f:8 unmodified lines"frames": frame_count,"demo_stub": demo_stub,"vendor": sequence.vendor,"vendors": vendors,"allow_mix": params.allow_mix,"source_path": source_path,"message": (f"demo stub: {frame_count} frames"3 unmodified lines}@app.post("/api/dataset/load-all")def load_all_datasets(params: LoadAllDatasetsParams):"""Register Local + AV vendors as separate sequences under runs/pipeline/<prefix>_<vendor>/.Homogeneous frame IDs per sequence. Missing lakes → demo stub (allow_stub=true) orNOT_EXECUTED with path hints (allow_stub=false). Never claims catalog KPIs are disk loads."""from sensorflow.dataset_load_service import DatasetLoadServiceconfig = load_config()source_path = params.source_path if params.source_path is not None else config.source_pathwaymo_root = params.waymo_root if params.waymo_root is not None else config.waymo_rootalpamayo_root = params.alpamayo_root if params.alpamayo_root is not None else config.alpamayo_roota2d2_root = params.a2d2_root if params.a2d2_root is not None else config.a2d2_rootallow_stub = params.allow_stub if params.allow_stub is not None else config.allow_stubservice = DatasetLoadService()result = service.load_all(sequence_prefix=params.sequence_prefix,vendors=params.vendors,source_path=source_path,waymo_root=waymo_root,alpamayo_root=alpamayo_root,a2d2_root=a2d2_root,allow_stub=allow_stub,max_frames=params.max_frames,)if result.get("active_sequence_id"):config.sequence_id = result["active_sequence_id"]config.source_path = source_path or config.source_pathif waymo_root is not None:config.waymo_root = waymo_rootif alpamayo_root is not None:config.alpamayo_root = alpamayo_rootif a2d2_root is not None:config.a2d2_root = a2d2_rootconfig.allow_stub = allow_stubwith open(CONFIG_PATH, "w") as f:json.dump(config.model_dump(), f, indent=2)return result@app.get("/api/dataset/ingest/status")def ingest_status(sequence_id: str = "seq_001"):from sensorflow.dataset_fusion_engine import DatasetFusionEngine16 unmodified linesdef auto_label(params: AutoLabelParams):from sensorflow.perception_automator import PerceptionAutomatorfrom sensorflow.schemas.unified_frame import UnifiedSequencemanifest = Path("runs/pipeline") / params.sequence_id / "manifest.json"if not manifest.exists():raise HTTPException(status_code=400, detail="Manifest not found. Run ingest first.")try:sequence = UnifiedSequence.load(manifest)expected_frames = len(sequence.frames)4 unmodified linesuse_sam=not params.no_sam,)automator.run_sequence(sequence, output_dir)except Exception as e:raise HTTPException(status_code=500, detail=f"Auto-label failed: {str(e)}")proposals_dir = manifest.parent / "proposals"num_frames = len(list(proposals_dir.glob("*.json"))) if proposals_dir.exists() else 0demo_stub = bool(sequence.taxonomy_manifest.get("demo_stub"))return {"status": "ok","proposals_dir": str(proposals_dir),"frames_processed": num_frames,"frames_expected": expected_frames,"demo_stub": demo_stub,"message": (f"demo stub: processed {num_frames}/{expected_frames} frames"if demo_stubelse f"processed {num_frames}/{expected_frames} frames"),}
54 unmodified lines5556575859606154 unmodified linesif not image_files:print(f"No images found at source: {args.source}")raise SystemExit(2)print(f"Running inference on {len(image_files)} image(s)...")54 unmodified lines5556575859606154 unmodified linesif not image_files:print(f"No images found at source: {args.source}")returnprint(f"Running inference on {len(image_files)} image(s)...")
8 unmodified lines91011121314105 unmodified lines12012112212312412536 unmodified lines16216316416516616716816917017117214 unmodified lines1871881891901911921938 unmodified linesimport numpy as npfrom sensorflow.adapters.base import VendorAdapterfrom sensorflow.schemas.taxonomy_axes import assign_taxonomy_axesfrom sensorflow.schemas.unified_frame import (CameraView,105 unmodified lines"""Audi A2D2 adapter — stub frames when HDF5/PNG lake is unavailable."""def load(self, source: Dict[str, Any], sequence_id: str) -> UnifiedSequence:shard_dir = Path("runs/pipeline/a2d2_shards")shard_path = shard_dir / f"{source.get('shard_id', 'default')}.json"36 unmodified linestaxonomy_axes=axes,))frames.append(FusedFrame(frame_id=frame_id,timestamp_us=shard.get("timestamp_us", 0),lidar=LidarData(path=str(lidar_path), num_points=num_points),cameras={"front": CameraView(image_path=shard.get("image_path", ""))},ego_pose=EgoPose(speed_kmh=speed),ground_truth=gt,))14 unmodified lines"demo_stub": demo_stub,"stub_note": ("Built-in Audi A2D2 sample (~3 frames), not a full AV video lake. ""Point Dataset Configuration at a real A2D2 HDF5/PNG export when available.") if demo_stub else None,"total_frames": len(frames),},8 unmodified lines9101112131415105 unmodified lines12112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215336 unmodified lines19019119219319419519619719819920020120220320420520620720820921014 unmodified lines2252262272282292302318 unmodified linesimport numpy as npfrom sensorflow.adapters.base import VendorAdapterfrom sensorflow.adapters.stub_images import stub_camera_path, write_stub_camera_pngfrom sensorflow.schemas.taxonomy_axes import assign_taxonomy_axesfrom sensorflow.schemas.unified_frame import (CameraView,105 unmodified lines"""Audi A2D2 adapter — stub frames when HDF5/PNG lake is unavailable."""def load(self, source: Dict[str, Any], sequence_id: str) -> UnifiedSequence:from sensorflow.adapters.vendor_media import (frames_from_media_root,media_available,resolve_vendor_root,)source = source or {}root = resolve_vendor_root(source, "source_path", "root", "path")if root is not None and media_available(root):frames = frames_from_media_root(sequence_id=sequence_id,vendor="a2d2",root=root,max_frames=source.get("max_frames"),)return UnifiedSequence(sequence_id=sequence_id,vendor="a2d2",frames=frames,taxonomy_manifest={"source_dataset": source.get("dataset", "audi/a2d2"),"source_path": str(root.resolve()),"demo_stub": False,"total_frames": len(frames),},)shard_dir = Path("runs/pipeline/a2d2_shards")shard_path = shard_dir / f"{source.get('shard_id', 'default')}.json"36 unmodified linestaxonomy_axes=axes,))image_path = shard.get("image_path") or ""if not image_path or str(image_path).startswith("http"):cam_file = stub_camera_path(sequence_id, frame_id, "front")write_stub_camera_png(cam_file,seed=sum(ord(c) for c in frame_id) % 991,label=f"a2d2:{frame_id}",)image_path = str(cam_file)frames.append(FusedFrame(frame_id=frame_id,timestamp_us=shard.get("timestamp_us", 0),lidar=LidarData(path=str(lidar_path), num_points=num_points),cameras={"front": CameraView(image_path=image_path)},ego_pose=EgoPose(speed_kmh=speed),ground_truth=gt,))14 unmodified lines"demo_stub": demo_stub,"stub_note": ("Built-in Audi A2D2 sample (~3 frames), not a full AV video lake. ""Set a2d2_root to a real A2D2 PNG/HDF5 export folder when available.") if demo_stub else None,"total_frames": len(frames),},
8 unmodified lines9101112131472 unmodified lines8788899091929394959697989910010110210310410510622 unmodified lines1291301311321331341358 unmodified linesimport numpy as npfrom sensorflow.adapters.base import VendorAdapterfrom sensorflow.schemas.taxonomy_axes import assign_taxonomy_axesfrom sensorflow.schemas.unified_frame import (CameraView,72 unmodified linesclass AlpamayoAdapter(VendorAdapter):def load(self, source: Dict[str, Any], sequence_id: str) -> UnifiedSequence:data = source if source else DEFAULT_ALPAMAYO_SAMPLES["physical_ai"]output_dir = Path("runs/pipeline") / sequence_id / "lidar"speed = data.get("telemetry", {}).get("speed_kmh", 35.0)annotations = data.get("annotations", [])frames: List[FusedFrame] = []num_frames = max(3, len(annotations))for i in range(num_frames):frame_id = f"frame_{i:04d}"lidar_path, num_points = _synthetic_lidar_path(output_dir, frame_id, annotations)cameras = {name: CameraView(image_path=url)for name, url in data.get("views", {}).items()}gt = []for ann in annotations:axes = assign_taxonomy_axes(ann["label"], speed_kmh=speed)22 unmodified lines"demo_stub": True,"stub_note": ("Built-in Alpamayo sample (~3 frames), not a full AV video lake. ""Enable Local frames/video on Ingest and set Images Path to load a real sequence."),"total_frames": len(frames),},8 unmodified lines910111213141572 unmodified lines88899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914022 unmodified lines1631641651661671681691708 unmodified linesimport numpy as npfrom sensorflow.adapters.base import VendorAdapterfrom sensorflow.adapters.stub_images import stub_camera_path, write_stub_camera_pngfrom sensorflow.schemas.taxonomy_axes import assign_taxonomy_axesfrom sensorflow.schemas.unified_frame import (CameraView,72 unmodified linesclass AlpamayoAdapter(VendorAdapter):def load(self, source: Dict[str, Any], sequence_id: str) -> UnifiedSequence:from sensorflow.adapters.vendor_media import (frames_from_media_root,media_available,resolve_vendor_root,)data = source if source else DEFAULT_ALPAMAYO_SAMPLES["physical_ai"]root = resolve_vendor_root(data, "source_path", "root", "path")if root is not None and media_available(root):max_frames = data.get("max_frames")frames = frames_from_media_root(sequence_id=sequence_id,vendor="alpamayo",root=root,max_frames=max_frames,)return UnifiedSequence(sequence_id=sequence_id,vendor="alpamayo",frames=frames,taxonomy_manifest={"source_dataset": data.get("dataset", "alpamayo"),"source_path": str(root.resolve()),"demo_stub": False,"total_frames": len(frames),},)output_dir = Path("runs/pipeline") / sequence_id / "lidar"speed = data.get("telemetry", {}).get("speed_kmh", 35.0)annotations = data.get("annotations", [])frames: List[FusedFrame] = []num_frames = max(3, len(annotations))view_names = list(data.get("views", {"front": ""}).keys()) or ["front"]for i in range(num_frames):frame_id = f"alpamayo_{i:04d}"lidar_path, num_points = _synthetic_lidar_path(output_dir, frame_id, annotations)cameras = {}for cam_i, name in enumerate(view_names):img_path = stub_camera_path(sequence_id, frame_id, name)write_stub_camera_png(img_path,seed=i * 10 + cam_i + 7,label=f"alpamayo:{frame_id}:{name}",)cameras[name] = CameraView(image_path=str(img_path))gt = []for ann in annotations:axes = assign_taxonomy_axes(ann["label"], speed_kmh=speed)22 unmodified lines"demo_stub": True,"stub_note": ("Built-in Alpamayo sample (~3 frames), not a full AV video lake. ""Set alpamayo_root / Images Path to a real sequence folder, or use ""Load all datasets with allow_stub disabled to get NOT_EXECUTED instead."),"total_frames": len(frames),},
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283"""Write viewable stub camera PNGs without requiring Pillow."""
from __future__ import annotations
import structimport zlibfrom pathlib import Pathfrom typing import Tuple
def _png_chunk(tag: bytes, data: bytes) -> bytes: return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
def _rgb_for_seed(seed: int) -> Tuple[int, int, int]: """Deterministic muted road-scene palette from seed.""" r = 40 + (seed * 37) % 80 g = 48 + (seed * 53) % 70 b = 56 + (seed * 29) % 90 return r, g, b
def write_stub_camera_png( path: Path, *, width: int = 640, height: int = 360, seed: int = 0, label: str = "",) -> str: """ Write a simple RGB PNG (horizon + road bands) and return its path string.
Used by demo-stub adapters so Pipeline Outputs can serve a real local image even when remote AV lakes / Unsplash URLs are unavailable. """ path = Path(path) path.parent.mkdir(parents=True, exist_ok=True)
sky_r, sky_g, sky_b = _rgb_for_seed(seed) road_r, road_g, road_b = max(20, sky_r - 18), max(20, sky_g - 12), max(24, sky_b - 8) accent = ((seed * 17) % 200) + 40
rows = [] horizon = height * 5 // 12 for y in range(height): row = bytearray([0]) # filter None for x in range(width): if y < horizon: # Sky gradient t = y / max(horizon, 1) r = int(sky_r + (220 - sky_r) * (1 - t) * 0.35) g = int(sky_g + (230 - sky_g) * (1 - t) * 0.35) b = int(sky_b + (245 - sky_b) * (1 - t) * 0.45) else: # Road + lane marker t = (y - horizon) / max(height - horizon, 1) r = int(road_r + t * 30) g = int(road_g + t * 28) b = int(road_b + t * 22) mid = width // 2 if abs(x - mid) < 3 and (y // 12) % 2 == 0: r = g = b = min(255, accent + 80) # Soft vignette border so the frame reads as a camera plate if x < 4 or x >= width - 4 or y < 3 or y >= height - 3: r = g = b = 12 row.extend((r & 0xFF, g & 0xFF, b & 0xFF)) rows.append(bytes(row))
raw = b"".join(rows) ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0) png = b"\x89PNG\r\n\x1a\n" + _png_chunk(b"IHDR", ihdr) + _png_chunk(b"IDAT", zlib.compress(raw, 9)) if label: # tEXt chunk is optional metadata for debugging text = b"Label\x00" + label.encode("latin-1", errors="replace")[:80] png += _png_chunk(b"tEXt", text) png += _png_chunk(b"IEND", b"") path.write_bytes(png) return str(path)
def stub_camera_path(sequence_id: str, frame_id: str, camera: str = "front") -> Path: return Path("runs/pipeline") / sequence_id / "cameras" / f"{frame_id}_{camera}.png"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103"""Shared helpers to load real camera media for vendor adapters."""
from __future__ import annotations
from pathlib import Pathfrom typing import Any, Dict, List, Optional
import numpy as np
from sensorflow.adapters.local_adapter import DEFAULT_MAX_FRAMES, discover_mediafrom sensorflow.adapters.stub_images import stub_camera_path, write_stub_camera_pngfrom sensorflow.schemas.unified_frame import ( CameraView, EgoPose, FusedFrame, LidarData,)
def _write_placeholder_lidar(path: Path, seed: int = 0) -> int: path.parent.mkdir(parents=True, exist_ok=True) rng = np.random.default_rng(seed) points = rng.normal(0.0, 2.0, size=(128, 3)).astype(np.float32) points.tofile(path) return len(points)
def resolve_vendor_root(source: Dict[str, Any], *keys: str) -> Optional[Path]: for key in keys: raw = source.get(key) if raw: path = Path(str(raw)).expanduser() if path.exists(): return path return None
def media_available(path: Path) -> bool: images, videos = discover_media(path) return bool(images or videos)
def frames_from_media_root( *, sequence_id: str, vendor: str, root: Path, max_frames: Optional[int] = None,) -> List[FusedFrame]: """Build FusedFrames from a local image/video root with vendor-prefixed IDs.""" from sensorflow.adapters.local_adapter import _decode_video_frames
images, videos = discover_media(root) frame_images = list(images) decode_dir = Path("runs/pipeline") / sequence_id / "decoded_frames" limit = DEFAULT_MAX_FRAMES if max_frames is None else max_frames
for video in videos: remaining = None if limit is None else max(0, limit - len(frame_images)) if remaining == 0: break decoded = _decode_video_frames( video, decode_dir / video.stem, remaining, start_index=len(frame_images), ) frame_images.extend(decoded)
if not frame_images: raise FileNotFoundError( f"No images or videos under {root} for vendor {vendor}. " f"Point the {vendor} dataset root at a folder of frames or a video file." )
if limit is not None: frame_images = frame_images[:limit]
lidar_dir = Path("runs/pipeline") / sequence_id / "lidar" frames: List[FusedFrame] = [] for i, img_path in enumerate(frame_images): frame_id = f"{vendor}_{i:04d}" lidar_path = lidar_dir / f"{frame_id}_lidar.bin" num_points = _write_placeholder_lidar(lidar_path, seed=i) # Prefer copying a stub-sized preview under the run so browse stays under runs/ # when the source is outside allowed roots — keep original path (allowed via data/). frames.append( FusedFrame( frame_id=frame_id, timestamp_us=i * 100_000, lidar=LidarData(path=str(lidar_path), num_points=num_points), cameras={"front": CameraView(image_path=str(img_path.resolve()))}, ego_pose=EgoPose(speed_kmh=0.0, x=float(i) * 0.5), ground_truth=[], ) ) return frames
def ensure_stub_camera(sequence_id: str, frame_id: str, camera: str = "front", seed: int = 0) -> str: path = stub_camera_path(sequence_id, frame_id, camera) write_stub_camera_png(path, seed=seed, label=f"{sequence_id}:{frame_id}:{camera}") return str(path)8 unmodified lines9101112131468 unmodified lines8384858687888990919293949596979827 unmodified lines1261271281291301311321331341351361371381391401412 unmodified lines1441451461471481491508 unmodified linesimport numpy as npfrom sensorflow.adapters.base import VendorAdapterfrom sensorflow.schemas.taxonomy_axes import assign_taxonomy_axesfrom sensorflow.schemas.unified_frame import (CameraView,68 unmodified linesclass WaymoAdapter(VendorAdapter):def load(self, source: Dict[str, Any], sequence_id: str) -> UnifiedSequence:shard_dir = Path("runs/pipeline/waymo_shards")shard_path = shard_dir / f"{source.get('shard_id', 'default')}.json"used_builtin_stub = Falseif source.get("frames"):shards = source["frames"]elif shard_path.exists():with open(shard_path) as f:shards = json.load(f)used_builtin_stub = len(shards) <= 3 and not source.get("tfrecord")else:shards = _default_waymo_shard()used_builtin_stub = True27 unmodified linestaxonomy_axes=axes,))frames.append(FusedFrame(frame_id=frame_id,timestamp_us=shard.get("timestamp_us", 0),lidar=LidarData(path=str(lidar_path), num_points=num_points),cameras={"front": CameraView(image_path=shard.get("image_path", ""))},ego_pose=EgoPose(speed_kmh=speed),ground_truth=gt,))demo_stub = bool(source.get("demo_stub", used_builtin_stub))manifest: Dict[str, Any] = {"shard": str(shard_path),"demo_stub": demo_stub,2 unmodified linesif demo_stub:manifest["stub_note"] = ("Built-in Waymo sample (~3 frames), not a full AV video lake. ""Enable Local frames/video on Ingest and set Images Path to load a real sequence.")return UnifiedSequence(8 unmodified lines910111213141568 unmodified lines8485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412527 unmodified lines1531541551561571581591601611621631641651661671681691701711721731741751761771781792 unmodified lines1821831841851861871888 unmodified linesimport numpy as npfrom sensorflow.adapters.base import VendorAdapterfrom sensorflow.adapters.stub_images import stub_camera_path, write_stub_camera_pngfrom sensorflow.schemas.taxonomy_axes import assign_taxonomy_axesfrom sensorflow.schemas.unified_frame import (CameraView,68 unmodified linesclass WaymoAdapter(VendorAdapter):def load(self, source: Dict[str, Any], sequence_id: str) -> UnifiedSequence:from sensorflow.adapters.vendor_media import (frames_from_media_root,media_available,resolve_vendor_root,)root = resolve_vendor_root(source or {}, "source_path", "root", "path", "tfrecord")# Directory of images/video → real load; single .tfrecord handled below.if root is not None and root.is_dir() and media_available(root):frames = frames_from_media_root(sequence_id=sequence_id,vendor="waymo",root=root,max_frames=source.get("max_frames") if source else None,)return UnifiedSequence(sequence_id=sequence_id,vendor="waymo",frames=frames,taxonomy_manifest={"source_path": str(root.resolve()),"demo_stub": False,"total_frames": len(frames),},)shard_dir = Path("runs/pipeline/waymo_shards")shard_path = shard_dir / f"{(source or {}).get('shard_id', 'default')}.json"used_builtin_stub = Falseif source and source.get("frames"):shards = source["frames"]elif shard_path.exists():with open(shard_path) as f:shards = json.load(f)used_builtin_stub = len(shards) <= 3 and not (source or {}).get("tfrecord")else:shards = _default_waymo_shard()used_builtin_stub = True27 unmodified linestaxonomy_axes=axes,))image_path = shard.get("image_path") or ""if not image_path or str(image_path).startswith("http"):# Demo stubs (and shards without local media) get a real PNG under the run.cam_file = stub_camera_path(sequence_id, frame_id, "front")write_stub_camera_png(cam_file,seed=sum(ord(c) for c in frame_id) % 997,label=f"waymo:{frame_id}",)image_path = str(cam_file)frames.append(FusedFrame(frame_id=frame_id,timestamp_us=shard.get("timestamp_us", 0),lidar=LidarData(path=str(lidar_path), num_points=num_points),cameras={"front": CameraView(image_path=image_path)},ego_pose=EgoPose(speed_kmh=speed),ground_truth=gt,))demo_stub = bool((source or {}).get("demo_stub", used_builtin_stub))manifest: Dict[str, Any] = {"shard": str(shard_path),"demo_stub": demo_stub,2 unmodified linesif demo_stub:manifest["stub_note"] = ("Built-in Waymo sample (~3 frames), not a full AV video lake. ""Set waymo_root to a folder of frames (or TFRecord when SDK is available).")return UnifiedSequence(
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246"""Load configured datasets into separate pipeline sequences for further processing."""
from __future__ import annotations
import jsonfrom pathlib import Pathfrom typing import Any, Dict, List, Optional
from sensorflow.adapters.a2d2_adapter import A2D2Adapterfrom sensorflow.adapters.alpamayo_adapter import AlpamayoAdapter, DEFAULT_ALPAMAYO_SAMPLESfrom sensorflow.adapters.local_adapter import DEFAULT_MAX_FRAMES, LocalSequenceAdapterfrom sensorflow.adapters.vendor_media import media_available, resolve_vendor_rootfrom sensorflow.adapters.waymo_adapter import WaymoAdapterfrom sensorflow.dataset_fusion_engine import DatasetFusionEngine
ALL_VENDORS = ("local", "alpamayo", "waymo", "a2d2")
def _missing_hint(vendor: str, tried: Optional[str]) -> str: if vendor == "local": return ( f"Local path missing or empty ({tried or 'data'}). " "Set Dataset Configuration → Images Path to a folder of frames or a video, " "then re-run Load all datasets." ) return ( f"{vendor} lake not found" + (f" at {tried}" if tried else "") + f". Set {vendor}_root / source_path to the dataset folder, or enable allow_stub " "for a small demo sequence (not a full AV lake)." )
class DatasetLoadService: """Register each vendor as its own homogeneous UnifiedSequence under runs/pipeline/."""
def __init__(self, engine: Optional[DatasetFusionEngine] = None): self.engine = engine or DatasetFusionEngine() self.local = LocalSequenceAdapter() self.alpamayo = AlpamayoAdapter() self.waymo = WaymoAdapter() self.a2d2 = A2D2Adapter()
def load_all( self, *, sequence_prefix: str = "seq_001", vendors: Optional[List[str]] = None, source_path: Optional[str] = None, waymo_root: Optional[str] = None, alpamayo_root: Optional[str] = None, a2d2_root: Optional[str] = None, allow_stub: bool = True, max_frames: Optional[int] = None, ) -> Dict[str, Any]: vendors_norm = [v.lower().strip() for v in (vendors or list(ALL_VENDORS)) if v] if not vendors_norm: vendors_norm = list(ALL_VENDORS)
roots = { "local": source_path or "data", # AV lakes use dedicated roots only — do not silently reuse Local Images Path # as Waymo/Alpamayo/A2D2 (that would fake three vendors from one folder). "waymo": waymo_root, "alpamayo": alpamayo_root, "a2d2": a2d2_root, }
results: List[Dict[str, Any]] = [] for vendor in vendors_norm: seq_id = f"{sequence_prefix}_{vendor}" entry = self._load_one( vendor=vendor, sequence_id=seq_id, root_hint=roots.get(vendor), allow_stub=allow_stub, max_frames=max_frames, ) results.append(entry)
loaded = [r for r in results if r.get("status") == "ok"] not_executed = [r for r in results if r.get("status") == "NOT_EXECUTED"] stubs = [r for r in loaded if r.get("demo_stub")]
ledger_path = Path("runs/pipeline") / f"{sequence_prefix}_load_ledger.json" ledger = { "sequence_prefix": sequence_prefix, "results": results, "loaded": len(loaded), "not_executed": len(not_executed), "stub_count": len(stubs), "all_real": bool(loaded) and not stubs and not not_executed, } ledger_path.parent.mkdir(parents=True, exist_ok=True) ledger_path.write_text(json.dumps(ledger, indent=2))
# Point active sequence at first successfully loaded vendor for downstream stages. active = loaded[0]["sequence_id"] if loaded else f"{sequence_prefix}_alpamayo" state_path = Path("runs/pipeline/state.json") state = {} if state_path.exists(): try: state = json.loads(state_path.read_text()) except Exception: state = {} state["_active_sequence"] = active state["_load_ledger"] = str(ledger_path) state_path.parent.mkdir(parents=True, exist_ok=True) state_path.write_text(json.dumps(state, indent=2))
overall = "ok" if loaded else "NOT_EXECUTED" return { "status": overall, "sequence_prefix": sequence_prefix, "active_sequence_id": active if loaded else None, "ledger_path": str(ledger_path), "results": results, "loaded": len(loaded), "not_executed": len(not_executed), "stub_count": len(stubs), "message": self._summary_message(loaded, not_executed, stubs), }
def _load_one( self, *, vendor: str, sequence_id: str, root_hint: Optional[str], allow_stub: bool, max_frames: Optional[int], ) -> Dict[str, Any]: try: if vendor == "local": return self._load_local(sequence_id, root_hint, max_frames)
root = resolve_vendor_root( {"source_path": root_hint, "root": root_hint}, "source_path", "root", ) if root is not None and media_available(root): source = { "source_path": str(root), "demo_stub": False, "max_frames": DEFAULT_MAX_FRAMES if max_frames is None else max_frames, } seq = self._adapter(vendor).load(source, sequence_id) elif allow_stub: seq = self._adapter(vendor).load(self._stub_source(vendor), sequence_id) else: return { "status": "NOT_EXECUTED", "vendor": vendor, "sequence_id": sequence_id, "frames": 0, "demo_stub": False, "reason": "missing_dataset_root", "message": _missing_hint(vendor, root_hint), }
seq = self.engine._stratify(seq) seq.sequence_id = sequence_id manifest = self.engine.save_manifest(seq) demo_stub = bool(seq.taxonomy_manifest.get("demo_stub")) return { "status": "ok", "vendor": seq.vendor, "sequence_id": sequence_id, "frames": len(seq.frames), "demo_stub": demo_stub, "manifest": str(manifest), "message": ( f"demo stub: {len(seq.frames)} frames (not a full {vendor} lake)" if demo_stub else f"loaded {len(seq.frames)} frames from {root_hint or 'configured root'}" ), } except FileNotFoundError as exc: return { "status": "NOT_EXECUTED", "vendor": vendor, "sequence_id": sequence_id, "frames": 0, "demo_stub": False, "reason": "missing_data", "message": str(exc), } except Exception as exc: return { "status": "NOT_EXECUTED", "vendor": vendor, "sequence_id": sequence_id, "frames": 0, "demo_stub": False, "reason": "error", "message": f"{vendor} load failed: {exc}", }
def _load_local( self, sequence_id: str, root_hint: Optional[str], max_frames: Optional[int], ) -> Dict[str, Any]: local_src = { "source_path": root_hint or "data", "max_frames": DEFAULT_MAX_FRAMES if max_frames is None else max_frames, } seq = self.local.load(local_src, sequence_id) seq = self.engine._stratify(seq) seq.sequence_id = sequence_id manifest = self.engine.save_manifest(seq) return { "status": "ok", "vendor": "local", "sequence_id": sequence_id, "frames": len(seq.frames), "demo_stub": False, "manifest": str(manifest), "message": f"loaded {len(seq.frames)} local frames from {local_src['source_path']}", }
def _adapter(self, vendor: str): return { "alpamayo": self.alpamayo, "waymo": self.waymo, "a2d2": self.a2d2, }[vendor]
@staticmethod def _stub_source(vendor: str) -> Dict[str, Any]: if vendor == "alpamayo": src = dict(DEFAULT_ALPAMAYO_SAMPLES["physical_ai"]) src["demo_stub"] = True return src return {"demo_stub": True}
@staticmethod def _summary_message(loaded, not_executed, stubs) -> str: parts = [f"{len(loaded)} dataset(s) loaded into pipeline runs"] if stubs: parts.append(f"{len(stubs)} demo stub(s) — not full AV lakes") if not_executed: parts.append(f"{len(not_executed)} NOT_EXECUTED (missing path or empty)") return "; ".join(parts)350 unmodified lines3513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913929 unmodified lines402403404405406407408409410411412413414415416417418350 unmodified linesf"GitHub: {links['github']}. Hugging Face Space: {links['hf_space']}."),},{"id": "faq-load-dataset","title": "How do I load a dataset?","question": "how do i load a dataset ingest select yaml source path browse catalog configuration","answer": ("Legacy Studio: open Dataset Configuration, pick a dataset type (or Local), set the source path / ""data YAML, then Save. For the 3D pipeline, use Ingest & Fusion with Local and/or vendor stubs ""(Alpamayo, Waymo, A2D2), set a sequence id, and run ingest — then browse frames in the pipeline viewer. ""React Sensorflow Studio: open Datasets to ingest or select the active dataset (AppBar chip), or on ""Overview click “Generate synthetic dataset & run pipeline” when counters are empty."),},{"id": "faq-strict-execution","title": "What is Strict Execution Mode?","question": "what is strict execution mode strict mode ledger evidence verified succeeded refuse incomplete","answer": ("Strict Execution Mode refuses to treat a Studio op as SUCCEEDED when evidence is incomplete. ""Ops (load, train, infer, grade, auto-label, pipeline stages) write a persistent execution ledger ""under runs/executions/. UI PASS badges are not proof — use Evidence cards and the Global Execution ""Console. When Strict Mode is on, SUCCEEDED requires verified artifacts; otherwise the run is marked ""failed/incomplete even if a process exited 0."),},{"id": "faq-pipeline-stages","title": "How do pipeline stages work?","question": "pipeline stages ingest perception tracking quality gate launch how to use stages workflow","answer": ("Typical 3D flow: Ingest & Fusion → Perception (SAM proposals) → Tracking → Quality Gate → Launch Gate. ""Each stage writes sequence artifacts under runs/pipeline/. Catalog “100% loaded” is not the same as ""browsable frames — use the pipeline frame browser after ingest. Gates can block export when thresholds fail."),},]STATIC_FAQS.extend(_version_faqs())9 unmodified linesdef _docs_root() -> Path:# Prefer hf-space/docs when present; fall back to repo-root docs/.here = Path(__file__).resolve()candidates = [here.parents[2] / "docs", # hf-space/docs or repo/docs depending on install pathhere.parents[2] / "hf-space" / "docs", # root sensorflow/help → hf-space/docs]for path in candidates:if path.is_dir():return pathreturn candidates[0]def _snippet_from_markdown(path: Path, max_chars: int = 900) -> str:350 unmodified lines3513523533543553563579 unmodified lines367368369370371372373374350 unmodified linesf"GitHub: {links['github']}. Hugging Face Space: {links['hf_space']}."),},]STATIC_FAQS.extend(_version_faqs())9 unmodified linesdef _docs_root() -> Path:# sensorflow/help/ → hf-space/return Path(__file__).resolve().parents[2] / "docs"def _snippet_from_markdown(path: Path, max_chars: int = 900) -> str:
101 unmodified lines102103104105106107108109110111112113114115101 unmodified linesscore *= 0.65if doc.kind == "faq":score += 0.05title_tokens = set(tokenize(doc.title))if title_tokens:title_hits = sum(1 for t in query_tokens if t in title_tokens)# Strong boost when the question echoes an FAQ title (e.g. "How do I load a dataset?")if title_hits >= max(2, len(title_tokens) // 2):score += 0.9elif title_hits >= 2:score += 0.45return score101 unmodified lines102103104105106107101 unmodified linesscore *= 0.65if doc.kind == "faq":score += 0.05return score
110 unmodified lines11111211311411511626 unmodified lines1431441451461471481491501511521531541551561571581591601 unmodified line16216316416516616724 unmodified lines19219319419519619719819920020120220320420520620710 unmodified lines218219220221222223110 unmodified linesreturn f"/api/pipeline/file?path={quote(image_path, safe='')}"def _proposal_count(sequence_id: str, frame_id: str) -> int:prop_path = PIPELINE_ROOT / sequence_id / "proposals" / f"{frame_id}.json"if not prop_path.exists():26 unmodified linesframes_out: List[Dict[str, Any]] = []for frame in data.get("frames", []):cameras = frame.get("cameras") or {}camera_previews = []for cam_name, cam in cameras.items():img = cam.get("image_path") if isinstance(cam, dict) else Nonecamera_previews.append({"name": cam_name,"image_path": img,"preview_url": _image_url(img) if img else None,"local_file": bool(img and not str(img).startswith("http")),})primary = next((c for c in camera_previews if c.get("preview_url")), None)fid = frame.get("frame_id", "")frames_out.append({1 unmodified line"timestamp_us": frame.get("timestamp_us"),"cameras": camera_previews,"preview_url": primary["preview_url"] if primary else None,"proposal_count": _proposal_count(sequence_id, fid),"gt_count": len(frame.get("ground_truth") or []),}24 unmodified linesraise FileNotFoundError(f"Frame {frame_id} not found in sequence {sequence_id}")cameras = frame.get("cameras") or {}camera_previews = []for cam_name, cam in cameras.items():img = cam.get("image_path") if isinstance(cam, dict) else Nonecamera_previews.append({"name": cam_name,"image_path": img,"preview_url": _image_url(img) if img else None,})proposals: Any = []prop_path = PIPELINE_ROOT / sequence_id / "proposals" / f"{frame_id}.json"10 unmodified lines"frame_id": frame_id,"frame": frame,"cameras": camera_previews,"proposals": proposals,"proposal_count": len(proposals) if isinstance(proposals, list) else 0,"proposals_path": str(prop_path) if prop_path.exists() else None,110 unmodified lines11111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314426 unmodified lines1711721731741751761771781791801811 unmodified line18318418518618718818924 unmodified lines21421521621721821922022122222310 unmodified lines234235236237238239240110 unmodified linesreturn f"/api/pipeline/file?path={quote(image_path, safe='')}"def _local_image_exists(image_path: Optional[str]) -> bool:if not image_path or str(image_path).startswith("http"):return Falseraw = Path(image_path)candidate = raw if raw.is_absolute() else Path.cwd() / rawtry:return candidate.is_file()except OSError:return Falsedef _camera_preview(cam_name: str, cam: Any) -> Dict[str, Any]:img = cam.get("image_path") if isinstance(cam, dict) else Noneexists = _local_image_exists(img) if img and not str(img).startswith("http") else bool(img)preview = _image_url(img) if img and exists else None# Remote http(s) URLs are treated as available for preview.if img and str(img).startswith("http"):preview = _image_url(img)exists = Truereturn {"name": cam_name,"image_path": img,"preview_url": preview,"local_file": bool(img and not str(img).startswith("http")),"available": bool(preview),}def _proposal_count(sequence_id: str, frame_id: str) -> int:prop_path = PIPELINE_ROOT / sequence_id / "proposals" / f"{frame_id}.json"if not prop_path.exists():26 unmodified linesframes_out: List[Dict[str, Any]] = []for frame in data.get("frames", []):cameras = frame.get("cameras") or {}camera_previews = [_camera_preview(cam_name, cam) for cam_name, cam in cameras.items()]primary = next((c for c in camera_previews if c.get("preview_url")), None)available_cams = [c for c in camera_previews if c.get("available")]fid = frame.get("frame_id", "")frames_out.append({1 unmodified line"timestamp_us": frame.get("timestamp_us"),"cameras": camera_previews,"preview_url": primary["preview_url"] if primary else None,"available_camera_count": len(available_cams),"proposal_count": _proposal_count(sequence_id, fid),"gt_count": len(frame.get("ground_truth") or []),}24 unmodified linesraise FileNotFoundError(f"Frame {frame_id} not found in sequence {sequence_id}")cameras = frame.get("cameras") or {}camera_previews = [_camera_preview(cam_name, cam) for cam_name, cam in cameras.items()]primary = next((c for c in camera_previews if c.get("preview_url")), None)proposals: Any = []prop_path = PIPELINE_ROOT / sequence_id / "proposals" / f"{frame_id}.json"10 unmodified lines"frame_id": frame_id,"frame": frame,"cameras": camera_previews,"preview_url": primary["preview_url"] if primary else None,"proposals": proposals,"proposal_count": len(proposals) if isinstance(proposals, list) else 0,"proposals_path": str(prop_path) if prop_path.exists() else None,
26 unmodified lines2728293031323334353626 unmodified linesconst SUGGESTIONS = ['What is Sensorflow Studio?','How do I load a dataset?','What is Strict Execution Mode?','How do pipeline stages work?','How do I get started?','Does help chat need a GPU?',];26 unmodified lines272829303132333435363726 unmodified linesconst SUGGESTIONS = ['What is Sensorflow Studio?','How do I get started?',"What's new?",'What version is this?','When do humans review labels?','What does the Command Center do?','Does help chat need a GPU?',];
1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545551 unmodified lines1071081091101111121131141159 unmodified lines12512612712812913013113213339 unmodified lines17317417517617717817942 unmodified lines2222232242252262272282292302312322332342352362372382 unmodified lines24124224324424524624724824925025141 unmodified lines29329429529629729829930030130230330430530630730830931031143 unmodified lines355356357358359360361362363364365366367368369370371372373374375376377102 unmodified lines4804814824834844854864874884894904914924934944954962 unmodified lines49950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453524 unmodified lines5605615625635645655665675685695705715725735745755765775785795805815825835 unmodified lines589590591592593594595596597598599600601602603604605606607608609610611140 unmodified lines752753754755756757758759760761762130 unmodified lines89389489589689789889990090174 unmodified lines97697797897998098198298398498598698798898999096 unmodified lines108710881089109010911092109312 unmodified lines110611071108110911101111111221 unmodified lines113411351136113711381139114013 unmodified lines115411551156115711581159116011611162116311641165116611671168116911701171280 unmodified lines1452145314541455145614571458508 unmodified lines19671968196919701971197219731974197576 unmodified lines20522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421459 unmodified lines21552156215721582159216021612162216321642165216621672168216910 unmodified lines21802181218221832184218515 unmodified lines2201220222032204220522066 unmodified lines22132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122529 unmodified lines22622263226422652266226733 unmodified lines23012302230323042305230612 unmodified lines23192320232123222323232423258 unmodified lines2334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235994 unmodified lines245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726981 unmodified line// API base URLconst API_BASE = '';// Non-blocking status signaling (replaces window.alert for routine feedback)const toastStack = document.getElementById('toast-stack');const TOAST_ICONS = { success: '✓', error: '✕', warning: '!', info: 'ℹ' };const TOAST_DEFAULT_MS = { success: 3800, info: 4200, warning: 5200, error: 6500 };function notify(message, type = 'info', options = {}) {if (!toastStack || message == null || message === '') return;const kind = ['success', 'error', 'warning', 'info'].includes(type) ? type : 'info';const duration = options.duration ?? TOAST_DEFAULT_MS[kind];const el = document.createElement('div');el.className = `toast toast-${kind}`;el.setAttribute('role', kind === 'error' ? 'alert' : 'status');const icon = document.createElement('span');icon.className = 'toast-icon';icon.textContent = TOAST_ICONS[kind];icon.setAttribute('aria-hidden', 'true');const body = document.createElement('div');body.className = 'toast-body';body.textContent = String(message);const close = document.createElement('button');close.type = 'button';close.className = 'toast-close';close.setAttribute('aria-label', 'Dismiss');close.textContent = '×';let hideTimer = null;const dismiss = () => {if (hideTimer) clearTimeout(hideTimer);el.classList.add('toast-out');setTimeout(() => el.remove(), 180);};close.addEventListener('click', dismiss);el.appendChild(icon);el.appendChild(body);el.appendChild(close);toastStack.appendChild(el);if (duration > 0) {hideTimer = setTimeout(dismiss, duration);}return dismiss;}// Stage Navigationconst navButtons = document.querySelectorAll('.nav-btn');const panels = document.querySelectorAll('.stage-panel');51 unmodified linesif (meta.completionOnly) {if (verdict === true) {badge.textContent = pipelineState.demo_stub ? 'STUB' : 'DONE';badge.style.background = pipelineState.demo_stub ? '#fbbf2433' : '#00ffaa33';badge.style.color = pipelineState.demo_stub ? '#fbbf24' : '#00ffaa';} else {badge.textContent = '';}9 unmodified linesbadge.style.background = '#ff444433';badge.style.color = '#ff4444';} else if (completed === true) {badge.textContent = 'RAN';badge.style.background = '#3b82f633';badge.style.color = '#93c5fd';} else {badge.textContent = '';}39 unmodified linesconst currentStage = document.querySelector('.nav-btn.active')?.dataset.stage;const meta = STAGE_METADATA[currentStage];if (meta && meta.gateKey && pipelineState[meta.gateKey] === false) {notify('Launch gate not passed. Complete the quality gate first.', 'warning');return;}switchStage(nextBtn.dataset.next);42 unmodified linessource_path: datasetSourcePath.value})});if (!res.ok) throw new Error(`HTTP ${res.status}`);const data = await res.json();notify('Configuration saved (YAML/paths not yet executed).', 'success');const cfgStatus = document.getElementById('config-exec-status');if (cfgStatus) {cfgStatus.textContent = 'CONFIGURATION SAVED / not yet used by an execution — run Load & Preprocess.';cfgStatus.dataset.modified = '1';}} catch (e) {console.error(e);notify('Failed to save dataset configuration.', 'error');}});2 unmodified linestry {const res = await fetch(`${API_BASE}/api/precheck`);const data = await res.json();const precheckType = data.verified ? 'success' : 'warning';notify(`Pre-check: ${data.status}\n${data.message || ''}`, precheckType);refreshScriptStatus(data.scripts);} catch (e) {notify('Failed to complete pre-check.', 'error');}});41 unmodified lines})});const data = await res.json();if (!res.ok) {terminalLogs.textContent += `Error: ${JSON.stringify(data)}\n`;resetTrainingUI();notify(data.detail?.message || data.detail || 'Failed to start training', 'error');return;}renderEvidenceCard('evidence-training', {status: 'RUNNING',execution_id: data.execution_id,process_id: data.process_id,command: data.command,message: 'Training process spawned',});pollTraining();trainInterval = setInterval(pollTraining, 1500);} catch (e) {43 unmodified lines}if (!status.running) {const verdict = status.status || (status.exit_code === 0 ? 'SUCCEEDED' : 'FAILED');terminalLogs.textContent += `\n--- Process finished: ${verdict} exit_code=${status.exit_code} ---\n`;renderEvidenceCard('evidence-training', {status: verdict,execution_id: status.execution_id,exit_code: status.exit_code,process_id: status.process_id,command: status.command,metrics: {epochs_observed: status.epochs_observed,epochs_requested: status.epochs_requested,checkpoint: status.checkpoint,losses_parsed: (status.losses || []).length,},message: `Training ${verdict}`,});refreshExecutionConsole();resetTrainingUI();}} catch (e) {102 unmodified lines})});const data = await res.json();if (!res.ok) {const detail = data.detail?.message || data.detail || JSON.stringify(data);notify(`Inference failed: ${detail}`, 'error');renderEvidenceCard('evidence-inference', {status: 'FAILED',execution_id: data.detail?.execution_id || data.execution_id,message: detail,});return;}selectInferImage.innerHTML = '';if (data.images && data.images.length > 0) {data.images.forEach(img => {2 unmodified linesopt.textContent = img;selectInferImage.appendChild(opt);});loadImage(data.images[0]);} else {selectInferImage.innerHTML = '<option value="">No images found</option>';}renderEvidenceCard('evidence-inference', {status: data.status,execution_id: data.execution_id,duration_ms: data.duration_ms,model: data.model,checkpoint: data.checkpoint,metrics: {discovered: data.records_discovered,processed: data.records_processed,succeeded: data.records_succeeded,failed: data.records_failed,inference_calls: data.inference_calls,predictions: data.predictions_generated,output_dir: data.output_dir,exit_code: data.exit_code,},message: data.message,});refreshExecutionConsole();if (data.status === 'SUCCEEDED' || data.status === 'PARTIAL_SUCCESS') {notify(`Inference ${data.status}: ${data.records_succeeded}/${data.records_discovered} images`, 'success');} else {notify(`Inference ${data.status}: ${data.message || 'see evidence'}`, 'warning');}} catch (e) {console.error(e);notify('Inference execution failed.', 'error');} finally {btnRunInfer.textContent = '⚡ Run Auto-Labeler';btnRunInfer.disabled = false;24 unmodified linestry {const res = await fetch(`${API_BASE}/api/grade`);const data = await res.json();if (!res.ok) {notify(data.detail?.message || data.detail || 'Grader failed', 'error');renderEvidenceCard('evidence-grader', {status: 'FAILED',execution_id: data.detail?.execution_id || data.execution_id,message: data.detail?.message || data.detail,});return;}graderScore.textContent = data.quality_score != null ? Number(data.quality_score).toFixed(1) : '—';statTotalImgs.textContent = data.total_images ?? '—';statTotalPreds.textContent = data.total_predictions ?? '—';graderIssuesList.innerHTML = '';if (data.status === 'NOT_EXECUTED') {graderIssuesList.innerHTML = '<div class="empty-state">NOT_EXECUTED — no predictions artifact. This is not a perfect score.</div>';} else if (data.issues && data.issues.length > 0) {data.issues.forEach(issue => {const el = document.createElement('div');el.className = `issue-card ${issue.severity.toLowerCase()}`;5 unmodified linesgraderIssuesList.appendChild(el);});} else {graderIssuesList.innerHTML = '<div class="empty-state">No quality anomalies reported by grader output (not a claim of ground-truth perfection).</div>';}renderEvidenceCard('evidence-grader', {status: data.status,execution_id: data.execution_id,duration_ms: data.duration_ms,metrics: data.metrics || {total_images: data.total_images,total_predictions: data.total_predictions,quality_score: data.quality_score,},message: data.message,});refreshExecutionConsole();} catch (e) {console.error(e);notify('Failed to run quality diagnostics.', 'error');} finally {btnRunGrader.textContent = 'Run Quality Diagnostics';btnRunGrader.disabled = false;140 unmodified linescurrentMitlData = data.data;originalCocText = currentMitlData.coc_trace;renderMitlData();notify(`Dataset loaded: ${currentMitlData.dataset}`, 'success');}} catch (e) {console.error(e);notify('Failed to load NVIDIA dataset.', 'error');}}130 unmodified lines}} catch (e) {console.error(e);const statusEl = document.getElementById('source-browse-status');if (statusEl) statusEl.textContent = 'Catalog metadata load failed.';notify('Catalog metadata load failed.', 'error');} finally {btnPreprocessDataset.textContent = 'Load Catalog Metadata';btnPreprocessDataset.disabled = false;74 unmodified lines});const data = await res.json();if (data.status === 'ok') {notify(`Pipeline configuration saved\nAnnotation: ${annotationTool}\nTraining: ${trainingFramework}\nValidation: ${validationMethod}`,'success');pipelineWizardModal.classList.add('hidden');}} catch (e) {console.error(e);notify('Failed to save pipeline configuration settings.', 'error');} finally {btnWizardSubmit.textContent = 'Save Pipeline Configuration';btnWizardSubmit.disabled = false;96 unmodified lines// Add Box HandlerbtnMitlAddBox.addEventListener('click', () => {if (!currentMitlData) {notify('Please load a dataset first.', 'warning');return;}const nextId = currentMitlData.annotations.length > 012 unmodified lines// Save Human EditsbtnMitlSave.addEventListener('click', async () => {if (!currentMitlData) {notify('No dataset currently loaded to save.', 'warning');return;}21 unmodified lines});if (parseError) {notify('Invalid bounding box format. Use coordinates [x, y, w, h].', 'error');return;}13 unmodified lines// Update local memorycurrentMitlData.annotations = updatedAnns;currentMitlData.coc_trace = mitlCocTrace.value;notify('Triage results saved to runs/mitl_annotations.json.', 'success');}} catch (e) {console.error(e);notify('Failed to save human edits.', 'error');}});// Ask Gemma 4 critiquebtnMitlAudit.addEventListener('click', async () => {if (!currentMitlData) {notify('No dataset currently loaded to audit.', 'warning');return;}280 unmodified lines}} catch (e) {console.error(e);notify('Failed to toggle MCP server state.', 'error');checkbox.checked = !checkbox.checked;bullet.style.transform = checkbox.checked ? 'translateX(22px)' : 'none';updateSliderStyle();508 unmodified lines}),});ssamState.selectedRow.manual_annotation = ssamDrawerAnnotation.value;notify(`Annotation saved for ${ssamState.selectedRow.street_name}`, 'success');} catch (e) {notify('Failed to save annotation.', 'error');} finally {ssamDrawerSave.textContent = 'Save Annotation';ssamDrawerSave.disabled = false;76 unmodified linesloadDatasetYaml();dataYamlPath.addEventListener('change', loadDatasetYaml);// --- HELP CHATBOT DRAWER (❓ FAB) ---const floatingHelpBtn = document.getElementById('floating-help-btn');const helpDrawer = document.getElementById('help-drawer');const closeDrawerBtn = document.getElementById('close-drawer-btn');const helpChatLog = document.getElementById('help-chat-log');const helpChatForm = document.getElementById('help-chat-form');const helpChatInput = document.getElementById('help-chat-input');const helpChatSend = document.getElementById('help-chat-send');let helpChatBusy = false;const isHelpOpen = () => helpDrawer && !helpDrawer.classList.contains('hidden');const setHelpOpen = (open) => {if (!helpDrawer || !floatingHelpBtn) return;helpDrawer.classList.toggle('hidden', !open);floatingHelpBtn.setAttribute('aria-expanded', open ? 'true' : 'false');if (open) {helpChatInput?.focus();}};const appendHelpMessage = (role, text, meta) => {if (!helpChatLog) return;const el = document.createElement('div');el.className = `help-chat-msg help-chat-${role === 'user' ? 'user' : 'bot'}`;el.style.cssText = role === 'user'? 'padding: 10px 12px; border-radius: 8px; background: rgba(0,200,150,0.12); border: 1px solid var(--border); font-size: 13px; color: #e6e9ec; line-height: 1.5; white-space: pre-wrap;': 'padding: 10px 12px; border-radius: 8px; background: #141a20; border: 1px solid var(--border); font-size: 13px; color: #e6e9ec; line-height: 1.5; white-space: pre-wrap;';el.textContent = text;if (meta) {const cap = document.createElement('div');cap.style.cssText = 'margin-top: 6px; font-size: 11px; color: var(--text-muted);';cap.textContent = meta;el.appendChild(cap);}helpChatLog.appendChild(el);helpChatLog.scrollTop = helpChatLog.scrollHeight;};const askHelpChat = async (raw) => {const question = (raw || '').trim();if (!question || helpChatBusy) return;helpChatBusy = true;if (helpChatSend) helpChatSend.disabled = true;appendHelpMessage('user', question);if (helpChatInput) helpChatInput.value = '';try {const res = await fetch(`${API_BASE}/api/help/chat`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ question }),});const data = await res.json().catch(() => ({}));if (!res.ok) {throw new Error(data.detail || data.message || `Help API ${res.status}`);}const provider = data.provider === 'faq_offline' ? 'local FAQ index' : (data.provider || 'help');const sources = Array.isArray(data.sources) && data.sources.length? `Sources: ${data.sources.map((s) => s.title).filter(Boolean).slice(0, 4).join(' · ')}`: null;appendHelpMessage('assistant', data.answer || 'No answer returned.', `via ${provider}${sources ? ` · ${sources}` : ''}`);} catch (err) {appendHelpMessage('assistant','Help API unreachable. Try again when the backend is up.\n\n'+ 'Quick tips:\n'+ '• Dataset Configuration → set YAML / source path → Save\n'+ '• Ingest & Fusion → run ingest → browse pipeline frames\n'+ '• Strict Execution Mode → Evidence cards / Execution Console (ledger under runs/executions/)',err instanceof Error ? err.message : String(err),);} finally {helpChatBusy = false;if (helpChatSend) helpChatSend.disabled = false;}};floatingHelpBtn?.addEventListener('click', () => setHelpOpen(!isHelpOpen()));closeDrawerBtn?.addEventListener('click', () => setHelpOpen(false));helpChatForm?.addEventListener('submit', (e) => {e.preventDefault();void askHelpChat(helpChatInput?.value || '');});document.querySelectorAll('.help-suggest-btn').forEach((btn) => {btn.addEventListener('click', () => {setHelpOpen(true);void askHelpChat(btn.getAttribute('data-q') || btn.textContent || '');});});// Populate initial default dataset if loaded9 unmodified linesconst btnLaunchGateRun = document.getElementById('btn-launch-gate-run');if (btnIngestRun) {btnIngestRun.addEventListener('click', async () => {const vendors = [];if (document.getElementById('ingest-vendor-local')?.checked) vendors.push('local');if (document.getElementById('ingest-vendor-alpamayo')?.checked) vendors.push('alpamayo');if (document.getElementById('ingest-vendor-waymo')?.checked) vendors.push('waymo');if (document.getElementById('ingest-vendor-a2d2')?.checked) vendors.push('a2d2');if (!vendors.length) {document.getElementById('ingest-status').textContent ='Select at least one vendor (Local for real sequences, or Alpamayo/Waymo/A2D2 demo stubs).';return;}currentSequenceId = document.getElementById('ingest-sequence-id')?.value || 'seq_001';10 unmodified linesheaders: { 'Content-Type': 'application/json' },body: JSON.stringify({vendors,sequence_id: currentSequenceId,source_path: sourcePath,max_frames: Number.isFinite(maxFrames) ? maxFrames : undefined,15 unmodified lines});}if (btnPerceptionRun) {btnPerceptionRun.addEventListener('click', async () => {const statusEl = document.getElementById('perception-status');6 unmodified linessequence_id: currentSequenceId,sam_checkpoint: document.getElementById('perception-sam-checkpoint')?.value || 'models/sam_vit_b.pth',device: document.getElementById('perception-device')?.value || 'cpu',no_sam: !!document.getElementById('perception-no-sam')?.checked,}),});const data = await res.json();if (!res.ok) {statusEl.textContent = `Error: ${data.detail?.message || data.detail || JSON.stringify(data)}`;renderEvidenceCard('evidence-perception', {status: 'FAILED',execution_id: data.detail?.execution_id || data.execution_id,message: data.detail?.message || data.detail,});} else {const stubPrefix = data.demo_stub ? 'demo stub: ' : '';const expected = data.frames_expected != null ? `/${data.frames_expected}` : '';statusEl.textContent =`${data.status}: ${stubPrefix}Processed ${data.frames_processed}${expected} frames → ${data.proposals_dir}`;renderEvidenceCard('evidence-perception', {status: data.status,execution_id: data.execution_id,duration_ms: data.duration_ms,model: data.model,checkpoint: data.checkpoint,metrics: {frames_processed: data.frames_processed,frames_expected: data.frames_expected,predictions_generated: data.predictions_generated,inference_calls: data.inference_calls,sam_ran: data.sam_ran,output_dir: data.proposals_dir,},message: data.message,events: data.events,});refreshExecutionConsole();}await refreshPipelineStatus();await refreshAllOutputBrowsers();9 unmodified linesconst frameList = root.querySelector('.out-frame-list');const summary = root.querySelector('.out-summary');const previewImg = root.querySelector('.out-preview-img');const previewMeta = root.querySelector('.out-preview-meta');const proposalsPre = root.querySelector('.out-proposals-json');const refreshBtn = root.querySelector('.out-refresh-btn');33 unmodified linesif (summary) summary.textContent = `Loading ${seqId}…`;frameList.innerHTML = '';previewImg.style.display = 'none';proposalsPre.style.display = 'none';previewMeta.textContent = 'No frame selected.';try {12 unmodified linesconst btn = document.createElement('button');btn.type = 'button';btn.className = 'out-frame-item';btn.innerHTML = `<div>${frame.frame_id}</div><div class="muted">${frame.proposal_count} proposals · ${frame.cameras?.length || 0} cam</div>`;btn.addEventListener('click', () => {frameList.querySelectorAll('.out-frame-item').forEach((el) => el.classList.remove('active'));btn.classList.add('active');8 unmodified linesasync function showFrame(seqId, frameSummary) {previewMeta.textContent = `Loading ${frameSummary.frame_id}…`;try {const res = await fetch(`${API_BASE}/api/pipeline/frame?sequence_id=${encodeURIComponent(seqId)}&frame_id=${encodeURIComponent(frameSummary.frame_id)}`);const data = await res.json();const url = (data.cameras || []).find((c) => c.preview_url)?.preview_url || frameSummary.preview_url;if (url) {previewImg.src = url;previewImg.style.display = 'block';} else {previewImg.style.display = 'none';}previewMeta.textContent =`${data.frame_id} · ${data.proposal_count} proposals` +(data.proposals_path ? ` · ${data.proposals_path}` : ' · no proposals yet');if (data.proposals && (Array.isArray(data.proposals) ? data.proposals.length : true)) {proposalsPre.style.display = 'block';proposalsPre.textContent = JSON.stringify(data.proposals, null, 2);} else {proposalsPre.style.display = 'block';proposalsPre.textContent = '// No proposals for this frame yet. Run Auto-Label.';}} catch (e) {94 unmodified lines}});}// --- Execution integrity: evidence cards, console, strict mode, load ---function esc(s) {return String(s ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');}function renderEvidenceCard(elementId, evidence) {const el = document.getElementById(elementId);if (!el || !evidence) return;const status = evidence.status || 'NOT_EXECUTED';const metrics = evidence.metrics || {};const metricRows = Object.entries(metrics).map(([k, v]) => {const val = typeof v === 'object' ? JSON.stringify(v) : v;return `<div class="ev-row"><span>${esc(k)}</span><strong>${esc(val)}</strong></div>`;}).join('');const events = (evidence.events || []).slice(-8).map(ev =>`<li><code>${esc(ev.ts || '')}</code> ${esc(ev.kind || '')}: ${esc(ev.message || '')}</li>`).join('');const ckpt = evidence.checkpoint? `<div class="ev-row"><span>checkpoint</span><strong>${esc(evidence.checkpoint.path || evidence.checkpoint)} ${evidence.checkpoint.exists === false ? '(missing)' : ''}</strong></div>`: '';el.innerHTML = `<h4>What actually happened?</h4><div class="ev-status ev-status-${esc(status)}">${esc(status)}</div><div class="ev-row"><span>execution_id</span><strong class="font-mono">${esc(evidence.execution_id || '—')}</strong></div>${evidence.duration_ms != null ? `<div class="ev-row"><span>duration_ms</span><strong>${esc(evidence.duration_ms)}</strong></div>` : ''}${evidence.model ? `<div class="ev-row"><span>model</span><strong>${esc(evidence.model)}</strong></div>` : ''}${ckpt}${evidence.process_id != null ? `<div class="ev-row"><span>process_id</span><strong>${esc(evidence.process_id)}</strong></div>` : ''}${evidence.exit_code != null ? `<div class="ev-row"><span>exit_code</span><strong>${esc(evidence.exit_code)}</strong></div>` : ''}${evidence.command ? `<div class="ev-row"><span>command</span><strong class="font-mono">${esc(Array.isArray(evidence.command) ? evidence.command.join(' ') : evidence.command)}</strong></div>` : ''}${metricRows}${evidence.message ? `<p class="ev-msg">${esc(evidence.message)}</p>` : ''}${evidence.execution_id ? `<a class="ev-log-link" href="/api/executions/${encodeURIComponent(evidence.execution_id)}/log" target="_blank" rel="noopener">Open execution log</a>` : ''}${events ? `<details class="ev-timeline"><summary>Event timeline</summary><ul>${events}</ul></details>` : ''}`;}function refreshScriptStatus(scripts) {const map = {'train.py': 'script-status-train','infer.py': 'script-status-infer','autograder.py': 'script-status-grader',};Object.entries(map).forEach(([name, id]) => {const el = document.getElementById(id);const r = scripts?.[name];if (!el || !r) return;if (!r.exists) {el.textContent = `Missing (${name})`;el.className = 'val font-mono';el.style.color = '#ff8888';} else if (r.syntax_valid && r.dry_run_ok) {el.textContent = `Verified (${name})${r.last_status ? ' · last ' + r.last_status : ''}`;el.className = 'val font-mono green';el.style.color = '';} else {el.textContent = `Found but unverified (${name})`;el.className = 'val font-mono';el.style.color = '#fbbf24';}});}async function refreshHealth() {try {const res = await fetch(`${API_BASE}/api/health`);const data = await res.json();const chip = document.getElementById('health-status-chip');if (chip) {chip.textContent = [data.filesystem_writable ? 'FS writable' : 'FS FAIL',data.torch_installed ? 'torch' : 'no-torch',data.ultralytics_installed ? 'yolo' : 'no-yolo',data.gpu?.available ? `GPU:${data.gpu.name}` : 'CPU',data.last_successful_execution_id ? `last:${data.last_successful_execution_id}` : 'no-success-yet',].join(' · ');}if (data.scripts) refreshScriptStatus(data.scripts);const tog = document.getElementById('toggle-strict-mode');if (tog) tog.checked = !!data.strict_mode;} catch (e) {const chip = document.getElementById('health-status-chip');if (chip) chip.textContent = 'Backend unreachable';}}async function refreshExecutionConsole() {const list = document.getElementById('exec-console-list');if (!list) return;try {const res = await fetch(`${API_BASE}/api/executions?limit=40`);const data = await res.json();const rows = data.executions || [];if (!rows.length) {list.innerHTML = '<p class="evidence-empty">No executions recorded yet.</p>';return;}list.innerHTML = rows.map(e => `<button type="button" class="exec-row" data-id="${esc(e.execution_id)}"><span class="ev-status ev-status-${esc(e.status)}">${esc(e.status)}</span><span class="font-mono">${esc(e.execution_id)}</span><span>${esc(e.operation)}</span><span>${esc(e.duration_ms != null ? e.duration_ms + 'ms' : '—')}</span><span>${e.verified ? 'verified' : 'unverified'}</span></button>`).join('');list.querySelectorAll('.exec-row').forEach(btn => {btn.addEventListener('click', async () => {const detail = document.getElementById('exec-console-detail');const r = await fetch(`${API_BASE}/api/executions/${encodeURIComponent(btn.dataset.id)}`);const full = await r.json();detail.classList.remove('hidden');detail.innerHTML = `<pre>${esc(JSON.stringify(full, null, 2))}</pre>`;});});} catch (e) {list.innerHTML = `<p class="evidence-empty">Failed to load executions: ${esc(e.message)}</p>`;}}const btnLoadPreprocess = document.getElementById('btn-load-preprocess');if (btnLoadPreprocess) {btnLoadPreprocess.addEventListener('click', async () => {btnLoadPreprocess.disabled = true;btnLoadPreprocess.textContent = 'Loading…';const statusEl = document.getElementById('source-browse-status');try {const res = await fetch(`${API_BASE}/api/dataset/load`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({source_path: datasetSourcePath?.value || 'data',yaml_path: dataYamlPath?.value || 'coco8.yaml',dataset_type: selectDatasetType?.value || 'local',}),});const data = await res.json();const m = data.metrics || {};if (statusEl) {statusEl.textContent = `${data.status}: discovered=${m.images_discovered ?? 0} readable=${m.images_readable ?? 0} corrupt=${m.images_corrupt ?? 0} → ${data.manifest_path || ''}`;}renderEvidenceCard('evidence-dataset', {status: data.status,execution_id: data.execution_id,duration_ms: data.duration_ms,metrics: {...m,reconciliation: data.reconciliation?.state,manifest: data.manifest_path,},message: data.message,events: data.events,});const badge = document.getElementById('ds-meta-badge');const loadedEl = document.getElementById('ds-kpi-loaded-rows');const pctEl = document.getElementById('ds-kpi-ingest-pct');if (loadedEl) loadedEl.textContent = m.images_readable ?? 0;if (pctEl) pctEl.textContent = m.loaded_pct_of_discovered != null ? `${m.loaded_pct_of_discovered}% of discovered` : '—';if (badge) {if (data.status === 'FAILED' || (m.images_readable ?? 0) === 0) {badge.textContent = 'FAILED — 0 loaded';badge.style.background = 'rgba(255, 68, 68, 0.12)';badge.style.color = '#ff8888';} else {badge.textContent = `${m.images_readable} loaded (evidence)`;badge.style.background = 'rgba(0, 255, 170, 0.15)';badge.style.color = '#00ffaa';}}const cfgStatus = document.getElementById('config-exec-status');if (cfgStatus) {cfgStatus.textContent = `used_by_execution YES · last execution_id ${data.execution_id}`;cfgStatus.dataset.modified = '0';}refreshExecutionConsole();if (data.status === 'FAILED' || data.status === 'VALIDATION_FAILED') {notify(data.message || 'Load failed', 'error');} else if (data.status === 'PARTIAL_SUCCESS') {notify(data.message || 'Partial load', 'warning');} else {notify(data.message || 'Load complete', 'success');}} catch (e) {if (statusEl) statusEl.textContent = `Load failed: ${e.message}`;notify('Load & Preprocess failed.', 'error');} finally {btnLoadPreprocess.disabled = false;btnLoadPreprocess.textContent = 'Load & Preprocess';}});}const btnYamlValidate = document.getElementById('btn-yaml-validate');if (btnYamlValidate) {btnYamlValidate.addEventListener('click', async () => {try {const res = await fetch(`${API_BASE}/api/yaml/validate`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ path: dataYamlPath?.value || 'coco8.yaml' }),});const data = await res.json();notify(`${data.status}: classes=${data.class_count} images=${JSON.stringify(data.image_counts)}`, data.status === 'SUCCEEDED' ? 'success' : 'warning');const cfgStatus = document.getElementById('config-exec-status');if (cfgStatus) {cfgStatus.textContent = `YAML hash ${data.content_hash || '—'} · ${data.status} · execution ${data.execution_id || '—'}`;}refreshExecutionConsole();} catch (e) {notify(`YAML validate failed: ${e.message}`, 'error');}});}document.getElementById('btn-open-exec-console')?.addEventListener('click', () => {document.getElementById('exec-console-modal')?.classList.remove('hidden');refreshExecutionConsole();});document.getElementById('btn-close-exec-console')?.addEventListener('click', () => {document.getElementById('exec-console-modal')?.classList.add('hidden');});document.getElementById('btn-refresh-executions')?.addEventListener('click', refreshExecutionConsole);document.getElementById('btn-health-check')?.addEventListener('click', async () => {await refreshHealth();notify('Health refreshed — see Workspace Status chip.', 'info');});document.getElementById('toggle-strict-mode')?.addEventListener('change', async (e) => {try {await fetch(`${API_BASE}/api/strict-mode`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ enabled: e.target.checked }),});notify(e.target.checked ? 'Strict Execution Mode ON' : 'Strict Execution Mode OFF', 'info');} catch (err) {notify('Failed to toggle strict mode', 'error');}});refreshHealth();});1 unmodified line23456751 unmodified lines5960616263646566679 unmodified lines7778798081828384858639 unmodified lines12612712812913013113242 unmodified lines1751761771781791801811821831841852 unmodified lines18818919019119219319419519641 unmodified lines23823924024124224324424543 unmodified lines289290291292293294295102 unmodified lines3983994004014024034044052 unmodified lines40840941041141241341441541641741841942042142224 unmodified lines4474484494504514524534544554564574584594605 unmodified lines466467468469470471472473474475476140 unmodified lines617618619620621622623624625626627130 unmodified lines75875976076176276376474 unmodified lines83984084184284384484584684784884985096 unmodified lines94794894995095195295312 unmodified lines96696796896997097197221 unmodified lines994995996997998999100013 unmodified lines101410151016101710181019102010211022102310241025102610271028102910301031280 unmodified lines1312131313141315131613171318508 unmodified lines18271828182918301831183218331834183576 unmodified lines1912191319141915191619171918191919201921192219231924192519261927192819291930193119329 unmodified lines1942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198510 unmodified lines199619971998199920002001200215 unmodified lines2018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620776 unmodified lines208420852086208720882089209020912092209320942095209620972098209921009 unmodified lines211021112112211321142115211633 unmodified lines2150215121522153215421552156215712 unmodified lines217021712172217321742175217621778 unmodified lines21862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223394 unmodified lines23282329233023311 unmodified line// API base URLconst API_BASE = '';// Stage Navigationconst navButtons = document.querySelectorAll('.nav-btn');const panels = document.querySelectorAll('.stage-panel');51 unmodified linesif (meta.completionOnly) {if (verdict === true) {badge.textContent = 'PASS';badge.style.background = '#00ffaa33';badge.style.color = '#00ffaa';} else {badge.textContent = '';}9 unmodified linesbadge.style.background = '#ff444433';badge.style.color = '#ff4444';} else if (completed === true) {// Ran stage artifact exists but no explicit pass/fail yetbadge.textContent = 'PASS';badge.style.background = '#00ffaa33';badge.style.color = '#00ffaa';} else {badge.textContent = '';}39 unmodified linesconst currentStage = document.querySelector('.nav-btn.active')?.dataset.stage;const meta = STAGE_METADATA[currentStage];if (meta && meta.gateKey && pipelineState[meta.gateKey] === false) {alert('Launch gate not passed. Complete the quality gate first.');return;}switchStage(nextBtn.dataset.next);42 unmodified linessource_path: datasetSourcePath.value})});const data = await res.json();alert('Configuration saved & verified successfully!');} catch (e) {console.error(e);alert('Failed to save dataset configuration.');}});2 unmodified linestry {const res = await fetch(`${API_BASE}/api/precheck`);const data = await res.json();alert(`Pre-Check Complete!\n\nStatus: ${data.status}\nDetails: ${data.message}`);} catch (e) {alert('Failed to complete pre-check.');}});41 unmodified lines})});const data = await res.json();// Start polling logs and statuspollTraining();trainInterval = setInterval(pollTraining, 1500);} catch (e) {43 unmodified lines}if (!status.running) {terminalLogs.textContent += '\n--- Process finished ---\n';resetTrainingUI();}} catch (e) {102 unmodified lines})});const data = await res.json();// Populate select dropdownselectInferImage.innerHTML = '';if (data.images && data.images.length > 0) {data.images.forEach(img => {2 unmodified linesopt.textContent = img;selectInferImage.appendChild(opt);});// Trigger image loadloadImage(data.images[0]);} else {selectInferImage.innerHTML = '<option value="">No images found</option>';}alert('Inference finished successfully!');} catch (e) {console.error(e);alert('Inference execution failed.');} finally {btnRunInfer.textContent = '⚡ Run Auto-Labeler';btnRunInfer.disabled = false;24 unmodified linestry {const res = await fetch(`${API_BASE}/api/grade`);const data = await res.json();graderScore.textContent = data.quality_score.toFixed(1);statTotalImgs.textContent = data.total_images;statTotalPreds.textContent = data.total_predictions;// Render issues listgraderIssuesList.innerHTML = '';if (data.issues && data.issues.length > 0) {data.issues.forEach(issue => {const el = document.createElement('div');el.className = `issue-card ${issue.severity.toLowerCase()}`;5 unmodified linesgraderIssuesList.appendChild(el);});} else {graderIssuesList.innerHTML = '<div class="empty-state">✅ Perfect score! No quality anomalies detected.</div>';}} catch (e) {console.error(e);alert('Failed to run quality diagnostics.');} finally {btnRunGrader.textContent = 'Run Quality Diagnostics';btnRunGrader.disabled = false;140 unmodified linescurrentMitlData = data.data;originalCocText = currentMitlData.coc_trace;renderMitlData();alert(`Dataset loaded successfully: ${currentMitlData.dataset}`);}} catch (e) {console.error(e);alert('Failed to load NVIDIA dataset.');}}130 unmodified lines}} catch (e) {console.error(e);alert('Catalog metadata load failed.');} finally {btnPreprocessDataset.textContent = 'Load Catalog Metadata';btnPreprocessDataset.disabled = false;74 unmodified lines});const data = await res.json();if (data.status === 'ok') {alert(`Pipeline configuration saved!\n\n- Annotation: ${annotationTool}\n- Training: ${trainingFramework}\n- Validation: ${validationMethod}`);pipelineWizardModal.classList.add('hidden');}} catch (e) {console.error(e);alert('Failed to save pipeline configuration settings.');} finally {btnWizardSubmit.textContent = 'Save Pipeline Configuration';btnWizardSubmit.disabled = false;96 unmodified lines// Add Box HandlerbtnMitlAddBox.addEventListener('click', () => {if (!currentMitlData) {alert('Please load a dataset first.');return;}const nextId = currentMitlData.annotations.length > 012 unmodified lines// Save Human EditsbtnMitlSave.addEventListener('click', async () => {if (!currentMitlData) {alert('No dataset currently loaded to save.');return;}21 unmodified lines});if (parseError) {alert('Invalid bounding box format. Please enter coordinates in format [x, y, w, h].');return;}13 unmodified lines// Update local memorycurrentMitlData.annotations = updatedAnns;currentMitlData.coc_trace = mitlCocTrace.value;alert('Triage results successfully saved to runs/mitl_annotations.json!');}} catch (e) {console.error(e);alert('Failed to save human edits.');}});// Ask Gemma 4 critiquebtnMitlAudit.addEventListener('click', async () => {if (!currentMitlData) {alert('No dataset currently loaded to audit.');return;}280 unmodified lines}} catch (e) {console.error(e);alert("Failed to toggle MCP server state.");checkbox.checked = !checkbox.checked;bullet.style.transform = checkbox.checked ? 'translateX(22px)' : 'none';updateSliderStyle();508 unmodified lines}),});ssamState.selectedRow.manual_annotation = ssamDrawerAnnotation.value;alert(`Annotation saved for ${ssamState.selectedRow.street_name}`);} catch (e) {alert('Failed to save annotation.');} finally {ssamDrawerSave.textContent = 'Save Annotation';ssamDrawerSave.disabled = false;76 unmodified linesloadDatasetYaml();dataYamlPath.addEventListener('change', loadDatasetYaml);// --- ONSCREEN GUIDANCE DRAWER ---const floatingHelpBtn = document.getElementById('floating-help-btn');const helpDrawer = document.getElementById('help-drawer');const closeDrawerBtn = document.getElementById('close-drawer-btn');floatingHelpBtn.addEventListener('click', () => {if (helpDrawer.style.right === '0px') {helpDrawer.style.right = '-400px';} else {helpDrawer.style.right = '0px';}});closeDrawerBtn.addEventListener('click', () => {helpDrawer.style.right = '-400px';});// Populate initial default dataset if loaded9 unmodified linesconst btnLaunchGateRun = document.getElementById('btn-launch-gate-run');if (btnIngestRun) {const vendorIds = ['ingest-vendor-local','ingest-vendor-alpamayo','ingest-vendor-waymo','ingest-vendor-a2d2',];const mixToggle = document.getElementById('ingest-mix-vendors');function enforceSingleVendor(changedId) {if (mixToggle?.checked) return;const changed = document.getElementById(changedId);if (!changed?.checked) return;vendorIds.forEach((id) => {if (id === changedId) return;const el = document.getElementById(id);if (el) el.checked = false;});}vendorIds.forEach((id) => {document.getElementById(id)?.addEventListener('change', () => enforceSingleVendor(id));});btnIngestRun.addEventListener('click', async () => {const vendors = [];if (document.getElementById('ingest-vendor-local')?.checked) vendors.push('local');if (document.getElementById('ingest-vendor-alpamayo')?.checked) vendors.push('alpamayo');if (document.getElementById('ingest-vendor-waymo')?.checked) vendors.push('waymo');if (document.getElementById('ingest-vendor-a2d2')?.checked) vendors.push('a2d2');const allowMix = !!mixToggle?.checked;if (!vendors.length) {document.getElementById('ingest-status').textContent ='Select at least one vendor (Local for real sequences, or one Alpamayo/Waymo/A2D2 demo stub).';return;}if (vendors.length > 1 && !allowMix) {document.getElementById('ingest-status').textContent ='Multiple vendors selected. Enable “Mix vendors” or keep a single dataset selected.';return;}currentSequenceId = document.getElementById('ingest-sequence-id')?.value || 'seq_001';10 unmodified linesheaders: { 'Content-Type': 'application/json' },body: JSON.stringify({vendors,allow_mix: allowMix,sequence_id: currentSequenceId,source_path: sourcePath,max_frames: Number.isFinite(maxFrames) ? maxFrames : undefined,15 unmodified lines});}const btnLoadAllDatasets = document.getElementById('btn-load-all-datasets');if (btnLoadAllDatasets) {btnLoadAllDatasets.addEventListener('click', async () => {const statusEl = document.getElementById('ingest-status');const prefix = document.getElementById('ingest-sequence-id')?.value || 'seq_001';const sourcePath = document.getElementById('ingest-source-path')?.value|| document.getElementById('dataset-source-path')?.value || 'data';const maxFramesRaw = document.getElementById('ingest-max-frames')?.value;const maxFrames = maxFramesRaw ? Number(maxFramesRaw) : undefined;const allowStub = !!document.getElementById('ingest-allow-stub')?.checked;const vendors = [];if (document.getElementById('ingest-vendor-local')?.checked) vendors.push('local');if (document.getElementById('ingest-vendor-alpamayo')?.checked) vendors.push('alpamayo');if (document.getElementById('ingest-vendor-waymo')?.checked) vendors.push('waymo');if (document.getElementById('ingest-vendor-a2d2')?.checked) vendors.push('a2d2');// Load-all defaults to all four when nothing selected so "all datasets" means all.const body = {sequence_prefix: prefix,vendors: vendors.length ? vendors : ['local', 'alpamayo', 'waymo', 'a2d2'],source_path: sourcePath,waymo_root: document.getElementById('ingest-waymo-root')?.value || undefined,alpamayo_root: document.getElementById('ingest-alpamayo-root')?.value || undefined,a2d2_root: document.getElementById('ingest-a2d2-root')?.value || undefined,allow_stub: allowStub,max_frames: Number.isFinite(maxFrames) ? maxFrames : undefined,};statusEl.textContent = 'Loading configured datasets into pipeline runs…';try {const res = await fetch(`${API_BASE}/api/dataset/load-all`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(body),});const data = await res.json();if (!res.ok) {statusEl.textContent = `Error: ${data.detail || JSON.stringify(data)}`;return;}const lines = (data.results || []).map((r) => {const tag = r.status === 'ok'? (r.demo_stub ? 'STUB' : 'LOADED'): 'NOT_EXECUTED';return `${tag} ${r.vendor}: ${r.frames || 0} frames → ${r.sequence_id || '—'} (${r.message || ''})`;});if (data.active_sequence_id) currentSequenceId = data.active_sequence_id;statusEl.textContent = `${data.message || data.status}\n${lines.join('\n')}`;await refreshPipelineStatus();await refreshAllOutputBrowsers();} catch (e) {statusEl.textContent = `Error: ${e.message}`;}});}if (btnPerceptionRun) {btnPerceptionRun.addEventListener('click', async () => {const statusEl = document.getElementById('perception-status');6 unmodified linessequence_id: currentSequenceId,sam_checkpoint: document.getElementById('perception-sam-checkpoint')?.value || 'models/sam_vit_b.pth',device: document.getElementById('perception-device')?.value || 'cpu',no_sam: true,}),});const data = await res.json();if (data.status === 'ok') {const stubPrefix = data.demo_stub ? 'demo stub: ' : '';const expected = data.frames_expected != null ? `/${data.frames_expected}` : '';statusEl.textContent =`${stubPrefix}Processed ${data.frames_processed}${expected} frames -> ${data.proposals_dir}`;} else {statusEl.textContent = `Error: ${data.detail || JSON.stringify(data)}`;}await refreshPipelineStatus();await refreshAllOutputBrowsers();9 unmodified linesconst frameList = root.querySelector('.out-frame-list');const summary = root.querySelector('.out-summary');const previewImg = root.querySelector('.out-preview-img');const cameraEmpty = root.querySelector('.out-camera-empty');const previewMeta = root.querySelector('.out-preview-meta');const proposalsPre = root.querySelector('.out-proposals-json');const refreshBtn = root.querySelector('.out-refresh-btn');33 unmodified linesif (summary) summary.textContent = `Loading ${seqId}…`;frameList.innerHTML = '';previewImg.style.display = 'none';previewImg.removeAttribute('src');if (cameraEmpty) cameraEmpty.style.display = 'none';proposalsPre.style.display = 'none';previewMeta.textContent = 'No frame selected.';try {12 unmodified linesconst btn = document.createElement('button');btn.type = 'button';btn.className = 'out-frame-item';const camCount = frame.available_camera_count ?? frame.cameras?.filter((c) => c.preview_url || c.available)?.length ?? frame.cameras?.length ?? 0;btn.innerHTML = `<div>${frame.frame_id}</div><div class="muted">${frame.proposal_count} proposals · ${camCount} cam</div>`;btn.addEventListener('click', () => {frameList.querySelectorAll('.out-frame-item').forEach((el) => el.classList.remove('active'));btn.classList.add('active');8 unmodified linesasync function showFrame(seqId, frameSummary) {previewMeta.textContent = `Loading ${frameSummary.frame_id}…`;previewImg.style.display = 'none';previewImg.removeAttribute('src');if (cameraEmpty) cameraEmpty.style.display = 'none';try {const res = await fetch(`${API_BASE}/api/pipeline/frame?sequence_id=${encodeURIComponent(seqId)}&frame_id=${encodeURIComponent(frameSummary.frame_id)}`);const data = await res.json();// Camera image is primary; proposals (or lack thereof) never hide it.const url =data.preview_url ||(data.cameras || []).find((c) => c.preview_url)?.preview_url ||frameSummary.preview_url;if (url) {previewImg.onload = () => {previewImg.style.display = 'block';if (cameraEmpty) cameraEmpty.style.display = 'none';};previewImg.onerror = () => {previewImg.style.display = 'none';if (cameraEmpty) {cameraEmpty.textContent = 'Camera path present but image failed to load.';cameraEmpty.style.display = 'block';}};previewImg.src = url.startsWith('http') || url.startsWith('/')? url: `${API_BASE}${url}`;// Show immediately; onload still confirms.previewImg.style.display = 'block';} else if (cameraEmpty) {cameraEmpty.textContent = 'No camera image for this frame.';cameraEmpty.style.display = 'block';}previewMeta.textContent =`${data.frame_id} · ${data.proposal_count} proposals` +(data.proposals_path ? ` · ${data.proposals_path}` : ' · no proposals yet');// Proposals JSON is secondary — always show status, never replace the camera.proposalsPre.style.display = 'block';if (data.proposals && (Array.isArray(data.proposals) ? data.proposals.length : true)) {proposalsPre.textContent = JSON.stringify(data.proposals, null, 2);} else {proposalsPre.textContent = '// No proposals for this frame yet. Run Auto-Label.';}} catch (e) {94 unmodified lines}});}});
101 unmodified lines10210310410510610710810911011111211332 unmodified lines1461471481491501511521531541551561571581591601611621635 unmodified lines16917017117217317417517617717817918018118218318418518618791 unmodified lines27928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830913 unmodified lines32332432532632732832916 unmodified lines34634734834935035135235335435535635735835936013 unmodified lines3743753763773783793808 unmodified lines3893903913923933943953963973985 unmodified lines404405406407408409410411412413113 unmodified lines52752852953053153253353453553634 unmodified lines57157257357457557657757857958035 unmodified lines616617618619620621622623624625429 unmodified lines1055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100101 unmodified lines<h2 id="stage-title">Dataset Configuration</h2><p id="stage-desc">Prepare and validate your image source path and annotation files.</p></div><div class="controls-area" style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;"><label class="strict-mode-toggle" title="Refuse SUCCEEDED unless process, exit, outputs, metrics, and execution_id are verified"><input type="checkbox" id="toggle-strict-mode"> Strict Execution</label><button class="btn btn-secondary" id="btn-open-exec-console" title="Global execution history">Execution Console</button><button class="btn btn-secondary" id="btn-health-check" title="Meaningful backend health">Health</button><button class="btn btn-secondary" id="btn-validate">Run Pre-Check</button><button class="btn btn-primary" id="btn-global-action">Proceed to Model</button></div>32 unmodified lines</div><div class="actions-row" style="display: flex; gap: 12px; flex-wrap: wrap;"><button class="btn btn-primary" id="btn-save-dataset">Save Config</button><button class="btn btn-primary" id="btn-load-preprocess" title="Real discovery/decode/validation with ledger evidence">Load & Preprocess</button><button class="btn btn-secondary" id="btn-preprocess-dataset">Load Catalog Metadata</button><button class="btn btn-secondary" id="btn-browse-source" title="List and preview images under Images Path">Validate & Browse Images Path</button><button class="btn btn-secondary" id="btn-yaml-validate" title="Semantic YAML path/class validation">Validate YAML</button></div><div id="config-exec-status" class="config-exec-status" style="margin-top:10px;font-size:12px;color:var(--text-muted);"></div><div id="source-browse-status" class="status-box" style="margin-top:12px;"></div><div id="source-browse-gallery" class="output-browse-gallery" style="margin-top:12px;"></div><div class="evidence-card" id="evidence-dataset" data-stage="dataset"><h4>What actually happened?</h4><p class="evidence-empty">No execution yet — Load & Preprocess to generate verifiable evidence.</p></div></div><div class="card card-glass">5 unmodified lines</div><div class="info-row"><span class="lbl">Train script:</span><span class="val font-mono" id="script-status-train">Verifying…</span></div><div class="info-row"><span class="lbl">Infer script:</span><span class="val font-mono" id="script-status-infer">Verifying…</span></div><div class="info-row"><span class="lbl">Auto-Grader script:</span><span class="val font-mono" id="script-status-grader">Verifying…</span></div><div class="info-row"><span class="lbl">Backend health:</span><span class="val font-mono" id="health-status-chip">—</span></div></div></div>91 unmodified lines<section class="stage-panel" id="panel-ingest"><div class="card card-glass"><h3>Exabyte Ingest, Fusion & Stratification</h3><p class="text-muted">Fuse Alpamayo, Waymo, and Audi A2D2 (and/or local frames/video) into a UnifiedSequence. Vendor checkboxes without a full lake use demo stubs (~3 frames each), not full AV lakes.</p><div class="form-group"><label>Vendors</label><div style="display:flex;gap:12px;flex-wrap:wrap;"><label title="Load frames from Dataset Configuration Images Path"><input type="checkbox" id="ingest-vendor-local"> Local frames / video</label><label title="NVIDIA Alpamayo (Physical AI AV Dataset)"><input type="checkbox" id="ingest-vendor-alpamayo" checked> Alpamayo (demo stub)</label><label title="Waymo Open Dataset"><input type="checkbox" id="ingest-vendor-waymo" checked> Waymo (demo stub)</label><label title="Audi A2D2 (Audi Autonomous Driving Dataset)"><input type="checkbox" id="ingest-vendor-a2d2" checked> Audi A2D2 (demo stub)</label></div></div><div class="form-group"><label for="ingest-source-path">Local source path (images folder or video file)</label><input type="text" id="ingest-source-path" value="data" class="input-field" placeholder="e.g. data/seq_001 or path/to/clip.mp4"><span class="help-text">Uses Dataset Configuration Images Path when left as default. Enable Local above to load all frames (vendor stubs alone are ~3 frames each).</span></div><div class="form-group"><label for="ingest-max-frames">Max frames (local)</label><input type="number" id="ingest-max-frames" value="10000" min="1" class="input-field" title="Cap for local image/video ingest. Default 10000 — not silently capped at 6."></div><div class="form-group"><label for="ingest-sequence-id">Sequence ID</label><input type="text" id="ingest-sequence-id" value="seq_001" class="input-field"></div><button class="btn btn-primary" id="btn-ingest-run">Run Ingest & Fusion</button><div id="ingest-status" class="status-box" style="margin-top:16px;"></div></div><div class="card card-glass pipeline-output-browser" style="margin-top:16px;" data-browser="ingest"><h3>Pipeline Outputs — browse & validate</h3>13 unmodified lines</div><div><div class="out-preview-meta" style="font-size:12px;color:var(--text-muted);margin-bottom:8px;">No frame selected.</div><img class="out-preview-img" alt="Frame preview" style="display:none;max-width:100%;max-height:280px;border-radius:8px;border:1px solid var(--border);background:#04060b;"><pre class="out-proposals-json" style="display:none;margin-top:10px;max-height:200px;overflow:auto;background:#04060b;border:1px solid var(--border);border-radius:8px;padding:10px;font-size:11px;color:#00ffaa;"></pre></div></div>16 unmodified lines<option value="cuda">CUDA</option></select></div><div class="form-group"><label><input type="checkbox" id="perception-no-sam"> Skip SAM (fallback / NOT a model SUCCESS)</label></div><button class="btn btn-primary" id="btn-perception-run">Run Auto-Label</button><div id="perception-status" class="status-box" style="margin-top:16px;"></div><div class="evidence-card" id="evidence-perception" data-stage="perception"><h4>What actually happened?</h4><p class="evidence-empty">No auto-label execution yet.</p></div></div><div class="card card-glass pipeline-output-browser" style="margin-top:16px;" data-browser="perception"><h3>Pipeline Outputs — proposals & frames</h3>13 unmodified lines</div><div><div class="out-preview-meta" style="font-size:12px;color:var(--text-muted);margin-bottom:8px;">No frame selected.</div><img class="out-preview-img" alt="Frame preview" style="display:none;max-width:100%;max-height:280px;border-radius:8px;border:1px solid var(--border);background:#04060b;"><pre class="out-proposals-json" style="display:none;margin-top:10px;max-height:200px;overflow:auto;background:#04060b;border:1px solid var(--border);border-radius:8px;padding:10px;font-size:11px;color:#00ffaa;"></pre></div></div>8 unmodified lines<button class="btn btn-primary" id="btn-tracking-run">Run Temporal Tracker</button><div id="tracking-status" class="status-box" style="margin-top:16px;"></div><div id="tracking-tracks-table" style="margin-top:16px;"></div><div class="evidence-card evidence-stub" id="evidence-tracking" data-stage="tracking"><h4>What actually happened?</h4><p class="evidence-empty">Ledger wiring pending — status will show NOT_EXECUTED until this stage records evidence.</p></div></div></section>5 unmodified lines<button class="btn btn-primary" id="btn-quality-gate-run">Run Quality Gate</button><div id="quality-gate-status" class="status-box" style="margin-top:16px;"></div><div id="quality-gate-metrics" style="margin-top:16px;"></div><div class="evidence-card evidence-stub" id="evidence-quality-gate" data-stage="quality-gate"><h4>What actually happened?</h4><p class="evidence-empty">Evidence panel stub — gate results are live, full ledger wiring deferred.</p></div></div></section>113 unmodified lines<div class="progress-bar-fill" id="train-progress-bar" style="width: 0%"></div></div></div><div class="evidence-card" id="evidence-training" data-stage="training"><h4>What actually happened?</h4><p class="evidence-empty">No training execution yet.</p></div></div><div class="card card-glass">34 unmodified lines<span class="range-val" id="val-infer-iou">0.45</span></div><button class="btn btn-primary btn-large" id="btn-run-infer">⚡ Run Auto-Labeler</button><div class="evidence-card" id="evidence-inference" data-stage="inference"><h4>What actually happened?</h4><p class="evidence-empty">No inference execution yet.</p></div></div><div class="card card-glass">35 unmodified lines</div></div><button class="btn btn-primary width-full" id="btn-run-grader" style="margin-top: 15px;">Run Quality Diagnostics</button><div class="evidence-card" id="evidence-grader" data-stage="grader"><h4>What actually happened?</h4><p class="evidence-empty">No grader execution yet.</p></div></div><div class="card card-glass">429 unmodified lines</div></div></div><!-- Floating help chatbot (opens panel; answers via POST /api/help/chat) --><button id="floating-help-btn" class="floating-btn" type="button" title="Ask the help chatbot" aria-label="Open help chatbot" aria-controls="help-drawer" aria-expanded="false" style="position: fixed; bottom: 20px; right: 20px; width: 45px; height: 45px; border-radius: 50%; background: var(--primary); color: #000; border: none; font-size: 20px; cursor: pointer; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 15px rgba(0, 200, 150, 0.4); z-index: 1100; transition: transform 0.2s ease;">❓</button><!-- Help chatbot drawer --><div id="help-drawer" class="drawer-wrapper hidden" role="dialog" aria-label="Help chatbot" style="position: fixed; top: 0; right: 0; width: min(400px, 100vw); height: 100%; background: rgba(10, 15, 25, 0.97); border-left: 1px solid var(--border); box-shadow: -10px 0 30px rgba(0,0,0,0.5); z-index: 1101; box-sizing: border-box; backdrop-filter: blur(12px); display: flex; flex-direction: column;"><div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid var(--border); padding: 16px 20px; flex-shrink: 0;"><h3 style="margin: 0; font-size: 16px; color: #fff;">Help chatbot</h3><button id="close-drawer-btn" type="button" aria-label="Close help chatbot" style="background: none; border: none; color: var(--text-muted); font-size: 24px; cursor: pointer; line-height: 1;">×</button></div><div id="help-chat-log" style="flex: 1; overflow-y: auto; padding: 16px 20px; display: flex; flex-direction: column; gap: 12px;"><div class="help-chat-msg help-chat-bot" style="padding: 10px 12px; border-radius: 8px; background: #141a20; border: 1px solid var(--border); font-size: 13px; color: var(--text-muted); line-height: 1.5;">Ask about Studio stages, datasets, Strict Execution Mode, SSAM, or any page. Answers use the local FAQ / page-guide index (CPU-safe; no GPU required).</div></div><div id="help-chat-suggestions" style="display: flex; flex-wrap: wrap; gap: 6px; padding: 0 16px 10px;"><button type="button" class="help-suggest-btn" data-q="How do I load a dataset?" style="font-size: 11px; padding: 4px 8px; border-radius: 999px; border: 1px solid var(--border); background: #1d242c; color: var(--text-muted); cursor: pointer;">How do I load a dataset?</button><button type="button" class="help-suggest-btn" data-q="What is Strict Execution Mode?" style="font-size: 11px; padding: 4px 8px; border-radius: 999px; border: 1px solid var(--border); background: #1d242c; color: var(--text-muted); cursor: pointer;">What is Strict Execution Mode?</button><button type="button" class="help-suggest-btn" data-q="How do pipeline stages work?" style="font-size: 11px; padding: 4px 8px; border-radius: 999px; border: 1px solid var(--border); background: #1d242c; color: var(--text-muted); cursor: pointer;">Pipeline stages</button><button type="button" class="help-suggest-btn" data-q="What is Sensorflow Studio?" style="font-size: 11px; padding: 4px 8px; border-radius: 999px; border: 1px solid var(--border); background: #1d242c; color: var(--text-muted); cursor: pointer;">What is Sensorflow Studio?</button></div><form id="help-chat-form" style="display: flex; gap: 8px; padding: 12px 16px 16px; border-top: 1px solid var(--border); flex-shrink: 0;"><input id="help-chat-input" type="text" maxlength="2000" placeholder="Ask about a page or feature…" aria-label="Help question" style="flex: 1; padding: 10px 12px; border-radius: 8px; border: 1px solid var(--border); background: #0d1218; color: #e6e9ec; font-size: 13px;"><button id="help-chat-send" type="submit" class="btn btn-primary" style="min-width: 72px;">Ask</button></form></div><div id="toast-stack" class="toast-stack" aria-live="polite" aria-relevant="additions"></div><div id="exec-console-modal" class="modal-overlay hidden" role="dialog" aria-label="Execution Console"><div class="modal-card exec-console-card"><div class="modal-header" style="display:flex;justify-content:space-between;align-items:center;gap:12px;"><h3 style="margin:0;">Global Execution Console</h3><div style="display:flex;gap:8px;"><button type="button" class="btn btn-secondary" id="btn-refresh-executions">Refresh</button><button type="button" class="btn btn-secondary" id="btn-close-exec-console">Close</button></div></div><p style="font-size:12px;color:var(--text-muted);margin:8px 0 12px;">Persistent ledger under <code>runs/executions/</code>. UI PASS badges are not evidence.</p><div id="exec-console-list" class="exec-console-list"></div><div id="exec-console-detail" class="exec-console-detail hidden"></div></div></div>101 unmodified lines10210310410510610710832 unmodified lines1411421431441451461471481491501515 unmodified lines15715815916016116216316416516616716816917017191 unmodified lines26326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631713 unmodified lines33133233333433533633733816 unmodified lines35535635735835936036136213 unmodified lines3763773783793803813823838 unmodified lines3923933943953963975 unmodified lines403404405406407408113 unmodified lines52252352452552652734 unmodified lines56256356456556656735 unmodified lines603604605606607608429 unmodified lines103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073101 unmodified lines<h2 id="stage-title">Dataset Configuration</h2><p id="stage-desc">Prepare and validate your image source path and annotation files.</p></div><div class="controls-area"><button class="btn btn-secondary" id="btn-validate">Run Pre-Check</button><button class="btn btn-primary" id="btn-global-action">Proceed to Model</button></div>32 unmodified lines</div><div class="actions-row" style="display: flex; gap: 12px; flex-wrap: wrap;"><button class="btn btn-primary" id="btn-save-dataset">Save Config</button><button class="btn btn-secondary" id="btn-preprocess-dataset">Load Catalog Metadata</button><button class="btn btn-secondary" id="btn-browse-source" title="List and preview images under Images Path">Validate & Browse Images Path</button></div><div id="source-browse-status" class="status-box" style="margin-top:12px;"></div><div id="source-browse-gallery" class="output-browse-gallery" style="margin-top:12px;"></div></div><div class="card card-glass">5 unmodified lines</div><div class="info-row"><span class="lbl">Train script:</span><span class="val font-mono green">Found (train.py)</span></div><div class="info-row"><span class="lbl">Infer script:</span><span class="val font-mono green">Found (infer.py)</span></div><div class="info-row"><span class="lbl">Auto-Grader script:</span><span class="val font-mono green">Found (autograder.py)</span></div></div></div>91 unmodified lines<section class="stage-panel" id="panel-ingest"><div class="card card-glass"><h3>Exabyte Ingest, Fusion & Stratification</h3><p class="text-muted">Ingest one vendor by default (homogeneous frame IDs). Or use Load all datasets to register Local + each AV vendor as separate sequences under runs/pipeline/<prefix>_<vendor>/. Missing lakes become clearly labeled demo stubs (or NOT_EXECUTED if stubs are disabled).</p><div class="form-group"><label>Vendors</label><div style="display:flex;gap:12px;flex-wrap:wrap;"><label title="Load frames from Dataset Configuration Images Path"><input type="checkbox" id="ingest-vendor-local"> Local frames / video</label><label title="NVIDIA Alpamayo (Physical AI AV Dataset)"><input type="checkbox" id="ingest-vendor-alpamayo" checked> Alpamayo (demo stub)</label><label title="Waymo Open Dataset"><input type="checkbox" id="ingest-vendor-waymo"> Waymo (demo stub)</label><label title="Audi A2D2 (Audi Autonomous Driving Dataset)"><input type="checkbox" id="ingest-vendor-a2d2"> Audi A2D2 (demo stub)</label></div><label style="display:block;margin-top:8px;" title="When off, selecting a vendor replaces the previous selection so ingest stays single-dataset."><input type="checkbox" id="ingest-mix-vendors"> Mix vendors (fuse multiple stubs into one sequence)</label><label style="display:block;margin-top:6px;" title="When off, Load all datasets reports NOT_EXECUTED for vendors without a configured lake path."><input type="checkbox" id="ingest-allow-stub" checked> Allow demo stubs when AV lakes are missing</label></div><div class="form-group"><label for="ingest-source-path">Local source path (images folder or video file)</label><input type="text" id="ingest-source-path" value="data" class="input-field" placeholder="e.g. data/seq_001 or path/to/clip.mp4"><span class="help-text">Uses Dataset Configuration Images Path when left as default. Enable Local above to load all frames (vendor stubs alone are ~3 frames each).</span></div><div class="grid-2" style="gap:12px;"><div class="form-group"><label for="ingest-waymo-root">Waymo root (optional)</label><input type="text" id="ingest-waymo-root" class="input-field" placeholder="path/to/waymo frames or lake"></div><div class="form-group"><label for="ingest-alpamayo-root">Alpamayo root (optional)</label><input type="text" id="ingest-alpamayo-root" class="input-field" placeholder="path/to/alpamayo frames"></div><div class="form-group"><label for="ingest-a2d2-root">A2D2 root (optional)</label><input type="text" id="ingest-a2d2-root" class="input-field" placeholder="path/to/a2d2 PNG export"></div><div class="form-group"><label for="ingest-max-frames">Max frames (local / lake folders)</label><input type="number" id="ingest-max-frames" value="10000" min="1" class="input-field" title="Cap for local image/video ingest. Default 10000 — not silently capped at 6."></div></div><div class="form-group"><label for="ingest-sequence-id">Sequence ID / prefix</label><input type="text" id="ingest-sequence-id" value="seq_001" class="input-field"><span class="help-text">Single ingest uses this ID. Load all datasets writes <prefix>_local, <prefix>_waymo, etc.</span></div><div style="display:flex;gap:12px;flex-wrap:wrap;"><button class="btn btn-primary" id="btn-ingest-run">Run Ingest & Fusion</button><button class="btn btn-secondary" id="btn-load-all-datasets" title="Register each vendor as its own pipeline sequence">Load all datasets</button></div><div id="ingest-status" class="status-box" style="margin-top:16px;white-space:pre-wrap;"></div></div><div class="card card-glass pipeline-output-browser" style="margin-top:16px;" data-browser="ingest"><h3>Pipeline Outputs — browse & validate</h3>13 unmodified lines</div><div><div class="out-preview-meta" style="font-size:12px;color:var(--text-muted);margin-bottom:8px;">No frame selected.</div><img class="out-preview-img" alt="Frame preview" style="display:none;max-width:100%;max-height:320px;border-radius:8px;border:1px solid var(--border);background:#04060b;"><div class="out-camera-empty" style="display:none;padding:24px;border:1px dashed var(--border);border-radius:8px;color:var(--text-muted);font-size:13px;background:rgba(4,6,11,0.35);">No camera image for this frame.</div><pre class="out-proposals-json" style="display:none;margin-top:10px;max-height:200px;overflow:auto;background:#04060b;border:1px solid var(--border);border-radius:8px;padding:10px;font-size:11px;color:#00ffaa;"></pre></div></div>16 unmodified lines<option value="cuda">CUDA</option></select></div><button class="btn btn-primary" id="btn-perception-run">Run Auto-Label</button><div id="perception-status" class="status-box" style="margin-top:16px;"></div></div><div class="card card-glass pipeline-output-browser" style="margin-top:16px;" data-browser="perception"><h3>Pipeline Outputs — proposals & frames</h3>13 unmodified lines</div><div><div class="out-preview-meta" style="font-size:12px;color:var(--text-muted);margin-bottom:8px;">No frame selected.</div><img class="out-preview-img" alt="Frame preview" style="display:none;max-width:100%;max-height:320px;border-radius:8px;border:1px solid var(--border);background:#04060b;"><div class="out-camera-empty" style="display:none;padding:24px;border:1px dashed var(--border);border-radius:8px;color:var(--text-muted);font-size:13px;background:rgba(4,6,11,0.35);">No camera image for this frame.</div><pre class="out-proposals-json" style="display:none;margin-top:10px;max-height:200px;overflow:auto;background:#04060b;border:1px solid var(--border);border-radius:8px;padding:10px;font-size:11px;color:#00ffaa;"></pre></div></div>8 unmodified lines<button class="btn btn-primary" id="btn-tracking-run">Run Temporal Tracker</button><div id="tracking-status" class="status-box" style="margin-top:16px;"></div><div id="tracking-tracks-table" style="margin-top:16px;"></div></div></section>5 unmodified lines<button class="btn btn-primary" id="btn-quality-gate-run">Run Quality Gate</button><div id="quality-gate-status" class="status-box" style="margin-top:16px;"></div><div id="quality-gate-metrics" style="margin-top:16px;"></div></div></section>113 unmodified lines<div class="progress-bar-fill" id="train-progress-bar" style="width: 0%"></div></div></div></div><div class="card card-glass">34 unmodified lines<span class="range-val" id="val-infer-iou">0.45</span></div><button class="btn btn-primary btn-large" id="btn-run-infer">⚡ Run Auto-Labeler</button></div><div class="card card-glass">35 unmodified lines</div></div><button class="btn btn-primary width-full" id="btn-run-grader" style="margin-top: 15px;">Run Quality Diagnostics</button></div><div class="card card-glass">429 unmodified lines</div></div></div><!-- Floating Onscreen Help Guide Button --><button id="floating-help-btn" class="floating-btn" title="Open Interactive Guide" style="position: fixed; bottom: 20px; right: 20px; width: 45px; height: 45px; border-radius: 50%; background: var(--primary); color: #000; border: none; font-size: 20px; cursor: pointer; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 15px rgba(0, 200, 150, 0.4); z-index: 999; transition: transform 0.2s ease;">❓</button><!-- Onscreen Help Guide Drawer --><div id="help-drawer" class="drawer-wrapper hidden" style="position: fixed; top: 0; right: -400px; width: 380px; height: 100%; background: rgba(10, 15, 25, 0.95); border-left: 1px solid var(--border); box-shadow: -10px 0 30px rgba(0,0,0,0.5); z-index: 1000; transition: right 0.3s ease; padding: 24px; box-sizing: border-box; overflow-y: auto; backdrop-filter: blur(12px);"><div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid var(--border); padding-bottom: 12px; margin-bottom: 20px;"><h3 style="margin: 0; font-size: 18px; color: #fff; display: flex; align-items: center; gap: 8px;">📖 Guidance Panel</h3><button id="close-drawer-btn" style="background: none; border: none; color: var(--text-muted); font-size: 24px; cursor: pointer; line-height: 1;">×</button></div><div style="display: flex; flex-direction: column; gap: 20px;"><div><h4 style="margin: 0 0 6px 0; color: var(--secondary); font-size: 14px;">📂 Dataset Configuration YAML</h4><p style="margin: 0; font-size: 12px; color: var(--text-muted); line-height: 1.5;">Sensorflow Studio uses the standard Ultralytics YOLO configuration format. Specify the root <code>path</code>, <code>train</code> path, <code>val</code> path, and class labels mapping index values to strings.</p></div><div><h4 style="margin: 0 0 6px 0; color: var(--warning); font-size: 14px;">🚦 FHWA SSAM Safety Surrogates</h4><p style="margin: 0; font-size: 12px; color: var(--text-muted); line-height: 1.5;">Conflict assessment monitors vehicle trajectories to calculate metrics:</p><ul style="margin: 6px 0 0 0; padding-left: 16px; font-size: 12px; color: var(--text-muted); line-height: 1.5;"><li style="margin-bottom: 4px;"><strong>TTC (Time-to-Collision):</strong> Time until crash if speed remains constant. Hazard threshold is <strong>< 1.5 seconds</strong>.</li><li><strong>PET (Post-Encroachment Time):</strong> Passage interval between two vehicles crossing the same interface area. Hazard threshold is <strong>< 5.0 seconds</strong>.</li></ul></div><div><h4 style="margin: 0 0 6px 0; color: var(--primary); font-size: 14px;">⚡ Remote Cluster Training (DGX Spark)</h4><p style="margin: 0; font-size: 12px; color: var(--text-muted); line-height: 1.5;">Allows routing heavy GPU execution to remote systems. Make sure you activate Tailscale, setup dependencies, and verify host resolution before executing.</p></div><div><h4 style="margin: 0 0 6px 0; color: var(--secondary); font-size: 14px;">🧭 Full Sensorflow Studio (React)</h4><p style="margin: 0; font-size: 12px; color: var(--text-muted); line-height: 1.5;">This legacy panel covers train/infer/SSAM. The primary dashboard (Command Center, label evaluation, safety, ROTR, Help menu + Q&A chatbot) lives in the React Sensorflow Studio app — open it from the Space UI or locally via the Vite frontend. Page guides and the help chatbot work on CPU without a GPU.</p></div></div></div>
668 unmodified lines669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785767 unmodified lines1553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649668 unmodified linescolor: var(--secondary);}.status-msg.success-msg {background: rgba(16, 185, 129, 0.12);border-color: rgba(16, 185, 129, 0.28);color: var(--success);}.status-msg.error-msg {background: rgba(239, 68, 68, 0.12);border-color: rgba(239, 68, 68, 0.28);color: var(--danger);}/* Non-blocking toast notifications (replaces window.alert) */.toast-stack {position: fixed;bottom: 24px;left: 50%;transform: translateX(-50%);display: flex;flex-direction: column-reverse;gap: 8px;z-index: 2000;width: min(420px, calc(100vw - 32px));pointer-events: none;}.toast {pointer-events: auto;display: flex;align-items: flex-start;gap: 10px;padding: 12px 14px;border-radius: 8px;background: rgba(15, 20, 34, 0.96);border: 1px solid var(--border);box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);color: var(--text);font-size: 13px;line-height: 1.45;white-space: pre-line;animation: toastIn 0.2s ease;}.toast.toast-out {animation: toastOut 0.18s ease forwards;}.toast-icon {flex-shrink: 0;width: 18px;text-align: center;font-size: 14px;line-height: 1.3;}.toast-body {flex: 1;min-width: 0;}.toast-close {flex-shrink: 0;background: transparent;border: none;color: var(--text-muted);cursor: pointer;font-size: 16px;line-height: 1;padding: 0 2px;}.toast-close:hover {color: var(--text);}.toast-success {border-color: rgba(16, 185, 129, 0.35);box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45), 0 0 0 1px rgba(16, 185, 129, 0.08);}.toast-success .toast-icon { color: var(--success); }.toast-error {border-color: rgba(239, 68, 68, 0.4);box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45), 0 0 0 1px rgba(239, 68, 68, 0.08);}.toast-error .toast-icon { color: var(--danger); }.toast-warning {border-color: rgba(245, 158, 11, 0.4);}.toast-warning .toast-icon { color: var(--warning); }.toast-info {border-color: rgba(59, 130, 246, 0.35);}.toast-info .toast-icon { color: var(--secondary); }@keyframes toastIn {from { opacity: 0; transform: translateY(10px); }to { opacity: 1; transform: translateY(0); }}@keyframes toastOut {from { opacity: 1; transform: translateY(0); }to { opacity: 0; transform: translateY(8px); }}/* Animations */@keyframes fadeIn {from { opacity: 0; transform: translateY(8px); }767 unmodified linescolor: var(--text-muted);font-size: 10px;}/* Execution integrity */.strict-mode-toggle {display: inline-flex;align-items: center;gap: 6px;font-size: 12px;color: var(--text-muted);cursor: pointer;user-select: none;}.evidence-card {margin-top: 16px;padding: 14px;border: 1px solid var(--border);border-radius: 8px;background: rgba(4, 6, 11, 0.55);}.evidence-card h4 {margin: 0 0 10px 0;font-size: 13px;color: var(--secondary);}.evidence-empty {font-size: 12px;color: var(--text-muted);margin: 0;}.ev-status {display: inline-block;font-size: 11px;font-weight: 700;letter-spacing: 0.4px;padding: 3px 8px;border-radius: 4px;margin-bottom: 10px;font-family: var(--font-mono);}.ev-status-SUCCEEDED { background: #00ffaa22; color: #00ffaa; }.ev-status-PARTIAL_SUCCESS { background: #fbbf2422; color: #fbbf24; }.ev-status-FAILED, .ev-status-VALIDATION_FAILED { background: #ff444422; color: #ff8888; }.ev-status-RUNNING, .ev-status-QUEUED { background: #3b82f622; color: #93c5fd; }.ev-status-NOT_EXECUTED, .ev-status-UNVERIFIED, .ev-status-CANCELLED { background: #64748b33; color: #94a3b8; }.ev-row {display: flex;justify-content: space-between;gap: 12px;font-size: 12px;padding: 3px 0;border-bottom: 1px solid rgba(255,255,255,0.04);}.ev-row span { color: var(--text-muted); }.ev-row strong { color: var(--text); text-align: right; word-break: break-all; }.ev-msg { font-size: 12px; color: var(--text-muted); margin: 10px 0 0; }.ev-log-link { display: inline-block; margin-top: 10px; font-size: 12px; color: #38bdf8; }.ev-timeline { margin-top: 10px; font-size: 11px; color: var(--text-muted); }.ev-timeline ul { margin: 6px 0 0 16px; padding: 0; }.exec-console-card {width: min(920px, 94vw);max-height: 85vh;overflow: auto;background: var(--bg-sidebar);border: 1px solid var(--border);border-radius: 12px;padding: 18px;}.exec-console-list { display: flex; flex-direction: column; gap: 6px; }.exec-row {display: grid;grid-template-columns: 140px 160px 1fr 80px 90px;gap: 8px;align-items: center;text-align: left;padding: 8px 10px;background: rgba(4,6,11,0.5);border: 1px solid var(--border);border-radius: 6px;color: var(--text);cursor: pointer;font-size: 12px;}.exec-row:hover { border-color: var(--border-active); }.exec-console-detail pre {margin-top: 12px;max-height: 320px;overflow: auto;background: #04060b;border: 1px solid var(--border);border-radius: 8px;padding: 12px;font-size: 11px;color: #00ffaa;}.config-exec-status { font-family: var(--font-mono); }668 unmodified lines669670671672673674767 unmodified lines144214431444668 unmodified linescolor: var(--secondary);}/* Animations */@keyframes fadeIn {from { opacity: 0; transform: translateY(8px); }767 unmodified linescolor: var(--text-muted);font-size: 10px;}
85 unmodified lines868788899091929394959697989910010110210310485 unmodified linesbody = client.post("/api/help/chat", json={"question": "what's new?"}).json()assert body["answer"]assert get_about()["version"] in body["answer"] or "release" in body["answer"].lower()def test_chat_load_dataset(client):body = client.post("/api/help/chat", json={"question": "How do I load a dataset?"}).json()assert body["answer"]assert any(k in body["answer"].lower() for k in ("dataset", "ingest", "yaml", "source"))def test_chat_strict_execution_mode(client):body = client.post("/api/help/chat", json={"question": "What is Strict Execution Mode?"}).json()assert body["answer"]lower = body["answer"].lower()assert "strict" in lowerassert any(k in lower for k in ("evidence", "ledger", "succeeded", "verified"))85 unmodified lines86878885 unmodified linesbody = client.post("/api/help/chat", json={"question": "what's new?"}).json()assert body["answer"]assert get_about()["version"] in body["answer"] or "release" in body["answer"].lower()
53 unmodified lines545556575859606113 unmodified lines75767753 unmodified linesseq_id = "full_pipeline"ingest = client.post("/api/dataset/ingest",json={"vendors": ["alpamayo", "waymo"], "sequence_id": seq_id},)assert ingest.json()["frames"] == 6assert ingest.json()["demo_stub"] is Truelabel = client.post("/api/perception/auto-label", json={"sequence_id": seq_id, "no_sam": True})13 unmodified linesassert status["tracking_complete"] is Trueassert status["frames_ingested"] == 6assert status["demo_stub"] is True53 unmodified lines54555657585960616213 unmodified lines76777879808182838485868753 unmodified linesseq_id = "full_pipeline"ingest = client.post("/api/dataset/ingest",json={"vendors": ["alpamayo", "waymo"], "sequence_id": seq_id, "allow_mix": True},)assert ingest.status_code == 200assert ingest.json()["frames"] == 6assert ingest.json()["demo_stub"] is Truelabel = client.post("/api/perception/auto-label", json={"sequence_id": seq_id, "no_sam": True})13 unmodified linesassert status["tracking_complete"] is Trueassert status["frames_ingested"] == 6assert status["demo_stub"] is Truedef test_ingest_rejects_mix_without_flag(client):res = client.post("/api/dataset/ingest",json={"vendors": ["alpamayo", "waymo"], "sequence_id": "no_mix"},)assert res.status_code == 400assert "allow_mix" in str(res.json()["detail"]).lower() or "Multiple vendors" in str(res.json()["detail"])
23 unmodified lines2425262728295 unmodified lines353637383940414243444546474823 unmodified lines)assert ingest.status_code == 200assert ingest.json()["frames"] >= 1seqs = client.get("/api/pipeline/sequences").json()assert any(s["sequence_id"] == seq_id for s in seqs["sequences"])5 unmodified linesframes = client.get(f"/api/pipeline/frames?sequence_id={seq_id}").json()assert frames["browsable"] is Trueassert len(frames["frames"]) >= 1frame_id = frames["frames"][0]["frame_id"]detail = client.get(f"/api/pipeline/frame?sequence_id={seq_id}&frame_id={frame_id}").json()assert detail["frame_id"] == frame_idassert "cameras" in detaildef test_pipeline_file_serves_local_image(client, tmp_path):23 unmodified lines242526272829305 unmodified lines3637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614723 unmodified lines)assert ingest.status_code == 200assert ingest.json()["frames"] >= 1assert ingest.json()["vendor"] == "alpamayo"seqs = client.get("/api/pipeline/sequences").json()assert any(s["sequence_id"] == seq_id for s in seqs["sequences"])5 unmodified linesframes = client.get(f"/api/pipeline/frames?sequence_id={seq_id}").json()assert frames["browsable"] is Trueassert frames["vendor"] == "alpamayo"assert len(frames["frames"]) >= 1# Homogeneous Alpamayo IDsassert all(f["frame_id"].startswith("alpamayo_") for f in frames["frames"])frame_id = frames["frames"][0]["frame_id"]assert frames["frames"][0].get("preview_url")detail = client.get(f"/api/pipeline/frame?sequence_id={seq_id}&frame_id={frame_id}").json()assert detail["frame_id"] == frame_idassert "cameras" in detailassert detail.get("preview_url") or any(c.get("preview_url") for c in detail["cameras"])# Empty proposals must not imply missing cameraassert detail["proposal_count"] == 0img_url = detail.get("preview_url") or detail["cameras"][0]["preview_url"]assert img_url.startswith("/api/pipeline/file?")img_res = client.get(img_url)assert img_res.status_code == 200assert img_res.content[:8] == b"\x89PNG\r\n\x1a\n"def test_single_vendor_waymo_homogeneous(client):ingest = client.post("/api/dataset/ingest",json={"vendors": ["waymo"], "sequence_id": "waymo_only"},)assert ingest.status_code == 200body = ingest.json()assert body["vendor"] == "waymo"frames = client.get("/api/pipeline/frames?sequence_id=waymo_only").json()assert frames["vendor"] == "waymo"assert all(f["frame_id"].startswith("waymo_") for f in frames["frames"])assert all(f.get("preview_url") for f in frames["frames"])def test_load_all_datasets_separate_sequences(client, tmp_path):# AV vendors stub when allow_stubres = client.post("/api/dataset/load-all",json={"sequence_prefix": "all_demo","vendors": ["alpamayo", "waymo", "a2d2"],"allow_stub": True,},)assert res.status_code == 200data = res.json()assert data["loaded"] == 3vendors = {r["vendor"] for r in data["results"]}assert vendors == {"alpamayo", "waymo", "a2d2"}for r in data["results"]:assert r["status"] == "ok"assert r["demo_stub"] is Trueframes = client.get(f"/api/pipeline/frames?sequence_id={r['sequence_id']}").json()assert frames["vendor"] == r["vendor"]assert frames["vendor"] != "mixed"prefix = f"{r['vendor']}_"assert all(f["frame_id"].startswith(prefix) for f in frames["frames"])def test_load_all_not_executed_without_stub(client, tmp_path):res = client.post("/api/dataset/load-all",json={"sequence_prefix": "strict","vendors": ["waymo", "a2d2"],"allow_stub": False,},)assert res.status_code == 200data = res.json()assert data["status"] == "NOT_EXECUTED"assert data["loaded"] == 0assert data["not_executed"] == 2for r in data["results"]:assert r["status"] == "NOT_EXECUTED"assert "message" in rdef test_load_all_local_real_when_path_has_images(client, tmp_path):data_dir = tmp_path / "data"data_dir.mkdir()(data_dir / "a.png").write_bytes(bytes.fromhex("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489""0000000a49444154789c63000100000500010d0a2db40000000049454e44ae426082"))res = client.post("/api/dataset/load-all",json={"sequence_prefix": "with_local","vendors": ["local", "waymo"],"source_path": "data","allow_stub": True,},)assert res.status_code == 200data = res.json()by_v = {r["vendor"]: r for r in data["results"]}assert by_v["local"]["status"] == "ok"assert by_v["local"]["demo_stub"] is Falseassert by_v["local"]["frames"] >= 1assert by_v["waymo"]["demo_stub"] is Truedef test_pipeline_file_serves_local_image(client, tmp_path):
app_backend.py+216-760
infer.py+1-1
sensorflow/adapters/a2d2_adapter.py+40-2
sensorflow/adapters/alpamayo_adapter.py+41-6
sensorflow/adapters/stub_images.pyAdded+83
sensorflow/adapters/vendor_media.pyAdded+103
sensorflow/adapters/waymo_adapter.py+44-6
sensorflow/dataset_load_service.pyAdded+246
sensorflow/help/knowledge.py+3-47
sensorflow/help/matcher.py-8
sensorflow/pipeline_artifacts.py+38-21
src/components/help/HelpChatbot.tsx+4-3
static/app.js+173-540
static/index.html+68-95
static/style.css-205
tests/test_help/test_matcher.py-16
tests/test_pipeline/test_api_pipeline.py+11-1
tests/test_pipeline/test_pipeline_browse.py+99