add logs for tracing processing task

This commit is contained in:
Dohyun Lim committed 2026-01-08 14:05:44 +09:00
1 parent efddee217a
commit 073777081e
81 files changed
+25300 -24561

No files matched your search

+61 -61
View File
@@ -1,61 +1,61 @@
from sqladmin import ModelView
from app.lyric.models import Lyric
class LyricAdmin(ModelView, model=Lyric):
name = "가사"
name_plural = "가사 목록"
icon = "fa-solid fa-music"
category = "가사 관리"
page_size = 20
column_list = [
"id",
"project_id",
"task_id",
"status",
"language",
"created_at",
]
column_details_list = [
"id",
"project_id",
"task_id",
"status",
"language",
"lyric_prompt",
"lyric_result",
"created_at",
]
# 폼(생성/수정)에서 제외
form_excluded_columns = ["created_at", "songs", "videos"]
column_searchable_list = [
Lyric.task_id,
Lyric.status,
Lyric.language,
]
column_default_sort = (Lyric.created_at, True) # True: DESC (최신순)
column_sortable_list = [
Lyric.id,
Lyric.project_id,
Lyric.status,
Lyric.language,
Lyric.created_at,
]
column_labels = {
"id": "ID",
"project_id": "프로젝트 ID",
"task_id": "작업 ID",
"status": "상태",
"language": "언어",
"lyric_prompt": "프롬프트",
"lyric_result": "생성 결과",
"created_at": "생성일시",
}
from sqladmin import ModelView
from app.lyric.models import Lyric
class LyricAdmin(ModelView, model=Lyric):
name = "가사"
name_plural = "가사 목록"
icon = "fa-solid fa-music"
category = "가사 관리"
page_size = 20
column_list = [
"id",
"project_id",
"task_id",
"status",
"language",
"created_at",
]
column_details_list = [
"id",
"project_id",
"task_id",
"status",
"language",
"lyric_prompt",
"lyric_result",
"created_at",
]
# 폼(생성/수정)에서 제외
form_excluded_columns = ["created_at", "songs", "videos"]
column_searchable_list = [
Lyric.task_id,
Lyric.status,
Lyric.language,
]
column_default_sort = (Lyric.created_at, True) # True: DESC (최신순)
column_sortable_list = [
Lyric.id,
Lyric.project_id,
Lyric.status,
Lyric.language,
Lyric.created_at,
]
column_labels = {
"id": "ID",
"project_id": "프로젝트 ID",
"task_id": "작업 ID",
"status": "상태",
"language": "언어",
"lyric_prompt": "프롬프트",
"lyric_result": "생성 결과",
"created_at": "생성일시",
}
+448 -417
View File
@@ -1,417 +1,448 @@
"""
Lyric API Router
이 모듈은 가사 관련 API 엔드포인트를 정의합니다.
모든 엔드포인트는 재사용 가능하도록 설계되었습니다.
엔드포인트 목록:
- POST /lyric/generate: 가사 생성
- GET /lyric/status/{task_id}: 가사 생성 상태 조회
- GET /lyric/{task_id}: 가사 상세 조회
- GET /lyrics: 가사 목록 조회 (페이지네이션)
사용 예시:
from app.lyric.api.routers.v1.lyric import router
app.include_router(router, prefix="/api/v1")
다른 서비스에서 재사용:
# 이 파일의 헬퍼 함수들을 import하여 사용 가능
from app.lyric.api.routers.v1.lyric import (
get_lyric_status_by_task_id,
get_lyric_by_task_id,
)
# 페이지네이션은 pagination 모듈 사용
from app.utils.pagination import PaginatedResponse, get_paginated
"""
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.session import get_session
from app.home.models import Project
from app.lyric.models import Lyric
from app.lyric.schemas.lyric import (
GenerateLyricRequest,
GenerateLyricResponse,
LyricDetailResponse,
LyricListItem,
LyricStatusResponse,
)
from app.lyric.worker.lyric_task import generate_lyric_background
from app.utils.chatgpt_prompt import ChatgptService
from app.utils.pagination import PaginatedResponse, get_paginated
router = APIRouter(prefix="/lyric", tags=["lyric"])
# =============================================================================
# Reusable Service Functions (다른 모듈에서 import하여 사용 가능)
# =============================================================================
async def get_lyric_status_by_task_id(
session: AsyncSession, task_id: str
) -> LyricStatusResponse:
"""task_id로 가사 생성 작업의 상태를 조회합니다.
Args:
session: SQLAlchemy AsyncSession
task_id: 작업 고유 식별자
Returns:
LyricStatusResponse: 상태 정보
Raises:
HTTPException: 404 - task_id에 해당하는 가사가 없는 경우
Usage:
# 다른 서비스에서 사용
from app.lyric.api.routers.v1.lyric import get_lyric_status_by_task_id
status_info = await get_lyric_status_by_task_id(session, "some-task-id")
if status_info.status == "completed":
# 완료 처리
"""
print(f"[get_lyric_status_by_task_id] START - task_id: {task_id}")
result = await session.execute(
select(Lyric)
.where(Lyric.task_id == task_id)
.order_by(Lyric.created_at.desc())
.limit(1)
)
lyric = result.scalar_one_or_none()
if not lyric:
print(f"[get_lyric_status_by_task_id] NOT FOUND - task_id: {task_id}")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"task_id '{task_id}'에 해당하는 가사를 찾을 수 없습니다.",
)
status_messages = {
"processing": "가사 생성 중입니다.",
"completed": "가사 생성이 완료되었습니다.",
"failed": "가사 생성에 실패했습니다.",
}
print(
f"[get_lyric_status_by_task_id] SUCCESS - task_id: {task_id}, status: {lyric.status}"
)
return LyricStatusResponse(
task_id=lyric.task_id,
status=lyric.status,
message=status_messages.get(lyric.status, "알 수 없는 상태입니다."),
)
async def get_lyric_by_task_id(
session: AsyncSession, task_id: str
) -> LyricDetailResponse:
"""task_id로 생성된 가사 상세 정보를 조회합니다.
Args:
session: SQLAlchemy AsyncSession
task_id: 작업 고유 식별자
Returns:
LyricDetailResponse: 가사 상세 정보
Raises:
HTTPException: 404 - task_id에 해당하는 가사가 없는 경우
Usage:
# 다른 서비스에서 사용
from app.lyric.api.routers.v1.lyric import get_lyric_by_task_id
lyric = await get_lyric_by_task_id(session, task_id)
"""
print(f"[get_lyric_by_task_id] START - task_id: {task_id}")
result = await session.execute(
select(Lyric)
.where(Lyric.task_id == task_id)
.order_by(Lyric.created_at.desc())
.limit(1)
)
lyric = result.scalar_one_or_none()
if not lyric:
print(f"[get_lyric_by_task_id] NOT FOUND - task_id: {task_id}")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"task_id '{task_id}'에 해당하는 가사를 찾을 수 없습니다.",
)
print(f"[get_lyric_by_task_id] SUCCESS - task_id: {task_id}, lyric_id: {lyric.id}")
return LyricDetailResponse(
id=lyric.id,
task_id=lyric.task_id,
project_id=lyric.project_id,
status=lyric.status,
lyric_prompt=lyric.lyric_prompt,
lyric_result=lyric.lyric_result,
created_at=lyric.created_at,
)
# =============================================================================
# API Endpoints
# =============================================================================
@router.post(
"/generate",
summary="가사 생성",
description="""
고객 정보를 기반으로 ChatGPT를 이용하여 가사를 생성합니다.
백그라운드에서 비동기로 처리되며, 즉시 task_id를 반환합니다.
## 요청 필드
- **task_id**: 작업 고유 식별자 (이미지 업로드 시 생성된 task_id, 필수)
- **customer_name**: 고객명/가게명 (필수)
- **region**: 지역명 (필수)
- **detail_region_info**: 상세 지역 정보 (선택)
- **language**: 가사 출력 언어 (Korean, English, Chinese, Japanese, Thai, Vietnamese)
## 반환 정보
- **success**: 요청 접수 성공 여부
- **task_id**: 작업 고유 식별자
- **lyric**: null (백그라운드 처리 중)
- **language**: 가사 언어
- **error_message**: 에러 메시지 (요청 접수 실패 시)
## 상태 확인
- GET /lyric/status/{task_id} 로 처리 상태 확인
- GET /lyric/{task_id} 로 생성된 가사 조회
## 사용 예시
```
POST /lyric/generate
{
"task_id": "0694b716-dbff-7219-8000-d08cb5fce431",
"customer_name": "스테이 머뭄",
"region": "군산",
"detail_region_info": "군산 신흥동 말랭이 마을",
"language": "Korean"
}
```
## 응답 예시
```json
{
"success": true,
"task_id": "0694b716-dbff-7219-8000-d08cb5fce431",
"lyric": null,
"language": "Korean",
"error_message": null
}
```
""",
response_model=GenerateLyricResponse,
responses={
200: {"description": "가사 생성 요청 접수 성공"},
500: {"description": "서버 내부 오류"},
},
)
async def generate_lyric(
request_body: GenerateLyricRequest,
background_tasks: BackgroundTasks,
session: AsyncSession = Depends(get_session),
) -> GenerateLyricResponse:
"""고객 정보를 기반으로 가사를 생성합니다. (백그라운드 처리)"""
task_id = request_body.task_id
print(
f"[generate_lyric] START - task_id: {task_id}, "
f"customer_name: {request_body.customer_name}, "
f"region: {request_body.region}"
)
try:
# 1. ChatGPT 서비스 초기화 및 프롬프트 생성
service = ChatgptService(
customer_name=request_body.customer_name,
region=request_body.region,
detail_region_info=request_body.detail_region_info or "",
language=request_body.language,
)
prompt = service.build_lyrics_prompt()
# 2. Project 테이블에 데이터 저장
project = Project(
store_name=request_body.customer_name,
region=request_body.region,
task_id=task_id,
detail_region_info=request_body.detail_region_info,
language=request_body.language,
)
session.add(project)
await session.commit()
await session.refresh(project)
print(
f"[generate_lyric] Project saved - "
f"project_id: {project.id}, task_id: {task_id}"
)
# 3. Lyric 테이블에 데이터 저장 (status: processing)
lyric = Lyric(
project_id=project.id,
task_id=task_id,
status="processing",
lyric_prompt=prompt,
lyric_result=None,
language=request_body.language,
)
session.add(lyric)
await session.commit()
await session.refresh(lyric)
print(
f"[generate_lyric] Lyric saved (processing) - "
f"lyric_id: {lyric.id}, task_id: {task_id}"
)
# 4. 백그라운드 태스크로 ChatGPT 가사 생성 실행
background_tasks.add_task(
generate_lyric_background,
task_id=task_id,
prompt=prompt,
language=request_body.language,
)
print(f"[generate_lyric] Background task scheduled - task_id: {task_id}")
# 5. 즉시 응답 반환
return GenerateLyricResponse(
success=True,
task_id=task_id,
lyric=None,
language=request_body.language,
error_message=None,
)
except Exception as e:
print(f"[generate_lyric] EXCEPTION - task_id: {task_id}, error: {e}")
await session.rollback()
return GenerateLyricResponse(
success=False,
task_id=task_id,
lyric=None,
language=request_body.language,
error_message=str(e),
)
@router.get(
"/status/{task_id}",
summary="가사 생성 상태 조회",
description="""
task_id로 가사 생성 작업의 현재 상태를 조회합니다.
## 상태 값
- **processing**: 가사 생성 중
- **completed**: 가사 생성 완료
- **failed**: 가사 생성 실패
## 사용 예시
```
GET /lyric/status/019123ab-cdef-7890-abcd-ef1234567890
```
""",
response_model=LyricStatusResponse,
responses={
200: {"description": "상태 조회 성공"},
404: {"description": "해당 task_id를 찾을 수 없음"},
},
)
async def get_lyric_status(
task_id: str,
session: AsyncSession = Depends(get_session),
) -> LyricStatusResponse:
"""task_id로 가사 생성 작업 상태를 조회합니다."""
return await get_lyric_status_by_task_id(session, task_id)
@router.get(
"s",
summary="가사 목록 조회 (페이지네이션)",
description="""
생성 완료된 가사를 페이지네이션으로 조회합니다.
## 파라미터
- **page**: 페이지 번호 (1부터 시작, 기본값: 1)
- **page_size**: 페이지당 데이터 수 (기본값: 20, 최대: 100)
## 반환 정보
- **items**: 가사 목록 (completed 상태만)
- **total**: 전체 데이터 수
- **page**: 현재 페이지
- **page_size**: 페이지당 데이터 수
- **total_pages**: 전체 페이지 수
- **has_next**: 다음 페이지 존재 여부
- **has_prev**: 이전 페이지 존재 여부
## 사용 예시
```
GET /lyrics # 기본 조회 (1페이지, 20개)
GET /lyrics?page=2 # 2페이지 조회
GET /lyrics?page=1&page_size=50 # 50개씩 조회
```
## 참고
- 생성 완료(completed)된 가사만 조회됩니다.
- processing, failed 상태의 가사는 조회되지 않습니다.
""",
response_model=PaginatedResponse[LyricListItem],
responses={
200: {"description": "가사 목록 조회 성공"},
},
)
async def list_lyrics(
page: int = Query(1, ge=1, description="페이지 번호 (1부터 시작)"),
page_size: int = Query(20, ge=1, le=100, description="페이지당 데이터 수"),
session: AsyncSession = Depends(get_session),
) -> PaginatedResponse[LyricListItem]:
"""페이지네이션으로 완료된 가사 목록을 조회합니다."""
return await get_paginated(
session=session,
model=Lyric,
item_schema=LyricListItem,
page=page,
page_size=page_size,
filters={"status": "completed"},
order_by="created_at",
order_desc=True,
)
@router.get(
"/{task_id}",
summary="가사 상세 조회",
description="""
task_id로 생성된 가사의 상세 정보를 조회합니다.
## 반환 정보
- **id**: 가사 ID
- **task_id**: 작업 고유 식별자
- **project_id**: 프로젝트 ID
- **status**: 처리 상태
- **lyric_prompt**: 가사 생성에 사용된 프롬프트
- **lyric_result**: 생성된 가사 (완료 시)
- **created_at**: 생성 일시
## 사용 예시
```
GET /lyric/019123ab-cdef-7890-abcd-ef1234567890
```
""",
response_model=LyricDetailResponse,
responses={
200: {"description": "가사 조회 성공"},
404: {"description": "해당 task_id를 찾을 수 없음"},
},
)
async def get_lyric_detail(
task_id: str,
session: AsyncSession = Depends(get_session),
) -> LyricDetailResponse:
"""task_id로 생성된 가사를 조회합니다."""
return await get_lyric_by_task_id(session, task_id)
"""
Lyric API Router
이 모듈은 가사 관련 API 엔드포인트를 정의합니다.
모든 엔드포인트는 재사용 가능하도록 설계되었습니다.
엔드포인트 목록:
- POST /lyric/generate: 가사 생성
- GET /lyric/status/{task_id}: 가사 생성 상태 조회
- GET /lyric/{task_id}: 가사 상세 조회
- GET /lyrics: 가사 목록 조회 (페이지네이션)
사용 예시:
from app.lyric.api.routers.v1.lyric import router
app.include_router(router, prefix="/api/v1")
다른 서비스에서 재사용:
# 이 파일의 헬퍼 함수들을 import하여 사용 가능
from app.lyric.api.routers.v1.lyric import (
get_lyric_status_by_task_id,
get_lyric_by_task_id,
)
# 페이지네이션은 pagination 모듈 사용
from app.utils.pagination import PaginatedResponse, get_paginated
"""
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.session import get_session
from app.home.models import Project
from app.lyric.models import Lyric
from app.lyric.schemas.lyric import (
GenerateLyricRequest,
GenerateLyricResponse,
LyricDetailResponse,
LyricListItem,
LyricStatusResponse,
)
from app.lyric.worker.lyric_task import generate_lyric_background
from app.utils.chatgpt_prompt import ChatgptService
from app.utils.pagination import PaginatedResponse, get_paginated
router = APIRouter(prefix="/lyric", tags=["lyric"])
# =============================================================================
# Reusable Service Functions (다른 모듈에서 import하여 사용 가능)
# =============================================================================
async def get_lyric_status_by_task_id(
session: AsyncSession, task_id: str
) -> LyricStatusResponse:
"""task_id로 가사 생성 작업의 상태를 조회합니다.
Args:
session: SQLAlchemy AsyncSession
task_id: 작업 고유 식별자
Returns:
LyricStatusResponse: 상태 정보
Raises:
HTTPException: 404 - task_id에 해당하는 가사가 없는 경우
Usage:
# 다른 서비스에서 사용
from app.lyric.api.routers.v1.lyric import get_lyric_status_by_task_id
status_info = await get_lyric_status_by_task_id(session, "some-task-id")
if status_info.status == "completed":
# 완료 처리
"""
print(f"[get_lyric_status_by_task_id] START - task_id: {task_id}")
result = await session.execute(
select(Lyric)
.where(Lyric.task_id == task_id)
.order_by(Lyric.created_at.desc())
.limit(1)
)
lyric = result.scalar_one_or_none()
if not lyric:
print(f"[get_lyric_status_by_task_id] NOT FOUND - task_id: {task_id}")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"task_id '{task_id}'에 해당하는 가사를 찾을 수 없습니다.",
)
status_messages = {
"processing": "가사 생성 중입니다.",
"completed": "가사 생성이 완료되었습니다.",
"failed": "가사 생성에 실패했습니다.",
}
print(
f"[get_lyric_status_by_task_id] SUCCESS - task_id: {task_id}, status: {lyric.status}"
)
return LyricStatusResponse(
task_id=lyric.task_id,
status=lyric.status,
message=status_messages.get(lyric.status, "알 수 없는 상태입니다."),
)
async def get_lyric_by_task_id(
session: AsyncSession, task_id: str
) -> LyricDetailResponse:
"""task_id로 생성된 가사 상세 정보를 조회합니다.
Args:
session: SQLAlchemy AsyncSession
task_id: 작업 고유 식별자
Returns:
LyricDetailResponse: 가사 상세 정보
Raises:
HTTPException: 404 - task_id에 해당하는 가사가 없는 경우
Usage:
# 다른 서비스에서 사용
from app.lyric.api.routers.v1.lyric import get_lyric_by_task_id
lyric = await get_lyric_by_task_id(session, task_id)
"""
print(f"[get_lyric_by_task_id] START - task_id: {task_id}")
result = await session.execute(
select(Lyric)
.where(Lyric.task_id == task_id)
.order_by(Lyric.created_at.desc())
.limit(1)
)
lyric = result.scalar_one_or_none()
if not lyric:
print(f"[get_lyric_by_task_id] NOT FOUND - task_id: {task_id}")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"task_id '{task_id}'에 해당하는 가사를 찾을 수 없습니다.",
)
print(f"[get_lyric_by_task_id] SUCCESS - task_id: {task_id}, lyric_id: {lyric.id}")
return LyricDetailResponse(
id=lyric.id,
task_id=lyric.task_id,
project_id=lyric.project_id,
status=lyric.status,
lyric_prompt=lyric.lyric_prompt,
lyric_result=lyric.lyric_result,
created_at=lyric.created_at,
)
# =============================================================================
# API Endpoints
# =============================================================================
@router.post(
"/generate",
summary="가사 생성",
description="""
고객 정보를 기반으로 ChatGPT를 이용하여 가사를 생성합니다.
백그라운드에서 비동기로 처리되며, 즉시 task_id를 반환합니다.
## 요청 필드
- **task_id**: 작업 고유 식별자 (이미지 업로드 시 생성된 task_id, 필수)
- **customer_name**: 고객명/가게명 (필수)
- **region**: 지역명 (필수)
- **detail_region_info**: 상세 지역 정보 (선택)
- **language**: 가사 출력 언어 (Korean, English, Chinese, Japanese, Thai, Vietnamese)
## 반환 정보
- **success**: 요청 접수 성공 여부
- **task_id**: 작업 고유 식별자
- **lyric**: null (백그라운드 처리 중)
- **language**: 가사 언어
- **error_message**: 에러 메시지 (요청 접수 실패 시)
## 상태 확인
- GET /lyric/status/{task_id} 로 처리 상태 확인
- GET /lyric/{task_id} 로 생성된 가사 조회
## 사용 예시
```
POST /lyric/generate
{
"task_id": "0694b716-dbff-7219-8000-d08cb5fce431",
"customer_name": "스테이 머뭄",
"region": "군산",
"detail_region_info": "군산 신흥동 말랭이 마을",
"language": "Korean"
}
```
## 응답 예시
```json
{
"success": true,
"task_id": "0694b716-dbff-7219-8000-d08cb5fce431",
"lyric": null,
"language": "Korean",
"error_message": null
}
```
""",
response_model=GenerateLyricResponse,
responses={
200: {"description": "가사 생성 요청 접수 성공"},
500: {"description": "서버 내부 오류"},
},
)
async def generate_lyric(
request_body: GenerateLyricRequest,
background_tasks: BackgroundTasks,
session: AsyncSession = Depends(get_session),
) -> GenerateLyricResponse:
"""고객 정보를 기반으로 가사를 생성합니다. (백그라운드 처리)"""
import time
request_start = time.perf_counter()
task_id = request_body.task_id
print(f"[generate_lyric] ========== START ==========")
print(
f"[generate_lyric] task_id: {task_id}, "
f"customer_name: {request_body.customer_name}, "
f"region: {request_body.region}"
)
try:
# ========== Step 1: ChatGPT 서비스 초기화 및 프롬프트 생성 ==========
step1_start = time.perf_counter()
print(f"[generate_lyric] Step 1: 서비스 초기화 및 프롬프트 생성...")
service = ChatgptService(
customer_name=request_body.customer_name,
region=request_body.region,
detail_region_info=request_body.detail_region_info or "",
language=request_body.language,
)
prompt = service.build_lyrics_prompt()
step1_elapsed = (time.perf_counter() - step1_start) * 1000
print(f"[generate_lyric] Step 1 완료 - 프롬프트 {len(prompt)}자 ({step1_elapsed:.1f}ms)")
# ========== Step 2: Project 테이블에 데이터 저장 ==========
step2_start = time.perf_counter()
print(f"[generate_lyric] Step 2: Project 저장...")
project = Project(
store_name=request_body.customer_name,
region=request_body.region,
task_id=task_id,
detail_region_info=request_body.detail_region_info,
language=request_body.language,
)
session.add(project)
await session.commit()
await session.refresh(project)
step2_elapsed = (time.perf_counter() - step2_start) * 1000
print(f"[generate_lyric] Step 2 완료 - project_id: {project.id} ({step2_elapsed:.1f}ms)")
# ========== Step 3: Lyric 테이블에 데이터 저장 ==========
step3_start = time.perf_counter()
print(f"[generate_lyric] Step 3: Lyric 저장 (processing)...")
lyric = Lyric(
project_id=project.id,
task_id=task_id,
status="processing",
lyric_prompt=prompt,
lyric_result=None,
language=request_body.language,
)
session.add(lyric)
await session.commit()
await session.refresh(lyric)
step3_elapsed = (time.perf_counter() - step3_start) * 1000
print(f"[generate_lyric] Step 3 완료 - lyric_id: {lyric.id} ({step3_elapsed:.1f}ms)")
# ========== Step 4: 백그라운드 태스크 스케줄링 ==========
step4_start = time.perf_counter()
print(f"[generate_lyric] Step 4: 백그라운드 태스크 스케줄링...")
background_tasks.add_task(
generate_lyric_background,
task_id=task_id,
prompt=prompt,
language=request_body.language,
)
step4_elapsed = (time.perf_counter() - step4_start) * 1000
print(f"[generate_lyric] Step 4 완료 ({step4_elapsed:.1f}ms)")
# ========== 완료 ==========
total_elapsed = (time.perf_counter() - request_start) * 1000
print(f"[generate_lyric] ========== COMPLETE ==========")
print(f"[generate_lyric] API 응답 소요시간: {total_elapsed:.1f}ms")
print(f"[generate_lyric] - Step 1 (프롬프트 생성): {step1_elapsed:.1f}ms")
print(f"[generate_lyric] - Step 2 (Project 저장): {step2_elapsed:.1f}ms")
print(f"[generate_lyric] - Step 3 (Lyric 저장): {step3_elapsed:.1f}ms")
print(f"[generate_lyric] - Step 4 (태스크 스케줄링): {step4_elapsed:.1f}ms")
print(f"[generate_lyric] (GPT API 호출은 백그라운드에서 별도 진행)")
# 5. 즉시 응답 반환
return GenerateLyricResponse(
success=True,
task_id=task_id,
lyric=None,
language=request_body.language,
error_message=None,
)
except Exception as e:
elapsed = (time.perf_counter() - request_start) * 1000
print(f"[generate_lyric] EXCEPTION - task_id: {task_id}, error: {e} ({elapsed:.1f}ms)")
await session.rollback()
return GenerateLyricResponse(
success=False,
task_id=task_id,
lyric=None,
language=request_body.language,
error_message=str(e),
)
@router.get(
"/status/{task_id}",
summary="가사 생성 상태 조회",
description="""
task_id로 가사 생성 작업의 현재 상태를 조회합니다.
## 상태 값
- **processing**: 가사 생성 중
- **completed**: 가사 생성 완료
- **failed**: 가사 생성 실패
## 사용 예시
```
GET /lyric/status/019123ab-cdef-7890-abcd-ef1234567890
```
""",
response_model=LyricStatusResponse,
responses={
200: {"description": "상태 조회 성공"},
404: {"description": "해당 task_id를 찾을 수 없음"},
},
)
async def get_lyric_status(
task_id: str,
session: AsyncSession = Depends(get_session),
) -> LyricStatusResponse:
"""task_id로 가사 생성 작업 상태를 조회합니다."""
return await get_lyric_status_by_task_id(session, task_id)
@router.get(
"s",
summary="가사 목록 조회 (페이지네이션)",
description="""
생성 완료된 가사를 페이지네이션으로 조회합니다.
## 파라미터
- **page**: 페이지 번호 (1부터 시작, 기본값: 1)
- **page_size**: 페이지당 데이터 수 (기본값: 20, 최대: 100)
## 반환 정보
- **items**: 가사 목록 (completed 상태만)
- **total**: 전체 데이터 수
- **page**: 현재 페이지
- **page_size**: 페이지당 데이터 수
- **total_pages**: 전체 페이지 수
- **has_next**: 다음 페이지 존재 여부
- **has_prev**: 이전 페이지 존재 여부
## 사용 예시
```
GET /lyrics # 기본 조회 (1페이지, 20개)
GET /lyrics?page=2 # 2페이지 조회
GET /lyrics?page=1&page_size=50 # 50개씩 조회
```
## 참고
- 생성 완료(completed)된 가사만 조회됩니다.
- processing, failed 상태의 가사는 조회되지 않습니다.
""",
response_model=PaginatedResponse[LyricListItem],
responses={
200: {"description": "가사 목록 조회 성공"},
},
)
async def list_lyrics(
page: int = Query(1, ge=1, description="페이지 번호 (1부터 시작)"),
page_size: int = Query(20, ge=1, le=100, description="페이지당 데이터 수"),
session: AsyncSession = Depends(get_session),
) -> PaginatedResponse[LyricListItem]:
"""페이지네이션으로 완료된 가사 목록을 조회합니다."""
return await get_paginated(
session=session,
model=Lyric,
item_schema=LyricListItem,
page=page,
page_size=page_size,
filters={"status": "completed"},
order_by="created_at",
order_desc=True,
)
@router.get(
"/{task_id}",
summary="가사 상세 조회",
description="""
task_id로 생성된 가사의 상세 정보를 조회합니다.
## 반환 정보
- **id**: 가사 ID
- **task_id**: 작업 고유 식별자
- **project_id**: 프로젝트 ID
- **status**: 처리 상태
- **lyric_prompt**: 가사 생성에 사용된 프롬프트
- **lyric_result**: 생성된 가사 (완료 시)
- **created_at**: 생성 일시
## 사용 예시
```
GET /lyric/019123ab-cdef-7890-abcd-ef1234567890
```
""",
response_model=LyricDetailResponse,
responses={
200: {"description": "가사 조회 성공"},
404: {"description": "해당 task_id를 찾을 수 없음"},
},
)
async def get_lyric_detail(
task_id: str,
session: AsyncSession = Depends(get_session),
) -> LyricDetailResponse:
"""task_id로 생성된 가사를 조회합니다."""
return await get_lyric_by_task_id(session, task_id)
+8 -8
View File
@@ -1,8 +1,8 @@
from typing import Annotated
from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.session import get_session
SessionDep = Annotated[AsyncSession, Depends(get_session)]
from typing import Annotated
from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.session import get_session
SessionDep = Annotated[AsyncSession, Depends(get_session)]
+133 -133
View File
@@ -1,133 +1,133 @@
from datetime import datetime
from typing import TYPE_CHECKING, List
from sqlalchemy import DateTime, ForeignKey, Integer, String, Text, func
from sqlalchemy.dialects.mysql import LONGTEXT
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.database.session import Base
if TYPE_CHECKING:
from app.home.models import Project
from app.song.models import Song
from app.video.models import Video
class Lyric(Base):
"""
가사 테이블
AI를 통해 생성된 가사 정보를 저장합니다.
프롬프트와 생성 결과, 처리 상태를 관리합니다.
Attributes:
id: 고유 식별자 (자동 증가)
project_id: 연결된 Project의 id (외래키)
task_id: 가사 생성 작업의 고유 식별자 (UUID 형식)
status: 처리 상태 (pending, processing, completed, failed 등)
lyric_prompt: 가사 생성에 사용된 프롬프트
lyric_result: 생성된 가사 결과 (LONGTEXT로 긴 가사 지원)
created_at: 생성 일시 (자동 설정)
Relationships:
project: 연결된 Project
songs: 이 가사를 사용한 노래 목록
videos: 이 가사를 사용한 영상 목록
"""
__tablename__ = "lyric"
__table_args__ = (
{
"mysql_engine": "InnoDB",
"mysql_charset": "utf8mb4",
"mysql_collate": "utf8mb4_unicode_ci",
},
)
id: Mapped[int] = mapped_column(
Integer,
primary_key=True,
nullable=False,
autoincrement=True,
comment="고유 식별자",
)
project_id: Mapped[int] = mapped_column(
Integer,
ForeignKey("project.id", ondelete="CASCADE"),
nullable=False,
index=True,
comment="연결된 Project의 id",
)
task_id: Mapped[str] = mapped_column(
String(36),
nullable=False,
comment="가사 생성 작업 고유 식별자 (UUID)",
)
status: Mapped[str] = mapped_column(
String(50),
nullable=False,
comment="처리 상태 (processing, completed, failed)",
)
lyric_prompt: Mapped[str] = mapped_column(
Text,
nullable=False,
comment="가사 생성에 사용된 프롬프트",
)
lyric_result: Mapped[str] = mapped_column(
LONGTEXT,
nullable=True,
comment="생성된 가사 결과",
)
language: Mapped[str] = mapped_column(
String(50),
nullable=False,
default="Korean",
comment="가사 출력 언어 (Korean, English, Chinese, Japanese, Thai, Vietnamese)",
)
created_at: Mapped[datetime] = mapped_column(
DateTime,
nullable=True,
server_default=func.now(),
comment="생성 일시",
)
# Relationships
project: Mapped["Project"] = relationship(
"Project",
back_populates="lyrics",
)
songs: Mapped[List["Song"]] = relationship(
"Song",
back_populates="lyric",
cascade="all, delete-orphan",
lazy="selectin",
)
videos: Mapped[List["Video"]] = relationship(
"Video",
back_populates="lyric",
cascade="all, delete-orphan",
lazy="selectin",
)
def __repr__(self) -> str:
def truncate(value: str | None, max_len: int = 10) -> str:
if value is None:
return "None"
return (value[:max_len] + "...") if len(value) > max_len else value
return (
f"<Lyric("
f"id={self.id}, "
f"task_id='{truncate(self.task_id)}', "
f"status='{self.status}'"
f")>"
)
from datetime import datetime
from typing import TYPE_CHECKING, List
from sqlalchemy import DateTime, ForeignKey, Integer, String, Text, func
from sqlalchemy.dialects.mysql import LONGTEXT
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.database.session import Base
if TYPE_CHECKING:
from app.home.models import Project
from app.song.models import Song
from app.video.models import Video
class Lyric(Base):
"""
가사 테이블
AI를 통해 생성된 가사 정보를 저장합니다.
프롬프트와 생성 결과, 처리 상태를 관리합니다.
Attributes:
id: 고유 식별자 (자동 증가)
project_id: 연결된 Project의 id (외래키)
task_id: 가사 생성 작업의 고유 식별자 (UUID 형식)
status: 처리 상태 (pending, processing, completed, failed 등)
lyric_prompt: 가사 생성에 사용된 프롬프트
lyric_result: 생성된 가사 결과 (LONGTEXT로 긴 가사 지원)
created_at: 생성 일시 (자동 설정)
Relationships:
project: 연결된 Project
songs: 이 가사를 사용한 노래 목록
videos: 이 가사를 사용한 영상 목록
"""
__tablename__ = "lyric"
__table_args__ = (
{
"mysql_engine": "InnoDB",
"mysql_charset": "utf8mb4",
"mysql_collate": "utf8mb4_unicode_ci",
},
)
id: Mapped[int] = mapped_column(
Integer,
primary_key=True,
nullable=False,
autoincrement=True,
comment="고유 식별자",
)
project_id: Mapped[int] = mapped_column(
Integer,
ForeignKey("project.id", ondelete="CASCADE"),
nullable=False,
index=True,
comment="연결된 Project의 id",
)
task_id: Mapped[str] = mapped_column(
String(36),
nullable=False,
comment="가사 생성 작업 고유 식별자 (UUID)",
)
status: Mapped[str] = mapped_column(
String(50),
nullable=False,
comment="처리 상태 (processing, completed, failed)",
)
lyric_prompt: Mapped[str] = mapped_column(
Text,
nullable=False,
comment="가사 생성에 사용된 프롬프트",
)
lyric_result: Mapped[str] = mapped_column(
LONGTEXT,
nullable=True,
comment="생성된 가사 결과",
)
language: Mapped[str] = mapped_column(
String(50),
nullable=False,
default="Korean",
comment="가사 출력 언어 (Korean, English, Chinese, Japanese, Thai, Vietnamese)",
)
created_at: Mapped[datetime] = mapped_column(
DateTime,
nullable=True,
server_default=func.now(),
comment="생성 일시",
)
# Relationships
project: Mapped["Project"] = relationship(
"Project",
back_populates="lyrics",
)
songs: Mapped[List["Song"]] = relationship(
"Song",
back_populates="lyric",
cascade="all, delete-orphan",
lazy="selectin",
)
videos: Mapped[List["Video"]] = relationship(
"Video",
back_populates="lyric",
cascade="all, delete-orphan",
lazy="selectin",
)
def __repr__(self) -> str:
def truncate(value: str | None, max_len: int = 10) -> str:
if value is None:
return "None"
return (value[:max_len] + "...") if len(value) > max_len else value
return (
f"<Lyric("
f"id={self.id}, "
f"task_id='{truncate(self.task_id)}', "
f"status='{self.status}'"
f")>"
)
+182 -182
View File
@@ -1,182 +1,182 @@
"""
Lyric API Schemas
이 모듈은 가사 관련 API 엔드포인트에서 사용되는 Pydantic 스키마를 정의합니다.
사용 예시:
from app.lyric.schemas.lyric import (
LyricStatusResponse,
LyricDetailResponse,
LyricListItem,
)
from app.utils.pagination import PaginatedResponse
# 라우터에서 response_model로 사용
@router.get("/lyric/{task_id}", response_model=LyricDetailResponse)
async def get_lyric(task_id: str):
...
# 페이지네이션 응답 (공통 스키마 사용)
@router.get("/songs", response_model=PaginatedResponse[SongListItem])
async def list_songs(...):
...
"""
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, ConfigDict, Field
class GenerateLyricRequest(BaseModel):
"""가사 생성 요청 스키마
Usage:
POST /lyric/generate
Request body for generating lyrics.
Example Request:
{
"task_id": "0694b716-dbff-7219-8000-d08cb5fce431",
"customer_name": "스테이 머뭄",
"region": "군산",
"detail_region_info": "군산 신흥동 말랭이 마을",
"language": "Korean"
}
"""
model_config = ConfigDict(
json_schema_extra={
"example": {
"task_id": "0694b716-dbff-7219-8000-d08cb5fce431",
"customer_name": "스테이 머뭄",
"region": "군산",
"detail_region_info": "군산 신흥동 말랭이 마을",
"language": "Korean",
}
}
)
task_id: str = Field(
..., description="작업 고유 식별자 (이미지 업로드 시 생성된 task_id)"
)
customer_name: str = Field(..., description="고객명/가게명")
region: str = Field(..., description="지역명")
detail_region_info: Optional[str] = Field(None, description="상세 지역 정보")
language: str = Field(
default="Korean",
description="가사 출력 언어 (Korean, English, Chinese, Japanese, Thai, Vietnamese)",
)
class GenerateLyricResponse(BaseModel):
"""가사 생성 응답 스키마
Usage:
POST /lyric/generate
Returns the generated lyrics.
Note:
실패 조건:
- ChatGPT API 오류
- ChatGPT 거부 응답 (I'm sorry, I cannot, I can't, I apologize 등)
- 응답에 ERROR: 포함
"""
model_config = ConfigDict(
json_schema_extra={
"example": {
"success": True,
"task_id": "0694b716-dbff-7219-8000-d08cb5fce431",
"lyric": "인스타 감성의 스테이 머뭄\n군산 신흥동 말랭이 마을에서\n여유로운 하루를 보내며\n추억을 만들어가요",
"language": "Korean",
"error_message": None,
}
}
)
success: bool = Field(..., description="생성 성공 여부")
task_id: Optional[str] = Field(None, description="작업 고유 식별자 (uuid7)")
lyric: Optional[str] = Field(None, description="생성된 가사 (성공 시)")
language: str = Field(..., description="가사 언어")
error_message: Optional[str] = Field(None, description="에러 메시지 (실패 시, ChatGPT 거부 응답 포함)")
class LyricStatusResponse(BaseModel):
"""가사 상태 조회 응답 스키마
Usage:
GET /lyric/status/{task_id}
Returns the current processing status of a lyric generation task.
"""
model_config = ConfigDict(
json_schema_extra={
"example": {
"task_id": "0694b716-dbff-7219-8000-d08cb5fce431",
"status": "completed",
"message": "가사 생성이 완료되었습니다.",
}
}
)
task_id: str = Field(..., description="작업 고유 식별자")
status: str = Field(..., description="처리 상태 (processing, completed, failed)")
message: str = Field(..., description="상태 메시지")
class LyricDetailResponse(BaseModel):
"""가사 상세 조회 응답 스키마
Usage:
GET /lyric/{task_id}
Returns the generated lyric content for a specific task.
"""
model_config = ConfigDict(
json_schema_extra={
"example": {
"id": 1,
"task_id": "0694b716-dbff-7219-8000-d08cb5fce431",
"project_id": 1,
"status": "completed",
"lyric_prompt": "고객명: 스테이 머뭄, 지역: 군산...",
"lyric_result": "인스타 감성의 스테이 머뭄\n군산 신흥동 말랭이 마을에서\n여유로운 하루를 보내며\n추억을 만들어가요",
"created_at": "2024-01-15T12:00:00",
}
}
)
id: int = Field(..., description="가사 ID")
task_id: str = Field(..., description="작업 고유 식별자")
project_id: int = Field(..., description="프로젝트 ID")
status: str = Field(..., description="처리 상태")
lyric_prompt: str = Field(..., description="가사 생성 프롬프트")
lyric_result: Optional[str] = Field(None, description="생성된 가사")
created_at: Optional[datetime] = Field(None, description="생성 일시")
class LyricListItem(BaseModel):
"""가사 목록 아이템 스키마
Usage:
Used as individual items in paginated lyric list responses.
"""
model_config = ConfigDict(
json_schema_extra={
"example": {
"id": 1,
"task_id": "0694b716-dbff-7219-8000-d08cb5fce431",
"status": "completed",
"lyric_result": "인스타 감성의 스테이 머뭄\n군산 신흥동 말랭이 마을에서...",
"created_at": "2024-01-15T12:00:00",
}
}
)
id: int = Field(..., description="가사 ID")
task_id: str = Field(..., description="작업 고유 식별자")
status: str = Field(..., description="처리 상태")
lyric_result: Optional[str] = Field(None, description="생성된 가사 (미리보기)")
created_at: Optional[datetime] = Field(None, description="생성 일시")
"""
Lyric API Schemas
이 모듈은 가사 관련 API 엔드포인트에서 사용되는 Pydantic 스키마를 정의합니다.
사용 예시:
from app.lyric.schemas.lyric import (
LyricStatusResponse,
LyricDetailResponse,
LyricListItem,
)
from app.utils.pagination import PaginatedResponse
# 라우터에서 response_model로 사용
@router.get("/lyric/{task_id}", response_model=LyricDetailResponse)
async def get_lyric(task_id: str):
...
# 페이지네이션 응답 (공통 스키마 사용)
@router.get("/songs", response_model=PaginatedResponse[SongListItem])
async def list_songs(...):
...
"""
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, ConfigDict, Field
class GenerateLyricRequest(BaseModel):
"""가사 생성 요청 스키마
Usage:
POST /lyric/generate
Request body for generating lyrics.
Example Request:
{
"task_id": "0694b716-dbff-7219-8000-d08cb5fce431",
"customer_name": "스테이 머뭄",
"region": "군산",
"detail_region_info": "군산 신흥동 말랭이 마을",
"language": "Korean"
}
"""
model_config = ConfigDict(
json_schema_extra={
"example": {
"task_id": "0694b716-dbff-7219-8000-d08cb5fce431",
"customer_name": "스테이 머뭄",
"region": "군산",
"detail_region_info": "군산 신흥동 말랭이 마을",
"language": "Korean",
}
}
)
task_id: str = Field(
..., description="작업 고유 식별자 (이미지 업로드 시 생성된 task_id)"
)
customer_name: str = Field(..., description="고객명/가게명")
region: str = Field(..., description="지역명")
detail_region_info: Optional[str] = Field(None, description="상세 지역 정보")
language: str = Field(
default="Korean",
description="가사 출력 언어 (Korean, English, Chinese, Japanese, Thai, Vietnamese)",
)
class GenerateLyricResponse(BaseModel):
"""가사 생성 응답 스키마
Usage:
POST /lyric/generate
Returns the generated lyrics.
Note:
실패 조건:
- ChatGPT API 오류
- ChatGPT 거부 응답 (I'm sorry, I cannot, I can't, I apologize 등)
- 응답에 ERROR: 포함
"""
model_config = ConfigDict(
json_schema_extra={
"example": {
"success": True,
"task_id": "0694b716-dbff-7219-8000-d08cb5fce431",
"lyric": "인스타 감성의 스테이 머뭄\n군산 신흥동 말랭이 마을에서\n여유로운 하루를 보내며\n추억을 만들어가요",
"language": "Korean",
"error_message": None,
}
}
)
success: bool = Field(..., description="생성 성공 여부")
task_id: Optional[str] = Field(None, description="작업 고유 식별자 (uuid7)")
lyric: Optional[str] = Field(None, description="생성된 가사 (성공 시)")
language: str = Field(..., description="가사 언어")
error_message: Optional[str] = Field(None, description="에러 메시지 (실패 시, ChatGPT 거부 응답 포함)")
class LyricStatusResponse(BaseModel):
"""가사 상태 조회 응답 스키마
Usage:
GET /lyric/status/{task_id}
Returns the current processing status of a lyric generation task.
"""
model_config = ConfigDict(
json_schema_extra={
"example": {
"task_id": "0694b716-dbff-7219-8000-d08cb5fce431",
"status": "completed",
"message": "가사 생성이 완료되었습니다.",
}
}
)
task_id: str = Field(..., description="작업 고유 식별자")
status: str = Field(..., description="처리 상태 (processing, completed, failed)")
message: str = Field(..., description="상태 메시지")
class LyricDetailResponse(BaseModel):
"""가사 상세 조회 응답 스키마
Usage:
GET /lyric/{task_id}
Returns the generated lyric content for a specific task.
"""
model_config = ConfigDict(
json_schema_extra={
"example": {
"id": 1,
"task_id": "0694b716-dbff-7219-8000-d08cb5fce431",
"project_id": 1,
"status": "completed",
"lyric_prompt": "고객명: 스테이 머뭄, 지역: 군산...",
"lyric_result": "인스타 감성의 스테이 머뭄\n군산 신흥동 말랭이 마을에서\n여유로운 하루를 보내며\n추억을 만들어가요",
"created_at": "2024-01-15T12:00:00",
}
}
)
id: int = Field(..., description="가사 ID")
task_id: str = Field(..., description="작업 고유 식별자")
project_id: int = Field(..., description="프로젝트 ID")
status: str = Field(..., description="처리 상태")
lyric_prompt: str = Field(..., description="가사 생성 프롬프트")
lyric_result: Optional[str] = Field(None, description="생성된 가사")
created_at: Optional[datetime] = Field(None, description="생성 일시")
class LyricListItem(BaseModel):
"""가사 목록 아이템 스키마
Usage:
Used as individual items in paginated lyric list responses.
"""
model_config = ConfigDict(
json_schema_extra={
"example": {
"id": 1,
"task_id": "0694b716-dbff-7219-8000-d08cb5fce431",
"status": "completed",
"lyric_result": "인스타 감성의 스테이 머뭄\n군산 신흥동 말랭이 마을에서...",
"created_at": "2024-01-15T12:00:00",
}
}
)
id: int = Field(..., description="가사 ID")
task_id: str = Field(..., description="작업 고유 식별자")
status: str = Field(..., description="처리 상태")
lyric_result: Optional[str] = Field(None, description="생성된 가사 (미리보기)")
created_at: Optional[datetime] = Field(None, description="생성 일시")
+91 -91
View File
@@ -1,91 +1,91 @@
from dataclasses import dataclass, field
from datetime import datetime
from typing import Dict, List
from fastapi import Request
@dataclass
class StoreData:
id: int
created_at: datetime
store_name: str
store_category: str | None = None
store_region: str | None = None
store_address: str | None = None
store_phone_number: str | None = None
store_info: str | None = None
@dataclass
class AttributeData:
id: int
attr_category: str
attr_value: str
created_at: datetime
@dataclass
class SongSampleData:
id: int
ai: str
ai_model: str
sample_song: str
season: str | None = None
num_of_people: int | None = None
people_category: str | None = None
genre: str | None = None
@dataclass
class PromptTemplateData:
id: int
prompt: str
description: str | None = None
@dataclass
class SongFormData:
store_name: str
store_id: str
prompts: str
attributes: Dict[str, str] = field(default_factory=dict)
attributes_str: str = ""
lyrics_ids: List[int] = field(default_factory=list)
llm_model: str = "gpt-4o"
@classmethod
async def from_form(cls, request: Request):
"""Request의 form 데이터로부터 dataclass 인스턴스 생성"""
form_data = await request.form()
# 고정 필드명들
fixed_keys = {"store_info_name", "store_id", "llm_model", "prompts"}
# lyrics-{id} 형태의 모든 키를 찾아서 ID 추출
lyrics_ids = []
attributes = {}
for key, value in form_data.items():
if key.startswith("lyrics-"):
lyrics_id = key.split("-")[1]
lyrics_ids.append(int(lyrics_id))
elif key not in fixed_keys:
attributes[key] = value
# attributes를 문자열로 변환
attributes_str = (
"\r\n\r\n".join([f"{key} : {value}" for key, value in attributes.items()])
if attributes
else ""
)
return cls(
store_name=form_data.get("store_info_name", ""),
store_id=form_data.get("store_id", ""),
attributes=attributes,
attributes_str=attributes_str,
lyrics_ids=lyrics_ids,
llm_model=form_data.get("llm_model", "gpt-4o"),
prompts=form_data.get("prompts", ""),
)
from dataclasses import dataclass, field
from datetime import datetime
from typing import Dict, List
from fastapi import Request
@dataclass
class StoreData:
id: int
created_at: datetime
store_name: str
store_category: str | None = None
store_region: str | None = None
store_address: str | None = None
store_phone_number: str | None = None
store_info: str | None = None
@dataclass
class AttributeData:
id: int
attr_category: str
attr_value: str
created_at: datetime
@dataclass
class SongSampleData:
id: int
ai: str
ai_model: str
sample_song: str
season: str | None = None
num_of_people: int | None = None
people_category: str | None = None
genre: str | None = None
@dataclass
class PromptTemplateData:
id: int
prompt: str
description: str | None = None
@dataclass
class SongFormData:
store_name: str
store_id: str
prompts: str
attributes: Dict[str, str] = field(default_factory=dict)
attributes_str: str = ""
lyrics_ids: List[int] = field(default_factory=list)
llm_model: str = "gpt-5-mini"
@classmethod
async def from_form(cls, request: Request):
"""Request의 form 데이터로부터 dataclass 인스턴스 생성"""
form_data = await request.form()
# 고정 필드명들
fixed_keys = {"store_info_name", "store_id", "llm_model", "prompts"}
# lyrics-{id} 형태의 모든 키를 찾아서 ID 추출
lyrics_ids = []
attributes = {}
for key, value in form_data.items():
if key.startswith("lyrics-"):
lyrics_id = key.split("-")[1]
lyrics_ids.append(int(lyrics_id))
elif key not in fixed_keys:
attributes[key] = value
# attributes를 문자열로 변환
attributes_str = (
"\r\n\r\n".join([f"{key} : {value}" for key, value in attributes.items()])
if attributes
else ""
)
return cls(
store_name=form_data.get("store_info_name", ""),
store_id=form_data.get("store_id", ""),
attributes=attributes,
attributes_str=attributes_str,
lyrics_ids=lyrics_ids,
llm_model=form_data.get("llm_model", "gpt-5-mini"),
prompts=form_data.get("prompts", ""),
)
+23 -23
View File
@@ -1,24 +1,24 @@
from uuid import UUID
from sqlalchemy.ext.asyncio import AsyncSession
from sqlmodel import SQLModel
class BaseService:
def __init__(self, model, session: AsyncSession):
self.model = model
self.session = session
async def _get(self, id: UUID):
return await self.session.get(self.model, id)
async def _add(self, entity):
self.session.add(entity)
await self.session.commit()
await self.session.refresh(entity)
return entity
async def _update(self, entity):
return await self._add(entity)
async def _delete(self, entity):
from uuid import UUID
from sqlalchemy.ext.asyncio import AsyncSession
from sqlmodel import SQLModel
class BaseService:
def __init__(self, model, session: AsyncSession):
self.model = model
self.session = session
async def _get(self, id: UUID):
return await self.session.get(self.model, id)
async def _add(self, entity):
self.session.add(entity)
await self.session.commit()
await self.session.refresh(entity)
return entity
async def _update(self, entity):
return await self._add(entity)
async def _delete(self, entity):
await self.session.delete(entity)
File diff suppressed because it is too large. Load diff
+146 -98
View File
@@ -1,98 +1,146 @@
"""
Lyric Background Tasks
가사 생성 관련 백그라운드 태스크를 정의합니다.
"""
from sqlalchemy import select
from app.database.session import BackgroundSessionLocal
from app.lyric.models import Lyric
from app.utils.chatgpt_prompt import ChatgptService
async def generate_lyric_background(
task_id: str,
prompt: str,
language: str,
) -> None:
"""백그라운드에서 ChatGPT를 통해 가사를 생성하고 Lyric 테이블을 업데이트합니다.
Args:
task_id: 프로젝트 task_id
prompt: ChatGPT에 전달할 프롬프트
language: 가사 언어
"""
print(f"[generate_lyric_background] START - task_id: {task_id}")
try:
# ChatGPT 서비스 초기화 (프롬프트는 이미 생성되어 있음)
service = ChatgptService(
customer_name="", # 프롬프트가 이미 생성되었으므로 빈 값
region="",
detail_region_info="",
language=language,
)
# ChatGPT를 통해 가사 생성
print(f"[generate_lyric_background] ChatGPT generation started - task_id: {task_id}")
result = await service.generate(prompt=prompt)
print(f"[generate_lyric_background] ChatGPT generation completed - task_id: {task_id}")
# 실패 응답 검사 (ERROR 또는 ChatGPT 거부 응답)
failure_patterns = [
"ERROR:",
"I'm sorry",
"I cannot",
"I can't",
"I apologize",
"I'm unable",
"I am unable",
"I'm not able",
"I am not able",
]
is_failure = any(
pattern.lower() in result.lower() for pattern in failure_patterns
)
# Lyric 테이블 업데이트 (백그라운드 전용 세션 사용)
async with BackgroundSessionLocal() as session:
query_result = await session.execute(
select(Lyric)
.where(Lyric.task_id == task_id)
.order_by(Lyric.created_at.desc())
.limit(1)
)
lyric = query_result.scalar_one_or_none()
if lyric:
if is_failure:
print(f"[generate_lyric_background] FAILED - task_id: {task_id}, error: {result}")
lyric.status = "failed"
lyric.lyric_result = result
else:
print(f"[generate_lyric_background] SUCCESS - task_id: {task_id}")
lyric.status = "completed"
lyric.lyric_result = result
await session.commit()
else:
print(f"[generate_lyric_background] Lyric NOT FOUND in DB - task_id: {task_id}")
except Exception as e:
print(f"[generate_lyric_background] EXCEPTION - task_id: {task_id}, error: {e}")
# 실패 시 Lyric 테이블 업데이트
async with BackgroundSessionLocal() as session:
query_result = await session.execute(
select(Lyric)
.where(Lyric.task_id == task_id)
.order_by(Lyric.created_at.desc())
.limit(1)
)
lyric = query_result.scalar_one_or_none()
if lyric:
lyric.status = "failed"
lyric.lyric_result = f"Error: {str(e)}"
await session.commit()
print(f"[generate_lyric_background] FAILED - task_id: {task_id}, status updated to failed")
"""
Lyric Background Tasks
가사 생성 관련 백그라운드 태스크를 정의합니다.
"""
import logging
import traceback
from sqlalchemy import select
from sqlalchemy.exc import SQLAlchemyError
from app.database.session import BackgroundSessionLocal
from app.lyric.models import Lyric
from app.utils.chatgpt_prompt import ChatgptService
# 로거 설정
logger = logging.getLogger(__name__)
async def _update_lyric_status(
task_id: str,
status: str,
result: str | None = None,
) -> bool:
"""Lyric 테이블의 상태를 업데이트합니다.
Args:
task_id: 프로젝트 task_id
status: 변경할 상태 ("processing", "completed", "failed")
result: 가사 결과 또는 에러 메시지
Returns:
bool: 업데이트 성공 여부
"""
try:
async with BackgroundSessionLocal() as session:
query_result = await session.execute(
select(Lyric)
.where(Lyric.task_id == task_id)
.order_by(Lyric.created_at.desc())
.limit(1)
)
lyric = query_result.scalar_one_or_none()
if lyric:
lyric.status = status
if result is not None:
lyric.lyric_result = result
await session.commit()
logger.info(f"[Lyric] Status updated - task_id: {task_id}, status: {status}")
print(f"[Lyric] Status updated - task_id: {task_id}, status: {status}")
return True
else:
logger.warning(f"[Lyric] NOT FOUND in DB - task_id: {task_id}")
print(f"[Lyric] NOT FOUND in DB - task_id: {task_id}")
return False
except SQLAlchemyError as e:
logger.error(f"[Lyric] DB Error while updating status - task_id: {task_id}, error: {e}")
print(f"[Lyric] DB Error while updating status - task_id: {task_id}, error: {e}")
return False
except Exception as e:
logger.error(f"[Lyric] Unexpected error while updating status - task_id: {task_id}, error: {e}")
print(f"[Lyric] Unexpected error while updating status - task_id: {task_id}, error: {e}")
return False
async def generate_lyric_background(
task_id: str,
prompt: str,
language: str,
) -> None:
"""백그라운드에서 ChatGPT를 통해 가사를 생성하고 Lyric 테이블을 업데이트합니다.
Args:
task_id: 프로젝트 task_id
prompt: ChatGPT에 전달할 프롬프트
language: 가사 언어
"""
import time
task_start = time.perf_counter()
logger.info(f"[generate_lyric_background] START - task_id: {task_id}")
print(f"[generate_lyric_background] ========== START ==========")
print(f"[generate_lyric_background] task_id: {task_id}")
print(f"[generate_lyric_background] language: {language}")
print(f"[generate_lyric_background] prompt length: {len(prompt)}자")
try:
# ========== Step 1: ChatGPT 서비스 초기화 ==========
step1_start = time.perf_counter()
print(f"[generate_lyric_background] Step 1: ChatGPT 서비스 초기화...")
service = ChatgptService(
customer_name="", # 프롬프트가 이미 생성되었으므로 빈 값
region="",
detail_region_info="",
language=language,
)
step1_elapsed = (time.perf_counter() - step1_start) * 1000
print(f"[generate_lyric_background] Step 1 완료 ({step1_elapsed:.1f}ms)")
# ========== Step 2: ChatGPT API 호출 (가사 생성) ==========
step2_start = time.perf_counter()
logger.info(f"[generate_lyric_background] Step 2: ChatGPT API 호출 시작 - task_id: {task_id}")
print(f"[generate_lyric_background] Step 2: ChatGPT API 호출 시작...")
result = await service.generate(prompt=prompt)
step2_elapsed = (time.perf_counter() - step2_start) * 1000
logger.info(f"[generate_lyric_background] Step 2 완료 - 응답 {len(result)}자 ({step2_elapsed:.1f}ms)")
print(f"[generate_lyric_background] Step 2 완료 - 응답 {len(result)}자 ({step2_elapsed:.1f}ms)")
# ========== Step 3: DB 상태 업데이트 ==========
step3_start = time.perf_counter()
print(f"[generate_lyric_background] Step 3: DB 상태 업데이트...")
await _update_lyric_status(task_id, "completed", result)
step3_elapsed = (time.perf_counter() - step3_start) * 1000
print(f"[generate_lyric_background] Step 3 완료 ({step3_elapsed:.1f}ms)")
# ========== 완료 ==========
total_elapsed = (time.perf_counter() - task_start) * 1000
logger.info(f"[generate_lyric_background] SUCCESS - task_id: {task_id}, 총 소요시간: {total_elapsed:.1f}ms")
print(f"[generate_lyric_background] ========== SUCCESS ==========")
print(f"[generate_lyric_background] 총 소요시간: {total_elapsed:.1f}ms")
print(f"[generate_lyric_background] - Step 1 (서비스 초기화): {step1_elapsed:.1f}ms")
print(f"[generate_lyric_background] - Step 2 (GPT API 호출): {step2_elapsed:.1f}ms")
print(f"[generate_lyric_background] - Step 3 (DB 업데이트): {step3_elapsed:.1f}ms")
except SQLAlchemyError as e:
elapsed = (time.perf_counter() - task_start) * 1000
logger.error(f"[generate_lyric_background] DB ERROR - task_id: {task_id}, error: {e} ({elapsed:.1f}ms)")
print(f"[generate_lyric_background] DB ERROR - {e} ({elapsed:.1f}ms)")
traceback.print_exc()
await _update_lyric_status(task_id, "failed", f"Database Error: {str(e)}")
except Exception as e:
elapsed = (time.perf_counter() - task_start) * 1000
logger.error(f"[generate_lyric_background] EXCEPTION - task_id: {task_id}, error: {e} ({elapsed:.1f}ms)")
print(f"[generate_lyric_background] EXCEPTION - {e} ({elapsed:.1f}ms)")
traceback.print_exc()
await _update_lyric_status(task_id, "failed", f"Error: {str(e)}")