# -*- coding: utf-8 -*-
"""第2步：以中等难度线条图为参考，按各主题配色方案生成配色图（图生图 strength=0.6）"""
import base64, glob, json, os, sys, 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']
SRC = '/data/www/files/pandaReadArt/lineart_mid5'
OUT = '/data/www/files/pandaReadArt/color_mid5'
os.makedirs(OUT, exist_ok=True)

BASE_INSTR = ("Create the watercolour COLOURED version of this exact line drawing, painted in the style of a "
              "schoolchild's watercolour painting. Keep EXACTLY the same shapes, positions, proportions and "
              "composition — do not add, remove, move or redraw any element. Simply fill the outlined areas with "
              "clean transparent flat watercolour washes that stay neatly inside the black outlines, with the "
              "black outlines still clearly visible on top. Gentle layered washes, soft transparent pooling, "
              "visible watercolour paper grain. NO text of any kind, no letters, no characters, no numbers, no "
              "signature, no watermark, no stamp. Keep it simple and neatly painted — no heavy shading, no dark "
              "rendering, no gradients into black. ")

COLORS = {
 'A_马灯下的接力': " Colour scheme: deep blue-violet night sky with a pale cream crescent moon and pale yellow stars; "
                   "black-violet silhouette mountain and distant tents; middle-distance grass in muted blue-green; "
                   "near grass tufts in warm yellow-green with small red and yellow wildflowers; the wooden post in "
                   "warm brown; the oil lantern body warm ochre glass glowing pale yellow with a visible warm halo "
                   "around it; the girl's shirt white, her neckerchief pure bright red, her hair black-brown; the "
                   "boy's cap and uniform faded grey-green with a red star on the cap, his shoulder bag brown; the "
                   "open book's pages pale cream; fireflies pale yellow; the two ribbons in the sky pure red.",
 'B_遵义的红灯': " Colour scheme: night sky deep blue-violet with a few pale stars; brick walls of the building "
                 "blue-grey, roof tiles dark slate grey; the star ornament above the door and all the hanging "
                 "lanterns pure bright red, glowing warm; the flag on the roof pure red with visible folds; the "
                 "single lit window glowing warm yellow with the long light beam tinted pale warm cream across the "
                 "scene; the tree trunk brown with a deep green leaf crown; stone paving warm light grey with pale "
                 "blue shadow lines; the boy's shirt white, his neckerchief bright red, hair dark brown; the small "
                 "ground lantern warm red.",
 'C_飞夺泸定桥': " Colour scheme: sky soft blue with white and pale grey clouds, warm golden light rays; the two "
                 "mountains cool grey-green with paler misty bands and dark green pine trees; the iron chains dark "
                 "grey against the light; the river below turquoise-green with white water ripples and spray; the "
                 "soldiers' uniforms faded grey-green with red stars on their caps; the flag pure bright red; the "
                 "big book on the rock in the lower left with pale cream pages; the rock warm grey-brown.",
 'D_宝塔山下的读书声': " Colour scheme: sky light clear blue with white clouds and a pale yellow sun; the loess "
                       "hillside warm golden ochre with slightly deeper ochre lines for the terraces; the cave "
                       "dwelling doorways deep warm brown with pale wood door frames; the pagoda warm ochre with "
                       "dark brown eaves; the blackboard surface blank dark green-black with a wooden frame; the "
                       "children's clothing pale grey and pale blue with pure bright red neckerchiefs, hair dark; "
                       "the corn cobs warm yellow; the river pale blue with white ripples; the chickens white and "
                       "warm brown; the clothes on the line pale blue and white.",
 'E_红种子长成书树': " Colour scheme: sky pale blue with white clouds and a pale yellow sun; hills soft green; the "
                     "tree trunk warm brown; the crown made of stacked books in cheerful assorted colours (red, "
                     "blue, green, yellow, orange, purple) painted as flat front covers; the flag on the topmost "
                     "book pure bright red; the small lanterns among the books red and yellow; the winding path up "
                     "the trunk pale tan with the tiny marching figures in grey-green and red-star caps; the star "
                     "shapes along the path bright red; the ribbon around the trunk pure red; the picnic mat a "
                     "cheerful red-and-cream check pattern; the girl's shirt white with a bright red neckerchief "
                     "and dark brown hair; the panda black and white with a bright red neckerchief; scattered books "
                     "in assorted colours; fallen leaves warm orange.",
}


def colorize(path, strength=0.6):
    name = os.path.basename(path)
    key = name.rsplit('.', 1)[0]
    prompt = BASE_INSTR + COLORS.get(key, '')
    b64 = base64.b64encode(open(path, 'rb').read()).decode()
    for a in range(3):
        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,
                      "image": f"data:image/jpeg;base64,{b64}", "strength": strength}, 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}  s={strength}  {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__':
    strength = float(sys.argv[1]) if len(sys.argv) > 1 else 0.6
    names = sys.argv[2:]
    files = sorted(glob.glob(os.path.join(SRC, '*.jpg')))
    if names:
        files = [f for f in files if any(n in os.path.basename(f) for n in names)]
    with ThreadPoolExecutor(max_workers=5) as ex:
        print(list(ex.map(lambda f: colorize(f, strength), files)))
