시연 영상은 다음과 같다. 보안상 흐릿하긴 하지만 느낌만 알면 좋겠다.
원글은
https://brunch.co.kr/@hajunho/1077
다음 서비스에서 UI 바꾸고, IP 필터링 기능 + 안정성 + Queue 구조를 강화하였다. 이 글은 멤버십 글로 초기 소스를 공개한다. 실험이 성공적인 초기 코드 조각은 아주 강력한 챗봇(LLM) 답변을 만들 수 있다. 고급편의 내 글은... 다른 글에 쓰지 않더라도 프로그래머라면, 긁어가기 위해 크롬 개발자 모드는 이용할 수 있다는 것을 항상 가정한다. 프로그래머가 아니라면 머릿속에 keywords 만 필터링해서 저장할 수 있는 기억 능력이 있다고 가정한다.
파일은 단 2개다.
# main.py
import os
import time
import torch
from collections import deque, defaultdict
from fastapi import FastAPI, Request, BackgroundTasks, Form
from fastapi.responses import HTMLResponse, FileResponse, JSONResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from diffusers import StableDiffusion3Pipeline
app = FastAPI()
# 디렉토리 설정
GENERATED_DIR = './generated_images'
STATIC_DIR = './static'
os.makedirs(GENERATED_DIR, exist_ok=True)
os.makedirs(STATIC_DIR, exist_ok=True)
# 템플릿 설정
templates = Jinja2Templates(directory="templates")
# 정적 파일 서빙
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
app.mount("/generated_images", StaticFiles(directory=GENERATED_DIR), name="generated_images")
# 접속 제한 관리
ip_connections = defaultdict(int)
MAX_CONNECTIONS_PER_IP = 5
# 작업 큐
queue = deque()
current_task = None
# Stable Diffusion 3.5 Large 모델 로딩 (A6000 최적화)
print("� 모델 초기화 중...")
pipe = StableDiffusion3Pipeline.from_pretrained(
"stabilityai/stable-diffusion-3.5-large",
torch_dtype=torch.float16,
use_safetensors=True,
low_cpu_mem_usage=True
)
pipe.enable_attention_slicing()
pipe = pipe.to("cuda")
print("모델 로딩 완료")
# GPU 메모리 정리 함수
def cleanup_gpu_memory():
torch.cuda.empty_cache()
# 백그라운드 작업 (프롬프트 기반 이미지 생성)
def generate_image_task(filename: str, prompt: str, client_ip: str):
global current_task
current_task = filename
try:
print(f"이미지 생성 시작: {prompt[:50]}...")
image = pipe(
prompt=prompt,
num_inference_steps=40,
guidance_scale=7.5,
width=1024,
height=1024,
).images[0]
base_path = os.path.join(GENERATED_DIR, filename)
image.save(base_path)
print(f"이미지 생성 완료: {filename}")
except Exception as e:
지금 바로 작가의 멤버십 구독자가 되어
멤버십 특별 연재 콘텐츠를 모두 만나 보세요.
오직 멤버십 구독자만 볼 수 있는,
이 작가의 특별 연재 콘텐츠