# -*- coding: utf-8 -*-
"""重做 3 份 —— 直接生成"真正的水彩插画"（不再走线稿填色产线）
针对体检出的 5 个病灶逐条写进提示词：
  1 手部畸形/缺失 → 手画成"连指手套状"、明确"手握住杯子"、禁多余肢体
  2 线条机械无手绘温度 → 水彩+彩铅手绘笔触、干笔边、纸纹
  3 上色偏平 → 层次化透明罩染、强而不脏的对比、几处强调色
  4 结构逻辑/比例违和 → 元素数降到 ~16、主体放大、场景连贯（不再拼接互不相干的场景）
  5 元素重复 → 三个/两个孩子发型与衣服各不相同
横版 A4 比例 2896x2048。
"""
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/waterHealthArt/final/illustration'
os.makedirs(OUT, exist_ok=True)
SIZE = '2896x2048'

NOTEXT = ("No text anywhere: no Chinese characters, no letters, no numbers, no calligraphy, no labels, no captions, "
          "no logos, no watermark, no signature. Every screen, signboard, label and printed surface is completely "
          "blank. No numbers on any cup or bottle — measuring marks are plain short tick lines only. ")

ART = (" Hand-painted children's picture-book illustration in watercolour with coloured-pencil accents, drawn in the "
        "warm sincere style of a gifted ten-year-old's award-winning painting: confident varied brush lines with "
        "thicker and thinner strokes, layered transparent watercolour washes, soft blooms and dry-brush edges, a "
        "little visible paper grain, a warm lively harmonious palette with a few strong accent colours, clear "
        "readable silhouettes, soft natural daylight. NOT flat vector art, NOT computer flat colouring, NOT a "
        "colouring-book fill, NOT 3D render, NOT a photograph. ")

SAFE = (" Rounded simple mitten-shaped hands with no separated fingers; every glass, cup or bottle is firmly held and "
        "supported by a clearly drawn hand — no missing hands, no extra limbs, no deformed fingers. Nothing floats "
        "in the air: every water drop falls or splashes from a clearly drawn source, and every object rests on a "
        "surface. Warm, healthy, wholesome and suitable for primary-school children. ")

T = {}

# ------------------------------------------------ A 饮水思源——一滴水的旅行
T['A_饮水思源_一滴水的旅行'] = NOTEXT + ART + (
 " A drinking-water education painting set in a riverside town in eastern Sichuan, showing where a cup of drinking "
 "water comes from. "
 "Foreground right: ONE girl with a ponytail, a round face, dot eyes and a small smile, in a light blue shirt and a "
 "red neckerchief, standing and holding a tall clear glass tumbler up to her mouth with BOTH hands as she takes a "
 "small sip; a thin wisp of steam rises from the glass and the glass carries three plain short tick marks; she "
 "stands on a stone-paved plaza with grass tufts and two small flowers along the bottom edge. "
 "Middle ground: one long winding S-shaped ribbon of clear blue water flows down through the picture from the upper "
 "left to her glass; along that ribbon, from far to near — a small mountain stream tumbling over three round "
 "stones, then a wide river with ripple lines carrying one small wooden boat with a boatman, reeds on the bank, and "
 "then the ribbon runs behind a low white house wall with one square window. Beside that wall stand a small tap "
 "with a red handle, a wooden bucket catching drips, and a watering can next to a flower bed with three flowers; in "
 "front of the wall a white porcelain cooling jar with a lid and a spout rests on a low table, and a kettle on a "
 "small stove sends up a curly steam line. "
 "Background: a tall plain stone monument standing on a wide stepped plaza with three small lamp posts on the right "
 "horizon, a long river-bank line, a big mountain with simple ridge lines and three pine shapes on the left, a round "
 "sun with short rays, two soft clouds and three small birds. "
 "Colour: clear blue water, fresh green mountain, warm sandstone plaza, white walls, cream steam, the girl's "
 "neckerchief bright red as the one strong accent. "
) + SAFE

# ------------------------------------------------ B 白开水最好喝
T['B_白开水最好喝'] = NOTEXT + ART + (
 " An old riverside trading-street scene in eastern Sichuan about choosing plain water instead of a sweet bottled "
 "drink. "
 "Foreground centre: TWO children drinking side by side — the nearer a boy with a short bowl haircut, the further a "
 "girl with two braids — both with round faces, dot eyes and small smiles, in shirts and red neckerchiefs; each "
 "holds a tall plain glass of clear water up to the mouth with BOTH hands and takes a small sip, and three small "
 "sparkle shapes are drawn beside their glasses. "
 "Foreground left: a wooden table carrying one tall transparent bottle lying tipped over on its side with a straw in "
 "its neck, packed inside with stacked cube-shaped sugar lumps, and a big heap of about twenty cube-shaped sugar "
 "lumps spilling out of it into a small white hill on the table top; two loose lumps lie on the ground below. "
 "Foreground right: a small wooden table with a white porcelain cooling jar, which has a lid and a spout, and a round "
 "plate holding one whole fruit; a bamboo chair stands behind it. "
 "Middle ground: a stone-paved street with joint lines; on the left the tiled eaves and wooden wall of an old house "
 "with rows of roof tiles and three round red lanterns hanging under the eave; a big clay rain-water jar with a "
 "wooden lid and a bamboo dipper standing against the wall; a wooden bench. "
 "Background: a wide river with ripple lines and two wooden boats with masts, two thin bands of morning mist, a "
 "distant hill outline, one leafy tree on the far bank and three small birds. "
 "Colour: warm morning light, honey-brown wood, warm grey stone, white sugar lumps, clear cyan-blue water, three red "
 "lanterns and two red neckerchiefs as the strong accents. "
) + SAFE

# ------------------------------------------------ C 接一杯 喝一口 关紧它
T['C_接一杯_喝一口_关紧它'] = NOTEXT + ART + (
 " A wide primary-school corridor scene about drinking water at school and not wasting it. "
 "Foreground: three children along a long straight drinking-water station with three separate wall taps. From left "
 "to right — a girl with two braids in a sky blue shirt holds a blue water bottle with plain tick marks under the "
 "first tap and fills it, a clear stream of water running into the bottle with small spray droplets; in the middle, "
 "drawn biggest and nearest, a boy with a short bowl haircut in a bright yellow shirt tips a small cup up to his "
 "mouth with BOTH hands and takes a small sip; on the right a boy with flat short hair in a white shirt reaches up "
 "with one hand and turns the third tap shut with no water running, holding a green water bottle in his other hand. "
 "All three have round faces, dot eyes, small smiles and red neckerchiefs; each water bottle has plain tick marks "
 "and its own stripe pattern. "
 "Middle ground: the corridor floor with long perspective lines and a corridor railing with vertical bars; outside "
 "the corridor TWO two-storey school teaching buildings with rows of square windows; a big plastic bucket catching "
 "rain water under the eave; a flower bed with three flowers. "
 "Background: a red running-track arc with white lane lines, a basketball hoop with a backboard in the far left "
 "distance, two leafy trees and one bamboo clump, a long mountain ridge, a round sun with short rays, three soft "
 "clouds and four small birds. "
 "Colour: bright daylight, warm cream corridor, brick-red track, fresh green court, clear cyan-blue water, the three "
 "water bottles in bright red, blue and green as the accents. "
) + SAFE


def gen(name, prompt, retries=3):
    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": SIZE, "n": 1, "watermark": False},
                timeout=300)
            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)[:220]}", flush=True)
        except Exception as e:
            print(f"EXC {name} #{a}: {e}", flush=True)
        time.sleep(6)
    return None


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