#!/usr/bin/env python3
"""PC 参考检测器 — 复刻 MediaPipe HandDetector 后处理(权威配置来源见下)

配置出处(mediapipe 官方源码, 已逐字段核对):
  mediapipe/tasks/cc/vision/hand_detector/hand_detector_graph.cc
    TensorsToDetections: num_boxes=2016, num_coords=18, keypoint_offset=4, 7 kpts,
        sigmoid=true, clip=100, reverse_output_order=true → 原始顺序 (x,y,w,h)
        scale=192 (x/y/w/h), min_score_thresh=min_detection_confidence
    NMS: WEIGHTED 算法, IoU>0.3(min_suppression_threshold)
    SsdAnchors: 4 层 strides=8,16,16,16, min_scale=0.1484375, max_scale=0.75,
        aspect_ratios=[1.0], interpolated=1.0, fixed_anchor_size=true,
        anchor_offset=0.5 → 每格 2 个(24×24 层)/ 6 个(12×12 层) = 2016

用途:
  1) 生成板端 C++ 实现可比对的参考结果(box/keypoint/score)
  2) 渲染可视化(letterbox 放大图 + 原图反映射), 人工核对
  3) 与板端 model_bench dump 逐元素比对, 定位量化/预处理偏差

用法:
  ~/.handwash-ref-venv/bin/python tools/ref_det.py [选项]
"""
import argparse
import json
import sys
from pathlib import Path

import numpy as np

ROOT = Path(__file__).resolve().parent.parent

# ---- 官方配置常量 ----
INPUT_SIZE = 192
STRIDES = [8, 16, 16, 16]
ASPECT_RATIOS = [1.0]
INTERP_RATIO = 1.0
ANCHOR_OFFSET = 0.5
XYWH_SCALE = 192.0
SCORE_CLIP = 100.0
NUM_KEYPOINTS = 7
NMS_IOU = 0.3
SRC_W, SRC_H = 720, 480          # HandWash_001 视频原始分辨率


def generate_anchors():
    """严格按 ssd_anchors_calculator.cc 生成 2016 个 anchor (x_c, y_c, w, h)。"""
    anchors = []
    layer_id = 0
    while layer_id < len(STRIDES):
        group_end = layer_id
        while group_end < len(STRIDES) and STRIDES[group_end] == STRIDES[layer_id]:
            group_end += 1
        n_per_layer = len(ASPECT_RATIOS) + (1 if INTERP_RATIO > 0 else 0)
        n_per_cell = n_per_layer * (group_end - layer_id)   # 同 stride 层合并
        fm = int(np.ceil(INPUT_SIZE / STRIDES[layer_id]))
        for y in range(fm):
            for x in range(fm):
                cx = (x + ANCHOR_OFFSET) / fm
                cy = (y + ANCHOR_OFFSET) / fm
                for _ in range(n_per_cell):
                    anchors.append((cx, cy, 1.0, 1.0))     # fixed_anchor_size
        layer_id = group_end
    return np.asarray(anchors, dtype=np.float32)


def decode(raw_boxes, raw_scores, anchors):
    """TensorsToDetections 解码(reverse_output_order=true → x,y,w,h)。

    返回 [N, 1+4+14]: score, xmin,ymin,xmax,ymax(归一化), 7×(kx,ky)(归一化)
    """
    scores = 1.0 / (1.0 + np.exp(-np.clip(raw_scores, -SCORE_CLIP, SCORE_CLIP)))
    a = anchors
    x_c = raw_boxes[:, 0] / XYWH_SCALE * a[:, 2] + a[:, 0]
    y_c = raw_boxes[:, 1] / XYWH_SCALE * a[:, 3] + a[:, 1]
    w = raw_boxes[:, 2] / XYWH_SCALE * a[:, 2]
    h = raw_boxes[:, 3] / XYWH_SCALE * a[:, 3]
    det = np.zeros((raw_boxes.shape[0], 5 + 2 * NUM_KEYPOINTS), dtype=np.float32)
    det[:, 0] = scores
    det[:, 1] = x_c - w / 2
    det[:, 2] = y_c - h / 2
    det[:, 3] = x_c + w / 2
    det[:, 4] = y_c + h / 2
    for k in range(NUM_KEYPOINTS):
        det[:, 5 + 2 * k] = raw_boxes[:, 4 + 2 * k] / XYWH_SCALE * a[:, 2] + a[:, 0]
        det[:, 5 + 2 * k + 1] = raw_boxes[:, 5 + 2 * k] / XYWH_SCALE * a[:, 3] + a[:, 1]
    return det


