# -*- coding: utf-8 -*-
"""黑板报配色底图（粉笔版式，无文字）—— 5 版，2400x1600 (3:2)
配色图 = 底图 + Pillow 粉笔标题；线条图 = 由底图 i2i 反推 + 空心字标题
"""
import base64, 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/heibanbaoArt/chalk'
os.makedirs(OUT, exist_ok=True)

STYLE = (
 "A hand-drawn CHALKBOARD NEWSPAPER (Chinese primary school 黑板报) layout, drawn entirely with coloured chalk "
 "on a dark chalkboard. The image IS the flat board surface, seen perfectly straight-on and filling the whole "
 "frame — no wooden board frame, no easel, no classroom, no desk, no people in front of it. "
 "SURFACE: deep dark green-black chalkboard (#1E2A26) with a faint cloudy chalk-dust haze and a few soft "
 "erased grey smudges, but completely empty in the background otherwise. "
 "MEDIUM: every line and every filled area is CHALK — powdery, slightly ragged edges, tiny crumbs, grainy "
 "texture, some strokes a little uneven. NOT marker pen, NOT watercolour, NOT vector art, NOT digital gloss. "
 "COLOURS: bright white chalk, warm yellow chalk, coral red chalk, sky blue chalk, mint green chalk, pink "
 "chalk — high contrast against the very dark board. "
 "FLAT 2D: flat chalk colouring only, NO gradients, NO shading, NO 3D, NO photorealism, NO glow, NO drop shadows. "
 "COMPOSITION: a well-balanced poster-like page of chalk-drawn panel frames plus chalk-drawn illustrations. "
 "Every panel frame is drawn with a thick chalk line and its INTERIOR IS COMPLETELY EMPTY dark board, ready for "
 "a pupil to write into with chalk — never fill a panel interior with anything. "
 "TITLE BAND: the TOP 34 PERCENT of the board is left COMPLETELY EMPTY — bare chalkboard only. NOTHING AT "
 "ALL is drawn inside that band: no frame line, no panel, no sun, no cloud, no fruit, no animal, no "
 "character, no decoration, no symbol, no scribble — nothing from the left edge to the right edge. That "
 "whole band is bare empty dark chalkboard, because a big hand-written title will be placed there. Every "
 "panel frame, every illustration and every decorative element must stay BELOW the 36 percent height line "
 "of the image. "
 "NO wooden frame, NO border, NO easel around the board: the dark board runs edge to edge and is cropped by "
 "the image edges. "
 "ABSOLUTELY NO TEXT ANYWHERE: no Chinese characters, no letters, no words, no numbers, no digits, no "
 "calligraphy, no captions, no title, no logo, no watermark, no signature, no seal. Any signboard, screen, "
 "banner, poster, blackboard or book in the scene must be completely BLANK."
)

