# -*- coding: utf-8 -*-
"""① 边缘细查：左/底/上/右四条边缘条放大后判读  ② AI重绘版修正重出"""
import base64, io, json, os, time, requests
from PIL import Image
from concurrent.futures import ThreadPoolExecutor

CFG = json.load(open('/data/www/files/LhyjdesignPro/config.json'))
KEY, BASE, MODEL = CFG['api_key'], CFG['base_url'], CFG['models']['image_gen']
VIS = CFG['models']['text_vision']
D = '/data/www/files/pandaReadArt/convert'
crop = Image.open(os.path.join(D, '00_海报本体_裁切.jpg'))
W, H = crop.size
print('crop', crop.size)

# ---- 边缘条 ----
strips = {
 'left': crop.crop((0, 0, 26, H)),
 'bottom': crop.crop((0, H - 14, W, H)),
 'top': crop.crop((0, 0, W, 14)),
 'right': crop.crop((W - 26, 0, W, H)),
}
paths = {}
for k, s in strips.items():
    if k in ('left', 'right'):
        s = s.resize((s.width * 6, s.height // 3), Image.LANCZOS)
    else:
        s = s.resize((s.width // 3, s.height * 6), Image.LANCZOS)
    p = os.path.join(D, f'_strip_{k}.jpg')
    s.save(p, quality=95)
    paths[k] = p


def img(p):
    return {"type": "image_url",
            "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(open(p, 'rb').read()).decode()}}


def vis(q, ps):
    msgs = [{"role": "user", "content": [img(p) for p in ps] + [{"type": "text", "text": q}]}]
    r = requests.post(f"{BASE}/chat/completions",
        headers={"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"},
        json={"model": VIS, "messages": msgs, "max_tokens": 300}, timeout=200).json()
    return r.get('choices', [{}])[0].get('message', {}).get('content', 'ERR')


print('\n--- 边缘条判读 ---')
print('LEFT  :', vis("这一竖向细条放大图来自海报左边缘。它显示的是什么？(A)红色飘带边框本身 (B)手机界面/状态栏/桌面等非海报内容。"
                    "只回答 A 或 B，并简述看到的颜色与形状。", [paths['left']]).strip().replace('\n', ' '))
print('BOTTOM:', vis("这一横向细条放大图来自海报下边缘。它显示的是什么？(A)海报底部图案（卷云/边框） (B)桌面/木架等非海报内容。"
                    "只回答 A 或 B，并简述看到的颜色与形状。", [paths['bottom']]).strip().replace('\n', ' '))
print('TOP   :', vis("这一横向细条放大图来自海报上边缘。它显示的是什么？(A)海报顶部图案（天空/边框） (B)手机界面/状态栏等非海报内容。"
                    "只回答 A 或 B，并简述看到的颜色与形状。", [paths['top']]).strip().replace('\n', ' '))
print('RIGHT :', vis("这一竖向细条放大图来自海报右边缘。它显示的是什么？(A)红色飘带边框本身 (B)手机界面/桌面等非海报内容。"
                    "只回答 A 或 B，并简述看到的颜色与形状。", [paths['right']]).strip().replace('\n', ' '))

# ---- 重出重绘版（修正党徽 / 纪念碑乱码 / 飘带变形） ----
REDRAW2 = (" Faithfully reproduce this exact children's poster as a clean high-quality version, preserving the same "
 "composition, layout, number of objects and positions. Bold uniform black outlines with flat bright marker "
 "colouring, no shading, no gradients. Keep: 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. CRITICAL FIXES: the flag's white circular emblem must contain a clean symmetrical hammer and sickle — "
 "a hammer with a straight handle and a sickle with a clearly curved crescent blade crossing each other, nothing "
 "else inside the circle, no extra star. The tall white monument must be completely PLAIN and SMOOTH with "
 "absolutely no marks, no lines and no writing on it. The thick wavy red ribbon border must be one clean smooth "
 "continuous wave with no deformation. Leave the sky in the upper area completely empty for a title. 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. ")


def gen(prompt, strength, name, retries=3):
    b64 = base64.b64encode(open(os.path.join(D, '00_海报本体_裁切.jpg'), '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": "2400x1700", "n": 1, "watermark": False,
                      "image": f"data:image/jpeg;base64,{b64}", "strength": strength}, timeout=300)
            d = r.json()
            if d.get('data'):
                im = Image.open(io.BytesIO(requests.get(d['data'][0]['url'], timeout=200).content)).convert('RGB')
                p = os.path.join(D, name)
                im.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 {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(6)
    return None


print()
gen(REDRAW2, 0.30, '02_AI重绘高清版.jpg')
