modify url parameter

This commit is contained in:
Dohyun Lim committed 2026-01-19 16:59:25 +09:00
1 parent f362effe7a
commit 56069a04a1
17 files changed
+68 -492

No files matched your search

+48 -46
View File
@@ -5,7 +5,7 @@ Song API Router
엔드포인트 목록:
- POST /song/generate/{task_id}: 노래 생성 요청 (task_id로 Project/Lyric 연결)
- GET /song/status/{suno_task_id}: Suno API 노래 생성 상태 조회
- GET /song/status/{song_id}: Suno API 노래 생성 상태 조회
- GET /song/download/{task_id}: 노래 다운로드 상태 조회 (DB polling)
사용 예시:
@@ -58,7 +58,7 @@ Suno API를 통해 노래 생성을 요청합니다.
## 반환 정보
- **success**: 요청 성공 여부
- **task_id**: 내부 작업 ID (Project/Lyric task_id)
- **suno_task_id**: Suno API 작업 ID (상태 조회에 사용)
- **song_id**: Suno API 작업 ID (상태 조회에 사용)
- **message**: 응답 메시지
## 사용 예시
@@ -73,7 +73,7 @@ POST /song/generate/019123ab-cdef-7890-abcd-ef1234567890
## 참고
- 생성되는 노래는 약 1분 이내 길이입니다.
- suno_task_id를 사용하여 /status/{suno_task_id} 엔드포인트에서 생성 상태를 확인할 수 있습니다.
- song_id를 사용하여 /status/{song_id} 엔드포인트에서 생성 상태를 확인할 수 있습니다.
- Song 테이블에 데이터가 저장되며, project_id와 lyric_id가 자동으로 연결됩니다.
""",
response_model=GenerateSongResponse,
@@ -193,7 +193,7 @@ async def generate_song(
return GenerateSongResponse(
success=False,
task_id=task_id,
suno_task_id=None,
song_id=None,
message="노래 생성 요청에 실패했습니다.",
error_message=str(e),
)
@@ -237,7 +237,7 @@ async def generate_song(
return GenerateSongResponse(
success=False,
task_id=task_id,
suno_task_id=None,
song_id=None,
message="노래 생성 요청에 실패했습니다.",
error_message=str(e),
)
@@ -273,8 +273,8 @@ async def generate_song(
return GenerateSongResponse(
success=True,
task_id=task_id,
suno_task_id=suno_task_id,
message="노래 생성 요청이 접수되었습니다. suno_task_id로 상태를 조회하세요.",
song_id=suno_task_id,
message="노래 생성 요청이 접수되었습니다. song_id로 상태를 조회하세요.",
error_message=None,
)
@@ -286,28 +286,26 @@ async def generate_song(
return GenerateSongResponse(
success=False,
task_id=task_id,
suno_task_id=suno_task_id,
song_id=suno_task_id,
message="노래 생성은 요청되었으나 DB 업데이트에 실패했습니다.",
error_message=str(e),
)
@router.get(
"/status/{suno_task_id}",
"/status/{song_id}",
summary="노래 생성 상태 조회",
description="""
Suno API를 통해 노래 생성 작업의 상태를 조회합니다.
SUCCESS 상태인 경우 백그라운드에서 MP3 파일을 다운로드하고 Azure Blob Storage에 업로드한 뒤 Song 테이블을 업데이트합니다.
## 경로 파라미터
- **suno_task_id**: 노래 생성 시 반환된 Suno API 작업 ID (필수)
- **song_id**: 노래 생성 시 반환된 작업 ID (필수)
## 반환 정보
- **success**: 조회 성공 여부
- **status**: 작업 상태 (PENDING, processing, SUCCESS, failed)
- **message**: 상태 메시지
- **clips**: 생성된 노래 클립 목록 (완료 시)
- **raw_response**: Suno API 원본 응답
## 사용 예시
```
@@ -334,64 +332,68 @@ GET /song/status/abc123...
},
)
async def get_song_status(
suno_task_id: str,
song_id: str,
session: AsyncSession = Depends(get_session),
) -> PollingSongResponse:
"""suno_task_id로 노래 생성 작업의 상태를 조회합니다.
"""song_id로 노래 생성 작업의 상태를 조회합니다.
SUCCESS 상태인 경우 백그라운드에서 MP3 파일을 다운로드하고
Azure Blob Storage에 업로드한 뒤 Song 테이블의 status를 completed로,
song_result_url을 Blob URL로 업데이트합니다.
"""
logger.info(f"[get_song_status] START - suno_task_id: {suno_task_id}")
logger.info(f"[get_song_status] START - song_id: {song_id}")
try:
suno_service = SunoService()
result = await suno_service.get_task_status(suno_task_id)
result = await suno_service.get_task_status(song_id)
parsed_response = suno_service.parse_status_response(result)
logger.info(f"[get_song_status] Suno API response - suno_task_id: {suno_task_id}, status: {parsed_response.status}")
logger.info(f"[get_song_status] Suno API response - song_id: {song_id}, status: {parsed_response.status}")
# SUCCESS 상태인 경우 첫 번째 클립 정보를 DB에 직접 저장
if parsed_response.status == "SUCCESS" and parsed_response.clips:
# 첫 번째 클립(clips[0])의 audioUrl과 duration 사용
first_clip = parsed_response.clips[0]
audio_url = first_clip.audio_url
clip_duration = first_clip.duration
logger.debug(f"[get_song_status] Using first clip - id: {first_clip.id}, audio_url: {audio_url}, duration: {clip_duration}")
if parsed_response.status == "SUCCESS" and result:
# result에서 직접 clips 데이터 추출
data = result.get("data", {})
response_data = data.get("response") or {}
clips_data = response_data.get("sunoData") or []
if audio_url:
# suno_task_id로 Song 조회
song_result = await session.execute(
select(Song)
.where(Song.suno_task_id == suno_task_id)
.order_by(Song.created_at.desc())
.limit(1)
)
song = song_result.scalar_one_or_none()
if clips_data:
# 첫 번째 클립(clips[0])의 audioUrl과 duration 사용
first_clip = clips_data[0]
audio_url = first_clip.get("audioUrl")
clip_duration = first_clip.get("duration")
logger.debug(f"[get_song_status] Using first clip - id: {first_clip.get('id')}, audio_url: {audio_url}, duration: {clip_duration}")
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
await session.commit()
logger.info(f"[get_song_status] Song updated - suno_task_id: {suno_task_id}, status: completed, song_result_url: {audio_url}, duration: {clip_duration}")
elif song and song.status == "completed":
logger.info(f"[get_song_status] SKIPPED - Song already completed, suno_task_id: {suno_task_id}")
if audio_url:
# song_id로 Song 조회
song_result = await session.execute(
select(Song)
.where(Song.suno_task_id == song_id)
.order_by(Song.created_at.desc())
.limit(1)
)
song = song_result.scalar_one_or_none()
logger.info(f"[get_song_status] SUCCESS - suno_task_id: {suno_task_id}")
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
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}")
elif song and song.status == "completed":
logger.info(f"[get_song_status] SKIPPED - Song already completed, song_id: {song_id}")
logger.info(f"[get_song_status] SUCCESS - song_id: {song_id}")
return parsed_response
except Exception as e:
import traceback
logger.error(f"[get_song_status] EXCEPTION - suno_task_id: {suno_task_id}, error: {e}")
logger.error(f"[get_song_status] EXCEPTION - song_id: {song_id}, error: {e}")
return PollingSongResponse(
success=False,
status="error",
message="상태 조회에 실패했습니다.",
clips=None,
raw_response=None,
error_message=f"{type(e).__name__}: {e}\n{traceback.format_exc()}",
)
+7 -25
View File
@@ -1,6 +1,6 @@
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, Dict, List, Optional
from typing import Dict, List, Optional
from fastapi import Request
from pydantic import BaseModel, Field
@@ -64,8 +64,8 @@ class GenerateSongResponse(BaseModel):
{
"success": true,
"task_id": "019123ab-cdef-7890-abcd-ef1234567890",
"suno_task_id": "abc123...",
"message": "노래 생성 요청이 접수되었습니다. suno_task_id로 상태를 조회하세요.",
"song_id": "abc123...",
"message": "노래 생성 요청이 접수되었습니다. song_id로 상태를 조회하세요.",
"error_message": null
}
@@ -73,7 +73,7 @@ class GenerateSongResponse(BaseModel):
{
"success": false,
"task_id": "019123ab-cdef-7890-abcd-ef1234567890",
"suno_task_id": null,
"song_id": null,
"message": "노래 생성 요청에 실패했습니다.",
"error_message": "Suno API connection error"
}
@@ -81,7 +81,7 @@ class GenerateSongResponse(BaseModel):
success: bool = Field(..., description="요청 성공 여부")
task_id: Optional[str] = Field(None, description="내부 작업 ID (Project/Lyric task_id)")
suno_task_id: Optional[str] = Field(None, description="Suno API 작업 ID")
song_id: Optional[str] = Field(None, description="Suno API 작업 ID")
message: str = Field(..., description="응답 메시지")
error_message: Optional[str] = Field(None, description="에러 메시지 (실패 시)")
@@ -90,7 +90,7 @@ class PollingSongRequest(BaseModel):
"""노래 생성 상태 조회 요청 스키마 (Legacy)
Note:
현재 사용되지 않음. GET /song/status/{suno_task_id} 엔드포인트 사용.
현재 사용되지 않음. GET /song/status/{song_id} 엔드포인트 사용.
Example Request:
{
@@ -117,7 +117,7 @@ class PollingSongResponse(BaseModel):
"""노래 생성 상태 조회 응답 스키마
Usage:
GET /song/status/{suno_task_id}
GET /song/status/{song_id}
Suno API 작업 상태를 조회합니다.
Note:
@@ -138,8 +138,6 @@ class PollingSongResponse(BaseModel):
"success": true,
"status": "processing",
"message": "노래를 생성하고 있습니다.",
"clips": null,
"raw_response": {...},
"error_message": null
}
@@ -148,18 +146,6 @@ class PollingSongResponse(BaseModel):
"success": true,
"status": "SUCCESS",
"message": "노래 생성이 완료되었습니다.",
"clips": [
{
"id": "clip-id",
"audio_url": "https://...",
"stream_audio_url": "https://...",
"image_url": "https://...",
"title": "Song Title",
"status": "complete",
"duration": 60.0
}
],
"raw_response": {...},
"error_message": null
}
@@ -168,8 +154,6 @@ class PollingSongResponse(BaseModel):
"success": false,
"status": "error",
"message": "상태 조회에 실패했습니다.",
"clips": null,
"raw_response": null,
"error_message": "ConnectionError: ..."
}
"""
@@ -179,8 +163,6 @@ class PollingSongResponse(BaseModel):
None, description="작업 상태 (PENDING, processing, SUCCESS, failed)"
)
message: str = Field(..., description="상태 메시지")
clips: Optional[List[SongClipData]] = Field(None, description="생성된 노래 클립 목록")
raw_response: Optional[Dict[str, Any]] = Field(None, description="Suno API 원본 응답")
error_message: Optional[str] = Field(None, description="에러 메시지 (실패 시)")