# -*- coding: utf-8 -*-
"""加强版：07 遵义的红灯 / 09 红种子长成书树"""
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/pandaReadArt/anniv10'

NOTEXT = ("Absolutely NO TEXT anywhere in the image. No Chinese characters, no letters, no words, no numbers, "
          "no calligraphy, no writing on banners, 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. ")
RED = (" Prominent bright Chinese red accents used as the main colour accent: a large waving red flag with a "
       "golden five-pointed star, several glowing red five-pointed stars, red silk ribbons, and red lanterns. "
       "These red revolutionary symbols must be large and clearly visible. ")

T = {}

T['07_遵义的红灯'] = NOTEXT + (
 " Night scene in front of a historic two-storey grey-brick building with dark tiled eaves, arched windows and a "
 "small wooden balcony, standing on an old stone-paved street under a large old locust tree. A tall bright red "
 "flag waves from the roof of the building and a large glowing red five-pointed star is mounted above its entrance "
 "doorway; a row of red paper lanterns hangs along the eaves. One single upper window blazes with warm golden "
 "lamplight while all other windows are dark; a long soft beam of light slants out of that window across the whole "
 "composition and falls exactly on the open pages of a big picture book held by a present-day boy wearing a red "
 "neckerchief, who sits on the stone steps below reading by that borrowed light. Red silk ribbons curl through the "
 "air, mists drift across the street, distant hills behind. Quiet, mysterious and hopeful, emphasising the single "
 "guiding light of revolution."
) + RED + SAFE + STYLE

T['09_红种子长成书树'] = NOTEXT + (
 " A miraculous giant tree on a green hill whose crown is made entirely of hundreds of colourful books instead of "
 "leaves, with a tall bright red flag with a golden five-pointed star flying at its very top. The wide trunk is "
 "carved with a long winding mountain path on which tiny heroic figures in grey-green uniforms with red-star caps "
 "march upward in a line, and glowing red five-pointed stars are set along that carved path. At the roots lies a "
 "small red five-pointed-star-shaped seed sprouting into a green shoot. A long red silk ribbon is tied around the "
 "trunk, streaming in the wind. Under the tree, a present-day girl in a white shirt and red neckerchief reads "
 "together with a fluffy black-and-white giant panda that also wears a red neckerchief, sitting on a picnic mat; "
 "one open book releases a flock of glowing golden birds. Fallen books and red maple leaves on the grass, warm "
 "afternoon sunlight streaming through the book-leaves, a red star pattern of light on the ground."
) + RED + 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)
    return None


if __name__ == '__main__':
    from concurrent.futures import ThreadPoolExecutor
    with ThreadPoolExecutor(max_workers=2) as ex:
        print(list(ex.map(lambda kv: gen(*kv), T.items())))
