# -*- coding: utf-8 -*-
"""3 份重制 v4 —— 修 1～6，顺带优化 7～11
1 标题带去掉（由 A4 合成脚本处理，见 export_a4.py）
2 B：方糖改为"从倒掉的饮料瓶里滑出、被孩子用手掌推开"，不再当静物摆着
3 C：接水处改为"立式直饮水机"（方机体＋按键面板＋内凹接水槽＋沥水格栅＋顶部倒扣大水桶），杜绝"洗手池喝自来水"误读
4 A：孩子杯中不再画热气（热气只出现在水壶上），杜绝"鼻涕"误读
5 手：改为"手掌＋拇指＋并拢四指"的正常手形，绝非连指手套
6 A：去掉太阳，改为阴晴一致的"雨后山间"，雨天与云雾并存不再矛盾
7 趣味性：加拟人小水滴（站立在地面/石上，不悬浮）、小鸟、小猫、书包挂小水壶、水壶贴纸图案
8 色彩统一：水用柔和青蓝而非荧光蓝；云雨去灰暗
9 手绘感：线条轻重变化、断笔、干笔飞白、纸纹
10 结构：透视统一到同一消失点；C 手臂与肩连接明确；A 纪念碑移离水面
11 覆盖：A 桌上三只小杯、C 孩子手里第二只杯＋水壶，补上"足量规律饮水"
"""
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/final2/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 signboard, label, screen, sticker and printed surface is "
          "completely blank. No numbers on any cup, bottle or sticker — 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: ink-and-brush outlines with clearly "
        "VARIED line weight (some strokes thicker, some thinner, a few broken or dry-brush edges), layered "
        "transparent watercolour washes, soft blooms, a little visible watercolour paper grain and texture, a warm "
        "harmonious palette with a few strong accent colours, clear readable silhouettes, soft natural daylight. "
        "NOT flat vector art, NOT smooth computer colouring, NOT a colouring-book fill, NOT 3D render, NOT a "
        "photograph. ")

SAFE = (" Hands are drawn in a simple but ANATOMICALLY CLEAR way — a normal rounded palm with a visible thumb and "
        "four fingers held loosely together — so they clearly read as real hands and never as mittens or gloves; "
        "every glass, cup or bottle is firmly held by such a hand; no missing hands, no extra limbs, no deformed "
        "fingers. No steam or vapour rises from any child's cup and nothing white touches a child's face or mouth. "
        "Nothing floats in the air: no decorative sparkles, no floating droplets; every drop falls or splashes from "
        "a clearly drawn source, and every object rests on a surface or is fixed to a wall. Nothing passes through "
        "anything else and the perspective of ground, walls, furniture and buildings follows ONE consistent "
        "vanishing point. 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, on a fresh day just after rain, "
 "showing where a cup of drinking water comes from. The sky is evenly overcast after rain: NO sun anywhere — "
 "instead a fat pale rain cloud with short straight rain lines at the upper left over the green mountain, and two "
 "soft pale-grey clouds; thin mist bands cling to the mountainside. "
 "Left and centre, a pure natural water path: the rain feeds a small mountain stream that tumbles over three round "
 "stones down the green slope, and the stream widens into a big river with long ripple lines that runs across the "
 "picture and leaves the frame at the right edge; one small wooden boat with a boatman floats on the river, reeds "
 "grow on the near bank, and three pine trees stand on the mountain. "
 "Right foreground, standing on the stone-paved riverbank plaza and clearly separate from the water: TWO children "
 "drinking side by side at the same time — a girl with a ponytail in a light blue shirt, and beside her a boy with "
 "a short bowl haircut in a warm yellow shirt; both have round faces, dot eyes and small smiles, wear red "
 "neckerchiefs, and each holds a plain glass of clear water up to the mouth with BOTH hands, taking a small sip; "
 "NO steam at their glasses — the water has already cooled; the girl's glass carries three plain short tick marks; "
 "a school bag with a small water bottle hooked on it rests on the ground at their feet. "
 "Right middle ground, on the plaza: a low white house wall with one square window and a wooden door; a small tap "
 "with a red handle is FIXED ON that wall with a wooden bucket standing on the ground directly under it; a "
 "watering can stands beside a flower bed with three flowers. In front of the wall a low table holds a white "
 "porcelain cooling jar with a lid and a spout, plus a row of THREE small cups filled with clear water — three "
 "cups that mark drinking water several times a day; next to the table a small stove carries a metal kettle whose "
 "spout sends up a curly steam line, the ONLY steam in the picture. "
 "Along the near riverbank: three cheerful little cartoon water-drop characters with dot eyes and tiny smiles, each "
 "resting ON the grass or on a bank stone, drawn as friendly mascots. "
 "Background: a tall plain stone monument standing well back on the wide stepped plaza with three small lamp posts, "
 "a big mountain with simple ridge lines and three pine shapes behind the stream, two soft clouds and three small "
 "birds. Grass tufts and two small flowers along the bottom edge. "
 "All ground lines, the house wall, the table and the plaza steps share ONE consistent vanishing point. "
 "Colour: soft clear cyan-blue water, fresh green mountain, warm sandstone plaza, white walls, cream steam, the two "
 "red neckerchiefs and the red tap handle as the strong accents; the rain cloud in pale blue-grey, never muddy. "
) + SAFE

