# -*- coding: utf-8 -*-
"""第1步：5份【中等难度·四年级可画】水彩稿的线条图
要求：中等细节（可含瓦片、竹节、书页、叶簇等细节线），但禁止阴影/排线/灰阶/彩色填充"""
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/pandaReadArt/lineart_mid5'
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 or on any banner. The blackboard and all banners must be 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, book page lines, leaf clumps, water ripples, stone paving lines. "
        "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 = {}

T['A_马灯下的接力'] = NOTEXT + (
 " Night scene on a grassy plain. Foreground: tufts of long grass, small wildflowers, and a few small round "
 "fireflies with dots, plus an open book lying on the grass shown with page lines. Middle ground: two children "
 "sitting side by side on the ground reading one big open book together — on the left a girl with a ponytail, a "
 "round face, dot eyes and a small smile, wearing a shirt and a neckerchief triangle on her chest; on the right a "
 "boy seen from the back wearing a small army cap with a star on it, a shoulder bag strap across his back; both "
 "have simple arms and legs clearly drawn. Behind them stands a tall wooden post with a rectangular oil lantern "
 "hanging from the top, the lantern with a curved roof and a small star on its side, a curved handle above it. "
 "Background: a wavy horizon line, a rolling low mountain outline, three tiny distant tents and a string of tiny "
 "distant lights; above, a large crescent moon and several stars drawn as small circles with four-point sparkles; "
 "two drifting ribbon shapes in the sky."
) + LINE

T['B_遵义的红灯'] = NOTEXT + (
 " Night street scene in front of a historic building. Middle ground: a two-storey building with a traditional "
 "Chinese tiled roof — the roof drawn as rows of small tile arcs, upturned eaves, a small wooden balcony with a "
 "railing, arched windows with frames; a large glowing five-pointed star ornament set above the main doorway; a "
 "row of four hanging lanterns under the eaves connected by a curved string; a tall traditional flag on the roof "
 "with visible folds. On the right, a big old tree with a thick trunk and a crown drawn as overlapping cloud-like "
 "clumps of leaves. Foreground: a stone-paved street drawn with paving lines in simple perspective, three steps "
 "in front of the door, and a boy with a round face, dot eyes and a neckerchief sitting on the steps holding an "
 "open book with page lines on his knees; a small lantern on the ground beside him. Two long straight lines "
 "radiating from one lit upper window across the whole composition to show a beam of light. Background: distant "
 "hill outline, a few stars, thin mist lines."
) + LINE

T['C_飞夺泸定桥'] = NOTEXT + (
 " Heroic gorge landscape. Left and right: two tall steep mountains drawn with simple ridge lines and a few pine "
 "tree shapes; mist bands crossing the mountain sides. Centre: a long chain suspension bridge across the gorge — "
 "two long sagging curves as the main chains, drawn with many small circles along them as chain links, and a few "
 "straight plank rectangles only at the near end, with many planks missing in the middle; four small soldiers in "
 "cap and uniform marching along the chains, leaning forward, the leading one holding a flag on a pole; the flag "
 "has visible folds. Bottom: a rushing river with wave and spray lines, and a few swift bird shapes. Sky: large "
 "billowing cloud shapes and a break of light rays. Lower-left foreground: a big open book resting on a rock, "
 "with page lines and a small simple picture of a bridge drawn on its open page, and a child's hand resting on "
 "the page."
) + LINE

T['D_宝塔山下的读书声'] = NOTEXT + (
 " An open-air school on a loess hillside. Background: a hill with four arched cave dwellings cut into two tiers "
 "with a low railing in front of each tier, a nine-tier pagoda with a pointed roof standing on the hill top, "
 "simple tree shapes, the sun and two cloud shapes in the sky. Middle ground: a blackboard on a wooden stand "
 "(the board surface completely blank, no writing at all), a teenager standing beside it holding a pointing "
 "stick, a clothesline with three pieces of clothing, a string of corn cobs hanging under an eave. Foreground: "
 "six children with round faces, dot eyes and small smiles sitting cross-legged in a row on the ground, each "
 "holding a small book with page lines, wearing neckerchief triangles; two chickens pecking on the ground near "
 "them; a low stone wall behind them. Lower edge: a river drawn with wavy ripple lines winding across."
) + LINE

T['E_红种子长成书树'] = NOTEXT + (
 " A miraculous book tree on a green hillside. Centre and upper area: a huge tree with a thick trunk and a "
 "crown built entirely out of many stacked and leaning rectangles representing books of different sizes, with a "
 "flag on a pole on the topmost book and a few small hanging lanterns among the books; the wide trunk is drawn "
 "with bark lines and a long winding double-line path carved up it, with five tiny marching figures in caps and "
 "uniforms along that path and several five-pointed star shapes drawn beside the path. Lower area: the tree's "
 "roots with a star-shaped seed and a small sprouting shoot, a long ribbon tied around the trunk with visible "
 "folds. Foreground: a checkered picnic mat on the grass under the tree, a girl with a ponytail, dot eyes and a "
 "neckerchief sitting on it reading an open book, and beside her a fluffy panda also holding an open book, both "
 "with simple clear limbs; several books and leaves scattered on the grass. Background: rolling hill outlines and "
 "the sun and two clouds."
) + 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)[:200]}", 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())))
