Spaces:
Running on T4
Running on T4
Download baseball_batting/dataset.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 5.75 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/baseball_batting/dataset.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/baseball_batting/dataset.py
-
curl -L -o dataset.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/baseball_batting/dataset.py
5.75 kB
| """Reproducible grouped datasets from exact-video reviewed labels and source frames.""" | |
| from pathlib import Path | |
| import numpy as np | |
| from .storage import read_json, atomic_json, sha256_file, digest, StageCache | |
| from .ingest import ingest, iter_frames | |
| from .annotations import load_annotations | |
| from .learning import PHASES, BOUNDARIES, FEATURE_VERSION, features | |
| def validate_splits(records): | |
| seen={};sessions={};videos={} | |
| for record in records: | |
| player,session,split=record.get("player_id"),record.get("session_id"),record.get("split") | |
| if not player or not session or split not in {"train","validation","test"}:raise ValueError("Explicit athlete/session and split required") | |
| if player in seen and seen[player]!=split:raise ValueError("Athlete leakage across splits") | |
| if session in sessions and sessions[session]!=split:raise ValueError("Session leakage across splits") | |
| seen[player]=split;sessions[session]=split | |
| fingerprint=sha256_file(record["video_path"]) | |
| if fingerprint in videos and videos[fingerprint]!=split:raise ValueError("Identical video leakage across splits") | |
| videos[fingerprint]=split | |
| if set(seen.values())!={"train","validation","test"}:raise ValueError("Three nonempty grouped partitions required") | |
| return seen | |
| def make_dataset(index_path,output,kind): | |
| import cv2 | |
| records=read_json(index_path);validate_splits(records) | |
| output=Path(output);output.mkdir(parents=True,exist_ok=True);samples=[] | |
| for number,record in enumerate(records): | |
| capture=ingest(record["video_path"],record.get("metadata",{})) | |
| labels=load_annotations(record["annotations_path"],capture["input_sha256"],capture["frame_count"],capture["frames"][0]["width"],capture["frames"][0]["height"]) | |
| common={"player_id":record["player_id"],"session_id":record["session_id"],"split":record["split"], | |
| "input_sha256":capture["input_sha256"],"annotations_sha256":sha256_file(record["annotations_path"])} | |
| if kind=="endpoint_cnn": | |
| for i,_,_,image in iter_frames(record["video_path"],capture["rotation_degrees"]): | |
| label=labels.get("frames",{}).get(str(i),{});box=label.get("crop") | |
| if not box or not any(label.get(k) is not None for k in ("knob","barrel")):continue | |
| x1,y1,x2,y2=map(int,box);crop=cv2.resize(image[y1:y2,x1:x2],(256,256))[...,::-1].copy() | |
| target=np.zeros((2,64,64),np.float32);visible=np.zeros(2,np.float32);visibility_mask=np.zeros(2,np.float32) | |
| yy,xx=np.mgrid[:64,:64] | |
| for j,name in enumerate(("knob","barrel")): | |
| point=label.get(name) | |
| if point is not None: | |
| xy=(np.array(point)-[x1,y1])/[x2-x1,y2-y1]*64-.5 | |
| if not np.all((xy>=0)&(xy<64)):raise ValueError("Endpoint label lies outside its training crop") | |
| target[j]=np.exp(-((xx-xy[0])**2+(yy-xy[1])**2)/(2*1.5**2));visible[j]=1;visibility_mask[j]=1 | |
| elif label.get("bat_occluded") is True:visibility_mask[j]=1 | |
| path=output/f"endpoint_{number:05d}_{i:06d}.npz" | |
| np.savez_compressed(path,image=crop,heatmaps=target,visible=visible,visibility_mask=visibility_mask) | |
| samples.append({**common,"path":path.name,"frame_id":i}) | |
| else: | |
| directory=Path(record["analysis_directory"]) | |
| cache_index=read_json(directory/"observation_index.json") | |
| cache=StageCache(directory,"observations",cache_index["cache_key"]) | |
| from .observations import collect_observations | |
| observations=collect_observations(cache,cache_index["chunk_count"]) | |
| if cache_index["input_sha256"]!=capture["input_sha256"]:raise ValueError("Analysis/label video mismatch") | |
| x=features(observations,capture);n=capture["frame_count"] | |
| phase=np.full(n,-100,np.int64) | |
| for interval in labels.get("phases",[]): | |
| if interval["phase"] not in PHASES:raise ValueError("Unknown reviewed phase") | |
| a,b=interval["frame_interval"] | |
| if not 0<=a<=b<n or np.any(phase[a:b+1]!=-100):raise ValueError("Invalid/overlapping reviewed phases") | |
| phase[a:b+1]=PHASES.index(interval["phase"]) | |
| boundary=np.zeros((len(BOUNDARIES),n),np.float32);mask=np.zeros_like(boundary) | |
| presence=np.zeros(len(BOUNDARIES),np.float32);presence_mask=np.zeros_like(presence) | |
| for event in labels.get("events",[]): | |
| if event["type"] not in BOUNDARIES or event["state"]=="unknown":continue | |
| j=BOUNDARIES.index(event["type"]);presence_mask[j]=1;mask[j]=1 | |
| if event["state"]=="confirmed": | |
| a,b=event["frame_interval"];boundary[j,a:b+1]=1;presence[j]=1 | |
| if not np.any(phase!=-100):raise ValueError("Event training requires reviewed phase intervals") | |
| path=output/f"events_{number:05d}.npz" | |
| np.savez_compressed(path,features=x,phase=phase,boundary=boundary,boundary_mask=mask, | |
| presence=presence,presence_mask=presence_mask,frame_ids=np.arange(n)) | |
| samples.append({**common,"path":path.name}) | |
| if not samples:raise ValueError("No eligible reviewed training examples") | |
| manifest={"schema_version":"1.0","kind":kind,"feature_version":FEATURE_VERSION if kind=="mstcn_events" else None, | |
| "samples":samples,"index_sha256":sha256_file(index_path),"split_unit":"athlete_and_session", | |
| "artifact_hashes":{r["path"]:sha256_file(output/r["path"]) for r in samples}} | |
| atomic_json(output/"dataset.json",manifest);return manifest | |