def _iou(a, b):
    x1 = max(a[1], b[1]); y1 = max(a[2], b[2])
    x2 = min(a[3], b[3]); y2 = min(a[4], b[4])
    inter = max(0.0, x2 - x1) * max(0.0, y2 - y1)
    union = (a[3] - a[1]) * (a[4] - a[2]) + (b[3] - b[1]) * (b[4] - b[2]) - inter
    return inter / union if union > 0 else 0.0


def weighted_nms(dets, min_score=0.5, iou_thresh=NMS_IOU):
    """复刻 NonMaxSuppressionCalculator(WEIGHTED): 组内按分数加权平均框与关键点。

    注意: 官方 NMS 的输入是 TensorsToDetections 已经过滤过的检测(score>=阈值),
    因此必须先过滤再合并 —— 否则低于阈值的 anchor 会混入加权平均。
    """
    dets = dets[dets[:, 0] >= min_score]
    if dets.shape[0] == 0:
        return dets
    remained = [int(i) for i in np.argsort(-dets[:, 0])]
    out = []
    while remained:
        n_before = len(remained)
        top = dets[remained[0]]
        cand, rest = [], []
        for i in remained:
            (cand if _iou(dets[i], top) > iou_thresh else rest).append(i)
        merged = top.copy()
        if cand:
            total = sum(float(dets[i, 0]) for i in cand)
            for col in range(1, dets.shape[1]):
                merged[col] = sum(float(dets[i, col]) * float(dets[i, 0])
                                  for i in cand) / total
        out.append(merged)
        if n_before == len(rest):
            break
        remained = rest
    return np.asarray(out, dtype=np.float32) if out else np.zeros((0, dets.shape[1]), np.float32)


def letterbox_params():
    scale = min(INPUT_SIZE / SRC_W, INPUT_SIZE / SRC_H)
    nw, nh = round(SRC_W * scale), round(SRC_H * scale)
    return scale, (INPUT_SIZE - nw) // 2, (INPUT_SIZE - nh) // 2


def lb_to_orig(x_lb, y_lb):
    scale, pad_x, pad_y = letterbox_params()
    return (x_lb * INPUT_SIZE - pad_x) / scale, (y_lb * INPUT_SIZE - pad_y) / scale


