#!/usr/bin/env python3
"""PC 参考: 手部关键点流水线(MediaPipe Tasks HandLandmarker 语义手动复刻)

配置出处(mediapipe 官方源码, 已逐字段核对, 2026-09-20):
  tasks/cc/vision/hand_detector/hand_detector_graph.cc
    DetectionsToRects: start_kp=0(腕), end_kp=2(中指MCP), target_angle=90°
    RectTransformation: scale_x=scale_y=2.6, shift_y=-0.5, square_long=true
  tasks/cc/vision/hand_landmarker/hand_landmarks_detector_graph.cc
    模型输入 224x224; 输出 4 张量: [landmarks(63), presence(1), handedness(1), world(63)]
    TensorsToLandmarks: num_landmarks=21, normalize=true (x/224, y/224),
                        z/w/0.4; 无激活
    presence: TensorsToFloats 原始值, 阈值 min_detection_confidence(0.5)
    handedness: binary classification: score0(Right)=raw, score1(Left)=1-raw, top1
    LandmarkProjection: GetRotatedSubRectToRectTransformMatrix(rect, W, H) 投影回原图
      new_x = (a*c*(x-0.5) - b*d*(y-0.5) + e) / W   [x,y=裁剪归一化坐标]
      new_y = (a*d*(x-0.5) + b*c*(y-0.5) + f) / H

用途:
  1) PC 端参考结果(JSON): 检测框 + ROI rect + 21 关键点(原图像素)
  2) 导出 224x224 RGB patch(.bin) 给板端做同输入数值比对(隔离转换/推理误差)
  3) 渲染可视化(原图叠加骨架); 可 --check-gt 与训练仓库 GT 骨架(npz)对照
  4) --patch 模式: 对给定 patch 跑 tflite 并 dump 原始输出(与板端 dump 逐值比对)

用法:
  ~/.handwash-ref-venv/bin/python tools/ref_lm.py --frames testdata/lm_frames_001 \
      --n 12 --out out_pc/lm_run1
"""
import argparse
import json
import math
import sys
from pathlib import Path

import numpy as np

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(Path(__file__).resolve().parent))
from ref_det import decode as det_decode          # noqa: E402  手掌检测解码(已对齐官方)
from ref_det import weighted_nms, generate_anchors  # noqa: E402

# ---- 官方配置常量 ----
PALM_IN = 192
LM_IN = 224
NUM_LM = 21
TARGET_ANGLE = math.pi / 2
ROT_START_KP = 0
ROT_END_KP = 2
SCALE_X = 2.6
SCALE_Y = 2.6
SHIFT_Y = -0.5
LM_MIN_PRESENCE = 0.5

HAND_CONNECTIONS = [
    (0, 1), (1, 2), (2, 3), (3, 4),
    (0, 5), (5, 6), (6, 7), (7, 8),
    (5, 9), (9, 10), (10, 11), (11, 12),
    (9, 13), (13, 14), (14, 15), (15, 16),
    (13, 17), (17, 18), (18, 19), (19, 20),
    (0, 17),
]


def normalize_radians(angle):
    return angle - 2 * math.pi * math.floor((angle + math.pi) / (2 * math.pi))


# ---------------- 手工 letterbox / 采样 ----------------

def letterbox_params(src_w, src_h, dst):
    scale = min(dst / src_w, dst / src_h)
    nw, nh = round(src_w * scale), round(src_h * scale)
    return scale, (dst - nw) // 2, (dst - nh) // 2


def letterbox_image(img, dst):
    """黑边 letterbox(BORDER_ZERO), 双线性缩放, 与检测官方预处理一致。"""
    from PIL import Image
    h, w = img.shape[:2]
    scale, pad_x, pad_y = letterbox_params(w, h, dst)
    nw, nh = round(w * scale), round(h * scale)
    resized = np.asarray(Image.fromarray(img).resize((nw, nh), Image.BILINEAR))
    canvas = np.zeros((dst, dst, 3), dtype=np.uint8)
    canvas[pad_y:pad_y + nh, pad_x:pad_x + nw] = resized
    return canvas


