# -*- coding: utf-8 -*-
"""黑板报底图质检：结构性质询（不问'是否体现主题'）"""
import base64, json, os, sys, glob, requests
from concurrent.futures import ThreadPoolExecutor

CFG = json.load(open('/data/www/files/LhyjdesignPro/config.json'))
API_KEY, BASE = CFG['api_key'], CFG['base_url']
VM = CFG['models']['text_vision']
D = sys.argv[1] if len(sys.argv) > 1 else '/data/www/files/heibanbaoArt/chalk'

Q = (
"请只描述你看到的事实，不做评价，逐条回答：\n"
"1) 这张图整体是什么？（黑板报版式／海报／教室照片／其他）底色是什么颜色？线条是不是粉笔质感？\n"
"2) 画面里有没有出现任何文字、汉字、字母、数字、印章、水印、伪文字？有就原样写出来在什么位置；没有就写「无」。\n"
"3) 画面里有几个用于写字的框／空白区域？分别是什么形状、在画面什么位置？里面是不是完全空的？\n"
"4) 画面的主要插画元素有哪些？逐个列出。\n"
"5) 画面里有没有元素悬空、形体断裂、人物手臂与身体断开、或者明显的 AI 硬伤？\n"
"6) 画面顶部大约五分之一区域是空的吗？顶部有没有画标题、框线或大块装饰？\n")

def qa(p):
    b64 = base64.b64encode(open(p, 'rb').read()).decode()
    for a in range(3):
        try:
            r = requests.post(f"{BASE}/chat/completions",
                headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
                json={"model": VM, "messages": [{"role": "user", "content": [
                    {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64}"}},
                    {"type": "text", "text": Q}]}], "temperature": 0.1}, timeout=300)
            t = r.json()['choices'][0]['message']['content']
            return os.path.basename(p), t
        except Exception as e:
            print('EXC', p, a, e, flush=True)
    return os.path.basename(p), 'FAIL'

if __name__ == '__main__':
    files = sorted(glob.glob(os.path.join(D, '*.jpg')))
    with ThreadPoolExecutor(max_workers=5) as ex:
        for n, t in ex.map(qa, files):
            print('\n' + '=' * 70 + f'\n【{n}】\n{t}', flush=True)
