Skip to content

ristponex/uncensored-ai-api-guide

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 

Repository files navigation

🔓 Uncensored AI API Guide — Complete Developer Guide to Content-Filter-Free AI Generation

License: MIT Atlas Cloud

A production-ready developer guide for integrating uncensored AI generation APIs — video, image, and text — with real code, real API calls, and real implementation patterns.

Translations: 简体中文 | 日本語 | 한국어

🔒 Enterprise-Grade Security — Atlas Cloud is SOC I & II Certified | HIPAA Compliant | US-based company. Your data and usage are protected by enterprise-grade security standards.


Table of Contents


1. Why Uncensored AI APIs?

Industries That Require Uncensored Generation

Mainstream AI APIs aggressively filter content, but many legitimate industries need unrestricted generation:

Industry Use Case Why Filters Break It
Adult Content Platforms Generate marketing materials, thumbnails, animations Core business requirement
Medical Education Anatomical illustrations, surgical simulations Nudity filters block medical imagery
Fine Art & Photography Nude figure studies, artistic expression Classical art triggers NSFW classifiers
Fiction & Creative Writing Novels, screenplays, mature storytelling Refusal-trained LLMs won't write explicit scenes
Game Development Mature-rated games (M/AO), character design Content policies block character design
Film & Animation Pre-visualization, concept art, storyboards Violence/nudity filters limit creative scope

The Problem with Censored APIs

# 典型的审查API失败案例
prompt = "Renaissance oil painting of Venus emerging from the sea, classical nude figure study"

# OpenAI DALL-E: ❌ "This request was rejected because it may violate our content policy"
# Midjourney: ❌ "Job queued but content filter triggered"
# Stability AI: ❌ Returns blurred/black image

# Atlas Cloud Flux Dev (enable_safety_checker=False): ✅ Full quality output

False positive rates on censored platforms can reach 15-30% for legitimate artistic content, making them unusable for production workflows.

Legal Framework

Uncensored AI generation is legal in most jurisdictions for:

  • Content involving consenting adults (fictional or commissioned)
  • Artistic and educational materials
  • Medical and scientific illustration
  • Creative fiction and storytelling

⚠️ Always comply with local laws. Generation of illegal content (CSAM, non-consensual deepfakes of real individuals, etc.) is prohibited regardless of API restrictions.


2. API Architecture Deep Dive

2.1 How Content Filters Work

Understanding why some APIs are censored helps you choose the right uncensored approach.

Layer 1: Input Prompt Filtering (Pre-Generation)

User Prompt → [Keyword Blocklist] → [Semantic Classifier] → Model
                    ↓ blocked                ↓ blocked
              "Rejected"              "Content policy violation"
  • Keyword blocklists: Simple regex/string matching against banned terms
  • Semantic classifiers: BERT-based models that detect intent even with euphemisms
  • Embedding-space filtering: Measures cosine similarity between prompt embedding and known NSFW prompt clusters

Layer 2: Output Classification (Post-Generation)

Model Output → [CLIP-based NSFW Classifier] → [Custom CNN] → User
                        ↓ flagged                ↓ flagged
                   Blurred/blocked          Blurred/blocked
  • CLIP-based classifiers: Compare generated image embeddings against NSFW concept embeddings (e.g., laion-ai/CLIP-based-NSFW-Detector)
  • Custom CNN classifiers: Trained specifically on NSFW image datasets (nudity detection, violence detection)
  • Multi-stage filtering: Some platforms run 3-4 classifiers in sequence

Layer 3: Model-Level Safety Training

Base Model → [RLHF with safety preference] → Safety-Trained Model
                                                    ↓
                                        "I can't generate that content"
  • RLHF safety alignment: The model itself is trained to refuse certain requests
  • This is the hardest to bypass: The refusal behavior is baked into the model weights
  • Fine-tuning can remove it: Models like Wan 2.2 Spicy are fine-tuned to override safety training

2.2 Atlas Cloud's Approach

Atlas Cloud uses three different technical strategies to provide uncensored content:

Strategy 1: Fine-Tuned NSFW Models (Wan 2.2 Spicy)

Base Wan 2.2 → [LoRA fine-tune on NSFW dataset] → Wan 2.2 Spicy

The model natively generates NSFW content — it's not bypassing a filter; the model itself was trained to produce explicit content. This means:

  • Higher quality NSFW output (the model understands anatomy, poses, lighting for NSFW)
  • No artifacts from filter removal
  • Consistent results across prompts

Strategy 2: Disabling Output Classifiers (Flux Dev)

Flux Dev Generation → [Safety Checker: DISABLED] → Direct Output
                       enable_safety_checker: false

The underlying Flux Dev model can generate any content — Black Forest Labs' safety checker is simply turned off in Atlas Cloud's deployment. You control this via a single parameter:

"enable_safety_checker": False  # 这一个参数就能关闭所有输出过滤

Strategy 3: Whitelisted Accounts (Seedream, Seedance)

Request + API Key → [Whitelist Check] → Content Filter Bypass → Model

For premium models (Seedream v5.0, Seedance v1.5), Atlas Cloud maintains a whitelist. Whitelisted API keys skip the content filter entirely. Contact Atlas Cloud support to get whitelisted.

Strategy 4: Unaligned LLM Deployments (DeepSeek, Qwen)

Atlas Cloud deploys text models without the safety system prompt and with relaxed RLHF alignment, so they don't refuse explicit content requests.


3. Complete API Reference

Prerequisites

# 安装依赖
pip install requests openai aiohttp

# 设置环境变量
export ATLAS_API_KEY="your_atlas_cloud_api_key"

Get your API key: Atlas Cloud Dashboard

3.1 NSFW Video Generation API

Available Models

Model Type Price Resolution Duration NSFW Method
Wan 2.2 Spicy Image-to-Video from $0.03/s 720p 5s Fine-tuned LoRA
Wan 2.5 Text/Image-to-Video from $0.04/s 720p-1080p 5-10s Filter bypass
Wan 2.6 Text/Image-to-Video from $0.05/s 1080p 5-10s Filter bypass
Seedance v1.5 Image-to-Video from $0.06/s 1080p 5-10s Whitelisted
Kling 1.6 Text/Image-to-Video from $0.204/s 1080p 5-10s Whitelisted
Vidu Q3-Pro Text/Image/Start-End-to-Video from $0.06/s 540p-1080p 4-8s Whitelisted
Vidu Q3-Turbo Text/Image/Start-End-to-Video from $0.034/s 540p-1080p 4-8s Whitelisted

⚠️ Note: Vidu Q3 models may add mosaic/blur to certain NSFW scenes due to training data limitations. Not guaranteed 100% uncensored. For reliable uncensored output, use Wan 2.2 Spicy ($0.03) or Wan 2.6 ($0.07).

Python — Wan 2.2 Spicy (Image-to-Video)

import requests
import time
import os

# 初始化API配置
API_KEY = os.getenv("ATLAS_API_KEY", "your_atlas_cloud_api_key")
BASE_URL = "https://api.atlascloud.ai/api/v1/model"
HEADERS = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}


