"""cine-27 demo: read a pulse from a webcam video, then check it against a finger sensor.

Data: MCD-rPPG (Egorov et al., huggingface.co/datasets/kyegorov/mcd_rppg, CC BY 4.0): frontal webcam videos
(640x480) of people sitting still ("before") and after exercise ("after"), with a finger PPG synced per frame
(ppg_sync/*.txt). No face is ever saved or shown: only the skin's average colour per frame leaves this script.

    python pulse.py DATA_DIR OUT_DIR

Per video: find the face (OpenCV's Haar cascade, re-detected every 15 frames, smoothed), average the forehead and
both cheeks (skin only) per frame -> R, G, B traces. Two ways to a pulse signal:
  GREEN: the green trace, detrended and band-passed 0.7-3.5 Hz (Verkruysse et al. 2008: green carries most of it)
  POS:   the plane-orthogonal-to-skin projection (Wang et al. 2017), 1.6 s windows, overlap-added, band-passed
Heart rate: the strongest frequency in 0.7-3.5 Hz (42-210 bpm) in 10 s windows stepped 5 s, the same for the finger
PPG (the reference). Scored per window and per video (the median of its windows).
"""
import glob, json, os, sys
import numpy as np
import cv2
from scipy import signal

DATA, OUT = sys.argv[1], sys.argv[2]
os.makedirs(OUT, exist_ok=True)
CASC = cv2.CascadeClassifier(os.path.join(cv2.data.haarcascades, "haarcascade_frontalface_default.xml"))
LO, HI, WIN, STEP = 0.7, 3.5, 10.0, 5.0


def skin_rgb(path):
    cap = cv2.VideoCapture(path)
    fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
    rgb, box, i = [], None, 0
    while True:
        ok, fr = cap.read()
        if not ok:
            break
        if i % 15 == 0 or box is None:
            g = cv2.cvtColor(fr, cv2.COLOR_BGR2GRAY)
            faces = CASC.detectMultiScale(g, 1.15, 5, minSize=(90, 90))
            if len(faces):
                f = max(faces, key=lambda b: b[2] * b[3]).astype(float)
                box = f if box is None else 0.7 * box + 0.3 * f
        i += 1
        if box is None:
            rgb.append([np.nan] * 3); continue
        x, y, w, h = box
        rois = [(x + 0.30 * w, y + 0.10 * h, 0.40 * w, 0.15 * h),       # forehead
                (x + 0.15 * w, y + 0.50 * h, 0.20 * w, 0.18 * h),       # left cheek
                (x + 0.65 * w, y + 0.50 * h, 0.20 * w, 0.18 * h)]       # right cheek
        px = []
        for rx, ry, rw, rh in rois:
            p = fr[int(ry):int(ry + rh), int(rx):int(rx + rw)].reshape(-1, 3).astype(np.float32)
            px.append(p)
        p = np.concatenate(px)
        ycc = cv2.cvtColor(p.reshape(-1, 1, 3).astype(np.uint8), cv2.COLOR_BGR2YCrCb).reshape(-1, 3)
        m = (ycc[:, 1] > 133) & (ycc[:, 1] < 173) & (ycc[:, 2] > 77) & (ycc[:, 2] < 127)   # skin pixels only
        p = p[m] if m.sum() > 50 else p
        rgb.append(p.mean(0)[::-1].tolist())                            # BGR -> RGB
    cap.release()
    a = np.array(rgb, float)
    for c in range(3):                                                  # fill brief misses
        bad = np.isnan(a[:, c])
        if bad.any() and (~bad).any():
            a[bad, c] = np.interp(np.where(bad)[0], np.where(~bad)[0], a[~bad, c])
    return a, fps


def bandpass(x, fps):
    b, a = signal.butter(3, [LO / (fps / 2), HI / (fps / 2)], btype="band")
    return signal.filtfilt(b, a, signal.detrend(x))


def pos(rgb, fps):
    n, L = len(rgb), int(1.6 * fps)
    h = np.zeros(n)
    P = np.array([[0, 1, -1], [-2, 1, 1]], float)
    for t in range(n - L + 1):
        C = rgb[t:t + L].T
        Cn = C / C.mean(1, keepdims=True)
        S = P @ Cn
        hh = S[0] + (S[0].std() / (S[1].std() + 1e-9)) * S[1]
        h[t:t + L] += hh - hh.mean()
    return bandpass(h, fps)


