# -*- coding: utf-8 -*-
"""第1步修订版 v3：重出 2/3 两张线条图
修点：
  2 竹节 —— 杯子改为坐在"竹筒托座"里（短截竹筒挖空做底座），竹竿顶端干净收尾，八杯高度成阶梯
  3 嘉陵江 —— 关键改法：透明瓶子里面装的是堆叠的方块糖（"一瓶饮料就是一瓶糖"），不再画"往杯里加糖"；
              铜壶坐在小炉子上（防悬空）；孩子用手掌把糖瓶推开
"""
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 digits, "
          "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. "
          "No numbers or digits on any cup, bottle or measuring scale — the measuring marks must be plain short "
          "horizontal tick lines only. Every signboard, screen and printed surface must be completely blank. ")

NOFILL = ("Any liquid inside a cup, glass, jar or pot must be shown with OUTLINES ONLY — a simple wavy surface "
          "line — with absolutely NO grey fill, NO shading and NO tonal patches inside the liquid. ")

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. Every object rests on or "
        "touches something solid — nothing floats in the air unsupported. Closed clear shapes, readable "
        "silhouette, well-balanced wide composition, white margins. ")

T = {}

# ---------------------------------------------------------------- 2 竹节（v3）
T['2_竹节里的八杯水'] = NOTEXT + NOFILL + (
 " A fresh green mountain-bamboo scene that uses a bamboo stalk as 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, standing on two stepping stones on the ground and holding up a small cup with plain "
 "tick marks, taking a small slow sip with the cup raised near the chin; two clear water droplets fall from the "
 "cup; grass tufts and three small mushrooms at the bottom edge. "
 "Centre of the picture: one very thick bamboo stalk rises straight up from the bottom of the frame to the top, "
 "drawn with EIGHT clearly separated bamboo nodes marked as horizontal joint lines, plus long vertical fibre "
 "lines; the very top of the stalk ends in a clean straight cut with exactly two small bamboo leaves, and "
 "nothing else. At EACH of the eight nodes, one thick short bamboo side-branch sticks out sideways, and at the "
 "end of every side-branch there is a short hollow bamboo section standing upright like a little socket; inside "
 "each socket stands one small cup, clearly held by the socket so it cannot fall; every cup is drawn with plain "
 "short tick marks and one wavy water-surface line, and the eight cups sit at eight clearly different heights so "
 "that they climb upwards like a small staircase, the higher cups holding a little more water. One single big "
 "water drop rests on a bamboo leaf beside three of the cups. "
 "At the foot of the stalk: a rock face with a narrow crack from which a spring water line flows out and "
 "splashes into a small pool drawn with ripple rings; 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 lying on a flat stone, and "
 "a small wooden bucket standing on the ground. "
 "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 嘉陵江（v3）
T['3_嘉陵江边的一壶白开水'] = NOTEXT + NOFILL + (
 " A warm old riverside town street scene showing that a bottled sweet drink is really just a bottle of sugar, "
 "and that plain boiled water is the better choice. "
 "Foreground, centre: a wooden square table with four straight legs standing on the pavement. On the table, at "
 "the right side, stands one transparent bottle with a drinking straw in its neck, and the bottle is drawn "
 "COMPLETELY SEE-THROUGH: instead of liquid, inside it is packed from bottom to top with stacked cube-shaped "
 "sugar lumps, each lump drawn as a clear little block with visible cube edges, so the bottle plainly looks like "
 "a bottle full of sugar blocks. A few sugar lumps have spilled out of the bottle mouth and lie in a small heap "
 "at its base on the table. On the left side of the table stands one tall plain glass of clear water with a "
 "small sparkle. A child with a round face, dot eyes and a small smile, wearing a shirt and a red neckerchief, "
 "stands at the table: one flat open palm pushes the sugar bottle away to the right, with three short curved "
 "motion lines behind the pushing hand, while the other hand lifts the tall plain glass of clear water up high "
 "with three small four-point sparkle shapes drawn around it. "
 "Beside the table, standing on the ground, a small round charcoal brazier with three short legs holds a "
 "long-spouted copper kettle; the kettle is tipped forward and pours a thin stream of hot water into a white "
 "porcelain pot standing on the table, and one curly steam line rises from the spout. "
 "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 standing on the pavement; 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 cat sitting on the wooden bench. "
 "Background: the wide river surface 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


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=2) as ex:
        print(list(ex.map(lambda kv: gen(*kv), T.items())))