def render(img_lb, dets, frame_rgb, out_prefix, top_n=4):
    """letterbox 图放大 3x 画框 + 原图反映射画框。"""
    from PIL import Image, ImageDraw

    z = 3
    im = Image.fromarray(img_lb).resize((INPUT_SIZE * z, INPUT_SIZE * z), Image.NEAREST)
    d = ImageDraw.Draw(im)
    for det in dets[:top_n]:
        d.rectangle([det[1] * INPUT_SIZE * z, det[2] * INPUT_SIZE * z,
                     det[3] * INPUT_SIZE * z, det[4] * INPUT_SIZE * z],
                    outline=(255, 0, 0), width=2)
        d.text((det[1] * INPUT_SIZE * z + 2, det[2] * INPUT_SIZE * z + 2),
               f"{det[0]:.2f}", fill=(255, 255, 0))
        for k in range(NUM_KEYPOINTS):
            px, py = det[5 + 2 * k] * INPUT_SIZE * z, det[6 + 2 * k] * INPUT_SIZE * z
            d.ellipse([px - 3, py - 3, px + 3, py + 3], fill=(0, 255, 0))
    im.save(f"{out_prefix}_lb.png")

    fo = Image.fromarray(frame_rgb).copy()
    do = ImageDraw.Draw(fo)
    for det in dets[:top_n]:
        x1, y1 = lb_to_orig(det[1], det[2])
        x2, y2 = lb_to_orig(det[3], det[4])
        do.rectangle([x1, y1, x2, y2], outline=(255, 0, 0), width=2)
        do.text((x1 + 2, y1 + 2), f"{det[0]:.2f}", fill=(255, 255, 0))
        for k in range(NUM_KEYPOINTS):
            px, py = lb_to_orig(det[5 + 2 * k], det[6 + 2 * k])
            do.ellipse([px - 3, py - 3, px + 3, py + 3], fill=(0, 255, 0))
    fo.save(f"{out_prefix}_orig.png")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--model", default=str(Path.home() / "Desktop/标定/palm_detection_full.tflite"))
    ap.add_argument("--inputs", default=str(ROOT / "testdata"))
    ap.add_argument("--board-dump", default=str(ROOT / "out_board/det_out"))
    ap.add_argument("--n", type=int, default=12)
    ap.add_argument("--min-score", type=float, default=0.5)
    ap.add_argument("--render", default="")
    ap.add_argument("--json", default="")
    args = ap.parse_args()

    import ai_edge_litert.interpreter as itp

    interp = itp.Interpreter(model_path=args.model)
    interp.allocate_tensors()
    inp = interp.get_input_details()[0]
    outs = interp.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])
    anchors = generate_anchors()
    print(f"model={Path(args.model).name}  anchors={anchors.shape[0]}")

    board_reg = board_cls = None
    bd, bc = Path(str(args.board_dump) + "0.bin"), Path(str(args.board_dump) + "1.bin")
    if bd.exists() and bc.exists():
        board_reg = np.fromfile(bd, dtype=np.float32).reshape(-1, 18)
        board_cls = np.fromfile(bc, dtype=np.float32).reshape(-1)

    frames = []
    if args.render:
        import subprocess, tempfile
        from PIL import Image
        with tempfile.TemporaryDirectory() as td:
            subprocess.run(["ffmpeg", "-y", "-v", "error", "-i",
                            str(ROOT / "HandWash_001_A_01_G01.mp4"), "-vf", "fps=10",
                            "-frames:v", str(args.n), f"{td}/f_%03d.png"], check=True)
            for fp in sorted(Path(td).glob("f_*.png")):
                frames.append(np.asarray(Image.open(fp).convert("RGB")))

    results = {}
    best = None
    files = sorted(Path(args.inputs).glob("det_in_*.bin"))[: args.n]
    for idx, fp in enumerate(files):
        img = np.fromfile(fp, dtype=np.uint8).reshape(INPUT_SIZE, INPUT_SIZE, 3)
        interp.set_tensor(inp["index"], (img.astype(np.float32) / 255.0)[None, ...])
        interp.invoke()
        raw_reg = interp.get_tensor(outs[reg_idx]["index"])[0]
        raw_cls = interp.get_tensor(outs[cls_idx]["index"])[0, :, 0]

        dets = decode(raw_reg, raw_cls, anchors)
        kept = weighted_nms(dets, min_score=args.min_score)
        print(f"\n== {fp.name}  raw-cls[{raw_cls.min():.2f},{raw_cls.max():.2f}] "
              f">={args.min_score}: {(dets[:, 0] >= args.min_score).sum()}  NMS→{len(kept)}")
        for det in kept:
            x1, y1 = lb_to_orig(det[1], det[2])
            x2, y2 = lb_to_orig(det[3], det[4])
            kx, ky = lb_to_orig(det[5], det[6])
            print(f"   score={det[0]:.3f} box(orig {SRC_W}x{SRC_H})=[{x1:6.1f},{y1:6.1f},"
                  f"{x2:6.1f},{y2:6.1f}] wrist=({kx:5.1f},{ky:5.1f})")
        results[fp.name] = [[round(float(v), 6) for v in det] for det in kept]

        if board_reg is not None:
            d_reg = float(np.abs(board_reg - raw_reg).mean())
            d_cls = float(np.abs(board_cls - raw_cls).mean())
            if best is None or (d_reg + d_cls) < best[1]:
                best = (fp.name, d_reg + d_cls, d_reg, d_cls)
        if args.render and idx < len(frames) and len(kept):
            render(img, kept, frames[idx], f"{args.render}_{idx:03d}")

    if board_reg is not None and best:
        print(f"\n板端 dump 最匹配输入: {best[0]}  (reg mean|d|={best[2]:.3f}, cls mean|d|={best[3]:.3f})")
        bdets = weighted_nms(decode(board_reg, board_cls, anchors), args.min_score)
        print(f"板端 wNMS 后 {len(bdets)} 个检测(板端 score 受量化上限截断, sigmoid≤0.5):")
        for det in bdets:
            x1, y1 = lb_to_orig(det[1], det[2])
            x2, y2 = lb_to_orig(det[3], det[4])
            print(f"   [board] ({det[0]:.3f}) box=[{x1:6.1f},{y1:6.1f},{x2:6.1f},{y2:6.1f}]")

    if args.json:
        Path(args.json).write_text(json.dumps(results, indent=1))
        print(f"\n参考结果已保存: {args.json}")


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