# -*- coding: utf-8 -*-
"""校园 5 份 · 修订 v2：只重出 3/4/5
3 科学课：放大镜改为"举在眼前看杯子"、蒸汽只从电水壶壶嘴冒出（白瓷壶不冒汽）
4 饮水角：手部强化——杯子加大、四道手指短线画在杯身前、擦机器的抹布也画出手指线
5 放学路上：明确"书包侧袋里立着自己的水壶、瓶口有带子扣住"
"""
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'
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 THE SINGLE MOST IMPORTANT DETAIL: every hand must be BIG ENOUGH TO READ and must be "
         "drawn in the classic children's-book way — the FOUR FINGERS shown as four separate short parallel curved "
         "lines lying across the FRONT of whatever is being held (glass, tumbler, bottle, cloth or magnifying "
         "glass), each finger its own line with a small gap beside it, plus the THUMB 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 = {}

# ------------------------------------------------ 3 科学课（v2）
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 — no other steam anywhere in the picture; a white "
 "porcelain cooling jar with a lid and a spout standing closed on the table; three clear glass beakers of clear "
 "water of different sizes; a folded white cloth. A teacher's hand enters from the right edge, attached to a clearly "
 "drawn rolled-up sleeve, pouring water from the porcelain jar into one glass beaker; four separate short parallel "
 "finger lines are drawn across the jar with the thumb line beside them. "
 "Foreground left: one child stands beside the desk — a boy with flat short hair in a white shirt — holding a glass "
 "of clear water UP AT EYE LEVEL with one hand, four separate short parallel finger lines drawn across the front of "
 "the glass, and holding a round magnifying glass up in his OTHER hand directly between his eye and the glass, lens "
 "facing the glass, so he is looking through it at the water; his other arm is clearly connected to his shoulder. "
 "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 resting on the desk and clearly connected to their shoulders. "
 "Middle ground behind: a large classroom blackboard, completely BLANK with no writing and no marks, with a plain "
 "wooden frame and a chalk tray holding only two sticks of chalk; a wall 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 饮水角（v2）
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; no taps anywhere else on the machine; a drain pipe runs from the cabinet base to a floor channel. "
 "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 his mouth — the tumbler is drawn as wide as his own palm — and on the FRONT of "
 "that big tumbler the four fingers of his hand are clearly drawn as four separate short parallel curved lines with "
 "the thumb line beside them; a second small cup waits on the drip tray. "
 "LEFT: a girl with two braids in a sky-blue shirt kneels on one knee and wipes the front of the machine with a "
 "folded cloth; her forearm runs continuously from shoulder to hand, and on the cloth the four fingers of her hand "
 "are drawn as four separate short parallel lines; a small bucket of water stands on the floor beside her. "
 "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, the four fingers of that hand also "
 "drawn as four short parallel lines; his other arm hangs at his side holding a green water bottle with plain tick "
 "marks and four finger lines across it. 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 放学路上（v2）
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 ON THEIR BACK. On the OUTSIDE "
 "of each backpack there is a visible mesh side pocket, and standing upright in that pocket is the child's OWN water "
 "bottle with a short strap looped over its neck and clipped; the bottle stands clearly above the pocket rim so it "
 "is easy to see. The nearer boy has a short bowl haircut and a bright yellow shirt: he has just pulled his bottle "
 "out of the side 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 his 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 across it, and smiles; her "
 "backpack still shows the empty mesh pocket with the strap. 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; his backpack also shows a bottle standing in its side mesh pocket. "
 "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=3) as ex:
        print(list(ex.map(lambda kv: gen(*kv), T.items())))
