Spaces:
Running on T4
Running on T4
github-actions[bot] commited on
Commit ·
393a41f
1
Parent(s): 7a3215f
Automated Deploy: 5316883b2454a6786d5d8dde21d9368a7b7e7006
Browse files- baseball_batting/api_jobs.py +6 -0
- baseball_batting/job_terminal.py +89 -0
- docs/GPU_API_DEPLOYMENT.md +7 -0
- tests/test_job_terminal.py +83 -0
baseball_batting/api_jobs.py
CHANGED
|
@@ -328,11 +328,15 @@ class JobService:
|
|
| 328 |
|
| 329 |
def execute(self, identifier):
|
| 330 |
directory = self.job_directory(identifier)
|
|
|
|
|
|
|
|
|
|
| 331 |
process = None
|
| 332 |
try:
|
| 333 |
process = self.launch(self.command_factory(directory), directory / "worker.log")
|
| 334 |
started = time.monotonic()
|
| 335 |
while process.poll() is None:
|
|
|
|
| 336 |
current = self.store.get(identifier)
|
| 337 |
if current["status"] == "cancel_requested":
|
| 338 |
stop_process(process)
|
|
@@ -376,6 +380,8 @@ class JobService:
|
|
| 376 |
LOG.exception("Analysis job %s failed", identifier)
|
| 377 |
self.finish_failed(identifier, directory, "worker_error")
|
| 378 |
finally:
|
|
|
|
|
|
|
| 379 |
# Keep uploads only when a server restart will retry the job.
|
| 380 |
if self.store.get(identifier)["status"] in TERMINAL:
|
| 381 |
for video in directory.glob("input.*"):
|
|
|
|
| 328 |
|
| 329 |
def execute(self, identifier):
|
| 330 |
directory = self.job_directory(identifier)
|
| 331 |
+
from .job_terminal import JobTerminal
|
| 332 |
+
terminal = JobTerminal(identifier, directory)
|
| 333 |
+
terminal.emit('started')
|
| 334 |
process = None
|
| 335 |
try:
|
| 336 |
process = self.launch(self.command_factory(directory), directory / "worker.log")
|
| 337 |
started = time.monotonic()
|
| 338 |
while process.poll() is None:
|
| 339 |
+
terminal.progress()
|
| 340 |
current = self.store.get(identifier)
|
| 341 |
if current["status"] == "cancel_requested":
|
| 342 |
stop_process(process)
|
|
|
|
| 380 |
LOG.exception("Analysis job %s failed", identifier)
|
| 381 |
self.finish_failed(identifier, directory, "worker_error")
|
| 382 |
finally:
|
| 383 |
+
record = self.store.get(identifier)
|
| 384 |
+
terminal.finish(record['status'], record.get('error'))
|
| 385 |
# Keep uploads only when a server restart will retry the job.
|
| 386 |
if self.store.get(identifier)["status"] in TERMINAL:
|
| 387 |
for video in directory.glob("input.*"):
|
baseball_batting/job_terminal.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Concise server stdout summaries; never relay raw model output or inputs."""
|
| 2 |
+
import math
|
| 3 |
+
import re
|
| 4 |
+
import time
|
| 5 |
+
from .storage import read_json
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def _token(value):
|
| 9 |
+
return re.sub(r'[^a-zA-Z0-9_.-]', '_', str(value))[:100]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _read(path):
|
| 13 |
+
try:
|
| 14 |
+
data = read_json(path)
|
| 15 |
+
return data if isinstance(data, dict) else {}
|
| 16 |
+
except (OSError, ValueError):
|
| 17 |
+
return {}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class JobTerminal:
|
| 21 |
+
def __init__(self, identifier, directory, clock=time.monotonic):
|
| 22 |
+
self.identifier = _token(identifier)
|
| 23 |
+
self.directory = directory
|
| 24 |
+
self.clock = clock
|
| 25 |
+
self.started = clock()
|
| 26 |
+
self.last_poll = -math.inf
|
| 27 |
+
self.last_log = -math.inf
|
| 28 |
+
self.stage = None
|
| 29 |
+
self.count = None
|
| 30 |
+
|
| 31 |
+
def emit(self, message):
|
| 32 |
+
# stdout is captured by Docker/Hugging Face/systemd without configuring
|
| 33 |
+
# Python's root logger. A closed log stream must not fail a GPU job.
|
| 34 |
+
try:
|
| 35 |
+
print(f'[analysis {self.identifier}] {message}', flush=True)
|
| 36 |
+
except (OSError, ValueError):
|
| 37 |
+
pass
|
| 38 |
+
|
| 39 |
+
def progress(self, force=False):
|
| 40 |
+
now = self.clock()
|
| 41 |
+
if not force and now-self.last_poll < .5:
|
| 42 |
+
return
|
| 43 |
+
self.last_poll = now
|
| 44 |
+
row = _read(self.directory/'progress.json')
|
| 45 |
+
if not isinstance(row.get('stage'), str):
|
| 46 |
+
return
|
| 47 |
+
stage = _token(row['stage'])
|
| 48 |
+
done, total = row.get('completed_frames'), row.get('total_frames')
|
| 49 |
+
valid = (isinstance(done, int) and not isinstance(done, bool) and done >= 0 and
|
| 50 |
+
isinstance(total, int) and not isinstance(total, bool) and total > 0)
|
| 51 |
+
count = (done, total) if valid else None
|
| 52 |
+
if stage == self.stage and (now-self.last_log < 15 or (force and count == self.count)):
|
| 53 |
+
return
|
| 54 |
+
# Worker "complete" is artifact generation, not queue completion.
|
| 55 |
+
label = 'artifacts_ready' if stage == 'complete' else stage
|
| 56 |
+
suffix = f' {done}/{total} ({min(100, round(100*done/total))}%)' if valid else ''
|
| 57 |
+
self.emit(f'{label}{suffix} elapsed={now-self.started:.1f}s')
|
| 58 |
+
self.stage, self.count, self.last_log = stage, count, now
|
| 59 |
+
|
| 60 |
+
def finish(self, status, error=None):
|
| 61 |
+
self.progress(force=True)
|
| 62 |
+
if status == 'completed':
|
| 63 |
+
result = _read(self.directory/'result.json')
|
| 64 |
+
sampling, quality = result.get('sampling'), result.get('quality')
|
| 65 |
+
if isinstance(sampling, dict) and isinstance(quality, dict):
|
| 66 |
+
self.emit('result frames='+_token(sampling.get('frame_count', 'unknown'))+
|
| 67 |
+
' usable='+_token(quality.get('usable_frame_count', 'unknown')))
|
| 68 |
+
coordinates = result.get('coordinates')
|
| 69 |
+
if isinstance(coordinates, dict):
|
| 70 |
+
for name, key in (('up', 'up_estimation'), ('pitcher', 'pitcher_estimation')):
|
| 71 |
+
reference = coordinates.get(key)
|
| 72 |
+
if not isinstance(reference, dict):
|
| 73 |
+
continue
|
| 74 |
+
text = f'{name}={_token(reference.get("status", "unknown"))}'
|
| 75 |
+
vector = reference.get(name+'_vector')
|
| 76 |
+
if (isinstance(vector, (list, tuple)) and len(vector) == 3 and
|
| 77 |
+
all(isinstance(v, (int, float)) and math.isfinite(v) for v in vector)):
|
| 78 |
+
text += ' vector=['+', '.join(f'{v:.3f}' for v in vector)+']'
|
| 79 |
+
if reference.get('method'):
|
| 80 |
+
text += ' method='+_token(reference['method'])
|
| 81 |
+
if reference.get('reason_code'):
|
| 82 |
+
text += ' reason='+_token(reference['reason_code'])
|
| 83 |
+
self.emit(text)
|
| 84 |
+
elif status == 'failed':
|
| 85 |
+
reason = _read(self.directory/'error.json').get('reason_code')
|
| 86 |
+
if reason:
|
| 87 |
+
self.emit('failure_reason='+_token(reason))
|
| 88 |
+
suffix = ' error='+_token(error) if error else ''
|
| 89 |
+
self.emit(f'{_token(status)} elapsed={self.clock()-self.started:.1f}s{suffix}')
|
docs/GPU_API_DEPLOYMENT.md
CHANGED
|
@@ -82,6 +82,13 @@ Use one Uvicorn worker and one service replica per data directory. A file lock p
|
|
| 82 |
|
| 83 |
## Diagnose startup or a failed job
|
| 84 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
```bash
|
| 86 |
docker compose logs --tail=100 api
|
| 87 |
docker compose exec api cat /data/gpu-preflight.log
|
|
|
|
| 82 |
|
| 83 |
## Diagnose startup or a failed job
|
| 84 |
|
| 85 |
+
Analysis jobs print concise progress to the server terminal (Docker/container
|
| 86 |
+
stdout): job ID, stage changes, progress counts when available, a heartbeat every
|
| 87 |
+
15 seconds during long steps, and final status with elapsed time. Motion jobs
|
| 88 |
+
also summarize the up and pitcher directions, or the reason they are unknown.
|
| 89 |
+
Full model output stays in each job's `worker.log`; payloads and uploads are not
|
| 90 |
+
dumped to the terminal. Use `docker compose logs -f api` to follow live progress.
|
| 91 |
+
|
| 92 |
```bash
|
| 93 |
docker compose logs --tail=100 api
|
| 94 |
docker compose exec api cat /data/gpu-preflight.log
|
tests/test_job_terminal.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from baseball_batting.job_terminal import JobTerminal
|
| 3 |
+
from baseball_batting.storage import atomic_json
|
| 4 |
+
from test_api import fake_service, settings
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_progress_is_visible_but_throttled_with_heartbeat(tmp_path, capsys):
|
| 8 |
+
now = [0.]
|
| 9 |
+
log = JobTerminal('job-123', tmp_path, clock=lambda: now[0])
|
| 10 |
+
atomic_json(tmp_path/'progress.json', {'stage':'pose', 'completed_frames':0, 'total_frames':100})
|
| 11 |
+
log.progress()
|
| 12 |
+
for i in range(1, 15):
|
| 13 |
+
now[0] = i
|
| 14 |
+
atomic_json(tmp_path/'progress.json', {'stage':'pose', 'completed_frames':i, 'total_frames':100})
|
| 15 |
+
log.progress()
|
| 16 |
+
assert len(capsys.readouterr().out.splitlines()) == 1
|
| 17 |
+
now[0] = 15
|
| 18 |
+
log.progress()
|
| 19 |
+
assert '14/100 (14%)' in capsys.readouterr().out
|
| 20 |
+
now[0] = 30
|
| 21 |
+
log.progress()
|
| 22 |
+
assert 'elapsed=30.0s' in capsys.readouterr().out
|
| 23 |
+
now[0] = 31
|
| 24 |
+
atomic_json(tmp_path/'progress.json', {'stage':'measurements'})
|
| 25 |
+
log.progress()
|
| 26 |
+
assert 'measurements' in capsys.readouterr().out
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_results_are_short_and_do_not_dump_payloads(tmp_path, capsys):
|
| 30 |
+
atomic_json(tmp_path/'result.json', {'private':'DO_NOT_LOG', 'coordinates':{
|
| 31 |
+
'up_estimation':{'status':'estimated', 'up_vector':[0,-1,0], 'up_source':'DO_NOT_LOG'},
|
| 32 |
+
'pitcher_estimation':{'status':'unknown', 'reason_code':'insufficient_clear_home_plate_frames'}}})
|
| 33 |
+
JobTerminal('id', tmp_path).finish('completed')
|
| 34 |
+
out = capsys.readouterr().out
|
| 35 |
+
assert 'up=estimated vector=[0.000, -1.000, 0.000]' in out
|
| 36 |
+
assert 'pitcher=unknown reason=insufficient_clear_home_plate_frames' in out
|
| 37 |
+
assert 'completed elapsed=' in out and 'DO_NOT_LOG' not in out
|
| 38 |
+
assert len(out.splitlines()) == 3
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test_missing_and_partial_files_do_not_break_logging(tmp_path, capsys):
|
| 42 |
+
log = JobTerminal('id', tmp_path)
|
| 43 |
+
log.progress(force=True)
|
| 44 |
+
(tmp_path/'progress.json').write_text('{')
|
| 45 |
+
log.progress(force=True)
|
| 46 |
+
log.finish('cancelled')
|
| 47 |
+
assert 'cancelled' in capsys.readouterr().out
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_motion_result_reports_frame_counts(tmp_path, capsys):
|
| 51 |
+
atomic_json(tmp_path/'result.json', {'sampling':{'frame_count':120}, 'quality':{'usable_frame_count':112}})
|
| 52 |
+
JobTerminal('id', tmp_path).finish('completed')
|
| 53 |
+
assert 'result frames=120 usable=112' in capsys.readouterr().out
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_queue_relays_subprocess_progress_to_server_stdout(tmp_path, capsys):
|
| 57 |
+
service = fake_service(settings(tmp_path), delay=.7)
|
| 58 |
+
identifier = service.store.create(8)
|
| 59 |
+
directory = service.job_directory(identifier)
|
| 60 |
+
directory.mkdir()
|
| 61 |
+
service.store.update(identifier, 'queued')
|
| 62 |
+
assert service.store.claim() == identifier
|
| 63 |
+
service.execute(identifier)
|
| 64 |
+
out = capsys.readouterr().out
|
| 65 |
+
assert f'[analysis {identifier}] started' in out
|
| 66 |
+
assert 'pose_2d 1/2 (50%)' in out
|
| 67 |
+
assert 'completed elapsed=' in out
|
| 68 |
+
assert service.store.get(identifier)['status'] == 'completed'
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def test_failure_includes_public_reason_without_traceback(tmp_path, capsys):
|
| 72 |
+
service = fake_service(settings(tmp_path))
|
| 73 |
+
identifier = service.store.create(8)
|
| 74 |
+
directory = service.job_directory(identifier)
|
| 75 |
+
directory.mkdir()
|
| 76 |
+
atomic_json(directory/'error.json', {'code':'inference_failed', 'reason_code':'no_usable_motion', 'private':'DO_NOT_LOG'})
|
| 77 |
+
service.command_factory = lambda _: [sys.executable, '-c', 'raise SystemExit(1)']
|
| 78 |
+
service.store.update(identifier, 'queued')
|
| 79 |
+
service.store.claim()
|
| 80 |
+
service.execute(identifier)
|
| 81 |
+
out = capsys.readouterr().out
|
| 82 |
+
assert 'failure_reason=no_usable_motion' in out
|
| 83 |
+
assert 'failed elapsed=' in out and 'DO_NOT_LOG' not in out
|