# -*- coding: utf-8 -*-
"""第1步修订版 v5：只重出 3 嘉陵江（去壶去炉，构图做减法）
背景：铜壶+瓷壶放在同一桌上会被读成"往杯里加糖"。本份只讲"一杯白开水 vs 一瓶方糖"。
"""
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 shop signs, 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 "
          "and printed surface must be completely blank. ")

NOFILL = ("Any liquid inside a cup or glass 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, 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 about choosing a plain glass of water instead of a bottled sweet "
 "drink. There is NO kettle, NO stove and NO teapot anywhere in this picture. "
 "Foreground, centre: a wooden square table with four straight legs standing on the pavement. In the middle of "
 "the table top stands one tall plain glass of clear water. On the FAR RIGHT corner of the table lies one "
 "transparent plastic bottle tipped over on its side with a drinking straw sticking out of its neck; the bottle "
 "is drawn COMPLETELY SEE-THROUGH, and instead of liquid it is packed from bottom to top with stacked "
 "cube-shaped sugar lumps, each lump drawn as a clear little block with visible straight cube edges; a few of "
 "these sugar lumps have spilled out of the bottle mouth and lie in a short scattered line on the table beside "
 "it, with two short curved motion lines behind the bottle showing it has just rolled aside. A child with a "
 "round face, dot eyes and a happy small smile, wearing a shirt and a red neckerchief, stands at the table and "
 "holds the tall plain glass of clear water with BOTH hands lifted to chest height; three small four-point "
 "sparkle shapes and one water droplet are drawn around the glass. "
 "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, drawn with rows of roof tiles, a wooden door frame and a square "
 "window; three round lanterns hanging in a row under the eave; a bamboo chair with a curved back standing on "
 "the pavement beside 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 wooden wall peg; a cat sitting on the "
 "wooden bench; some grass tufts growing between the paving stones. "
 "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))