LAYOUTS = {
 '1_安全伴我行_盾牌':
   " LAYOUT: the visual anchor is a BIG chalk-drawn security shield standing in the centre of the LOWER HALF "
   "(wide rounded shield with a small safety-cross on top), its interior empty. Around it four chalk "
   "panel frames of different shapes: a cloud-shaped frame at the upper left, a rounded-rectangle frame at the "
   "upper right, a wavy-edged frame at the lower left, a hexagon frame at the lower right. On the far left, a "
   "small school gate with a security guard standing beside it and two children holding hands walking in; on "
   "the far right, a child walking UP a short staircase that has a handrail on the right-hand side. Along the "
   "very bottom edge, a row of small chalk icons: a bicycle helmet, a seat-belt buckle, a triangular warning "
   "sign, a bar of soap with water drops, a fire extinguisher, a green leaf. A few small chalk stars in the two lower corners only.",

 '2_文明出行_交通标志':
   " LAYOUT: the composition is built from three BIG chalk traffic-sign boards used as text panels — a round "
   "sign with a thick red chalk ring at the left-centre, a triangular warning sign with a thick red chalk "
   "border at the right-centre, and a wide rectangular direction board along the lower middle — every sign "
   "face COMPLETELY BLANK and empty inside. Each sign stands on a post planted on a clearly drawn road surface "
   "that runs across the lower part of the page, with a visible ground line — the signs must sit ON the road, "
   "never floating and never resting on scribbles, doodles or random pencil lines. Between them, a zebra "
   "crossing running diagonally with "
   "bold white stripes, a tall traffic light with three round lamps standing at the left, a small school bus "
   "at the right with a child boarding it and another child raising a hand to cross, and in the lower right "
   "corner a fire hydrant beside a red fire extinguisher with a small flame crossed out by a chalk slash. "
   "A few small chalk stars in the two lower corners only.",

 '3_珍爱生命_防溺水':
   " LAYOUT: the bottom third is a big stylised chalk water surface made of bold wavy chalk lines in sky blue "
   "and white, with a round life-buoy with red and white quarters floating on it and a blank warning sign "
   "board on TWO solid wooden legs standing firmly in the grass on the bank, clearly resting on the ground. On the bank a child stands well back from the water reaching out one arm "
   "while a taller adult grips the child's other arm and holds him back. Above the water there are two chalk "
   "panel frames with wavy scalloped edges (one at the left, one at the right), each interior empty. Down in the "
   "LOWER RIGHT corner a small food corner: a red apple, a carton of milk and a bar of soap with water drops. "
   "No fish and no floating objects in the water.",

 '4_反诈小卫士_手机':
   " LAYOUT: the visual anchor is a HUGE chalk-drawn smartphone standing upright in the centre of the lower "
   "two thirds, drawn in thick white chalk with a thin bezel and a small speaker slit at the top; the whole "
   "screen is COMPLETELY EMPTY WHITE — a big blank writing panel that a pupil will fill in, NOT filled with "
   "any colour. A chalk chat bubble floats "
   "above the phone with its inside empty. To the LEFT of the phone stands a police officer in a dark navy-blue "
   "uniform with a peaked cap and a badge, one arm raised in a stopping gesture; to the RIGHT a boy holds a "
   "small phone up and looks at it doubtfully, with a question mark drawn in chalk above his head. EVERY "
   "figure in the picture is drawn in exactly the same flat chalk style: white chalk outlines with simple "
   "flat chalk colour fills — NO realistic skin tones, NO hair colour, NO cartoon shading, NO illustrated "
   "or painted-looking characters that differ from the chalk style. Along the bottom edge, "
   "three cloud-shaped chalk chat bubbles of different sizes, interiors empty, plus a big chalk padlock and a "
   "round police badge with a five-pointed star. A few chalk coins and a crossed-out hook are scattered near "
   "the corners.",

 '5_远离毒品_健康成长':
   " LAYOUT: on the left a BIG chalk tree — a thick warm-brown trunk and a crown made of three large overlapping "
   "round chalk circles drawn with THICK bold chalk outlines, each circle large enough to write inside and its "
   "interior COMPLETELY EMPTY dark board as a text panel; a chalk sun with short rays low on the right side, and a "
   "chalk warning sign board (blank inside) beside it. In the centre-right a large round chalk prohibition sign "
   "(thick red ring with one thick red diagonal bar) laid over a simple drooping poppy flower with a bent stem "
   "and three falling petals. Below the sign, one healthy boy and one girl in school clothes running and jumping "
   "with happy faces. Only THREE small crossed-out icons along the very bottom edge: a syringe, a pill capsule, "
   "and a plain shield with a big tick inside it that is NOT crossed out. Keep the background decoration VERY SPARSE: no scattered stars, only two small "
   "chalk clouds in the top corners, so that the board has plenty of open empty space.",
}


def gen(key, layout):
    name = key + '.jpg'
    prompt = STYLE + layout
    for a in range(4):
        try:
            r = requests.post(f"{BASE}/images/generations",
                headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
                json={"model": MODEL, "prompt": prompt, "size": "2400x1600", "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, name)
                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)[:260]}", flush=True)
        except Exception as e:
            print(f"EXC {name} #{a}: {e}", flush=True)
        time.sleep(8)
    return None


if __name__ == '__main__':
    with ThreadPoolExecutor(max_workers=5) as ex:
        list(ex.map(lambda kv: gen(*kv), LAYOUTS.items()))
