#!/usr/bin/python3.12
"""批量豆包重生成 0817 不合格配图（9张，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"
IMG_DIR = "/data/news/images/0818/"

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'})
    for attempt in range(3):
        try:
            with urllib.request.urlopen(req, timeout=120) as r:
                result = json.loads(r.read().decode('utf-8'))
            img_url = result.get('data', [{}])[0].get('url', '')
            if not img_url:
                raise Exception("豆包未返回图片URL")
            img_req = urllib.request.Request(img_url, headers={'User-Agent': 'Mozilla/5.0'})
            with urllib.request.urlopen(img_req, timeout=60) as ir:
                data = ir.read()
            local_path = os.path.join(IMG_DIR, fname)
            with open(local_path, 'wb') as f:
                f.write(data)
            return len(data)
        except Exception as e:
            print(f"  ⚠️ 尝试{attempt+1}失败: {e}")
            time.sleep(5)
    return 0

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

# 读取 yes_data 获取标题/摘要
d = json.load(open('/data/news/json/yes_data/0817data.json'))
def find_item(sect, idx):
    for s in d:
        if s.get('name') == sect:
            return s['list'][idx]
    return None

# (板块, idx, 文件名)
targets = [
    ("brand_hotspots", 4, "brand_hotspots_4.jpg"),
    ("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"),
    ("vehicle_hotspots", 4, "vehicle_hotspots_4.jpg"),
    ("social_hotspots", 0, "social_hotspots_0.jpg"),
    ("social_hotspots", 3, "social_hotspots_3.jpg"),
    ("social_hotspots", 4, "social_hotspots_4.jpg"),
]

for sect, idx, fname in targets:
    it = find_item(sect, idx)
    if not it:
        print(f"❌ 找不到 {sect}[{idx}]")
        continue
    title = clean_title(it.get('title', ''))
    summary = it.get('summary', '')
    # 清理摘要中的反爬内容
    for bad in ['环境异常', '验证码', '页面加载异常', '加载失败', '反爬']:
        if bad in summary:
            summary = ''
            break
    prompt = f"配图：{title}，{summary[:60]}，新闻配图风格，写实，横向构图，16:9，高清"
    print(f"🖼️  {sect}[{idx}] {fname}: {title[:30]}")
    size = gen_image(prompt, fname)
    if size > 0:
        print(f"  ✅ 生成成功 {size}B")
    else:
        print(f"  ❌ 生成失败")
    time.sleep(2)

print("\n✅ 批量生成完成")
