Spaces:
Running on T4
Running on T4
Download baseball_batting/api_jobs.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 20.3 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/baseball_batting/api_jobs.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/baseball_batting/api_jobs.py
-
curl -L -o api_jobs.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/baseball_batting/api_jobs.py
20.3 kB
| """Durable single-GPU queue with isolated, cancellable subprocesses.""" | |
| from dataclasses import dataclass | |
| from contextlib import contextmanager | |
| import fcntl | |
| import logging | |
| import os | |
| from pathlib import Path | |
| import shutil | |
| import signal | |
| import sqlite3 | |
| import subprocess | |
| import sys | |
| import threading | |
| import time | |
| import uuid | |
| from .storage import read_json, sha256_file | |
| LOG = logging.getLogger(__name__) | |
| ACTIVE = ("uploading", "queued", "running", "cancel_requested") | |
| TERMINAL = ("completed", "failed", "cancelled") | |
| class ApiSettings: | |
| api_key: str | |
| data_root: Path = Path("api-data") | |
| model_root: Path = Path("downloads") | |
| max_upload_bytes: int = 512 * 1024 * 1024 | |
| max_active_jobs: int = 8 | |
| max_frames: int = 7200 | |
| max_pixels: int = 8294400 | |
| max_duration_s: float = 120 | |
| job_timeout_s: float = 1800 | |
| retention_s: float = 86400 | |
| minimum_free_bytes: int = 1024 * 1024 * 1024 | |
| def __post_init__(self): | |
| if len(self.api_key) < 16: | |
| raise ValueError("Set BASEBALL_API_KEY to a secret of at least 16 characters") | |
| self.data_root, self.model_root = Path(self.data_root).resolve(), Path(self.model_root).resolve() | |
| for value in (self.max_upload_bytes, self.max_active_jobs, self.max_frames, | |
| self.max_pixels, self.max_duration_s, self.job_timeout_s, self.retention_s): | |
| if value <= 0: | |
| raise ValueError("API limits must be positive") | |
| if self.minimum_free_bytes < 0: | |
| raise ValueError("Free disk reserve must not be negative") | |
| def from_env(cls): | |
| return cls(api_key=os.environ.get("BASEBALL_API_KEY", ""), | |
| data_root=Path(os.environ.get("BASEBALL_DATA_ROOT", "/data")), | |
| model_root=Path(os.environ.get("BASEBALL_MODEL_ROOT", "/opt/models")), | |
| max_upload_bytes=int(os.environ.get("BASEBALL_MAX_UPLOAD_MB", "512")) * 1024 * 1024, | |
| max_active_jobs=int(os.environ.get("BASEBALL_MAX_ACTIVE_JOBS", "8")), | |
| max_frames=int(os.environ.get("BASEBALL_MAX_FRAMES", "7200")), | |
| max_pixels=int(os.environ.get("BASEBALL_MAX_PIXELS", "8294400")), | |
| max_duration_s=float(os.environ.get("BASEBALL_MAX_DURATION_S", "120")), | |
| job_timeout_s=float(os.environ.get("BASEBALL_JOB_TIMEOUT_S", "1800")), | |
| retention_s=float(os.environ.get("BASEBALL_RETENTION_HOURS", "24")) * 3600, | |
| minimum_free_bytes=int(os.environ.get("BASEBALL_DISK_RESERVE_MB", "1024")) * 1024 * 1024) | |
| class QueueFull(Exception): pass | |
| class JobStore: | |
| def __init__(self, root): | |
| self.root = Path(root) | |
| self.root.mkdir(parents=True, exist_ok=True) | |
| self.path = self.root / "jobs.sqlite3" | |
| with self.connect() as db: | |
| db.execute("PRAGMA journal_mode=WAL") | |
| db.execute("""CREATE TABLE IF NOT EXISTS jobs ( | |
| id TEXT PRIMARY KEY, status TEXT NOT NULL, created REAL NOT NULL, | |
| updated REAL NOT NULL, error TEXT, result_sha256 TEXT, coach_payload_sha256 TEXT, | |
| load_timing_sha256 TEXT)""") | |
| if "coach_payload_sha256" not in {r[1] for r in db.execute("PRAGMA table_info(jobs)")}: | |
| db.execute("ALTER TABLE jobs ADD COLUMN coach_payload_sha256 TEXT") | |
| if "load_timing_sha256" not in {r[1] for r in db.execute("PRAGMA table_info(jobs)")}: | |
| db.execute("ALTER TABLE jobs ADD COLUMN load_timing_sha256 TEXT") | |
| if 'timing_evidence_sha256' not in {r[1] for r in db.execute('PRAGMA table_info(jobs)')}: | |
| db.execute('ALTER TABLE jobs ADD COLUMN timing_evidence_sha256 TEXT') | |
| if 'product_sha256' not in {r[1] for r in db.execute('PRAGMA table_info(jobs)')}: | |
| db.execute('ALTER TABLE jobs ADD COLUMN product_sha256 TEXT') | |
| if 'swings_sha256' not in {r[1] for r in db.execute('PRAGMA table_info(jobs)')}: | |
| db.execute('ALTER TABLE jobs ADD COLUMN swings_sha256 TEXT') | |
| if 'kind' not in {r[1] for r in db.execute('PRAGMA table_info(jobs)')}: | |
| db.execute("ALTER TABLE jobs ADD COLUMN kind TEXT NOT NULL DEFAULT 'legacy'") | |
| db.execute('CREATE TABLE IF NOT EXISTS motion_revisions (analysis_id TEXT NOT NULL, revision INTEGER NOT NULL, job_id TEXT UNIQUE NOT NULL, parent_job_id TEXT, PRIMARY KEY (analysis_id, revision))') | |
| def connect(self): | |
| db = sqlite3.connect(self.path, timeout=30) | |
| try: | |
| with db: | |
| yield db | |
| finally: | |
| db.close() | |
| def create(self, max_active, kind='legacy'): | |
| now, identifier = time.time(), uuid.uuid4().hex | |
| with self.connect() as db: | |
| db.execute("BEGIN IMMEDIATE") | |
| active = db.execute("SELECT COUNT(*) FROM jobs WHERE status IN (?,?,?,?)", ACTIVE).fetchone()[0] | |
| if active >= max_active: raise QueueFull() | |
| db.execute("INSERT INTO jobs (id,status,created,updated,kind) VALUES (?, 'uploading', ?, ?, ?)", (identifier, now, now, kind)) | |
| return identifier | |
| def get(self, identifier): | |
| with self.connect() as db: | |
| db.row_factory = sqlite3.Row | |
| value = db.execute("SELECT * FROM jobs WHERE id=?", (identifier,)).fetchone() | |
| return dict(value) if value else None | |
| def create_motion(self,max_active,parent_job_id=None): | |
| now=time.time();identifier=uuid.uuid4().hex | |
| with self.connect() as db: | |
| db.execute('BEGIN IMMEDIATE') | |
| if db.execute('SELECT COUNT(*) FROM jobs WHERE status IN (?,?,?,?)',ACTIVE).fetchone()[0]>=max_active: | |
| raise QueueFull() | |
| root=identifier;revision=1 | |
| if parent_job_id: | |
| parent=db.execute('SELECT analysis_id FROM motion_revisions WHERE job_id=?',(parent_job_id,)).fetchone() | |
| if parent is None:raise ValueError('Motion parent not found') | |
| root=parent[0] | |
| revision=db.execute('SELECT MAX(revision) FROM motion_revisions WHERE analysis_id=?',(root,)).fetchone()[0]+1 | |
| db.execute("INSERT INTO jobs (id,status,created,updated,kind) VALUES (?, 'uploading', ?, ?, 'motion_player')",(identifier,now,now)) | |
| db.execute('INSERT INTO motion_revisions VALUES (?,?,?,?)',(root,revision,identifier,parent_job_id)) | |
| return {'job_id':identifier,'analysis_id':root,'analysis_revision':revision,'parent_job_id':parent_job_id} | |
| def motion_lineage(self,identifier): | |
| with self.connect() as db: | |
| row=db.execute('SELECT analysis_id, revision, parent_job_id FROM motion_revisions WHERE job_id=?',(identifier,)).fetchone() | |
| return {'job_id':identifier,'analysis_id':row[0],'analysis_revision':row[1],'parent_job_id':row[2]} if row else None | |
| def update(self, identifier, status, error=None, result_hash=None, coach_hash=None, timing_hash=None, evidence_hash=None, product_hash=None, swings_hash=None): | |
| with self.connect() as db: | |
| db.execute("UPDATE jobs SET status=?, updated=?, error=?, result_sha256=?, coach_payload_sha256=?, load_timing_sha256=?, timing_evidence_sha256=?, product_sha256=?, swings_sha256=? WHERE id=?", | |
| (status, time.time(), error, result_hash, coach_hash, timing_hash, evidence_hash, product_hash, swings_hash, identifier)) | |
| def claim(self): | |
| with self.connect() as db: | |
| db.execute("BEGIN IMMEDIATE") | |
| row = db.execute("SELECT id FROM jobs WHERE status='queued' ORDER BY created LIMIT 1").fetchone() | |
| if row: | |
| db.execute("UPDATE jobs SET status='running', updated=? WHERE id=?", (time.time(), row[0])) | |
| return row[0] | |
| def update_product(self, identifier, product_hash): | |
| """Preserve all measurement checksums when retrying optional video feedback.""" | |
| with self.connect() as db: | |
| db.execute("UPDATE jobs SET updated=?, product_sha256=? WHERE id=? AND status='completed'", | |
| (time.time(), product_hash, identifier)) | |
| def cancel(self, identifier): | |
| with self.connect() as db: | |
| db.execute("BEGIN IMMEDIATE") | |
| row = db.execute("SELECT status FROM jobs WHERE id=?", (identifier,)).fetchone() | |
| if not row: return None | |
| status = "cancel_requested" if row[0] in ("running", "cancel_requested") else "cancelled" | |
| db.execute("UPDATE jobs SET status=?, updated=?, result_sha256=NULL, coach_payload_sha256=NULL, load_timing_sha256=NULL, timing_evidence_sha256=NULL, product_sha256=NULL, swings_sha256=NULL WHERE id=?", | |
| (status, time.time(), identifier)) | |
| return status | |
| def recover(self): | |
| with self.connect() as db: | |
| # Retired contact jobs must never fall back to the batting worker. | |
| # Keep their records and artifacts until normal retention expires. | |
| db.execute("UPDATE jobs SET status='failed', error='api_removed', updated=? " | |
| "WHERE kind='contact' AND status IN (?,?,?,?)", (time.time(), *ACTIVE)) | |
| uploads = [r[0] for r in db.execute("SELECT id FROM jobs WHERE status='uploading'")] | |
| cancellations = [r[0] for r in db.execute("SELECT id FROM jobs WHERE status='cancel_requested'")] | |
| db.execute("DELETE FROM jobs WHERE status='uploading'") | |
| db.execute("UPDATE jobs SET status='queued', updated=? WHERE status='running'", (time.time(),)) | |
| db.execute("UPDATE jobs SET status='cancelled', updated=? WHERE status='cancel_requested'", (time.time(),)) | |
| return uploads + cancellations | |
| def forget(self, identifier): | |
| with self.connect() as db: | |
| db.execute("DELETE FROM jobs WHERE id=?", (identifier,)) | |
| db.execute('DELETE FROM motion_revisions WHERE job_id=?',(identifier,)) | |
| def expired(self, cutoff): | |
| with self.connect() as db: | |
| return [r[0] for r in db.execute( | |
| "SELECT id FROM jobs WHERE status IN (?,?,?) AND updated < ?", (*TERMINAL, cutoff))] | |
| def stop_process(process): | |
| if process.poll() is not None: return | |
| try: | |
| os.killpg(process.pid, signal.SIGTERM) | |
| process.wait(timeout=3) | |
| except subprocess.TimeoutExpired: | |
| os.killpg(process.pid, signal.SIGKILL) | |
| process.wait(timeout=3) | |
| except ProcessLookupError: | |
| process.wait(timeout=3) | |
| class JobService: | |
| def __init__(self, settings, command_factory=None, preflight_command=None): | |
| self.settings = settings | |
| self.store = JobStore(settings.data_root) | |
| self.jobs_root = settings.data_root / "jobs" | |
| self.jobs_root.mkdir(exist_ok=True) | |
| self.command_factory = command_factory or self.job_command | |
| self.preflight_command = preflight_command or [sys.executable, "-m", "baseball_batting.api_worker", | |
| "--preflight", "--models", str(settings.model_root), "--output", str(settings.data_root / "gpu-ready.json")] | |
| self.ready = False | |
| self.tracking_ready = False | |
| self.visual_model_status = {'status': 'not_checked'} | |
| self.readiness_reason = "gpu_preflight_pending" | |
| self.stopping = threading.Event() | |
| self.wakeup = threading.Event() | |
| self.thread = None | |
| self.lock = None | |
| # Serializes completion/cancellation and deletion against result downloads. | |
| self.mutation_lock = threading.RLock() | |
| def job_directory(self, identifier): | |
| if len(identifier) != 32 or any(c not in "0123456789abcdef" for c in identifier): | |
| raise ValueError("Invalid job ID") | |
| return self.jobs_root / identifier | |
| def job_command(self, directory): | |
| s = self.settings | |
| kind=(self.store.get(directory.name) or {}).get('kind') | |
| if kind not in {'legacy', 'sam_batting', 'motion_player'}: | |
| raise ValueError('Unsupported analysis job kind') | |
| module={'sam_batting':'baseball_batting.sam_measurement_worker','motion_player':'baseball_batting.motion_worker'}.get(kind,'baseball_batting.api_worker') | |
| command=[sys.executable, "-m", module, "--models", str(s.model_root), | |
| "--job", str(directory), "--max-frames", str(s.max_frames), | |
| "--max-pixels", str(s.max_pixels), "--max-duration", str(s.max_duration_s)] | |
| if kind=='motion_player':command+=['--retention-s',str(s.retention_s)] | |
| return command | |
| def start(self): | |
| self.lock = (self.settings.data_root / ".service.lock").open("a") | |
| try: | |
| fcntl.flock(self.lock, fcntl.LOCK_EX | fcntl.LOCK_NB) | |
| except BlockingIOError: | |
| self.lock.close() | |
| raise RuntimeError("This data directory already has an API worker; use one Uvicorn worker") | |
| for identifier in self.store.recover(): | |
| shutil.rmtree(self.job_directory(identifier), ignore_errors=True) | |
| self.thread = threading.Thread(target=self.loop, name="gpu-job-queue", daemon=True) | |
| self.thread.start() | |
| def stop(self): | |
| self.ready = False | |
| self.stopping.set(); self.wakeup.set() | |
| if self.thread: | |
| self.thread.join(timeout=15) | |
| if self.thread.is_alive(): | |
| raise RuntimeError("GPU worker did not stop") | |
| if self.lock: | |
| self.lock.close() | |
| def environment(self): | |
| env = dict(os.environ) | |
| # The inference subprocess does not need the service credential. | |
| env.pop("BASEBALL_API_KEY", None) | |
| env["MPLBACKEND"] = "Agg"; env["PYTHONUNBUFFERED"] = "1" | |
| repo = str(Path(__file__).resolve().parents[1]) | |
| env["PYTHONPATH"] = repo + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "") | |
| return env | |
| def launch(self, command, log_path): | |
| with Path(log_path).open("wb") as log: | |
| return subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, | |
| env=self.environment(), start_new_session=True) | |
| def delete(self, identifier): | |
| with self.mutation_lock: | |
| status = self.store.cancel(identifier) | |
| if status == "cancelled": | |
| shutil.rmtree(self.job_directory(identifier), ignore_errors=True) | |
| self.wakeup.set() | |
| return status | |
| def cleanup(self): | |
| with self.mutation_lock: | |
| for identifier in self.store.expired(time.time() - self.settings.retention_s): | |
| shutil.rmtree(self.job_directory(identifier), ignore_errors=True) | |
| self.store.forget(identifier) | |
| def finish_failed(self, identifier, directory, code): | |
| with self.mutation_lock: | |
| if self.store.get(identifier)["status"] == "cancel_requested": | |
| self.store.update(identifier, "cancelled") | |
| shutil.rmtree(directory, ignore_errors=True) | |
| else: | |
| self.store.update(identifier, "failed", code) | |
| def loop(self): | |
| try: | |
| readiness_path = self.settings.data_root/'gpu-ready.json' | |
| readiness_path.unlink(missing_ok=True) | |
| preflight = self.launch(self.preflight_command, self.settings.data_root / "gpu-preflight.log") | |
| start = time.monotonic() | |
| while preflight.poll() is None: | |
| if self.stopping.wait(.1) or time.monotonic() - start > 300: | |
| stop_process(preflight) | |
| self.readiness_reason = "gpu_preflight_timeout" | |
| return | |
| if preflight.returncode: | |
| self.readiness_reason = "gpu_preflight_failed" | |
| return | |
| if readiness_path.is_file(): | |
| record = read_json(readiness_path) | |
| self.tracking_ready = record.get('ready') is True and record.get('bat_ball_tracking') is True | |
| self.visual_model_status = record.get('visual_model_status', {'status': 'not_checked'}) | |
| self.ready = True; self.readiness_reason = "ready" | |
| while not self.stopping.is_set(): | |
| self.cleanup() | |
| identifier = self.store.claim() | |
| if identifier: | |
| self.execute(identifier) | |
| else: | |
| self.wakeup.wait(.5); self.wakeup.clear() | |
| except Exception: | |
| self.readiness_reason = "queue_worker_failed" | |
| LOG.exception("GPU job queue stopped") | |
| finally: | |
| self.ready = False | |
| self.tracking_ready = False | |
| def execute(self, identifier): | |
| directory = self.job_directory(identifier) | |
| from .job_terminal import JobTerminal | |
| terminal = JobTerminal(identifier, directory) | |
| terminal.emit('started') | |
| process = None | |
| try: | |
| process = self.launch(self.command_factory(directory), directory / "worker.log") | |
| started = time.monotonic() | |
| while process.poll() is None: | |
| terminal.progress() | |
| current = self.store.get(identifier) | |
| if current["status"] == "cancel_requested": | |
| stop_process(process) | |
| with self.mutation_lock: | |
| self.store.update(identifier, "cancelled") | |
| shutil.rmtree(directory, ignore_errors=True) | |
| return | |
| if self.stopping.wait(.1): | |
| stop_process(process) | |
| with self.mutation_lock: | |
| if self.store.get(identifier)["status"] == "cancel_requested": | |
| self.store.update(identifier, "cancelled") | |
| shutil.rmtree(directory, ignore_errors=True) | |
| else: | |
| self.store.update(identifier, "queued") | |
| return | |
| if time.monotonic() - started > self.settings.job_timeout_s: | |
| stop_process(process) | |
| self.finish_failed(identifier, directory, "job_timeout") | |
| return | |
| with self.mutation_lock: | |
| if self.store.get(identifier)["status"] == "cancel_requested": | |
| self.store.update(identifier, "cancelled") | |
| shutil.rmtree(directory, ignore_errors=True) | |
| elif process.returncode == 0 and (directory / "result.json").is_file(): | |
| coach_path = directory / "coach-payload.json" | |
| timing_path = directory / "load-timing.json" | |
| self.store.update(identifier, "completed", result_hash=sha256_file(directory / "result.json"), | |
| coach_hash=sha256_file(coach_path) if coach_path.is_file() else None, | |
| timing_hash=sha256_file(timing_path) if timing_path.is_file() else None, | |
| evidence_hash=sha256_file(directory/'load-timing-evidence.json') if (directory/'load-timing-evidence.json').is_file() else None, | |
| product_hash=sha256_file(directory/'product.json') if (directory/'product.json').is_file() else None, | |
| swings_hash=sha256_file(directory/'swings.json') if (directory/'swings.json').is_file() else None) | |
| else: | |
| error = read_json(directory / "error.json") if (directory / "error.json").exists() else {} | |
| code = error.get("code") | |
| if code not in {"invalid_video_or_capture", "inference_failed"}: code = "inference_failed" | |
| self.store.update(identifier, "failed", code) | |
| except Exception: | |
| if process: stop_process(process) | |
| LOG.exception("Analysis job %s failed", identifier) | |
| self.finish_failed(identifier, directory, "worker_error") | |
| finally: | |
| record = self.store.get(identifier) | |
| terminal.finish(record['status'], record.get('error')) | |
| # Keep uploads only when a server restart will retry the job. | |
| if self.store.get(identifier)["status"] in TERMINAL: | |
| for video in directory.glob("input.*"): | |
| video.unlink(missing_ok=True) | |
| for video in directory.glob('secondary.*'): | |
| video.unlink(missing_ok=True) | |