#!/usr/bin/env python3
"""短剧《雨夜撞上陆总后》第十六集 - 场景图生成"""
import json, urllib.request, time
COMFYUI_URL = "http://127.0.0.1:8188"
BEST_MODEL = "SDXL 1.0\\9527DetailRealistic_v30.safetensors"
NEGATIVE_PROMPT = "(worst quality, low quality:1.4), deformed, distorted, disfigured, bad anatomy, bad proportions, ugly, noisy, blurry, low contrast, watermark, text, signature, cartoon, anime, 3d, painting, drawing, illustration, western features, blue eyes, blonde hair, extra fingers, malformed hands, missing limbs, floating limbs, disconnected limbs, nsfw, nude, naked"
SCENES = [
    {"id": "01", "name": "清晨孕吐", "seed": 18001, "width": 832, "height": 1216, "prompt": "(masterpiece, best quality, ultra-detailed:1.3), beautiful chinese woman kneeling in bathroom, morning sickness, pregnant, holding stomach, distressed expression, early morning light, photorealistic, 8k, medium shot", "output_prefix": "Drama_EP16_01_Morning_Sickness_"},
    {"id": "02", "name": "心疼拍背", "seed": 18002, "width": 1216, "height": 832, "prompt": "(masterpiece, best quality, ultra-detailed:1.3), handsome chinese man kneeling beside woman in bathroom, comforting her, gentle expression, caring gesture, bedroom background, soft lighting, photorealistic, 8k, medium shot", "output_prefix": "Drama_EP16_02_Comforting_Wife_"},
    {"id": "03", "name": "取消会议", "seed": 18003, "width": 1216, "height": 832, "prompt": "(masterpiece, best quality, ultra-detailed:1.3), handsome chinese man in office, talking to secretary, serious expression, luxury office interior, business attire, professional setting, photorealistic, 8k, medium shot", "output_prefix": "Drama_EP16_03_Cancel_Meeting_"},
    {"id": "04", "name": "回家陪伴", "seed": 18004, "width": 1216, "height": 832, "prompt": "(masterpiece, best quality, ultra-detailed:1.3), couple sitting on sofa at home, man holding woman's hand, pregnant woman resting, warm home interior, afternoon light, photorealistic, 8k, medium shot", "output_prefix": "Drama_EP16_04_Home_Together_"},
    {"id": "05", "name": "学做酸梅汤", "seed": 18005, "width": 1216, "height": 832, "prompt": "(masterpiece, best quality, ultra-detailed:1.3), handsome chinese man in kitchen, cooking, looking at phone recipe, focused expression, modern kitchen, apron, photorealistic, 8k, medium shot", "output_prefix": "Drama_EP16_05_Cooking_Learning_"},
    {"id": "06", "name": "品尝酸梅汤", "seed": 18006, "width": 832, "height": 1216, "prompt": "(masterpiece, best quality, ultra-detailed:1.3), beautiful pregnant chinese woman drinking soup, happy surprised expression, holding glass, home interior, soft lighting, photorealistic, 8k, close-up", "output_prefix": "Drama_EP16_06_Tasting_Soup_"},
    {"id": "07", "name": "真情告白", "seed": 18007, "width": 832, "height": 1216, "prompt": "(masterpiece, best quality, ultra-detailed:1.3), handsome chinese man holding woman's face, looking into her eyes, emotional expression, intimate moment, soft lighting, photorealistic, 8k, close-up portrait", "output_prefix": "Drama_EP16_07_Emotional_Confession_"},
    {"id": "08", "name": "胎动惊喜", "seed": 18008, "width": 1216, "height": 832, "prompt": "(masterpiece, best quality, ultra-detailed:1.3), couple lying in bed at night, man's hand on woman's pregnant belly, both smiling, moonlight through window, intimate moment, photorealistic, 8k, medium shot", "output_prefix": "Drama_EP16_08_Baby_Kick_"}
]
def submit_prompt(scene):
    prompt_data = {"prompt": {"3": {"class_type": "KSampler", "inputs": {"cfg": 7.0, "denoise": 1, "latent_image": ["5", 0], "model": ["4", 0], "negative": ["7", 0], "positive": ["6", 0], "sampler_name": "dpmpp_2m", "scheduler": "karras", "seed": scene["seed"], "steps": 30}}, "4": {"class_type": "CheckpointLoaderSimple", "inputs": {"ckpt_name": BEST_MODEL}}, "5": {"class_type": "EmptyLatentImage", "inputs": {"batch_size": 1, "height": scene["height"], "width": scene["width"]}}, "6": {"class_type": "CLIPTextEncode", "inputs": {"clip": ["4", 1], "text": scene["prompt"]}}, "7": {"class_type": "CLIPTextEncode", "inputs": {"clip": ["4", 1], "text": NEGATIVE_PROMPT}}, "8": {"class_type": "VAEDecode", "inputs": {"samples": ["3", 0], "vae": ["4", 2]}}, "9": {"class_type": "SaveImage", "inputs": {"filename_prefix": scene["output_prefix"], "images": ["8", 0]}}}}
    try:
        req = urllib.request.Request(f'{COMFYUI_URL}/prompt', data=json.dumps(prompt_data).encode('utf-8'), headers={'Content-Type': 'application/json'}, method='POST')
        with urllib.request.urlopen(req, timeout=10) as response:
            result = json.loads(response.read().decode('utf-8'))
            return True, result.get('prompt_id', 'unknown')
    except Exception as e:
        return False, str(e)
def main():
    print("=" * 70); print("🎬 短剧《雨夜撞上陆总后》第二季 第十六集 - 场景图生成"); print("=" * 70)
    print(f"\n📦 使用模型:{BEST_MODEL}"); print(f"📊 场景数量:{len(SCENES)} 个"); print("=" * 70)
    print("\n📡 检查 ComfyUI 连接...")
    try:
        req = urllib.request.Request(f'{COMFYUI_URL}/queue', method='GET')
        with urllib.request.urlopen(req, timeout=5) as response:
            queue = json.loads(response.read().decode('utf-8'))
            print(f"✅ ComfyUI 连接成功"); print(f"   当前队列:{len(queue.get('queue_running', []))} 运行中,{len(queue.get('queue_pending', []))} 等待中")
    except Exception as e:
        print(f"❌ 无法连接 ComfyUI: {e}"); return
    print("\n" + "=" * 70); print("🚀 开始提交生成任务..."); print("=" * 70)
    success_count = 0
    for i, scene in enumerate(SCENES, 1):
        print(f"\n[{i}/{len(SCENES)}] {scene['name']}"); success, result = submit_prompt(scene)
        if success: print(f"   ✅ 提交成功 (Prompt ID: {result})"); success_count += 1
        else: print(f"   ❌ 提交失败:{result}"); time.sleep(0.5)
    print("\n" + "=" * 70); print("📊 生成结果"); print("=" * 70); print(f"✅ 成功:{success_count}/{len(SCENES)}")
    if success_count > 0: print(f"\n💾 图片将保存到:ComfyUI/output/\n   文件名前缀:Drama_EP16_XX_场景名_\n\n🌐 查看进度:http://127.0.0.1:8188")
    print("\n" + "=" * 70); print("\n📋 场景清单:"); print("-" * 70)
    for scene in SCENES: print(f"  {scene['id']}. {scene['name']} - {scene['output_prefix']}")
    print("-" * 70)
if __name__ == "__main__":
    main()