# -*- coding: utf-8 -*-
"""v5：只修第 5 条（手）+ B 的"推开方糖"动作加强
手：改用儿童插画惯用手法——手握住杯子，四根手指画成横在杯身上的四道短弧线，拇指在近侧单独一道线；
    明确禁止"连指手套/手套/整块圆润色块"的画法。
"""
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'
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. ")

# ↓↓↓ 本条是 v5 的核心修点
HANDS = (" HOW TO DRAW EVERY HAND (very important): draw the hand wrapped around the glass in the classic "
         "children's-book way — the FOUR FINGERS are shown as four separate short parallel curved lines lying "
         "across the front of the glass, each finger its own line with a small gap between them, and the THUMB is "
         "drawn separately as one short line on the near side of the glass, plus a simple rounded palm shape behind "
         "the glass. Never draw a mitten, a glove, a solid rounded block, or a hand without finger lines. Draw the "
         "same clear finger lines on every hand that holds anything. ")

SAFE = (HANDS +
        " 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 unsupported 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 = {}

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, taking a small sip; NO steam at their "
 "glasses; 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; 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. "
 "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

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, turns his "
 "body and face AWAY from the sweet drink: his arm is stretched out and his flat open palm has just shoved a small "
 "heap of sugar lumps off the outer edge of the table, so that six or seven small lumps are already tumbling down "
 "through the air toward the ground below, with three short curved motion lines beside his pushing hand; his other "
 "hand holds up his own tall glass of clear water and he looks at it with a happy face. 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 PLASTIC SODA 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; the remaining short trail of small "
 "sugar lumps is sliding out of the bottle mouth toward the table edge and being pushed off; a few single lumps "
 "already lie 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 small 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

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 down to a floor channel. "
 "Three children use it in turn. 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 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 joined to his shoulder, "
 "reaching up to the button panel and pressing the button to stop the water, his other hand holding a green water "
 "bottle at his side. All three children have round faces, dot eyes, small smiles and red neckerchiefs, with arms "
 "and legs 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())))
