# -*- coding: utf-8 -*-
"""校园主题 5 份 —— 第1步：水彩插画（横版 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/campus/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. The blackboard, every signboard, notice board, duty roster, screen, "
          "sticker, poster and printed surface is completely BLANK. No numbers on any cup, bottle or ticket — "
          "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 one continuous connected shape from shoulder to hand — no detached arms. ")

SAFE = (HANDS +
        " No steam or vapour rises from any child's drinking 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; every object rests on a surface or is fixed to a wall or machine. Nothing "
        "passes through anything else, and the perspective of floor, walls, furniture and buildings follows ONE "
        "consistent vanishing point. Warm, healthy, wholesome and suitable for primary-school children. ")

T = {}

# ------------------------------------------------ 1 体育课后的第一杯水（操场）
T['1_体育课后的第一杯水'] = NOTEXT + ART + (
 " A sunny primary-school playground in eastern Sichuan just after a PE lesson. There are exactly THREE children "
 "in the picture and no other people, no extra arms and no half-visible bodies. "
 "Foreground centre: two children sitting side by side on a low bench at the edge of the playground, both with "
 "round faces, dot eyes and small smiles, in sports shirts and shorts and red neckerchiefs. The nearer boy has a "
 "short bowl haircut and a bright yellow shirt: he holds his own water bottle up near his mouth and drinks in SMALL "
 "SIPS, with four separate short parallel finger lines drawn across the front of the bottle and his thumb line "
 "beside them; three drops of sweat are drawn on his temple and a small towel lies across his shoulder. The girl "
 "beside him has two braids and a sky-blue shirt: she pours water from her own bottle into a small glass cup held "
 "on her knee, the four fingers of her hand drawn as four short lines across the bottle. Both bottles carry plain "
 "short tick marks and a simple picture of a star or a leaf (no text, no numbers). NO steam at any cup or bottle. "
 "On the bench between them stand two more small cups filled with clear water and a folded hand towel. "
 "Behind them, standing on the ground with both feet flat, a third child, a boy with flat short hair in a white "
 "shirt, holds a round basketball at his hip with one hand, the other hand shading his eyes, smiling. "
 "Middle ground: the red running track with white lane lines curving across the picture, the green basketball court "
 "with painted court lines, a basketball hoop with a backboard and a red rim standing on its pole beside the court, "
 "a low bench, a water tap FIXED ON a low wall with a wooden bucket standing on the ground directly under it. "
 "Background: TWO two-storey school teaching buildings with rows of square windows, two leafy trees and one bamboo "
 "clump, a long mountain ridge, a round sun with short rays, three soft clouds, a sparrow on the bench back and "
 "four small birds in the sky. "
 "Colour: bright daylight, brick-red track, fresh green court, warm cream school walls, water in soft clear "
 "cyan-blue, the two water bottles in bright red and bright blue as the accents, saturated yellow and blue shirts "
 "so the main figures stand out. "
) + SAFE

# ------------------------------------------------ 2 食堂门口的一杯温开水
T['2_食堂门口的一杯温开水'] = NOTEXT + ART + (
 " A warm school canteen scene in eastern Sichuan at lunch time. There are exactly THREE children in the picture "
 "and no other people, no extra arms and no half-visible bodies. "
 "Foreground centre: a long plain wooden canteen table; on it stand steel trays and bowls and two tall plain "
 "glasses of clear water. A girl with two braids in a sky-blue shirt sits at the table holding her glass near her "
 "mouth and drinks in SMALL SIPS, four separate short parallel finger lines drawn across the front of the glass; a "
 "boy with a short bowl haircut in a warm yellow shirt sits beside her, one hand resting on his steel tray, the "
 "other hand just setting down his glass, his finger lines clearly drawn. Both have round faces, dot eyes, small "
 "smiles and red neckerchiefs. NO steam at their glasses. "
 "Standing behind them, a third child, a boy with flat short hair in a white shirt, holds his own water bottle "
 "under the spout of a big stainless-steel hot-water barrel that stands ON a low wooden stand with both feet on the "
 "floor; the barrel is drawn as a tall cylinder with a lid and one tap at its lower front, a short bracket joins "
 "the tap to the barrel, a small wisp of steam rises from the lid only, and water runs from the tap into his bottle "
 "with two small spray droplets at the bottle mouth. "
 "Middle ground: the canteen interior — a long serving counter with a low front panel and three plain round "
 "containers standing behind it, a wide window with a cross frame and a short plain curtain, two long wooden "
 "benches, a folded dishcloth on the counter, a big clay water jar with a wooden lid in the corner. "
 "Background, seen through the window: a school yard with two leafy trees, a red running-track arc in the far "
 "distance, a long mountain ridge, two soft clouds and three small birds. "
 "Colour: warm cream walls, honey-brown tables and benches, steel grey trays and barrel, water in soft clear "
 "cyan-blue, the girl's sky-blue shirt and the boy's warm yellow shirt with two bright red neckerchiefs as the "
 "accents. "
) + SAFE

# ------------------------------------------------ 3 科学课：烧开的水才安全
T['3_科学课_烧开的水才安全'] = NOTEXT + ART + (
 " A primary-school science classroom in eastern Sichuan during a lesson about safe drinking water. There are "
 "exactly FOUR children in the picture, three seated and one standing, and no other people, no extra arms and no "
 "half-visible bodies. "
 "Foreground centre: a plain teacher's demonstration table. On it stand an electric kettle with its lid closed and "
 "one thin curly wisp of steam rising from its spout only, a white porcelain cooling jar with a lid and a spout, "
 "three clear glass beakers of clear water of different sizes, a small round magnifying glass lying flat, and a "
 "folded white cloth. A teacher's hand (only the forearm and hand, coming in from the right edge, attached to a "
 "clearly drawn rolled-up sleeve) pours water from the porcelain jar into one glass beaker; four separate short "
 "parallel finger lines are drawn across the jar. "
 "Middle ground: THREE children seated behind the demonstration table at a long wooden desk, watching closely with "
 "round faces, dot eyes and small smiles, all in shirts and red neckerchiefs — on the left a girl with two braids "
 "in a sky-blue shirt, in the middle a boy with a short bowl haircut in a warm yellow shirt, on the right a girl "
 "with a ponytail in a pale cream shirt; each has a small glass of clear water and a small notebook with BLANK "
 "pages on the desk in front of them, their arms clearly connected to their shoulders. "
 "Foreground left: one child stands beside the desk, a boy with flat short hair in a white shirt, holding up his own "
 "glass of clear water and looking at it through the magnifying glass, four finger lines drawn across the glass. "
 "Middle ground behind: a large classroom blackboard, completely BLANK with no writing and no marks at all, with a "
 "plain wooden frame and a chalk tray holding only two sticks of chalk; a wall map frame kept blank; a tall window "
 "with a cross frame along the right side. "
 "Background, seen through the window: two leafy trees, a corner of a two-storey school building, a long mountain "
 "ridge, a round sun with short rays, two soft clouds and two small birds. "
 "Colour: warm cream classroom walls, honey-brown desks, a deep green-black blank blackboard, steel grey kettle and "
 "beakers, water in soft clear cyan-blue, the children's shirts in sky blue, warm yellow and cream with bright red "
 "neckerchiefs as the accents. "
) + SAFE

# ------------------------------------------------ 4 班级饮水角的值日生
T['4_班级饮水角的值日生'] = NOTEXT + ART + (
 " A corner of a Chinese primary-school classroom set up as the class drinking-water corner. There are exactly "
 "THREE children in the 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 classroom floor, all four sides 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 TWO spouts point downwards over a drip-tray "
 "grille; there are no taps anywhere else on the machine; a drain pipe runs from the cabinet base to a floor "
 "channel. A small clean cloth and a shallow basin with a little water in it stand on the floor beside the machine. "
 "Three children work and drink here. LEFT: a girl with two braids in a sky-blue shirt kneels on one knee and wipes "
 "the front of the machine with a cloth, her arm clearly running from shoulder to hand; a small bucket of water "
 "stands beside her. MIDDLE, drawn biggest and nearest: a boy with a short bowl haircut in a bright yellow shirt "
 "holds a big tall glass tumbler of clear water up near his mouth and drinks in small sips, 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. RIGHT: a boy with flat short hair in a white shirt stands squarely facing the machine with both "
 "feet flat, one continuous arm reaching to the button panel with his hand pressing a button, and his other arm at "
 "his side holding a green water bottle with plain tick marks and four finger lines. All three have round faces, dot "
 "eyes, small smiles and red neckerchiefs. NO steam at any cup. "
 "Middle ground: the classroom corner — a long wooden desk with BLANK notebooks and a plain pencil case, a chair, a "
 "low shelf holding two small potted plants, a window sill with a watering can beside the plants, a blank notice "
 "board on the wall with nothing written on it. "
 "Background, seen through the window: a school yard with a red running-track arc, two leafy trees and one bamboo "
 "clump, a two-storey teaching building, a long mountain ridge, three soft clouds and three small birds. "
 "Colour: warm cream walls, honey-brown desk and shelf, pale grey-white machine body with a clear cyan-blue water "
 "bottle on top, water in soft clear cyan-blue, the children's shirts in sky blue, bright yellow and white with red "
 "neckerchiefs as the accents, plants in fresh green. "
) + SAFE

# ------------------------------------------------ 5 放学路上，水壶在我书包里
T['5_放学路上_水壶在我书包里'] = NOTEXT + ART + (
 " A primary-school gate scene in eastern Sichuan at the end of the school day, about carrying your own water "
 "instead of buying a sweet drink. There are exactly THREE children in the picture and no other people, no extra "
 "arms and no half-visible bodies. "
 "Foreground centre: TWO children walking out through the school gate, both with round faces, dot eyes and small "
 "smiles, wearing shirts, shorts and red neckerchiefs, each carrying a school backpack with a water bottle standing "
 "in the side pocket and a small bottle strap over it. The nearer boy has a short bowl haircut and a bright yellow "
 "shirt: he has pulled his own bottle out of the pocket and drinks from it in SMALL SIPS as he walks, four separate "
 "short parallel finger lines drawn across the front of the bottle; his other hand holds the shoulder strap. The "
 "girl beside him has two braids and a sky-blue shirt: she holds her own bottle up in one hand, four finger lines "
 "drawn across it, and smiles. NO steam at either bottle; both bottles have plain short tick marks and a simple "
 "picture of a star or a leaf (no text, no numbers). "
 "Foreground left, clearly separated from the children by the gate pillar: a small shop kiosk with a plain wooden "
 "counter and a low glass-fronted cooler cabinet; inside the cooler stand several brightly coloured bottled drinks "
 "with BLANK labels, and on the counter stands one transparent bottle lying on its side with a straw in its neck, "
 "packed inside with small cube-shaped sugar lumps each the size of a fingertip; a short trail of about eight such "
 "lumps has slid out of its mouth and lies in a little heap on the counter. No hand touches the kiosk, the cooler or "
 "the sugar heap. "
 "Middle ground: the school gate — two square brick pillars with plain blank name plates, a low iron fence with "
 "vertical bars, a small guard booth with a window; the third child, a boy with flat short hair in a white shirt, "
 "stands just inside the gate with both feet flat, waving goodbye with one continuous arm from shoulder to hand "
 "while his other hand holds his backpack strap. "
 "Background: the two-storey school teaching building with rows of square windows behind the gate, two leafy trees "
 "and one bamboo clump, a long mountain ridge, a round sun with short rays, three soft clouds, a sparrow on the "
 "fence and four small birds. "
 "Colour: warm afternoon light, brick gate pillars, warm grey pavement, the cooler's pale blue glass, small white "
 "sugar lumps, water in soft clear cyan-blue, the children's shirts in bright yellow and sky blue with red "
 "neckerchiefs as the accents, the bottled drinks in bright but slightly dull colours so the plain water stands "
 "out. "
) + 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=5) as ex:
        print(list(ex.map(lambda kv: gen(*kv), T.items())))