def generate_nsfw_video(image_url, prompt, duration=5, resolution="720p", seed=-1):
    """
    使用Wan 2.2 Spicy生成NSFW视频

    参数:
        image_url: 参考图像URL(建议使用Flux Dev生成的NSFW图像)
        prompt: 动作描述提示词
        duration: 视频时长(秒),支持3-5秒
        resolution: 分辨率,支持 "480p", "720p"
        seed: 随机种子,-1为随机

    返回:
        生成的视频URL
    """
    # 发送生成请求
    response = requests.post(
        f"{BASE_URL}/generateVideo",
        headers=HEADERS,
        json={
            "model": "alibaba/wan-2.2-spicy/image-to-video",
            "image": image_url,
            "prompt": prompt,
            "resolution": resolution,
            "duration": duration,
            "seed": seed
        }
    )
    response.raise_for_status()
    task_id = response.json()["data"]["id"]
    print(f"任务已提交,ID: {task_id}")

    # 轮询获取结果(通常需要60-120秒)
    max_wait = 300  # 最大等待时间(秒)
    elapsed = 0
    while elapsed < max_wait:
        result = requests.get(
            f"{BASE_URL}/result/{task_id}",
            headers=HEADERS
        ).json()

        status = result["data"]["status"]
        if status in ["completed", "succeeded"]:
            video_url = result["data"]["outputs"][0]
            print(f"生成完成!视频URL: {video_url}")
            return video_url
        elif status == "failed":
            error_msg = result["data"].get("error", "未知错误")
            raise Exception(f"生成失败: {error_msg}")
        else:
            print(f"状态: {status},已等待 {elapsed}s...")
            time.sleep(3)
            elapsed += 3

    raise TimeoutError(f"生成超时,已等待 {max_wait}s")


# 使用示例
if __name__ == "__main__":
    video_url = generate_nsfw_video(
        image_url="https://example.com/reference-image.jpg",
        prompt="The woman slowly turns toward camera, soft studio lighting, smooth cinematic movement, high quality",
        duration=5,
        resolution="720p"
    )
    print(f"视频已生成: {video_url}")

Python — Wan 2.6 (Text-to-Video, Higher Quality)

def generate_wan26_video(prompt, resolution="1080p", duration=5, seed=-1):
    """
    使用Wan 2.6生成高质量视频(支持文生视频)

    参数:
        prompt: 详细的场景描述
        resolution: "720p" 或 "1080p"
        duration: 视频时长(秒),支持5或10
        seed: 随机种子

    注意: Wan 2.6比2.2质量更高,但价格也更高($0.05/视频)
    """
    response = requests.post(
        f"{BASE_URL}/generateVideo",
        headers=HEADERS,
        json={
            "model": "alibaba/wan-2.6/text-to-video",
            "prompt": prompt,
            "resolution": resolution,
            "duration": duration,
            "num_inference_steps": 50,  # 更多步数=更高质量
            "guidance_scale": 7.0,      # 控制提示词匹配度
            "seed": seed
        }
    )
    response.raise_for_status()
    task_id = response.json()["data"]["id"]

    # 轮询逻辑(Wan 2.6需要更长时间,约2-4分钟)
    max_wait = 600
    elapsed = 0
    while elapsed < max_wait:
        result = requests.get(
            f"{BASE_URL}/result/{task_id}",
            headers=HEADERS
        ).json()

        status = result["data"]["status"]
        if status in ["completed", "succeeded"]:
            return result["data"]["outputs"][0]
        elif status == "failed":
            raise Exception(f"生成失败: {result['data'].get('error', '未知错误')}")

        time.sleep(5)
        elapsed += 5

    raise TimeoutError("生成超时")


# 使用示例 — 纯文本生成视频
video_url = generate_wan26_video(
    prompt="A beautiful woman in a flowing red dress walks through a sunlit garden, "
           "gentle breeze moving her hair, cinematic lighting, 4K quality, smooth camera tracking",
    resolution="1080p",
    duration=5
)

Python — Seedance v1.5 (Image-to-Video with Audio Sync)

def generate_seedance_video(image_url, prompt, duration=5, seed=-1):
    """
    使用Seedance v1.5生成带音频同步的视频

    参数:
        image_url: 参考图像URL
        prompt: 动作和场景描述
        duration: 视频时长(秒),支持5或10
        seed: 随机种子

    注意: 需要白名单账户才能生成NSFW内容
    价格: $0.06/视频
    """
    response = requests.post(
        f"{BASE_URL}/generateVideo",
        headers=HEADERS,
        json={
            "model": "seedance/seedance-1.5/image-to-video",
            "image": image_url,
            "prompt": prompt,
            "duration": duration,
            "seed": seed
        }
    )
    response.raise_for_status()
    task_id = response.json()["data"]["id"]

    # 轮询获取结果
    max_wait = 600
    elapsed = 0
    while elapsed < max_wait:
        result = requests.get(
            f"{BASE_URL}/result/{task_id}",
            headers=HEADERS
        ).json()

        status = result["data"]["status"]
        if status in ["completed", "succeeded"]:
            return result["data"]["outputs"][0]
        elif status == "failed":
            raise Exception(f"生成失败: {result['data'].get('error')}")

        time.sleep(5)
        elapsed += 5

    raise TimeoutError("生成超时")


# 使用示例
video_url = generate_seedance_video(
    image_url="https://example.com/character-portrait.jpg",
    prompt="Character speaks to camera with natural lip movements, subtle expressions, studio lighting",
    duration=5
)

cURL — Wan 2.2 Spicy

# 步骤1: 提交生成任务
curl -X POST "https://api.atlascloud.ai/api/v1/model/generateVideo" \
  -H "Authorization: Bearer $ATLAS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "alibaba/wan-2.2-spicy/image-to-video",
    "image": "https://example.com/reference.jpg",
    "prompt": "Smooth cinematic movement, soft lighting, the subject turns slowly",
    "resolution": "720p",
    "duration": 5,
    "seed": -1
  }'

# 响应: {"data": {"id": "task_abc123", "status": "processing"}}

# 步骤2: 轮询结果
curl -X GET "https://api.atlascloud.ai/api/v1/model/result/task_abc123" \
  -H "Authorization: Bearer $ATLAS_API_KEY"

# 响应(完成后): {"data": {"status": "succeeded", "outputs": ["https://cdn.atlascloud.ai/video/xxx.mp4"]}}

JavaScript/Node.js — Wan 2.2 Spicy

const axios = require('axios');

const API_KEY = process.env.ATLAS_API_KEY || 'your_atlas_cloud_api_key';
const BASE_URL = 'https://api.atlascloud.ai/api/v1/model';
const headers = {
  'Authorization': `Bearer ${API_KEY}`,
  'Content-Type': 'application/json'
};

/**
 * 使用Wan 2.2 Spicy生成NSFW视频
 * @param {string} imageUrl - 参考图像URL
 * @param {string} prompt - 动作描述
 * @param {number} duration - 视频时长(秒)
 * @param {string} resolution - 分辨率
 * @returns {Promise<string>} 生成的视频URL
 */
async function generateNsfwVideo(imageUrl, prompt, duration = 5, resolution = '720p') {
  // 提交生成任务
  const submitRes = await axios.post(`${BASE_URL}/generateVideo`, {
    model: 'alibaba/wan-2.2-spicy/image-to-video',
    image: imageUrl,
    prompt: prompt,
    resolution: resolution,
    duration: duration,
    seed: -1
  }, { headers });

  const taskId = submitRes.data.data.id;
  console.log(`任务已提交,ID: ${taskId}`);

  // 轮询获取结果
  const maxWait = 300000; // 5分钟
  const startTime = Date.now();

  while (Date.now() - startTime < maxWait) {
    const resultRes = await axios.get(`${BASE_URL}/result/${taskId}`, { headers });
    const status = resultRes.data.data.status;

    if (['completed', 'succeeded'].includes(status)) {
      return resultRes.data.data.outputs[0];
    } else if (status === 'failed') {
      throw new Error(`生成失败: ${resultRes.data.data.error || '未知错误'}`);
    }

    console.log(`状态: ${status},已等待 ${Math.floor((Date.now() - startTime) / 1000)}s`);
    await new Promise(resolve => setTimeout(resolve, 3000));
  }

  throw new Error('生成超时');
}

