"""CS-10: Pose estimation, frame by frame -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/cs10-pose-frame-by-frame/
Data:     https://apopt.com/data/tutorials/cs10-pose-frame-by-frame/ (keep raw/ next to this file)
"""

# %% [markdown]
# ### Step 1 · Gather: what is in the file?
#
# A video is a stack of pictures and a clock. Before any model runs, read the clock: how many
# frames, how many per second, how big. The clip is the short running clip from the
# Data-Driven Engineering course. Steps 1 and 2 run in a notebook on your computer or in Colab,
# because the pose model does not run inside a web page here; from Step 3 on, everything runs
# in this page from the table that Step 2 writes.

# %%
# Step 1 · Read the clip's header
import cv2

cap = cv2.VideoCapture("runner.mp4")
fps = cap.get(cv2.CAP_PROP_FPS)
n = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
w, h = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print(f"{n} frames at {fps:.0f} fps = {n / fps:.2f} s, {w} x {h} pixels")
cap.release()

# %% [markdown]
# Twenty-two frames: a short clip, which makes it a good first one. Everything a pose model does
# to it fits in a table of 22 rows. (The header gives the *stored* frame rate. Chapter 8 shows
# clips filmed at 120 frames per second and stored at 30; check your own clips the same way.)
#
# ### Step 2 · Run a pose model on every frame
#
# The loop below is the whole of frame-by-frame pose estimation. For each frame: run the
# model, keep the most confident person, and write one row: the frame number, the x and y of
# 17 keypoints in pixels, and the model's confidence in each, from 0 to 1. It also writes an
# annotated copy of the video for you to watch (`local/runner_pose.mp4`, on your computer only).
# Two model sizes are run, the smallest (n) and the next (s), so Step 6 can compare them.

# %%
# Step 2 · Frame by frame: model, keypoints, table
import os
import time
import pandas as pd
from ultralytics import YOLO

NAMES = ["nose", "l_eye", "r_eye", "l_ear", "r_ear", "l_shoulder", "r_shoulder", "l_elbow", "r_elbow",
         "l_wrist", "r_wrist", "l_hip", "r_hip", "l_knee", "r_knee", "l_ankle", "r_ankle"]
