import json, time, urllib.request, os, hashlib, shutil, subprocess
import numpy as np, cv2
from scipy.io import wavfile
from scipy.signal import butter, sosfilt
from PIL import Image, ImageDraw, ImageFont
from insightface.app import FaceAnalysis

BASE = "http://127.0.0.1:8189"
I = "/var/aiadultvideo/input/"
A = "/var/aiadultvideo/output/aiadult/"
OUT = A + "s06bv6/"
os.makedirs(OUT, exist_ok=True)
J = json.load(open(I + "s06bv6.json"))
ALIGN = "How the reference picture aligns with the target video — Picture 1 (from [Shot 1]) aligns with the 0.00-second mark of the target video."
P = (ALIGN + "\n\nintegrated_multimodal_description:\n" + J["main"] + " " + J["cons"] +
     "\n\noverall_soundscape:\n" + J["sound"] + "\n\nnon_diegetic_music:\nN/A")
print("prompt_chars", len(P), "md5", hashlib.md5(P.encode()).hexdigest(), flush=True)

app = FaceAnalysis(name="buffalo_l", providers=["CPUExecutionProvider"])
app.prepare(ctx_id=-1, det_size=(1280, 1280))


def post(p, b):
    req = urllib.request.Request(BASE + p, data=json.dumps(b).encode(),
                                 headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=300) as r:
        return json.loads(r.read().decode())


def wait(pid, timeout=3600):
    t0 = time.time()
    while time.time() - t0 < timeout:
        try:
            h = json.loads(urllib.request.urlopen(BASE + "/history/" + pid, timeout=30).read())
        except Exception:
            time.sleep(3); continue
        if pid in h:
            st = h[pid].get("status", {})
            if st.get("status_str") == "success":
                for k in h[pid]["outputs"]:
                    for v in h[pid]["outputs"][k].get("videos", []) + h[pid]["outputs"][k].get("images", []):
                        fn = v.get("filename")
                        if fn:
                            cand = os.path.join("/var/aiadultvideo/output", v.get("subfolder") or "", fn)
                            if os.path.exists(cand):
                                return cand, time.time() - t0
                return None, time.time() - t0
            if st.get("status_str") == "error":
                print("ERR", json.dumps(st)[:400], flush=True); return None, time.time() - t0
        time.sleep(4)
    return None, time.time() - t0


def graph(p, seed, length=107):
    return {
     "1": {"class_type": "UNETLoader", "inputs": {"unet_name": "minimax_h3_ref2va_pruned_fp8_scaled.safetensors", "weight_dtype": "default"}},
     "2": {"class_type": "CLIPLoader", "inputs": {"clip_name": "qwen3vl_32b_heretic_minimax_h3_nvfp4.safetensors", "type": "minimax", "device": "default"}},
     "3": {"class_type": "VAELoader", "inputs": {"vae_name": "minimax_h3_video_vae_fp16.safetensors"}},
     "4": {"class_type": "VAELoader", "inputs": {"vae_name": "minimax_h3_audio_vae_fp32.safetensors"}},
     "5": {"class_type": "LoraLoaderModelOnly", "inputs": {"model": ["1", 0], "lora_name": "pika_h3_flex_turbo_8step_hd_ref2va.safetensors", "strength_model": 1.0}},
     "6": {"class_type": "MiniMaxH3SigmaShift", "inputs": {"model": ["5", 0], "shift_video": 12.0, "shift_audio": 3.0}},
     "7": {"class_type": "LoadImage", "inputs": {"image": "S06b_first.png"}},
     "8": {"class_type": "MiniMaxH3ImageToVideo", "inputs": {"clip": ["2", 0], "vae": ["3", 0], "prompt": p, "width": 1312, "height": 736, "length": length, "first_frame": ["7", 0]}},
     "9": {"class_type": "ConditioningZeroOut", "inputs": {"conditioning": ["8", 0]}},
     "10": {"class_type": "KSampler", "inputs": {"model": ["6", 0], "seed": seed, "steps": 8, "cfg": 1.0, "sampler_name": "res_multistep", "scheduler": "simple", "positive": ["8", 0], "negative": ["9", 0], "latent_image": ["8", 1], "denoise": 1.0}},
     "11": {"class_type": "VAEDecode", "inputs": {"samples": ["10", 0], "vae": ["3", 0]}},
     "12": {"class_type": "VAEDecodeAudio", "inputs": {"samples": ["10", 0], "vae": ["4", 0]}},
     "13": {"class_type": "CreateVideo", "inputs": {"images": ["11", 0], "fps": 24.0, "audio": ["12", 0]}},
     "14": {"class_type": "SaveVideo", "inputs": {"video": ["13", 0], "filename_prefix": "aiadult/s06bv6/S06b_v6_s%d" % seed, "format": "auto", "codec": "auto"}},
    }


SR = 16000
sos_bp = butter(4, [200, 3400], btype="bandpass", fs=SR, output="sos")


