노래 백그라운드 추가

This commit is contained in:
bluebamus committed 2025-12-24 15:13:46 +09:00
1 parent cafe6a894e
commit b7df726345
14 files changed
+1102 -715

No files matched your search

-146
View File
@@ -1,146 +0,0 @@
from typing import Any
from fastapi import APIRouter, Depends, Request # , UploadFile, File, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.session import get_session
from app.lyrics.services import lyrics
router = APIRouter(prefix="/lyrics", tags=["lyrics"])
@router.get("/store")
async def home(
request: Request,
conn: AsyncSession = Depends(get_session),
):
# store_info_list: List[StoreData] = await lyrics_svc.get_store_info(conn)
result: Any = await lyrics.get_store_info(conn)
# return templates.TemplateResponse(
# request=request,
# name="store.html",
# context={"store_info_list": result},
# )
pass
@router.post("/attributes")
async def attribute(
request: Request,
conn: AsyncSession = Depends(get_session),
):
print("attributes")
print(await request.form())
result: Any = await lyrics.get_attribute(conn)
print(result)
# return templates.TemplateResponse(
# request=request,
# name="attribute.html",
# context={
# "attribute_group_dict": result,
# "before_dict": await request.form(),
# },
# )
pass
@router.post("/fewshot")
async def sample_song(
request: Request,
conn: AsyncSession = Depends(get_session),
):
print("fewshot")
print(await request.form())
result: Any = await lyrics.get_sample_song(conn)
print(result)
# return templates.TemplateResponse(
# request=request,
# name="fewshot.html",
# context={"fewshot_list": result, "before_dict": await request.form()},
# )
pass
@router.post("/prompt")
async def prompt_template(
request: Request,
conn: AsyncSession = Depends(get_session),
):
print("prompt_template")
print(await request.form())
result: Any = await lyrics.get_prompt_template(conn)
print(result)
print("prompt_template after")
print(await request.form())
# return templates.TemplateResponse(
# request=request,
# name="prompt.html",
# context={"prompt_list": result, "before_dict": await request.form()},
# )
pass
@router.post("/result")
async def song_result(
request: Request,
conn: AsyncSession = Depends(get_session),
):
print("song_result")
print(await request.form())
result: Any = await lyrics.make_song_result(request, conn)
print("result : ", result)
# return templates.TemplateResponse(
# request=request,
# name="result.html",
# context={"result_dict": result},
# )
pass
@router.get("/result")
async def get_song_result(
request: Request,
conn: AsyncSession = Depends(get_session),
):
print("get_song_result")
print(await request.form())
result: Any = await lyrics.get_song_result(conn)
print("result : ", result)
# return templates.TemplateResponse(
# request=request,
# name="result.html",
# context={"result_dict": result},
# )
pass
@router.post("/automation")
async def automation(
request: Request,
conn: AsyncSession = Depends(get_session),
):
print("automation")
print(await request.form())
result: Any = await lyrics.make_automation(request, conn)
print("result : ", result)
# return templates.TemplateResponse(
# request=request,
# name="result.html",
# context={"result_dict": result},
# )
pass
+230 -187
View File
@@ -4,110 +4,45 @@ Song API Router
이 모듈은 Suno API를 통한 노래 생성 관련 API 엔드포인트를 정의합니다.
엔드포인트 목록:
- POST /song/generate: 노래 생성 요청
- GET /song/status/{task_id}: 노래 생성 상태 조회
- GET /song/download/{task_id}: 노래 다운로드
- POST /song/generate/{task_id}: 노래 생성 요청 (task_id로 Project/Lyric 연결)
- GET /song/status/{suno_task_id}: Suno API 노래 생성 상태 조회
- GET /song/download/{task_id}: 노래 다운로드 상태 조회 (DB polling)
사용 예시:
from app.song.api.routers.v1.song import router
app.include_router(router, prefix="/api/v1")
"""
from datetime import date
from pathlib import Path
import aiofiles
import httpx
from fastapi import APIRouter
from uuid_extensions import uuid7str
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
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.song.models import Song
from app.song.schemas.song_schema import (
DownloadSongResponse,
GenerateSongRequest,
GenerateSongResponse,
PollingSongResponse,
SongClipData,
)
from app.song.worker.song_task import download_and_save_song
from app.utils.suno import SunoService
from config import prj_settings
def _parse_suno_status_response(result: dict | None) -> PollingSongResponse:
"""Suno API 상태 응답을 파싱하여 PollingSongResponse로 변환합니다."""
if result is None:
return PollingSongResponse(
success=False,
status="error",
message="Suno API 응답이 비어있습니다.",
clips=None,
raw_response=None,
error_message="Suno API returned None response",
)
code = result.get("code", 0)
data = result.get("data", {})
if code != 200:
return PollingSongResponse(
success=False,
status="failed",
message="Suno API 응답 오류",
clips=None,
raw_response=result,
error_message=result.get("msg", "Unknown error"),
)
status = data.get("status", "unknown")
# 클립 데이터는 data.response.sunoData에 있음 (camelCase)
# data.get()이 None을 반환할 수 있으므로 or {}로 처리
response_data = data.get("response") or {}
clips_data = response_data.get("sunoData") or []
# 상태별 메시지 (Suno API는 다양한 상태값 반환)
status_messages = {
"pending": "노래 생성 대기 중입니다.",
"processing": "노래를 생성하고 있습니다.",
"complete": "노래 생성이 완료되었습니다.",
"SUCCESS": "노래 생성이 완료되었습니다.",
"TEXT_SUCCESS": "노래 생성이 완료되었습니다.",
"failed": "노래 생성에 실패했습니다.",
}
# 클립 데이터 파싱 (Suno API는 camelCase 사용)
clips = None
if clips_data:
clips = [
SongClipData(
id=clip.get("id"),
audio_url=clip.get("audioUrl"),
stream_audio_url=clip.get("streamAudioUrl"),
image_url=clip.get("imageUrl"),
title=clip.get("title"),
status=clip.get("status"),
duration=clip.get("duration"),
)
for clip in clips_data
]
return PollingSongResponse(
success=True,
status=status,
message=status_messages.get(status, f"상태: {status}"),
clips=clips,
raw_response=result,
error_message=None,
)
router = APIRouter(prefix="/song", tags=["song"])
@router.post(
"/generate",
"/generate/{task_id}",
summary="노래 생성 요청",
description="""
Suno API를 통해 노래 생성을 요청합니다.
## 경로 파라미터
- **task_id**: Project/Lyric의 task_id (필수) - 연관된 프로젝트와 가사를 조회하는 데 사용
## 요청 필드
- **lyrics**: 노래에 사용할 가사 (필수)
- **genre**: 음악 장르 (필수) - K-Pop, Pop, R&B, Hip-Hop, Ballad, EDM, Rock, Jazz 등
@@ -115,12 +50,13 @@ Suno API를 통해 노래 생성을 요청합니다.
## 반환 정보
- **success**: 요청 성공 여부
- **task_id**: Suno 작업 ID (폴링에 사용)
- **task_id**: 내부 작업 ID (Project/Lyric task_id)
- **suno_task_id**: Suno API 작업 ID (상태 조회에 사용)
- **message**: 응답 메시지
## 사용 예시
```
POST /song/generate
POST /song/generate/019123ab-cdef-7890-abcd-ef1234567890
{
"lyrics": "여기 군산에서 만나요\\n아름다운 하루를 함께",
"genre": "K-Pop",
@@ -130,53 +66,124 @@ POST /song/generate
## 참고
- 생성되는 노래는 약 1분 이내 길이입니다.
- task_id를 사용하여 /status/{task_id} 엔드포인트에서 생성 상태를 확인할 수 있습니다.
- suno_task_id를 사용하여 /status/{suno_task_id} 엔드포인트에서 생성 상태를 확인할 수 있습니다.
- Song 테이블에 데이터가 저장되며, project_id와 lyric_id가 자동으로 연결됩니다.
""",
response_model=GenerateSongResponse,
responses={
200: {"description": "노래 생성 요청 성공"},
404: {"description": "Project 또는 Lyric을 찾을 수 없음"},
500: {"description": "노래 생성 요청 실패"},
},
)
async def generate_song(
task_id: str,
request_body: GenerateSongRequest,
session: AsyncSession = Depends(get_session),
) -> GenerateSongResponse:
"""가사와 장르를 기반으로 Suno API를 통해 노래를 생성합니다."""
try:
suno_service = SunoService()
"""가사와 장르를 기반으로 Suno API를 통해 노래를 생성합니다.
task_id = await suno_service.generate(
1. task_id로 Project와 Lyric 조회
2. Song 테이블에 초기 데이터 저장 (status: processing)
3. Suno API 호출
4. suno_task_id 업데이트 후 응답 반환
"""
print(f"[generate_song] START - task_id: {task_id}, genre: {request_body.genre}, language: {request_body.language}")
try:
# 1. task_id로 Project 조회
project_result = await session.execute(
select(Project).where(Project.task_id == task_id)
)
project = project_result.scalar_one_or_none()
if not project:
print(f"[generate_song] Project NOT FOUND - task_id: {task_id}")
raise HTTPException(
status_code=404,
detail=f"task_id '{task_id}'에 해당하는 Project를 찾을 수 없습니다.",
)
print(f"[generate_song] Project found - project_id: {project.id}, task_id: {task_id}")
# 2. task_id로 Lyric 조회
lyric_result = await session.execute(
select(Lyric).where(Lyric.task_id == task_id)
)
lyric = lyric_result.scalar_one_or_none()
if not lyric:
print(f"[generate_song] Lyric NOT FOUND - task_id: {task_id}")
raise HTTPException(
status_code=404,
detail=f"task_id '{task_id}'에 해당하는 Lyric을 찾을 수 없습니다.",
)
print(f"[generate_song] Lyric found - lyric_id: {lyric.id}, task_id: {task_id}")
# 3. Song 테이블에 초기 데이터 저장
song_prompt = (
f"[Lyrics]\n{request_body.lyrics}\n\n[Genre]\n{request_body.genre}"
)
song = Song(
project_id=project.id,
lyric_id=lyric.id,
task_id=task_id,
suno_task_id=None,
status="processing",
song_prompt=song_prompt,
language=request_body.language,
)
session.add(song)
await session.flush() # ID 생성을 위해 flush
print(f"[generate_song] Song saved (processing) - task_id: {task_id}")
# 4. Suno API 호출
print(f"[generate_song] Suno API generation started - task_id: {task_id}")
suno_service = SunoService()
suno_task_id = await suno_service.generate(
prompt=request_body.lyrics,
genre=request_body.genre,
)
# 5. suno_task_id 업데이트
song.suno_task_id = suno_task_id
await session.commit()
print(f"[generate_song] SUCCESS - task_id: {task_id}, suno_task_id: {suno_task_id}")
return GenerateSongResponse(
success=True,
task_id=task_id,
message="노래 생성 요청이 접수되었습니다. task_id로 상태를 조회하세요.",
suno_task_id=suno_task_id,
message="노래 생성 요청이 접수되었습니다. suno_task_id로 상태를 조회하세요.",
error_message=None,
)
except HTTPException:
raise
except Exception as e:
print(f"[generate_song] EXCEPTION - task_id: {task_id}, error: {e}")
await session.rollback()
return GenerateSongResponse(
success=False,
task_id=None,
task_id=task_id,
suno_task_id=None,
message="노래 생성 요청에 실패했습니다.",
error_message=str(e),
)
@router.get(
"/status/{task_id}",
"/status/{suno_task_id}",
summary="노래 생성 상태 조회",
description="""
Suno API를 통해 노래 생성 작업의 상태를 조회합니다.
SUCCESS 상태인 경우 백그라운드에서 MP3 파일을 다운로드하고 Song 테이블을 업데이트합니다.
## 경로 파라미터
- **task_id**: 노래 생성 시 반환된 작업 ID (필수)
- **suno_task_id**: 노래 생성 시 반환된 Suno API 작업 ID (필수)
## 반환 정보
- **success**: 조회 성공 여부
- **status**: 작업 상태 (pending, processing, complete, failed)
- **status**: 작업 상태 (PENDING, processing, SUCCESS, failed)
- **message**: 상태 메시지
- **clips**: 생성된 노래 클립 목록 (완료 시)
- **raw_response**: Suno API 원본 응답
@@ -187,14 +194,15 @@ GET /song/status/abc123...
```
## 상태 값
- **pending**: 대기 중
- **PENDING**: 대기 중
- **processing**: 생성 중
- **complete**: 생성 완료
- **SUCCESS**: 생성 완료
- **failed**: 생성 실패
## 참고
- 스트림 URL: 30-40초 내 생성
- 다운로드 URL: 2-3분 내 생성
- SUCCESS 시 백그라운드에서 MP3 다운로드 및 DB 업데이트 진행
""",
response_model=PollingSongResponse,
responses={
@@ -203,16 +211,63 @@ GET /song/status/abc123...
},
)
async def get_song_status(
task_id: str,
suno_task_id: str,
background_tasks: BackgroundTasks,
session: AsyncSession = Depends(get_session),
) -> PollingSongResponse:
"""task_id로 노래 생성 작업의 상태를 조회합니다."""
"""suno_task_id로 노래 생성 작업의 상태를 조회합니다.
SUCCESS 상태인 경우 백그라운드에서 MP3 파일을 다운로드하고
Song 테이블의 status를 completed로, song_result_url을 업데이트합니다.
"""
print(f"[get_song_status] START - suno_task_id: {suno_task_id}")
try:
suno_service = SunoService()
result = await suno_service.get_task_status(task_id)
return _parse_suno_status_response(result)
result = await suno_service.get_task_status(suno_task_id)
parsed_response = suno_service.parse_status_response(result)
print(f"[get_song_status] Suno API response - suno_task_id: {suno_task_id}, status: {parsed_response.status}")
# SUCCESS 상태인 경우 백그라운드 태스크 실행
if parsed_response.status == "SUCCESS" and parsed_response.clips:
# 첫 번째 클립의 audioUrl 가져오기
first_clip = parsed_response.clips[0]
audio_url = first_clip.audio_url
if audio_url:
# suno_task_id로 Song 조회하여 task_id 가져오기 (여러 개 있을 경우 가장 최근 것 선택)
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 song:
# task_id로 Project 조회하여 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"
# 백그라운드 태스크로 MP3 다운로드 및 DB 업데이트
print(f"[get_song_status] Background task args - task_id: {song.task_id}, audio_url: {audio_url}, store_name: {store_name}")
background_tasks.add_task(
download_and_save_song,
task_id=song.task_id,
audio_url=audio_url,
store_name=store_name,
)
print(f"[get_song_status] SUCCESS - suno_task_id: {suno_task_id}")
return parsed_response
except Exception as e:
import traceback
print(f"[get_song_status] EXCEPTION - suno_task_id: {suno_task_id}, error: {e}")
return PollingSongResponse(
success=False,
status="error",
@@ -225,127 +280,115 @@ async def get_song_status(
@router.get(
"/download/{task_id}",
summary="노래 다운로드",
summary="노래 다운로드 상태 조회",
description="""
완료된 노래를 서버에 다운로드하고 접근 가능한 URL을 반환합니다.
task_id를 기반으로 Song 테이블의 상태를 polling하고,
completed인 경우 Project 정보와 노래 URL을 반환합니다.
## 경로 파라미터
- **task_id**: 노래 생성 시 반환된 작업 ID (필수)
## 경로 파라미터
- **task_id**: 프로젝트 task_id (필수)
## 반환 정보
- **success**: 다운로드 성공 여부
- **message**: 응답 메시지
- **file_path**: 저장된 파일의 상대 경로
- **file_url**: 프론트엔드에서 접근 가능한 파일 URL
## 반환 정보
- **success**: 조회 성공 여부
- **status**: 처리 상태 (processing, completed, failed)
- **message**: 응답 메시지
- **store_name**: 업체명
- **region**: 지역명
- **detail_region_info**: 상세 지역 정보
- **task_id**: 작업 고유 식별자
- **language**: 언어
- **song_result_url**: 노래 결과 URL (completed 시)
- **created_at**: 생성 일시
## 사용 예시
```
GET /song/download/abc123...
```
## 사용 예시
```
GET /song/download/019123ab-cdef-7890-abcd-ef1234567890
```
## 참고
- 노래 생성이 완료된 상태(complete)에서만 다운로드 가능합니다.
- 파일은 /media/{날짜}/{uuid7}/song.mp3 경로에 저장됩니다.
- 반환된 file_url을 사용하여 프론트엔드에서 MP3를 재생할 수 있습니다.
## 참고
- processing 상태인 경우 song_result_url은 null입니다.
- completed 상태인 경우 Project 정보와 함께 song_result_url을 반환합니다.
""",
response_model=DownloadSongResponse,
responses={
200: {"description": "다운로드 성공"},
400: {"description": "노래 생성이 완료되지 않음"},
500: {"description": "다운로드 실패"},
200: {"description": "조회 성공"},
404: {"description": "Song을 찾을 수 없음"},
500: {"description": "조회 실패"},
},
)
async def download_song(
task_id: str,
session: AsyncSession = Depends(get_session),
) -> DownloadSongResponse:
"""완료된 노래를 다운로드하여 서버에 저장하고 접근 URL을 반환합니다."""
"""task_id로 Song 상태를 polling하고 completed 시 Project 정보와 노래 URL을 반환합니다."""
print(f"[download_song] START - task_id: {task_id}")
try:
suno_service = SunoService()
result = await suno_service.get_task_status(task_id)
# task_id로 Song 조회 (여러 개 있을 경우 가장 최근 것 선택)
song_result = await session.execute(
select(Song)
.where(Song.task_id == task_id)
.order_by(Song.created_at.desc())
.limit(1)
)
song = song_result.scalar_one_or_none()
# API 응답 확인
if result.get("code") != 200:
if not song:
print(f"[download_song] Song NOT FOUND - task_id: {task_id}")
return DownloadSongResponse(
success=False,
message="Suno API 응답 오류",
error_message=result.get("msg", "Unknown error"),
status="not_found",
message=f"task_id '{task_id}'에 해당하는 Song을 찾을 수 없습니다.",
error_message="Song not found",
)
data = result.get("data", {})
status = data.get("status", "unknown")
print(f"[download_song] Song found - task_id: {task_id}, status: {song.status}")
# 완료 상태 확인 (Suno API는 다양한 완료 상태값 반환)
completed_statuses = {"complete", "SUCCESS", "TEXT_SUCCESS"}
if status not in completed_statuses:
# processing 상태인 경우
if song.status == "processing":
print(f"[download_song] PROCESSING - task_id: {task_id}")
return DownloadSongResponse(
success=True,
status="processing",
message="노래 생성이 진행 중입니다.",
task_id=task_id,
)
# failed 상태인 경우
if song.status == "failed":
print(f"[download_song] FAILED - task_id: {task_id}")
return DownloadSongResponse(
success=False,
message=f"노래 생성이 완료되지 않았습니다. 현재 상태: {status}",
error_message="노래 생성 완료 후 다운로드해 주세요.",
status="failed",
message="노래 생성에 실패했습니다.",
task_id=task_id,
error_message="Song generation failed",
)
# 클립 데이터는 data.response.sunoData에 있음 (camelCase)
# data.get()이 None을 반환할 수 있으므로 or {}로 처리
response_data = data.get("response") or {}
clips_data = response_data.get("sunoData") or []
if not clips_data:
return DownloadSongResponse(
success=False,
message="생성된 노래 클립이 없습니다.",
error_message="sunoData is empty",
)
# 첫 번째 클립의 streamAudioUrl 가져오기 (camelCase)
first_clip = clips_data[0]
stream_audio_url = first_clip.get("streamAudioUrl")
if not stream_audio_url:
return DownloadSongResponse(
success=False,
message="스트리밍 오디오 URL을 찾을 수 없습니다.",
error_message="stream_audio_url is missing",
)
# 저장 경로 생성: media/{날짜}/{uuid7}/song.mp3
today = date.today().isoformat()
unique_id = uuid7str()
relative_dir = f"{today}/{unique_id}"
file_name = "song.mp3"
# 절대 경로 생성
media_dir = Path("media") / today / unique_id
media_dir.mkdir(parents=True, exist_ok=True)
file_path = media_dir / file_name
# 오디오 파일 다운로드 (비동기 파일 쓰기)
async with httpx.AsyncClient() as client:
response = await client.get(stream_audio_url, timeout=60.0)
response.raise_for_status()
# aiofiles는 Path 객체를 문자열로 변환하여 사용
async with aiofiles.open(str(file_path), "wb") as f:
await f.write(response.content)
# 프론트엔드에서 접근 가능한 URL 생성
relative_path = f"/media/{relative_dir}/{file_name}"
base_url = f"http://{prj_settings.PROJECT_DOMAIN}"
file_url = f"{base_url}{relative_path}"
# completed 상태인 경우 - Project 정보 조회
project_result = await session.execute(
select(Project).where(Project.id == song.project_id)
)
project = project_result.scalar_one_or_none()
print(f"[download_song] COMPLETED - task_id: {task_id}, song_result_url: {song.song_result_url}")
return DownloadSongResponse(
success=True,
status="completed",
message="노래 다운로드가 완료되었습니다.",
file_path=relative_path,
file_url=file_url,
store_name=project.store_name if project else None,
region=project.region if project else None,
detail_region_info=project.detail_region_info if project else None,
task_id=task_id,
language=project.language if project else None,
song_result_url=song.song_result_url,
created_at=song.created_at,
)
except httpx.HTTPError as e:
return DownloadSongResponse(
success=False,
message="오디오 파일 다운로드에 실패했습니다.",
error_message=str(e),
)
except Exception as e:
print(f"[download_song] EXCEPTION - task_id: {task_id}, error: {e}")
return DownloadSongResponse(
success=False,
message="노래 다운로드에 실패했습니다.",
status="error",
message="노래 다운로드 조회에 실패했습니다.",
error_message=str(e),
)
+11 -4
View File
@@ -15,7 +15,9 @@ class SongAdmin(ModelView, model=Song):
"project_id",
"lyric_id",
"task_id",
"suno_task_id",
"status",
"language",
"created_at",
]
@@ -24,10 +26,11 @@ class SongAdmin(ModelView, model=Song):
"project_id",
"lyric_id",
"task_id",
"suno_task_id",
"status",
"language",
"song_prompt",
"song_result_url_1",
"song_result_url_2",
"song_result_url",
"created_at",
]
@@ -36,7 +39,9 @@ class SongAdmin(ModelView, model=Song):
column_searchable_list = [
Song.task_id,
Song.suno_task_id,
Song.status,
Song.language,
]
column_default_sort = (Song.created_at, True) # True: DESC (최신순)
@@ -46,6 +51,7 @@ class SongAdmin(ModelView, model=Song):
Song.project_id,
Song.lyric_id,
Song.status,
Song.language,
Song.created_at,
]
@@ -54,9 +60,10 @@ class SongAdmin(ModelView, model=Song):
"project_id": "프로젝트 ID",
"lyric_id": "가사 ID",
"task_id": "작업 ID",
"suno_task_id": "Suno 작업 ID",
"status": "상태",
"language": "언어",
"song_prompt": "프롬프트",
"song_result_url_1": "결과 URL 1",
"song_result_url_2": "결과 URL 2",
"song_result_url": "결과 URL",
"created_at": "생성일시",
}