#!/usr/bin/env python3.12
# -*- coding: utf-8 -*-
import json, urllib.request, os, re, time
from PIL import Image

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/1104'
JSON_PATH = '/data/news/json/yes_data/1103data.json'

d = json.load(open(JSON_PATH))

def find_item(section, idx):
    for s in d:
        if s.get('name') == section:
            return s['list'][idx]
    return None

targets = [('brand_hotspots', 1, 'brand_hotspots_1.jpg')]

def gen_img(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=180)
    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=90)
    with open(local_path, 'wb') as f:
        f.write(img_resp.read())
    return local_path

for section, idx, fname in targets:
    item = find_item(section, idx)
    title = item.get('title', '')
    summary = item.get('summary', '')
    prompt = (f'配图：{title}，{summary}。画面为陈列在木质货架上的橙子礼盒包装与品牌周边文创产品，'
              f'橙色调，无人物，无文字，商业摄影风格，写实，横向构图，高清')
    try:
        local = gen_img(prompt, fname)
        im = Image.open(local)
        w, h = im.size
        sz = os.path.getsize(local)
        # 裁掉底部60px水印
        if h > 780:
            im2 = im.crop((0, 0, w, h - 60))
            if im2.mode != 'RGB':
                im2 = im2.convert('RGB')
            im2.save(local, 'JPEG', quality=88)
            im = Image.open(local)
        print(f'  OK {section}[{idx}] {fname} {im.size} {os.path.getsize(local)//1024}KB')
        item['thumb'] = f'/images/1104/{fname}'
        json.dump(d, open(JSON_PATH, 'w'), ensure_ascii=False, indent=2)
    except Exception as e:
        print(f'  FAIL {section}[{idx}] {fname}: {e}')
    time.sleep(1)
print('END')
