feat: update song model and related routers, schemas, worker
This commit is contained in:
1 parent
ece201f92b
commit
ee6069e5d5
7 files changed
+222
-148
No files matched your search
@@ -13,7 +13,7 @@ Song API Router
|
||||
app.include_router(router, prefix="/api/v1")
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
@@ -32,6 +32,7 @@ from app.song.schemas.song_schema import (
|
||||
PollingSongResponse,
|
||||
SongListItem,
|
||||
)
|
||||
from app.song.worker.song_task import download_and_upload_song_by_suno_task_id
|
||||
from app.utils.logger import get_logger
|
||||
from app.utils.pagination import PaginatedResponse
|
||||
from app.utils.suno import SunoService
|
||||
@@ -294,17 +295,17 @@ async def generate_song(
|
||||
|
||||
@router.get(
|
||||
"/status/{song_id}",
|
||||
summary="노래 생성 상태 조회",
|
||||
summary="노래 생성 상태 조회 (Suno API)",
|
||||
description="""
|
||||
Suno API를 통해 노래 생성 작업의 상태를 조회합니다.
|
||||
SUCCESS 상태인 경우 백그라운드에서 MP3 파일을 다운로드하고 Azure Blob Storage에 업로드한 뒤 Song 테이블을 업데이트합니다.
|
||||
SUCCESS 상태인 경우 백그라운드에서 MP3 파일을 다운로드하고 Azure Blob Storage에 업로드를 시작합니다.
|
||||
|
||||
## 경로 파라미터
|
||||
- **song_id**: 노래 생성 시 반환된 작업 ID (필수)
|
||||
- **song_id**: 노래 생성 시 반환된 Suno API 작업 ID (필수)
|
||||
|
||||
## 반환 정보
|
||||
- **success**: 조회 성공 여부
|
||||
- **status**: 작업 상태 (PENDING, processing, SUCCESS, failed)
|
||||
- **status**: Suno API 작업 상태
|
||||
- **message**: 상태 메시지
|
||||
|
||||
## 사용 예시
|
||||
@@ -312,27 +313,28 @@ SUCCESS 상태인 경우 백그라운드에서 MP3 파일을 다운로드하고
|
||||
GET /song/status/abc123...
|
||||
```
|
||||
|
||||
## 상태 값
|
||||
- **PENDING**: 대기 중
|
||||
- **processing**: 생성 중
|
||||
- **SUCCESS**: 생성 완료
|
||||
- **failed**: 생성 실패
|
||||
## 상태 값 (Suno API 응답)
|
||||
- **PENDING**: Suno API 대기 중
|
||||
- **processing**: Suno API에서 노래 생성 중
|
||||
- **SUCCESS**: Suno API 노래 생성 완료 (백그라운드 Blob 업로드 시작)
|
||||
- **TEXT_SUCCESS**: Suno API 노래 생성 완료
|
||||
- **failed**: Suno API 노래 생성 실패
|
||||
- **error**: API 조회 오류
|
||||
|
||||
## 참고
|
||||
- 스트림 URL: 30-40초 내 생성
|
||||
- 다운로드 URL: 2-3분 내 생성
|
||||
- SUCCESS 시 백그라운드에서 MP3 다운로드 → Azure Blob Storage 업로드 → Song 테이블 업데이트 진행
|
||||
- 저장 경로: Azure Blob Storage ({BASE_URL}/{task_id}/song/{store_name}.mp3)
|
||||
- Song 테이블의 song_result_url에 Blob URL이 저장됩니다
|
||||
- 이 엔드포인트는 Suno API의 상태를 반환합니다
|
||||
- SUCCESS 응답 시 백그라운드에서 MP3 다운로드 → Azure Blob Storage 업로드가 시작됩니다
|
||||
- 최종 완료 상태는 `/song/download/{task_id}` 엔드포인트에서 확인하세요
|
||||
- Song 테이블 상태: processing → uploading → completed
|
||||
""",
|
||||
response_model=PollingSongResponse,
|
||||
responses={
|
||||
200: {"description": "상태 조회 성공"},
|
||||
500: {"description": "상태 조회 실패"},
|
||||
},
|
||||
)
|
||||
async def get_song_status(
|
||||
song_id: str,
|
||||
background_tasks: BackgroundTasks,
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> PollingSongResponse:
|
||||
"""song_id로 노래 생성 작업의 상태를 조회합니다.
|
||||
@@ -345,10 +347,11 @@ async def get_song_status(
|
||||
try:
|
||||
suno_service = SunoService()
|
||||
result = await suno_service.get_task_status(song_id)
|
||||
logger.debug(f"[get_song_status] Suno API raw response - song_id: {song_id}, result: {result}")
|
||||
parsed_response = suno_service.parse_status_response(result)
|
||||
logger.info(f"[get_song_status] Suno API response - song_id: {song_id}, status: {parsed_response.status}")
|
||||
|
||||
# SUCCESS 상태인 경우 첫 번째 클립 정보를 DB에 직접 저장
|
||||
# SUCCESS 상태인 경우 백그라운드에서 MP3 다운로드 및 Blob 업로드 진행
|
||||
if parsed_response.status == "SUCCESS" and result:
|
||||
# result에서 직접 clips 데이터 추출
|
||||
data = result.get("data", {})
|
||||
@@ -372,14 +375,33 @@ async def get_song_status(
|
||||
)
|
||||
song = song_result.scalar_one_or_none()
|
||||
|
||||
if song and song.status != "completed":
|
||||
# 첫 번째 클립의 audio_url과 duration을 직접 DB에 저장
|
||||
song.status = "completed"
|
||||
song.song_result_url = audio_url
|
||||
if clip_duration is not None:
|
||||
song.duration = clip_duration
|
||||
# processing 상태인 경우에만 백그라운드 태스크 실행 (중복 방지)
|
||||
if song and song.status == "processing":
|
||||
# store_name 조회
|
||||
project_result = await session.execute(
|
||||
select(Project).where(Project.id == song.project_id)
|
||||
)
|
||||
project = project_result.scalar_one_or_none()
|
||||
store_name = project.store_name if project else "song"
|
||||
|
||||
# 상태를 uploading으로 변경 (중복 호출 방지)
|
||||
song.status = "uploading"
|
||||
song.suno_audio_id = first_clip.get('id')
|
||||
await session.commit()
|
||||
logger.info(f"[get_song_status] Song updated - song_id: {song_id}, status: completed, song_result_url: {audio_url}, duration: {clip_duration}")
|
||||
logger.info(f"[get_song_status] Song status changed to uploading - song_id: {song_id}")
|
||||
|
||||
# 백그라운드 태스크로 MP3 다운로드 및 Blob 업로드 실행
|
||||
background_tasks.add_task(
|
||||
download_and_upload_song_by_suno_task_id,
|
||||
suno_task_id=song_id,
|
||||
audio_url=audio_url,
|
||||
store_name=store_name,
|
||||
duration=clip_duration,
|
||||
)
|
||||
logger.info(f"[get_song_status] Background task scheduled - song_id: {song_id}, store_name: {store_name}")
|
||||
|
||||
elif song and song.status == "uploading":
|
||||
logger.info(f"[get_song_status] SKIPPED - Song is already uploading, song_id: {song_id}")
|
||||
elif song and song.status == "completed":
|
||||
logger.info(f"[get_song_status] SKIPPED - Song already completed, song_id: {song_id}")
|
||||
|
||||
@@ -400,7 +422,7 @@ async def get_song_status(
|
||||
|
||||
@router.get(
|
||||
"/download/{task_id}",
|
||||
summary="노래 생성 URL 조회",
|
||||
summary="노래 다운로드 상태 조회 (DB Polling)",
|
||||
description="""
|
||||
task_id를 기반으로 Song 테이블의 상태를 조회하고,
|
||||
completed인 경우 Project 정보와 노래 URL을 반환합니다.
|
||||
@@ -410,31 +432,38 @@ completed인 경우 Project 정보와 노래 URL을 반환합니다.
|
||||
|
||||
## 반환 정보
|
||||
- **success**: 조회 성공 여부
|
||||
- **status**: 처리 상태 (processing, completed, failed, not_found)
|
||||
- **status**: DB 처리 상태 (processing, uploading, completed, failed, not_found, error)
|
||||
- **message**: 응답 메시지
|
||||
- **store_name**: 업체명
|
||||
- **region**: 지역명
|
||||
- **detail_region_info**: 상세 지역 정보
|
||||
- **store_name**: 업체명 (completed 시)
|
||||
- **region**: 지역명 (completed 시)
|
||||
- **detail_region_info**: 상세 지역 정보 (completed 시)
|
||||
- **task_id**: 작업 고유 식별자
|
||||
- **language**: 언어
|
||||
- **language**: 언어 (completed 시)
|
||||
- **song_result_url**: 노래 결과 URL (completed 시, Azure Blob Storage URL)
|
||||
- **created_at**: 생성 일시
|
||||
- **created_at**: 생성 일시 (completed 시)
|
||||
- **error_message**: 에러 메시지 (실패 시)
|
||||
|
||||
## 사용 예시
|
||||
```
|
||||
GET /song/download/019123ab-cdef-7890-abcd-ef1234567890
|
||||
```
|
||||
|
||||
## 상태 값 (DB 상태)
|
||||
- **processing**: Suno API에서 노래 생성 중
|
||||
- **uploading**: MP3 다운로드 및 Azure Blob 업로드 중
|
||||
- **completed**: 모든 작업 완료, Blob URL 사용 가능
|
||||
- **failed**: 노래 생성 또는 업로드 실패
|
||||
- **not_found**: task_id에 해당하는 Song 없음
|
||||
- **error**: 조회 중 오류 발생
|
||||
|
||||
## 참고
|
||||
- processing 상태인 경우 song_result_url은 null입니다.
|
||||
- completed 상태인 경우 Project 정보와 함께 song_result_url (Azure Blob URL)을 반환합니다.
|
||||
- 이 엔드포인트는 DB의 Song 테이블 상태를 반환합니다
|
||||
- completed 상태인 경우 Project 정보와 함께 song_result_url (Azure Blob URL)을 반환합니다
|
||||
- song_result_url 형식: {AZURE_BLOB_BASE_URL}/{task_id}/song/{store_name}.mp3
|
||||
""",
|
||||
response_model=DownloadSongResponse,
|
||||
responses={
|
||||
200: {"description": "조회 성공"},
|
||||
404: {"description": "Song을 찾을 수 없음"},
|
||||
500: {"description": "조회 실패"},
|
||||
200: {"description": "조회 성공 (모든 상태에서 200 반환)"},
|
||||
},
|
||||
)
|
||||
async def download_song(
|
||||
@@ -474,6 +503,16 @@ async def download_song(
|
||||
task_id=task_id,
|
||||
)
|
||||
|
||||
# uploading 상태인 경우
|
||||
if song.status == "uploading":
|
||||
logger.info(f"[download_song] UPLOADING - task_id: {task_id}")
|
||||
return DownloadSongResponse(
|
||||
success=True,
|
||||
status="uploading",
|
||||
message="노래 파일을 업로드 중입니다.",
|
||||
task_id=task_id,
|
||||
)
|
||||
|
||||
# failed 상태인 경우
|
||||
if song.status == "failed":
|
||||
logger.warning(f"[download_song] FAILED - task_id: {task_id}")
|
||||
@@ -546,7 +585,6 @@ GET /songs/?page=1&page_size=10
|
||||
response_model=PaginatedResponse[SongListItem],
|
||||
responses={
|
||||
200: {"description": "노래 목록 조회 성공"},
|
||||
500: {"description": "조회 실패"},
|
||||
},
|
||||
)
|
||||
async def get_songs(
|
||||
|
||||
Reference in new issue
Block a user