# -*- coding: utf-8 -*-
"""彩色版式 -> 线条图（白底黑线，构图一致）strength=0.55"""
import base64, glob, json, os, sys, time, requests
from concurrent.futures import ThreadPoolExecutor

CFG = json.load(open('/data/www/files/LhyjdesignPro/config.json'))
API_KEY, BASE, MODEL = CFG['api_key'], CFG['base_url'], CFG['models']['image_gen']
SRC = '/data/www/files/heibanbao3in1/rich'
OUT = '/data/www/files/heibanbao3in1/line_rich'
os.makedirs(OUT, exist_ok=True)

PROMPT = (
 "Convert this colourful poster layout into a clean BLACK-AND-WHITE LINE DRAWING on PURE WHITE paper — a "
 "tracing outline that a pupil can copy. "
 "Keep EXACTLY the same layout: the same positions, sizes, proportions, shapes and number of every single "
 "element. Do NOT add, remove, move, enlarge or redraw anything. "
 "Remove all colour completely: the paper stays COMPLETELY PURE WHITE, and every coloured shape becomes a "
 "plain black outline with a PURE WHITE interior. Every outline line is ONE single weight-consistent colour: "
 "solid black. NO colour, NO grey, NO dark blocks, NO coloured outlines, NO offset double lines. "
 "All panel frames and text panels stay as closed black outlines with pure white empty interiors. "
 "MODERATE level of interior detail — enough lines that a 9-10 year old can copy it, but ABSOLUTELY NO "
 "cross-hatching, NO stippling, NO shading, NO gradients, NO tonal patches, NO texture, NO drop shadows. "
 "Simple expressive faces (dot eyes, small smile). "
 "ABSOLUTELY NO TEXT ANYWHERE: no Chinese characters, no letters, no words, no numbers, no digits, no "
 "calligraphy, no captions, no title, no logo, no watermark, no signature, no seal. Every signboard, sign "
 "face, screen, banner, book and panel must stay blank. "
 "Every object rests on or touches something solid — nothing floats in the air unsupported. "
 "Wide horizontal A4 composition, pure white margins."
)


def convert(path):
    name = os.path.basename(path)
    b64 = base64.b64encode(open(path, 'rb').read()).decode()
    for a in range(4):
        try:
            r = requests.post(f"{BASE}/images/generations",
                headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
                json={"model": MODEL, "prompt": PROMPT, "size": "2896x2048", "n": 1, "watermark": False,
                      "image": f"data:image/jpeg;base64,{b64}", "strength": 0.55}, timeout=300)
            d = r.json()
            if d.get('data'):
                img = requests.get(d['data'][0]['url'], timeout=180).content
                p = os.path.join(OUT, name)
                open(p, 'wb').write(img)
                print(f"OK  {name}  {len(img)//1024}KB", flush=True)
                return p
            print(f"ERR {name} #{a}: {json.dumps(d, ensure_ascii=False)[:260]}", flush=True)
        except Exception as e:
            print(f"EXC {name} #{a}: {e}", flush=True)
        time.sleep(8)
    return None


if __name__ == '__main__':
    files = sorted(glob.glob(os.path.join(SRC, '*.jpg')))
    if len(sys.argv) > 1:
        files = [f for f in files if any(n in os.path.basename(f) for n in sys.argv[1:])]
    with ThreadPoolExecutor(max_workers=4) as ex:
        list(ex.map(convert, files))