// 使用示例
(async () => {
  try {
    const videoUrl = await generateNsfwVideo(
      'https://example.com/reference.jpg',
      'Smooth cinematic motion, the subject turns toward camera, soft warm lighting',
      5,
      '720p'
    );
    console.log(`视频已生成: ${videoUrl}`);
  } catch (error) {
    console.error(`错误: ${error.message}`);
  }
})();

3.2 NSFW Image Generation API

Available Models

Model Price Resolution Speed NSFW Method
Flux Dev $0.012/image Up to 2048x2048 ~5s enable_safety_checker: false
Flux Dev LoRA $0.015/image Up to 2048x2048 ~8s Safety checker disabled + custom LoRA
Seedream v5.0 $0.032/image Up to 2048x2048 ~10s Whitelisted accounts

Python — Flux Dev (Uncensored Image Generation)

import requests
import time
import os

API_KEY = os.getenv("ATLAS_API_KEY", "your_atlas_cloud_api_key")
BASE_URL = "https://api.atlascloud.ai/api/v1/model"
HEADERS = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}


def generate_nsfw_image(prompt, negative_prompt="", size="1024*1024",
                        num_inference_steps=28, guidance_scale=3.5, seed=-1):
    """
    使用Flux Dev生成无审查图像

    参数:
        prompt: 图像描述(英文效果最好)
        negative_prompt: 反向提示词(描述不想出现的内容)
        size: 尺寸,支持 "512*512", "768*768", "1024*1024", "1024*1536", "1536*1024", "2048*2048"
        num_inference_steps: 推理步数(20-50,越高质量越好但越慢)
        guidance_scale: 引导比例(1.0-20.0,越高越贴合提示词)
        seed: 随机种子,-1为随机,固定种子可复现结果

    返回:
        生成的图像URL
    """
    response = requests.post(
        f"{BASE_URL}/generateImage",
        headers=HEADERS,
        json={
            "model": "black-forest-labs/flux-dev",
            "prompt": prompt,
            "negative_prompt": negative_prompt,
            "size": size,
            "num_inference_steps": num_inference_steps,
            "guidance_scale": guidance_scale,
            "enable_safety_checker": False,  # 关键参数:关闭安全检查器
            "seed": seed
        }
    )
    response.raise_for_status()
    task_id = response.json()["data"]["id"]

    # 轮询获取结果(图像通常5-15秒完成)
    max_wait = 120
    elapsed = 0
    while elapsed < max_wait:
        result = requests.get(
            f"{BASE_URL}/result/{task_id}",
            headers=HEADERS
        ).json()

        status = result["data"]["status"]
        if status in ["completed", "succeeded"]:
            image_url = result["data"]["outputs"][0]
            return image_url
        elif status == "failed":
            raise Exception(f"生成失败: {result['data'].get('error', '未知错误')}")

        time.sleep(2)
        elapsed += 2

    raise TimeoutError("生成超时")


# 使用示例
if __name__ == "__main__":
    image_url = generate_nsfw_image(
        prompt="Professional studio photograph of a beautiful woman, artistic nude, "
               "rembrandt lighting, fine art photography, high detail, 8K",
        negative_prompt="low quality, blurry, deformed, ugly, watermark",
        size="1024*1536",  # 竖版人像比例
        num_inference_steps=30,
        guidance_scale=4.0
    )
    print(f"图像已生成: {image_url}")

Python — Flux Dev LoRA (Custom NSFW Styles)

def generate_lora_image(prompt, lora_url, lora_scale=0.8, size="1024*1024",
                        num_inference_steps=28, guidance_scale=3.5, seed=-1):
    """
    使用Flux Dev + LoRA生成自定义风格的NSFW图像

    参数:
        prompt: 图像描述
        lora_url: LoRA权重文件的URL(.safetensors格式)
        lora_scale: LoRA强度(0.0-1.0,越高风格越强)
        size: 图像尺寸
        num_inference_steps: 推理步数
        guidance_scale: 引导比例
        seed: 随机种子

    LoRA模型来源:
        - Civitai: https://civitai.com (大量NSFW LoRA)
        - HuggingFace: https://huggingface.co/models
        - 自训练: 使用kohya_ss等工具训练
    """
    response = requests.post(
        f"{BASE_URL}/generateImage",
        headers=HEADERS,
        json={
            "model": "black-forest-labs/flux-dev-lora",
            "prompt": prompt,
            "size": size,
            "num_inference_steps": num_inference_steps,
            "guidance_scale": guidance_scale,
            "enable_safety_checker": False,
            "lora_url": lora_url,        # LoRA权重文件URL
            "lora_scale": lora_scale,    # LoRA强度
            "seed": seed
        }
    )
    response.raise_for_status()
    task_id = response.json()["data"]["id"]

    # 轮询(LoRA加载可能需要更长时间)
    max_wait = 180
    elapsed = 0
    while elapsed < max_wait:
        result = requests.get(
            f"{BASE_URL}/result/{task_id}",
            headers=HEADERS
        ).json()

        status = result["data"]["status"]
        if status in ["completed", "succeeded"]:
            return result["data"]["outputs"][0]
        elif status == "failed":
            raise Exception(f"生成失败: {result['data'].get('error')}")

        time.sleep(3)
        elapsed += 3

    raise TimeoutError("生成超时")


# 使用示例 — 使用动漫风格LoRA
image_url = generate_lora_image(
    prompt="anime girl, detailed face, dynamic pose, vibrant colors, masterpiece",
    lora_url="https://huggingface.co/user/model/resolve/main/anime-style.safetensors",
    lora_scale=0.75,
    size="1024*1536"
)

Python — Seedream v5.0 (Highest Quality NSFW Image)

def generate_seedream_image(prompt, size="1024*1024", seed=-1):
    """
    使用Seedream v5.0生成最高质量NSFW图像

    参数:
        prompt: 图像描述
        size: 图像尺寸
        seed: 随机种子

    注意:
        - 需要白名单账户
        - 价格: $0.032/张
        - 质量最高,适合需要照片级真实感的场景
    """
    response = requests.post(
        f"{BASE_URL}/generateImage",
        headers=HEADERS,
        json={
            "model": "seedream/seedream-5.0",
            "prompt": prompt,
            "size": size,
            "seed": seed
        }
    )
    response.raise_for_status()
    task_id = response.json()["data"]["id"]

    max_wait = 180
    elapsed = 0
    while elapsed < max_wait:
        result = requests.get(
            f"{BASE_URL}/result/{task_id}",
            headers=HEADERS
        ).json()

        status = result["data"]["status"]
        if status in ["completed", "succeeded"]:
            return result["data"]["outputs"][0]
        elif status == "failed":
            raise Exception(f"生成失败: {result['data'].get('error')}")

        time.sleep(3)
        elapsed += 3

    raise TimeoutError("生成超时")


# 使用示例
image_url = generate_seedream_image(
    prompt="Photorealistic portrait, professional studio lighting, high fashion, "
           "detailed skin texture, shallow depth of field, 8K resolution",
    size="1024*1536"
)

Python — Batch Image Generation Script

import asyncio
import aiohttp
import json
from typing import List, Dict

API_KEY = os.getenv("ATLAS_API_KEY")
BASE_URL = "https://api.atlascloud.ai/api/v1/model"
HEADERS = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

# 并发控制:避免触发速率限制
CONCURRENCY_LIMIT = 5
semaphore = asyncio.Semaphore(CONCURRENCY_LIMIT)


