import requests
import json
import time
from PIL import Image
import numpy as np
import io

url = "https://api.acedata.cloud/openai/images/generations"

headers = {
    "accept": "application/json",
    "authorization": "Bearer 3a3b982990c44fc5ba5428320d72330e",
    "content-type": "application/json"
}

prompt = """A single luxurious 3D Token coin/currency symbol icon on pure white background. The token symbol is a hexagonal golden coin with the letter 'T' in the center, surrounded by a glowing circular ring of binary code and neural network patterns. The coin has a metallic gold and cyan gradient, with subtle holographic shimmer effects, microchip circuit lines etched on the rim, and a soft glowing aura. Style: 3D rendered, ultra-detailed, photorealistic, premium fintech/AI icon design, no text labels, single object only, perfect for app icon or logo usage, isolated on pure white background only."""

payload = {
    "model": "gpt-image-2",
    "prompt": prompt,
    "size": "1024x1024"
}

print("正在调用 gpt-image-2 API 生成 Token 货币符号...")
response = requests.post(url, json=payload, headers=headers)
result = response.json()
print(f"响应状态: {response.status_code}")

if response.status_code == 200 and 'data' in result and len(result['data']) > 0:
    img_url = result['data'][0].get('url')
    print(f"图片URL: {img_url}")

    img_response = requests.get(img_url)
    if img_response.status_code == 200:
        # 用 PIL 加载图片
        img = Image.open(io.BytesIO(img_response.content)).convert('RGBA')
        print(f"原始图片尺寸: {img.size}, 模式: {img.mode}")

        # 转换为 numpy 数组
        data = np.array(img)

        # 将白色背景转换为透明
        # 设定阈值为接近白色的像素
        threshold = 240
        r, g, b, a = data[:,:,0], data[:,:,1], data[:,:,2], data[:,:,3]

        # 创建白色掩码
        white_mask = (r > threshold) & (g > threshold) & (b > threshold)

        # 将白色像素设为透明
        data[:,:,3] = np.where(white_mask, 0, 255)

        # 创建新图片
        img_transparent = Image.fromarray(data, 'RGBA')

        # 保存透明 PNG
        timestamp = int(time.time())
        filename = f"token-coin-transparent-{timestamp}.png"
        filepath = f"/var/www/html/share/{filename}"
        img_transparent.save(filepath, 'PNG')

        print(f"\n✅ 透明PNG已保存: {filepath}")
        print(f"访问地址: http://43.156.179.74/share/{filename}")
        print(f"文件大小: {len(img_response.content)} bytes")

        # 同时保存原图（白底）作为参考
        filename_white = f"token-coin-whitebg-{timestamp}.png"
        filepath_white = f"/var/www/html/share/{filename_white}"
        with open(filepath_white, 'wb') as f:
            f.write(img_response.content)
        print(f"\n原图（白底）: http://43.156.179.74/share/{filename_white}")
else:
    print(f"错误响应: {json.dumps(result, indent=2, ensure_ascii=False)[:1000]}")