baseball-engine / examples /api_client.py
github-actions[bot]
Automated Deploy: d224e5e7e286809d46aa129b6ddaf8b604039efe
e21e264
Raw History Blame
3.72 kB
"""Upload, poll and download. API key comes from the environment, not source."""
import argparse
import json
import os
from pathlib import Path
import time
from contextlib import ExitStack
import requests
def main():
parser = argparse.ArgumentParser()
parser.add_argument("video", type=Path)
parser.add_argument("--url", required=True)
parser.add_argument("--options", type=Path)
parser.add_argument("--output", type=Path, default=Path("result.json"))
outputs = parser.add_mutually_exclusive_group()
outputs.add_argument("--coach-payload", action="store_true", help="Download the existing nine-field coach payload")
outputs.add_argument("--load-timing", action="store_true", help="Download the four-field version 3.0 timing payload using 2D only")
parser.add_argument('--include-evidence', action='store_true', help='With --load-timing, get 3.1 event intervals, context and reason codes')
parser.add_argument('--secondary-video', type=Path, help='Optional second view; options must include stereo_tracking calibration')
parser.add_argument("--wait-seconds", type=float, default=1900)
args = parser.parse_args()
if args.include_evidence and not args.load_timing:
parser.error('--include-evidence requires --load-timing')
key = os.environ.get("BASEBALL_API_KEY")
if not key: parser.error("Set BASEBALL_API_KEY")
base = args.url.rstrip("/")
options = json.loads(args.options.read_text()) if args.options else {}
if args.load_timing:
if options.get("measurement_backend", "2d") != "2d":
parser.error("--load-timing uses measurement_backend=2d; remove the 3D backend option")
options["measurement_backend"] = "2d"
with requests.Session() as client:
client.headers["Authorization"] = "Bearer " + key
with ExitStack() as files:
uploads = {'video': (args.video.name, files.enter_context(args.video.open('rb')))}
if args.secondary_video:
uploads['secondary_video'] = (args.secondary_video.name, files.enter_context(args.secondary_video.open('rb')))
response = client.post(base + ('/v1/load-timing/analyses' if args.load_timing else '/v1/analyses'), files=uploads,
data={"options": json.dumps(options)}, timeout=(10, 300))
response.raise_for_status()
job = response.json()
print("Job:", job["job_id"])
deadline = time.monotonic() + args.wait_seconds
while time.monotonic() < deadline:
response = client.get(base + job["status_url"], timeout=30)
response.raise_for_status()
status = response.json()
print(status["status"], status.get("progress"))
if status["status"] == "completed":
target = (job["load_timing_url"] if args.load_timing else
job["coach_payload_url"] if args.coach_payload else job["result_url"])
if args.include_evidence:
target = job['load_timing_evidence_url']
with client.get(base + target, stream=True, timeout=60) as result:
result.raise_for_status()
with args.output.open("wb") as out:
for block in result.iter_content(64 * 1024): out.write(block)
print("Saved:", args.output)
return
if status["status"] in {"failed", "cancelled"}:
raise RuntimeError("Job ended: " + str(status.get("error") or status["status"]))
time.sleep(3)
raise TimeoutError("Client wait ended; the server job can still be polled using its ID")
if __name__ == "__main__":
main()