"""Trainable endpoints and phase/boundary heads. Candidate weights do not auto-activate.""" from pathlib import Path import importlib.util import subprocess import numpy as np from .storage import read_json, sha256_file, digest, atomic_json from .contracts import RTMW_CORE, Event MS_TCN_REVISION = "aef4e46c31bc7b2462065354054f968f91e54be1" PHASES = ["setup", "load", "stride", "forward_swing", "follow_through"] BOUNDARIES = ["load", "lead_foot_lift", "lead_foot_contact", "forward_swing_onset", "contact", "follow_through"] FEATURE_VERSION = "body_object_visual_v1" def endpoint_network(): import torch.nn as nn class EndpointCNN(nn.Module): def __init__(self): super().__init__() self.stem = nn.Sequential(nn.Conv2d(3,32,5,2,2),nn.ReLU(),nn.Conv2d(32,64,3,2,1),nn.ReLU(), nn.Conv2d(64,64,3,1,1),nn.ReLU()) self.heatmap = nn.Conv2d(64,2,1) self.visible = nn.Sequential(nn.AdaptiveAvgPool2d(1),nn.Flatten(),nn.Linear(64,2)) def forward(self,x): features=self.stem(x) return self.heatmap(features),self.visible(features) return EndpointCNN() def temporal_network(repository, architecture): import torch import torch.nn as nn repository=Path(repository) revision=subprocess.run(["git","-C",str(repository),"rev-parse","HEAD"],capture_output=True,text=True,check=True).stdout.strip() if revision != MS_TCN_REVISION: raise ValueError("MS-TCN++ source must be the selected valid pinned revision") source=repository/"model.py" module_spec=importlib.util.spec_from_file_location("batting_official_mstcn",source) module=importlib.util.module_from_spec(module_spec);module_spec.loader.exec_module(module) class TemporalHead(nn.Module): def __init__(self): super().__init__() self.phases=module.MS_TCN2(architecture["prediction_layers"],architecture["refinement_layers"], architecture["refinements"],architecture["channels"],architecture["feature_dim"],len(PHASES)) self.boundaries=nn.Conv1d(len(PHASES),len(BOUNDARIES),1) self.presence=nn.Linear(len(PHASES),len(BOUNDARIES)) def forward(self,x): phases=self.phases(x) probability=torch.softmax(phases[-1],dim=1) return phases,self.boundaries(probability),self.presence(probability.mean(-1)) return TemporalHead(), {"revision":revision,"model_source_sha256":sha256_file(source)} def features(observations,capture): values=[] indices=list(RTMW_CORE.values()) for frame, timing in zip(observations["frames"],capture["frames"]): scale=np.array([timing["width"],timing["height"]],float) points=np.asarray(frame["body_points"],float)[indices]/scale valid=np.array([frame["body_states"][i] in {"manual","image_supported","model_inferred"} for i in indices]) valid &= np.isfinite(points).all(1);points[~valid]=0 bat=np.zeros((2,2));bat_mask=np.zeros(2) if frame["bat"].get("points") is not None: bat=np.asarray(frame["bat"]["points"],float)/scale bat_mask=np.array([s in {"manual","image_supported"} for s in frame["bat"]["states"]],float) bat[bat_mask==0]=0 ball=np.zeros(2);ball_mask=0 if frame["ball"].get("point") is not None: ball=np.asarray(frame["ball"]["point"],float)/scale;ball_mask=1 visual=np.asarray(frame.get("visual_feature",np.zeros(64)),float) values.append(np.r_[points.ravel(),valid,bat.ravel(),bat_mask,ball,ball_mask,visual]) return np.asarray(values,np.float32).T def qualification(manifest_path,checkpoint,kind): manifest=read_json(manifest_path) if manifest.get("kind")!=kind or manifest.get("checkpoint_sha256")!=sha256_file(checkpoint): raise ValueError("Checkpoint kind/hash does not match manifest") record=manifest.get("qualification",{}) if record.get("status")!="passed" or record.get("held_out_athletes") is not True or not record.get("evaluation_sha256"): raise ValueError("Checkpoint has no passed held-out technical qualification") # Qualification is explicit experimental scope, never proof of biomechanical validity. if not record.get("scope"): raise ValueError("Checkpoint qualification scope missing") evidence_path=Path(manifest_path).resolve().parent/"evaluation.json" if not evidence_path.is_file() or sha256_file(evidence_path)!=record["evaluation_sha256"]: raise ValueError("Checkpoint qualification evidence missing or changed") evidence=read_json(evidence_path) if evidence.get("passed") is not True or evidence.get("checkpoint_sha256")!=manifest["checkpoint_sha256"] or evidence.get("scope")!=record["scope"]: raise ValueError("Checkpoint qualification evidence mismatch") return manifest class EndpointPredictor: def __init__(self,checkpoint,manifest_path,device): import torch self.torch=torch;self.device=device self.manifest=qualification(manifest_path,checkpoint,"endpoint_cnn") self.model=endpoint_network().to(device).eval() self.model.load_state_dict(torch.load(checkpoint,map_location=device,weights_only=True)) def __call__(self,image,box): import cv2 x1,y1,x2,y2=np.asarray(box,int) h,w=image.shape[:2];x1=max(x1,0);y1=max(y1,0);x2=min(x2,w);y2=min(y2,h) if x2-x1<8 or y2-y1<8: return None crop=cv2.resize(image[y1:y2,x1:x2],(256,256))[...,::-1].copy()/255. x=self.torch.tensor(crop.transpose(2,0,1),dtype=self.torch.float32,device=self.device)[None] with self.torch.no_grad(): heatmap,visibility=self.model(x) if (visibility.sigmoid()62): return None return {"points":points.tolist(),"states":["model_inferred"]*2,"method":"qualified_endpoint_cnn_v1", "qualification_scope":self.manifest["qualification"]["scope"]} def run_learned_events(request,capture,config,observations): root=Path(request["root"]) try: if not config.event_manifest_path or not config.event_checkpoint_path: raise ValueError("no_qualified_checkpoint") import torch manifest=qualification(config.event_manifest_path,config.event_checkpoint_path,"mstcn_events") if manifest.get("feature_version")!=FEATURE_VERSION: raise ValueError("Event feature definition mismatch") model,source=temporal_network(config.mstcn_repo,manifest["architecture"]) if source!=manifest["source"]: raise ValueError("Event source hash mismatch") model.load_state_dict(torch.load(config.event_checkpoint_path,map_location="cpu",weights_only=True)) model=model.to(config.device).eval() x=features(observations,capture) with torch.no_grad(): phase,boundary,presence=model(torch.tensor(x,device=config.device)[None]) phase=phase[-1].softmax(1)[0].cpu().numpy(); boundary=boundary.sigmoid()[0].cpu().numpy();presence=presence.sigmoid()[0].cpu().numpy() candidates=[] for i,name in enumerate(BOUNDARIES): if presence[i]