async def submit_image_task(session: aiohttp.ClientSession, prompt: str, index: int) -> Dict:
    """提交单个图像生成任务"""
    async with semaphore:
        async with session.post(
            f"{BASE_URL}/generateImage",
            headers=HEADERS,
            json={
                "model": "black-forest-labs/flux-dev",
                "prompt": prompt,
                "size": "1024*1024",
                "num_inference_steps": 28,
                "guidance_scale": 3.5,
                "enable_safety_checker": False,
                "seed": -1
            }
        ) as resp:
            data = await resp.json()
            task_id = data["data"]["id"]
            print(f"[{index}] 任务已提交: {task_id}")
            return {"index": index, "task_id": task_id, "prompt": prompt}


async def poll_result(session: aiohttp.ClientSession, task: Dict) -> Dict:
    """轮询单个任务的结果"""
    task_id = task["task_id"]
    index = task["index"]
    max_wait = 120
    elapsed = 0

    while elapsed < max_wait:
        async with session.get(
            f"{BASE_URL}/result/{task_id}",
            headers=HEADERS
        ) as resp:
            data = await resp.json()
            status = data["data"]["status"]

            if status in ["completed", "succeeded"]:
                url = data["data"]["outputs"][0]
                print(f"[{index}] ✅ 完成: {url[:60]}...")
                return {**task, "status": "success", "url": url}
            elif status == "failed":
                print(f"[{index}] ❌ 失败")
                return {**task, "status": "failed", "url": None}

        await asyncio.sleep(2)
        elapsed += 2

    print(f"[{index}] ⏰ 超时")
    return {**task, "status": "timeout", "url": None}


async def batch_generate(prompts: List[str]) -> List[Dict]:
    """
    批量生成图像

    参数:
        prompts: 提示词列表

    返回:
        结果列表,每个结果包含 index, prompt, status, url
    """
    async with aiohttp.ClientSession() as session:
        # 第一阶段:提交所有任务
        print(f"正在提交 {len(prompts)} 个任务...")
        submit_tasks = [
            submit_image_task(session, prompt, i)
            for i, prompt in enumerate(prompts)
        ]
        submitted = await asyncio.gather(*submit_tasks)

        # 第二阶段:轮询所有结果
        print(f"\n正在等待 {len(submitted)} 个结果...")
        poll_tasks = [poll_result(session, task) for task in submitted]
        results = await asyncio.gather(*poll_tasks)

    # 统计结果
    success = sum(1 for r in results if r["status"] == "success")
    failed = sum(1 for r in results if r["status"] == "failed")
    timeout = sum(1 for r in results if r["status"] == "timeout")
    total_cost = success * 0.012  # Flux Dev每张$0.012

    print(f"\n=== 批量生成完成 ===")
    print(f"成功: {success} | 失败: {failed} | 超时: {timeout}")
    print(f"总费用: ${total_cost:.3f}")

    return results


# 使用示例 — 批量生成100张图像
if __name__ == "__main__":
    prompts = [
        f"Beautiful woman in {setting}, professional photography, detailed, 8K"
        for setting in [
            "a sunlit garden", "a modern studio", "an urban rooftop",
            "a tropical beach", "a cozy library", "a vintage café",
            # ... 添加更多场景
        ] * 17  # 重复生成约100张
    ][:100]

    results = asyncio.run(batch_generate(prompts))

    # 保存结果到JSON文件
    with open("batch_results.json", "w") as f:
        json.dump(results, f, indent=2, ensure_ascii=False)

cURL — Flux Dev

# 提交图像生成任务(关闭安全检查)
curl -X POST "https://api.atlascloud.ai/api/v1/model/generateImage" \
  -H "Authorization: Bearer $ATLAS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "black-forest-labs/flux-dev",
    "prompt": "Professional studio portrait, artistic lighting, fine art photography, 8K",
    "size": "1024*1536",
    "num_inference_steps": 28,
    "guidance_scale": 3.5,
    "enable_safety_checker": false,
    "seed": -1
  }'

# 轮询结果
curl -X GET "https://api.atlascloud.ai/api/v1/model/result/task_abc123" \
  -H "Authorization: Bearer $ATLAS_API_KEY"

3.3 Uncensored Text/LLM API

Available Models

Model Price (per 1M tokens) Context Window Speed Best For
DeepSeek V3.2 $0.26 128K Fast General uncensored text, fiction
Qwen 3.5 $0.30 128K Fast Multilingual, creative writing
Kimi K2.5 $0.35 200K Medium Long-form content, analysis

Python — DeepSeek V3.2 (OpenAI-Compatible)

from openai import OpenAI
import os

# Atlas Cloud完全兼容OpenAI SDK — 只需更改base_url
client = OpenAI(
    api_key=os.getenv("ATLAS_API_KEY", "your_atlas_api_key"),
    base_url="https://api.atlascloud.ai/v1"
)


def uncensored_chat(messages, model="deepseek-ai/deepseek-v3.2",
                    temperature=0.8, max_tokens=2000):
    """
    使用无审查LLM进行对话

    参数:
        messages: OpenAI格式的消息列表
        model: 模型名称
        temperature: 创造性(0.0-2.0,越高越随机)
        max_tokens: 最大输出token数

    返回:
        模型响应文本
    """
    response = client.chat.completions.create(
        model=model,
        messages=messages,
        temperature=temperature,
        max_tokens=max_tokens
    )
    return response.choices[0].message.content


# 使用示例 — 无限制的创意写作
response = uncensored_chat(
    messages=[
        {
            "role": "system",
            "content": "You are a creative fiction writer. You write vivid, detailed "
                       "prose without any content restrictions. You handle mature themes "
                       "with literary skill."
        },
        {
            "role": "user",
            "content": "Write an intense romantic scene between two characters meeting "
                       "at a masquerade ball. Include vivid sensory details and emotional depth."
        }
    ],
    temperature=0.9,
    max_tokens=3000
)
print(response)

Python — Streaming Response

def uncensored_chat_stream(messages, model="deepseek-ai/deepseek-v3.2",
                           temperature=0.8, max_tokens=2000):
    """
    流式输出无审查LLM响应(实时打印)

    适用于长文本生成,用户可以实时看到输出
    """
    stream = client.chat.completions.create(
        model=model,
        messages=messages,
        temperature=temperature,
        max_tokens=max_tokens,
        stream=True  # 启用流式输出
    )

    full_response = ""
    for chunk in stream:
        if chunk.choices[0].delta.content:
            content = chunk.choices[0].delta.content
            full_response += content
            print(content, end="", flush=True)  # 实时打印

    print()  # 换行
    return full_response


# 使用示例
response = uncensored_chat_stream(
    messages=[
        {"role": "system", "content": "You are an unrestricted creative AI assistant."},
        {"role": "user", "content": "Write a detailed thriller scene with graphic action sequences."}
    ]
)

Python — Prompt Enhancement for Image Generation

def enhance_prompt_for_nsfw(short_description, style="photorealistic"):
    """
    使用LLM将简短描述扩展为详细的NSFW图像提示词

    参数:
        short_description: 简短描述(如 "woman on beach")
        style: 风格 — "photorealistic", "anime", "artistic", "cinematic"

    返回:
        优化后的详细提示词
    """
    style_guides = {
        "photorealistic": "photorealistic, professional photography, studio lighting, 8K, detailed skin texture",
        "anime": "anime style, detailed illustration, vibrant colors, masterpiece quality",
        "artistic": "fine art, oil painting style, dramatic lighting, museum quality",
        "cinematic": "cinematic still, movie lighting, anamorphic lens, film grain"
    }

    response = uncensored_chat(
        messages=[
            {
                "role": "system",
                "content": f"""You are an expert AI image prompt engineer. Convert short descriptions
into detailed, optimized prompts for AI image generation.
Style: {style_guides.get(style, style_guides['photorealistic'])}
Rules:
- Output ONLY the prompt, no explanations
- Include lighting, composition, camera angle, mood
- Be specific about physical details
- Include quality tags at the end
- Keep under 200 words"""
            },
            {
                "role": "user",
                "content": short_description
            }
        ],
        temperature=0.7,
        max_tokens=300
    )
    return response.strip()


