"""Q-24: Seventeen keypoints for one frame, as a table -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q24-keypoint-table/
Data:     https://apopt.com/data/tutorials/q24-keypoint-table/ (keep raw/ next to this file)
"""

# %% [markdown]
# A pose model turns each frame of a video into one row of numbers: the frame number, an x and
# a y in pixels for each of 17 keypoints, and the model's confidence in each. The file here is
# the one Chapter 8 builds from its running example, a hand-drawn runner animated and seen from
# the side (`form3_30fps.mp4`, 117 frames), with the smallest YOLO26 pose model. Everything in
# this tutorial runs in the page.

# %%
# Open the keypoint table
import pandas as pd

kp = pd.read_csv("raw/form3_30fps_yolo26n-pose.csv")
print(kp.shape, "(rows = frames with a person, columns)")
print("first columns:", kp.columns[:5].tolist())
print("last columns: ", kp.columns[-3:].tolist())

# %% [markdown]
# 117 rows and 52 columns: 1 + 17 × 2 + 17. A row this wide is hard to read. Turn one row into
# a short table of its own, one line per keypoint. Frame 30 is the one Chapter 8 (Section 8.4)
# draws on the video, because something goes wrong in it.

# %%
# One frame as 17 rows
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"]
row = kp[kp["frame"] == 30].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(one.round(2).sort_values("confidence").to_string())
print(f"below 0.5: {(one['confidence'] < 0.5).sum()} of 17")

# %% [markdown]
# The least sure points are all on the runner's right side, the side away from the camera:
# the right ear, eye and wrist. Those are hidden behind the head and body, and the model says
# so. The hips, knees and ankles score 0.91 or more.
#
# ### Draw the row
#
# Join the points into a stick figure. Image y grows downward, so the axis is turned over.
# Bones with an end below 0.5 are drawn faint and dashed.

# %%
# The frame as a stick figure, from the table alone
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")]
fig, ax = plt.subplots(figsize=(4.4, 5))
for a, b in BONES:
    low = min(one.loc[a, "confidence"], one.loc[b, "confidence"]) < 0.5
    ax.plot(one.loc[[a, b], "x"], one.loc[[a, b], "y"], color="gray" if low else "black",
            ls="--" if (low or a.startswith("r_")) else "-", lw=1 if low else 2.5)
ax.scatter(one["x"], one["y"], c="black", s=12, zorder=3)
for k in ["nose", "l_knee", "r_knee", "l_ankle", "r_ankle", "r_wrist"]:
    ax.annotate(f"{k} {one['confidence'].round(2)[k]:.2f}", (one.loc[k, "x"], one.loc[k, "y"]), fontsize=7,
                xytext=(5, 0), textcoords="offset points")
ax.invert_yaxis(); ax.set_aspect("equal")
ax.set(xlabel="x (pixels)", ylabel="y (pixels, grows downward)", title="frame 30, YOLO26n")
plt.tight_layout()

# %% [markdown]
# The table says the legs are certain. The drawing on the video says otherwise: in this frame
# the nano model put both ankles mid-shin and the right knee in the thigh (Chapter 8, Section
# 8.4), while the next size up (s) followed the legs to the feet. Nothing in the confidence
# column warns you. A confidence is the model's own score, not a check that the point is right;
# the only checks are looking at the skeleton on the video and comparing two models, which
# CS-10 does.
#
# **For the athlete:** before trusting a knee angle from a clip, look at the skeleton drawn on
# the frame it came from.
