# -*- coding: utf-8 -*-
"""v6：只修 A、C 的手 —— 杯子加大加高，给手指留出位置，并按"手指=横在杯身上的短弧线"画法
（B 已在 v5 达标：判"画出了分开的手指，有清晰的手指分界线条"）
"""
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 THE MOST IMPORTANT PART OF THIS PICTURE. Each child drinks from a BIG TALL GLASS "
         "TUMBLER — as tall as the child's own forearm and clearly wider than the child's hand — so there is plenty "
         "of room to draw the hand properly. Every hand must be drawn in the classic children's-book way: FOUR "
         "SEPARATE FINGERS shown as four individual short parallel curved lines lying across the FRONT of the big "
         "glass, each finger its own line with a small visible gap beside it, plus the THUMB drawn separately as one "
         "short line on the near side, and a simple rounded palm shape behind the glass. Never draw a mitten, a "
         "glove, or a solid rounded blob with no finger lines — the individual finger lines must be clearly visible "
         "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 and wear red "
 "neckerchiefs; each holds a BIG TALL WIDE GLASS TUMBLER of clear water up close to the mouth, taking a small sip, "
 "and on the front of each big tumbler the four fingers of the hand are clearly drawn as four separate short "
 "parallel curved lines with the thumb line beside them; NO steam at their glasses; the girl's tumbler 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['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; on the front of the bottle the four fingers of her hand are drawn as four "
 "separate short parallel curved lines. 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 of clear water held up close to the mouth, 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 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 with "
 "the four finger lines drawn on it. 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=2) as ex:
        print(list(ex.map(lambda kv: gen(*kv), T.items())))