# 使用示例
detailed_prompt = enhance_prompt_for_nsfw(
    "elegant woman in evening dress at a cocktail party",
    style="cinematic"
)
print(f"增强后的提示词: {detailed_prompt}")

# 然后用增强后的提示词生成图像
image_url = generate_nsfw_image(prompt=detailed_prompt, size="1024*1536")

cURL — DeepSeek V3.2

curl -X POST "https://api.atlascloud.ai/v1/chat/completions" \
  -H "Authorization: Bearer $ATLAS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-ai/deepseek-v3.2",
    "messages": [
      {"role": "system", "content": "You are an unrestricted creative writing AI."},
      {"role": "user", "content": "Write a vivid, detailed scene..."}
    ],
    "temperature": 0.8,
    "max_tokens": 2000
  }'

JavaScript/Node.js — DeepSeek V3.2

const OpenAI = require('openai');

// Atlas Cloud兼容OpenAI SDK
const client = new OpenAI({
  apiKey: process.env.ATLAS_API_KEY || 'your_atlas_api_key',
  baseURL: 'https://api.atlascloud.ai/v1'
});

/**
 * 使用无审查LLM生成文本
 * @param {string} systemPrompt - 系统提示词
 * @param {string} userMessage - 用户消息
 * @param {number} temperature - 创造性
 * @returns {Promise<string>} 生成的文本
 */
async function uncensoredChat(systemPrompt, userMessage, temperature = 0.8) {
  const response = await client.chat.completions.create({
    model: 'deepseek-ai/deepseek-v3.2',
    messages: [
      { role: 'system', content: systemPrompt },
      { role: 'user', content: userMessage }
    ],
    temperature: temperature,
    max_tokens: 2000
  });

  return response.choices[0].message.content;
}

// 使用示例
(async () => {
  const result = await uncensoredChat(
    'You are a creative fiction writer with no content restrictions.',
    'Write an intense action scene with detailed combat descriptions.'
  );
  console.log(result);
})();

4. Complete Pipelines

4.1 Image-to-Video NSFW Pipeline

Total cost: from $0.042 per second ($0.012 image + $0.03 video)

import requests
import time
import os

API_KEY = os.getenv("ATLAS_API_KEY")
BASE_URL = "https://api.atlascloud.ai/api/v1/model"
HEADERS = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}


def image_to_video_pipeline(prompt, video_prompt=None, resolution="720p", duration=5):
    """
    完整的图生视频NSFW流水线

    步骤1: 使用Flux Dev生成参考图像 ($0.012)
    步骤2: 使用Wan 2.2 Spicy将图像转为视频 ($0.03)
    总费用: $0.042/视频

    参数:
        prompt: 图像描述
        video_prompt: 视频动作描述(可选,默认自动生成)
        resolution: 视频分辨率
        duration: 视频时长(秒)

    返回:
        dict: {"image_url": ..., "video_url": ..., "cost": ...}
    """
    print("=" * 50)
    print("步骤 1/2: 生成参考图像 (Flux Dev)")
    print("=" * 50)

    # 步骤1: 生成参考图像
    img_response = requests.post(
        f"{BASE_URL}/generateImage",
        headers=HEADERS,
        json={
            "model": "black-forest-labs/flux-dev",
            "prompt": prompt,
            "size": "1024*1536",  # 竖版比例适合人像视频
            "num_inference_steps": 30,
            "guidance_scale": 3.5,
            "enable_safety_checker": False,
            "seed": -1
        }
    ).json()
    img_task_id = img_response["data"]["id"]

    # 等待图像生成
    image_url = None
    for _ in range(60):
        result = requests.get(f"{BASE_URL}/result/{img_task_id}", headers=HEADERS).json()
        if result["data"]["status"] in ["completed", "succeeded"]:
            image_url = result["data"]["outputs"][0]
            print(f"图像生成完成: {image_url[:80]}...")
            break
        elif result["data"]["status"] == "failed":
            raise Exception("图像生成失败")
        time.sleep(2)

    if not image_url:
        raise TimeoutError("图像生成超时")

    print()
    print("=" * 50)
    print("步骤 2/2: 生成视频 (Wan 2.2 Spicy)")
    print("=" * 50)

    # 步骤2: 将图像转为视频
    if video_prompt is None:
        video_prompt = "Subtle natural movement, the subject breathes naturally, slight body sway, soft lighting changes, cinematic quality"

    vid_response = requests.post(
        f"{BASE_URL}/generateVideo",
        headers=HEADERS,
        json={
            "model": "alibaba/wan-2.2-spicy/image-to-video",
            "image": image_url,
            "prompt": video_prompt,
            "resolution": resolution,
            "duration": duration,
            "seed": -1
        }
    ).json()
    vid_task_id = vid_response["data"]["id"]

    # 等待视频生成
    video_url = None
    for _ in range(100):
        result = requests.get(f"{BASE_URL}/result/{vid_task_id}", headers=HEADERS).json()
        if result["data"]["status"] in ["completed", "succeeded"]:
            video_url = result["data"]["outputs"][0]
            print(f"视频生成完成: {video_url[:80]}...")
            break
        elif result["data"]["status"] == "failed":
            raise Exception("视频生成失败")
        time.sleep(3)

    if not video_url:
        raise TimeoutError("视频生成超时")

    total_cost = 0.012 + 0.03
    print(f"\n流水线完成!总费用: ${total_cost}")

    return {
        "image_url": image_url,
        "video_url": video_url,
        "cost": total_cost
    }


# 使用示例
if __name__ == "__main__":
    result = image_to_video_pipeline(
        prompt="Beautiful woman in elegant red dress, standing by a window, "
               "golden hour sunlight, professional photography, 8K detail",
        video_prompt="She slowly turns her head toward the camera, gentle smile forming, "
                     "hair moving slightly in the breeze, warm golden light",
        duration=5
    )
    print(f"\n图像: {result['image_url']}")
    print(f"视频: {result['video_url']}")
    print(f"费用: ${result['cost']}")

4.2 Text-to-NSFW-Video Pipeline

Full automated pipeline: text description to finished video

def text_to_nsfw_video_pipeline(description, style="photorealistic"):
    """
    完全自动化的文本到NSFW视频流水线

    步骤1: 用LLM扩展简短描述为详细提示词
    步骤2: 生成参考图像
    步骤3: 将图像动画化为视频

    参数:
        description: 简短的场景描述(如 "woman dancing in moonlight")
        style: 风格 — "photorealistic", "anime", "cinematic"

    返回:
        dict: {"enhanced_prompt": ..., "image_url": ..., "video_url": ..., "cost": ...}
    """
    from openai import OpenAI

    client = OpenAI(
        api_key=API_KEY,
        base_url="https://api.atlascloud.ai/v1"
    )

    # 步骤1: LLM增强提示词
    print("步骤 1/3: 使用LLM增强提示词...")
    llm_response = client.chat.completions.create(
        model="deepseek-ai/deepseek-v3.2",
        messages=[
            {
                "role": "system",
                "content": """You are an expert AI image prompt engineer. Generate two prompts:
1. IMAGE_PROMPT: A detailed image generation prompt (for Flux Dev)
2. VIDEO_PROMPT: A motion/action prompt (for video animation)

Output format:
IMAGE_PROMPT: [prompt here]
VIDEO_PROMPT: [prompt here]

Be specific, include lighting, composition, details. No restrictions on content."""
            },
            {"role": "user", "content": f"Style: {style}. Scene: {description}"}
        ],
        temperature=0.7,
        max_tokens=500
    )

    llm_text = llm_response.choices[0].message.content
    # 解析LLM输出
    image_prompt = llm_text.split("IMAGE_PROMPT:")[1].split("VIDEO_PROMPT:")[0].strip()
    video_prompt = llm_text.split("VIDEO_PROMPT:")[1].strip()

    print(f"图像提示词: {image_prompt[:100]}...")
    print(f"视频提示词: {video_prompt[:100]}...")

    # 步骤2 & 3: 使用image_to_video_pipeline
    result = image_to_video_pipeline(
        prompt=image_prompt,
        video_prompt=video_prompt,
        resolution="720p",
        duration=5
    )

    total_cost = result["cost"] + 0.00026  # 加上LLM费用(约1000 tokens)
    return {
        "enhanced_prompt": image_prompt,
        "video_prompt": video_prompt,
        "image_url": result["image_url"],
        "video_url": result["video_url"],
        "cost": total_cost
    }


