Spaces:
Running
Running
Fix local progress and Colab handoff
Browse files36 unmodified lines373839404142146 unmodified lines189190191192193194311 unmodified lines506507508509510511512513514515516517518519520521522523524201 unmodified lines72672772872973073173273373473573673773873974074136 unmodified linesload_dotenv(Path(__file__).with_name(".env"))jobs = {}executor = ThreadPoolExecutor(max_workers=1)logger = logging.getLogger("sporalize")POSE_MODEL_FILE = "Weights/rtmpose-x-halpe26.onnx"146 unmodified lineslogger.info("Temporary Colab handoff cleanup skipped for %s: %s", remote_path, error)@lru_cache(maxsize=1)def runtime():root = Path(__file__).resolve().parent.parent / "Core"311 unmodified linesif reports is None:if job.get("cancel"):raise InterruptedError()job.update(status="running", progress=5, phase="Analyzing session", stage="analysis")pipeline, weights = runtime()def progress(action, total, frame, frames):action_number = action + 1frame_total = max(1, frames)job.update(progress=5 + 85 * (action + (frame + 1) / frame_total) / max(total, 1),phase=f"Analyzing action {action_number}/{total}", step=frame + 1,total=frame_total, action=action_number, actionsTotal=total,updatedAt=int(time.time() * 1000))return not job.get("cancel")reports = pipeline(cameras, {**weights, "CALIBRATION_PATH": str(work / "calibration.npz"), "ACTIONS_PATH": str(work / "actions.json")}, {"YOLO_IMGSZ": YOLO_IMGSZ}, progress)if job.get("cancel"):raise InterruptedError()(work / "results.json").write_text(json.dumps(json_value(reports), allow_nan=False), encoding="utf-8")201 unmodified lines@app.post("/api/cancel/{client_id}")def cancel(client_id: str, request: Request):job = owned_job(client_id, request.state.user_id, request.state.is_admin)if job["status"] not in {"completed", "failed", "cancelled", "sync_failed"}:job["cancel"] = Truereturn {"status": job["status"], "clientId": client_id}def cancel_session_job(session_id: UUID):matching = [(client_id, job) for client_id, job in list(jobs.items()) if job.get("sessionId") == str(session_id)]for client_id, job in matching:if job.get("status") in {"uploading", "queued", "running"}:job["cancel"] = Truefuture = job.get("future")if future is not None:try:36 unmodified lines37383940414243146 unmodified lines190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257311 unmodified lines569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603201 unmodified lines80580680780880981081181281381481581681781881982082182282336 unmodified linesload_dotenv(Path(__file__).with_name(".env"))jobs = {}jobs_lock = threading.RLock()executor = ThreadPoolExecutor(max_workers=1)logger = logging.getLogger("sporalize")POSE_MODEL_FILE = "Weights/rtmpose-x-halpe26.onnx"146 unmodified lineslogger.info("Temporary Colab handoff cleanup skipped for %s: %s", remote_path, error)def monitor_colab_worker(job, stop_event):if len(os.environ.get("COLAB_WORKER_SECRET", "")) < 32:returnwhile not stop_event.wait(10):if job.get("cancel") or job.get("stage") != "analysis":returnworker_url = registered_colab_worker()if stop_event.is_set():returnif not worker_url:continuewith jobs_lock:if stop_event.is_set() or job.get("cancel") or job.get("stage") != "analysis":returnjob.update(cancel=True,cancelReason="colab_handoff",handoffWorkerUrl=worker_url,phase="Colab connected; restarting analysis from the beginning",updatedAt=int(time.time() * 1000),)logger.info("Switching analysis %s from the primary server to Colab; restarting from the beginning", job["clientId"])returndef run_local_pipeline(pipeline, cameras, utils_paths, sizes, job, allow_colab_handoff=True):stop_event = threading.Event()monitor = Noneif allow_colab_handoff:monitor = threading.Thread(target=monitor_colab_worker, args=(job, stop_event), daemon=True)monitor.start()def progress(action, total, frame, frames):action_number = action + 1frame_total = max(1, frames)with jobs_lock:job.update(progress=5 + 85 * (action + (frame + 1) / frame_total) / max(total, 1),phase=f"Analyzing action {action_number}/{total}", step=frame + 1,total=frame_total, action=action_number, actionsTotal=total,updatedAt=int(time.time() * 1000))return not job.get("cancel")try:reports = pipeline(cameras, utils_paths, sizes, progress_cb=progress)except InterruptedError:with jobs_lock:if job.get("cancelReason") != "colab_handoff":raisereturn None, job.get("handoffWorkerUrl")finally:stop_event.set()if monitor is not None:monitor.join()with jobs_lock:if job.get("cancelReason") == "colab_handoff":return None, job.get("handoffWorkerUrl")if job.get("cancel"):raise InterruptedError("Processing cancelled by user")return reports, None@lru_cache(maxsize=1)def runtime():root = Path(__file__).resolve().parent.parent / "Core"311 unmodified linesif reports is None:if job.get("cancel"):raise InterruptedError()pipeline, weights = runtime()utils_paths = {**weights, "CALIBRATION_PATH": str(work / "calibration.npz"), "ACTIONS_PATH": str(work / "actions.json")}sizes = {"YOLO_IMGSZ": YOLO_IMGSZ}allow_handoff = worker_url is Nonewhile True:job.update(status="running", progress=5, phase="Analyzing session", stage="analysis",step=0, total=0, action=0, actionsTotal=0)reports, handoff_url = run_local_pipeline(pipeline, cameras, utils_paths, sizes, job, allow_colab_handoff=allow_handoff,)if not handoff_url:breakwith jobs_lock:if job.get("cancelReason") != "colab_handoff":raise InterruptedError("Processing cancelled by user")job.update(cancel=False, cancelReason=None, handoffWorkerUrl=None,status="running", progress=5, phase="Restarting analysis on Colab from the beginning",stage="analysis", step=0, total=0, action=0, actionsTotal=0,updatedAt=int(time.time() * 1000))logger.info("Restarting analysis %s on Colab from the original uploaded videos", client_id)reports = run_pipeline_on_colab(handoff_url, client_id, work, cameras, job)if reports is not None:breakif job.get("cancel"):raise InterruptedError()logger.warning("Colab handoff failed for analysis %s; restarting on the primary server", client_id)allow_handoff = Falseif job.get("cancel"):raise InterruptedError()(work / "results.json").write_text(json.dumps(json_value(reports), allow_nan=False), encoding="utf-8")201 unmodified lines@app.post("/api/cancel/{client_id}")def cancel(client_id: str, request: Request):job = owned_job(client_id, request.state.user_id, request.state.is_admin)with jobs_lock:if job["status"] not in {"completed", "failed", "cancelled", "sync_failed"}:job.update(cancel=True, cancelReason="user")return {"status": job["status"], "clientId": client_id}def cancel_session_job(session_id: UUID):matching = [(client_id, job) for client_id, job in list(jobs.items()) if job.get("sessionId") == str(session_id)]for client_id, job in matching:with jobs_lock:if job.get("status") in {"uploading", "queued", "running"}:job.update(cancel=True, cancelReason="delete")if job.get("status") in {"uploading", "queued", "running"}:future = job.get("future")if future is not None:try:
app.py+97-15