예제: 텍스트-투-이미지 생성

Atlas Cloud API를 사용한 텍스트 기반 이미지 생성 완전 예제

개요

이 튜토리얼에서는 Atlas Cloud API를 사용한 완전한 텍스트-투-이미지 생성 워크플로우를 안내합니다 — 요청 제출부터 최종 이미지 조회까지.

사전 요구 사항

  • API 키가 있는 Atlas Cloud 계정
  • Python 3.7+ 및 requests 라이브러리, 또는 Node.js 18+

Python 전체 예제

import requests
import time
import os

API_KEY = os.environ.get("ATLASCLOUD_API_KEY", "your-api-key")
BASE_URL = "https://api.atlascloud.ai/api/v1"

def generate_image(prompt, model="seedream-3.0"):
    """이미지 생성 작업을 제출합니다."""
    response = requests.post(
        f"{BASE_URL}/model/generateImage",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        },
        json={
            "model": model,
            "prompt": prompt
        }
    )
    response.raise_for_status()
    return response.json()["data"]["id"]

def wait_for_result(prediction_id, interval=2, timeout=120):
    """생성 결과를 폴링합니다."""
    elapsed = 0
    while elapsed < timeout:
        response = requests.get(
            f"{BASE_URL}/model/prediction/{prediction_id}",
            headers={"Authorization": f"Bearer {API_KEY}"}
        )
        result = response.json()
        status = result["data"]["status"]

        if status == "completed":
            return result["data"]["outputs"][0]
        elif status == "failed":
            raise Exception(f"Failed: {result['data'].get('error')}")

        print(f"  Status: {status} ({elapsed}s)")
        time.sleep(interval)
        elapsed += interval

    raise TimeoutError("Generation timed out")

# 이미지 생성
prompt = "A majestic snow-capped mountain reflected in a crystal-clear lake at sunrise, photorealistic"
print(f"Generating image: {prompt}")

prediction_id = generate_image(prompt)
print(f"Task submitted: {prediction_id}")

image_url = wait_for_result(prediction_id)
print(f"Image ready: {image_url}")

Node.js 전체 예제

const API_KEY = process.env.ATLASCLOUD_API_KEY || "your-api-key";
const BASE_URL = "https://api.atlascloud.ai/api/v1";

async function generateImage(prompt, model = "seedream-3.0") {
  const response = await fetch(`${BASE_URL}/model/generateImage`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ model, prompt }),
  });

  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  const data = await response.json();
  return data.data.id;
}

async function waitForResult(predictionId, interval = 2000, timeout = 120000) {
  const start = Date.now();
  while (Date.now() - start < timeout) {
    const response = await fetch(
      `${BASE_URL}/model/prediction/${predictionId}`,
      { headers: { Authorization: `Bearer ${API_KEY}` } }
    );
    const result = await response.json();
    const status = result.data.status;

    if (status === "completed") return result.data.outputs[0];
    if (status === "failed") throw new Error(result.data.error);

    console.log(`  Status: ${status}`);
    await new Promise((r) => setTimeout(r, interval));
  }
  throw new Error("Timeout");
}

// 실행
const prompt =
  "A majestic snow-capped mountain reflected in a crystal-clear lake at sunrise, photorealistic";
console.log(`Generating: ${prompt}`);

const predictionId = await generateImage(prompt);
console.log(`Task: ${predictionId}`);

const imageUrl = await waitForResult(predictionId);
console.log(`Image: ${imageUrl}`);

cURL 예제

# 1단계: 생성 작업 제출
PREDICTION_ID=$(curl -s -X POST https://api.atlascloud.ai/api/v1/model/generateImage \
  -H "Authorization: Bearer $ATLASCLOUD_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "seedream-3.0",
    "prompt": "A majestic snow-capped mountain reflected in a crystal-clear lake"
  }' | jq -r '.data.id')

echo "Prediction ID: $PREDICTION_ID"

# 2단계: 결과 폴링
while true; do
  RESULT=$(curl -s "https://api.atlascloud.ai/api/v1/model/prediction/$PREDICTION_ID" \
    -H "Authorization: Bearer $ATLASCLOUD_API_KEY")
  STATUS=$(echo $RESULT | jq -r '.data.status')
  echo "Status: $STATUS"
  if [ "$STATUS" = "completed" ]; then
    echo $RESULT | jq -r '.data.outputs[0]'
    break
  elif [ "$STATUS" = "failed" ]; then
    echo "Failed: $(echo $RESULT | jq -r '.data.error')"
    break
  fi
  sleep 2
done

  • 모델 선택: 다른 스타일에 다른 모델을 시도하세요. Seedream은 포토리얼리스틱 이미지에, FLUX는 아트 스타일에 뛰어납니다
  • 프롬프트 엔지니어링: 스타일, 구도, 조명, 색상, 분위기를 구체적으로 설명하세요
  • 배치 생성: 대량 이미지 생성을 위해 여러 요청을 병렬로 제출하세요
  • 오류 처리: 항상 failed 상태를 확인하고 타임아웃을 적절히 처리하세요

다음 단계