본문으로 이동
My AI Console

API URL 하나로 이미지 만들기 — Python과 Flux3

One API URL. One image. — 가린 imageGenerate 주소와 요청 본문에서 FLUX 3가 그린 빨간 자전거 그림이 나오는 대표 이미지

이번 글에서 쓸 것은 API URL 하나입니다.

https://api-3.flameai.im/Nx7bQ2mZ/cortex/7f3c9a12-4e6b-4d8f-9a21-6b5e8c1f2d3a/imageGenerate

콘솔의 Cortex 목록에서 복사한 이미지 Cortex의 주소입니다(위는 예시 값). 이 주소 하나와 Secret Key만 있으면 그림을 만들 수 있습니다. 이 주소로 그릴 내용을 보내면 내 PC의 FlameBox에서 돌아가는 FLUX 3가 그림을 그리고, 결과 파일도 같은 주소 아래에서 받습니다. 이번에는 Python 파일 하나로, 설치할 라이브러리 없이 만들어 봅니다.

FlameBox 설치가 아직이라면 설치 편을, FlameAI API가 처음이라면 첫 API 호출을 먼저 봐 주세요. Java로 짠 이미지 생성기는 Java로 만드는 AI 이미지 생성기에 있습니다.

0. 준비

  • FLUX 3 Cortex — 콘솔의 Cortex 만들기에서 이미지 탭의 FLUX 3 Image Klein으로 만듭니다. 제작사 기준으로 VRAM 8GB GPU에서도 돌아갑니다.
  • Python 3.9 이상 — 설치할 라이브러리는 없습니다.
  • 값 2개 — API URL은 Cortex 목록에서 FLUX 3 카드의 주소를 복사하고(…/imageGenerate로 끝남), Secret Key는 설정 › My API에서 복사합니다.

1. 주소 하나에서 두 가지를 얻는다

import argparse
import json
import os
import re
import time
import urllib.error
import urllib.request

# ── Settings — copy from the FlameAI console ─────────────────────────────────
API_URL = "https://api-xxxx.flameai.im/AbCd1234/cortex/YOUR_CORTEX_ID/imageGenerate"  # Cortex list › API URL
SECRET_KEY = "YOUR_SECRET_KEY"                                                          # Settings › My API › Secret key


def setting(constant, env_name):
    placeholder = "YOUR_" in constant or "api-xxxx" in constant
    return (os.environ.get(env_name, "") if placeholder else constant).strip()


URL = re.sub(r"^POST\s+", "", setting(API_URL, "FLAMEAI_API_URL"))   # "POST https://…" as copied is fine
CORTEX = re.sub(r"(/cortex/[^/]+).*$", r"\1", URL)                    # https://…/cortex/{id} — files live here too
KEY = setting(SECRET_KEY, "FLAMEAI_SECRET_KEY")

API URL은 {계정 주소}/cortex/{Cortex ID}/imageGenerate 모양입니다. 그대로 그리기 요청에 쓰고, 끝의 /imageGenerate를 뗀 …/cortex/{Cortex ID}(코드의 CORTEX)는 결과 파일을 받고 지우는 주소로 씁니다. 그래서 주소 하나면 충분합니다.

두 값은 상수에 넣어도 되지만, 환경변수로 넣으면 파일에 키가 남지 않습니다. 상수가 자리 표시 값 그대로면 환경변수를 읽습니다.

Windows (PowerShell)

$env:FLAMEAI_API_URL    = "https://api-3.flameai.im/Nx7bQ2mZ/cortex/7f3c9a12-4e6b-4d8f-9a21-6b5e8c1f2d3a/imageGenerate"
$env:FLAMEAI_SECRET_KEY = "0123456789ABCDEFGH"

macOS · Linux

export FLAMEAI_API_URL="https://api-3.flameai.im/Nx7bQ2mZ/cortex/7f3c9a12-4e6b-4d8f-9a21-6b5e8c1f2d3a/imageGenerate"
export FLAMEAI_SECRET_KEY="0123456789ABCDEFGH"

