# -*- coding: utf-8 -*-
"""第1步：生成5份简单易画的线条图（白描/涂色稿），无文字、无阴影、纯白底"""
import json, os, 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']
OUT = '/data/www/files/pandaReadArt/lineart5'
os.makedirs(OUT, exist_ok=True)

NOTEXT = ("Absolutely NO TEXT anywhere. No Chinese characters, no letters, no words, no numbers, no calligraphy, "
          "no captions, no titles, no logos, no watermarks, no signature, no seals or stamps. ")

LINE = (" Simple clean black-and-white line drawing for a children's coloring book page. Uniform bold black "
        "outlines on pure white background. FLAT 2D only: absolutely NO shading, NO hatching, NO cross-hatching, "
        "NO grey tones, NO gradients, NO shadows, NO colour fills, NO texture. Draw only the essential outlines "
        "using basic easy shapes (circles, triangles, rectangles, simple curves) — very few details, minimal line "
        "count, easy for a 9-year-old to copy by hand. Big clear shapes, generous white space, centered "
        "composition, wide margins. ")

T = {}

T['01_红船启航'] = NOTEXT + (
 " Line drawing of a simple wooden boat with a curved traditional Chinese roof and a small triangular flag on a "
 "pole at its bow, floating on water. Three wavy lines under the boat to show the lake surface, two lotus leaves "
 "and one lotus flower beside the boat, one round sun with short rays in the upper corner, two simple cloud "
 "shapes in the sky. Every element drawn with single clean outlines and nothing else."
) + LINE

T['02_一颗红星一本书'] = NOTEXT + (
 " Line drawing of one big open book with page lines at the bottom centre, and above it one large five-pointed "
 "star with a short flowing ribbon beneath it; two simple leaf shapes and one small sprouting plant beside the "
 "book. Everything drawn with single clean outlines and nothing else."
) + LINE

T['03_熊猫陪我读红色故事'] = NOTEXT + (
 " Line drawing of a cute chubby panda sitting on the ground holding an open book in its paws, and beside the "
 "panda a small smiling child sitting cross-legged with a neckerchief triangle on the chest and also holding a "
 "small book. Two simple bamboo stalks with a few leaves behind them. Every element drawn with single clean "
 "outlines and nothing else."
) + LINE

T['04_雪山上的红旗'] = NOTEXT + (
 " Line drawing of two big triangular snow mountains with a wavy snow line across the middle of each, and a red-"
 "flag-shaped triangle flag on a pole planted on the peak of the taller mountain; a curved dotted trail of "
 "footprints winding up the slope, three simple pine-tree triangles in the lower corner and one round sun in the "
 "sky. Every element drawn with single clean outlines and nothing else."
) + LINE

T['05_宝塔山下的读书声'] = NOTEXT + (
 " Line drawing of a simple nine-tier pagoda standing on a hill top, three arched cave-dwelling doorways carved in "
 "a stepped hillside below it, a small smiling child standing in front of the caves holding up an open book, a "
 "wavy river line across the lower part of the scene, one round sun and two simple cloud shapes in the sky. "
 "Every element drawn with single clean outlines and nothing else."
) + LINE


def gen(name, prompt, retries=2):
    for a in range(retries + 1):
        try:
            r = requests.post(f"{BASE}/images/generations",
                headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
                json={"model": MODEL, "prompt": prompt, "size": "2048x2048", "n": 1, "watermark": False},
                timeout=240)
            d = r.json()
            if d.get('data'):
                img = requests.get(d['data'][0]['url'], timeout=180).content
                p = os.path.join(OUT, f"{name}.jpg")
                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)[:200]}", flush=True)
        except Exception as e:
            print(f"EXC {name} #{a}: {e}", flush=True)
        time.sleep(5)
    return None


if __name__ == '__main__':
    with ThreadPoolExecutor(max_workers=5) as ex:
        print(list(ex.map(lambda kv: gen(*kv), T.items())))
