#!/usr/bin/python3.12
"""批量重生成 vehicle_hotspots 小尺寸图（<600px 一律豆包重生成 1280x720）"""
import json, urllib.request, os, re, 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"

path = '/data/news/json/yes_data/0827data.json'
img_dir = '/data/news/images/0828/'
d = json.load(open(path))

targets = []
for s in d:
    if s.get('name') != 'vehicle_hotspots':
        continue
    for idx, it in enumerate(s.get('list', [])):
        targets.append((idx, it))

print(f'共 {len(targets)} 张需重生成')

def gen(idx, it):
    title = it.get('title', '')
    summary = it.get('summary', '')
    # 清理标题末尾热度值
    clean_title = re.sub(r'\s*\d[\d,.]*\s*万(?:热度)?\s*$', '', title)
    # 清理摘要异常内容
    bad_kw = ['环境异常', '验证码', '反爬']
    if any(k in summary for k in bad_kw):
        summary = ''
    # 简化 prompt：去掉中文引号、不用16:9
    prompt = f"配图：{clean_title}，{summary[:60]}，新闻配图风格，写实，横向构图，高清"
    prompt = prompt.replace('"', '').replace('“', '').replace('”', '')
    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")
    fname = f'vehicle_hotspots_{idx}.jpg'
    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())
    it['thumb'] = f'/images/0828/{fname}'
    print(f'  ✅ [{idx}] {clean_title[:30]} -> {local_path} ({os.path.getsize(local_path)}B)')

for idx, it in targets:
    try:
        gen(idx, it)
    except Exception as e:
        print(f'  ❌ [{idx}] 失败: {e}')
        time.sleep(3)
    time.sleep(2)

json.dump(d, open(path, 'w'), ensure_ascii=False, indent=2)
print('✅ 全部完成，已更新 yes_data thumb')
