first commit

This commit is contained in:
bluebamus committed 2025-10-31 15:56:42 +09:00
1 parent 78da3838f0
commit 09c86adf7b
486 files changed
+47300

No files matched your search

+540
View File
@@ -0,0 +1,540 @@
# O2Sound API Documentation
## 목차
1. [개요](#개요)
2. [인증](#인증)
3. [API 엔드포인트](#api-엔드포인트)
- [기본 엔드포인트](#기본-엔드포인트)
- [인증 API](#인증-api)
- [소셜 로그인 API](#소셜-로그인-api)
- [사용자 API](#사용자-api)
- [비디오 스트리밍 API](#비디오-스트리밍-api)
- [영상 제작 API](#영상-제작-api)
4. [에러 처리](#에러-처리)
5. [워크플로우 상세](#워크플로우-상세)
## 개요
### 기본 정보
- **Base URL**: `http://localhost:8000`
- **API Version**: v1
- **Framework**: FastAPI
- **Documentation**: `/docs` (Swagger UI), `/redoc` (ReDoc)
### 기술 스택
- **백엔드 프레임워크**: FastAPI
- **비동기 작업 처리**: Celery
- **메시지 브로커**: Redis
- **데이터베이스**: PostgreSQL (추정)
- **인증**: Session-based + OAuth 2.0 (Google)
### 응답 형식
모든 API 응답은 `@response_wrapper` 데코레이터를 통해 일관된 형식으로 반환됩니다.
## 인증
### 세션 기반 인증
- 로그인 후 세션 쿠키를 통한 인증
- SessionMiddleware 사용
### OAuth 2.0
- Google OAuth 지원
- 임시 토큰을 통한 안전한 토큰 교환
## API 엔드포인트
### 기본 엔드포인트
#### 서비스 정보 확인
```http
GET /
```
**응답 예시:**
```json
{
"message": "FastAPI DDD with Celery Workers",
"version": "1.0.0",
"docs": "/docs"
}
```
#### 헬스 체크
```http
GET /health
```
**응답 예시:**
```json
{
"status": "healthy",
"database": "connected",
"redis": "connected",
"celery": "running"
}
```
### 인증 API
#### 회원가입
```http
POST /auth/join
Content-Type: application/json
```
**요청 본문:**
```json
{
"user_id": "testuser",
"name": "홍길동",
"password": "securepassword123",
"email": "test@example.com",
"phone_number": "010-1234-5678"
}
```
**응답 (201 Created):**
```json
{
"id": "123e4567-e89b-12d3-a456-426614174000",
"name": "홍길동"
}
```
#### 로그인
```http
POST /auth/login
Content-Type: application/json
```
**요청 본문:**
```json
{
"user_id": "testuser",
"password": "securepassword123"
}
```
**응답 (200 OK):**
```json
{
"id": "123e4567-e89b-12d3-a456-426614174000",
"name": "홍길동"
}
```
### 소셜 로그인 API
#### Google OAuth 로그인 시작
```http
GET /social/google/login?return_url=http://localhost:3300/dashboard
```
**쿼리 파라미터:**
- `return_url` (선택): 로그인 성공 후 리다이렉트할 URL
**응답:**
- Google OAuth 인증 페이지로 302 리다이렉트
#### Google OAuth 콜백
```http
GET /social/google/callback?code=AUTHORIZATION_CODE&state=STATE
```
**쿼리 파라미터:**
- `code`: Google에서 제공한 인증 코드
- `state`: CSRF 방지를 위한 상태 값
- `error` (선택): OAuth 에러 발생 시
**응답:**
- 성공: `{return_url}?token={temp_token_id}&auth_success=true`로 리다이렉트
- 실패: `http://localhost:3300/auth/error?error={error_message}`로 리다이렉트
#### Google 토큰 정보 조회
```http
GET /social/google/token/{temp_token_id}
```
**경로 파라미터:**
- `temp_token_id`: 임시 토큰 ID
**응답 (200 OK):**
```json
{
"access_token": "ya29.a0AfH6SMBx...",
"refresh_token": "1//0gVO1VQ...",
"token_type": "Bearer",
"expires_in": 3599,
"user_info": {
"id": "google_user_id",
"email": "user@gmail.com",
"name": "사용자 이름",
"picture": "https://lh3.googleusercontent.com/..."
}
}
```
### 사용자 API
#### 사용자 업체 목록 조회
```http
POST /user/items
Content-Type: application/json
```
**요청 본문:**
```json
{
"id": "123e4567-e89b-12d3-a456-426614174000"
}
```
**응답 (200 OK):**
```json
{
"total_count": 2,
"items": [
{
"item_id": "550e8400-e29b-41d4-a716-446655440000",
"name": "카페 블루문",
"address": "서울시 강남구 역삼동 123-45",
"url": "https://bluemoon.cafe",
"phone_number": "02-1234-5678",
"thumbnail_url": "https://example.com/thumb1.jpg",
"hashtags": ["카페", "브런치", "디저트"]
}
]
}
```
#### 업체 정보 수정
```http
PUT /user/item/update
Content-Type: application/json
```
**요청 본문:**
```json
{
"id": "123e4567-e89b-12d3-a456-426614174000",
"item_id": "550e8400-e29b-41d4-a716-446655440000",
"name": "카페 블루문 강남점",
"address": "서울시 강남구 역삼동 123-45",
"url": "https://bluemoon-gangnam.cafe",
"phone_number": "02-1234-5678",
"thumbnail_url": "https://example.com/new-thumb.jpg"
}
```
**응답 (200 OK):**
```json
{
"success": true,
"item_id": "550e8400-e29b-41d4-a716-446655440000"
}
```
#### 업체 삭제
```http
DELETE /user/item/delete
Content-Type: application/json
```
**요청 본문:**
```json
{
"id": "123e4567-e89b-12d3-a456-426614174000",
"item_id": "550e8400-e29b-41d4-a716-446655440000"
}
```
**응답 (200 OK):**
```json
{
"success": true,
"item_id": "550e8400-e29b-41d4-a716-446655440000"
}
```
#### 사용자 비디오 목록 조회
```http
POST /user/videos
Content-Type: application/json
```
**요청 본문:**
```json
{
"id": "123e4567-e89b-12d3-a456-426614174000"
}
```
**응답 (200 OK):**
```json
{
"total_count": 3,
"videos": [
{
"id": "660e8400-e29b-41d4-a716-446655440000",
"title": "카페 블루문 홍보 영상",
"description": "아늑한 분위기의 카페 블루문을 소개합니다",
"url": "/user/video/bluemoon_promo_2024.mp4",
"is_uploaded": true,
"download_count": 15,
"resolution": "1920x1080",
"status": "completed",
"thumbnail_url": "https://example.com/video-thumb1.jpg"
}
]
}
```
#### 비디오 삭제
```http
DELETE /user/video/delete
Content-Type: application/json
```
**요청 본문:**
```json
{
"user_id": "testuser",
"video_id": "660e8400-e29b-41d4-a716-446655440000"
}
```
**응답 (200 OK):**
```json
{
"message": "비디오가 성공적으로 삭제되었습니다"
}
```
#### 사용자 프로필 조회
```http
POST /user/profile
Content-Type: application/json
```
**요청 본문:**
```json
{
"id": "123e4567-e89b-12d3-a456-426614174000"
}
```
**응답 (200 OK):**
```json
{
"id": "123e4567-e89b-12d3-a456-426614174000",
"name": "홍길동",
"email": "test@example.com",
"phone_number": "010-1234-5678",
"created_at": "2024-01-15T10:30:00Z"
}
```
#### 프로필 수정
```http
PUT /user/profile/update
Content-Type: application/json
```
**요청 본문:**
```json
{
"id": "123e4567-e89b-12d3-a456-426614174000",
"name": "홍길동",
"email": "newemail@example.com",
"phone_number": "010-9876-5432"
}
```
**응답 (200 OK):**
```json
{
"user_id": "testuser",
"name": "홍길동"
}
```
### 비디오 스트리밍 API
#### 비디오 파일 스트리밍
```http
GET /user/video/{filename}
```
**경로 파라미터:**
- `filename`: 비디오 파일명 (URL 인코딩 지원)
**예시:**
```http
GET /user/video/bluemoon_promo_2024.mp4
```
**응답:**
- Content-Type: `video/mp4`
- 비디오 파일 스트리밍
**에러 응답 (404 Not Found):**
```json
{
"detail": "Video not found"
}
```
### 영상 제작 API
#### 영상 제작 워크플로우 시작
```http
POST /moviemaker/start-workflow
Content-Type: application/json
```
**요청 본문:**
```json
{
"url": "https://bluemoon.cafe"
}
```
**응답 (200 OK):**
```json
{
"task_id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
"progress": {
"metadata": false,
"lyrics": false,
"songs": false,
"images": false,
"movies": false,
"combined": false
}
}
```
#### 워크플로우 진행률 확인
```http
POST /moviemaker/progress
Content-Type: application/json
```
**요청 본문:**
```json
{
"task_id": "f47ac10b-58cc-4372-a567-0e02b2c3d479"
}
```
**응답 (200 OK):**
```json
{
"progress": {
"metadata": true,
"lyrics": true,
"songs": true,
"images": false,
"movies": false,
"combined": false
}
}
```
## 에러 처리
### 표준 에러 응답 형식
```json
{
"error_code": "ERROR_CODE",
"error_message": "사용자 친화적인 에러 메시지"
}
```
### 일반적인 HTTP 상태 코드
- `200 OK`: 요청 성공
- `201 Created`: 리소스 생성 성공
- `400 Bad Request`: 잘못된 요청
- `401 Unauthorized`: 인증 필요
- `403 Forbidden`: 권한 없음
- `404 Not Found`: 리소스를 찾을 수 없음
- `422 Unprocessable Entity`: 유효성 검사 실패
- `500 Internal Server Error`: 서버 오류
### 에러 코드 예시
- `AUTH_001`: 잘못된 로그인 정보
- `AUTH_002`: 이미 존재하는 사용자 ID
- `USER_001`: 사용자를 찾을 수 없음
- `VIDEO_001`: 비디오를 찾을 수 없음
- `TASK_001`: 작업을 찾을 수 없음
## 워크플로우 상세
### 영상 제작 프로세스
1. **URL 크롤링 (task1_crawl)**
- 입력 URL에서 메타데이터 추출
- 업체명, 설명, 키워드 등 수집
2. **병렬 처리**
**가사 및 음악 생성 브랜치:**
- **가사 생성 (task2_generate_lyrics)**
- 크롤링한 메타데이터 기반 가사 생성
- AI 모델을 통한 창의적인 가사 작성
- **음악 생성 (task3_generate_music)**
- 생성된 가사에 맞는 음악 제작
- 장르, 템포, 분위기 자동 매칭
**이미지 및 비디오 생성 브랜치:**
- **이미지 크롤링 (task1_crawl_images)**
- 웹사이트에서 관련 이미지 수집
- 품질 및 관련성 필터링
- **비디오 생성 (task4_generate_video)**
- 수집된 이미지로 비디오 제작
- 전환 효과 및 애니메이션 적용
3. **최종 병합 (task5_merge_results)**
- 음악과 비디오 동기화
- 최종 영상 파일 생성
- 업로드 및 저장
### 진행률 추적
- Redis를 통한 실시간 상태 업데이트
- 각 단계별 완료 상태 확인 가능
- 비동기 작업으로 긴 처리 시간 대응
## 개발 가이드
### 로컬 개발 환경 실행
```bash
# Poetry 환경 설정
poetry install
# 환경 변수 설정
cp .env.local .env
# Redis 실행 (Docker)
docker run -d -p 6379:6379 redis
# Celery Worker 실행
./run-celery.sh
# FastAPI 서버 실행
./run-local.sh
```
### API 테스트
- Swagger UI: `http://localhost:8000/docs`
- ReDoc: `http://localhost:8000/redoc`
### 프로덕션 배포
```bash
# Docker 이미지 빌드
docker build -t o2sound-backend .
# 프로덕션 실행
./run-prod.sh
```
+367
View File
@@ -0,0 +1,367 @@
# O2Sound API Quick Reference
## Authentication Endpoints
### Register
```bash
curl -X POST http://localhost:8000/auth/join \
-H "Content-Type: application/json" \
-d '{
"user_id": "john_doe",
"name": "John Doe",
"password": "SecurePass123!",
"email": "john@example.com",
"phone_number": "010-1234-5678"
}'
```
### Login
```bash
curl -X POST http://localhost:8000/auth/login \
-H "Content-Type: application/json" \
-d '{
"user_id": "john_doe",
"password": "SecurePass123!"
}'
```
## User Management Endpoints
### Get User Items
```bash
curl -X POST http://localhost:8000/user/items \
-H "Content-Type: application/json" \
-H "Cookie: session=YOUR_SESSION_COOKIE" \
-d '{
"id": "123e4567-e89b-12d3-a456-426614174000"
}'
```
### Update Item
```bash
curl -X PUT http://localhost:8000/user/item/update \
-H "Content-Type: application/json" \
-H "Cookie: session=YOUR_SESSION_COOKIE" \
-d '{
"id": "123e4567-e89b-12d3-a456-426614174000",
"item_id": "550e8400-e29b-41d4-a716-446655440000",
"name": "Updated Business Name",
"address": "New Address",
"url": "https://newurl.com",
"phone_number": "02-9876-5432"
}'
```
### Delete Item
```bash
curl -X DELETE http://localhost:8000/user/item/delete \
-H "Content-Type: application/json" \
-H "Cookie: session=YOUR_SESSION_COOKIE" \
-d '{
"id": "123e4567-e89b-12d3-a456-426614174000",
"item_id": "550e8400-e29b-41d4-a716-446655440000"
}'
```
## Video Management Endpoints
### Get User Videos
```bash
curl -X POST http://localhost:8000/user/videos \
-H "Content-Type: application/json" \
-H "Cookie: session=YOUR_SESSION_COOKIE" \
-d '{
"id": "123e4567-e89b-12d3-a456-426614174000"
}'
```
### Delete Video
```bash
curl -X DELETE http://localhost:8000/user/video/delete \
-H "Content-Type: application/json" \
-H "Cookie: session=YOUR_SESSION_COOKIE" \
-d '{
"user_id": "john_doe",
"video_id": "660e8400-e29b-41d4-a716-446655440000"
}'
```
### Stream Video
```bash
# Direct browser access or video player
http://localhost:8000/user/video/my_video_2024.mp4
# Using curl (saves to file)
curl -o downloaded_video.mp4 \
http://localhost:8000/user/video/my_video_2024.mp4
```
## Profile Management Endpoints
### Get Profile
```bash
curl -X POST http://localhost:8000/user/profile \
-H "Content-Type: application/json" \
-H "Cookie: session=YOUR_SESSION_COOKIE" \
-d '{
"id": "123e4567-e89b-12d3-a456-426614174000"
}'
```
### Update Profile
```bash
curl -X PUT http://localhost:8000/user/profile/update \
-H "Content-Type: application/json" \
-H "Cookie: session=YOUR_SESSION_COOKIE" \
-d '{
"id": "123e4567-e89b-12d3-a456-426614174000",
"name": "John Doe Updated",
"email": "john.updated@example.com",
"phone_number": "010-9999-8888"
}'
```
## Movie Maker Endpoints
### Start Video Generation Workflow
```bash
curl -X POST http://localhost:8000/moviemaker/start-workflow \
-H "Content-Type: application/json" \
-H "Cookie: session=YOUR_SESSION_COOKIE" \
-d '{
"url": "https://example-business.com"
}'
```
### Check Progress
```bash
curl -X POST http://localhost:8000/moviemaker/progress \
-H "Content-Type: application/json" \
-H "Cookie: session=YOUR_SESSION_COOKIE" \
-d '{
"task_id": "f47ac10b-58cc-4372-a567-0e02b2c3d479"
}'
```
## Google OAuth Flow
### 1. Initiate Login
```bash
# Browser redirect
http://localhost:8000/social/google/login?return_url=http://localhost:3300/dashboard
```
### 2. After Google Authentication
```bash
# Google redirects to:
http://localhost:8000/social/google/callback?code=AUTH_CODE&state=STATE_VALUE
```
### 3. Get Token Info
```bash
curl -X GET http://localhost:8000/social/google/token/TEMP_TOKEN_ID
```
## Health Check
```bash
# Basic health check
curl http://localhost:8000/health
# Service info
curl http://localhost:8000/
```
## WebSocket Connection (if implemented)
```javascript
// JavaScript WebSocket example for real-time progress
const ws = new WebSocket('ws://localhost:8000/ws/progress/{task_id}');
ws.onmessage = (event) => {
const progress = JSON.parse(event.data);
console.log('Progress update:', progress);
};
```
## Python Client Example
```python
import requests
import json
class O2SoundClient:
def __init__(self, base_url="http://localhost:8000"):
self.base_url = base_url
self.session = requests.Session()
def login(self, user_id, password):
response = self.session.post(
f"{self.base_url}/auth/login",
json={"user_id": user_id, "password": password}
)
return response.json()
def start_video_generation(self, url):
response = self.session.post(
f"{self.base_url}/moviemaker/start-workflow",
json={"url": url}
)
return response.json()
def check_progress(self, task_id):
response = self.session.post(
f"{self.base_url}/moviemaker/progress",
json={"task_id": task_id}
)
return response.json()
# Usage
client = O2SoundClient()
client.login("john_doe", "SecurePass123!")
result = client.start_video_generation("https://example.com")
task_id = result["task_id"]
# Check progress
import time
while True:
progress = client.check_progress(task_id)
print(progress)
if progress["progress"]["combined"]:
break
time.sleep(5)
```
## JavaScript/TypeScript Client Example
```typescript
interface LoginRequest {
user_id: string;
password: string;
}
interface WorkflowRequest {
url: string;
}
interface ProgressRequest {
task_id: string;
}
class O2SoundAPI {
private baseURL: string;
constructor(baseURL: string = 'http://localhost:8000') {
this.baseURL = baseURL;
}
async login(credentials: LoginRequest) {
const response = await fetch(`${this.baseURL}/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify(credentials)
});
return response.json();
}
async startWorkflow(data: WorkflowRequest) {
const response = await fetch(`${this.baseURL}/moviemaker/start-workflow`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify(data)
});
return response.json();
}
async checkProgress(data: ProgressRequest) {
const response = await fetch(`${this.baseURL}/moviemaker/progress`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify(data)
});
return response.json();
}
}
// Usage
const api = new O2SoundAPI();
async function generateVideo(url: string) {
// Login first
await api.login({
user_id: 'john_doe',
password: 'SecurePass123!'
});
// Start workflow
const { task_id } = await api.startWorkflow({ url });
// Poll for progress
const checkStatus = async () => {
const { progress } = await api.checkProgress({ task_id });
if (progress.combined) {
console.log('Video generation complete!');
} else {
console.log('Progress:', progress);
setTimeout(checkStatus, 5000);
}
};
checkStatus();
}
```
## Environment Variables
```bash
# .env.local example
PROJECT_NAME=O2Sound
API_V1_STR=/api/v1
SESSION_SECRET_KEY=your-secret-key-here
DATABASE_URL=postgresql://user:pass@localhost/o2sound
REDIS_URL=redis://localhost:6379
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
GOOGLE_REDIRECT_URI=http://localhost:8000/social/google/callback
```
## Common Response Formats
### Success Response
```json
{
"status": "success",
"data": {
// Response data here
}
}
```
### Error Response
```json
{
"status": "error",
"error_code": "ERROR_CODE",
"error_message": "Human readable error message",
"details": {
// Additional error details if available
}
}
```
### Pagination Response (if implemented)
```json
{
"total_count": 100,
"page": 1,
"page_size": 20,
"total_pages": 5,
"items": [
// Array of items
]
}
```
+424
View File
@@ -0,0 +1,424 @@
# O2Sound Backend 개발자 가이드
## 프로젝트 구조
```
backend/
├── app/
│ ├── core/ # 핵심 설정 및 유틸리티
│ │ ├── celery_app.py # Celery 설정
│ │ ├── database.py # 데이터베이스 연결
│ │ ├── env_setting.py # 환경 변수 설정
│ │ └── redis/ # Redis 관련 설정
│ ├── domain/ # 도메인 모델
│ │ └── models/ # SQLAlchemy 모델
│ ├── infra/ # 인프라 레이어
│ │ └── google/ # Google OAuth 구현
│ ├── presentation/ # 프레젠테이션 레이어
│ │ ├── api/ # API 라우터
│ │ │ └── v1/ # v1 API 엔드포인트
│ │ └── schemas/ # Pydantic 스키마
│ ├── services/ # 비즈니스 로직
│ ├── shared/ # 공통 유틸리티
│ │ ├── decorator/ # 데코레이터
│ │ ├── logger.py # 로깅 설정
│ │ └── progress.py # 진행률 추적
│ └── workers/ # Celery 작업
│ └── tasks.py # 비동기 작업 정의
├── docs/ # API 문서
├── uploads/ # 업로드된 파일
├── main.py # FastAPI 앱 엔트리포인트
├── dependencies.py # 의존성 주입
├── pyproject.toml # Poetry 설정
└── Dockerfile # Docker 설정
```
## 핵심 개념
### 1. DDD (Domain-Driven Design) 구조
프로젝트는 DDD 원칙을 따라 구성되어 있습니다:
- **Domain Layer**: 비즈니스 엔티티와 도메인 로직
- **Application Layer**: 서비스와 비즈니스 유스케이스
- **Infrastructure Layer**: 외부 시스템과의 통합
- **Presentation Layer**: API 엔드포인트와 스키마
### 2. 의존성 주입
FastAPI의 의존성 주입 시스템을 활용:
```python
from app.dependencies import get_user_service
@router.post("/items")
async def get_items(
request: GetItemsRequest,
user_service: UserService = Depends(get_user_service)
):
return user_service.get_items(request)
```
### 3. Response Wrapper
모든 API 응답은 일관된 형식으로 래핑됩니다:
```python
from app.shared.decorator.response_wrapper import response_wrapper
@router.post("/login")
@response_wrapper
async def login(request: LoginRequest):
# 자동으로 성공/실패 형식으로 래핑됨
return auth_service.login(request)
```
## 주요 기능 구현
### 1. 인증 시스템
#### 세션 기반 인증
```python
# main.py
app.add_middleware(SessionMiddleware, secret_key=settings.SESSION_SECRET_KEY)
```
#### OAuth 2.0 (Google)
```python
# infra/google/service.py
class GoogleService:
async def get_login_url(self, return_url: Optional[str], request: Request):
# OAuth 플로우 시작
async def handle_callback(self, request: Request):
# 콜백 처리 및 토큰 교환
```
### 2. 비동기 작업 처리 (Celery)
#### 작업 정의
```python
# workers/tasks.py
@celery_app.task(bind=True)
def task1_crawl(self, url: str, root_task_id: str):
# 웹 크롤링 작업
process = Process(redis_manager)
process.update_progress(root_task_id, "metadata", True)
```
#### 워크플로우 체인
```python
# presentation/api/v1/moviemakers.py
workflow = chain(
crawl,
chord(
[lyrics_to_music, image_to_video],
task5_merge_results.s(root_task_id)
)
)
```
### 3. 진행률 추적
```python
# shared/progress.py
class Process:
def __init__(self, redis_manager: RedisManager):
self.redis = redis_manager
async def init_task_status(self, task_id: str):
# 초기 상태 설정
async def update_progress(self, task_id: str, step: str, completed: bool):
# 진행률 업데이트
```
## 개발 환경 설정
### 1. 초기 설정
```bash
# Poetry 설치
pip install poetry
# 의존성 설치
poetry install
# 환경 변수 설정
cp .env.local .env
```
### 2. 개발 서버 실행
```bash
# Redis 실행 (Docker)
docker run -d -p 6379:6379 redis
# PostgreSQL 실행 (Docker)
docker run -d -p 5432:5432 \
-e POSTGRES_USER=o2sound \
-e POSTGRES_PASSWORD=password \
-e POSTGRES_DB=o2sound \
postgres:14
# Celery Worker 실행
poetry run celery -A app.core.celery_app worker --loglevel=info
# FastAPI 개발 서버
poetry run uvicorn main:app --reload --port 8000
```
### 3. 환경 변수 설정 (.env)
```env
# 기본 설정
PROJECT_NAME=O2Sound
API_V1_STR=/api/v1
DEBUG=True
# 데이터베이스
DATABASE_URL=postgresql://o2sound:password@localhost:5432/o2sound
# Redis
REDIS_URL=redis://localhost:6379
# 세션
SESSION_SECRET_KEY=your-secret-key-here
# Google OAuth
GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret
GOOGLE_REDIRECT_URI=http://localhost:8000/social/google/callback
# Celery
CELERY_BROKER_URL=redis://localhost:6379/0
CELERY_RESULT_BACKEND=redis://localhost:6379/0
```
## 새로운 기능 추가하기
### 1. 새 엔드포인트 추가
#### Step 1: 스키마 정의
```python
# presentation/schemas/new_feature_schema.py
from pydantic import BaseModel
from uuid import UUID
class NewFeatureRequest(BaseModel):
user_id: UUID
feature_data: str
class NewFeatureResponse(BaseModel):
success: bool
result: str
```
#### Step 2: 서비스 구현
```python
# services/new_feature_service.py
class NewFeatureService:
def __init__(self, db_session):
self.db = db_session
def process_feature(self, request: NewFeatureRequest):
# 비즈니스 로직 구현
return NewFeatureResponse(success=True, result="processed")
```
#### Step 3: 라우터 추가
```python
# presentation/api/v1/new_feature.py
from fastapi import APIRouter, Depends
router = APIRouter(prefix="/new-feature", tags=["new-feature"])
@router.post("/process")
@response_wrapper
async def process_feature(
request: NewFeatureRequest,
service: NewFeatureService = Depends(get_new_feature_service)
):
return service.process_feature(request)
```
#### Step 4: 메인 앱에 등록
```python
# main.py
from app.presentation.api.v1.new_feature import router as new_feature_router
app.include_router(new_feature_router)
```
### 2. 새 Celery 작업 추가
```python
# workers/tasks.py
@celery_app.task(bind=True)
def new_async_task(self, data: dict, task_id: str):
try:
# 작업 시작
update_progress(task_id, "started", 0)
# 처리 로직
result = process_data(data)
# 완료
update_progress(task_id, "completed", 100)
return result
except Exception as e:
update_progress(task_id, "failed", -1)
raise
```
## 테스트
### 1. 단위 테스트
```python
# tests/test_auth.py
import pytest
from app.services.auth_service import AuthService
def test_user_registration():
service = AuthService(mock_db_session)
result = service.join(JoinRequest(
user_id="test_user",
name="Test User",
password="password123"
))
assert result.name == "Test User"
```
### 2. API 테스트
```python
# tests/test_api.py
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_health_check():
response = client.get("/health")
assert response.status_code == 200
assert response.json()["status"] == "healthy"
```
### 3. 통합 테스트
```bash
# Postman 컬렉션 실행
newman run tests/postman/O2Sound.postman_collection.json
```
## 배포
### 1. Docker 빌드
```bash
docker build -t o2sound-backend .
```
### 2. Docker Compose
```yaml
# docker-compose.yml
version: '3.8'
services:
backend:
image: o2sound-backend
ports:
- "8000:8000"
environment:
- DATABASE_URL=postgresql://user:pass@db:5432/o2sound
- REDIS_URL=redis://redis:6379
depends_on:
- db
- redis
worker:
image: o2sound-backend
command: celery -A app.core.celery_app worker
environment:
- CELERY_BROKER_URL=redis://redis:6379/0
depends_on:
- redis
db:
image: postgres:14
environment:
- POSTGRES_USER=user
- POSTGRES_PASSWORD=pass
- POSTGRES_DB=o2sound
redis:
image: redis:7
```
### 3. 프로덕션 체크리스트
- [ ] 환경 변수 확인
- [ ] 데이터베이스 마이그레이션
- [ ] Redis 연결 확인
- [ ] Celery Worker 실행
- [ ] 로그 설정
- [ ] 모니터링 설정
- [ ] 백업 전략 수립
## 모니터링
### 1. 로그 확인
```bash
# FastAPI 로그
tail -f logs/app.log
# Celery 로그
tail -f logs/celery.log
```
### 2. Celery Flower (웹 UI)
```bash
celery -A app.core.celery_app flower --port=5555
```
### 3. 성능 모니터링
- APM 도구 (예: New Relic, DataDog)
- Prometheus + Grafana
- ELK Stack (Elasticsearch, Logstash, Kibana)
## 문제 해결
### 일반적인 문제
1. **Redis 연결 실패**
```
❌ Redis 연결 실패: Connection refused
```
해결: Redis 서버가 실행 중인지 확인
2. **데이터베이스 연결 오류**
```
sqlalchemy.exc.OperationalError
```
해결: DATABASE_URL 및 PostgreSQL 서버 상태 확인
3. **Celery 작업 실패**
```
Task task1_crawl[...] raised unexpected
```
해결: Celery Worker 로그 확인 및 재시작
### 디버깅 팁
1. **FastAPI 자동 문서**
- Swagger UI: `http://localhost:8000/docs`
- ReDoc: `http://localhost:8000/redoc`
2. **대화형 디버깅**
```python
import pdb; pdb.set_trace()
```
3. **로그 레벨 조정**
```python
# 개발 환경에서 상세 로그
logger.setLevel(logging.DEBUG)
```
## 추가 리소스
- [FastAPI 공식 문서](https://fastapi.tiangolo.com/)
- [Celery 공식 문서](https://docs.celeryproject.org/)
- [SQLAlchemy 공식 문서](https://www.sqlalchemy.org/)
- [Redis 공식 문서](https://redis.io/documentation)
+87
View File
@@ -0,0 +1,87 @@
# O2Sound Backend API Documentation
O2Sound 백엔드 API 서버의 기술 문서입니다.
## 📚 문서 목록
### 1. [API Documentation](./API_Documentation.md)
전체 API 엔드포인트에 대한 상세한 설명과 사용법을 포함합니다.
- 인증 API
- 사용자 관리 API
- 영상 제작 API
- 소셜 로그인 API
- 에러 처리 가이드
### 2. [API Quick Reference](./API_Quick_Reference.md)
빠른 참조를 위한 API 호출 예제 모음입니다.
- cURL 명령어 예제
- Python 클라이언트 예제
- JavaScript/TypeScript 클라이언트 예제
- 환경 변수 설정
### 3. [Developer Guide](./Developer_Guide.md)
개발자를 위한 상세한 가이드입니다.
- 프로젝트 구조
- 개발 환경 설정
- 새 기능 추가 방법
- 테스트 및 배포
- 문제 해결
## 🚀 빠른 시작
### 요구사항
- Python 3.9+
- PostgreSQL 14+
- Redis 6+
- Poetry
### 설치 및 실행
```bash
# 1. 의존성 설치
poetry install
# 2. 환경 변수 설정
cp .env.local .env
# 3. 데이터베이스 마이그레이션
poetry run alembic upgrade head
# 4. 개발 서버 실행
poetry run uvicorn main:app --reload
```
### API 문서 확인
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
## 📋 주요 기능
1. **사용자 인증 및 관리**
- 회원가입/로그인
- Google OAuth 2.0
- 프로필 관리
2. **영상 제작 자동화**
- URL 기반 크롤링
- AI 가사 생성
- 음악 생성
- 비디오 제작
- 최종 병합
3. **비즈니스 관리**
- 업체 정보 CRUD
- 생성된 비디오 관리
- 비디오 스트리밍
## 🛠 기술 스택
- **웹 프레임워크**: FastAPI
- **비동기 작업**: Celery
- **메시지 브로커**: Redis
- **데이터베이스**: PostgreSQL
- **ORM**: SQLAlchemy
- **인증**: Session + OAuth 2.0
## 📞 문의
문제가 있거나 질문이 있으시면 이슈를 생성해주세요.