def hr_windows(x, fps):
    out = []
    n, w, s = len(x), int(WIN * fps), int(STEP * fps)
    for a in range(0, n - w + 1, s):
        f, p = signal.welch(x[a:a + w], fs=fps, nperseg=w, nfft=max(4096, w))
        m = (f >= LO) & (f <= HI)
        out.append(60.0 * f[m][np.argmax(p[m])])
    return np.array(out)


rows = []
for vp in sorted(glob.glob(os.path.join(DATA, "video", "*_FullHDwebcam_*.avi"))):
    name = os.path.basename(vp)[:-4]
    tp = os.path.join(DATA, "ppg_sync", name + ".txt")
    if not os.path.exists(tp):
        continue
    ref = np.loadtxt(tp)
    ref = ref[:, 0] if ref.ndim > 1 else ref
    rgb, fps = skin_rgb(vp)
    n = min(len(rgb), len(ref))
    rgb, ref = rgb[:n], ref[:n]
    g = bandpass(rgb[:, 1], fps)
    ps = pos(rgb, fps)
    rf = bandpass(ref, fps)
    hg, hp, hr = hr_windows(g, fps), hr_windows(ps, fps), hr_windows(rf, fps)
    k = min(len(hg), len(hp), len(hr))
    row = {"video": name, "subject": name.split("_")[0], "cond": name.split("_")[-1], "fps": fps, "frames": int(n),
           "seconds": round(n / fps, 1), "ref_bpm": float(np.median(hr[:k])), "pos_bpm": float(np.median(hp[:k])),
           "green_bpm": float(np.median(hg[:k])),
           "pos_win_err": [round(float(v), 2) for v in np.abs(hp[:k] - hr[:k])],
           "green_win_err": [round(float(v), 2) for v in np.abs(hg[:k] - hr[:k])],
           "green_pulse_levels": float(np.percentile(g, 95) - np.percentile(g, 5)) / 2}   # the beat's size, 8-bit levels
    rows.append(row)
    print(f"{name}: finger {row['ref_bpm']:.0f}  POS {row['pos_bpm']:.0f}  green {row['green_bpm']:.0f}  "
          f"(pulse ~{row['green_pulse_levels']:.2f} levels)", flush=True)
    if not os.path.exists(os.path.join(OUT, "example.json")) and row["cond"] == "before" and abs(row["pos_bpm"] - row["ref_bpm"]) < 3:
        t = np.arange(n) / fps
        sl = slice(int(5 * fps), int(25 * fps))
        json.dump({"video": name, "fps": fps, "t": np.round(t[sl], 3).tolist(),
                   "green_raw": np.round(rgb[sl, 1], 3).tolist(), "green": np.round(g[sl], 4).tolist(),
                   "pos": np.round(ps[sl], 5).tolist(), "finger": np.round(rf[sl], 4).tolist(),
                   "ref_bpm": row["ref_bpm"], "pos_bpm": row["pos_bpm"]}, open(os.path.join(OUT, "example.json"), "w"))
pe = np.array([abs(r["pos_bpm"] - r["ref_bpm"]) for r in rows]); ge = np.array([abs(r["green_bpm"] - r["ref_bpm"]) for r in rows])
winp = np.concatenate([r["pos_win_err"] for r in rows]); wing = np.concatenate([r["green_win_err"] for r in rows])
summ = {"videos": len(rows), "people": len({r["subject"] for r in rows}),
        "pos_within5": int((pe <= 5).sum()), "green_within5": int((ge <= 5).sum()),
        "pos_within3": int((pe <= 3).sum()), "pos_mae": float(pe.mean()), "green_mae": float(ge.mean()),
        "pos_windows_within5": float((winp <= 5).mean()), "green_windows_within5": float((wing <= 5).mean()),
        "by_cond": {c: {"n": int(sum(r["cond"] == c for r in rows)),
                        "pos_within5": int(sum(abs(r["pos_bpm"] - r["ref_bpm"]) <= 5 for r in rows if r["cond"] == c))}
                    for c in ("before", "after")},
        "median_pulse_levels": float(np.median([r["green_pulse_levels"] for r in rows]))}
json.dump({"summary": summ, "rows": rows}, open(os.path.join(OUT, "pulse.json"), "w"), indent=1)
print(json.dumps(summ, indent=1))