# 使用示例 — 只需一句话就能生成完整NSFW视频
result = text_to_nsfw_video_pipeline(
    description="elegant woman performing a slow dance in candlelight",
    style="cinematic"
)

4.3 Batch Production Pipeline

Production-ready pipeline for generating large volumes concurrently.

import asyncio
import aiohttp
import json
import time
from dataclasses import dataclass, field, asdict
from typing import List, Optional

API_KEY = os.getenv("ATLAS_API_KEY")
BASE_URL = "https://api.atlascloud.ai/api/v1/model"
HEADERS = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}


@dataclass
class GenerationJob:
    """单个生成任务"""
    index: int
    prompt: str
    model: str = "black-forest-labs/flux-dev"
    task_id: Optional[str] = None
    status: str = "pending"
    output_url: Optional[str] = None
    error: Optional[str] = None
    cost: float = 0.0
    start_time: float = 0.0
    end_time: float = 0.0


@dataclass
class BatchStats:
    """批处理统计"""
    total: int = 0
    success: int = 0
    failed: int = 0
    timeout: int = 0
    total_cost: float = 0.0
    total_time: float = 0.0


class BatchGenerator:
    """
    批量生成器 — 支持并发控制、重试、成本追踪

    参数:
        max_concurrent: 最大并发数
        max_retries: 最大重试次数
        poll_interval: 轮询间隔(秒)
        timeout: 单任务超时时间(秒)
    """

    def __init__(self, max_concurrent=5, max_retries=2, poll_interval=3, timeout=180):
        self.max_concurrent = max_concurrent
        self.max_retries = max_retries
        self.poll_interval = poll_interval
        self.timeout = timeout
        self.semaphore = asyncio.Semaphore(max_concurrent)
        self.stats = BatchStats()

        # 模型价格表
        self.price_map = {
            "black-forest-labs/flux-dev": 0.012,
            "black-forest-labs/flux-dev-lora": 0.015,
            "seedream/seedream-5.0": 0.032,
            "alibaba/wan-2.2-spicy/image-to-video": 0.03,
            "alibaba/wan-2.6/text-to-video": 0.05,
        }

    async def _submit_job(self, session: aiohttp.ClientSession, job: GenerationJob) -> GenerationJob:
        """提交单个任务"""
        async with self.semaphore:
            try:
                endpoint = "generateImage" if "flux" in job.model or "seedream" in job.model else "generateVideo"
                payload = {
                    "model": job.model,
                    "prompt": job.prompt,
                    "seed": -1
                }
                # 图像模型的特殊参数
                if endpoint == "generateImage":
                    payload.update({
                        "size": "1024*1024",
                        "num_inference_steps": 28,
                        "guidance_scale": 3.5,
                        "enable_safety_checker": False,
                    })

                async with session.post(
                    f"{BASE_URL}/{endpoint}",
                    headers=HEADERS,
                    json=payload
                ) as resp:
                    data = await resp.json()
                    job.task_id = data["data"]["id"]
                    job.status = "submitted"
                    job.start_time = time.time()
                    print(f"[{job.index}] 已提交: {job.task_id}")

            except Exception as e:
                job.status = "failed"
                job.error = str(e)
                print(f"[{job.index}] 提交失败: {e}")

        return job

    async def _poll_job(self, session: aiohttp.ClientSession, job: GenerationJob) -> GenerationJob:
        """轮询单个任务结果"""
        if job.status != "submitted":
            return job

        elapsed = 0
        while elapsed < self.timeout:
            try:
                async with session.get(
                    f"{BASE_URL}/result/{job.task_id}",
                    headers=HEADERS
                ) as resp:
                    data = await resp.json()
                    status = data["data"]["status"]

                    if status in ["completed", "succeeded"]:
                        job.status = "success"
                        job.output_url = data["data"]["outputs"][0]
                        job.end_time = time.time()
                        job.cost = self.price_map.get(job.model, 0)
                        self.stats.success += 1
                        self.stats.total_cost += job.cost
                        print(f"[{job.index}] ✅ 完成 ({job.end_time - job.start_time:.1f}s)")
                        return job
                    elif status == "failed":
                        job.status = "failed"
                        job.error = data["data"].get("error", "未知错误")
                        self.stats.failed += 1
                        print(f"[{job.index}] ❌ 失败: {job.error}")
                        return job

            except Exception as e:
                print(f"[{job.index}] 轮询异常: {e}")

            await asyncio.sleep(self.poll_interval)
            elapsed += self.poll_interval

        job.status = "timeout"
        self.stats.timeout += 1
        print(f"[{job.index}] ⏰ 超时")
        return job

    async def run(self, prompts: List[str], model: str = "black-forest-labs/flux-dev") -> List[GenerationJob]:
        """
        运行批量生成

        参数:
            prompts: 提示词列表
            model: 使用的模型

        返回:
            GenerationJob列表
        """
        self.stats = BatchStats(total=len(prompts))
        jobs = [GenerationJob(index=i, prompt=p, model=model) for i, p in enumerate(prompts)]

        batch_start = time.time()

        async with aiohttp.ClientSession() as session:
            # 提交所有任务
            print(f"🚀 正在提交 {len(jobs)} 个任务(并发限制: {self.max_concurrent})...")
            submit_tasks = [self._submit_job(session, job) for job in jobs]
            jobs = await asyncio.gather(*submit_tasks)

            # 轮询所有结果
            submitted_jobs = [job for job in jobs if job.status == "submitted"]
            print(f"\n⏳ 正在等待 {len(submitted_jobs)} 个结果...")
            poll_tasks = [self._poll_job(session, job) for job in submitted_jobs]
            await asyncio.gather(*poll_tasks)

        self.stats.total_time = time.time() - batch_start

        # 打印统计
        print(f"\n{'=' * 50}")
        print(f"📊 批量生成统计")
        print(f"{'=' * 50}")
        print(f"总数: {self.stats.total}")
        print(f"成功: {self.stats.success}")
        print(f"失败: {self.stats.failed}")
        print(f"超时: {self.stats.timeout}")
        print(f"总费用: ${self.stats.total_cost:.3f}")
        print(f"总耗时: {self.stats.total_time:.1f}s")
        print(f"平均耗时: {self.stats.total_time / max(self.stats.total, 1):.1f}s/任务")

        return jobs


