# -*- coding: utf-8 -*-
"""用补边后的海报重出线条图 + 叠加空心标题"""
import base64, io, json, os, re, time, requests
from PIL import Image, ImageDraw, ImageFont
CFG = json.load(open('/data/www/files/LhyjdesignPro/config.json'))
KEY, BASE, MODEL = CFG['api_key'], CFG['base_url'], CFG['models']['image_gen']
D = '/data/www/files/pandaReadArt/convert'
FONT = '/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc'
REF = os.path.join(D, '00_海报本体_补边.jpg')

NOTEXT = (" Absolutely NO TEXT anywhere: no letters, no Chinese characters, no numbers, no calligraphy, no "
          "captions, no titles, no labels, no writing on any plaque, sign, banner, monument or flag, no logos, no "
          "watermarks, no signature, no seals. Every plaque, sign and banner must be blank. ")
KEEP = (" Keep exactly: the thick wavy red ribbon border; the yellow five-pointed star with a red outline in the "
        "bottom-left corner; the red and white swirling clouds along the bottom; the light blue sky with white "
        "clouds and small red stars; the two white doves; the four cartoon child soldiers in blue uniforms with "
        "red collar tabs and caps with red stars marching along a yellow path, the leading boy carrying a large "
        "red flag; the girl with pigtails and the other two boys; the three-arch grey stone bridge over the blue "
        "river; the winding yellow path up the green hill with small red flags planted along it; and the tall "
        "white monument on the hilltop. The white monument must be completely PLAIN with no marks or writing. ")
LINE = (" Convert this exact poster into a pure black-and-white LINE DRAWING for a children's colouring template. "
        "Keep EXACTLY the same shapes, positions, proportions, number of objects and composition — do not add, "
        "remove, move or redraw anything. Uniform bold black outlines only on a pure white background: no colour, "
        "no grey tones, no shading, no cross-hatching, no stippling, no gradients, no filled dark areas — every "
        "region left pure white with clean closed outlines. Draw the ribbon border, the bottom clouds and the "
        "corner star as simple black outlines too. On the red flag draw the emblem as a plain round white circle "
        "containing a neat symmetrical hammer and sickle with a straight handle and a clearly curved crescent "
        "blade in clean black lines. Leave the upper sky empty for a title. ") + KEEP + NOTEXT


def call(prompt, size, strength, name, retries=3):
    b64 = base64.b64encode(open(REF, 'rb').read()).decode()
    for a in range(retries):
        try:
            r = requests.post(f"{BASE}/images/generations",
                headers={"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"},
                json={"model": MODEL, "prompt": prompt, "size": size, "n": 1, "watermark": False,
                      "image": f"data:image/jpeg;base64,{b64}", "strength": strength}, timeout=300)
            d = r.json()
            if d.get('data'):
                img = Image.open(io.BytesIO(requests.get(d['data'][0]['url'], timeout=200).content)).convert('RGB')
                p = os.path.join(D, name)
                img.save(p, quality=95, subsampling=0)
                print(f'OK {name} s={strength} {os.path.getsize(p)/1024/1024:.2f}MB', flush=True)
                return p
            print(f'ERR #{a}: {json.dumps(d, ensure_ascii=False)[:200]}', flush=True)
        except Exception as e:
            print(f'EXC #{a}: {e}', flush=True)
        time.sleep(6)
    return None


def add_hollow_title(path, title='长征胜利90周年'):
    im = Image.open(path).convert('RGB')
    W, H = im.size
    d = ImageDraw.Draw(im)
    base = int(H * 0.082)
    segs = re.findall(r'\d+|\D+', title)
    fonts, widths = [], []
    for s in segs:
        f = ImageFont.truetype(FONT, int(base * 1.45) if s.isdigit() else base)
        fonts.append(f)
        widths.append(d.textbbox((0, 0), s, font=f, anchor='ls')[2])
    gap = int(base * 0.06)
    x = (W - (sum(widths) + gap * (len(segs) - 1))) / 2
    y = int(H * 0.145)
    for s, f, wd in zip(segs, fonts, widths):
        d.text((x, y), s, font=f, fill=(255, 255, 255), anchor='ls',
               stroke_width=max(3, base // 12), stroke_fill=(20, 20, 20))
        x += wd + gap
    im.save(path, quality=95, subsampling=0)
    print('TITLE ok')


p = call(LINE, '2400x1700', 0.6, '03_线条图.jpg')
if p:
    add_hollow_title(p)
