Spaces:
Running on T4
Running on T4
Download baseball_batting/events.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 9.55 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/baseball_batting/events.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/baseball_batting/events.py
-
curl -L -o events.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/baseball_batting/events.py
9.55 kB
| """Conservative candidates. Projected overlap is never converted into contact.""" | |
| import numpy as np | |
| from .contracts import Event, RTMW_CORE | |
| def sustained(mask, length): | |
| return [i for i in range(max(0,len(mask)-length+1)) if np.all(mask[i:i+length])] | |
| def additional_candidates(curves, observations, capture, parameters): | |
| """Observable intervals with explicit context; these never assert contact.""" | |
| output = [] | |
| frames = observations["frames"]; n = len(frames) | |
| context = capture.get("metadata",{}).get("event_context", {}) | |
| run = parameters["sustained_frames"] | |
| hands = (curves["left_hand_path_pixels"]+curves["right_hand_path_pixels"])/2 | |
| delta = np.diff(hands,axis=0) | |
| threshold = parameters["motion_threshold_px_per_frame"] | |
| fixed = capture["camera_stability"] == "fixed_verified" | |
| direction = context.get("pitcher_direction_image") | |
| if fixed and context.get("source") and direction is not None: | |
| direction = np.asarray(direction,float) | |
| if direction.shape != (2,) or not np.isfinite(direction).all() or np.linalg.norm(direction)<1e-8: | |
| raise ValueError("Pitcher image direction must be a documented finite nonzero xy vector") | |
| along = delta@(direction/np.linalg.norm(direction)) | |
| forward = sustained(np.isfinite(along)&(along>threshold),run) | |
| load = sustained(np.isfinite(along)&(along<-threshold),run) | |
| if forward: | |
| a=forward[0];output.append(Event("forward_candidate","forward_swing_onset","candidate",[a,a+run],list(range(a,a+run+1)),"documented_direction_projected_hand_motion_v2")) | |
| if load: | |
| a=load[0];end=next((i for i in forward if i>a),min(a+run,n-1)) | |
| output.append(Event("load_candidate","load","candidate",[a,end],list(range(a,end+1)),"documented_opposing_projected_hand_motion_v2")) | |
| lead = context.get("lead_side") | |
| ground = context.get("ground_line_image") | |
| if fixed and context.get("source") and lead in {"left","right"} and ground is not None: | |
| line=np.asarray(ground,float) | |
| if line.shape!=(3,) or not np.isfinite(line).all() or np.linalg.norm(line[:2])<1e-8: raise ValueError("Ground line requires finite ax+by+c=0 coefficients") | |
| foot=curves["body_pixels"][:,RTMW_CORE[lead+"_big_toe"]] | |
| height=np.abs(np.c_[foot,np.ones(n)]@line)/np.linalg.norm(line[:2]) | |
| tolerance=parameters.get("ground_tolerance_px",5.) | |
| lifted=sustained(np.isfinite(height)&(height>2*tolerance),run) | |
| landed=sustained(np.isfinite(height)&(height<tolerance),run) | |
| if lifted: | |
| a=lifted[0];output.append(Event("foot_lift_candidate","lead_foot_lift","candidate",[a,a+run],list(range(a,a+run+1)),"documented_ground_projected_foot_distance_v2")) | |
| landing=next((i for i in landed if i>a+run),None) | |
| if landing is not None: | |
| output.append(Event("foot_contact_candidate","lead_foot_contact","candidate",[landing,landing+run],list(range(landing,landing+run+1)),"projected_ground_return_v2",notes=["Projected ground return alone does not prove physical foot contact"])) | |
| bat=curves.get("bat_endpoints_pixels") | |
| if bat is None: | |
| bat=np.full((n,2,2),np.nan) | |
| for i,f in enumerate(frames): | |
| if f["bat"].get("points") is not None and all(s in {"manual","image_supported"} for s in f["bat"]["states"]):bat[i]=f["bat"]["points"] | |
| ball=np.full((n,2),np.nan) | |
| for i,f in enumerate(frames): | |
| if f["ball"].get("point") is not None and f["ball"]["state"] in {"manual","model_inferred","image_supported"}: | |
| ball[i]=f["ball"]["point"] | |
| shaft=bat[:,1]-bat[:,0];length2=np.sum(shaft**2,axis=1) | |
| fraction=np.clip(np.sum((ball-bat[:,0])*shaft,axis=1)/np.where(length2>1e-8,length2,np.nan),0,1) | |
| distance=np.linalg.norm(ball-(bat[:,0]+fraction[:,None]*shaft),axis=1) | |
| eligible=np.flatnonzero(np.isfinite(distance)&(fraction>=.5)) | |
| if len(eligible): | |
| i=int(eligible[np.argmin(distance[eligible])]) | |
| output.append(Event("closest_projected_approach","closest_projected_approach","candidate",[i,i],[i],"measured_projected_ball_shaft_distance_v2",notes=[f"Projected distance {distance[i]:.2f}px; no physical collision established"])) | |
| radius=parameters.get("interaction_distance_px",8.) | |
| if distance[i]<=radius and 1<=i<n-3 and np.isfinite(ball[i-1:i+4]).all(): | |
| outgoing=np.diff(ball[i:i+4],axis=0) | |
| incoming=ball[i]-ball[i-1] | |
| if np.linalg.norm(incoming)>1 and np.all(np.linalg.norm(outgoing,axis=1)>1): | |
| cosine=np.dot(incoming,outgoing[0])/(np.linalg.norm(incoming)*np.linalg.norm(outgoing[0])) | |
| if cosine < parameters.get("outgoing_direction_cosine_max",.5): | |
| output.append(Event("interaction_candidate","bat_ball_interaction","candidate",[max(i-1,0),i+1],list(range(i-1,i+4)),"projected_approach_and_changed_outgoing_ball_v2",notes=["Requires review; detector association and image projection may mimic interaction"])) | |
| movement=np.linalg.norm(delta,axis=1) | |
| high=sustained(np.isfinite(movement)&(movement>threshold),run) | |
| settled=sustained(np.isfinite(movement)&(movement<threshold*.5),run) | |
| if fixed and high: | |
| end=next((i for i in settled if i>high[-1]+run),None) | |
| if end is not None and end+run<n-1: | |
| output.append(Event("follow_candidate","follow_through","candidate",[end,end+run],list(range(end,end+run+1)),"visible_post_motion_settling_v2",notes=["Visible settling candidate; not inferred from clip termination"])) | |
| audio=capture.get("metadata",{}).get("audio",{}) | |
| if audio.get("source") and audio.get("synchronization_verified") is True: | |
| offset=audio.get("offset_to_video_s");delay=audio.get("propagation_delay_s") | |
| if isinstance(offset,(int,float)) and isinstance(delay,(int,float)): | |
| times=np.array([f["playback_s"] for f in capture["frames"]],float) | |
| for peak in audio.get("reviewed_impulse_times_s",[]): | |
| time=float(peak)+offset-delay | |
| for event in output: | |
| if event.type=="bat_ball_interaction" and event.frame_interval: | |
| a,b=event.frame_interval | |
| if times[a]-.05<=time<=times[b]+.05: event.notes.append("Synchronized reviewed audio impulse corroborates candidate; audio alone cannot confirm contact") | |
| return output | |
| def detect_events(curves, observations, capture, annotations, parameters): | |
| events = [] | |
| # Hand motion supports a generic onset candidate; direction is not inferred from view. | |
| left, right = curves["left_hand_path_pixels"], curves["right_hand_path_pixels"] | |
| with np.errstate(invalid="ignore"): | |
| hands = (left+right)/2 | |
| movement = np.linalg.norm(np.diff(hands, axis=0), axis=1) | |
| threshold = parameters["motion_threshold_px_per_frame"] | |
| run = parameters["sustained_frames"] | |
| onset = None | |
| if capture["camera_stability"] == "fixed_verified" and np.isfinite(hands).all(axis=1).sum() >= parameters["min_visible_frames"]: | |
| for i in range(max(0, len(movement)-run+1)): | |
| if np.all(np.isfinite(movement[i:i+run])) and np.all(movement[i:i+run] > threshold): | |
| onset = i | |
| break | |
| if onset is not None: | |
| events.append(Event("hand_motion_onset_candidate", "hand_motion_onset", "candidate", [onset, onset+run], | |
| list(range(onset, onset+run+1)), "sustained_projected_hand_motion_v1", | |
| notes=["May be loading or forward motion; not a confirmed forward-swing boundary"])) | |
| events.append(Event("forward_swing_onset", "forward_swing_onset", "unknown", None, [], "directional_evidence_not_established")) | |
| events.append(Event("contact", "contact", "unknown", None, [], "no_qualified_contact_evidence", | |
| notes=["Missing contact evidence does not prove a miss or a dry swing"])) | |
| events.append(Event("lead_foot_contact", "lead_foot_contact", "unknown", None, [], "ground_and_visibility_not_established")) | |
| events.append(Event("load", "load", "unknown", None, [], "phase_not_confirmed")) | |
| events.append(Event("follow_through", "follow_through", "unknown", None, [], "clip_end_is_not_biomechanical_endpoint")) | |
| for candidate in additional_candidates(curves,observations,capture,parameters): | |
| events=[e for e in events if not (e.type==candidate.type and e.state=="unknown")] | |
| events.append(candidate) | |
| for i, label in enumerate(annotations.get("events", [])): | |
| event_type = label["type"] | |
| events = [e for e in events if e.type != event_type] | |
| events.append(Event(f"reviewed_{event_type}_{i}", event_type, label["state"], label.get("frame_interval"), | |
| label.get("evidence_frames", []), "human_review", "reviewed", annotations["annotator"], | |
| notes=[label.get("evidence_description", "Footage does not establish this event")])) | |
| outcome = [e for e in events if e.type in {"contact", "miss", "dry_swing"} and e.state == "confirmed"] | |
| if len({e.type for e in outcome}) > 1: | |
| raise ValueError("Conflicting confirmed hit/miss/dry outcomes; resolve review") | |
| for e in events: | |
| if e.frame_interval: | |
| a, b = e.frame_interval | |
| e.playback_interval_s = [capture["frames"][a]["playback_s"], capture["frames"][b]["playback_s"]] | |
| e.physical_interval_s = [capture["frames"][a]["physical_s"], capture["frames"][b]["physical_s"]] | |
| return events | |