# ------------------------------------------------ B 白开水最好喝
T['B_白开水最好喝'] = NOTEXT + ART + (
 " An old riverside trading-street scene in eastern Sichuan about a child choosing plain water and pushing a sweet "
 "bottled drink away. "
 "Foreground centre: TWO children. The NEARER one, a boy with a short bowl haircut in a pale cream shirt, has "
 "turned slightly away from the shop side; his arm is stretched out with a flat open palm pressing against a "
 "small heap of sugar lumps, clearly PUSHING that heap away toward the outer edge of the table, with three short "
 "curved motion lines beside his hand, while his other hand holds up his own tall glass of clear water. The "
 "further child, a girl with two braids in a sky blue shirt, holds her tall glass of clear water with both hands "
 "and takes a small sip. Both have round faces, dot eyes and small smiles and wear red neckerchiefs; NO steam at "
 "either glass. "
 "Foreground left: at the outer edge of a wooden table lies ONE transparent bottle tipped over on its side with a "
 "straw in its neck, clearly see-through and packed inside with many SMALL cube-shaped sugar lumps, each only the "
 "size of a fingertip and clearly smaller than the bottle mouth; a short trail of about ten such small sugar lumps "
 "has slid out of the bottle mouth and is being pushed toward the table edge, spilling off it, with three single "
 "lumps already on the ground below — the sugar is clearly being got rid of, not being added to anything. "
 "Foreground right: a small wooden table holding a white porcelain cooling jar, which has a lid and a spout, and a "
 "round plate with one whole fruit; a bamboo chair stands behind it, and a small orange cat sits on a wooden bench "
 "nearby. "
 "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 small tap with a red "
 "handle is FIXED ON that wall with a wooden bucket standing on the ground under it; a low stove beside it carries "
 "a kettle whose spout sends up one curly upward steam line; a big clay rain-water jar with a wooden lid and a "
 "bamboo dipper stands against the wall; a sparrow perches on the 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, small white sugar lumps, water painted in a SOFT "
 "muted cyan-blue (not neon) so it sits harmoniously with the warm surroundings, 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 safe water at school and not wasting it. "
 "Foreground centre: a FLOOR-STANDING DRINKING-WATER DISPENSER, unmistakable and clearly NOT a wash basin: a tall "
 "rectangular machine cabinet with a flat top, standing on the corridor floor; on top of the cabinet a large "
 "transparent water bottle sits UPSIDE DOWN in its socket; the front of the cabinet has a control panel with two "
 "round press-buttons above a deep RECESSED alcove; inside the alcove THREE spouts point downwards over a "
 "drip-tray grille at the bottom of the alcove; the whole boxy cabinet body is fully drawn, and a drain pipe runs "
 "from the cabinet base to the corridor floor channel. "
 "Three children use it in turn, one after another. Left: a girl with two braids in a sky blue shirt holds a blue "
 "water bottle with plain tick marks under the left spout and fills it, a clear stream of water falling into the "
 "bottle with small spray droplets at the bottle mouth. 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, with a "
 "second cup waiting on the drip tray in front of him. Right: a boy with flat short hair in a white shirt, his arm "
 "clearly attached at the shoulder and reaching up to the button panel, presses the button and has just stopped the "
 "water, his other hand holding a green water bottle at his side. All three have round faces, dot eyes, small "
 "smiles and red neckerchiefs, with arms and legs drawn clearly connected to their bodies; each water bottle has "
 "plain tick marks and its own simple picture of a star, a fish or a leaf on it (no text, no numbers). "
 "Middle ground: the corridor floor with long perspective lines converging on ONE vanishing point, the heavy "
 "dispenser standing on that floor; 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; a sparrow perched on the railing. "
 "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, water in soft clear cyan-blue, "
 "the three water bottles in bright red, blue and green as the accents, and the children's clothes in saturated "
 "yellow and blue so the main figures stand out from the pale background. "
) + 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())))
