# -*- coding: utf-8 -*-
import json, time, uuid, urllib.request, urllib.parse
BASE="http://192.168.31.31:8189"; op=urllib.request.build_opener(urllib.request.ProxyHandler({}))
ABC=open('inst2.abc',encoding='utf-8').read().strip()
STYLE=("instrumental only, solo violin lead plays the whole melody, no vocals, no singing, no humming, no choir, "
       "slow melancholy Chinese ballad, expressive legato violin, warm room reverb, soft piano bed, cinematic autumn")
graph={
 "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":STYLE,"lyrics":"[instrumental]","cot":"melody","seed":20261034,
     "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":ABC,"abort_after_plan":False,"save_artifacts":False}},
 "6":{"class_type":"SaveAudioMP3","inputs":{"audio":["5",0],"filename_prefix":"audio/yue_violin_candF","quality":"V0"}},
}
json.dump(graph,open('api_f.json','w',encoding='utf-8'),ensure_ascii=False,indent=1)
body=json.dumps({"prompt":graph,"client_id":str(uuid.uuid4())}).encode()
req=urllib.request.Request(BASE+"/prompt",data=body,headers={"Content-Type":"application/json"})
try:
    with op.open(req,timeout=120) as r: data=json.load(r)
except urllib.error.HTTPError as e:
    print("REJECTED",e.code,e.read().decode()[:1200]); raise SystemExit(1)
pid=data["prompt_id"]; print("submitted",pid,flush=True)
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",e,flush=True); time.sleep(25); continue
    if pid in h:
        rec=h[pid]; st=rec.get("status",{})
        print(" status",st.get("status_str"),f"{int(time.time()-t0)}s",flush=True)
        if st.get("completed") or st.get("status_str") in ("error","failed"):
            json.dump(rec,open("history_F.json","w",encoding='utf-8'),ensure_ascii=False,indent=1); break
    time.sleep(15)
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")})
            with op.open(f"{BASE}/view?{q}",timeout=600) as r, open(f"cand_F_{fn}","wb") as f: f.write(r.read())
            print(" saved cand_F_"+fn,flush=True)