# 使用示例 — 批量生成100张图像
if __name__ == "__main__":
    generator = BatchGenerator(
        max_concurrent=10,   # 最大10个并发
        max_retries=2,       # 失败重试2次
        poll_interval=2,     # 每2秒轮询一次
        timeout=120          # 单任务超时120秒
    )

    prompts = [f"Professional portrait photo #{i}, studio lighting, 8K" for i in range(100)]

    jobs = asyncio.run(generator.run(prompts, model="black-forest-labs/flux-dev"))

    # 保存结果
    results = [asdict(job) for job in jobs]
    with open("batch_output.json", "w") as f:
        json.dump(results, f, indent=2, ensure_ascii=False)
    print(f"\n结果已保存到 batch_output.json")

4.4 Character Consistency Pipeline

def character_consistency_pipeline(character_description, poses, lora_url=None):
    """
    角色一致性流水线 — 生成同一角色的多个姿势/角度

    参数:
        character_description: 角色基础描述
        poses: 姿势/场景列表
        lora_url: 可选的LoRA模型URL(用于角色LoRA)

    返回:
        生成的图像URL列表
    """
    # 构建一致性提示词前缀(包含角色特征)
    consistency_prefix = (
        f"{character_description}, consistent character, same face, same body type, "
        f"same hair color and style, "
    )

    results = []
    # 使用固定种子的前几位确保面部一致性
    base_seed = 42

    for i, pose in enumerate(poses):
        full_prompt = f"{consistency_prefix}{pose}, highly detailed, professional quality, 8K"
        print(f"正在生成姿势 {i + 1}/{len(poses)}: {pose[:50]}...")

        if lora_url:
            # 使用角色LoRA获得更好的一致性
            url = generate_lora_image(
                prompt=full_prompt,
                lora_url=lora_url,
                lora_scale=0.8,
                size="1024*1536",
                seed=base_seed + i  # 相近的种子有助于保持一致性
            )
        else:
            url = generate_nsfw_image(
                prompt=full_prompt,
                size="1024*1536",
                seed=base_seed + i
            )

        results.append({"pose": pose, "url": url})
        print(f"完成: {url[:60]}...")

    return results


# 使用示例 — 生成同一角色的多个姿势
character = "Young woman with long black hair, blue eyes, slim build, fair skin"
poses = [
    "standing facing camera, neutral expression, full body shot",
    "sitting on chair, crossed legs, slight smile, medium shot",
    "profile view, looking left, dramatic lighting, close-up",
    "walking away from camera, looking over shoulder, full body",
    "lying down, relaxed pose, soft lighting, medium shot",
]

results = character_consistency_pipeline(character, poses)
for r in results:
    print(f"{r['pose'][:40]}: {r['url']}")

5. Error Handling & Best Practices

Common API Errors and Solutions

Error Code Meaning Solution
401 Invalid API key Check your ATLAS_API_KEY is valid
402 Insufficient balance Add credits at atlascloud.ai
429 Rate limit exceeded Reduce concurrency, add delays between requests
500 Server error Retry after 5-10 seconds
timeout Generation took too long Retry; high-res/long videos take longer
content_filtered Content was filtered For Seedream/Seedance: ensure your account is whitelisted

Robust Error Handling Template

import requests
import time
from functools import wraps


def retry_on_failure(max_retries=3, backoff_factor=2):
    """
    带指数退避的重试装饰器

    参数:
        max_retries: 最大重试次数
        backoff_factor: 退避倍数(每次重试等待时间翻倍)
    """
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            last_exception = None
            for attempt in range(max_retries + 1):
                try:
                    return func(*args, **kwargs)
                except requests.exceptions.HTTPError as e:
                    if e.response.status_code == 429:
                        # 速率限制:使用更长的退避
                        wait = backoff_factor ** (attempt + 2)
                        print(f"速率限制,等待 {wait}s 后重试...")
                        time.sleep(wait)
                    elif e.response.status_code >= 500:
                        # 服务器错误:正常退避
                        wait = backoff_factor ** attempt
                        print(f"服务器错误,等待 {wait}s 后重试...")
                        time.sleep(wait)
                    else:
                        raise  # 4xx错误(除429外)不重试
                    last_exception = e
                except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e:
                    wait = backoff_factor ** attempt
                    print(f"连接错误,等待 {wait}s 后重试...")
                    time.sleep(wait)
                    last_exception = e

            raise last_exception
        return wrapper
    return decorator


@retry_on_failure(max_retries=3, backoff_factor=2)
def generate_with_retry(prompt):
    """带自动重试的图像生成"""
    return generate_nsfw_image(prompt)

Optimal Parameters for Each Model

# Flux Dev — 最佳参数
FLUX_DEV_OPTIMAL = {
    "num_inference_steps": 28,     # 28步是质量/速度的最佳平衡
    "guidance_scale": 3.5,         # 3.0-4.0之间效果最好
    "size": "1024*1536",           # 竖版人像最佳比例
    "enable_safety_checker": False  # 必须关闭才能生成NSFW
}

# Wan 2.2 Spicy — 最佳参数
WAN_SPICY_OPTIMAL = {
    "resolution": "720p",  # 720p质量/速度最佳
    "duration": 5,         # 5秒是默认且最稳定的时长
    # 提示词建议:描述动作而非静态场景
}

# Wan 2.6 — 最佳参数
WAN_26_OPTIMAL = {
    "resolution": "1080p",        # 支持更高分辨率
    "duration": 5,                # 5-10秒
    "num_inference_steps": 50,    # 更多步数获得更高质量
    "guidance_scale": 7.0         # 较高的引导比例
}

# DeepSeek V3.2 — 最佳参数
DEEPSEEK_OPTIMAL = {
    "temperature": 0.8,    # 0.7-0.9适合创意写作
    "max_tokens": 2000,    # 根据需要调整
    "top_p": 0.95,         # 保持多样性
}

Quality vs Speed vs Cost Tradeoffs

质量优先:
  图像: Seedream v5.0 ($0.032) > Flux Dev 30步 ($0.012) > Flux Dev 20步 ($0.012)
  视频: Wan 2.6 1080p ($0.05) > Seedance v1.5 ($0.06) > Wan 2.2 Spicy ($0.03)

速度优先:
  图像: Flux Dev 20步 (~3s) > Flux Dev 28步 (~5s) > Seedream v5.0 (~10s)
  视频: Wan 2.2 Spicy (~60s) > Wan 2.6 (~120s) > Seedance v1.5 (~180s)

成本优先:
  图像: Flux Dev ($0.012) > Flux Dev LoRA ($0.015) > Seedream v5.0 ($0.032)
  视频: Wan 2.2 Spicy ($0.03) > Wan 2.5 ($0.04) > Wan 2.6 ($0.05)

6. Platform Comparison (Technical)

Feature Atlas Cloud Replicate fal.ai RunPod Self-hosted
NSFW Video ✅ Native (Wan 2.2 Spicy) ⚠️ Limited models ⚠️ Some models ✅ (own GPU) ✅ Full control
NSFW Image ✅ Native (Flux Dev) ⚠️ Filter bypasses ⚠️ Some models ✅ (own GPU) ✅ Full control
NSFW Text ✅ Native (DeepSeek) ❌ Filtered ❌ No LLMs ✅ (own GPU) ✅ Full control
Setup time 0 min (API key only) 5 min 5 min 30+ min Hours/days
Min cost/image $0.012 $0.05+ $0.03+ $0.50/hr min GPU purchase/rental
Min cost/video from $0.03/s $0.10+ $0.08+ $0.50/hr min GPU purchase/rental
Concurrent jobs 10+ 5 5 GPU-limited GPU-limited
GPU management ❌ Not needed ❌ Not needed ❌ Not needed ✅ Required ✅ Required
OpenAI SDK compatible ✅ Yes ❌ Custom API ❌ Custom API Depends Depends
Dedicated NSFW models ✅ (Wan Spicy) Manual setup Manual setup
Auto-scaling ❌ Manual ❌ Manual

