DeepAi 中文文档 下载 App

DeepAI API Python 与 JavaScript 实战示例

准备工作

在开始写代码之前,你需要:

  1. 一个 DeepAI 账号(免费注册即可)
  2. 一个 API Key(在开发者控制台生成)
  3. Python 环境:pip install requests
  4. Node.js 环境:npm install node-fetch(或用原生 fetch)

Python 示例

示例一:文生图(最简版)

import requests

API_KEY = "YOUR_API_KEY"

r = requests.post(
    "https://api.deepai.org/api/text2img",
    data={
        'text': 'A cinematic shot of a majestic wizard cat holding a glowing crystal, cyberpunk style',
        'image_generator_version': 'hd',
        'width': '1024',
        'height': '1024',
    },
    headers={'api-key': API_KEY}
)

if r.status_code == 200:
    print(f"Image URL: {r.json()['output_url']}")
else:
    print(f"Error {r.status_code}: {r.text}")

示例二:带反向提示词的文生图

import requests

API_KEY = "YOUR_API_KEY"
negative = "bad anatomy, extra fingers, blurry, low quality, watermark, text"

r = requests.post(
    "https://api.deepai.org/api/text2img",
    data={
        'text': 'A beautiful sunset over mountains with purple clouds',
        'image_generator_version': 'hd',
        'width': '1216',
        'height': '832',
        'negative_prompt': negative,
        'grid_size': '2',  # 生成 4 张对比
    },
    headers={'api-key': API_KEY}
)

for result in r.json():
    print(result.get('output_url', result))

示例三:批量生成 + 自动重试 + 结果下载

import requests
import time
import os
from urllib.request import urlretrieve

API_KEY = "YOUR_API_KEY"
OUTPUT_DIR = "deepai_results"
os.makedirs(OUTPUT_DIR, exist_ok=True)

prompts = [
    "A cyberpunk city at night, neon signs, rain",
    "A cute corgi wearing sunglasses, beach background",
    "An astronaut riding a horse on Mars, cinematic",
    "Cherry blossoms in bloom, soft sunlight, dreamy",
]

def call_with_retry(endpoint, data, max_retries=3):
    for i in range(max_retries):
        try:
            r = requests.post(
                f"https://api.deepai.org/api/{endpoint}",
                data=data,
                headers={'api-key': API_KEY},
                timeout=30
            )
            if r.status_code == 200:
                return r.json()
            elif r.status_code == 429:
                print(f"Rate limited, waiting 10s...")
                time.sleep(10)
            else:
                print(f"Error {r.status_code}: {r.text}")
        except requests.exceptions.RequestException as e:
            print(f"Request error: {e}")
            time.sleep(5)
    return None

for i, prompt in enumerate(prompts):
    print(f"Generating {i+1}/{len(prompts)}: {prompt}")
    result = call_with_retry('text2img', {
        'text': prompt,
        'image_generator_version': 'hd',
        'width': '1024',
        'height': '1024',
    })
    if result and 'output_url' in result:
        fname = f"{OUTPUT_DIR}/result_{i}.png"
        urlretrieve(result['output_url'], fname)
        print(f"  Saved to {fname}")
    else:
        print(f"  Failed")

示例四:图像处理流水线(抠图 + 超分)

import requests
import base64

API_KEY = "YOUR_API_KEY"
headers = {'api-key': API_KEY}

# Step 1: 上传本地图片并抠图
with open('product.jpg', 'rb') as f:
    b64 = base64.b64encode(f.read()).decode()

r1 = requests.post(
    "https://api.deepai.org/api/backgroundremover",
    data={'image': f'data:image/jpeg;base64,{b64}'},
    headers=headers
)
transparent_url = r1.json()['output_url']
print(f"Transparent: {transparent_url}")

# Step 2: 超分辨率放大
r2 = requests.post(
    "https://api.deepai.org/api/superresolution",
    data={'image': transparent_url},
    headers=headers
)
final_url = r2.json()['output_url']
print(f"Final: {final_url}")

JavaScript 示例

示例一:浏览器端(fetch)

const API_KEY = 'YOUR_API_KEY';

async function generateImage(prompt) {
    const resp = await fetch('https://api.deepai.org/api/text2img', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'api-key': API_KEY
        },
        body: JSON.stringify({
            text: prompt,
            image_generator_version: 'hd',
            width: 1024,
            height: 1024
        })
    });
    
    if (!resp.ok) {
        throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);
    }
    return (await resp.json()).output_url;
}

// 使用
generateImage('A beautiful mountain landscape at sunrise')
    .then(url => {
        const img = document.createElement('img');
        img.src = url;
        document.body.appendChild(img);
    })
    .catch(err => console.error(err));

示例二:Node.js 端

const https = require('https');
const fs = require('fs');

const API_KEY = 'YOUR_API_KEY';

function deepaiCall(endpoint, data) {
    return new Promise((resolve, reject) => {
        const postData = new URLSearchParams(data).toString();
        const options = {
            hostname: 'api.deepai.org',
            path: `/api/${endpoint}`,
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'api-key': API_KEY,
                'Content-Length': Buffer.byteLength(postData)
            }
        };
        
        const req = https.request(options, res => {
            let body = '';
            res.on('data', chunk => body += chunk);
            res.on('end', () => {
                if (res.statusCode === 200) {
                    resolve(JSON.parse(body));
                } else {
                    reject(new Error(`HTTP ${res.statusCode}: ${body}`));
                }
            });
        });
        
        req.on('error', reject);
        req.write(postData);
        req.end();
    });
}

// 使用示例
deepaiCall('backgroundremover', {
    image: 'https://example.com/product.jpg'
}).then(result => {
    console.log('Background removed:', result.output_url);
}).catch(console.error);

示例三:带进度的批量生成 + 错误重试

const API_KEY = 'YOUR_API_KEY';

async function callWithRetry(endpoint, data, maxRetries = 3) {
    for (let i = 0; i < maxRetries; i++) {
        try {
            const resp = await fetch(`https://api.deepai.org/api/${endpoint}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'api-key': API_KEY
                },
                body: JSON.stringify(data)
            });
            
            if (resp.ok) return await resp.json();
            if (resp.status === 429) {
                await new Promise(r => setTimeout(r, 10000));
                continue;
            }
            throw new Error(`HTTP ${resp.status}`);
        } catch (e) {
            console.log(`Attempt ${i+1} failed: ${e.message}`);
            await new Promise(r => setTimeout(r, 5000));
        }
    }
    return null;
}

async function batchGenerate(prompts) {
    for (let i = 0; i < prompts.length; i++) {
        console.log(`[${i+1}/${prompts.length}] ${prompts[i]}`);
        const result = await callWithRetry('text2img', {
            text: prompts[i],
            image_generator_version: 'hd',
            width: 1024, height: 1024
        });
        if (result?.output_url) {
            console.log(`  URL: ${result.output_url}`);
        } else {
            console.log('  Failed');
        }
    }
}

batchGenerate([
    'A cyberpunk city at night',
    'A cute corgi at the beach',
    'Cherry blossoms in bloom'
]);

最佳实践总结

实践原因
加重试机制(指数退避)网络抖动、速率限制是常态
加请求超时防止网络卡死导致进程永远挂起
结果缓存相同参数不要重复调用
批量处理时控制并发DeepAI 速率限制不明确,建议串行或小并发
每次调用存日志方便调试和统计用量
监控钱包余额避免意外刷爆