# -*- coding: utf-8 -*-
"""v7：修 B 的手势语义 + C 的断臂
B：删掉"伸手推向方糖"的动作（会被读成"去接糖"），改为——孩子背对甜饮料，用自家水壶给自己倒白开水；
   甜饮料瓶侧倒在远处柜台上、瓶口堆出一小堆方糖，没有任何手去碰它。
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'
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, layered transparent watercolour washes, soft blooms, visible watercolour paper grain, 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. ")

HANDS = (" DRAWING THE HANDS IS IMPORTANT: every hand is drawn 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 object being held, "
         "each finger its own line with a small visible gap beside it, plus the THUMB drawn as one separate short "
         "line, and a simple rounded palm behind. Never a mitten, never a glove, never a solid blob without finger "
         "lines. Every arm is drawn as ONE continuous connected shape running from the shoulder to the hand — no arm "
         "may be detached from its body. ")

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['B_白开水最好喝'] = NOTEXT + ART + (
 " An old riverside trading-street scene in eastern Sichuan showing two children drinking their OWN plain water "
 "while a sweet bottled drink is left untouched on the shop counter. There are exactly TWO children in the whole "
 "picture and NO other people, no extra arms and no half-visible bodies. "
 "Foreground centre-right: the two children stand with their bodies and faces turned AWAY from the shop counter and "
 "toward the viewer's right. The nearer child, a boy with a short bowl haircut in a pale cream shirt, holds his own "
 "small stainless-steel thermos flask in one hand and pours a thin stream of clear water from it into his tall "
 "glass, which stands on a small wooden table in front of him with the four fingers of his hand drawn as four "
 "separate short parallel curved lines across the flask; he smiles as he pours. 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, her finger "
 "lines clearly drawn. Both have round faces, dot eyes and small smiles, wear red neckerchiefs; NO steam at either "
 "glass; the water in both glasses is colourless and clear. "
 "Foreground FAR LEFT, well away from the children and clearly abandoned: a small shop counter of plain wood, and "
 "on it ONE transparent plastic soda bottle lying 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 lumps has slid out of the bottle mouth and lies in a "
 "little heap on the counter beside it, and two single lumps have rolled onto the ground below. No hand touches the "
 "bottle or that heap — nobody is picking it up. "
 "Foreground right: a white porcelain cooling jar with a lid and a spout and a round plate with one whole fruit on "
 "the small wooden table; a bamboo chair behind it, and a small orange cat asleep 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 in a soft muted "
 "cyan-blue (not neon) so it sits harmoniously with the warm surroundings, the 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. There are exactly "
 "THREE children in the whole picture and NO other people, no extra arms and no half-visible bodies. "
 "Foreground centre: a FLOOR-STANDING DRINKING-WATER DISPENSER, clearly NOT a wash basin: a tall rectangular "
 "machine cabinet with a flat top standing on the corridor floor, all four sides of the cabinet drawn; on top a "
 "large transparent water bottle sits upside down in its socket; the front face carries a control panel with two "
 "round press-buttons above a deep RECESSED alcove, and INSIDE that alcove THREE spouts point downwards over a "
 "drip-tray grille at the bottom of the alcove; there are NO taps anywhere else on the machine's sides; a drain "
 "pipe runs from the cabinet base down to a floor channel. "
 "The three children use the dispenser 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 INSIDE the alcove and fills it, a clear stream of water falling "
 "into the bottle with small spray droplets at the bottle mouth; the four fingers of her hand are drawn as four "
 "separate short parallel curved lines across the bottle. MIDDLE, drawn biggest and nearest: a boy with a short "
 "bowl haircut in a bright yellow shirt drinks from a big tall wide glass tumbler held up near the mouth, the four "
 "fingers of his hand drawn as four separate short parallel curved lines across the front of the tumbler; a second "
 "small cup waits on the drip tray in front of him. RIGHT: a boy with flat short hair in a white shirt stands "
 "squarely facing the machine with both feet flat on the floor, both arms drawn as single continuous shapes from "
 "shoulder to hand — one arm reaching up to the button panel with his hand pressing the button that has just "
 "stopped the water, and his short sleeve and shoulder clearly joined to that arm; his other arm hangs naturally at "
 "his side holding a green water bottle with plain tick marks at his hip. All three children have round faces, dot "
 "eyes, small smiles and red neckerchiefs, with arms and legs clearly connected to their bodies; each bottle has a "
 "simple picture of a star, a fish or a leaf (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. The running track and playground lie far away in "
 "the background, beyond the teaching buildings. "
 "Background: a red running-track arc with white lane lines and a basketball hoop with a backboard far away beyond "
 "the buildings, 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=2) as ex:
        print(list(ex.map(lambda kv: gen(*kv), T.items())))