def bilinear_sample(img, xs, ys):
    """img: (H,W,3) uint8; xs,ys: float 数组(像素坐标 0..W-1) → (…,3) float"""
    h, w = img.shape[:2]
    xs = np.clip(xs, 0.0, w - 1.001)
    ys = np.clip(ys, 0.0, h - 1.001)
    x0 = np.floor(xs).astype(np.int32)
    y0 = np.floor(ys).astype(np.int32)
    wx = (xs - x0)[..., None]
    wy = (ys - y0)[..., None]
    out = ((img[y0, x0] * (1 - wx) + img[y0, x0 + 1] * wx) * (1 - wy) +
           (img[y0 + 1, x0] * (1 - wx) + img[y0 + 1, x0 + 1] * wx) * wy)
    return out


def crop_roi(img, rect):
    """按官方 ROI(旋转矩形)裁剪 224x224 patch。

    rect 像素参数: {center_x, center_y, width, height, rotation}
    采样公式(即官方投影公式的反向利用):
      px = a*c*(xn-0.5) - b*d*(yn-0.5) + e ;  xn=(u+0.5)/224
      py = a*d*(xn-0.5) + b*c*(yn-0.5) + f ;  yn=(v+0.5)/224
    """
    a, b = rect["width"], rect["height"]
    e, f = rect["center_x"], rect["center_y"]
    c, d = math.cos(rect["rotation"]), math.sin(rect["rotation"])
    u = (np.arange(LM_IN) + 0.5) / LM_IN
    xn, yn = np.meshgrid(u, u)                     # (224,224)
    px = a * c * (xn - 0.5) - b * d * (yn - 0.5) + e
    py = a * d * (xn - 0.5) + b * c * (yn - 0.5) + f
    return bilinear_sample(img, px, py).astype(np.uint8)


def project_landmark(xn, yn, rect):
    """裁剪归一化坐标 (0..1) → 原图像素坐标(官方 LandmarkProjection 公式)。"""
    a, b = rect["width"], rect["height"]
    e, f = rect["center_x"], rect["center_y"]
    c, d = math.cos(rect["rotation"]), math.sin(rect["rotation"])
    px = a * c * (xn - 0.5) - b * d * (yn - 0.5) + e
    py = a * d * (xn - 0.5) + b * c * (yn - 0.5) + f
    return px, py


# ---------------- 官方 ROI 几何 ----------------

def palm_box_to_rect(box, img_w, img_h):
    """手掌检测(原图像素) → NormalizedRect(官方 DetectionsToRects + RectTransformation)。"""
    x1, y1, x2, y2 = box["x1"], box["y1"], box["x2"], box["y2"]
    kp0 = box["kp"][ROT_START_KP]      # 腕
    kp2 = box["kp"][ROT_END_KP]        # 中指 MCP
    rot = normalize_radians(TARGET_ANGLE - math.atan2(-(kp2[1] - kp0[1]),
                                                      kp2[0] - kp0[0]))
    # 归一化 rect
    width = (x2 - x1) / img_w
    height = (y2 - y1) / img_h
    x_center = ((x1 + x2) / 2) / img_w
    y_center = ((y1 + y2) / 2) / img_h

    # RectTransformation(归一化版, 官方公式)
    if rot == 0:
        x_center += width * 0.0            # shift_x = 0
        y_center += height * SHIFT_Y
    else:
        x_center += (img_w * width * 0.0 * math.cos(rot) -
                     img_h * height * SHIFT_Y * math.sin(rot)) / img_w
        y_center += (img_w * width * 0.0 * math.sin(rot) +
                     img_h * height * SHIFT_Y * math.cos(rot)) / img_h
    long_side = max(width * img_w, height * img_h)
    width = long_side / img_w
    height = long_side / img_h
    width *= SCALE_X
    height *= SCALE_Y
    return {
        "center_x": x_center * img_w, "center_y": y_center * img_h,
        "width": width * img_w, "height": height * img_h,   # 像素(存入像素坐标系)
        "rotation": rot,
    }


