"""Q-22: Detect a person in one image -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q22-detect-person/
Data:     https://apopt.com/data/tutorials/q22-detect-person/ (keep raw/ next to this file)
"""

# %% [markdown]
# A pose model starts by finding the person. An **object detector** does only that first part:
# it returns a box around each thing it recognizes, a class name ("person", "car", "sports
# ball") and a confidence from 0 to 1. You will run one on a street photo from the
# Data-Driven Engineering course, keep the result as a table, and draw the boxes without the
# photo.
#
# The first cell needs the `ultralytics` package, so it runs in a notebook on your computer
# or in Colab, not in this page. The photo shows people's faces, so it stays where it was
# downloaded; only the table of boxes is published.

# %%
# Run a detector on one photo
import os
import pandas as pd
from ultralytics import YOLO

model = YOLO("yolo26n.pt")                       # the smallest YOLO26 detector, 80 COCO classes
r = model("street.png", verbose=False, device="cpu")[0]
rows = [[model.names[int(c)], float(p), *map(float, b)]
        for c, p, b in zip(r.boxes.cls, r.boxes.conf, r.boxes.xyxy)]
det = pd.DataFrame(rows, columns=["label", "confidence", "x1", "y1", "x2", "y2"]).round(2)
os.makedirs("clean", exist_ok=True)
det.to_csv("clean/detections.csv", index=False)
print(f"image {r.orig_shape[1]} x {r.orig_shape[0]} pixels, {len(det)} boxes")
print(det.to_string(index=False))

# %% [markdown]
# Each row is one box: the class, the confidence, and the top-left (`x1`, `y1`) and
# bottom-right (`x2`, `y2`) corners in pixels. As in every image, y grows **downward**.
#
# ### Count and gate
#
# From here on, everything runs in this page from the table. Count the boxes by class, then
# keep only the people the detector was reasonably sure of.

# %%
# Count by class, then gate on confidence
import pandas as pd

det = pd.read_csv("clean/detections.csv")
print(det.groupby("label")["confidence"].agg(["count", "min", "max"]).round(2).to_string())
people = det[(det["label"] == "person") & (det["confidence"] >= 0.5)].copy()
people["height_px"] = people["y2"] - people["y1"]
print(f"people at confidence 0.5 or more: {len(people)}")
print(people[["confidence", "x1", "y1", "height_px"]].sort_values("x1").to_string(index=False))

# %% [markdown]
# ### Draw the boxes, not the photo
#
# A drawing made from the table is the detector's view of the scene. Boxes the detector was
# unsure of (below 0.5) are dashed.

# %%
# The scene as the detector saw it
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

fig, ax = plt.subplots(figsize=(7, 4.2))
for _, b in det.iterrows():
    sure = b["confidence"] >= 0.5
    ax.add_patch(Rectangle((b["x1"], b["y1"]), b["x2"] - b["x1"], b["y2"] - b["y1"], fill=False,
                           lw=2 if b["label"] == "person" else 1, ls="-" if sure else "--",
                           color="black" if b["label"] == "person" else "gray"))
    ax.text(b["x1"], b["y1"] - 6, f"{b['label']} {b['confidence']:.2f}", fontsize=7)
ax.set(xlim=(0, 1139), ylim=(681, 0), xlabel="x (pixels)", ylabel="y (pixels, grows downward)")
ax.set_aspect("equal")
plt.tight_layout()

# %% [markdown]
# Compare the drawing with your prediction. The photo holds six people and the detector
# returns five boxes labelled "person". The sixth, a woman standing half hidden behind the man
# on the left, gets no box: that is **occlusion**, the first failure in Chapter 8's table. The
# box of the man on the left starts at y = 0 because he is cut off by the top of the frame,
# so its height (651 px) is not his full height. The box heights already show who is near the
# camera and who is far: the same pixel does not stand for the same distance across the photo,
# the scale problem of Chapter 8. The bus is called a "car" (0.45), only one of the bags is
# found, and the plane is found but with the lowest score of all (0.32). (The Data-Driven
# Engineering page, with an older detector, misses the plane.)
#
# The running app keeps only the single most confident person whose score is above 0.25 in each
# frame, so in a clip with a coach or teammate in view it can follow the wrong person.
#
# **For the athlete:** film alone in the frame, or with others well behind you, so the app
# measures you and not someone else.
