#!/usr/bin/env python3.12
"""豆包重生成 social[1]民企出海 / social[2]SpaceX 配图（内容不匹配）"""
import json, re, urllib.request, os, 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/0831'

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

# 针对性场景 prompt（标题+行业场景，不含中文引号和16:9字面量）
targets = [
    ('social_hotspots', 1, 'social_hotspots_1.jpg',
     '配图：中国民营企业出口贸易，海关港口集装箱货轮出海场景，外贸物流，新闻配图风格，写实，横向构图，高清'),
    ('social_hotspots', 2, 'social_hotspots_2.jpg',
     '配图：SpaceX火箭发动机涡轮叶片，AI数据中心供电设施，太空科技工业，新闻配图风格，写实，横向构图，高清'),
]

yes = json.load(open('/data/news/json/yes_data/0830data.json'))
for name, idx, fname, prompt in targets:
    print(f"[{name}][{idx}] 生成 {fname} ...", flush=True)
    try:
        path = gen_image(prompt, fname)
        print(f"  OK {path} ({os.path.getsize(path)} bytes)", flush=True)
    except Exception as e:
        print(f"  FAIL {e}", flush=True)
    time.sleep(1)

print("✅ 完成")