# ---------------- 推理 ----------------

def detect_palms(det_it, anchors, img, min_score=0.5, max_hands=2):
    """原图 → letterbox 192 → palm tflite → 解码+NMS → 原图像素框+7关键点。"""
    h, w = img.shape[:2]
    lb = letterbox_image(img, PALM_IN)
    ind = det_it.get_input_details()[0]
    outs = det_it.get_output_details()
    reg_idx = next(i for i, o in enumerate(outs) if o["shape"].tolist() == [1, 2016, 18])
    cls_idx = next(i for i, o in enumerate(outs) if o["shape"].tolist() == [1, 2016, 1])
    det_it.set_tensor(ind["index"], (lb.astype(np.float32) / 255.0)[None, ...])
    det_it.invoke()
    raw_reg = det_it.get_tensor(outs[reg_idx]["index"])[0]
    raw_cls = det_it.get_tensor(outs[cls_idx]["index"])[0, :, 0]

    dets = det_decode(raw_reg, raw_cls, anchors)
    kept = weighted_nms(dets, min_score=min_score)

    scale, pad_x, pad_y = letterbox_params(w, h, PALM_IN)

    def to_px(nx, ny):
        return ((nx * PALM_IN - pad_x) / scale, (ny * PALM_IN - pad_y) / scale)

    boxes = []
    for det in kept[:max_hands]:
        x1, y1 = to_px(det[1], det[2])
        x2, y2 = to_px(det[3], det[4])
        kp = []
        for k in range(7):
            kp.append(to_px(det[5 + 2 * k], det[6 + 2 * k]))
        boxes.append({"score": float(det[0]), "x1": x1, "y1": y1, "x2": x2, "y2": y2,
                      "kp": kp, "raw_reg": raw_reg, "raw_cls": raw_cls})
    return boxes, (raw_reg, raw_cls)


def run_landmark(lm_it, patch):
    """224x224 RGB patch → 反量化前浮点: 坐标(224 尺度), presence, handedness, world

    模型输出名(实测 tflite): Identity=landmarks[1,63], Identity_1=presence[1,1],
    Identity_2=handedness[1,1], Identity_3=world[1,63]
    (与官方 graph 的 split 顺序 [landmarks, presence, handedness, world] 一致)
    """
    ind = lm_it.get_input_details()[0]
    outs = {o["name"]: o for o in lm_it.get_output_details()}
    o_lm = outs["Identity"]
    o_ps = outs["Identity_1"]
    o_hd = outs["Identity_2"]
    o_wl = outs["Identity_3"]
    lm_it.set_tensor(ind["index"], (patch.astype(np.float32) / 255.0)[None, ...])
    lm_it.invoke()
    raw_lm = lm_it.get_tensor(o_lm["index"])[0]
    presence = float(lm_it.get_tensor(o_ps["index"])[0, 0])
    handedness = float(lm_it.get_tensor(o_hd["index"])[0, 0])
    world = lm_it.get_tensor(o_wl["index"])[0]
    return raw_lm, presence, handedness, world


def decode_landmarks(raw_lm, presence, handedness, rect):
    """原始输出 → 原图像素 21 点 + 元信息(官方语义)。"""
    pts3 = raw_lm.reshape(NUM_LM, 3)
    landmarks = []
    for i in range(NUM_LM):
        xn = pts3[i, 0] / LM_IN
        yn = pts3[i, 1] / LM_IN
        px, py = project_landmark(xn, yn, rect)
        landmarks.append([float(px), float(py), float(pts3[i, 2] / LM_IN)])
    side = "Right" if handedness >= 0.5 else "Left"
    return {"landmarks_px": landmarks, "side": side,
            "side_score": float(max(handedness, 1 - handedness)),
            "presence": float(presence)}


