안녕하세요! 👋 Streamlit으로 프로토타입을 만들어봤다면, 이제는 FastAPI로 실제 서비스 가능한 튼튼한 백엔드 API를 구축해볼 차례입니다! 🌪️💨
코드를 한 파일에 다 넣으면 나중에 수정할 때 머리가 지끈지끈하겠죠? 🤯 그래서 오늘은 유지보수하기 딱 좋은 **"모듈형 프로젝트 구조"**를 소개합니다! 📂✨
📂 1. 전체 프로젝트 구조 미리보기 (Tree View) 🌳
먼저 폴더 정리를 어떻게 할지 큰 그림을 그려봐요! 👀
Plaintext
my_ai_project/ 📁
├── main.py # 🏁 앱의 시작점! (Entry Point)
├── app/ # 📦 핵심 로직들이 모여있는 곳
│ ├── __init__.py
│ ├── schemas.py # 📝 데이터의 모양(입출력)을 정의 (Pydantic)
│ ├── model_loader.py # 🧠 AI 모델을 불러오고 예측하는 로직
│ └── api/ # 🛣️ URL 경로(엔드포인트)를 관리
│ ├── __init__.py
│ └── endpoints.py # 실제 API 동작 함수들
└── requirements.txt # 📚 필요한 라이브러리 목록
📝 2. 데이터 규칙 정하기: schemas.py
손님(Client)이 아무 데이터나 던지면 곤란하겠죠? 🙅♀️ Pydantic을 사용해서 데이터의 입출력 규격을 딱 정해줍니다! ✅
Python
# @title app/schemas.py
from pydantic import BaseModel
# 입력 데이터 형식: 붓꽃(Iris) 정보를 예시로 들어볼게요 🌸
class PredictionInput(BaseModel):
sepal_length: float
sepal_width: float
petal_length: float
petal_width: float
# 출력 데이터 형식: 모델이 예측한 결과 🏷️
class PredictionOutput(BaseModel):
class_name: str
confidence: float
🧠 3. AI 두뇌 만들기: model_loader.py
AI 모델을 로드하고 예측하는 핵심 로직은 여기서 담당해요! 🤖 모델을 매번 로드하지 않도록 클래스로 만들어서 관리하는 게 포인트! 🌟
Python
# @title app/model_loader.py
import random # 실제로는 torch나 sklearn 등을 사용하세요! 😉
class AIModel:
def __init__(self):
self.model = None
def load_model(self):
print("모델 로딩 중... 으라차차! 🏋️♀️")
# 여기서 torch.load('model.pth') 등을 수행합니다.
self.model = "My Awesome Model"
print("모델 로딩 완료! 🟢")
def predict(self, input_data: list):
# 실제 모델 추론 로직이 들어갈 자리 🕵️♀️
# 예시로 랜덤한 결과를 반환합니다.
classes = ["Setosa", "Versicolor", "Virginica"]
return {
"class_name": random.choice(classes),
"confidence": 0.95
}
# 싱글톤처럼 전역 변수로 인스턴스 생성 🌐
ai_model = AIModel()
🛣️ 4. 주문 받기: api/endpoints.py
실제 URL 주소와 기능을 연결해주는 곳이에요! 🔗 APIRouter를 사용해서 길을 터줍니다. 🚦
Python
# @title app/api/endpoints.py
from fastapi import APIRouter, HTTPException
from app.schemas import PredictionInput, PredictionOutput
from app.model_loader import ai_model
router = APIRouter()
@router.post("/predict", response_model=PredictionOutput)
async def predict_flower(input_data: PredictionInput):
# 모델이 로드되지 않았으면 에러! 🚨
if not ai_model.model:
raise HTTPException(status_code=503, detail="모델이 아직 준비되지 않았어요 😢")
# 입력 데이터를 리스트로 변환해서 예측 요청 📨
data_list = [
input_data.sepal_length,
input_data.sepal_width,
input_data.petal_length,
input_data.petal_width
]
result = ai_model.predict(data_list)
return result
🏁 5. 문 열기: main.py
마지막으로 모든 조각을 모아서 앱을 실행합니다! 🧩 Lifespan(수명 주기) 기능을 써서 앱이 켜질 때 모델을 딱 한 번만 로드하게 설정해요! ⚡️
Python
# @title main.py
from fastapi import FastAPI
from contextlib import asynccontextmanager
from app.model_loader import ai_model
from app.api import endpoints
# 앱이 시작될 때 모델을 로드하고, 꺼질 때 정리하는 설정 🔄
@asynccontextmanager
async def lifespan(app: FastAPI):
# 시작 전 실행 (Startup) ☀️
ai_model.load_model()
yield
# 종료 후 실행 (Shutdown) 🌙
print("모델 메모리 해제 및 정리 👋")
app = FastAPI(lifespan=lifespan)
# 라우터 연결! 🔌
app.include_router(endpoints.router, prefix="/api/v1")
@app.get("/")
def read_root():
return {"message": "AI API 서버가 정상 작동 중입니다! 🚀✨"}
💡 쉽고 정확한 비유: "체계적인 레스토랑 주방" 👨🍳🍽️
FastAPI의 구조를 나누는 건 레스토랑을 운영하는 것과 비슷해요!
- main.py 👉 지배인 (Manager) 🤵 : 레스토랑 문을 열고(Startup), 각 파트가 잘 돌아가는지 총괄해요.
- schemas.py 👉 주문서 양식 (Order Ticket) 📝 : 손님이 "아무거나" 달라고 하면 안 되죠? 정해진 메뉴판과 주문서 양식대로만 주문을 받아요.
- api/endpoints.py 👉 웨이터 (Waiter) 💁♂️ : 홀에서 손님의 주문(Request)을 받아서 주방으로 전달하고, 완성된 요리(Response)를 서빙해요.
- model_loader.py 👉 메인 셰프 (Head Chef) 👩🍳 : 실제로 요리(예측, Inference)를 하는 핵심 인물이에요! 재료 손질(모델 로드)은 오픈 전에 미리 다 해놓는답니다.
'AI 엔지니어준비' 카테고리의 다른 글
| 컴퓨터 비전 네 가지 개념 설명 (이미지 분류, 객체 인식, 이미지 세그멘테이션, 이미지 생성) (1) | 2026.01.15 |
|---|---|
| 🏛️ [실전 아키텍처] Next.js와 FastAPI로 구축하는 AI 패션 코디 서비스 "FitCheck" 설계도 🎨👗 (1) | 2026.01.05 |
| 🚀 Streamlit으로 AI 모델 웹 앱 만들기: 3단계 완전 정복! 🛠️ (0) | 2026.01.05 |
| 🚀 LangSmith 사용 여부의 차이점 (0) | 2025.12.04 |
| 💡 Word2Vec: GPT의 조상, 단어의 의미를 담는 벡터 (0) | 2025.11.14 |