DALL-E 3 이미지 생성
from openai import OpenAI
import httpx
from pathlib import Path
client = OpenAI()
def generate_image(
prompt: str,
size: str = "1024x1024", # 1024x1024, 1792x1024, 1024x1792
quality: str = "standard", # standard or hd
style: str = "vivid", # vivid or natural
n: int = 1,
) -> list[str]:
"""이미지 URL 목록 반환"""
response = client.images.generate(
model="dall-e-3",
prompt=prompt,
size=size,
quality=quality,
style=style,
n=n,
)
return [img.url for img in response.data]
# 사용
urls = generate_image(
prompt="미래적인 한국 도시 전경, 밤, 네온사인, 사이버펑크 스타일",
size="1792x1024",
quality="hd",
)
# 이미지 다운로드
def download_image(url: str, path: str) -> None:
response = httpx.get(url)
Path(path).write_bytes(response.content)
download_image(urls[0], "generated.png")
프롬프트 자동 개선
GPT-4o로 프롬프트를 먼저 개선한 후 생성합니다.
def enhance_prompt(user_prompt: str) -> str:
response = client.chat.completions.create(
model="gpt-4o",
messages=[{
"role": "system",
"content": """당신은 DALL-E 이미지 생성 프롬프트 전문가입니다.
사용자의 간단한 설명을 DALL-E 3에 최적화된 상세한 프롬프트로 변환합니다.
다음을 포함하세요:
- 주제/오브젝트 상세 묘사
- 스타일 (사진적, 일러스트, 수채화 등)
- 조명 (자연광, 골든아워 등)
- 분위기/무드
- 기술적 특성 (초점, 앵글 등)"""
}, {
"role": "user",
"content": user_prompt
}],
max_tokens=300,
)
return response.choices[0].message.content
# 사용
basic = "강아지가 공원에서 뛰는 장면"
enhanced = enhance_prompt(basic)
print(f"개선된 프롬프트:\n{enhanced}")
urls = generate_image(enhanced, quality="hd")
이미지 배리에이션
def create_variation(image_path: str) -> list[str]:
"""기존 이미지의 변형 생성 (DALL-E 2 기능)"""
with open(image_path, "rb") as f:
response = client.images.create_variation(
image=f,
n=3,
size="1024x1024",
)
return [img.url for img in response.data]
이미지 편집 (Inpainting)
def edit_image(
image_path: str,
mask_path: str, # 흰 부분 = 편집 영역, 검정 = 유지
prompt: str,
) -> str:
with open(image_path, "rb") as img, open(mask_path, "rb") as mask:
response = client.images.edit(
image=img,
mask=mask,
prompt=prompt,
n=1,
size="1024x1024",
)
return response.data[0].url
# 예: 배경을 설산으로 변경
url = edit_image(
"portrait.png",
"background_mask.png",
"snowy mountain background, photorealistic"
)
이미지 생성 파이프라인
import asyncio
import httpx
async def batch_generate(prompts: list[str]) -> list[bytes]:
"""여러 이미지 병렬 생성"""
async def generate_one(prompt: str) -> bytes:
response = client.images.generate(
model="dall-e-3",
prompt=prompt,
size="1024x1024",
)
url = response.data[0].url
async with httpx.AsyncClient() as http:
r = await http.get(url)
return r.content
tasks = [generate_one(p) for p in prompts]
return await asyncio.gather(*tasks)
# 상품 이미지 배치 생성
product_prompts = [
"커피 머그컵, 흰 배경, 제품 사진 스타일",
"노트북 파우치, 가죽 재질, 스튜디오 조명",
"무선 이어폰 케이스, 미니멀 디자인",
]
images = asyncio.run(batch_generate(product_prompts))
for i, img_bytes in enumerate(images):
Path(f"product_{i}.png").write_bytes(img_bytes)
안전 필터와 수정된 프롬프트
response = client.images.generate(
model="dall-e-3",
prompt="폭발하는 도시",
)
# DALL-E 3는 프롬프트를 자동으로 수정할 수 있음
revised = response.data[0].revised_prompt
print(f"수정된 프롬프트: {revised}")
정리
| API | 기능 |
|---|---|
images.generate | 텍스트 → 이미지 (DALL-E 3) |
images.edit | 마스크 기반 이미지 편집 |
images.create_variation | 이미지 변형 생성 |
quality="hd" | 더 세밀한 이미지 ($0.08/장) |
다음 편에서는 오디오 처리 — Whisper 음성 인식과 TTS 음성 합성을 배웁니다.