Download apps/api/main.py from husnainbinmunawar/ShiftBudget-Research-Lab: direct link, hf CLI and curl.
- Browser
- Download file 20.5 kB
-
https://huggingface.co/spaces/husnainbinmunawar/ShiftBudget-Research-Lab/resolve/main/apps/api/main.py
- Command line
-
hf download hf://spaces/husnainbinmunawar/ShiftBudget-Research-Lab/apps/api/main.py
-
curl -L -o main.py https://huggingface.co/spaces/husnainbinmunawar/ShiftBudget-Research-Lab/resolve/main/apps/api/main.py
20.5 kB
| from __future__ import annotations | |
| import os | |
| import platform | |
| import sys | |
| import uuid | |
| from contextlib import asynccontextmanager | |
| from pathlib import Path | |
| from typing import Annotated | |
| import numpy as np | |
| from fastapi import FastAPI, File, Form, HTTPException, UploadFile | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import FileResponse | |
| from pydantic import BaseModel, Field | |
| CORE = Path(__file__).resolve().parents[2] / "packages" / "core" | |
| if str(CORE) not in sys.path: | |
| sys.path.insert(0, str(CORE)) | |
| from shiftbudget_core.calibration import Calibration, calibrate # noqa: E402 | |
| from shiftbudget_core.datasets import ingest_visa, read_manifest # noqa: E402 | |
| from shiftbudget_core.drift import score_embedding # noqa: E402 | |
| from shiftbudget_core.edge import device_profile # noqa: E402 | |
| from shiftbudget_core.image_ops import ( # noqa: E402 | |
| apply_shift, | |
| blend_heatmap, | |
| encode_png, | |
| image_bytes_to_rgb, | |
| load_rgb, | |
| quality_dict, | |
| sha256_bytes, | |
| ) | |
| from shiftbudget_core.patchcore import PatchCoreDetector, PatchCoreUnavailable # noqa: E402 | |
| from shiftbudget_core.policy import Budget, route # noqa: E402 | |
| from shiftbudget_core.storage import db, json_dump, json_load # noqa: E402 | |
| DATA_DIR = Path(os.getenv("SHIFTBUDGET_DATA_DIR", "data")).resolve() | |
| DB_PATH = DATA_DIR / "shiftbudget.db" | |
| MODEL_PATH = DATA_DIR / "models" / "patchcore_raw_patch_v1.npz" | |
| ARTIFACT_DIR = DATA_DIR / "artifacts" | |
| MAX_UPLOAD_BYTES = int(os.getenv("SHIFTBUDGET_MAX_UPLOAD_BYTES", str(10 * 1024 * 1024))) | |
| async def lifespan(_app: FastAPI): | |
| _ensure_dirs() | |
| yield | |
| app = FastAPI(title="ShiftBudget API", version="0.1.0", description="Evidence-backed visual inspection under controlled distribution shift", lifespan=lifespan) | |
| origins = [origin.strip() for origin in os.getenv("SHIFTBUDGET_API_ORIGINS", "http://localhost:3000,http://localhost:8000").split(",")] | |
| app.add_middleware(CORSMiddleware, allow_origins=origins, allow_credentials=False, allow_methods=["*"], allow_headers=["*"]) | |
| class IngestRequest(BaseModel): | |
| root: str = Field(min_length=1) | |
| category: str | None = None | |
| max_images_per_category: int | None = Field(default=100, ge=2, le=10000) | |
| seed: int = Field(default=42, ge=0, le=2**31 - 1) | |
| class FitRequest(BaseModel): | |
| category: str | None = None | |
| max_train: int = Field(default=200, ge=1, le=10000) | |
| max_memory: int = Field(default=4096, ge=32, le=100000) | |
| target_false_positive_rate: float = Field(default=0.05, gt=0, lt=1) | |
| class ReviewRequest(BaseModel): | |
| reviewer_action: str = Field(min_length=1, max_length=64) | |
| corrected_label: str | None = Field(default=None, max_length=64) | |
| comments: str | None = Field(default=None, max_length=2000) | |
| def _row(row: object) -> dict[str, object]: | |
| return dict(row) if row is not None else {} | |
| def _model_row(connection): | |
| row = connection.execute("SELECT * FROM models ORDER BY id LIMIT 1").fetchone() | |
| return _row(row) if row else None | |
| def _calibration(connection, model_id: int) -> Calibration | None: | |
| row = connection.execute("SELECT metadata_json FROM calibrations WHERE model_id=? ORDER BY id DESC LIMIT 1", (model_id,)).fetchone() | |
| if not row: | |
| return None | |
| data = json_load(row[0]) | |
| return Calibration(float(data["threshold"]), float(data["target_false_positive_rate"]), int(data["normal_count"]), float(data["median"]), float(data["mad"]), data.get("method", "empirical_normal_quantile")) | |
| def _ensure_dirs() -> None: | |
| for path in (DATA_DIR, DATA_DIR / "manifests", DATA_DIR / "models", ARTIFACT_DIR, ARTIFACT_DIR / "inspections", DATA_DIR / "uploads"): | |
| path.mkdir(parents=True, exist_ok=True) | |
| with db(DB_PATH): | |
| pass | |
| def health() -> dict[str, object]: | |
| _ensure_dirs() | |
| with db(DB_PATH) as connection: | |
| connection.execute("INSERT INTO audit_events(event_type, entity_type, entity_id, payload_json) VALUES (?,?,?,?)", ("health_check", "system", "api", "{}")) | |
| return {"status": "ok", "service": "shiftbudget-api", "version": "0.1.0", "evidence_mode": "real_artifacts_only"} | |
| def system() -> dict[str, object]: | |
| return {"device": device_profile(), "data_dir": str(DATA_DIR), "model_artifact_available": MODEL_PATH.exists(), "python": sys.version, "platform": platform.platform()} | |
| def dashboard() -> dict[str, object]: | |
| _ensure_dirs() | |
| with db(DB_PATH) as connection: | |
| datasets = connection.execute("SELECT COUNT(*) AS n FROM dataset_versions").fetchone()[0] | |
| images = connection.execute("SELECT COUNT(*) AS n FROM image_assets").fetchone()[0] | |
| runs = connection.execute("SELECT COUNT(*) AS n FROM inspection_runs").fetchone()[0] | |
| reviews = connection.execute("SELECT COUNT(*) AS n FROM review_tasks WHERE status='OPEN'").fetchone()[0] | |
| model = _model_row(connection) | |
| return {"datasets": datasets, "images": images, "inspection_runs": runs, "open_reviews": reviews, "model": model, "artifact_available": MODEL_PATH.exists(), "status_note": "Metrics are empty until a real dataset is ingested and an artifact is fitted."} | |
| def ingest(request: IngestRequest) -> dict[str, object]: | |
| root = Path(request.root).resolve() | |
| if not root.is_dir(): | |
| raise HTTPException(400, "root must be an existing extracted VisA directory") | |
| try: | |
| metadata = ingest_visa(root, DATA_DIR / "manifests", max_images_per_category=request.max_images_per_category, category=request.category, seed=request.seed) | |
| except (FileNotFoundError, ValueError) as exc: | |
| raise HTTPException(422, str(exc)) from exc | |
| with db(DB_PATH) as connection: | |
| cursor = connection.execute("INSERT INTO dataset_versions(name, metadata_json) VALUES (?,?)", ("Amazon VisA", json_dump(metadata))) | |
| dataset_id = cursor.lastrowid | |
| records = read_manifest(metadata["manifest"]) | |
| for record in records: | |
| connection.execute("INSERT OR REPLACE INTO image_assets(dataset_version_id,image_id,path,category,label,split,mask_path,sha256,width,height) VALUES (?,?,?,?,?,?,?,?,?,?)", (dataset_id, record.image_id, record.path, record.category, record.label, record.split, record.mask_path, record.sha256, record.width, record.height)) | |
| connection.execute("INSERT INTO audit_events(event_type,entity_type,entity_id,payload_json) VALUES (?,?,?,?)", ("dataset_ingested", "dataset_version", str(dataset_id), json_dump(metadata))) | |
| return {"status": "COMPLETED", "dataset_version_id": dataset_id, **metadata} | |
| def datasets() -> list[dict[str, object]]: | |
| with db(DB_PATH) as connection: | |
| rows = connection.execute("SELECT * FROM dataset_versions ORDER BY id DESC").fetchall() | |
| return [{**_row(row), "metadata": json_load(row["metadata_json"])} for row in rows] | |
| def images(category: str | None = None, split: str | None = None, label: str | None = None, limit: int = 60, offset: int = 0) -> list[dict[str, object]]: | |
| limit = min(max(limit, 1), 500) | |
| where, params = [], [] | |
| for field, value in (("category", category), ("split", split), ("label", label)): | |
| if value: | |
| where.append(field + "=?") | |
| params.append(value) | |
| sql = "SELECT * FROM image_assets" + (" WHERE " + " AND ".join(where) if where else "") + " ORDER BY id LIMIT ? OFFSET ?" | |
| params.extend([limit, offset]) | |
| with db(DB_PATH) as connection: | |
| rows = connection.execute(sql, params).fetchall() | |
| return [{**_row(row), "file_url": f"/api/v1/images/{row['id']}/file", "mask_url": f"/api/v1/images/{row['id']}/mask" if row["mask_path"] else None} for row in rows] | |
| def _image_asset(asset_id: int): | |
| with db(DB_PATH) as connection: | |
| return connection.execute("SELECT * FROM image_assets WHERE id=?", (asset_id,)).fetchone() | |
| def image_file(asset_id: int): | |
| row = _image_asset(asset_id) | |
| if not row or not Path(row["path"]).is_file(): | |
| raise HTTPException(404, "image asset is unavailable") | |
| return FileResponse(row["path"]) | |
| def image_mask(asset_id: int): | |
| row = _image_asset(asset_id) | |
| if not row or not row["mask_path"] or not Path(row["mask_path"]).is_file(): | |
| raise HTTPException(404, "ground-truth mask is unavailable for this asset") | |
| return FileResponse(row["mask_path"]) | |
| def models() -> list[dict[str, object]]: | |
| with db(DB_PATH) as connection: | |
| rows = connection.execute("SELECT * FROM models ORDER BY id DESC").fetchall() | |
| return [{**_row(row), "metadata": json_load(row["metadata_json"])} for row in rows] | |
| def fit_model(request: FitRequest) -> dict[str, object]: | |
| with db(DB_PATH) as connection: | |
| query = "SELECT * FROM image_assets WHERE label='normal' AND split='train'" | |
| params: list[object] = [] | |
| if request.category: | |
| query += " AND lower(category)=lower(?)" | |
| params.append(request.category) | |
| records = connection.execute(query + " ORDER BY id LIMIT ?", [*params, request.max_train]).fetchall() | |
| if not records: | |
| raise HTTPException(409, "no normal training images available; ingest VisA first") | |
| detector = PatchCoreDetector(max_memory=request.max_memory) | |
| try: | |
| metadata = detector.fit([load_rgb(row["path"]) for row in records], {"category": request.category or "all", "training_image_ids": [row["image_id"] for row in records]}) | |
| except (OSError, ValueError) as exc: | |
| raise HTTPException(422, str(exc)) from exc | |
| detector.save(MODEL_PATH, metadata) | |
| with db(DB_PATH) as connection: | |
| model_id = connection.execute("INSERT OR REPLACE INTO models(name,backend,artifact_path,metadata_json,status) VALUES (?,?,?,?,?)", ("PatchCore raw-patch baseline", detector.backend_name, str(MODEL_PATH), json_dump(metadata), "READY")).lastrowid | |
| calibration_rows = connection.execute("SELECT * FROM image_assets WHERE label='normal' AND split='calibration'" + (" AND lower(category)=lower(?)" if request.category else "") + " ORDER BY id", ([request.category] if request.category else [])).fetchall() | |
| scores = [detector.predict(load_rgb(row["path"])).anomaly_score for row in calibration_rows] | |
| calibration = calibrate(scores, request.target_false_positive_rate) if scores else None | |
| if calibration: | |
| connection.execute("INSERT INTO calibrations(model_id,metadata_json) VALUES (?,?)", (model_id, json_dump(calibration.__dict__))) | |
| connection.execute("INSERT INTO audit_events(event_type,entity_type,entity_id,payload_json) VALUES (?,?,?,?)", ("model_fitted", "model", str(model_id), json_dump(metadata))) | |
| return {"status": "COMPLETED", "model_id": model_id, "artifact": str(MODEL_PATH), "calibration": calibration.__dict__ if calibration else {"status": "NOT_AVAILABLE", "reason": "no calibration images in selected manifest"}, **metadata} | |
| def policies() -> list[dict[str, str]]: | |
| return [{"id": key, "label": label, "evidence": "implemented policy; outcome is computed per inspection"} for key, label in [("fixed_threshold", "Fixed threshold"), ("calibrated_threshold", "Validation-calibrated threshold"), ("uncertainty_abstention", "Uncertainty abstention"), ("shift_aware_review", "Shift-aware review"), ("resource_aware_cost_sensitive", "Resource-aware cost-sensitive")]] | |
| def _safe_artifact_path(run_id: str, name: str) -> Path: | |
| directory = ARTIFACT_DIR / "inspections" / run_id | |
| directory.mkdir(parents=True, exist_ok=True) | |
| path = (directory / name).resolve() | |
| if directory.resolve() not in path.parents: | |
| raise HTTPException(400, "invalid artifact path") | |
| return path | |
| async def inspection(file: Annotated[UploadFile | None, File()] = None, image_id: Annotated[int | None, Form()] = None, shift: Annotated[str, Form()] = "none", severity: Annotated[float, Form()] = 0.0, seed: Annotated[int, Form()] = 42, policy: Annotated[str, Form()] = "calibrated_threshold", false_accept_cost: Annotated[float, Form()] = 100.0, false_reject_cost: Annotated[float, Form()] = 10.0, human_review_cost: Annotated[float, Form()] = 2.0, max_review_rate: Annotated[float, Form()] = 0.2, max_latency_ms: Annotated[float, Form()] = 500.0): | |
| _ensure_dirs() | |
| if file is None and image_id is None: | |
| raise HTTPException(400, "provide an uploaded image or image_id") | |
| asset_id = image_id | |
| if file is not None: | |
| raw = await file.read(MAX_UPLOAD_BYTES + 1) | |
| if len(raw) > MAX_UPLOAD_BYTES: | |
| raise HTTPException(413, "uploaded image exceeds configured size limit") | |
| try: | |
| rgb = image_bytes_to_rgb(raw) | |
| except ValueError as exc: | |
| raise HTTPException(422, str(exc)) from exc | |
| upload_id = uuid.uuid4().hex | |
| source_path = DATA_DIR / "uploads" / f"{upload_id}.png" | |
| source_path.write_bytes(encode_png(rgb)) | |
| source_sha = sha256_bytes(raw) | |
| else: | |
| row = _image_asset(image_id) | |
| if not row: | |
| raise HTTPException(404, "image asset not found") | |
| try: | |
| rgb = load_rgb(row["path"]) | |
| except (OSError, ValueError) as exc: | |
| raise HTTPException(422, str(exc)) from exc | |
| source_path = Path(row["path"]) | |
| source_sha = row["sha256"] | |
| try: | |
| transformed, shift_params = apply_shift(rgb, shift, severity, seed) | |
| except ValueError as exc: | |
| raise HTTPException(422, str(exc)) from exc | |
| try: | |
| detector = PatchCoreDetector.load(MODEL_PATH) | |
| except PatchCoreUnavailable as exc: | |
| return {"status": "NOT_AVAILABLE", "reason": str(exc), "required_next_step": "ingest VisA and fit the model"} | |
| original_prediction = detector.predict(rgb) | |
| prediction = detector.predict(transformed) | |
| quality = quality_dict(transformed) | |
| drift = score_embedding(prediction.feature_vector, np.zeros_like(prediction.feature_vector), np.ones_like(prediction.feature_vector), 3.0) | |
| with db(DB_PATH) as connection: | |
| model = _model_row(connection) | |
| calibration = _calibration(connection, model["id"]) if model else None | |
| threshold = calibration.threshold if calibration else 2.0 | |
| uncertainty = calibration.uncertainty(prediction.anomaly_score) if calibration else abs(prediction.anomaly_score - threshold) | |
| budget = Budget(false_accept_cost=false_accept_cost, false_reject_cost=false_reject_cost, human_review_cost=human_review_cost, max_review_rate=max_review_rate, max_latency_ms=max_latency_ms) | |
| decision = route(score=prediction.anomaly_score, threshold=threshold, uncertainty=uncertainty, shift_score=drift.score, brightness=float(quality["brightness_mean"]), latency_ms=prediction.elapsed_ms, policy=policy, budget=budget) | |
| run_id = uuid.uuid4().hex | |
| original_path = _safe_artifact_path(run_id, "original.png") | |
| shifted_path = _safe_artifact_path(run_id, "shifted.png") if shift != "none" else None | |
| heatmap_path = _safe_artifact_path(run_id, "heatmap.png") | |
| original_path.write_bytes(encode_png(rgb)) | |
| if shifted_path: | |
| shifted_path.write_bytes(encode_png(transformed)) | |
| heatmap_path.write_bytes(encode_png(blend_heatmap(transformed, prediction.heatmap))) | |
| prediction_json = {"anomaly_score": prediction.anomaly_score, "original_anomaly_score": original_prediction.anomaly_score, "uncertainty": uncertainty, "backend": prediction.backend, "device": prediction.device, "inference_latency_ms": prediction.elapsed_ms, "original_inference_latency_ms": original_prediction.elapsed_ms} | |
| with db(DB_PATH) as connection: | |
| row = connection.execute("INSERT INTO inspection_runs(image_asset_id,model_id,input_sha256,original_path,shifted_path,heatmap_path,shift_json,prediction_json,quality_json,decision_json) VALUES (?,?,?,?,?,?,?,?,?,?)", (asset_id, model["id"] if model else None, source_sha, str(original_path), str(shifted_path) if shifted_path else None, str(heatmap_path), json_dump(shift_params), json_dump(prediction_json), json_dump(quality), json_dump(decision.to_dict()))) | |
| inspection_id = row.lastrowid | |
| if decision.action == "HUMAN_REVIEW": | |
| connection.execute("INSERT INTO review_tasks(inspection_id) VALUES (?)", (inspection_id,)) | |
| connection.execute("INSERT INTO audit_events(event_type,entity_type,entity_id,payload_json) VALUES (?,?,?,?)", ("inspection_completed", "inspection", str(inspection_id), json_dump({"policy": policy, "decision": decision.to_dict()}))) | |
| return {"status": "COMPLETED", "inspection_id": inspection_id, "source": {"sha256": source_sha, "asset_id": asset_id}, "images": {"original_url": f"/api/v1/inspections/{inspection_id}/original", "shifted_url": f"/api/v1/inspections/{inspection_id}/shifted" if shifted_path else None, "heatmap_url": f"/api/v1/inspections/{inspection_id}/heatmap"}, "shift": shift_params, "prediction": prediction_json, "quality": quality, "shift_score": drift.__dict__, "decision": decision.to_dict()} | |
| def _inspection_row(inspection_id: int): | |
| with db(DB_PATH) as connection: | |
| return connection.execute("SELECT * FROM inspection_runs WHERE id=?", (inspection_id,)).fetchone() | |
| def _artifact_for(inspection_id: int, field: str): | |
| row = _inspection_row(inspection_id) | |
| if not row or not row[field]: | |
| raise HTTPException(404, "artifact unavailable") | |
| path = Path(row[field]) | |
| if not path.is_file(): | |
| raise HTTPException(404, "artifact unavailable") | |
| return FileResponse(path) | |
| def inspection_list(limit: int = 50) -> list[dict[str, object]]: | |
| with db(DB_PATH) as connection: | |
| rows = connection.execute("SELECT * FROM inspection_runs ORDER BY id DESC LIMIT ?", (min(max(limit, 1), 200),)).fetchall() | |
| return [{**_row(row), "prediction": json_load(row["prediction_json"]), "decision": json_load(row["decision_json"]), "quality": json_load(row["quality_json"]), "shift": json_load(row["shift_json"])} for row in rows] | |
| def inspection_detail(inspection_id: int) -> dict[str, object]: | |
| row = _inspection_row(inspection_id) | |
| if not row: | |
| raise HTTPException(404, "inspection not found") | |
| return {**_row(row), "prediction": json_load(row["prediction_json"]), "decision": json_load(row["decision_json"]), "quality": json_load(row["quality_json"]), "shift": json_load(row["shift_json"]), "images": {"original_url": f"/api/v1/inspections/{inspection_id}/original", "shifted_url": f"/api/v1/inspections/{inspection_id}/shifted" if row["shifted_path"] else None, "heatmap_url": f"/api/v1/inspections/{inspection_id}/heatmap"}} | |
| def inspection_original(inspection_id: int): | |
| return _artifact_for(inspection_id, "original_path") | |
| def inspection_shifted(inspection_id: int): | |
| return _artifact_for(inspection_id, "shifted_path") | |
| def inspection_heatmap(inspection_id: int): | |
| return _artifact_for(inspection_id, "heatmap_path") | |
| def reviews() -> list[dict[str, object]]: | |
| with db(DB_PATH) as connection: | |
| rows = connection.execute("SELECT * FROM review_tasks ORDER BY id DESC").fetchall() | |
| return [_row(row) for row in rows] | |
| def review(review_id: int, request: ReviewRequest) -> dict[str, object]: | |
| with db(DB_PATH) as connection: | |
| cursor = connection.execute("UPDATE review_tasks SET status='COMPLETED', reviewer_action=?, corrected_label=?, comments=?, updated_at=CURRENT_TIMESTAMP WHERE id=?", (request.reviewer_action, request.corrected_label, request.comments, review_id)) | |
| if cursor.rowcount == 0: | |
| raise HTTPException(404, "review task not found") | |
| connection.execute("INSERT INTO audit_events(event_type,entity_type,entity_id,payload_json) VALUES (?,?,?,?)", ("human_review_completed", "review_task", str(review_id), json_dump(request.model_dump() if hasattr(request, "model_dump") else request.dict()))) | |
| row = connection.execute("SELECT * FROM review_tasks WHERE id=?", (review_id,)).fetchone() | |
| return _row(row) | |