Why Atlas Cloud for NSFW?

  1. Zero setup: No GPU management, no model deployment, no filter hacking
  2. Cheapest per-generation: $0.012/image and from $0.03/s beat all serverless competitors
  3. Purpose-built NSFW models: Wan 2.2 Spicy is fine-tuned for NSFW, not just filter-removed
  4. OpenAI SDK compatible: Drop-in replacement for existing code
  5. Production-ready: Auto-scaling, no cold starts, reliable uptime

💰 Atlas Cloud vs fal.ai — Price Comparison

Model fal.ai Price Atlas Cloud Price Savings
Wan 2.2 Spicy Not available $0.03/req Atlas exclusive
Wan 2.5 $0.05/sec (5sec = $0.25) $0.05/req 80% cheaper
Kling (Whitelisted) $0.224/sec $0.204/req 82% cheaper
Flux Dev (NSFW) No NSFW support $0.012/img Atlas exclusive
Seedream v5.0 (Whitelisted) Not available $0.032/img Atlas exclusive
Vidu Q3-Pro (Whitelisted) Not available $0.06/req Atlas exclusive
Vidu Q3-Turbo (Whitelisted) Not available $0.034/req Atlas exclusive

🏆 Atlas Cloud is the ONLY platform offering Wan 2.2 Spicy, and the only provider with whitelisted access to Seedance, Kling, Vidu, and Seedream for NSFW content generation.


7. Pricing Calculator

Image Generation Costs

Volume Flux Dev ($0.012) Flux Dev LoRA ($0.015) Seedream v5.0 ($0.032)
100 images $1.20 $1.50 $3.20
1,000 images $12.00 $15.00 $32.00
10,000 images $120.00 $150.00 $320.00
100,000 images $1,200.00 $1,500.00 $3,200.00

Video Generation Costs

Volume Wan 2.2 Spicy ($0.03) Wan 2.5 ($0.04) Wan 2.6 ($0.05) Seedance v1.5 ($0.06)
100 videos $3.00 $4.00 $5.00 $6.00
1,000 videos $30.00 $40.00 $50.00 $60.00
10,000 videos $300.00 $400.00 $500.00 $600.00
100,000 videos $3,000.00 $4,000.00 $5,000.00 $6,000.00

Text Generation Costs (per 1M tokens)

Volume DeepSeek V3.2 ($0.26) Qwen 3.5 ($0.30) Kimi K2.5 ($0.35)
1M tokens $0.26 $0.30 $0.35
10M tokens $2.60 $3.00 $3.50
100M tokens $26.00 $30.00 $35.00
1B tokens $260.00 $300.00 $350.00

Pipeline Costs (Image + Video)

Pipeline Cost Per Unit 1,000 Units 10,000 Units
Flux Dev + Wan 2.2 Spicy $0.042 $42.00 $420.00
Flux Dev + Wan 2.6 $0.062 $62.00 $620.00
Seedream + Seedance $0.092 $92.00 $920.00
LLM + Flux Dev + Wan Spicy ~$0.043 ~$43.00 ~$430.00

25% Signup Bonus

New accounts get 25% bonus credits when signing up through this link.

Example: Deposit $100 → Get $125 in credits → Generate 10,416 images or 4,166 videos with Wan 2.2 Spicy.


8. FAQ (Developer-Focused)

How do I disable the NSFW filter?

For Flux Dev, set enable_safety_checker: false in your API request:

json={
    "model": "black-forest-labs/flux-dev",
    "enable_safety_checker": False,  # 这个参数关闭NSFW过滤
    ...
}

For Wan 2.2 Spicy, no configuration needed — the model is fine-tuned for NSFW generation natively.

For Seedream/Seedance, contact Atlas Cloud support to get your API key whitelisted for NSFW content.

For text models (DeepSeek, Qwen, Kimi), no configuration needed — Atlas Cloud's deployment has no safety filters.

What's the best API for bulk NSFW generation?

Flux Dev at $0.012/image is the most cost-effective for bulk image generation. Use the batch generation script with max_concurrent=10 for optimal throughput.

For bulk video, Wan 2.2 Spicy at from $0.03/s offers the best value. Each video takes ~60-120 seconds, so set concurrency to 5-10 to maximize throughput without hitting rate limits.

How do I maintain character consistency across generations?

  1. Fixed seed approach: Use the same base seed with slight variations (seed + 1, seed + 2)
  2. LoRA approach: Train a character LoRA on 10-20 reference images, then use it with Flux Dev LoRA
  3. Prompt prefix approach: Use an identical character description prefix for all generations
  4. Image-to-video approach: Generate one perfect reference image, then use Wan 2.2 Spicy for different animations

See the Character Consistency Pipeline for a complete implementation.

What's the cheapest NSFW video API?

Wan 2.2 Spicy at from $0.03/s is the cheapest NSFW video API available. Combined with Flux Dev image generation ($0.012), a complete image-to-video pipeline costs only from $0.042 per second.

For comparison:

  • Self-hosted (A100 GPU): ~from $0.15-0.30/s (GPU rental cost)
  • RunPod: ~from $0.10-0.20/s
  • Replicate: ~from $0.10+/s (with limited NSFW support)

Can I use the OpenAI SDK with Atlas Cloud?

Yes. Atlas Cloud's text/LLM API is fully OpenAI-compatible:

from openai import OpenAI
client = OpenAI(
    api_key="your_atlas_key",
    base_url="https://api.atlascloud.ai/v1"  # 只需更改base_url
)
# 之后的用法与OpenAI完全相同

What content is prohibited even on uncensored APIs?

Atlas Cloud prohibits:

  • CSAM (child sexual abuse material)
  • Non-consensual deepfakes of real identifiable individuals
  • Content that violates applicable laws in your jurisdiction

All other content is permitted, including artistic nudity, adult content between fictional characters, violence in fiction, and mature creative writing.

How do I handle rate limits?

Atlas Cloud allows approximately 10 concurrent requests per API key. For bulk generation:

# 使用信号量控制并发
semaphore = asyncio.Semaphore(8)  # 留一些余量

async def rate_limited_generate(prompt):
    async with semaphore:
        return await generate_image(prompt)

If you hit 429 errors, implement exponential backoff (see Error Handling).

What image sizes are supported?

Flux Dev supports: 512*512, 768*768, 1024*1024, 1024*1536, 1536*1024, 2048*2048

For portrait/figure content, 1024*1536 (vertical) gives the best results. For landscape/scene content, 1536*1024 (horizontal) works best. For square/headshot content, 1024*1024 is optimal.


9. Get Started

Quick Start (5 minutes)

  1. Sign up at Atlas Cloud (25% bonus credits)
  2. Get your API key from the dashboard
  3. Install dependencies: pip install requests openai
  4. Generate your first uncensored image:
import requests

response = requests.post(
    "https://api.atlascloud.ai/api/v1/model/generateImage",
    headers={
        "Authorization": "Bearer YOUR_API_KEY",
        "Content-Type": "application/json"
    },
    json={
        "model": "black-forest-labs/flux-dev",
        "prompt": "Your prompt here",
        "enable_safety_checker": False,
        "size": "1024*1024"
    }
)
task_id = response.json()["data"]["id"]
print(f"Task submitted: {task_id}")
# 然后轮询结果...

Links

Resource URL
Sign Up (25% bonus) atlascloud.ai
API Documentation docs.atlascloud.ai
Dashboard app.atlascloud.ai

License

This guide is released under the MIT License. You are free to use, modify, and distribute this guide.

Star History

If this guide helped you, please give it a ⭐ on GitHub!


🚀 Start Generating — Get 25% Bonus Credits

The most affordable uncensored AI API for developers

Releases

No releases published

Packages

 
 
 

Contributors