# -*- coding: utf-8 -*-
"""10个红色节点绘画主题（建党105周年 + 红军长征胜利90周年）参考图批量生成"""
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/anniv10'
os.makedirs(OUT, exist_ok=True)

NOTEXT = ("Absolutely NO TEXT anywhere in the image. No Chinese characters, no letters, no words, no numbers, "
          "no calligraphy, no banners with writing, no captions, no titles, no logos, no watermarks, no signature, "
          "no seals or stamps, no readable marks of any kind. Pure illustration only. ")

SAFE = (" Warm, hopeful, wholesome and positive mood. Uplifting and inspiring. No violence, no injuries, no blood, "
        "no frightening imagery, no distress. Heroic but gentle, suitable for children. ")

STYLE = (" Children's picture-book illustration style, hand-painted watercolor washed over soft colored-pencil "
         "outlines, luminous translucent washes, paper grain, vivid yet gentle palette, expressive and "
         "easy to imitate, wide 4:3 composition with a clear central subject, no border, no frame. ")

T = {}

T['01_红船启航'] = NOTEXT + (
 " A magical scene of a small wooden boat with a red painted hull and a curved traditional Chinese roof, "
 "floating on a sea made of the pages of one enormous open book. The book lies on calm water at dawn, and the "
 "printed pages curl into gentle waves; golden sunrise light breaks over the horizon. The little red boat glides "
 "forward with a tiny glowing lantern at its bow, leaving a trail of soft golden ripples. In the far distance, "
 "faintly silhouetted against the dawn, sail the shapes of great modern ships. Lotus leaves, a few water birds, "
 "drifting red silk ribbons in the sky, and a single bright red star gleaming high above. Theme: a great journey "
 "began on a small boat, and reading carries it onward."
) + SAFE + STYLE

T['02_会师1936'] = NOTEXT + (
 " Joyful reunion on a golden loess plateau under a brilliant blue sky. Two teenage Red Army soldiers in faded "
 "grey-green uniforms and caps with red stars run toward each other with arms wide open, one holding a tall red "
 "flag, the other wearing straw sandals, both laughing with tears of happiness. Behind them two separate streams "
 "of tiny marching figures converge into one. The ground they stand on is one enormous opened book, its pages "
 "turning into the yellow earth. In the foreground, seen from behind, two present-day children wearing red "
 "neckercchiefs stand on a low hill holding a book and looking up at the scene, one of them raising a hand in "
 "greeting. Wild sunflowers and red silk ribbons everywhere. Theme: ninety years ago two long marches met and "
 "became one victory."
) + SAFE + STYLE

T['03_飞夺泸定桥'] = NOTEXT + (
 " Dramatic and heroic riverscape: a long chain suspension bridge of thirteen thick iron chains stretches across "
 "a deep gorge above a roaring turquoise river, thin wooden planks missing in the middle. A line of small brave "
 "figures in grey-green uniforms and red-star caps advances carefully along the chains, leaning into the wind, "
 "determined, with a red flag planted at the far end. Towering misty mountains on both sides, clouds tearing past, "
 "a break of golden light falling on the chain-walkers, spray and swifts rising from the water below. In the lower "
 "foreground corner, an open picture book rests on a rock showing the same bridge scene, with a child's hand "
 "resting on the page. Uplifting and inspiring, not frightening."
) + SAFE + STYLE

T['04_雪山红脚印'] = NOTEXT + (
 " A towering snow mountain ridge under a crystal blue sky, seen from behind: a small line of Red Army figures in "
 "grey-green padded coats and red-star caps climbs upward, bending against the wind, at the very top a small red "
 "flag flying. Their footprints are pressed deep into the snow, and the single line of footprints is drawn as a "
 "glowing warm red-gold trail that flows down the slope and turns into the pages of a huge open book lying in the "
 "snowy foreground, where a present-day child in a red neckerchief kneels and touches the trail of footprints. "
 "Snowflakes, a few hardy alpine flowers, ice crystals sparkling, warm amber light on the ridge top against cool "
 "blue shadows."
) + SAFE + STYLE

T['05_草地的红星火柴'] = NOTEXT + (
 " A dark green grassland marsh at night, star-filled sky reflected in the still water. In the very centre, a "
 "single match-stick is alight, held carefully in the cupped hands of a young Red Army soldier wrapped in a thin "
 "grey blanket, its small flame shaped like a five-pointed star. The tiny flame throws a huge warm golden circle "
 "of light, and inside that warm circle appear dreamy translucent visions: a campfire, a steaming pot, other "
 "soldiers sitting close together, and the roofs of distant villages. Present-day children kneel just outside the "
 "circle of light, leaning in, faces glowing. Fireflies drift over the marsh, a few reeds bent by the wind. "
 "Poignant, warm and hopeful."
) + SAFE + STYLE

