#!/usr/bin/env python3
"""toy_echo48u: echo toy whose UINT8 input domain is remapped to non-negative
bytes via the toolkit's fused input conversion (mean/std), mimicking the
verified-working landmark model input format.

Physical input = u8 domain [0,255]; input conversion ((u - 127.5) / 25.5)
reconstructs the feature domain [-5,5] inside the graph.  If the RV1106 input
path is fine with all-non-negative bytes (like the landmark model) this should
finally echo the values correctly.

Usage: /root/mmpose-venv/bin/python make_echo48u_toy.py
"""

from __future__ import annotations

from pathlib import Path

import numpy as np

WORK = Path("/root/handwash-st-gcn-rknn")
OUT = WORK / "output/toys2"


def make_u8_calibration() -> Path:
    """Raw u8-domain calibration: u = x * 25.5 + 127.5 (feature domain -> 0..255)."""
    src_list = WORK / "calibration/toy_t1/list.txt"
    dst_dir = WORK / "calibration/toy_t1_u8"
    dst_dir.mkdir(parents=True, exist_ok=True)
    lines = []
    for i, src in enumerate([l.strip() for l in src_list.read_text().splitlines() if l.strip()]):
        data = np.load(src)  # (1,3,32,48) feature domain
        raw = np.clip(data * 25.5 + 127.5, 0.0, 255.0)
        dst = dst_dir / f"{i:04d}.npy"
        np.save(dst, raw.astype(np.float32))
        lines.append(str(dst))
    (dst_dir / "list.txt").write_text("\n".join(lines) + "\n")
    print(f"    u8 域校准: {len(lines)} 个 -> {dst_dir}")
    return dst_dir / "list.txt"


def main() -> None:
    from rknn.api import RKNN

    calib = make_u8_calibration()
    rknn = RKNN(verbose=False)
    try:
        assert rknn.config(target_platform="rv1106",
                           mean_values=[[127.5, 127.5, 127.5]],
                           std_values=[[25.5, 25.5, 25.5]],
                           quantized_dtype="asymmetric_quantized-8",
                           optimization_level=3) == 0
        assert rknn.load_onnx(model=str(OUT / "toy_echo48.onnx")) == 0
        assert rknn.build(do_quantization=True, dataset=str(calib)) == 0
        assert rknn.export_rknn(str(OUT / "toy_echo48u_rv1106.rknn")) == 0
    finally:
        rknn.release()
    dest = OUT / "toy_echo48u_rv1106.rknn"
    print(f"    -> {dest.name} ({dest.stat().st_size/1024:.1f} KB)")
    print("板端预期: U8 策略输出 ≈ [-3 -2 -1 0 1 2 3]")


if __name__ == "__main__":
    main()
