File size: 3,722 Bytes
326d3cc
 
 
 
 
 
e21e264
326d3cc
 
 
 
 
 
 
 
 
1558b6d
 
 
e21e264
 
326d3cc
 
e21e264
 
326d3cc
 
 
 
1558b6d
 
 
 
326d3cc
 
e21e264
 
 
 
 
326d3cc
 
 
 
 
 
 
 
 
 
 
1558b6d
 
e21e264
 
326d3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""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()