Spaces:
Running on T4
Running on T4
Download AI-coach-agent/src/ai_coach/visual_scoring.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 9.27 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/AI-coach-agent/src/ai_coach/visual_scoring.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/AI-coach-agent/src/ai_coach/visual_scoring.py
-
curl -L -o visual_scoring.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/AI-coach-agent/src/ai_coach/visual_scoring.py
9.27 kB
| """Experimental visual rubric. The model supplies grades; Python computes points. | |
| No measurement, normal-range, player-ability or validated confidence score is | |
| created here. Unknown evidence is excluded, never converted into a poor grade. | |
| """ | |
| from typing import Literal | |
| import re | |
| from pydantic import BaseModel, ConfigDict, Field | |
| RUBRIC_VERSION = "visual-swing-v1" | |
| MIN_FEATURES = 2 | |
| NAMES = {"load_timing": "Preparation and forward movement", | |
| "hip_shoulder_separation": "Visible turning order", | |
| "bat_path_contact": "Visible bat movement near the ball"} | |
| POINTS = {"needs_practice": 0, "mixed": 1, "clear": 2} | |
| LABELS = {"needs_practice": "Needs practice", "mixed": "Mixed", "clear": "Clear sequence"} | |
| NOTICE = ("Subjective AI ratings of visible patterns in sampled images. Accuracy is not validated. " | |
| "This is not the Mechanics score, a player-ability rating, or a measured timing/separation/contact score.") | |
| RUBRIC_PROMPT = """Also provide an experimental visual rating for each observed feature. | |
| Use ONLY these fixed criteria, with grade clear, mixed, needs_practice, or null | |
| rating when the relevant sequence cannot be judged. Explain the visible pattern | |
| briefly and cite the feature's provided frames. Do not invent a numeric score; | |
| the server will compute points from the grades. Do not rate visibility as skill. | |
| load_timing: rate only visible preparation-to-forward-hand movement, NOT whether | |
| the player was early/late to a pitch. clear = preparation precedes a continuous | |
| forward hand movement; mixed = preparation precedes it but a visible interruption | |
| occurs during the forward movement; needs_practice = a clear reversal/interruption | |
| prevents a continuous transition. If movement order/continuity is uncertain, null. | |
| hip_shoulder_separation: rate only visible turning order, NOT a true separation | |
| angle or a comparison with elite/age/level norms. clear = hip opening is visibly | |
| before chest/shoulder turn; mixed = they visibly start together; needs_practice = | |
| chest/shoulders visibly turn before hip opening. If projection, blur or occlusion | |
| prevents distinguishing the order, null; do not guess from a still image. | |
| bat_path_contact: rate only continuous visible bat movement into the visible ball | |
| region, NOT contact quality, pitch location, a hit/miss diagnosis or launch angle. | |
| This rating requires directly visible bat/ball interaction AND | |
| ball_interaction_visible=true. clear = continuous visible movement into that | |
| region; mixed = a visible interruption before that region; needs_practice = a | |
| clear reversal/stop interrupts that route. If interaction or route is unclear, | |
| null. Seeing a ball somewhere in the image is insufficient. | |
| Never grade an unclear feature. At least two features of the SAME swing must be | |
| rateable for a swing score; do not change unclear to observed to produce a score. | |
| These are subjective POC criteria, not validated faults or universal ideals. | |
| Put the grade and short explanation in rating. Do not put numbers, units, scores, | |
| normal ranges, medical claims or player-ability judgments in rating explanations. | |
| """ | |
| class VisualRating(BaseModel): | |
| model_config = ConfigDict(extra="forbid") | |
| grade: Literal["needs_practice", "mixed", "clear"] | |
| explanation: str = Field(min_length=1, max_length=300) | |
| class FeatureScore(BaseModel): | |
| model_config = ConfigDict(extra="forbid") | |
| key: Literal["load_timing", "hip_shoulder_separation", "bat_path_contact"] | |
| label: str | |
| status: Literal["scored", "unavailable"] | |
| grade: Literal["needs_practice", "mixed", "clear"] | None | |
| grade_label: str | None | |
| points: int | None = Field(ge=0, le=2) | |
| max_points: Literal[2] = 2 | |
| reason_code: str | None | |
| explanation: str | |
| evidence_frame_ids: list[int] | |
| class RepVideoScore(BaseModel): | |
| model_config = ConfigDict(extra="forbid") | |
| rep: int = Field(ge=1) | |
| status: Literal["available", "unavailable"] | |
| value: int | None = Field(ge=0, le=100) | |
| features_scored: int = Field(ge=0, le=3) | |
| features_total: Literal[3] = 3 | |
| reason_code: str | None | |
| explanation: str | |
| breakdown: list[FeatureScore] = Field(min_length=3, max_length=3) | |
| class VideoScore(BaseModel): | |
| model_config = ConfigDict(extra="forbid") | |
| name: Literal["Experimental video score"] = "Experimental video score" | |
| rubric_version: Literal["visual-swing-v1"] = RUBRIC_VERSION | |
| basis: Literal["visual_rubric"] = "visual_rubric" | |
| scope: Literal["scorable_reviewed_swings_only"] = "scorable_reviewed_swings_only" | |
| status: Literal["available", "unavailable"] | |
| value: int | None = Field(ge=0, le=100) | |
| max_value: Literal[100] = 100 | |
| accuracy_validated: Literal[False] = False | |
| judgment_eligible: Literal[False] = False | |
| reviewed_reps: list[int] = Field(max_length=8) | |
| scored_reps: list[int] = Field(max_length=8) | |
| rep_scores: list[RepVideoScore] = Field(max_length=8) | |
| reason_code: str | None | |
| explanation: str | |
| notice: str = NOTICE | |
| def unavailable_score(reason="review_unavailable"): | |
| return VideoScore(status="unavailable", value=None, reviewed_reps=[], scored_reps=[], | |
| rep_scores=[], reason_code=reason, | |
| explanation="No experimental video score is available from this review.").model_dump(mode="json") | |
| def rating_reason(feature): | |
| if feature["status"] != "observed": | |
| return "feature_unclear" | |
| if feature["key"] == "bat_path_contact" and not feature.get("ball_interaction_visible"): | |
| return "ball_interaction_not_visible" | |
| if feature["key"] == "bat_path_contact": | |
| text = feature["observation"].lower() | |
| if (re.search(r"(?:interaction|contact|impact).{0,70}(?:unclear|unseen|unverified|cannot|can't|not.{0,20}(?:clear|visible|verified|seen))", text) | |
| or re.search(r"(?:no|missing|cannot see|can't see).{0,40}(?:interaction|contact|impact|ball evidence)", text)): | |
| return "ball_interaction_unclear" | |
| if feature.get("rating") is None: | |
| return "rating_not_supplied" | |
| if len(feature.get("evidence_frame_ids", [])) < 2: | |
| return "insufficient_evidence" | |
| return None | |
| def build_video_score(features, frames): | |
| """Equal feature weights within a rep; equal weights for scorable reps. | |
| Never combine isolated features from different swings to meet the minimum. | |
| Evidence references/chronology and model prose are validated by the review | |
| adapter before this function is called. | |
| """ | |
| reviewed = sorted({rep for frame in frames for rep in frame["reps"]}) | |
| rep_scores = [] | |
| for rep in reviewed: | |
| rows = [] | |
| for key, label in NAMES.items(): | |
| feature = next((f for f in features if f["rep"] == rep and f["key"] == key), None) | |
| reason = rating_reason(feature) if feature else "feature_not_reviewed" | |
| rating = feature.get("rating") if feature and reason is None else None | |
| rows.append(FeatureScore(key=key, label=label, | |
| status="scored" if rating else "unavailable", | |
| grade=rating["grade"] if rating else None, | |
| grade_label=LABELS[rating["grade"]] if rating else None, | |
| points=POINTS[rating["grade"]] if rating else None, reason_code=reason, | |
| explanation=rating["explanation"] if rating else (feature["observation"] if feature else | |
| "This feature was not individually reviewed for this swing."), | |
| evidence_frame_ids=feature["evidence_frame_ids"] if feature else [])) | |
| rated = [r for r in rows if r.status == "scored"] | |
| ready = len(rated) >= MIN_FEATURES | |
| value = round(100*sum(r.points for r in rated)/(2*len(rated))) if ready else None | |
| rep_scores.append(RepVideoScore(rep=rep, status="available" if ready else "unavailable", | |
| value=value, features_scored=len(rated), reason_code=None if ready else "insufficient_visible_features", | |
| explanation=(f"Based on {len(rated)} of 3 visible feature ratings for this swing. " | |
| "Unclear features were excluded." if ready else | |
| "At least two rateable features from this same swing are needed."), breakdown=rows)) | |
| scored = [r for r in rep_scores if r.status == "available"] | |
| return VideoScore(status="available" if scored else "unavailable", | |
| value=round(sum(r.value for r in scored)/len(scored)) if scored else None, | |
| reviewed_reps=reviewed, scored_reps=[r.rep for r in scored], rep_scores=rep_scores, | |
| reason_code=None if scored else "insufficient_visible_features", | |
| explanation=(f"Experimental rating from {len(scored)} scorable reviewed swing(s). " | |
| "Unreviewed and unclear swings are excluded; this does not rate every swing in the video." | |
| if scored else "No reviewed swing had two rateable features. Unclear evidence is not scored as zero.") | |
| ).model_dump(mode="json") | |
| def score_is_current(review): | |
| """A completed current-rubric review is reusable, even if its score abstains.""" | |
| score = review.get("score") or {} | |
| return (review.get("status") == "completed" and score.get("rubric_version") == RUBRIC_VERSION | |
| and score.get("basis") == "visual_rubric" and score.get("status") in ("available", "unavailable")) | |