import json, time, os, urllib.request, urllib.parse
API="http://192.168.31.31:8189"
OUT="/home/zyw/Downloads/dl-hub/138-高尚-ComfyUI出MJ工作流拆解/对比组-剑仙16x9"
op=urllib.request.build_opener(urllib.request.ProxyHandler({}))

LORA=[("krea/Krea_2_zidiusArt_Melancholy_v2.safetensors",0.60),
      ("krea/cinematic_movie_still_krea2.safetensors",0.20),
      ("krea/krea2_detail_slider.safetensors",0.60),
      ("krea/realism_engine_krea2_v3.1.safetensors",0.50),
      ("krea/krea2-Cc-MJ-影视柔光.safetensors",0.55),
      ("krea/krea2-Cc-MJ-风格滤镜.safetensors",0.60),
      ("krea/refusal_reduction_v2_full_rank.safetensors",0.70)]
BAL="1.0,1.0,1.0,1.0,1.0,1.0,1.0,2.5,5.0,1.1,4.0,1.0"
SEED=88135264906

P1=("masterpiece, best quality, amazing quality, very aesthetic, absurdres, newest, 1girl, solo, "
    "chinese style loli sword immortal, cinematic scene, black long straight hair, golden eyes, determined expression, "
    "red and gold traditional robe with dragon embroidery, holding glowing green sword, dynamic pose, "
    "standing on ancient stone bridge, bamboo forest background, falling cherry blossoms, volumetric lighting from moon, "
    "atmospheric fog, depth of field, low angle shot")
P2=("A cinematic wide shot of a lone Chinese-style sword immortal girl: long straight black hair, golden eyes, "
    "determined expression, wearing a red-and-gold traditional robe embroidered with dragons, holding a glowing green jade sword "
    "in a dynamic stance on an ancient stone bridge, bamboo forest behind her, cherry blossoms falling, "
    "moonlight cutting through volumetric fog, strong depth of field, low angle. Masterpiece, best quality, ultra detailed, newest aesthetic.")
P3=("大师级，最佳画质，极高细节，最新审美；国风少女剑仙，单人；乌黑长直发，金瞳，神情坚毅；"
    "红金相间的传统长袍，袍身绣盘龙纹；手持泛绿光的长剑；动感姿态，立于古老石桥之上；"
    "背景为竹林，樱瓣纷落；月光穿过雾气形成体积光，薄雾弥漫；浅景深；低角度仰拍，电影感宽画幅。")
P4=("masterpiece, best quality, amazing quality, very aesthetic, absurdres, newest, 1girl, solo, Chinese-style sword immortal, "
    "cinematic night scene, long straight black hair glowing at the edges, golden eyes, determined expression, "
    "red and gold traditional robe with dragon embroidery, holding a glowing green sword whose blade lights her face, dynamic lunge pose, "
    "ancient stone bridge with wet reflective stones, dense bamboo forest, falling cherry blossom petals, "
    "strong volumetric moonbeams through layered mist, rim light, atmospheric fog, shallow depth of field, low angle shot")
P5=("masterpiece, best quality, very aesthetic, absurdres, newest, 1girl, solo, Chinese-style sword immortal, cinematic wide landscape shot, "
    "long straight black hair, golden eyes, red and gold dragon-embroidered robe, glowing green sword, "
    "dynamic pose on an ancient arched stone bridge, bridge leading lines swept in fog, bamboo forest in silhouettes, "
    "cherry blossoms drifting across the frame, volumetric moonlight, layered atmospheric fog, deep depth of field, "
    "low angle wide shot, small figure in a vast scene")

CFG=[("V1-原始tag串-英文",P1,2048,1152),
     ("V2-英文自然语言",P2,2048,1152),
     ("V3-中文改写",P3,2048,1152),
     ("V4-夜景体积光强化",P4,2048,1152),
     ("V5-远景构图",P5,2048,1152)]

def build(text,w,h,tag):
    p={"1":{"class_type":"UNETLoader","inputs":{"unet_name":"krea2_turbo_fp8_scaled.safetensors","weight_dtype":"default"}},
       "2":{"class_type":"CLIPLoader","inputs":{"clip_name":"qwen3vl_4b_fp8_scaled.safetensors","type":"krea2"}},
       "3":{"class_type":"VAELoader","inputs":{"vae_name":"qwen_image_vae.safetensors"}}}
    pm,pc="1",("2",0)
    for i,(n,s) in enumerate(LORA):
        nid=str(4+i)
        p[nid]={"class_type":"LoraLoader","inputs":{"model":[pm,0],"clip":[pc[0],pc[1]],"lora_name":n,"strength_model":s,"strength_clip":0.0}}
        pm=nid; pc=(nid,1)
    b=4+len(LORA)
    p[str(b)]={"class_type":"CLIPTextEncode","inputs":{"clip":[pm,1],"text":text}}
    p[str(b+1)]={"class_type":"ConditioningZeroOut","inputs":{"conditioning":[str(b),0]}}
    p[str(b+2)]={"class_type":"ConditioningKrea2Rebalance","inputs":{"conditioning":[str(b),0],"multiplier":1.0,"per_layer_weights":BAL}}
    p[str(b+3)]={"class_type":"EmptyLatentImage","inputs":{"width":w,"height":h,"batch_size":1}}
    p[str(b+4)]={"class_type":"KSampler","inputs":{"model":[pm,0],"positive":[str(b+2),0],"negative":[str(b+1),0],"latent_image":[str(b+3),0],
                 "seed":SEED,"steps":8,"cfg":1.0,"sampler_name":"euler","scheduler":"simple","denoise":1.0}}
    p[str(b+5)]={"class_type":"VAEDecode","inputs":{"samples":[str(b+4),0],"vae":["3",0]}}
    p[str(b+6)]={"class_type":"SaveImage","inputs":{"images":[str(b+5),0],"filename_prefix":"sw16_"+tag}}
    return {"prompt":p,"client_id":"dsh-sw16"}

ids=[]
for name,text,w,h in CFG:
    r=json.load(op.open(urllib.request.Request(API+"/prompt",data=json.dumps(build(text,w,h,name.split('-')[0].lower())).encode(),
                    headers={"Content-Type":"application/json"}),timeout=30))
    ids.append((name,r["prompt_id"])); print("queued",name,r["prompt_id"],flush=True)

done={}; t0=time.time()
while len(done)<len(ids) and time.time()-t0<1800:
    time.sleep(10)
    for name,pid in ids:
        if name in done: continue
        try: d=json.load(op.open(API+"/history/"+pid,timeout=20))
        except Exception: continue
        if not d: continue
        v=list(d.values())[0]; st=v.get("status",{}).get("status_str")
        if st=="success":
            for n in (v.get("outputs") or {}).values():
                for im in n.get("images",[]): done[name]=im["filename"]
            print("done",name,done[name],round(time.time()-t0),"s",flush=True)
        elif st=="error": done[name]=None; print("ERR",name,flush=True)

for name,fn in done.items():
    if not fn: continue
    d=op.open(API+"/view?"+urllib.parse.urlencode({"filename":fn,"type":"output","subfolder":""}),timeout=180).read()
    open(os.path.join(OUT,name+".png"),"wb").write(d); print("saved",name,len(d),flush=True)
print("ALL",done)
