# -*- coding: utf-8 -*-
"""生成两个小学四年级绘画主题的创意参考图（儿童水彩+彩铅风格，无任何文字）"""
import json, os, re, time, base64, requests
from concurrent.futures import ThreadPoolExecutor

CFG = json.load(open('/data/www/files/LhyjdesignPro/config.json'))
API_KEY = CFG['api_key']
BASE = CFG['base_url']
MODEL = CFG['models']['image_gen']            # doubao-seedream-5-0-260128
OUT = '/data/www/files/pandaReadArt'
os.makedirs(OUT, exist_ok=True)

NOTEXT = ("Absolutely NO TEXT anywhere in the image. 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, no readable marks of any kind. Pure illustration only. ")

STYLE = (" Children's picture-book illustration style, hand-painted watercolor washed over soft colored-pencil "
         "outlines, vibrant yet gentle palette, textured paper grain, warm and cheerful, dreamy glowing light, "
         "rich detail, wholesome and positive, suitable for a 9-year-old primary school art project. "
         "Square-ish wide composition, clear main subject in the center, no border, no frame.")

T1 = NOTEXT + (
 " A heartwarming storybook scene on a vast grassland at night under a starry sky. In the center, an old "
 "tall wooden post holds a vintage brass oil lantern with a small red star painted on it, glowing warm golden "
 "light. Below the lantern, an open hardcover book lies on the grass, and brilliant golden light pours out of the "
 "open pages like a river, forming a winding glowing road that curves away into the far distance toward soft "
 "silhouettes of snow-capped mountains. Two children sit side by side reading that same glowing book: on the left "
 "a little girl of about nine years old wearing a white shirt and a bright red neckerchief, long black hair, "
 "smiling with wonder; on the right a small boy soldier seen from behind in a faded grey-green uniform and a cap "
 "with a red star, a cloth shoulder bag beside him — they are reading together across time. Around them: "
 "fireflies, small wildflowers, tall grass bending in the breeze, a few red silk ribbons drifting in the air "
 "like gentle flags, distant tiny tents and a long stream of tiny lantern lights on the horizon. Deep blue-violet "
 "night sky with a river of stars, warm amber lantern glow, strong warm-cool contrast."
) + STYLE

T2 = NOTEXT + (
 " An adorable giant panda postman inside a cozy bamboo-forest book hut, warm afternoon sunlight filtering "
 "through green bamboo leaves. The fluffy black-and-white panda wears a bright red neckerchief and holds a "
 "bamboo-leaf parcel tied with red string in one paw, a small red satchel across its body. Around the panda, "
 "bamboo shelves are packed with colorful picture books, and a bamboo table is piled with open books. Two happy "
 "schoolchildren, a girl with two braids and a boy, sit on a woven bamboo mat reading excitedly, pointing at a "
 "page. Above them float three soft dreamy cloud bubbles that show miniature historical picture-book scenes: a "
 "suspension bridge with iron chains over a rushing river, a snowy mountain with tiny marching figures, and a "
 "yellow-earth cave dwelling beside a tall pagoda hill. Letters folded from bamboo leaves fly out through the "
 "window like little paper planes, carried along a flowing red ribbon that loops through the whole scene. "
 "Fresh bamboo-green, warm orange sunlight, accents of bright Chinese red. Joyful, imaginative, full of "
 "storytelling."
) + STYLE

PROMPTS = {'T1_马灯亮处书页成路': T1, 'T2_熊猫竹屋的红色信箱': T2}


def gen(name, prompt, retries=2):
    for attempt 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": "2304x1728", "n": 1,
                      "watermark": False}, timeout=180)
            d = r.json()
            if d.get('data'):
                url = d['data'][0]['url']
                img = requests.get(url, timeout=120).content
                path = os.path.join(OUT, f"{name}.jpg")
                open(path, 'wb').write(img)
                print(f"OK  {name}  {len(img)//1024}KB  {path}")
                return path
            print(f"ERR {name} attempt{attempt}: {json.dumps(d, ensure_ascii=False)[:300]}")
        except Exception as e:
            print(f"EXC {name} attempt{attempt}: {e}")
        time.sleep(5)
    return None


if __name__ == '__main__':
    with ThreadPoolExecutor(max_workers=2) as ex:
        results = list(ex.map(lambda kv: gen(*kv), PROMPTS.items()))
    print("DONE", results)
