# -*- coding: utf-8 -*-
"""5份【中等难度·四年级可画】科学饮水主题绘画稿 —— 第1步：线条图
主题：科学饮水共促健康（结合四川广安地域特色）
要求：中等细节（可含瓦片、竹节、水波纹、石板缝等细节线），严禁阴影/排线/灰阶/彩色填充
"""
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/lineart'
os.makedirs(OUT, exist_ok=True)

NOTEXT = ("Absolutely NO TEXT anywhere. No Chinese characters, no letters, no words, no numbers, no calligraphy, "
          "no captions, no titles, no logos, no watermarks, no signature, no seals or stamps. No writing on the "
          "blackboard, on the banners, on the shop signs, on the labels or on any cup. Every signboard, screen and "
          "printed surface must be completely blank. ")

LINE = (" Clean black-and-white line drawing for a children's watercolour painting workbook — a tracing and "
        "colouring outline. Uniform black outlines on pure white background. MODERATE level of detail: include "
        "interior detail lines that a 9-10 year old can draw, such as roof tile rows, window frames, bamboo "
        "sections, water ripple lines, leaf clumps, stone paving lines, brick rows. "
        "ABSOLUTELY NO shading, NO cross-hatching, NO stippling, NO grey tones, NO gradients, NO tonal patches, "
        "NO colour fill, NO texture rendering — outlines only, every area left pure white. "
        "Genuine scene composition with foreground, middle ground and background, simple one-point perspective "
        "with nearer objects bigger and further objects smaller, clear overlapping layers. Characters drawn with "
        "simple but expressive faces (dot eyes, small smile) and clear limbs and poses. Closed clear shapes, "
        "readable silhouette, well-balanced wide composition, white margins. ")

T = {}

# ---------------------------------------------------------------- 1 饮水思源
T['1_饮水思源_一滴水的旅行'] = NOTEXT + (
 " A cheerful educational scene showing the whole journey of one drop of drinking water, set in a riverside "
 "town in eastern Sichuan. Foreground, right side: a happy child with a ponytail, round face, dot eyes and a "
 "small smile, wearing a shirt and a red neckerchief, standing and holding a tall clear glass tumbler with "
 "horizontal measuring marks on its side, taking a small slow sip; a thin wisp of steam rises from the glass; "
 "one very large stylized water-drop shape with a highlight is drawn floating in the air beside the child; "
 "several grass tufts and two small flowers at the bottom edge. "
 "A single long winding S-shaped blue water ribbon flows through the entire picture, from the top-left corner "
 "down across the middle to the child's glass. Along this ribbon, from far to near: a fat cloud with straight "
 "rain lines over a mountain ridge; a mountain stream tumbling over three rounded stones; a wide river with "
 "long ripple lines and one small wooden boat with a sail-less hull and a boatman; clumps of riverside reeds; "
 "a small stone arch bridge over the river; then the ribbon disappears behind a house wall. "
 "Middle ground, right: a plain white house wall with one square window and a wooden shelf; in front of it a "
 "small cooking stove with a metal kettle whose spout sends up a curly steam line; a white porcelain cooling "
 "jar with a lid and a spout standing on a low table; a wall tap with a child's hand turning it shut and a "
 "small bucket underneath catching drips; a watering can beside a flower bed with three flowers. "
 "Background: a tall stone monument on a wide stepped plaza with a row of small lamp posts, standing on the "
 "right horizon; the long horizontal bank line of the river; a big mountain with simple ridge lines and a few "
 "pine tree shapes on the left; two soft cloud shapes, a round sun with short rays, and three tiny birds."
) + LINE

# ---------------------------------------------------------------- 2 竹节里的八杯水
T['2_竹节里的八杯水'] = NOTEXT + (
 " A fresh green mountain-bamboo scene that turns a bamboo stalk into a drinking-water measuring scale. "
 "Foreground, lower left: a child with a round face, dot eyes and a small smile, hair tied up, wearing a shirt "
 "and a red neckerchief, holding a small cup with measuring marks and sipping; the child stands beside the "
 "lowest bamboo node with the cup's water level lined up with the node; grass tufts and three small mushrooms "
 "at the bottom edge. "
 "Centre of the picture: one very thick bamboo stalk rises vertically from the bottom of the frame right up to "
 "the top, drawn with EIGHT clearly separated bamboo nodes as horizontal joint lines and long vertical fibre "
 "lines; beside each of the eight nodes sits one small cup, each cup drawn with measuring marks and a "
 "different water level, the levels rising as the stalk goes up; a single big water drop rests on a bamboo "
 "leaf next to several of the cups. "
 "At the foot of the stalk: a rock face with a narrow crack from which a spring water line flows out, "
 "splashing into a small pool drawn with ripple rings, two stepping stones, and three young bamboo shoots "
 "with pointed tips and wrapping sheaths. "
 "Middle ground left and right: several bamboo leaf clusters in overlapping groups, a small bamboo fence, a "
 "winding mountain footpath with a low step, a wooden water ladle with a long handle leaning against a stone, "
 "and a small wooden bucket. "
 "Background: a large mountain with simple ridge lines and pine shapes, a soft band of morning cloud sea across "
 "its middle, a big rising sun with short straight rays behind the ridge, two birds, two soft cloud shapes, "
 "and clumps of distant bamboo on the far slopes."
) + LINE

