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 + "s06bv7/"
os.makedirs(OUT, exist_ok=True)
J = json.load(open(I + "s06bv7.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/s06bv7/S06b_v7_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 = {}
PLAN = [(2026, 107), (2026, 124), (31, 124)]
for seed, length in PLAN:
    print("=== seed", seed, "length", length, flush=True)
    r = post("/prompt", {"prompt": graph(P, seed, length)})
    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
    tag = "S06b_v7_s%d_L%d" % (seed, length)
    dst = OUT + tag + ".mp4"
    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 + tag + ".wav"
    subprocess.run(["ffmpeg", "-y", "-v", "error", "-i", dst, "-vn", "-ac", "1", "-ar", str(SR), "-c:a", "pcm_s16le", wav], check=True)
    syl = syllables(wav)
    segs = syl["segments"]
    r0 = segs[0][0] if segs else None
    r1 = max(x[1] for x in segs) if segs else None
    dur = N / 24.0
    nuclei = syl["nuclei_times"]
    gaps = [round(nuclei[i + 1] - nuclei[i], 3) for i in range(len(nuclei) - 1)]
    ent = {"seed": seed, "length": length, "prompt_id": pid, "wall": round(wall), "video": dst,
           "frames": N, "duration_sec": round(dur, 3), "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, 3) if (r0 is not None and r1 is not None) else None,
           "syllable_gaps": gaps,
           "chars_per_sec": round(4.0 / (r1 - r0), 2) if (r0 is not None and r1 is not None and r1 > r0) else None,
           "tail_margin_sec": round(dur - r1, 3) if 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_le_2p9"] = (r0 is not None and 2.2 <= r0 <= 2.9)
    ent["accept_end_joint_lt_3p9"] = (r0 is not None and ent["speech_len"] is not None and (r0 + ent["speech_len"]) < 3.9)
    ent["accept_tail_ge_0p3"] = (ent["tail_margin_sec"] is not None and ent["tail_margin_sec"] >= 0.3)
    ent["accept_all"] = all([ent["accept_nuclei4"], ent["accept_len_ge_0p8"], ent["accept_start_le_2p9"], ent["accept_end_joint_lt_3p9"], ent["accept_tail_ge_0p3"]])
    res[tag] = 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 + 17) // 18) * 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_" + tag + ".png"); print("SAVED sheet", tag, flush=True)
    json.dump(res, open(OUT + "s06bv7.json", "w"), ensure_ascii=False, indent=1)
    if ent["accept_all"]:
        print("ACCEPTED", tag, flush=True)
        break
    print("NOT_ACCEPTED", tag, "-> next", flush=True)
json.dump(res, open(OUT + "s06bv7.json", "w"), ensure_ascii=False, indent=1)
print("S06BV7_DONE", flush=True)