T['06_半条被子'] = NOTEXT + (
 " A cosy intimate interior scene of an old village house at night: a young Red Army woman soldier in a faded "
 "grey-green uniform and red-star cap sits on the edge of a wooden bed, carefully cutting a thick quilt in half "
 "with a pair of scissors; she is smiling warmly and looks tired but kind. Beside her a village grandmother and a "
 "little girl kneel on the bed, hands outstretched, and the little girl hugs one half of the quilt. Warm orange "
 "lamp light from an oil lamp on a small wooden table, a clay teapot, paper cut-outs on the paper window, snow "
 "falling outside the window. In the soft shadowed corner, a present-day girl in a red neckerchief sits reading a "
 "big picture book that shows this very room as a small illustration. Tender and moving."
) + SAFE + STYLE

T['07_遵义的红灯'] = NOTEXT + (
 " A two-storey grey-brick traditional Chinese building with dark tiled eaves and a small wooden balcony, standing "
 "under a deep night sky on an old stone-paved street, framed by a large old locust tree. On the upper floor one "
 "single window glows with warm golden lamplight while all the other windows are dark; a long soft beam of light "
 "slants out from that window across the whole composition and lands on the open pages of a big book held by a "
 "present-day boy wearing a red neckerchief, who sits on the stone steps below reading by that borrowed light, "
 "beside him a red paper lantern. A curl of red ribbon flows through the air. Quiet, mysterious, hopeful, "
 "emphasising the single guiding light."
) + SAFE + STYLE

T['08_宝塔山下的读书声'] = NOTEXT + (
 " A sunny Yan'an hillside with yellow earth cave dwellings carved in tiers into the loess slope and a tall "
 "nine-tier pagoda on the mountain top silhouetted against a bright morning sky. On a flat terrace in front of the "
 "caves, a group of children of the children's corps in small grey uniforms and red neckerchiefs sit cross-legged "
 "in a circle on the ground, each holding a small homemade book, while a teenage instructor stands at a small "
 "blackboard on a wooden stand pointing with a stick. Washing hangs on a line, corn cobs hang from the eaves, a "
 "few chickens peck on the ground, the river curves through the valley below with golden sunlight rippling across "
 "it. Cheerful, studious, full of hope."
) + SAFE + STYLE

T['09_红种子长成书树'] = NOTEXT + (
 " A miracle tree with a broad trunk and a crown made entirely of hundreds of colourful books instead of leaves, "
 "growing at the top of a green hill. At the roots of the tree lies a tiny red five-pointed-star-shaped seed "
 "sprouting, and the trunk shows the running chain of a long march carved into the bark as a winding path with tiny "
 "figures. Under the tree a present-day girl in a white shirt and red neckerchief and a fluffy black-and-white "
 "giant panda sit together on a picnic mat reading, one book falling open releasing a flock of glowing golden "
 "birds. Fallen books and red maple leaves on the grass, a long red ribbon tied around the trunk, warm afternoon "
 "sunlight streaming through the book-leaves."
) + SAFE + STYLE

T['10_书页升起长征星图'] = NOTEXT + (
 " Night on a quiet hillside, a present-day boy wearing a red neckerchief sits on a folding stool beside a small "
 "camping lantern, holding an open book. From the open pages rise luminous golden constellations that float into "
 "the deep blue starry sky, where the stars themselves are arranged to form a vast winding route map with tiny "
 "glowing landmarks along it: a little red boat, a stone bridge over a river, a snow-capped mountain, a marsh, "
 "and a tall pagoda silhouetted on a hill; at the end of the route the stars cluster into the shape of one large "
 "five-pointed red star directly above the boy. A red scarf of ribbon lifts from the book into the sky like a "
 "trail. Silhouetted pine trees frame the edges, fireflies below, Milky Way brilliance above."
) + SAFE + STYLE


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": "2304x1728", "n": 1, "watermark": False},
                timeout=240)
            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(5)
    print(f"FAIL {name}", flush=True)
    return None


if __name__ == '__main__':
    with ThreadPoolExecutor(max_workers=6) as ex:
        res = list(ex.map(lambda kv: gen(*kv), T.items()))
    ok = [r for r in res if r]
    print(f"\nDONE {len(ok)}/{len(T)}")
    for r in res:
        print(r)
