# -*- coding: utf-8 -*-
"""第1步修订版 v4：只重出 3 嘉陵江
修点：孩子改为"双手捧起白开水杯"，糖瓶侧倒在桌角并已滚开（不再有"扶着糖瓶"的歧义手势）
"""
import json, os, time, requests

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'

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. ")

PROMPT = 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, "
 "lying tipped over on the FAR RIGHT corner, is one transparent plastic bottle with a drinking straw in its "
 "neck, and it 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; the bottle "
 "has rolled away to the right and a few sugar lumps have spilled out of its mouth, lying in a small scattered "
 "line on the table top beside it, with two short curved motion lines behind the bottle showing it has just "
 "rolled aside. In the middle of the table stands one tall plain glass of clear water. A child with a round "
 "face, dot eyes and a small smile, wearing a shirt and a red neckerchief, stands at the table and CUPS the "
 "tall plain glass of clear water in BOTH hands, lifting it up to chest height with a happy face and three "
 "small four-point sparkle shapes drawn around the glass. "
 "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, with one curly steam line rising 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=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": "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__':
    print(gen('3_嘉陵江边的一壶白开水', PROMPT))
