#!/usr/bin/python3.12
"""为黄仁勋 AGI 条目生成配图（豆包 1280x720）"""
import json, urllib.request, os, re

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/0828data.json'
img_dir = '/data/news/images/0828/'
d = json.load(open(path))

it = d['social_hotspots'][2]
title = it.get('title', '')
summary = it.get('summary', '')
clean_title = re.sub(r'\s*\d[\d,.]*\s*万(?:热度)?\s*$', '', title)
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 = 'social_hotspots_2.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())
print(f'✅ 配图已生成: {local_path} ({os.path.getsize(local_path)}B)')

# 更新最终文件 thumb
d['social_hotspots'][2]['thumb'] = f'/images/0828/{fname}'
json.dump(d, open(path, 'w'), ensure_ascii=False, indent=2)

# 同步 yes_data
path_yd = '/data/news/json/yes_data/0827data.json'
yd = json.load(open(path_yd))
for s in yd:
    if s.get('name') == 'social_hotspots' and len(s.get('list', [])) > 2:
        s['list'][2]['thumb'] = f'/images/0828/{fname}'
        break
json.dump(yd, open(path_yd, 'w'), ensure_ascii=False, indent=2)
print('✅ thumb 已同步（最终文件 + yes_data）')