위 주소와 0123456789ABCDEFGH 자리에 내 API URL과 Secret Key를 넣으세요.

실제 Secret Key를 넣은 파일은 공유하거나 저장소에 올리지 마세요.

2. 키를 붙여 부르기

def call(method, url, body=None):
    """One HTTP call with the Secret Key. Raises SystemExit with a readable message on a FlameAI error."""
    req = urllib.request.Request(url, data=body, method=method, headers={
        "Authorization": f"Bearer {KEY}", "X-API-Version": "1", "Content-Type": "application/json"})
    try:
        return urllib.request.urlopen(req, timeout=900)   # loading the model + drawing can take minutes
    except urllib.error.HTTPError as e:
        err = json.loads(e.read() or b"{}").get("error", {})
        raise SystemExit(f"[오류] {err.get('code', e.code)}: {err.get('message', '')}")

모든 요청에 Authorization: Bearer {Secret Key}를 붙입니다. 모델을 올리고 그리는 데 몇 분이 걸릴 수도 있어서 타임아웃은 넉넉히 둡니다. 오류가 나면 FlameAI가 주는 code와 message를 그대로 보여 주고 끝냅니다.

3. 그리기 — 진행률을 보면서

# ── 1. Ask the Cortex to draw (stream: progress events, then the result) ─────
def generate(prompt, width, height, seed):
    body = json.dumps({"prompt": prompt, "width": width, "height": height, "seed": seed, "stream": True}).encode()
    event = ""
    with call("POST", URL, body) as res:
        for raw in res:                                   # Server-Sent Events, one line at a time
            line = raw.decode("utf-8").strip()
            if line.startswith("event:"):
                event = line[6:].strip()
            elif line.startswith("data:"):
                data = json.loads(line[5:])
                if event == "cortex.init_start":
                    print("모델을 올리는 중... (처음 한 번은 오래 걸릴 수 있습니다)")
                elif event == "generation.progress":
                    print(f"\r그리는 중 {data['step']}/{data['steps']}", end="", flush=True)
                elif event == "generation.result":
                    print()
                    return data                           # {"files": ["files/gen-….png"], "seed": …, …}
                elif event in ("cortex.init_failed", "generation.error"):
                    err = data.get("error", data)
                    raise SystemExit(f"\n[오류] {err.get('code')}: {err.get('message')}")
    raise SystemExit("[오류] 결과 없이 끝났습니다.")
  • 보내는 값은 prompt(그릴 내용), width·height(32의 배수), seed(-1이면 무작위)입니다.
  • stream: true로 보내면 진행 상황이 이벤트로 옵니다. 모델을 올릴 때 cortex.init_start, 그리는 동안 generation.progress(몇 번째 단계인지), 다 그리면 generation.result가 옵니다.
  • 결과에는 파일 이름(files/gen-….png)과 실제로 쓴 seed가 들어 있습니다. 같은 seed와 프롬프트로 다시 부르면 같은 그림을 얻습니다.

4. 받고, 지우기

# ── 2. Download the PNG, then delete it from the FlameBox ────────────────────
def save(file, out):
    with call("GET", f"{CORTEX}/{file}") as res:
        with open(out, "wb") as f:
            f.write(res.read())
    call("DELETE", f"{CORTEX}/{file}").close()            # the result stays on my PC only

결과 파일은 CORTEX 주소 뒤에 파일 이름을 붙여 GET으로 받습니다. 받은 뒤에는 DELETE로 FlameBox에 남은 파일을 지웁니다. 지우지 않으면 내 PC에 생성 파일이 계속 쌓입니다.

5. 실행부