# ---------------- 可视化 ----------------

def draw_hand(draw, landmarks, color, radius=3, width=2):
    for a, b in HAND_CONNECTIONS:
        draw.line([landmarks[a][0], landmarks[a][1], landmarks[b][0], landmarks[b][1]],
                  fill=color, width=width)
    for p in landmarks:
        draw.ellipse([p[0] - radius, p[1] - radius, p[0] + radius, p[1] + radius],
                     fill=(255, 255, 255), outline=color)


def render(img, hands, boxes, path):
    from PIL import Image, ImageDraw
    im = Image.fromarray(img).copy()
    d = ImageDraw.Draw(im)
    for b in boxes:
        d.rectangle([b["x1"], b["y1"], b["x2"], b["y2"]], outline=(255, 128, 0), width=1)
    for h in hands:
        draw_hand(d, h["landmarks_px"], (0, 200, 0))
        wrist = h["landmarks_px"][0]
        d.text((wrist[0] + 4, wrist[1] - 12), f"{h['side']} {h['presence']:.2f}",
               fill=(0, 200, 0))
    im.save(path)


# ---------------- GT 对照 ----------------

def check_against_gt(hands, gt_frame, gt_visible, img_w, img_h):
    """与训练仓库 GT(单帧)对照: 返回每个手匹配到的 GT 槽位和平均像素误差。"""
    results = []
    vis_slots = []
    for slot in range(gt_visible.shape[0] // NUM_LM):
        if gt_visible[slot * NUM_LM]:
            vis_slots.append(slot)
    for h in hands:
        wrist = np.array(h["landmarks_px"][0][:2])
        best = None
        for slot in vis_slots:
            gt_wrist = gt_frame[slot * NUM_LM][:2] * np.array([img_w, img_h])
            dist = float(np.linalg.norm(wrist - gt_wrist))
            if best is None or dist < best[1]:
                best = (slot, dist)
        if best is None:
            results.append({"slot": None})
            continue
        slot = best[0]
        errs = []
        for i in range(NUM_LM):
            gt_p = gt_frame[slot * NUM_LM + i][:2] * np.array([img_w, img_h])
            mx = np.array(h["landmarks_px"][i][:2])
            errs.append(float(np.linalg.norm(mx - gt_p)))
        results.append({"slot": slot, "wrist_dist": best[1],
                        "mean_err": float(np.mean(errs)), "max_err": float(np.max(errs))})
    return results


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--palm-model", default=str(Path.home() /
                    "Desktop/标定/palm_detection_full.tflite"))
    ap.add_argument("--lm-model", default=str(Path.home() /
                    "Desktop/标定/hand_landmarks_detector.tflite"))
    ap.add_argument("--frames", default=str(ROOT / "testdata/lm_frames_001"))
    ap.add_argument("--n", type=int, default=12)
    ap.add_argument("--start", type=int, default=0, help="起始帧号(0 基)")
    ap.add_argument("--indices", default="", help="指定帧号列表(逗号分隔), 覆盖 --start/--n")
    ap.add_argument("--out", default=str(ROOT / "out_pc/lm_run1"))
    ap.add_argument("--min-score", type=float, default=0.5)
    ap.add_argument("--gt-npz", default="", help="训练仓库 GT 骨架 npz(名帧对照)")
    ap.add_argument("--patch", default="", help="patch 模式: 224x224 RGB bin → dump 输出")
    ap.add_argument("--dump", default="", help="patch 模式输出前缀")
    args = ap.parse_args()

    import ai_edge_litert.interpreter as itp
    lm_it = itp.Interpreter(model_path=args.lm_model)
    lm_it.allocate_tensors()

    if args.patch:
        patch = np.fromfile(args.patch, dtype=np.uint8).reshape(LM_IN, LM_IN, 3)
        raw_lm, presence, handedness, world = run_landmark(lm_it, patch)
        print(f"presence={presence:.6f} handedness={handedness:.6f}")
        print("landmarks raw:", np.array2string(raw_lm, precision=3, max_line_width=100))
        if args.dump:
            Path(args.dump + "_lm0.bin").write_bytes(raw_lm.astype(np.float32).tobytes())
            np.array([presence], np.float32).tofile(args.dump + "_lm1.bin")
            np.array([handedness], np.float32).tofile(args.dump + "_lm2.bin")
            world.astype(np.float32).tofile(args.dump + "_lm3.bin")
            print(f"已 dump -> {args.dump}_lm{{0,1,2,3}}.bin")
        return 0

    from PIL import Image
    out_dir = Path(args.out)
    out_dir.mkdir(parents=True, exist_ok=True)

    det_it = itp.Interpreter(model_path=args.palm_model)
    det_it.allocate_tensors()
    anchors = generate_anchors()

    gt = None
    if args.gt_npz:
        gt = np.load(args.gt_npz)

    frames_all = sorted(Path(args.frames).glob("f_*.png"))
    if args.indices:
        idx_list = [int(x) for x in args.indices.split(",") if x.strip() != ""]
        frames = [(i, frames_all[i]) for i in idx_list]
    else:
        frames = [(args.start + i, fp)
                  for i, fp in enumerate(frames_all[args.start:args.start + args.n])]
    summary = []
    for idx, fp in frames:
        img = np.asarray(Image.open(fp).convert("RGB"))
        h, w = img.shape[:2]
        boxes, (raw_reg, raw_cls) = detect_palms(det_it, anchors, img, args.min_score)
        hands = []
        for bi, box in enumerate(boxes):
            rect = palm_box_to_rect(box, w, h)
            patch = crop_roi(img, rect)
            raw_lm, presence, handedness, world = run_landmark(lm_it, patch)
            hand = decode_landmarks(raw_lm, presence, handedness, rect)
            hand["rect"] = rect
            hand["box"] = {k: box[k] for k in ("score", "x1", "y1", "x2", "y2", "kp")}
            hand["world"] = world.reshape(NUM_LM, 3).tolist()
            hands.append(hand)
            patch.tofile(out_dir / f"patch_{idx:03d}_{bi}.bin")
        img_path = out_dir / f"frame_{idx:03d}.png"
        Image.fromarray(img).save(img_path)
        render(img, [h for h in hands if h["presence"] >= LM_MIN_PRESENCE], boxes,
               out_dir / f"pc_overlay_{idx:03d}.png")

        entry = {"frame": idx, "file": fp.name,
                 "boxes": [{k: (v.tolist() if hasattr(v, "tolist") else v)
                            for k, v in b.items() if k not in ("raw_reg", "raw_cls")}
                           for b in boxes],
                 "hands": [{"presence": h["presence"], "side": h["side"],
                            "side_score": h["side_score"], "rect": h["rect"],
                            "landmarks_px": h["landmarks_px"]} for h in hands]}
        if gt is not None and idx < len(gt["timestamps_ms"]):
            gt_res = check_against_gt(hands, gt["coords"][idx], gt["visible"][idx], w, h)
            entry["gt_check"] = gt_res
            show = " ".join(
                f"slot{r.get('slot')}:mean={r.get('mean_err', float('nan')):.1f}px" for r in gt_res)
            print(f"[{idx:03d}] {fp.name}: {len(boxes)} box, {len(hands)} hand | GT {show}")
        else:
            print(f"[{idx:03d}] {fp.name}: {len(boxes)} box, {len(hands)} hand")
        summary.append(entry)

    (out_dir / "pc_results.json").write_text(json.dumps(summary, indent=1, default=float))
    print(f"PC 参考结果: {out_dir}/pc_results.json ({len(summary)} 帧)")
    return 0


if __name__ == "__main__":
    sys.exit(main())