os.makedirs("clean", exist_ok=True)
os.makedirs("local", exist_ok=True)
for size in ["n", "s"]:
    model = YOLO(f"yolo26{size}-pose.pt")
    cap = cv2.VideoCapture("runner.mp4")
    out = cv2.VideoWriter(f"local/runner_pose_{size}.mp4", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
    rows, ms, i = [], [], 0
    while True:
        ok, frame = cap.read()
        if not ok:
            break
        t0 = time.perf_counter()
        r = model(frame, verbose=False, device="cpu")[0]
        ms.append(1000 * (time.perf_counter() - t0))
        out.write(r.plot())                               # the frame with the skeleton drawn on it
        if r.keypoints is not None and len(r.boxes):
            best = int(r.boxes.conf.argmax())             # the most confident person
            xy, conf = r.keypoints.xy[best].tolist(), r.keypoints.conf[best].tolist()
            rows.append([i] + [v for p in xy for v in p] + conf)
        i += 1
    cap.release(); out.release()
    cols = ["frame"] + [f"{k}_{a}" for k in NAMES for a in "xy"] + [f"{k}_c" for k in NAMES]
    pd.DataFrame(rows, columns=cols).round(2).to_csv(f"clean/keypoints_{size}.csv", index=False)
    print(f"yolo26{size}-pose: person found in {len(rows)} of {i} frames, "
          f"median {sorted(ms)[len(ms) // 2]:.0f} ms per frame on this computer's CPU")

# %% [markdown]
# Watch `local/runner_pose_n.mp4` on your computer: the skeleton is drawn on every frame. The
# timings are for the computer that built this page; yours will differ, but the ratio between
# the two sizes will be similar. From here on, everything runs in this page, from the two tables.
#
# ### Step 3 · One frame, seventeen keypoints
#
# Open the table and turn the first row into a short table of its own: one line per keypoint.

# %%
# Step 3 · Read one frame as 17 keypoints
import pandas as pd

NAMES = ["nose", "l_eye", "r_eye", "l_ear", "r_ear", "l_shoulder", "r_shoulder", "l_elbow", "r_elbow",
         "l_wrist", "r_wrist", "l_hip", "r_hip", "l_knee", "r_knee", "l_ankle", "r_ankle"]
kp = pd.read_csv("clean/keypoints_n.csv")
print(kp.shape, "(rows = frames with a person; columns = frame + 17 × (x, y) + 17 confidences)")
row = kp.iloc[0]
one = pd.DataFrame({"x": [row[f"{k}_x"] for k in NAMES], "y": [row[f"{k}_y"] for k in NAMES],
                    "confidence": [row[f"{k}_c"] for k in NAMES]}, index=NAMES)
print(f"frame {int(row['frame'])}:")
print(one.round(2).to_string())

# %% [markdown]
# Pixel y grows **downward**: the nose has the smallest y, the ankles the largest. Code that
# forgets this draws people upside down and reports upward speeds as negative.
#
# ### Step 4 · Statistics: how sure is the model, joint by joint?

# %%
# Step 4 · Confidence by keypoint over all frames
conf = kp[[f"{k}_c" for k in NAMES]]
conf.columns = NAMES
summary = conf.describe().T[["mean", "min"]].sort_values("mean")
print(summary.round(2).to_string())
print(f"keypoints below 0.5 confidence: {(conf < 0.5).to_numpy().sum()} of {conf.size}")

# %% [markdown]
# ### Step 5 · Visualize: the skeleton, without the pixels
#
# Draw the keypoints themselves, joined into a stick figure, for four frames, and plot the two
# ankles' height over the clip. A plot made from the table is the model's view of the runner:
# whatever it shows is what any later number will be built on. Faint points are the ones the
# model was unsure of.

# %%
# Step 5 · Stick figures and ankle traces
import matplotlib.pyplot as plt

BONES = [("l_shoulder", "r_shoulder"), ("l_shoulder", "l_elbow"), ("l_elbow", "l_wrist"),
         ("r_shoulder", "r_elbow"), ("r_elbow", "r_wrist"), ("l_shoulder", "l_hip"), ("r_shoulder", "r_hip"),
         ("l_hip", "r_hip"), ("l_hip", "l_knee"), ("l_knee", "l_ankle"), ("r_hip", "r_knee"), ("r_knee", "r_ankle")]

def stick(ax, r, dx=0, color="C0"):
    for a, b in BONES:
        ax.plot([r[f"{a}_x"] + dx, r[f"{b}_x"] + dx], [r[f"{a}_y"], r[f"{b}_y"]], color=color, lw=2,
                alpha=0.3 if min(r[f"{a}_c"], r[f"{b}_c"]) < 0.5 else 1)
    ax.plot(r["nose_x"] + dx, r["nose_y"], "o", color=color)

fig, ax = plt.subplots(1, 2, figsize=(10, 3.8), gridspec_kw={"width_ratios": [1.4, 1]})
for j, f in enumerate([0, 7, 14, 21]):
    r = kp[kp["frame"] == f]
    if len(r):
        stick(ax[0], r.iloc[0], dx=-r.iloc[0]["l_hip_x"] + 450 * j, color=f"C{j}")
        ax[0].text(450 * j, kp["l_ankle_y"].max() + 60, f"frame {f}", ha="center")
ax[0].invert_yaxis(); ax[0].set_aspect("equal"); ax[0].axis("off")
ax[1].plot(kp["frame"], kp["l_ankle_y"], "o-", label="left ankle")
ax[1].plot(kp["frame"], kp["r_ankle_y"], "s--", label="right ankle")
ax[1].invert_yaxis(); ax[1].set(xlabel="frame", ylabel="ankle y (pixels, up is up)"); ax[1].legend()
plt.tight_layout()

# %% [markdown]
# Two things stand out before any number is computed. The stick figure **shrinks** from frame 0
# to frame 21: the runner is moving away from the camera, so a pixel does not stand for the same
# distance in every frame (Chapter 8, "Scale"). And the ankle traces have **single-frame
# spikes**, the right ankle at frame 4 and the left at frame 10, where the trace jumps and comes
# straight back. At those frames both ankle labels landed on the same foot.
#
# Step through the clip one frame at a time in the viewer below. It draws the same table, with
# the frame number and each joint's confidence.

# %% [markdown]
# ### Step 6 · Cleanse: gate, despike, and check one model against another
#
# Three checks, none of which needs a ground truth. First, points the model was unsure of are
# set to missing (a *confidence gate*). Second, a point more than a quarter of a leg length away
# from the median of itself and its two neighbors is a spike: it jumped away for one frame and
# came back. It is set to missing too. Third, the two model sizes give two estimates of every point; where they disagree
# by many pixels, at least one is wrong.

# %%
# Step 6 · Confidence gate and model agreement
import numpy as np

GATE = 0.5
gated = kp.copy()
for k in NAMES:
    low = gated[f"{k}_c"] < GATE
    gated.loc[low, [f"{k}_x", f"{k}_y"]] = np.nan
print(f"set to missing by the {GATE} gate: {int(gated[[f'{k}_x' for k in NAMES]].isna().sum().sum())} points")

leg = np.hypot(kp["l_hip_x"] - kp["l_knee_x"], kp["l_hip_y"] - kp["l_knee_y"]).median() + \
      np.hypot(kp["l_knee_x"] - kp["l_ankle_x"], kp["l_knee_y"] - kp["l_ankle_y"]).median()
spikes = []
for k in NAMES:
    for a in "xy":
        v = gated[f"{k}_{a}"]
        mid = v.rolling(3, center=True, min_periods=2).median()   # this frame and its two neighbors
        jump = (v - mid).abs() > leg / 4
        spikes += [(k, int(f)) for f in gated.loc[jump, "frame"]]
        gated.loc[jump, [f"{k}_x", f"{k}_y"]] = np.nan
gated.to_csv("clean/keypoints_n_clean.csv", index=False)
print(f"leg length (hip-knee-ankle) in the image: {leg:.0f} px; spikes over {leg / 4:.0f} px set to missing:")
print(sorted(set(spikes)))

ks = pd.read_csv("clean/keypoints_s.csv")
both = kp.merge(ks, on="frame", suffixes=("_n", "_s"))
dist = pd.Series({k: np.hypot(both[f"{k}_x_n"] - both[f"{k}_x_s"], both[f"{k}_y_n"] - both[f"{k}_y_s"]).median()
                  for k in NAMES}).sort_values(ascending=False)
print("median disagreement between models n and s, pixels:")
print(dist.head(6).round(1).to_string())

# %% [markdown]
# ### Step 9 · Deploy: is this clip good enough, and for what?
#
# A measurement is good enough when its error is small next to the change you care about. Two
# quick tests decide what this clip can support.
#
# * **Timing.** At 30 frames per second each frame is 33 ms. A running contact lasts about
#   200 ms, so it spans about 6 frames, and one frame of error is about 17% of it.
# * **Counting.** Cadence needs several steps. Count the ground contacts in the clip from the
#   cleaned ankle traces: a contact is where an ankle is near its lowest point (largest y).

# %%
# Step 9 · What can this clip measure?
frame_ms = 1000 / 30
print(f"one frame = {frame_ms:.0f} ms; a 200 ms contact = {200 / frame_ms:.0f} frames; "
      f"one frame of error = {frame_ms / 200:.0%} of it")
contacts = {}
for side in ["l", "r"]:
    y = gated[f"{side}_ankle_y"].interpolate(limit=2)
    low = y > y.max() - 0.15 * (y.max() - y.min())              # within 15% of the lowest point
    contacts[side] = int((low & ~low.shift(fill_value=False)).sum())
print(f"contacts found: left {contacts['l']}, right {contacts['r']} in {len(kp) / 30:.2f} s")
print("enough for cadence?", "no: a cadence needs several strides" if sum(contacts.values()) < 6 else "yes")

# %% [markdown]
# The verdict has three parts. The hips, knees and ankles are found with high confidence in every
# frame, so a joint angle at one chosen instant is usable, as long as the frame is not one of the
# spikes. The clip is too short for cadence or for an average over strides, and at 30 frames per
# second a contact time carries a 17% one-frame error. And because the runner moves away from
# the camera, no single pixel-to-meter scale holds for the whole clip. That is the action: film
# 10 seconds or more, at 60 or 120 frames per second, from the side and square to the path,
# before measuring anything that repeats.