# ── 3. Command line ──────────────────────────────────────────────────────────
def main():
    ap = argparse.ArgumentParser(description="FLUX 3 이미지 생성 (영어 프롬프트 권장)")
    ap.add_argument("prompt", help="그릴 내용 — 영어로 자세히")
    ap.add_argument("-o", "--output", help="저장할 파일 이름 (기본: gen-….png)")
    ap.add_argument("--size", default="1024x1024", help="가로x세로, 32의 배수 (기본 1024x1024)")
    ap.add_argument("--seed", type=int, default=-1, help="같은 그림을 다시 얻을 때 (기본 -1 = 무작위)")
    a = ap.parse_args()
    if not URL or not KEY:
        raise SystemExit("파일 위쪽의 API_URL, SECRET_KEY 를 내 값으로 바꾸거나 환경변수 FLAMEAI_API_URL, FLAMEAI_SECRET_KEY 를 설정하세요")
    width, height = (int(v) for v in a.size.lower().split("x"))

    t0 = time.time()
    result = generate(a.prompt, width, height, a.seed)
    file = result["files"][0]
    out = a.output or file.split("/")[-1]
    save(file, out)
    print(f"저장: {out}  ({result['width']}x{result['height']}, seed {result['seed']}, {time.time() - t0:.0f}초)")


if __name__ == "__main__":
    main()

6. 실행 결과

> python flux3_image.py -o cabin.png "A small wooden cabin by a calm lake at sunrise, mist over the water, pine forest, warm golden light, photorealistic, wide shot"
모델을 올리는 중... (처음 한 번은 오래 걸릴 수 있습니다)
그리는 중 20/20
저장: cabin.png  (1024x1024, seed 1381978895, 50초)
FLUX 3가 그린, 해 뜨는 호숫가의 작은 나무 오두막과 물안개, 소나무 숲

[그림1. cabin.png — FLUX 3, 1024×1024]

> python flux3_image.py --size 1024x576 --seed 42 -o bike.png "A red vintage bicycle leaning against a blue wooden door on a narrow European street, morning sunlight, flower pots, photorealistic"
그리는 중 20/20
저장: bike.png  (1024x576, seed 42, 13초)
FLUX 3가 그린, 유럽 골목의 파란 나무 문에 기대 세워진 빨간 자전거와 화분

[그림2. bike.png — FLUX 3, 1024×576]

실제 실행 결과입니다(진행률 줄은 마지막 한 줄만 남겼습니다). 첫 장은 모델을 올리는 시간까지 더해 50초, 모델이 올라간 뒤 두 번째 장은 13초였습니다. 시간은 FlameBox PC의 GPU와 그림 크기에 따라 달라집니다.

완성된 소스는 GitHub에 — 위 코드를 모은 Python 파일 하나와 README입니다. FlameAI-Playground/apps › flux3-python

7. 알아 둘 점

  • 영어로 자세히 — FLUX 3는 영어로 구도·조명·색감·스타일까지 자세히 쓸 때 결과가 좋습니다. 짧은 한국어 요청을 자세한 영어로 바꿔 주는 FLUX 3 Prompt Upsampler도 함께 제공됩니다(FLUX 3 지원 공지).
  • 크기는 32의 배수 — 기본값은 1024×1024입니다. 클수록 오래 걸리고 메모리를 많이 씁니다.
  • 메모리 — 같은 PC에 큰 대화 모델이 함께 올라가 있으면 생성이 실패할 수 있습니다. 그때는 쓰지 않는 Cortex를 내리고 다시 하세요.
  • 라이선스 — FLUX Kommunity License입니다. 연 매출 500만 달러 미만의 개인·기업은 상업적 이용이 무료이며, 자세한 조건은 라이선스 원문을 확인하세요.

다음 단계

업샘플러로 프롬프트를 다듬은 뒤 FLUX 3로 그리는 2단계 방식을 쓰면 짧은 요청으로도 좋은 그림을 얻을 수 있습니다. 사진을 고치는 방법은 AI 사진 편집기를, 전체 API는 API 매뉴얼을 보세요.