# ---------------------------------------------------------------- 3 嘉陵江边的一壶白开水
T['3_嘉陵江边的一壶白开水'] = NOTEXT + (
 " A warm old riverside town street scene about choosing plain boiled water instead of sugary drinks. "
 "Foreground, centre: a wooden square table with four straight legs. On the table stand TWO glasses side by "
 "side — on the left a plain clear glass of water with a small highlight swirl, and on the right a glass of a "
 "dark drink with a drinking straw and a heap of about sixteen cube-shaped sugar lumps spilling out of a "
 "tipped-over bottle and piling up on the table. A child with a round face, dot eyes and a small smile, "
 "wearing a shirt and a red neckerchief, sits at the table: one hand pushes the pile of sugar lumps away from "
 "the glasses, the other hand holds up the plain clear glass of water. Beside the table a long-spouted copper "
 "kettle is tipped forward pouring a thin stream of hot water into a white porcelain pot, with a curly steam "
 "line rising from both the kettle and the pot. "
 "Middle ground: a stone-paved street drawn in simple perspective with paving-joint lines; the tiled eaves and "
 "one wall of an old wooden house on the left, with rows of roof tiles and three hanging round lanterns "
 "under the eave; a bamboo chair and a long wooden bench; a big clay rain-water jar with a wooden lid and a "
 "bamboo dipper standing against the wall; a bamboo-woven water bottle hanging from a wall peg; a winsome cat "
 "sitting on the wooden bench. "
 "Background: the wide river surface of the Jialing river with long ripple lines, two wooden boats with simple "
 "masts and hulls, two thin bands of morning mist, a distant hill outline, one leafy tree on the far bank, and "
 "three small birds."
) + LINE

# ---------------------------------------------------------------- 4 健行杯的哨声，每人的水壶
T['4_城里的校园球赛_每人的水壶'] = NOTEXT + (
 " A lively primary-school basketball game day scene about drinking enough water after sport. "
 "Foreground, left: three cheerful children standing at the sideline with round faces, dot eyes and small "
 "smiles, wearing sports shirts and shorts and red neckerchiefs; each child holds their own water bottle "
 "drawn with measuring marks and different stripe patterns; one child tips the bottle up and drinks in small "
 "sips, another child holds a towel over a shoulder and wipes sweat with visible sweat-drop shapes over the "
 "head, the third child has one hand cupped under a wall tap to fill the bottle. "
 "Middle ground: a red running track arc with lane lines and a plastic basketball court with painted court "
 "lines in perspective; a basketball hoop with a backboard, a pole and a net, standing on one side; one child "
 "in mid-air jumping to shoot a round basketball, drawn with clear arms and legs; a tall referee teacher "
 "standing at the side blowing a whistle with one raised hand; TWO separate two-storey school teaching "
 "buildings drawn with rows of square windows and a corridor railing; along the corridor wall a long straight "
 "drinking-water station with three taps and a low step; a flower bed with three flowers beside a watering "
 "can and a big plastic bucket catching rain water under the eave. "
 "Background: a flag platform with a plain blank pole and a blank banner-free pole, two leafy trees and one "
 "bamboo clump, a long mountain ridge outline, one big sun with short rays, three soft clouds and four small "
 "birds in the sky."
) + LINE

# ---------------------------------------------------------------- 5 我家的水位线
T['5_我家的水位线'] = NOTEXT + (
 " A warm and cosy home kitchen-and-dining scene about drinking water at home, using the water level in "
 "every cup as a family health scale. "
 "Foreground, on an old wooden table: THREE of the child's own cups standing in a row, left to right — a "
 "small bowl with a spoon, a small tumbler, and a taller bottle with measuring marks — with their water "
 "levels growing higher from left to right; a child's small hand rests on the tallest bottle; below the table "
 "edge a low stool and two pairs of slippers. "
 "Middle ground: the same old table holds the whole family's cups arranged in a semicircle — a white enamel "
 "mug with a rim stripe, a plain glass, a tall vacuum thermos flask with a lid, and a mug with a handle — "
 "each cup filled to a different water level, each shown with its own rim and handle details; a child with a "
 "round face, dot eyes and a small smile, wearing a shirt, stands and pours water from a small pot into the "
 "enamel mug of an elderly grandparent who sits on a wooden chair holding the mug with both hands; behind "
 "them a kitchen stove with a metal kettle blowing out a curly steam line, a wall shelf with two bowls and "
 "three stacked dishes. "
 "Background: a kitchen window with a cross frame and a short curtain; through the window a courtyard with a "
 "big clay rain-water jar under the eave, a clothesline with three hanging pieces of clothing, a leafy pomelo "
 "tree with round fruit, a low wall, a distant hill outline, two clouds and two birds; a round basket of fruit "
 "standing on a side cabinet; a cat curled up beside the clay jar; one potted plant with three leaves on the "
 "window sill."
) + LINE


def gen(name, prompt, retries=2):
    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": "2048x2048", "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())))
