# -*- coding: utf-8 -*-
import json, os, re, subprocess, time
D='/home/zyw/.local/bin/dreamina'
BASE='/home/zyw/Downloads/dl-hub/25-软件测试方法和技术第4版OCR整理/课件成品-PPT'
OUT=os.path.join(BASE,'assets','ch1')
ENV={k:v for k,v in os.environ.items() if k.lower() not in ('all_proxy','http_proxy','https_proxy','no_proxy')}
JOBS=[
 ('case-medical','教学插画：医院放射治疗室的直线加速器治疗机，治疗头对准治疗床，墙面有辐射警示标志，控制台屏幕显示异常升高的剂量曲线与红色警示，冷色调，庄重克制，画面中没有人物、没有文字'),
 ('case-xueshi','教学插画：两张并排摆放的 CD 光盘盒与一张裸露光盘，塑料壳有反光，封面为抽象的机甲与像素风插画，放在木桌上，暖色怀旧色调，90 年代质感，画面中没有可读文字与品牌标识'),
]
def sh(a,t=300):
    p=subprocess.run([D]+a,capture_output=True,text=True,env=ENV,timeout=t); return (p.stdout or '')+(p.stderr or '')
for name,prompt in JOBS:
    out=sh(['text2image','--prompt='+prompt,'--resolution_type=2k','--ratio=16:9','--model_version=5.0','--generate_num=1'])
    m=re.search(r'"submit_id"\s*:\s*"([^"]+)"',out)
    if not m: print('[fail]',name,out[:200],flush=True); continue
    sid=m.group(1); print('[submit]',name,sid,flush=True)
    seen=set(os.listdir(OUT)); got=None
    for i in range(40):
        time.sleep(12)
        sh(['query_result','--submit_id='+sid,'--download_dir='+OUT],180)
        new=[f for f in os.listdir(OUT) if f not in seen and f.lower().endswith(('.png','.jpg','.jpeg','.webp'))]
        if new: got=os.path.join(OUT,new[0]); break
    if got:
        os.replace(got, os.path.join(OUT,name+'.png')); print('[done]',name,flush=True)
    else: print('[timeout]',name,sid,flush=True)
print('[credits]', re.search(r'"total_credit"\s*:\s*(\d+)', sh(['user_credit'],120)).group(1), flush=True)