def syllables(wav):
    sr, x = wavfile.read(wav)
    x = x.astype(np.float64)
    band = sosfilt(sos_bp, x)
    hop = 160
    n = len(band) // hop
    e = np.sqrt((band[:n * hop].reshape(n, hop) ** 2).mean(1) + 1e-12)
    db = 20 * np.log10(e / 32768.0)
    noise = float(np.percentile(db, 10)); peak = float(np.percentile(db, 99))
    thr = max(noise + 8.0, peak - 22.0)
    v = db > thr
    segs = []; i = 0
    while i < n:
        if not v[i]: i += 1; continue
        j = i
        while j + 1 < n and v[j + 1]: j += 1
        if (j - i) * 0.01 >= 0.04: segs.append((round(i * 0.01, 2), round(j * 0.01, 2)))
        i = j + 1
    es = np.convolve(db, np.ones(3) / 3.0, mode="same")
    peaks = []
    for k in range(2, len(es) - 2):
        if es[k] > thr + 2 and es[k] >= es[k - 1] and es[k] > es[k + 1] and es[k] >= es[k - 2] and es[k] >= es[k + 2]:
            if not peaks or (k - peaks[-1]) * 0.01 >= 0.055:
                peaks.append(k)
    return {"segments": segs, "nuclei_count": len(peaks),
            "nuclei_times": [round(p * 0.01, 2) for p in peaks],
            "voiced_sec": round(float(v.sum()) * 0.01, 2),
            "noise_db": round(noise, 1), "peak_db": round(peak, 1)}


res = {}
for seed in (2026,):
    print("=== seed", seed, flush=True)
    r = post("/prompt", {"prompt": graph(P, seed)})
    pid = r.get("prompt_id")
    if not pid:
        print("CREATE_FAIL", json.dumps(r)[:300], flush=True); continue
    print("prompt_id", pid, flush=True)
    src, wall = wait(pid)
    print("wall %.0f" % wall, src, flush=True)
    if not src:
        continue
    dst = OUT + "S06b_v6_s%d.mp4" % seed
    shutil.copyfile(src, dst)
    cap = cv2.VideoCapture(dst); fr = []
    while True:
        ok, f = cap.read()
        if not ok: break
        fr.append(f)
    cap.release(); N = len(fr)
    d = [float(np.abs(fr[i].astype(np.float32) - fr[i - 1].astype(np.float32)).mean()) for i in range(1, N)]
    faces = [len(app.get(fr[i])) for i in range(0, N, 3)]
    lum = [float(f.astype(np.float32).mean()) for f in fr]
    wav = OUT + "S06b_v6_s%d.wav" % seed
    subprocess.run(["ffmpeg", "-y", "-v", "error", "-i", dst, "-vn", "-ac", "1", "-ar", str(SR), "-c:a", "pcm_s16le", wav], check=True)
    syl = syllables(wav)
    r0 = syl["segments"][0][0] if syl["segments"] else None
    r1 = max(s[1] for s in syl["segments"]) if syl["segments"] else None
    ent = {"seed": seed, "prompt_id": pid, "wall": round(wall), "video": dst,
           "frames": N, "prompt_md5": hashlib.md5(P.encode()).hexdigest(),
           "max_jump": round(max(d), 2), "max_jump_frame": int(np.argmax(d)) + 1,
           "max_faces": max(faces), "face_missing": sum(1 for x in faces if x == 0),
           "lum": [round(lum[0]), round(min(lum)), round(lum[-1])],
           "speech": syl, "speech_start": r0, "speech_end": r1,
           "speech_len": round(r1 - r0, 2) if (r0 is not None and r1 is not None) else None}
    ent["accept_nuclei4"] = syl["nuclei_count"] == 4
    ent["accept_len_ge_0p8"] = (ent["speech_len"] or 0) >= 0.8
    ent["accept_start_2p2_3p4"] = (r0 is not None and 2.2 <= r0 <= 3.4)
    ent["accept_end_lt_3p9"] = (r1 is not None and r1 < 3.9)
    ent["accept_all"] = all([ent["accept_nuclei4"], ent["accept_len_ge_0p8"], ent["accept_start_2p2_3p4"], ent["accept_end_lt_3p9"]])
    res[str(seed)] = ent
    print("MEASURE", json.dumps(ent, ensure_ascii=False), flush=True)
    try:
        font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 13)
    except Exception:
        font = None
    sh = Image.new("RGB", (6 * 300, ((N + 23) // 24) * 168), (10, 10, 10)); dd = ImageDraw.Draw(sh)
    for k, i in enumerate(range(0, N, 3)):
        xx = (k % 6) * 300; yy = (k // 6) * 168
        sh.paste(Image.fromarray(cv2.cvtColor(cv2.resize(fr[i], (300, 168)), cv2.COLOR_BGR2RGB)), (xx, yy))
        dd.text((xx + 3, yy + 3), "f%03d %.2fs" % (i, i / 24.0), fill=(255, 255, 0), font=font)
    sh.save(OUT + "sheet_S06b_v6_s%d.png" % seed); print("SAVED sheet", flush=True)
json.dump(res, open(OUT + "s06bv6.json", "w"), ensure_ascii=False, indent=1)
print("S06BV6_DONE", flush=True)
