# -*- coding: utf-8 -*-
import json, sys, time, uuid, urllib.request, urllib.parse
BASE="http://192.168.31.31:8189"
op=urllib.request.build_opener(urllib.request.ProxyHandler({}))
AUDIO="烟雨烟雨_src.mp3"

STYLE_INSTR=("instrumental only, solo violin lead carrying the melody, no vocals, no singing, no humming, no choir, "
             "no backing voices, no drums, no percussion, melancholy Chinese ballad, slow tempo, expressive legato violin, "
             "warm intimate room reverb, soft piano bed, cinematic autumn mood")

VARIANTS=[
 dict(id="C", seed=20261031, cot="off",   lyrics="",                style=STYLE_INSTR),
 dict(id="D", seed=20261032, cot="full",  lyrics="[instrumental]",  style=STYLE_INSTR),
 dict(id="E", seed=20261033, cot="melody",lyrics="[instrumental]",  style="solo violin instrumental, no vocals at all, wordless, slow legato violin melody over soft piano, intimate room reverb, melancholy autumn"),
]

def graph(v):
    return {
     "1":{"class_type":"LoadAudio","inputs":{"audio":AUDIO}},
     "2":{"class_type":"SheetSage2Loader","inputs":{"model":"SheetSage2","device":"cuda","dtype":"bfloat16","mert2_model":"MERT-v2-FullSong"}},
     "3":{"class_type":"SheetSage2Transcribe","inputs":{"model":["2",0],"audio":["1",0],"melody_only":True,"preset":"default",
         "max_seconds":45.0,"save_outputs":True,"abc_error_mode":"snap_invalid_notes","overlap_seconds":-1,"lookahead_seconds":-1,"auto_unload":False}},
     "4":{"class_type":"YuE2Loader","inputs":{"model":"YuE2-3B","vae":"YuE2-Vae","device":"cuda","memory_budget_gib":24,
         "offload_ar":False,"offline":True,"attention_backend":"auto","quantization":"none"}},
     "5":{"class_type":"YuE2Sampler","inputs":{"pipeline":["4",0],"style":v["style"],"lyrics":v["lyrics"],"cot":v["cot"],"seed":v["seed"],
         "cfg_scale":-1,"ode_steps":32,"abc_max_tokens":4096,"semantic_max_tokens":9000,"abc_temperature":0.7,
         "semantic_temperature":1.0,"save_flac":False,"save_abc":True,"vae_decode":"auto","vae_tile_frames":False,
         "abc":["3",0],"abort_after_plan":False,"save_artifacts":False}},
     "6":{"class_type":"SaveAudioMP3","inputs":{"audio":["5",0],"filename_prefix":f"audio/yue_violin_cand{v['id']}","quality":"V0"}},
    }

def submit(g):
    body=json.dumps({"prompt":g,"client_id":str(uuid.uuid4())}).encode()
    req=urllib.request.Request(BASE+"/prompt",data=body,headers={"Content-Type":"application/json"})
    with op.open(req,timeout=120) as r: return json.load(r)["prompt_id"]

def wait(pid):
    t0=time.time()
    while True:
        try:
            with op.open(f"{BASE}/history/{pid}",timeout=60) as r: h=json.load(r)
        except Exception as e:
            print("  poll err",e,flush=True); time.sleep(25); continue
        if pid in h:
            rec=h[pid]; st=rec.get("status",{})
            if st.get("completed") or st.get("status_str") in ("error","failed"):
                print("  status",st.get("status_str"),f"{int(time.time()-t0)}s",flush=True); return rec
        time.sleep(15)

for v in VARIANTS:
    print("=== variant",v["id"],"cot",v["cot"],"lyrics",repr(v["lyrics"])[:20],flush=True)
    try:
        pid=submit(graph(v)); print("  pid",pid,flush=True)
        rec=wait(pid)
        json.dump(rec,open(f"history_{v['id']}.json","w",encoding='utf-8'),ensure_ascii=False,indent=1)
        for _n,o in (rec.get("outputs") or {}).items():
            for it in (o.get("audio") or [])+(o.get("images") or []):
                fn=it.get("filename","")
                if fn:
                    q=urllib.parse.urlencode({"filename":fn,"subfolder":it.get("subfolder",""),"type":it.get("type","output")})
                    out=f"cand_{v['id']}_{fn}"
                    with op.open(f"{BASE}/view?{q}",timeout=600) as r, open(out,"wb") as f: f.write(r.read())
                    print("  saved",out,flush=True)
    except Exception as e:
        print("  ERROR",e,flush=True)
print("VARIANTS DONE",flush=True)
