#!/usr/bin/env python3.12
"""批量豆包重生成不合格图（2026-08-30）"""
import json, re, urllib.request, os, sys, time

API_KEY = "ark-563a4210-d804-47fa-a37a-40962192119b-ce6db"
API_URL = "https://ark.cn-beijing.volces.com/api/v3/images/generations"
MODEL = "doubao-seedream-4-0-250828"

YES = "/data/news/json/yes_data/0830data.json"
IMG_DIR = "/data/news/images/0831"

def clean_title(t):
    t = re.sub(r'\s*\d[\d,.]*\s*万(?:热度)?\s*$', '', t)
    return t

def gen_image(prompt, fname):
    payload = json.dumps({
        "model": MODEL,
        "prompt": prompt,
        "size": "1280x720",
        "n": 1,
        "response_format": "url"
    }).encode()
    req = urllib.request.Request(API_URL, data=payload,
        headers={'Authorization': f'Bearer {API_KEY}', 'Content-Type': 'application/json'})
    resp = urllib.request.urlopen(req, timeout=120)
    result = json.loads(resp.read().decode('utf-8'))
    img_url = result.get('data', [{}])[0].get('url', '')
    if not img_url:
        raise Exception("豆包未返回图片URL")
    local_path = os.path.join(IMG_DIR, fname)
    img_req = urllib.request.Request(img_url, headers={'User-Agent': 'Mozilla/5.0'})
    img_resp = urllib.request.urlopen(img_req, timeout=60)
    with open(local_path, 'wb') as f:
        f.write(img_resp.read())
    return local_path

def main():
    d = json.load(open(YES))
    targets = [
        ('vehicle_hotspots', 0, 'vehicle_hotspots_0.jpg'),
        ('vehicle_hotspots', 1, 'vehicle_hotspots_1.jpg'),
        ('vehicle_hotspots', 2, 'vehicle_hotspots_2.jpg'),
        ('vehicle_hotspots', 3, 'vehicle_hotspots_3.jpg'),
        ('social_hotspots', 0, 'social_hotspots_0.jpg'),
        ('social_hotspots', 4, 'social_hotspots_4.jpg'),
    ]
    for name, idx, fname in targets:
        for s in d:
            if s.get('name') == name:
                it = s['list'][idx]
                t = clean_title(it.get('title',''))
                summary = it.get('summary','')
                if any(k in summary for k in ['环境异常','验证码','反爬','未加载']):
                    summary = ''
                prompt = f"配图：{t}，{summary[:60]}，新闻配图风格，写实，横向构图，高清"
                # 避免中文引号和 16:9 字面量
                prompt = prompt.replace('“','').replace('”','').replace('"','')
                print(f"[{name}][{idx}] 生成 {fname} ...", flush=True)
                try:
                    path = gen_image(prompt, fname)
                    size = os.path.getsize(path)
                    print(f"  OK {path} ({size} bytes)", flush=True)
                    it['thumb'] = f'/images/0831/{fname}'
                except Exception as e:
                    print(f"  FAIL {e}", flush=True)
                time.sleep(1)
    json.dump(d, open(YES,'w'), ensure_ascii=False, indent=2)
    print("✅ 已更新 thumb 并保存")

if __name__ == '__main__':
    main()
