Compare commits

...
Author SHA1 Message Date
bluebamus 3bfb5c81b6 완성 2025-12-26 17:50:46 +09:00
bluebamus 52520d770b 크레아토 완료 2025-12-26 17:20:36 +09:00
bluebamus 586dd5ccc9 노래 생성 후 blob 업로드 완료 2025-12-26 16:02:14 +09:00
bluebamus 62dd681b83 이미지 업로드 관련 디버그 프린트 삭제 2025-12-26 15:45:35 +09:00
bluebamus 266a51fe1d 이미지 blob에 업로드 완료 2025-12-26 15:34:37 +09:00
bluebamus 12e6f7357c blob 이미지 업로드 완료 2025-12-26 15:25:13 +09:00
bluebamus 6917a76d60 finished upload images 2025-12-26 13:27:39 +09:00
18 changed files with 2458 additions and 584 deletions

No files matched your search

+468 -241
View File
@@ -1,15 +1,28 @@
import json
from datetime import date
from pathlib import Path
from typing import Optional
from urllib.parse import unquote, urlparse
from fastapi import APIRouter
import aiofiles
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.home.schemas.home import (
from app.database.session import get_session
from app.home.models import Image
from app.home.schemas.home_schema import (
CrawlingRequest,
CrawlingResponse,
ErrorResponse,
ImageUploadResponse,
ImageUploadResultItem,
ImageUrlItem,
MarketingAnalysis,
ProcessedInfo,
)
from app.utils.upload_blob_as_request import AzureBlobUploader
from app.utils.chatgpt_prompt import ChatgptService
from app.utils.common import generate_task_id
from app.utils.nvMapScraper import NvMapScraper
MEDIA_ROOT = Path("media")
@@ -123,8 +136,6 @@ async def crawling(request_body: CrawlingRequest):
def _extract_image_name(url: str, index: int) -> str:
"""URL에서 이미지 이름 추출 또는 기본 이름 생성"""
try:
from urllib.parse import unquote, urlparse
path = urlparse(url).path
filename = path.split("/")[-1] if path else ""
if filename:
@@ -134,259 +145,475 @@ def _extract_image_name(url: str, index: int) -> str:
return f"image_{index + 1:03d}"
# @router.post(
# "/generate",
# summary="기본 영상 생성 요청",
# description="""
# 고객 정보만 받아 영상 생성 작업을 시작합니다. (이미지 없음)
# ## 요청 필드
# - **customer_name**: 고객명/가게명 (필수)
# - **region**: 지역명 (필수)
# - **detail_region_info**: 상세 지역 정보 (선택)
# - **attribute**: 음악 속성 정보 (genre, vocal, tempo, mood)
# ## 반환 정보
# - **task_id**: 작업 고유 식별자 (UUID7)
# - **status**: 작업 상태
# - **message**: 응답 메시지
# """,
# response_model=GenerateResponse,
# response_description="생성 작업 시작 결과",
# tags=["generate"],
# )
# async def generate(
# request_body: GenerateRequest,
# background_tasks: BackgroundTasks,
# session: AsyncSession = Depends(get_session),
# ):
# """기본 영상 생성 요청 처리 (이미지 없음)"""
# # UUID7 생성 및 중복 검사
# while True:
# task_id = str(uuid7())
# existing = await session.execute(
# select(Project).where(Project.task_id == task_id)
# )
# if existing.scalar_one_or_none() is None:
# break
# # Project 생성 (이미지 없음)
# project = Project(
# store_name=request_body.customer_name,
# region=request_body.region,
# task_id=task_id,
# detail_region_info=json.dumps(
# {
# "detail": request_body.detail_region_info,
# "attribute": request_body.attribute.model_dump(),
# },
# ensure_ascii=False,
# ),
# )
# session.add(project)
# await session.commit()
# await session.refresh(project)
# background_tasks.add_task(task_process, request_body, task_id, project.id)
# return {
# "task_id": task_id,
# "status": "processing",
# "message": "생성 작업이 시작되었습니다.",
# }
ALLOWED_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".heic", ".heif"}
# @router.post(
# "/generate/urls",
# summary="URL 기반 영상 생성 요청",
# description="""
# 고객 정보와 이미지 URL을 받아 영상 생성 작업을 시작합니다.
# ## 요청 필드
# - **customer_name**: 고객명/가게명 (필수)
# - **region**: 지역명 (필수)
# - **detail_region_info**: 상세 지역 정보 (선택)
# - **attribute**: 음악 속성 정보 (genre, vocal, tempo, mood)
# - **images**: 이미지 URL 목록 (필수)
# ## 반환 정보
# - **task_id**: 작업 고유 식별자 (UUID7)
# - **status**: 작업 상태
# - **message**: 응답 메시지
# """,
# response_model=GenerateResponse,
# response_description="생성 작업 시작 결과",
# tags=["generate"],
# )
# async def generate_urls(
# request_body: GenerateUrlsRequest,
# session: AsyncSession = Depends(get_session),
# ):
# """URL 기반 영상 생성 요청 처리"""
# # UUID7 생성 및 중복 검사
# while True:
# task_id = str(uuid7())
# existing = await session.execute(
# select(Project).where(Project.task_id == task_id)
# )
# if existing.scalar_one_or_none() is None:
# break
# # Project 생성 (이미지 정보 제외)
# project = Project(
# store_name=request_body.customer_name,
# region=request_body.region,
# task_id=task_id,
# detail_region_info=json.dumps(
# {
# "detail": request_body.detail_region_info,
# "attribute": request_body.attribute.model_dump(),
# },
# ensure_ascii=False,
# ),
# )
# session.add(project)
# # Image 레코드 생성 (독립 테이블, task_id로 연결)
# for idx, img_item in enumerate(request_body.images):
# # name이 있으면 사용, 없으면 URL에서 추출
# img_name = img_item.name or _extract_image_name(img_item.url, idx)
# image = Image(
# task_id=task_id,
# img_name=img_name,
# img_url=img_item.url,
# img_order=idx,
# )
# session.add(image)
# await session.commit()
# return {
# "task_id": task_id,
# "status": "processing",
# "message": "생성 작업이 시작되었습니다.",
# }
def _is_valid_image_extension(filename: str | None) -> bool:
"""파일명의 확장자가 유효한 이미지 확장자인지 확인"""
if not filename:
return False
ext = Path(filename).suffix.lower()
return ext in ALLOWED_IMAGE_EXTENSIONS
# async def _save_upload_file(file: UploadFile, save_path: Path) -> None:
# """업로드 파일을 지정된 경로에 저장"""
# save_path.parent.mkdir(parents=True, exist_ok=True)
# async with aiofiles.open(save_path, "wb") as f:
# content = await file.read()
# await f.write(content)
def _get_file_extension(filename: str) -> str:
"""파일명에서 확장자 추출 (소문자)"""
return Path(filename).suffix.lower()
# def _get_file_extension(filename: str | None) -> str:
# """파일명에서 확장자 추출"""
# if not filename:
# return ".jpg"
# ext = Path(filename).suffix.lower()
# return ext if ext else ".jpg"
async def _save_upload_file(file: UploadFile, save_path: Path) -> None:
"""업로드 파일을 지정된 경로에 저장"""
save_path.parent.mkdir(parents=True, exist_ok=True)
async with aiofiles.open(save_path, "wb") as f:
content = await file.read()
await f.write(content)
# @router.post(
# "/generate/upload",
# summary="파일 업로드 기반 영상 생성 요청",
# description="""
# 고객 정보와 이미지 파일을 받아 영상 생성 작업을 시작합니다.
IMAGES_JSON_EXAMPLE = """[
{"url": "https://naverbooking-phinf.pstatic.net/20240514_189/1715688030436xT14o_JPEG/1.jpg"},
{"url": "https://naverbooking-phinf.pstatic.net/20240514_48/1715688030574wTtQd_JPEG/2.jpg"},
{"url": "https://naverbooking-phinf.pstatic.net/20240514_92/17156880307484bvpH_JPEG/3.jpg"},
{"url": "https://naverbooking-phinf.pstatic.net/20240514_7/1715688031000y8Y5q_JPEG/4.jpg"},
{"url": "https://naverbooking-phinf.pstatic.net/20240514_259/17156880311809wCnY_JPEG/5.jpg", "name": "외관"}
]"""
# ## 요청 필드 (multipart/form-data)
# - **customer_name**: 고객명/가게명 (필수)
# - **region**: 지역명 (필수)
# - **detail_region_info**: 상세 지역 정보 (선택)
# - **attribute**: 음악 속성 정보 JSON 문자열 (필수)
# - **images**: 이미지 파일 목록 (필수, 복수 파일)
# ## 반환 정보
# - **task_id**: 작업 고유 식별자 (UUID7)
# - **status**: 작업 상태
# - **message**: 응답 메시지
# - **uploaded_count**: 업로드된 이미지 개수
# """,
# response_model=GenerateUploadResponse,
# response_description="생성 작업 시작 결과",
# tags=["generate"],
# )
# async def generate_upload(
# customer_name: str = Form(..., description="고객명/가게명"),
# region: str = Form(..., description="지역명"),
# attribute: str = Form(..., description="음악 속성 정보 (JSON 문자열)"),
# images: list[UploadFile] = File(..., description="이미지 파일 목록"),
# detail_region_info: str | None = Form(None, description="상세 지역 정보"),
# session: AsyncSession = Depends(get_session),
# ):
# """파일 업로드 기반 영상 생성 요청 처리"""
# # attribute JSON 파싱 및 검증
# try:
# attribute_dict = json.loads(attribute)
# attribute_info = AttributeInfo(**attribute_dict)
# except json.JSONDecodeError:
# raise HTTPException(
# status_code=400, detail="attribute는 유효한 JSON 형식이어야 합니다."
# )
# except Exception as e:
# raise HTTPException(status_code=400, detail=f"attribute 검증 실패: {e}")
@router.post(
"/image/upload/server/{task_id}",
include_in_schema=False,
summary="이미지 업로드 (로컬 서버)",
description="""
task_id에 연결된 이미지를 로컬 서버(media 폴더)에 업로드합니다.
# # 이미지 파일 검증
# if not images:
# raise HTTPException(
# status_code=400, detail="최소 1개 이상의 이미지 파일이 필요합니다."
# )
## 요청 방식
multipart/form-data 형식으로 전송합니다.
# # UUID7 생성 및 중복 검사
# while True:
# task_id = str(uuid7())
# existing = await session.execute(
# select(Project).where(Project.task_id == task_id)
# )
# if existing.scalar_one_or_none() is None:
# break
## 요청 필드
- **images_json**: 외부 이미지 URL 목록 (JSON 문자열, 선택)
- **files**: 이미지 바이너리 파일 목록 (선택)
# # 저장 경로 생성: media/날짜/task_id/
# today = date.today().strftime("%Y%m%d")
# upload_dir = MEDIA_ROOT / today / task_id
**주의**: images_json 또는 files 중 최소 하나는 반드시 전달해야 합니다.
# # Project 생성 (이미지 정보 제외)
# project = Project(
# store_name=customer_name,
# region=region,
# task_id=task_id,
# detail_region_info=json.dumps(
# {
# "detail": detail_region_info,
# "attribute": attribute_info.model_dump(),
# },
# ensure_ascii=False,
# ),
# )
# session.add(project)
## 지원 이미지 확장자
jpg, jpeg, png, webp, heic, heif
# # 이미지 파일 저장 및 Image 레코드 생성
# for idx, file in enumerate(images):
# # 각 이미지에 고유 UUID7 생성
# img_uuid = str(uuid7())
# ext = _get_file_extension(file.filename)
# filename = f"{img_uuid}{ext}"
# save_path = upload_dir / filename
## images_json 예시
```json
[
{"url": "https://naverbooking-phinf.pstatic.net/20240514_189/1715688030436xT14o_JPEG/1.jpg"},
{"url": "https://naverbooking-phinf.pstatic.net/20240514_48/1715688030574wTtQd_JPEG/2.jpg"},
{"url": "https://naverbooking-phinf.pstatic.net/20240514_92/17156880307484bvpH_JPEG/3.jpg"},
{"url": "https://naverbooking-phinf.pstatic.net/20240514_7/1715688031000y8Y5q_JPEG/4.jpg"},
{"url": "https://naverbooking-phinf.pstatic.net/20240514_259/17156880311809wCnY_JPEG/5.jpg", "name": "외관"}
]
```
# # 파일 저장
# await _save_upload_file(file, save_path)
## 바이너리 파일 업로드 테스트 방법
# # Image 레코드 생성 (독립 테이블, task_id로 연결)
# img_url = f"/media/{today}/{task_id}/{filename}"
# image = Image(
# task_id=task_id,
# img_name=file.filename or filename,
# img_url=img_url,
# img_order=idx,
# )
# session.add(image)
### 1. Swagger UI에서 테스트
1. 이 엔드포인트의 "Try it out" 버튼 클릭
2. task_id 입력 (예: test-task-001)
3. files 항목에서 "Add item" 클릭하여 로컬 이미지 파일 선택
4. (선택) images_json에 URL 목록 JSON 입력
5. "Execute" 버튼 클릭
# await session.commit()
### 2. cURL로 테스트
```bash
# 바이너리 파일만 업로드
curl -X POST "http://localhost:8000/image/upload/server/test-task-001" \\
-F "files=@/path/to/image1.jpg" \\
-F "files=@/path/to/image2.png"
# return {
# "task_id": task_id,
# "status": "processing",
# "message": "생성 작업이 시작되었습니다.",
# "uploaded_count": len(images),
# }
# URL + 바이너리 파일 동시 업로드
curl -X POST "http://localhost:8000/image/upload/server/test-task-001" \\
-F 'images_json=[{"url":"https://example.com/image.jpg"}]' \\
-F "files=@/path/to/local_image.jpg"
```
### 3. Python requests로 테스트
```python
import requests
url = "http://localhost:8000/image/upload/server/test-task-001"
files = [
("files", ("image1.jpg", open("image1.jpg", "rb"), "image/jpeg")),
("files", ("image2.png", open("image2.png", "rb"), "image/png")),
]
data = {
"images_json": '[{"url": "https://example.com/image.jpg"}]'
}
response = requests.post(url, files=files, data=data)
print(response.json())
```
## 반환 정보
- **task_id**: 작업 고유 식별자
- **total_count**: 총 업로드된 이미지 개수
- **url_count**: URL로 등록된 이미지 개수 (Image 테이블에 외부 URL 그대로 저장)
- **file_count**: 파일로 업로드된 이미지 개수 (media 폴더에 저장)
- **saved_count**: Image 테이블에 저장된 row 수
- **images**: 업로드된 이미지 목록
- **source**: "url" (외부 URL) 또는 "file" (로컬 서버 저장)
## 저장 경로
- 바이너리 파일: /media/image/{날짜}/{uuid7}/{파일명}
- URL 이미지: 외부 URL 그대로 Image 테이블에 저장
""",
response_model=ImageUploadResponse,
responses={
200: {"description": "이미지 업로드 성공"},
400: {"description": "이미지가 제공되지 않음", "model": ErrorResponse},
},
tags=["image"],
)
async def upload_images(
task_id: str,
images_json: Optional[str] = Form(
default=None,
description="외부 이미지 URL 목록 (JSON 문자열)",
example=IMAGES_JSON_EXAMPLE,
),
files: Optional[list[UploadFile]] = File(
default=None, description="이미지 바이너리 파일 목록"
),
session: AsyncSession = Depends(get_session),
) -> ImageUploadResponse:
"""이미지 업로드 (URL + 바이너리 파일)"""
# 1. 진입 검증: images_json 또는 files 중 하나는 반드시 있어야 함
has_images_json = images_json is not None and images_json.strip() != ""
has_files = files is not None and len(files) > 0
if not has_images_json and not has_files:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="images_json 또는 files 중 하나는 반드시 제공해야 합니다.",
)
# 2. images_json 파싱 (있는 경우만)
url_images: list[ImageUrlItem] = []
if has_images_json:
try:
parsed = json.loads(images_json)
if isinstance(parsed, list):
url_images = [ImageUrlItem(**item) for item in parsed if item]
except (json.JSONDecodeError, TypeError, ValueError) as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"images_json 파싱 오류: {str(e)}",
)
# 3. 유효한 파일만 필터링 (빈 파일, 유효한 이미지 확장자가 아닌 경우 제외)
valid_files: list[UploadFile] = []
skipped_files: list[str] = []
if has_files and files:
for f in files:
is_valid_ext = _is_valid_image_extension(f.filename)
is_not_empty = (
f.size is None or f.size > 0
) # size가 None이면 아직 읽지 않은 것
is_real_file = (
f.filename and f.filename != "filename"
) # Swagger 빈 파일 체크
if f and is_real_file and is_valid_ext and is_not_empty:
valid_files.append(f)
else:
skipped_files.append(f.filename or "unknown")
# 유효한 데이터가 하나도 없으면 에러
if not url_images and not valid_files:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"유효한 이미지가 없습니다. 지원 확장자: {', '.join(ALLOWED_IMAGE_EXTENSIONS)}. 건너뛴 파일: {skipped_files}",
)
result_images: list[ImageUploadResultItem] = []
img_order = 0
# 1. URL 이미지 저장
for url_item in url_images:
img_name = url_item.name or _extract_image_name(url_item.url, img_order)
image = Image(
task_id=task_id,
img_name=img_name,
img_url=url_item.url,
img_order=img_order,
)
session.add(image)
await session.flush() # ID 생성을 위해 flush
result_images.append(
ImageUploadResultItem(
id=image.id,
img_name=img_name,
img_url=url_item.url,
img_order=img_order,
source="url",
)
)
img_order += 1
# 2. 바이너리 파일을 media에 저장
if valid_files:
today = date.today().strftime("%Y-%m-%d")
# 한 번의 요청에서 업로드된 모든 이미지는 같은 폴더에 저장
batch_uuid = await generate_task_id()
upload_dir = MEDIA_ROOT / "image" / today / batch_uuid
upload_dir.mkdir(parents=True, exist_ok=True)
for file in valid_files:
# 파일명: 원본 파일명 사용 (중복 방지를 위해 순서 추가)
original_name = file.filename or "image"
ext = _get_file_extension(file.filename) # type: ignore[arg-type]
# 파일명에서 확장자 제거 후 순서 추가
name_without_ext = (
original_name.rsplit(".", 1)[0]
if "." in original_name
else original_name
)
filename = f"{name_without_ext}_{img_order:03d}{ext}"
save_path = upload_dir / filename
# media에 파일 저장
await _save_upload_file(file, save_path)
# media 기준 URL 생성
img_url = f"/media/image/{today}/{batch_uuid}/{filename}"
img_name = file.filename or filename
image = Image(
task_id=task_id,
img_name=img_name,
img_url=img_url, # Media URL을 DB에 저장
img_order=img_order,
)
session.add(image)
await session.flush()
result_images.append(
ImageUploadResultItem(
id=image.id,
img_name=img_name,
img_url=img_url,
img_order=img_order,
source="file",
)
)
img_order += 1
saved_count = len(result_images)
await session.commit()
return ImageUploadResponse(
task_id=task_id,
total_count=len(result_images),
url_count=len(url_images),
file_count=len(valid_files),
saved_count=saved_count,
images=result_images,
)
@router.post(
"/image/upload/blob/{task_id}",
summary="이미지 업로드 (Azure Blob Storage)",
description="""
task_id에 연결된 이미지를 Azure Blob Storage에 업로드합니다.
바이너리 파일은 로컬 서버에 저장하지 않고 Azure Blob에 직접 업로드됩니다.
## 요청 방식
multipart/form-data 형식으로 전송합니다.
## 요청 필드
- **images_json**: 외부 이미지 URL 목록 (JSON 문자열, 선택)
- **files**: 이미지 바이너리 파일 목록 (선택)
**주의**: images_json 또는 files 중 최소 하나는 반드시 전달해야 합니다.
## 지원 이미지 확장자
jpg, jpeg, png, webp, heic, heif
## images_json 예시
```json
[
{"url": "https://example.com/image1.jpg"},
{"url": "https://example.com/image2.jpg", "name": "외관"}
]
```
## 바이너리 파일 업로드 테스트 방법
### cURL로 테스트
```bash
# 바이너리 파일만 업로드
curl -X POST "http://localhost:8000/image/upload/blob/test-task-001" \\
-F "files=@/path/to/image1.jpg" \\
-F "files=@/path/to/image2.png"
# URL + 바이너리 파일 동시 업로드
curl -X POST "http://localhost:8000/image/upload/blob/test-task-001" \\
-F 'images_json=[{"url":"https://example.com/image.jpg"}]' \\
-F "files=@/path/to/local_image.jpg"
```
## 반환 정보
- **task_id**: 작업 고유 식별자
- **total_count**: 총 업로드된 이미지 개수
- **url_count**: URL로 등록된 이미지 개수 (Image 테이블에 외부 URL 그대로 저장)
- **file_count**: 파일로 업로드된 이미지 개수 (Azure Blob Storage에 저장)
- **saved_count**: Image 테이블에 저장된 row 수
- **images**: 업로드된 이미지 목록
- **source**: "url" (외부 URL) 또는 "blob" (Azure Blob Storage)
## 저장 경로
- 바이너리 파일: Azure Blob Storage ({BASE_URL}/{task_id}/image/{파일명})
- URL 이미지: 외부 URL 그대로 Image 테이블에 저장
""",
response_model=ImageUploadResponse,
responses={
200: {"description": "이미지 업로드 성공"},
400: {"description": "이미지가 제공되지 않음", "model": ErrorResponse},
},
tags=["image"],
)
async def upload_images_blob(
task_id: str,
images_json: Optional[str] = Form(
default=None,
description="외부 이미지 URL 목록 (JSON 문자열)",
example=IMAGES_JSON_EXAMPLE,
),
files: Optional[list[UploadFile]] = File(
default=None, description="이미지 바이너리 파일 목록"
),
session: AsyncSession = Depends(get_session),
) -> ImageUploadResponse:
"""이미지 업로드 (URL + Azure Blob Storage)"""
# 1. 진입 검증
has_images_json = images_json is not None and images_json.strip() != ""
has_files = files is not None and len(files) > 0
if not has_images_json and not has_files:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="images_json 또는 files 중 하나는 반드시 제공해야 합니다.",
)
# 2. images_json 파싱
url_images: list[ImageUrlItem] = []
if has_images_json:
try:
parsed = json.loads(images_json)
if isinstance(parsed, list):
url_images = [ImageUrlItem(**item) for item in parsed if item]
except (json.JSONDecodeError, TypeError, ValueError) as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"images_json 파싱 오류: {str(e)}",
)
# 3. 유효한 파일만 필터링
valid_files: list[UploadFile] = []
skipped_files: list[str] = []
if has_files and files:
for f in files:
is_valid_ext = _is_valid_image_extension(f.filename)
is_not_empty = f.size is None or f.size > 0
is_real_file = f.filename and f.filename != "filename"
if f and is_real_file and is_valid_ext and is_not_empty:
valid_files.append(f)
else:
skipped_files.append(f.filename or "unknown")
if not url_images and not valid_files:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"유효한 이미지가 없습니다. 지원 확장자: {', '.join(ALLOWED_IMAGE_EXTENSIONS)}. 건너뛴 파일: {skipped_files}",
)
result_images: list[ImageUploadResultItem] = []
img_order = 0
# 1. URL 이미지 저장
for url_item in url_images:
img_name = url_item.name or _extract_image_name(url_item.url, img_order)
image = Image(
task_id=task_id,
img_name=img_name,
img_url=url_item.url,
img_order=img_order,
)
session.add(image)
await session.flush()
result_images.append(
ImageUploadResultItem(
id=image.id,
img_name=img_name,
img_url=url_item.url,
img_order=img_order,
source="url",
)
)
img_order += 1
# 2. 바이너리 파일을 Azure Blob Storage에 직접 업로드 (media 저장 없음)
if valid_files:
uploader = AzureBlobUploader(task_id=task_id)
for file in valid_files:
original_name = file.filename or "image"
ext = _get_file_extension(file.filename) # type: ignore[arg-type]
name_without_ext = (
original_name.rsplit(".", 1)[0]
if "." in original_name
else original_name
)
filename = f"{name_without_ext}_{img_order:03d}{ext}"
# 파일 내용 읽기
file_content = await file.read()
# Azure Blob Storage에 직접 업로드
upload_success = await uploader.upload_image_bytes(file_content, filename)
if upload_success:
blob_url = uploader.public_url
img_name = file.filename or filename
image = Image(
task_id=task_id,
img_name=img_name,
img_url=blob_url,
img_order=img_order,
)
session.add(image)
await session.flush()
result_images.append(
ImageUploadResultItem(
id=image.id,
img_name=img_name,
img_url=blob_url,
img_order=img_order,
source="blob",
)
)
img_order += 1
else:
skipped_files.append(filename)
saved_count = len(result_images)
await session.commit()
return ImageUploadResponse(
task_id=task_id,
total_count=len(result_images),
url_count=len(url_images),
file_count=len(valid_files) - len(skipped_files),
saved_count=saved_count,
images=result_images,
)
@@ -159,3 +159,61 @@ class ErrorResponse(BaseModel):
error_code: str = Field(..., description="에러 코드")
message: str = Field(..., description="에러 메시지")
detail: Optional[str] = Field(None, description="상세 에러 정보")
# =============================================================================
# Image Upload Schemas
# =============================================================================
class ImageUrlItem(BaseModel):
"""이미지 URL 아이템 스키마"""
url: str = Field(..., description="외부 이미지 URL")
name: Optional[str] = Field(None, description="이미지명 (없으면 URL에서 추출)")
class ImageUploadRequest(BaseModel):
"""이미지 업로드 요청 스키마 (JSON body 부분)
URL 이미지 목록을 전달합니다.
바이너리 파일은 multipart/form-data로 별도 전달됩니다.
"""
model_config = ConfigDict(
json_schema_extra={
"example": {
"images": [
{"url": "https://example.com/images/image_001.jpg"},
{"url": "https://example.com/images/image_002.jpg", "name": "외관"},
]
}
}
)
images: Optional[list[ImageUrlItem]] = Field(
None, description="외부 이미지 URL 목록"
)
class ImageUploadResultItem(BaseModel):
"""업로드된 이미지 결과 아이템"""
id: int = Field(..., description="이미지 ID")
img_name: str = Field(..., description="이미지명")
img_url: str = Field(..., description="이미지 URL")
img_order: int = Field(..., description="이미지 순서")
source: Literal["url", "file", "blob"] = Field(
..., description="이미지 소스 (url: 외부 URL, file: 로컬 서버, blob: Azure Blob)"
)
class ImageUploadResponse(BaseModel):
"""이미지 업로드 응답 스키마"""
task_id: str = Field(..., description="작업 고유 식별자")
total_count: int = Field(..., description="총 업로드된 이미지 개수")
url_count: int = Field(..., description="URL로 등록된 이미지 개수")
file_count: int = Field(..., description="파일로 업로드된 이미지 개수")
saved_count: int = Field(..., description="Image 테이블에 저장된 row 수")
images: list[ImageUploadResultItem] = Field(..., description="업로드된 이미지 목록")
+60
View File
@@ -0,0 +1,60 @@
"""
Home Worker 모듈
이미지 업로드 관련 백그라운드 작업을 처리합니다.
"""
from pathlib import Path
import aiofiles
from fastapi import UploadFile
from app.utils.upload_blob_as_request import AzureBlobUploader
MEDIA_ROOT = Path("media")
async def save_upload_file(file: UploadFile, save_path: Path) -> None:
"""업로드 파일을 지정된 경로에 저장"""
save_path.parent.mkdir(parents=True, exist_ok=True)
async with aiofiles.open(save_path, "wb") as f:
content = await file.read()
await f.write(content)
async def upload_image_to_blob(
task_id: str,
file: UploadFile,
filename: str,
save_dir: Path,
) -> tuple[bool, str, str]:
"""
이미지 파일을 media에 저장하고 Azure Blob Storage에 업로드합니다.
Args:
task_id: 작업 고유 식별자
file: 업로드할 파일 객체
filename: 저장될 파일명
save_dir: media 저장 디렉토리 경로
Returns:
tuple[bool, str, str]: (업로드 성공 여부, blob_url 또는 에러 메시지, media_path)
"""
save_path = save_dir / filename
media_path = str(save_path)
try:
# 1. media에 파일 저장
await save_upload_file(file, save_path)
# 2. Azure Blob Storage에 업로드
uploader = AzureBlobUploader(task_id=task_id)
upload_success = await uploader.upload_image(file_path=str(save_path))
if upload_success:
return True, uploader.public_url, media_path
else:
return False, f"Failed to upload {filename} to Blob", media_path
except Exception as e:
return False, str(e), media_path
-91
View File
@@ -1,91 +0,0 @@
import asyncio
from sqlalchemy import select
from app.database.session import get_worker_session
from app.home.schemas.home import GenerateRequest
from app.lyric.models import Lyric
from app.utils.chatgpt_prompt import ChatgptService
async def _save_lyric(task_id: str, project_id: int, lyric_prompt: str) -> int:
"""Lyric 레코드를 DB에 저장 (status=processing, lyric_result=null)"""
async with get_worker_session() as session:
lyric = Lyric(
task_id=task_id,
project_id=project_id,
status="processing",
lyric_prompt=lyric_prompt,
lyric_result=None,
)
session.add(lyric)
await session.commit()
await session.refresh(lyric)
print(f"Lyric saved: id={lyric.id}, task_id={task_id}, status=processing")
return lyric.id
async def _update_lyric_status(lyric_id: int, status: str, lyric_result: str | None = None) -> None:
"""Lyric 레코드의 status와 lyric_result를 업데이트"""
async with get_worker_session() as session:
result = await session.execute(select(Lyric).where(Lyric.id == lyric_id))
lyric = result.scalar_one_or_none()
if lyric:
lyric.status = status
if lyric_result is not None:
lyric.lyric_result = lyric_result
await session.commit()
print(f"Lyric updated: id={lyric_id}, status={status}")
async def lyric_task(
task_id: str,
project_id: int,
customer_name: str,
region: str,
detail_region_info: str,
language: str = "Korean",
) -> None:
"""가사 생성 작업: ChatGPT로 가사 생성 및 Lyric 테이블 저장/업데이트"""
service = ChatgptService(
customer_name=customer_name,
region=region,
detail_region_info=detail_region_info,
language=language,
)
# Lyric 레코드 저장 (status=processing, lyric_result=null)
lyric_prompt = service.build_lyrics_prompt()
lyric_id = await _save_lyric(task_id, project_id, lyric_prompt)
# GPT 호출
result = await service.generate(prompt=lyric_prompt)
print(f"GPT Response:\n{result}")
# 결과에 ERROR가 포함되어 있으면 status를 failed로 업데이트
if "ERROR:" in result:
await _update_lyric_status(lyric_id, "failed", lyric_result=result)
else:
await _update_lyric_status(lyric_id, "completed", lyric_result=result)
async def _task_process_async(request_body: GenerateRequest, task_id: str, project_id: int) -> None:
"""백그라운드 작업 처리 (async 버전)"""
customer_name = request_body.customer_name
region = request_body.region
detail_region_info = request_body.detail_region_info or ""
language = request_body.language
print(f"customer_name: {customer_name}")
print(f"region: {region}")
print(f"detail_region_info: {detail_region_info}")
print(f"language: {language}")
# 가사 생성 작업
await lyric_task(task_id, project_id, customer_name, region, detail_region_info, language)
def task_process(request_body: GenerateRequest, task_id: str, project_id: int) -> None:
"""백그라운드 작업 처리 함수 (sync wrapper)"""
asyncio.run(_task_process_async(request_body, task_id, project_id))
+44 -35
View File
@@ -32,7 +32,7 @@ from app.song.schemas.song_schema import (
PollingSongResponse,
SongListItem,
)
from app.song.worker.song_task import download_and_save_song
from app.song.worker.song_task import download_and_upload_song_by_suno_task_id
from app.utils.pagination import PaginatedResponse
from app.utils.suno import SunoService
@@ -182,7 +182,7 @@ async def generate_song(
summary="노래 생성 상태 조회",
description="""
Suno API를 통해 노래 생성 작업의 상태를 조회합니다.
SUCCESS 상태인 경우 백그라운드에서 MP3 파일을 다운로드하고 Song 테이블을 업데이트합니다.
SUCCESS 상태인 경우 백그라운드에서 MP3 파일을 다운로드하고 Azure Blob Storage에 업로드한 뒤 Song 테이블을 업데이트합니다.
## 경로 파라미터
- **suno_task_id**: 노래 생성 시 반환된 Suno API 작업 ID (필수)
@@ -208,7 +208,9 @@ GET /song/status/abc123...
## 참고
- 스트림 URL: 30-40초 내 생성
- 다운로드 URL: 2-3분 내 생성
- SUCCESS 시 백그라운드에서 MP3 다운로드 및 DB 업데이트 진행
- SUCCESS 시 백그라운드에서 MP3 다운로드 → Azure Blob Storage 업로드 → Song 테이블 업데이트 진행
- 저장 경로: Azure Blob Storage ({BASE_URL}/{task_id}/song/{store_name}.mp3)
- Song 테이블의 song_result_url에 Blob URL이 저장됩니다
""",
response_model=PollingSongResponse,
responses={
@@ -224,7 +226,8 @@ async def get_song_status(
"""suno_task_id로 노래 생성 작업의 상태를 조회합니다.
SUCCESS 상태인 경우 백그라운드에서 MP3 파일을 다운로드하고
Song 테이블의 status를 completed로, song_result_url을 업데이트합니다.
Azure Blob Storage에 업로드한 뒤 Song 테이블의 status를 completed로,
song_result_url을 Blob URL로 업데이트합니다.
"""
print(f"[get_song_status] START - suno_task_id: {suno_task_id}")
try:
@@ -235,12 +238,13 @@ async def get_song_status(
# SUCCESS 상태인 경우 백그라운드 태스크 실행
if parsed_response.status == "SUCCESS" and parsed_response.clips:
# 첫 번째 클립의 audioUrl 가져오기
# 첫 번째 클립의 audioUrl과 duration 가져오기
first_clip = parsed_response.clips[0]
audio_url = first_clip.audio_url
clip_duration = first_clip.duration
if audio_url:
# suno_task_id로 Song 조회하여 task_id 가져오기 (여러 개 있을 경우 가장 최근 것 선택)
# suno_task_id로 Song 조회하여 store_name 가져오기
song_result = await session.execute(
select(Song)
.where(Song.suno_task_id == suno_task_id)
@@ -249,8 +253,9 @@ async def get_song_status(
)
song = song_result.scalar_one_or_none()
if song:
# task_id로 Project 조회하여 store_name 가져오기
if song and song.status != "completed":
# 이미 완료된 경우 백그라운드 작업 중복 실행 방지
# project_id로 Project 조회하여 store_name 가져오기
project_result = await session.execute(
select(Project).where(Project.id == song.project_id)
)
@@ -258,14 +263,17 @@ async def get_song_status(
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}")
# 백그라운드 태스크로 MP3 다운로드 및 Blob 업로드, DB 업데이트 (suno_task_id 사용)
print(f"[get_song_status] Background task args - suno_task_id: {suno_task_id}, audio_url: {audio_url}, store_name: {store_name}, duration: {clip_duration}")
background_tasks.add_task(
download_and_save_song,
task_id=song.task_id,
download_and_upload_song_by_suno_task_id,
suno_task_id=suno_task_id,
audio_url=audio_url,
store_name=store_name,
duration=clip_duration,
)
elif song and song.status == "completed":
print(f"[get_song_status] SKIPPED - Song already completed, suno_task_id: {suno_task_id}")
print(f"[get_song_status] SUCCESS - suno_task_id: {suno_task_id}")
return parsed_response
@@ -286,34 +294,35 @@ async def get_song_status(
@router.get(
"/download/{task_id}",
summary="노래 다운로드 상태 조회",
summary="노래 생성 URL 조회",
description="""
task_id를 기반으로 Song 테이블의 상태를 polling하고,
completed인 경우 Project 정보와 노래 URL을 반환합니다.
task_id를 기반으로 Song 테이블의 상태를 조회하고,
completed인 경우 Project 정보와 노래 URL을 반환합니다.
## 경로 파라미터
- **task_id**: 프로젝트 task_id (필수)
## 경로 파라미터
- **task_id**: 프로젝트 task_id (필수)
## 반환 정보
- **success**: 조회 성공 여부
- **status**: 처리 상태 (processing, completed, failed)
- **message**: 응답 메시지
- **store_name**: 업체명
- **region**: 지역명
- **detail_region_info**: 상세 지역 정보
- **task_id**: 작업 고유 식별자
- **language**: 언어
- **song_result_url**: 노래 결과 URL (completed 시)
- **created_at**: 생성 일시
## 반환 정보
- **success**: 조회 성공 여부
- **status**: 처리 상태 (processing, completed, failed, not_found)
- **message**: 응답 메시지
- **store_name**: 업체명
- **region**: 지역명
- **detail_region_info**: 상세 지역 정보
- **task_id**: 작업 고유 식별자
- **language**: 언어
- **song_result_url**: 노래 결과 URL (completed 시, Azure Blob Storage URL)
- **created_at**: 생성 일시
## 사용 예시
```
GET /song/download/019123ab-cdef-7890-abcd-ef1234567890
```
## 사용 예시
```
GET /song/download/019123ab-cdef-7890-abcd-ef1234567890
```
## 참고
- processing 상태인 경우 song_result_url은 null입니다.
- completed 상태인 경우 Project 정보와 함께 song_result_url을 반환합니다.
## 참고
- processing 상태인 경우 song_result_url은 null입니다.
- 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={
+5
View File
@@ -100,6 +100,11 @@ class Song(Base):
comment="노래 결과 URL",
)
duration: Mapped[Optional[float]] = mapped_column(
nullable=True,
comment="노래 재생 시간 (초)",
)
language: Mapped[str] = mapped_column(
String(50),
nullable=False,
+236 -4
View File
@@ -14,6 +14,7 @@ from sqlalchemy import select
from app.database.session import AsyncSessionLocal
from app.song.models import Song
from app.utils.common import generate_task_id
from app.utils.upload_blob_as_request import AzureBlobUploader
from config import prj_settings
@@ -31,8 +32,8 @@ async def download_and_save_song(
"""
print(f"[download_and_save_song] START - task_id: {task_id}, store_name: {store_name}")
try:
# 저장 경로 생성: media/{날짜}/{uuid7}/{store_name}.mp3
today = date.today().isoformat()
# 저장 경로 생성: media/song/{날짜}/{uuid7}/{store_name}.mp3
today = date.today().strftime("%Y-%m-%d")
unique_id = await generate_task_id()
# 파일명에 사용할 수 없는 문자 제거
safe_store_name = "".join(
@@ -42,7 +43,7 @@ async def download_and_save_song(
file_name = f"{safe_store_name}.mp3"
# 절대 경로 생성
media_dir = Path("media") / today / unique_id
media_dir = Path("media") / "song" / today / unique_id
media_dir.mkdir(parents=True, exist_ok=True)
file_path = media_dir / file_name
print(f"[download_and_save_song] Directory created - path: {file_path}")
@@ -58,7 +59,7 @@ async def download_and_save_song(
print(f"[download_and_save_song] File saved - task_id: {task_id}, path: {file_path}")
# 프론트엔드에서 접근 가능한 URL 생성
relative_path = f"/media/{today}/{unique_id}/{file_name}"
relative_path = f"/media/song/{today}/{unique_id}/{file_name}"
base_url = f"http://{prj_settings.PROJECT_DOMAIN}"
file_url = f"{base_url}{relative_path}"
print(f"[download_and_save_song] URL generated - task_id: {task_id}, url: {file_url}")
@@ -99,3 +100,234 @@ async def download_and_save_song(
song.status = "failed"
await session.commit()
print(f"[download_and_save_song] FAILED - task_id: {task_id}, status updated to failed")
async def download_and_upload_song_to_blob(
task_id: str,
audio_url: str,
store_name: str,
) -> None:
"""백그라운드에서 노래를 다운로드하고 Azure Blob Storage에 업로드한 뒤 Song 테이블을 업데이트합니다.
Args:
task_id: 프로젝트 task_id
audio_url: 다운로드할 오디오 URL
store_name: 저장할 파일명에 사용할 업체명
"""
print(f"[download_and_upload_song_to_blob] START - task_id: {task_id}, store_name: {store_name}")
temp_file_path: Path | None = None
try:
# 파일명에 사용할 수 없는 문자 제거
safe_store_name = "".join(
c for c in store_name if c.isalnum() or c in (" ", "_", "-")
).strip()
safe_store_name = safe_store_name or "song"
file_name = f"{safe_store_name}.mp3"
# 임시 저장 경로 생성
temp_dir = Path("media") / "temp" / task_id
temp_dir.mkdir(parents=True, exist_ok=True)
temp_file_path = temp_dir / file_name
print(f"[download_and_upload_song_to_blob] Temp directory created - path: {temp_file_path}")
# 오디오 파일 다운로드
print(f"[download_and_upload_song_to_blob] Downloading audio - task_id: {task_id}, url: {audio_url}")
async with httpx.AsyncClient() as client:
response = await client.get(audio_url, timeout=60.0)
response.raise_for_status()
async with aiofiles.open(str(temp_file_path), "wb") as f:
await f.write(response.content)
print(f"[download_and_upload_song_to_blob] File downloaded - task_id: {task_id}, path: {temp_file_path}")
# Azure Blob Storage에 업로드
uploader = AzureBlobUploader(task_id=task_id)
upload_success = await uploader.upload_music(file_path=str(temp_file_path))
if not upload_success:
raise Exception("Azure Blob Storage 업로드 실패")
# SAS 토큰이 제외된 public_url 사용
blob_url = uploader.public_url
print(f"[download_and_upload_song_to_blob] Uploaded to Blob - task_id: {task_id}, url: {blob_url}")
# Song 테이블 업데이트 (새 세션 사용)
async with AsyncSessionLocal() as session:
# 여러 개 있을 경우 가장 최근 것 선택
result = await session.execute(
select(Song)
.where(Song.task_id == task_id)
.order_by(Song.created_at.desc())
.limit(1)
)
song = result.scalar_one_or_none()
if song:
song.status = "completed"
song.song_result_url = blob_url
await session.commit()
print(f"[download_and_upload_song_to_blob] SUCCESS - task_id: {task_id}, status: completed")
else:
print(f"[download_and_upload_song_to_blob] Song NOT FOUND in DB - task_id: {task_id}")
except Exception as e:
print(f"[download_and_upload_song_to_blob] EXCEPTION - task_id: {task_id}, error: {e}")
# 실패 시 Song 테이블 업데이트
async with AsyncSessionLocal() as session:
result = await session.execute(
select(Song)
.where(Song.task_id == task_id)
.order_by(Song.created_at.desc())
.limit(1)
)
song = result.scalar_one_or_none()
if song:
song.status = "failed"
await session.commit()
print(f"[download_and_upload_song_to_blob] FAILED - task_id: {task_id}, status updated to failed")
finally:
# 임시 파일 삭제
if temp_file_path and temp_file_path.exists():
try:
temp_file_path.unlink()
print(f"[download_and_upload_song_to_blob] Temp file deleted - path: {temp_file_path}")
except Exception as e:
print(f"[download_and_upload_song_to_blob] Failed to delete temp file: {e}")
# 임시 디렉토리 삭제 시도
temp_dir = Path("media") / "temp" / task_id
if temp_dir.exists():
try:
temp_dir.rmdir()
except Exception:
pass # 디렉토리가 비어있지 않으면 무시
async def download_and_upload_song_by_suno_task_id(
suno_task_id: str,
audio_url: str,
store_name: str,
duration: float | None = None,
) -> None:
"""suno_task_id로 Song을 조회하여 노래를 다운로드하고 Azure Blob Storage에 업로드한 뒤 Song 테이블을 업데이트합니다.
Args:
suno_task_id: Suno API 작업 ID
audio_url: 다운로드할 오디오 URL
store_name: 저장할 파일명에 사용할 업체명
duration: 노래 재생 시간 (초)
"""
print(f"[download_and_upload_song_by_suno_task_id] START - suno_task_id: {suno_task_id}, store_name: {store_name}, duration: {duration}")
temp_file_path: Path | None = None
task_id: str | None = None
try:
# suno_task_id로 Song 조회하여 task_id 가져오기
async with AsyncSessionLocal() as session:
result = await session.execute(
select(Song)
.where(Song.suno_task_id == suno_task_id)
.order_by(Song.created_at.desc())
.limit(1)
)
song = result.scalar_one_or_none()
if not song:
print(f"[download_and_upload_song_by_suno_task_id] Song NOT FOUND - suno_task_id: {suno_task_id}")
return
task_id = song.task_id
print(f"[download_and_upload_song_by_suno_task_id] Song found - suno_task_id: {suno_task_id}, task_id: {task_id}")
# 파일명에 사용할 수 없는 문자 제거
safe_store_name = "".join(
c for c in store_name if c.isalnum() or c in (" ", "_", "-")
).strip()
safe_store_name = safe_store_name or "song"
file_name = f"{safe_store_name}.mp3"
# 임시 저장 경로 생성
temp_dir = Path("media") / "temp" / task_id
temp_dir.mkdir(parents=True, exist_ok=True)
temp_file_path = temp_dir / file_name
print(f"[download_and_upload_song_by_suno_task_id] Temp directory created - path: {temp_file_path}")
# 오디오 파일 다운로드
print(f"[download_and_upload_song_by_suno_task_id] Downloading audio - suno_task_id: {suno_task_id}, url: {audio_url}")
async with httpx.AsyncClient() as client:
response = await client.get(audio_url, timeout=60.0)
response.raise_for_status()
async with aiofiles.open(str(temp_file_path), "wb") as f:
await f.write(response.content)
print(f"[download_and_upload_song_by_suno_task_id] File downloaded - suno_task_id: {suno_task_id}, path: {temp_file_path}")
# Azure Blob Storage에 업로드
uploader = AzureBlobUploader(task_id=task_id)
upload_success = await uploader.upload_music(file_path=str(temp_file_path))
if not upload_success:
raise Exception("Azure Blob Storage 업로드 실패")
# SAS 토큰이 제외된 public_url 사용
blob_url = uploader.public_url
print(f"[download_and_upload_song_by_suno_task_id] Uploaded to Blob - suno_task_id: {suno_task_id}, url: {blob_url}")
# Song 테이블 업데이트 (새 세션 사용)
async with AsyncSessionLocal() as session:
result = await session.execute(
select(Song)
.where(Song.suno_task_id == suno_task_id)
.order_by(Song.created_at.desc())
.limit(1)
)
song = result.scalar_one_or_none()
if song:
song.status = "completed"
song.song_result_url = blob_url
if duration is not None:
song.duration = duration
await session.commit()
print(f"[download_and_upload_song_by_suno_task_id] SUCCESS - suno_task_id: {suno_task_id}, status: completed, duration: {duration}")
else:
print(f"[download_and_upload_song_by_suno_task_id] Song NOT FOUND in DB - suno_task_id: {suno_task_id}")
except Exception as e:
print(f"[download_and_upload_song_by_suno_task_id] EXCEPTION - suno_task_id: {suno_task_id}, error: {e}")
# 실패 시 Song 테이블 업데이트
if task_id:
async with AsyncSessionLocal() as session:
result = await session.execute(
select(Song)
.where(Song.suno_task_id == suno_task_id)
.order_by(Song.created_at.desc())
.limit(1)
)
song = result.scalar_one_or_none()
if song:
song.status = "failed"
await session.commit()
print(f"[download_and_upload_song_by_suno_task_id] FAILED - suno_task_id: {suno_task_id}, status updated to failed")
finally:
# 임시 파일 삭제
if temp_file_path and temp_file_path.exists():
try:
temp_file_path.unlink()
print(f"[download_and_upload_song_by_suno_task_id] Temp file deleted - path: {temp_file_path}")
except Exception as e:
print(f"[download_and_upload_song_by_suno_task_id] Failed to delete temp file: {e}")
# 임시 디렉토리 삭제 시도
if task_id:
temp_dir = Path("media") / "temp" / task_id
if temp_dir.exists():
try:
temp_dir.rmdir()
except Exception:
pass # 디렉토리가 비어있지 않으면 무시
+101 -2
View File
@@ -25,10 +25,15 @@ response = creatomate.make_creatomate_call(template_id, modifications)
"""
import copy
from typing import Literal
import httpx
from config import apikey_settings
from config import apikey_settings, creatomate_settings
# Orientation 타입 정의
OrientationType = Literal["horizontal", "vertical"]
class CreatomateService:
@@ -36,13 +41,40 @@ class CreatomateService:
BASE_URL = "https://api.creatomate.com"
def __init__(self, api_key: str | None = None):
# 템플릿 설정 (config에서 가져옴)
TEMPLATE_CONFIG = {
"horizontal": {
"template_id": creatomate_settings.TEMPLATE_ID_HORIZONTAL,
"duration": creatomate_settings.TEMPLATE_DURATION_HORIZONTAL,
},
"vertical": {
"template_id": creatomate_settings.TEMPLATE_ID_VERTICAL,
"duration": creatomate_settings.TEMPLATE_DURATION_VERTICAL,
},
}
def __init__(
self,
api_key: str | None = None,
orientation: OrientationType = "vertical",
target_duration: float | None = None,
):
"""
Args:
api_key: Creatomate API 키 (Bearer token으로 사용)
None일 경우 config에서 자동으로 가져옴
orientation: 영상 방향 ("horizontal" 또는 "vertical", 기본값: "vertical")
target_duration: 목표 영상 길이 (초)
None일 경우 orientation에 해당하는 기본값 사용
"""
self.api_key = api_key or apikey_settings.CREATOMATE_API_KEY
self.orientation = orientation
# orientation에 따른 템플릿 설정 가져오기
config = self.TEMPLATE_CONFIG.get(orientation, self.TEMPLATE_CONFIG["vertical"])
self.template_id = config["template_id"]
self.target_duration = target_duration if target_duration is not None else config["duration"]
self.headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.api_key}",
@@ -62,6 +94,14 @@ class CreatomateService:
response.raise_for_status()
return response.json()
async def get_one_template_data_async(self, template_id: str) -> dict:
"""특정 템플릿 ID로 템플릿 정보를 비동기로 조회합니다."""
url = f"{self.BASE_URL}/v1/templates/{template_id}"
async with httpx.AsyncClient() as client:
response = await client.get(url, headers=self.headers, timeout=30.0)
response.raise_for_status()
return response.json()
def parse_template_component_name(self, template_source: list) -> dict:
"""템플릿 정보를 파싱하여 리소스 이름을 추출합니다."""
@@ -209,6 +249,65 @@ class CreatomateService:
response.raise_for_status()
return response.json()
async def make_creatomate_custom_call_async(self, source: dict):
"""템플릿 없이 Creatomate에 비동기로 커스텀 렌더링 요청을 보냅니다.
Note:
response에 요청 정보가 있으니 폴링 필요
"""
url = f"{self.BASE_URL}/v2/renders"
async with httpx.AsyncClient() as client:
response = await client.post(url, json=source, headers=self.headers, timeout=60.0)
response.raise_for_status()
return response.json()
def get_render_status(self, render_id: str) -> dict:
"""렌더링 작업의 상태를 조회합니다.
Args:
render_id: Creatomate 렌더 ID
Returns:
렌더링 상태 정보
Note:
상태 값:
- planned: 예약됨
- waiting: 대기 중
- transcribing: 트랜스크립션 중
- rendering: 렌더링 중
- succeeded: 성공
- failed: 실패
"""
url = f"{self.BASE_URL}/v1/renders/{render_id}"
response = httpx.get(url, headers=self.headers, timeout=30.0)
response.raise_for_status()
return response.json()
async def get_render_status_async(self, render_id: str) -> dict:
"""렌더링 작업의 상태를 비동기로 조회합니다.
Args:
render_id: Creatomate 렌더 ID
Returns:
렌더링 상태 정보
Note:
상태 값:
- planned: 예약됨
- waiting: 대기 중
- transcribing: 트랜스크립션 중
- rendering: 렌더링 중
- succeeded: 성공
- failed: 실패
"""
url = f"{self.BASE_URL}/v1/renders/{render_id}"
async with httpx.AsyncClient() as client:
response = await client.get(url, headers=self.headers, timeout=30.0)
response.raise_for_status()
return response.json()
def calc_scene_duration(self, template: dict) -> float:
"""템플릿의 전체 장면 duration을 계산합니다."""
total_template_duration = 0.0
+345 -51
View File
@@ -1,64 +1,358 @@
import requests
"""
Azure Blob Storage 업로드 유틸리티
Azure Blob Storage에 파일을 업로드하는 클래스를 제공합니다.
파일 경로 또는 바이트 데이터를 직접 업로드할 수 있습니다.
URL 경로 형식:
- 음악: {BASE_URL}/{task_id}/song/{파일명}
- 영상: {BASE_URL}/{task_id}/video/{파일명}
- 이미지: {BASE_URL}/{task_id}/image/{파일명}
사용 예시:
from app.utils.upload_blob_as_request import AzureBlobUploader
uploader = AzureBlobUploader(task_id="task-123")
# 파일 경로로 업로드
success = await uploader.upload_music(file_path="my_song.mp3")
success = await uploader.upload_video(file_path="my_video.mp4")
success = await uploader.upload_image(file_path="my_image.png")
# 바이트 데이터로 직접 업로드 (media 저장 없이)
success = await uploader.upload_music_bytes(audio_bytes, "my_song") # .mp3 자동 추가
success = await uploader.upload_video_bytes(video_bytes, "my_video") # .mp4 자동 추가
success = await uploader.upload_image_bytes(image_bytes, "my_image.png")
print(uploader.public_url) # 마지막 업로드의 공개 URL
"""
from pathlib import Path
SAS_TOKEN = "sp=racwdl&st=2025-12-01T00:13:29Z&se=2026-07-31T08:28:29Z&spr=https&sv=2024-11-04&sr=c&sig=7fE2ozVBPu3Gq43%2FZDxEYdEcPLDXyNVfTf16IBasmVQ%3D"
import aiofiles
import httpx
def upload_music_to_azure_blob(file_path = "스테이 머뭄_1.mp3", url = "https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/dev-user-idx/dev-task-idx/test_my_mp3_should_now_exist.mp3"):
access_url = f"{url}?{SAS_TOKEN}"
headers = {
"Content-Type": "audio/mpeg",
"x-ms-blob-type": "BlockBlob"
}
with open(file_path, "rb") as file:
response = requests.put(access_url, data=file, headers=headers)
if response.status_code in [200, 201]:
print(f"Success Status Code: {response.status_code}")
else:
print(f"Failed Status Code: {response.status_code}")
print(f"Response: {response.text}")
def upload_video_to_azure_blob(file_path = "스테이 머뭄.mp4", url = "https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/dev-user-idx/dev-task-idx/test_my_mp3_should_now_exist.mp4"):
access_url = f"{url}?{SAS_TOKEN}"
headers = {
"Content-Type": "video/mp4",
"x-ms-blob-type": "BlockBlob"
}
with open(file_path, "rb") as file:
response = requests.put(access_url, data=file, headers=headers)
if response.status_code in [200, 201]:
print(f"Success Status Code: {response.status_code}")
else:
print(f"Failed Status Code: {response.status_code}")
print(f"Response: {response.text}")
from config import azure_blob_settings
def upload_image_to_azure_blob(file_path = "스테이 머뭄.png", url = "https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/dev-user-idx/dev-task-idx/test_my_mp3_should_now_exist.png"):
access_url = f"{url}?{SAS_TOKEN}"
extension = Path(file_path).suffix.lower()
content_types = {
class AzureBlobUploader:
"""Azure Blob Storage 업로드 클래스
Azure Blob Storage에 음악, 영상, 이미지 파일을 업로드합니다.
URL 형식: {BASE_URL}/{task_id}/{category}/{file_name}?{SAS_TOKEN}
카테고리별 경로:
- 음악: {task_id}/song/{file_name}
- 영상: {task_id}/video/{file_name}
- 이미지: {task_id}/image/{file_name}
Attributes:
task_id: 작업 고유 식별자
"""
# Content-Type 매핑
IMAGE_CONTENT_TYPES = {
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".gif": "image/gif",
".webp": "image/webp",
".bmp": "image/bmp"
".bmp": "image/bmp",
}
content_type = content_types.get(extension, "image/jpeg")
headers = {
"Content-Type": content_type,
"x-ms-blob-type": "BlockBlob"
}
with open(file_path, "rb") as file:
response = requests.put(access_url, data=file, headers=headers)
if response.status_code in [200, 201]:
print(f"Success Status Code: {response.status_code}")
else:
print(f"Failed Status Code: {response.status_code}")
print(f"Response: {response.text}")
upload_video_to_azure_blob()
def __init__(self, task_id: str):
"""AzureBlobUploader 초기화
upload_image_to_azure_blob()
Args:
task_id: 작업 고유 식별자
"""
self._task_id = task_id
self._base_url = azure_blob_settings.AZURE_BLOB_BASE_URL
self._sas_token = azure_blob_settings.AZURE_BLOB_SAS_TOKEN
self._last_public_url: str = ""
@property
def task_id(self) -> str:
"""작업 고유 식별자"""
return self._task_id
@property
def public_url(self) -> str:
"""마지막 업로드의 공개 URL (SAS 토큰 제외)"""
return self._last_public_url
def _build_upload_url(self, category: str, file_name: str) -> str:
"""업로드 URL 생성 (SAS 토큰 포함)"""
# SAS 토큰 앞뒤의 ?, ', " 제거
sas_token = self._sas_token.strip("?'\"")
return f"{self._base_url}/{self._task_id}/{category}/{file_name}?{sas_token}"
def _build_public_url(self, category: str, file_name: str) -> str:
"""공개 URL 생성 (SAS 토큰 제외)"""
return f"{self._base_url}/{self._task_id}/{category}/{file_name}"
async def _upload_file(
self,
file_path: str,
category: str,
content_type: str,
timeout: float,
log_prefix: str,
) -> bool:
"""파일을 Azure Blob Storage에 업로드하는 내부 메서드
Args:
file_path: 업로드할 파일 경로
category: 카테고리 (song, video, image)
content_type: Content-Type 헤더 값
timeout: 요청 타임아웃 (초)
log_prefix: 로그 접두사
Returns:
bool: 업로드 성공 여부
"""
# 파일 경로에서 파일명 추출
file_name = Path(file_path).name
upload_url = self._build_upload_url(category, file_name)
self._last_public_url = self._build_public_url(category, file_name)
print(f"[{log_prefix}] Upload URL (without SAS): {self._last_public_url}")
headers = {"Content-Type": content_type, "x-ms-blob-type": "BlockBlob"}
async with aiofiles.open(file_path, "rb") as file:
file_content = await file.read()
async with httpx.AsyncClient() as client:
response = await client.put(
upload_url, content=file_content, headers=headers, timeout=timeout
)
if response.status_code in [200, 201]:
print(f"[{log_prefix}] Success - Status Code: {response.status_code}")
print(f"[{log_prefix}] Public URL: {self._last_public_url}")
return True
else:
print(f"[{log_prefix}] Failed - Status Code: {response.status_code}")
print(f"[{log_prefix}] Response: {response.text}")
return False
async def upload_music(self, file_path: str) -> bool:
"""음악 파일을 Azure Blob Storage에 업로드합니다.
URL 경로: {task_id}/song/{파일명}
Args:
file_path: 업로드할 파일 경로
Returns:
bool: 업로드 성공 여부
Example:
uploader = AzureBlobUploader(task_id="task-123")
success = await uploader.upload_music(file_path="my_song.mp3")
print(uploader.public_url) # {BASE_URL}/task-123/song/my_song.mp3
"""
return await self._upload_file(
file_path=file_path,
category="song",
content_type="audio/mpeg",
timeout=120.0,
log_prefix="upload_music",
)
async def upload_music_bytes(self, file_content: bytes, file_name: str) -> bool:
"""음악 바이트 데이터를 Azure Blob Storage에 직접 업로드합니다.
URL 경로: {task_id}/song/{파일명}
Args:
file_content: 업로드할 파일 바이트 데이터
file_name: 저장할 파일명 (확장자가 없으면 .mp3 추가)
Returns:
bool: 업로드 성공 여부
Example:
uploader = AzureBlobUploader(task_id="task-123")
success = await uploader.upload_music_bytes(audio_bytes, "my_song")
print(uploader.public_url) # {BASE_URL}/task-123/song/my_song.mp3
"""
# 확장자가 없으면 .mp3 추가
if not Path(file_name).suffix:
file_name = f"{file_name}.mp3"
upload_url = self._build_upload_url("song", file_name)
self._last_public_url = self._build_public_url("song", file_name)
print(f"[upload_music_bytes] Upload URL (without SAS): {self._last_public_url}")
headers = {"Content-Type": "audio/mpeg", "x-ms-blob-type": "BlockBlob"}
async with httpx.AsyncClient() as client:
response = await client.put(
upload_url, content=file_content, headers=headers, timeout=120.0
)
if response.status_code in [200, 201]:
print(f"[upload_music_bytes] Success - Status Code: {response.status_code}")
print(f"[upload_music_bytes] Public URL: {self._last_public_url}")
return True
else:
print(f"[upload_music_bytes] Failed - Status Code: {response.status_code}")
print(f"[upload_music_bytes] Response: {response.text}")
return False
async def upload_video(self, file_path: str) -> bool:
"""영상 파일을 Azure Blob Storage에 업로드합니다.
URL 경로: {task_id}/video/{파일명}
Args:
file_path: 업로드할 파일 경로
Returns:
bool: 업로드 성공 여부
Example:
uploader = AzureBlobUploader(task_id="task-123")
success = await uploader.upload_video(file_path="my_video.mp4")
print(uploader.public_url) # {BASE_URL}/task-123/video/my_video.mp4
"""
return await self._upload_file(
file_path=file_path,
category="video",
content_type="video/mp4",
timeout=180.0,
log_prefix="upload_video",
)
async def upload_video_bytes(self, file_content: bytes, file_name: str) -> bool:
"""영상 바이트 데이터를 Azure Blob Storage에 직접 업로드합니다.
URL 경로: {task_id}/video/{파일명}
Args:
file_content: 업로드할 파일 바이트 데이터
file_name: 저장할 파일명 (확장자가 없으면 .mp4 추가)
Returns:
bool: 업로드 성공 여부
Example:
uploader = AzureBlobUploader(task_id="task-123")
success = await uploader.upload_video_bytes(video_bytes, "my_video")
print(uploader.public_url) # {BASE_URL}/task-123/video/my_video.mp4
"""
# 확장자가 없으면 .mp4 추가
if not Path(file_name).suffix:
file_name = f"{file_name}.mp4"
upload_url = self._build_upload_url("video", file_name)
self._last_public_url = self._build_public_url("video", file_name)
print(f"[upload_video_bytes] Upload URL (without SAS): {self._last_public_url}")
headers = {"Content-Type": "video/mp4", "x-ms-blob-type": "BlockBlob"}
async with httpx.AsyncClient() as client:
response = await client.put(
upload_url, content=file_content, headers=headers, timeout=180.0
)
if response.status_code in [200, 201]:
print(f"[upload_video_bytes] Success - Status Code: {response.status_code}")
print(f"[upload_video_bytes] Public URL: {self._last_public_url}")
return True
else:
print(f"[upload_video_bytes] Failed - Status Code: {response.status_code}")
print(f"[upload_video_bytes] Response: {response.text}")
return False
async def upload_image(self, file_path: str) -> bool:
"""이미지 파일을 Azure Blob Storage에 업로드합니다.
URL 경로: {task_id}/image/{파일명}
Args:
file_path: 업로드할 파일 경로
Returns:
bool: 업로드 성공 여부
Example:
uploader = AzureBlobUploader(task_id="task-123")
success = await uploader.upload_image(file_path="my_image.png")
print(uploader.public_url) # {BASE_URL}/task-123/image/my_image.png
"""
extension = Path(file_path).suffix.lower()
content_type = self.IMAGE_CONTENT_TYPES.get(extension, "image/jpeg")
return await self._upload_file(
file_path=file_path,
category="image",
content_type=content_type,
timeout=60.0,
log_prefix="upload_image",
)
async def upload_image_bytes(self, file_content: bytes, file_name: str) -> bool:
"""이미지 바이트 데이터를 Azure Blob Storage에 직접 업로드합니다.
URL 경로: {task_id}/image/{파일명}
Args:
file_content: 업로드할 파일 바이트 데이터
file_name: 저장할 파일명
Returns:
bool: 업로드 성공 여부
Example:
uploader = AzureBlobUploader(task_id="task-123")
with open("my_image.png", "rb") as f:
content = f.read()
success = await uploader.upload_image_bytes(content, "my_image.png")
print(uploader.public_url) # {BASE_URL}/task-123/image/my_image.png
"""
extension = Path(file_name).suffix.lower()
content_type = self.IMAGE_CONTENT_TYPES.get(extension, "image/jpeg")
upload_url = self._build_upload_url("image", file_name)
self._last_public_url = self._build_public_url("image", file_name)
print(f"[upload_image_bytes] Upload URL (without SAS): {self._last_public_url}")
headers = {"Content-Type": content_type, "x-ms-blob-type": "BlockBlob"}
async with httpx.AsyncClient() as client:
response = await client.put(
upload_url, content=file_content, headers=headers, timeout=60.0
)
if response.status_code in [200, 201]:
print(f"[upload_image_bytes] Success - Status Code: {response.status_code}")
print(f"[upload_image_bytes] Public URL: {self._last_public_url}")
return True
else:
print(f"[upload_image_bytes] Failed - Status Code: {response.status_code}")
print(f"[upload_image_bytes] Response: {response.text}")
return False
# 사용 예시:
# import asyncio
#
# async def main():
# uploader = AzureBlobUploader(task_id="task-123")
#
# # 음악 업로드 -> {BASE_URL}/task-123/song/my_song.mp3
# await uploader.upload_music("my_song.mp3")
# print(uploader.public_url)
#
# # 영상 업로드 -> {BASE_URL}/task-123/video/my_video.mp4
# await uploader.upload_video("my_video.mp4")
# print(uploader.public_url)
#
# # 이미지 업로드 -> {BASE_URL}/task-123/image/my_image.png
# await uploader.upload_image("my_image.png")
# print(uploader.public_url)
#
# asyncio.run(main())
+594 -87
View File
@@ -1,108 +1,615 @@
"""
Video API Endpoints (Test)
Video API Router
프론트엔드 개발을 위한 테스트용 엔드포인트입니다.
이 모듈은 Creatomate API를 통한 영상 생성 관련 API 엔드포인트를 정의합니다.
엔드포인트 목록:
- POST /video/generate/{task_id}: 영상 생성 요청 (task_id로 Project/Lyric/Song 연결)
- GET /video/status/{creatomate_render_id}: Creatomate API 영상 생성 상태 조회
- GET /video/download/{task_id}: 영상 다운로드 상태 조회 (DB polling)
- GET /videos/: 완료된 영상 목록 조회 (페이지네이션)
사용 예시:
from app.video.api.routers.v1.video import router
app.include_router(router, prefix="/api/v1")
"""
from datetime import datetime, timedelta
from typing import Optional
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.session import get_session
from app.dependencies.pagination import (
PaginationParams,
get_pagination_params,
)
from app.home.models import Project
from app.lyric.models import Lyric
from app.song.models import Song
from app.video.models import Video
from app.video.schemas.video_schema import (
DownloadVideoResponse,
GenerateVideoRequest,
GenerateVideoResponse,
PollingVideoResponse,
VideoListItem,
VideoRenderData,
)
from app.video.worker.video_task import download_and_upload_video_to_blob
from app.utils.creatomate import CreatomateService
from app.utils.pagination import PaginatedResponse
from fastapi import APIRouter
from pydantic import BaseModel, Field
router = APIRouter(prefix="/video", tags=["video"])
# =============================================================================
# Schemas
# =============================================================================
class VideoGenerateResponse(BaseModel):
"""영상 생성 응답 스키마"""
success: bool = Field(..., description="성공 여부")
task_id: str = Field(..., description="작업 고유 식별자")
message: str = Field(..., description="응답 메시지")
error_message: Optional[str] = Field(None, description="에러 메시지")
class VideoStatusResponse(BaseModel):
"""영상 상태 조회 응답 스키마"""
task_id: str = Field(..., description="작업 고유 식별자")
status: str = Field(..., description="처리 상태 (processing, completed, failed)")
video_url: Optional[str] = Field(None, description="영상 URL")
class VideoItem(BaseModel):
"""영상 아이템 스키마"""
task_id: str = Field(..., description="작업 고유 식별자")
video_url: str = Field(..., description="영상 URL")
created_at: datetime = Field(..., description="생성 일시")
class VideoListResponse(BaseModel):
"""영상 목록 응답 스키마"""
videos: list[VideoItem] = Field(..., description="영상 목록")
total: int = Field(..., description="전체 개수")
# =============================================================================
# Test Endpoints
# =============================================================================
TEST_VIDEO_URL = "https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/dev-user-idx/dev-task-idx/1a584e86-6a74-417d-8cff-270ef60c8646.mp4"
@router.post(
"/generate/{task_id}",
summary="영상 생성 요청 (테스트)",
response_model=VideoGenerateResponse,
summary="영상 생성 요청",
description="""
Creatomate API를 통해 영상 생성을 요청합니다.
## 경로 파라미터
- **task_id**: Project/Lyric/Song의 task_id (필수) - 연관된 프로젝트, 가사, 노래를 조회하는 데 사용
## 요청 필드
- **orientation**: 영상 방향 (horizontal: 가로형, vertical: 세로형, 기본값: vertical) - 선택
- **image_urls**: 영상에 사용할 이미지 URL 목록 (필수)
- **lyrics**: 영상에 표시할 가사 (필수)
- **music_url**: 배경 음악 URL (필수)
## 반환 정보
- **success**: 요청 성공 여부
- **task_id**: 내부 작업 ID (Project task_id)
- **creatomate_render_id**: Creatomate 렌더 ID (상태 조회에 사용)
- **message**: 응답 메시지
## 사용 예시
```
POST /video/generate/019123ab-cdef-7890-abcd-ef1234567890
{
"image_urls": [
"https://naverbooking-phinf.pstatic.net/20240514_189/1715688030436xT14o_JPEG/1.jpg",
"https://naverbooking-phinf.pstatic.net/20240514_48/1715688030574wTtQd_JPEG/2.jpg",
"https://naverbooking-phinf.pstatic.net/20240514_92/17156880307484bvpH_JPEG/3.jpg",
"https://naverbooking-phinf.pstatic.net/20240514_7/1715688031000y8Y5q_JPEG/4.jpg",
"https://naverbooking-phinf.pstatic.net/20240514_259/17156880311809wCnY_JPEG/5.jpg",
"https://naverbooking-phinf.pstatic.net/20240514_64/1715688031601oGNsV_JPEG/6.jpg",
"https://naverbooking-phinf.pstatic.net/20240514_175/1715688031657oXc7l_JPEG/7.jpg",
"https://naverbooking-phinf.pstatic.net/20240514_192/1715688031798MbFDj_JPEG/8.jpg",
"https://naverbooking-phinf.pstatic.net/20240514_205/17156880318681JLwX_JPEG/9.jpg",
"https://naverbooking-phinf.pstatic.net/20240514_142/1715688031946hhxHz_JPEG/10.jpg"
],
"lyrics": "가사 내용...",
"music_url": "https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/0694e2d8-7ae2-730c-8000-308aacaa582d/song/스테이 머뭄.mp3"
}
```
## 가로형 영상 생성 예시
```
POST /video/generate/019123ab-cdef-7890-abcd-ef1234567890
{
"orientation": "horizontal",
"image_urls": [...],
"lyrics": "가사 내용...",
"music_url": "https://..."
}
```
## 참고
- creatomate_render_id를 사용하여 /status/{creatomate_render_id} 엔드포인트에서 생성 상태를 확인할 수 있습니다.
- Video 테이블에 데이터가 저장되며, project_id, lyric_id, song_id가 자동으로 연결됩니다.
""",
response_model=GenerateVideoResponse,
responses={
200: {"description": "영상 생성 요청 성공"},
404: {"description": "Project, Lyric 또는 Song을 찾을 수 없음"},
500: {"description": "영상 생성 요청 실패"},
},
)
async def generate_video(task_id: str) -> VideoGenerateResponse:
"""영상 생성 요청 테스트 엔드포인트"""
return VideoGenerateResponse(
success=True,
task_id=task_id,
message="영상 생성 요청 성공",
error_message=None,
)
async def generate_video(
task_id: str,
request_body: GenerateVideoRequest,
session: AsyncSession = Depends(get_session),
) -> GenerateVideoResponse:
"""Creatomate API를 통해 영상을 생성합니다.
1. task_id로 Project, Lyric, Song 조회
2. Video 테이블에 초기 데이터 저장 (status: processing)
3. Creatomate API 호출 (orientation에 따른 템플릿 자동 선택)
4. creatomate_render_id 업데이트 후 응답 반환
"""
print(f"[generate_video] START - task_id: {task_id}, orientation: {request_body.orientation}")
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_video] Project NOT FOUND - task_id: {task_id}")
raise HTTPException(
status_code=404,
detail=f"task_id '{task_id}'에 해당하는 Project를 찾을 수 없습니다.",
)
print(f"[generate_video] 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_video] Lyric NOT FOUND - task_id: {task_id}")
raise HTTPException(
status_code=404,
detail=f"task_id '{task_id}'에 해당하는 Lyric을 찾을 수 없습니다.",
)
print(f"[generate_video] Lyric found - lyric_id: {lyric.id}, task_id: {task_id}")
# 3. 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()
if not song:
print(f"[generate_video] Song NOT FOUND - task_id: {task_id}")
raise HTTPException(
status_code=404,
detail=f"task_id '{task_id}'에 해당하는 Song을 찾을 수 없습니다.",
)
print(f"[generate_video] Song found - song_id: {song.id}, task_id: {task_id}, duration: {song.duration}")
# 4. Video 테이블에 초기 데이터 저장
video = Video(
project_id=project.id,
lyric_id=lyric.id,
song_id=song.id,
task_id=task_id,
creatomate_render_id=None,
status="processing",
)
session.add(video)
await session.flush() # ID 생성을 위해 flush
print(f"[generate_video] Video saved (processing) - task_id: {task_id}")
# 5. Creatomate API 호출 (POC 패턴 적용)
print(f"[generate_video] Creatomate API generation started - task_id: {task_id}")
# orientation에 따른 템플릿 선택, duration은 Song에서 가져옴 (없으면 config 기본값 사용)
creatomate_service = CreatomateService(
orientation=request_body.orientation,
target_duration=song.duration, # Song의 duration 사용 (None이면 config 기본값)
)
print(f"[generate_video] Using template_id: {creatomate_service.template_id}, duration: {creatomate_service.target_duration} (song duration: {song.duration})")
# 5-1. 템플릿 조회 (비동기, CreatomateService에서 orientation에 맞는 template_id 사용)
template = await creatomate_service.get_one_template_data_async(creatomate_service.template_id)
print(f"[generate_video] Template fetched - task_id: {task_id}")
# 5-2. elements에서 리소스 매핑 생성
modifications = creatomate_service.elements_connect_resource_blackbox(
elements=template["source"]["elements"],
image_url_list=request_body.image_urls,
lyric=request_body.lyrics,
music_url=request_body.music_url,
)
print(f"[generate_video] Modifications created - task_id: {task_id}")
# 5-3. elements 수정
new_elements = creatomate_service.modify_element(
template["source"]["elements"],
modifications,
)
template["source"]["elements"] = new_elements
print(f"[generate_video] Elements modified - task_id: {task_id}")
# 5-4. duration 확장 (target_duration: 영상 길이)
final_template = creatomate_service.extend_template_duration(
template,
creatomate_service.target_duration,
)
print(f"[generate_video] Duration extended to {creatomate_service.target_duration}s - task_id: {task_id}")
# 5-5. 커스텀 렌더링 요청 (비동기)
render_response = await creatomate_service.make_creatomate_custom_call_async(
final_template["source"],
)
print(f"[generate_video] Creatomate API response - task_id: {task_id}, response: {render_response}")
# 렌더 ID 추출 (응답이 리스트인 경우 첫 번째 항목 사용)
if isinstance(render_response, list) and len(render_response) > 0:
creatomate_render_id = render_response[0].get("id")
elif isinstance(render_response, dict):
creatomate_render_id = render_response.get("id")
else:
creatomate_render_id = None
# 6. creatomate_render_id 업데이트
video.creatomate_render_id = creatomate_render_id
await session.commit()
print(f"[generate_video] SUCCESS - task_id: {task_id}, creatomate_render_id: {creatomate_render_id}")
return GenerateVideoResponse(
success=True,
task_id=task_id,
creatomate_render_id=creatomate_render_id,
message="영상 생성 요청이 접수되었습니다. creatomate_render_id로 상태를 조회하세요.",
error_message=None,
)
except HTTPException:
raise
except Exception as e:
print(f"[generate_video] EXCEPTION - task_id: {task_id}, error: {e}")
await session.rollback()
return GenerateVideoResponse(
success=False,
task_id=task_id,
creatomate_render_id=None,
message="영상 생성 요청에 실패했습니다.",
error_message=str(e),
)
@router.get(
"/status/{task_id}",
summary="영상 상태 조회 (테스트)",
response_model=VideoStatusResponse,
"/status/{creatomate_render_id}",
summary="영상 생성 상태 조회",
description="""
Creatomate API를 통해 영상 생성 작업의 상태를 조회합니다.
succeeded 상태인 경우 백그라운드에서 MP4 파일을 다운로드하고 Video 테이블을 업데이트합니다.
## 경로 파라미터
- **creatomate_render_id**: 영상 생성 시 반환된 Creatomate 렌더 ID (필수)
## 반환 정보
- **success**: 조회 성공 여부
- **status**: 작업 상태 (planned, waiting, rendering, succeeded, failed)
- **message**: 상태 메시지
- **render_data**: 렌더링 결과 데이터 (완료 시)
- **raw_response**: Creatomate API 원본 응답
## 사용 예시
```
GET /video/status/render-id-123...
```
## 상태 값
- **planned**: 예약됨
- **waiting**: 대기 중
- **transcribing**: 트랜스크립션 중
- **rendering**: 렌더링 중
- **succeeded**: 성공
- **failed**: 실패
## 참고
- succeeded 시 백그라운드에서 MP4 다운로드 및 DB 업데이트 진행
""",
response_model=PollingVideoResponse,
responses={
200: {"description": "상태 조회 성공"},
500: {"description": "상태 조회 실패"},
},
)
async def get_video_status(task_id: str) -> VideoStatusResponse:
"""영상 상태 조회 테스트 엔드포인트"""
return VideoStatusResponse(
task_id=task_id,
status="completed",
video_url=TEST_VIDEO_URL,
)
async def get_video_status(
creatomate_render_id: str,
background_tasks: BackgroundTasks,
session: AsyncSession = Depends(get_session),
) -> PollingVideoResponse:
"""creatomate_render_id로 영상 생성 작업의 상태를 조회합니다.
succeeded 상태인 경우 백그라운드에서 MP4 파일을 다운로드하고
Video 테이블의 status를 completed로, result_movie_url을 업데이트합니다.
"""
print(f"[get_video_status] START - creatomate_render_id: {creatomate_render_id}")
try:
creatomate_service = CreatomateService()
result = await creatomate_service.get_render_status_async(creatomate_render_id)
print(f"[get_video_status] Creatomate API response - creatomate_render_id: {creatomate_render_id}, status: {result.get('status')}")
status = result.get("status", "unknown")
video_url = result.get("url")
# 상태별 메시지 설정
status_messages = {
"planned": "영상 생성이 예약되었습니다.",
"waiting": "영상 생성 대기 중입니다.",
"transcribing": "트랜스크립션 진행 중입니다.",
"rendering": "영상을 렌더링하고 있습니다.",
"succeeded": "영상 생성이 완료되었습니다.",
"failed": "영상 생성에 실패했습니다.",
}
message = status_messages.get(status, f"상태: {status}")
# succeeded 상태인 경우 백그라운드 태스크 실행
if status == "succeeded" and video_url:
# creatomate_render_id로 Video 조회하여 task_id 가져오기
video_result = await session.execute(
select(Video)
.where(Video.creatomate_render_id == creatomate_render_id)
.order_by(Video.created_at.desc())
.limit(1)
)
video = video_result.scalar_one_or_none()
if video and video.status != "completed":
# 이미 완료된 경우 백그라운드 작업 중복 실행 방지
# task_id로 Project 조회하여 store_name 가져오기
project_result = await session.execute(
select(Project).where(Project.id == video.project_id)
)
project = project_result.scalar_one_or_none()
store_name = project.store_name if project else "video"
# 백그라운드 태스크로 MP4 다운로드 → Blob 업로드 → DB 업데이트 → 임시 파일 삭제
print(f"[get_video_status] Background task args - task_id: {video.task_id}, video_url: {video_url}, store_name: {store_name}")
background_tasks.add_task(
download_and_upload_video_to_blob,
task_id=video.task_id,
video_url=video_url,
store_name=store_name,
)
elif video and video.status == "completed":
print(f"[get_video_status] SKIPPED - Video already completed, creatomate_render_id: {creatomate_render_id}")
render_data = VideoRenderData(
id=result.get("id"),
status=status,
url=video_url,
snapshot_url=result.get("snapshot_url"),
)
print(f"[get_video_status] SUCCESS - creatomate_render_id: {creatomate_render_id}")
return PollingVideoResponse(
success=True,
status=status,
message=message,
render_data=render_data,
raw_response=result,
error_message=None,
)
except Exception as e:
import traceback
print(f"[get_video_status] EXCEPTION - creatomate_render_id: {creatomate_render_id}, error: {e}")
return PollingVideoResponse(
success=False,
status="error",
message="상태 조회에 실패했습니다.",
render_data=None,
raw_response=None,
error_message=f"{type(e).__name__}: {e}\n{traceback.format_exc()}",
)
@router.get(
"/download/{task_id}",
summary="영상 생성 URL 조회",
description="""
task_id를 기반으로 Video 테이블의 상태를 polling하고,
completed인 경우 Project 정보와 영상 URL을 반환합니다.
## 경로 파라미터
- **task_id**: 프로젝트 task_id (필수)
## 반환 정보
- **success**: 조회 성공 여부
- **status**: 처리 상태 (processing, completed, failed)
- **message**: 응답 메시지
- **store_name**: 업체명
- **region**: 지역명
- **task_id**: 작업 고유 식별자
- **result_movie_url**: 영상 결과 URL (completed 시)
- **created_at**: 생성 일시
## 사용 예시
```
GET /video/download/019123ab-cdef-7890-abcd-ef1234567890
```
## 참고
- processing 상태인 경우 result_movie_url은 null입니다.
- completed 상태인 경우 Project 정보와 함께 result_movie_url을 반환합니다.
""",
response_model=DownloadVideoResponse,
responses={
200: {"description": "조회 성공"},
404: {"description": "Video를 찾을 수 없음"},
500: {"description": "조회 실패"},
},
)
async def download_video(
task_id: str,
session: AsyncSession = Depends(get_session),
) -> DownloadVideoResponse:
"""task_id로 Video 상태를 polling하고 completed 시 Project 정보와 영상 URL을 반환합니다."""
print(f"[download_video] START - task_id: {task_id}")
try:
# task_id로 Video 조회 (여러 개 있을 경우 가장 최근 것 선택)
video_result = await session.execute(
select(Video)
.where(Video.task_id == task_id)
.order_by(Video.created_at.desc())
.limit(1)
)
video = video_result.scalar_one_or_none()
if not video:
print(f"[download_video] Video NOT FOUND - task_id: {task_id}")
return DownloadVideoResponse(
success=False,
status="not_found",
message=f"task_id '{task_id}'에 해당하는 Video를 찾을 수 없습니다.",
error_message="Video not found",
)
print(f"[download_video] Video found - task_id: {task_id}, status: {video.status}")
# processing 상태인 경우
if video.status == "processing":
print(f"[download_video] PROCESSING - task_id: {task_id}")
return DownloadVideoResponse(
success=True,
status="processing",
message="영상 생성이 진행 중입니다.",
task_id=task_id,
)
# failed 상태인 경우
if video.status == "failed":
print(f"[download_video] FAILED - task_id: {task_id}")
return DownloadVideoResponse(
success=False,
status="failed",
message="영상 생성에 실패했습니다.",
task_id=task_id,
error_message="Video generation failed",
)
# completed 상태인 경우 - Project 정보 조회
project_result = await session.execute(
select(Project).where(Project.id == video.project_id)
)
project = project_result.scalar_one_or_none()
print(f"[download_video] COMPLETED - task_id: {task_id}, result_movie_url: {video.result_movie_url}")
return DownloadVideoResponse(
success=True,
status="completed",
message="영상 다운로드가 완료되었습니다.",
store_name=project.store_name if project else None,
region=project.region if project else None,
task_id=task_id,
result_movie_url=video.result_movie_url,
created_at=video.created_at,
)
except Exception as e:
print(f"[download_video] EXCEPTION - task_id: {task_id}, error: {e}")
return DownloadVideoResponse(
success=False,
status="error",
message="영상 다운로드 조회에 실패했습니다.",
error_message=str(e),
)
@router.get(
"s/",
summary="영상 목록 조회 (테스트)",
response_model=VideoListResponse,
)
async def get_videos() -> VideoListResponse:
"""영상 목록 조회 테스트 엔드포인트"""
now = datetime.now()
videos = [
VideoItem(
task_id=f"test-task-id-{i:03d}",
video_url=TEST_VIDEO_URL,
created_at=now - timedelta(hours=i),
)
for i in range(10)
]
summary="생성된 영상 목록 조회",
description="""
완료된 영상 목록을 페이지네이션하여 조회합니다.
return VideoListResponse(
videos=videos,
total=len(videos),
)
## 쿼리 파라미터
- **page**: 페이지 번호 (1부터 시작, 기본값: 1)
- **page_size**: 페이지당 데이터 수 (기본값: 10, 최대: 100)
## 반환 정보
- **items**: 영상 목록 (store_name, region, task_id, result_movie_url, created_at)
- **total**: 전체 데이터 수
- **page**: 현재 페이지
- **page_size**: 페이지당 데이터 수
- **total_pages**: 전체 페이지 수
- **has_next**: 다음 페이지 존재 여부
- **has_prev**: 이전 페이지 존재 여부
## 사용 예시
```
GET /videos/?page=1&page_size=10
```
## 참고
- status가 'completed'인 영상만 반환됩니다.
- 동일한 task_id가 있는 경우 가장 최근에 생성된 1개만 반환됩니다.
- created_at 기준 내림차순 정렬됩니다.
""",
response_model=PaginatedResponse[VideoListItem],
responses={
200: {"description": "영상 목록 조회 성공"},
500: {"description": "조회 실패"},
},
)
async def get_videos(
session: AsyncSession = Depends(get_session),
pagination: PaginationParams = Depends(get_pagination_params),
) -> PaginatedResponse[VideoListItem]:
"""완료된 영상 목록을 페이지네이션하여 반환합니다."""
print(f"[get_videos] START - page: {pagination.page}, page_size: {pagination.page_size}")
try:
offset = (pagination.page - 1) * pagination.page_size
# 서브쿼리: task_id별 최신 Video의 id 조회 (completed 상태만)
subquery = (
select(func.max(Video.id).label("max_id"))
.where(Video.status == "completed")
.group_by(Video.task_id)
.subquery()
)
# 전체 개수 조회 (task_id별 최신 1개만)
count_query = select(func.count()).select_from(subquery)
total_result = await session.execute(count_query)
total = total_result.scalar() or 0
# 데이터 조회 (completed 상태, task_id별 최신 1개만, 최신순)
query = (
select(Video)
.where(Video.id.in_(select(subquery.c.max_id)))
.order_by(Video.created_at.desc())
.offset(offset)
.limit(pagination.page_size)
)
result = await session.execute(query)
videos = result.scalars().all()
# Project 정보와 함께 VideoListItem으로 변환
items = []
for video in videos:
# Project 조회 (video.project_id 직접 사용)
project_result = await session.execute(
select(Project).where(Project.id == video.project_id)
)
project = project_result.scalar_one_or_none()
item = VideoListItem(
store_name=project.store_name if project else None,
region=project.region if project else None,
task_id=video.task_id,
result_movie_url=video.result_movie_url,
created_at=video.created_at,
)
items.append(item)
# 개별 아이템 로그
print(
f"[get_videos] Item - store_name: {item.store_name}, region: {item.region}, "
f"task_id: {item.task_id}, result_movie_url: {item.result_movie_url}, "
f"created_at: {item.created_at}"
)
response = PaginatedResponse.create(
items=items,
total=total,
page=pagination.page,
page_size=pagination.page_size,
)
print(
f"[get_videos] SUCCESS - total: {total}, page: {pagination.page}, "
f"page_size: {pagination.page_size}, items_count: {len(items)}"
)
return response
except Exception as e:
print(f"[get_videos] EXCEPTION - error: {e}")
raise HTTPException(
status_code=500,
detail=f"영상 목록 조회에 실패했습니다: {str(e)}",
)
+6
View File
@@ -83,6 +83,12 @@ class Video(Base):
comment="영상 생성 작업 고유 식별자 (UUID)",
)
creatomate_render_id: Mapped[Optional[str]] = mapped_column(
String(64),
nullable=True,
comment="Creatomate API 렌더 ID",
)
status: Mapped[str] = mapped_column(
String(50),
nullable=False,
+187 -73
View File
@@ -1,91 +1,205 @@
from dataclasses import dataclass, field
"""
Video API Schemas
영상 생성 관련 Pydantic 스키마를 정의합니다.
"""
from datetime import datetime
from typing import Dict, List
from typing import Any, Dict, List, Literal, Optional
from fastapi import Request
from pydantic import BaseModel, Field
@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
# =============================================================================
# Request Schemas
# =============================================================================
@dataclass
class AttributeData:
id: int
attr_category: str
attr_value: str
created_at: datetime
class GenerateVideoRequest(BaseModel):
"""영상 생성 요청 스키마
Usage:
POST /video/generate/{task_id}
Request body for generating a video via Creatomate API.
Example Request:
{
"template_id": "abc123...",
"image_urls": ["https://...", "https://..."],
"lyrics": "가사 내용...",
"music_url": "https://..."
}
"""
model_config = {
"json_schema_extra": {
"example": {
"orientation": "vertical",
"image_urls": [
"https://naverbooking-phinf.pstatic.net/20240514_189/1715688030436xT14o_JPEG/1.jpg",
"https://naverbooking-phinf.pstatic.net/20240514_48/1715688030574wTtQd_JPEG/2.jpg",
"https://naverbooking-phinf.pstatic.net/20240514_92/17156880307484bvpH_JPEG/3.jpg",
"https://naverbooking-phinf.pstatic.net/20240514_7/1715688031000y8Y5q_JPEG/4.jpg",
"https://naverbooking-phinf.pstatic.net/20240514_259/17156880311809wCnY_JPEG/5.jpg",
"https://naverbooking-phinf.pstatic.net/20240514_64/1715688031601oGNsV_JPEG/6.jpg",
"https://naverbooking-phinf.pstatic.net/20240514_175/1715688031657oXc7l_JPEG/7.jpg",
"https://naverbooking-phinf.pstatic.net/20240514_192/1715688031798MbFDj_JPEG/8.jpg",
"https://naverbooking-phinf.pstatic.net/20240514_205/17156880318681JLwX_JPEG/9.jpg",
"https://naverbooking-phinf.pstatic.net/20240514_142/1715688031946hhxHz_JPEG/10.jpg",
],
"lyrics": "인스타 감성의 스테이 머뭄, 머물러봐요\n군산 신흥동 말랭이 마을의 마음 힐링",
"music_url": "https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/0694e2d8-7ae2-730c-8000-308aacaa582d/song/스테이 머뭄.mp3",
}
}
}
orientation: Literal["horizontal", "vertical"] = Field(
default="vertical",
description="영상 방향 (horizontal: 가로형, vertical: 세로형, 기본값: vertical)",
)
image_urls: List[str] = Field(..., description="영상에 사용할 이미지 URL 목록")
lyrics: str = Field(..., description="영상에 표시할 가사")
music_url: str = Field(..., description="배경 음악 URL")
@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
# =============================================================================
# Response Schemas
# =============================================================================
@dataclass
class PromptTemplateData:
id: int
prompt: str
description: str | None = None
class GenerateVideoResponse(BaseModel):
"""영상 생성 응답 스키마
Usage:
POST /video/generate/{task_id}
Returns the task IDs for tracking video generation.
Example Response (Success):
{
"success": true,
"task_id": "019123ab-cdef-7890-abcd-ef1234567890",
"creatomate_render_id": "render-id-123",
"message": "영상 생성 요청이 접수되었습니다.",
"error_message": null
}
"""
success: bool = Field(..., description="요청 성공 여부")
task_id: Optional[str] = Field(None, description="내부 작업 ID (Project task_id)")
creatomate_render_id: Optional[str] = Field(None, description="Creatomate 렌더 ID")
message: str = Field(..., description="응답 메시지")
error_message: Optional[str] = Field(None, description="에러 메시지 (실패 시)")
@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"
class VideoRenderData(BaseModel):
"""Creatomate 렌더링 결과 데이터"""
@classmethod
async def from_form(cls, request: Request):
"""Request의 form 데이터로부터 dataclass 인스턴스 생성"""
form_data = await request.form()
id: Optional[str] = Field(None, description="렌더 ID")
status: Optional[str] = Field(None, description="렌더 상태")
url: Optional[str] = Field(None, description="영상 URL")
snapshot_url: Optional[str] = Field(None, description="스냅샷 URL")
# 고정 필드명들
fixed_keys = {"store_info_name", "store_id", "llm_model", "prompts"}
# lyrics-{id} 형태의 모든 키를 찾아서 ID 추출
lyrics_ids = []
attributes = {}
class PollingVideoResponse(BaseModel):
"""영상 생성 상태 조회 응답 스키마
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
Usage:
GET /video/status/{creatomate_render_id}
Creatomate API 작업 상태를 조회합니다.
# attributes를 문자열로 변환
attributes_str = (
"\r\n\r\n".join([f"{key} : {value}" for key, value in attributes.items()])
if attributes
else ""
)
Note:
상태 값:
- planned: 예약됨
- waiting: 대기 중
- transcribing: 트랜스크립션 중
- rendering: 렌더링 중
- succeeded: 성공
- failed: 실패
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", ""),
)
Example Response (Success):
{
"success": true,
"status": "succeeded",
"message": "영상 생성이 완료되었습니다.",
"render_data": {
"id": "render-id",
"status": "succeeded",
"url": "https://...",
"snapshot_url": "https://..."
},
"raw_response": {...},
"error_message": null
}
"""
success: bool = Field(..., description="조회 성공 여부")
status: Optional[str] = Field(
None, description="작업 상태 (planned, waiting, rendering, succeeded, failed)"
)
message: str = Field(..., description="상태 메시지")
render_data: Optional[VideoRenderData] = Field(None, description="렌더링 결과 데이터")
raw_response: Optional[Dict[str, Any]] = Field(None, description="Creatomate API 원본 응답")
error_message: Optional[str] = Field(None, description="에러 메시지 (실패 시)")
class DownloadVideoResponse(BaseModel):
"""영상 다운로드 응답 스키마
Usage:
GET /video/download/{task_id}
Polls for video completion and returns project info with video URL.
Note:
상태 값:
- processing: 영상 생성 진행 중 (result_movie_url은 null)
- completed: 영상 생성 완료 (result_movie_url 포함)
- failed: 영상 생성 실패
- not_found: task_id에 해당하는 Video 없음
- error: 조회 중 오류 발생
Example Response (Completed):
{
"success": true,
"status": "completed",
"message": "영상 다운로드가 완료되었습니다.",
"store_name": "스테이 머뭄",
"region": "군산",
"task_id": "019123ab-cdef-7890-abcd-ef1234567890",
"result_movie_url": "http://localhost:8000/media/2025-01-15/video.mp4",
"created_at": "2025-01-15T12:00:00",
"error_message": null
}
"""
success: bool = Field(..., description="다운로드 성공 여부")
status: str = Field(..., description="처리 상태 (processing, completed, failed, not_found, error)")
message: str = Field(..., description="응답 메시지")
store_name: Optional[str] = Field(None, description="업체명")
region: Optional[str] = Field(None, description="지역명")
task_id: Optional[str] = Field(None, description="작업 고유 식별자")
result_movie_url: Optional[str] = Field(None, description="영상 결과 URL")
created_at: Optional[datetime] = Field(None, description="생성 일시")
error_message: Optional[str] = Field(None, description="에러 메시지 (실패 시)")
class VideoListItem(BaseModel):
"""영상 목록 아이템 스키마
Usage:
GET /videos 응답의 개별 영상 정보
Example:
{
"store_name": "스테이 머뭄",
"region": "군산",
"task_id": "019123ab-cdef-7890-abcd-ef1234567890",
"result_movie_url": "http://localhost:8000/media/2025-01-15/video.mp4",
"created_at": "2025-01-15T12:00:00"
}
"""
store_name: Optional[str] = Field(None, description="업체명")
region: Optional[str] = Field(None, description="지역명")
task_id: str = Field(..., description="작업 고유 식별자")
result_movie_url: Optional[str] = Field(None, description="영상 결과 URL")
created_at: Optional[datetime] = Field(None, description="생성 일시")
+242
View File
@@ -0,0 +1,242 @@
"""
Video Background Tasks
영상 생성 관련 백그라운드 태스크를 정의합니다.
"""
from pathlib import Path
import aiofiles
import httpx
from sqlalchemy import select
from app.database.session import AsyncSessionLocal
from app.video.models import Video
from app.utils.upload_blob_as_request import AzureBlobUploader
async def download_and_upload_video_to_blob(
task_id: str,
video_url: str,
store_name: str,
) -> None:
"""백그라운드에서 영상을 다운로드하고 Azure Blob Storage에 업로드한 뒤 Video 테이블을 업데이트합니다.
Args:
task_id: 프로젝트 task_id
video_url: 다운로드할 영상 URL
store_name: 저장할 파일명에 사용할 업체명
"""
print(f"[download_and_upload_video_to_blob] START - task_id: {task_id}, store_name: {store_name}")
temp_file_path: Path | None = None
try:
# 파일명에 사용할 수 없는 문자 제거
safe_store_name = "".join(
c for c in store_name if c.isalnum() or c in (" ", "_", "-")
).strip()
safe_store_name = safe_store_name or "video"
file_name = f"{safe_store_name}.mp4"
# 임시 저장 경로 생성
temp_dir = Path("media") / "temp" / task_id
temp_dir.mkdir(parents=True, exist_ok=True)
temp_file_path = temp_dir / file_name
print(f"[download_and_upload_video_to_blob] Temp directory created - path: {temp_file_path}")
# 영상 파일 다운로드
print(f"[download_and_upload_video_to_blob] Downloading video - task_id: {task_id}, url: {video_url}")
async with httpx.AsyncClient() as client:
response = await client.get(video_url, timeout=180.0)
response.raise_for_status()
async with aiofiles.open(str(temp_file_path), "wb") as f:
await f.write(response.content)
print(f"[download_and_upload_video_to_blob] File downloaded - task_id: {task_id}, path: {temp_file_path}")
# Azure Blob Storage에 업로드
uploader = AzureBlobUploader(task_id=task_id)
upload_success = await uploader.upload_video(file_path=str(temp_file_path))
if not upload_success:
raise Exception("Azure Blob Storage 업로드 실패")
# SAS 토큰이 제외된 public_url 사용
blob_url = uploader.public_url
print(f"[download_and_upload_video_to_blob] Uploaded to Blob - task_id: {task_id}, url: {blob_url}")
# Video 테이블 업데이트 (새 세션 사용)
async with AsyncSessionLocal() as session:
# 여러 개 있을 경우 가장 최근 것 선택
result = await session.execute(
select(Video)
.where(Video.task_id == task_id)
.order_by(Video.created_at.desc())
.limit(1)
)
video = result.scalar_one_or_none()
if video:
video.status = "completed"
video.result_movie_url = blob_url
await session.commit()
print(f"[download_and_upload_video_to_blob] SUCCESS - task_id: {task_id}, status: completed")
else:
print(f"[download_and_upload_video_to_blob] Video NOT FOUND in DB - task_id: {task_id}")
except Exception as e:
print(f"[download_and_upload_video_to_blob] EXCEPTION - task_id: {task_id}, error: {e}")
# 실패 시 Video 테이블 업데이트
async with AsyncSessionLocal() as session:
result = await session.execute(
select(Video)
.where(Video.task_id == task_id)
.order_by(Video.created_at.desc())
.limit(1)
)
video = result.scalar_one_or_none()
if video:
video.status = "failed"
await session.commit()
print(f"[download_and_upload_video_to_blob] FAILED - task_id: {task_id}, status updated to failed")
finally:
# 임시 파일 삭제
if temp_file_path and temp_file_path.exists():
try:
temp_file_path.unlink()
print(f"[download_and_upload_video_to_blob] Temp file deleted - path: {temp_file_path}")
except Exception as e:
print(f"[download_and_upload_video_to_blob] Failed to delete temp file: {e}")
# 임시 디렉토리 삭제 시도
temp_dir = Path("media") / "temp" / task_id
if temp_dir.exists():
try:
temp_dir.rmdir()
except Exception:
pass # 디렉토리가 비어있지 않으면 무시
async def download_and_upload_video_by_creatomate_render_id(
creatomate_render_id: str,
video_url: str,
store_name: str,
) -> None:
"""creatomate_render_id로 Video를 조회하여 영상을 다운로드하고 Azure Blob Storage에 업로드한 뒤 Video 테이블을 업데이트합니다.
Args:
creatomate_render_id: Creatomate API 렌더 ID
video_url: 다운로드할 영상 URL
store_name: 저장할 파일명에 사용할 업체명
"""
print(f"[download_and_upload_video_by_creatomate_render_id] START - creatomate_render_id: {creatomate_render_id}, store_name: {store_name}")
temp_file_path: Path | None = None
task_id: str | None = None
try:
# creatomate_render_id로 Video 조회하여 task_id 가져오기
async with AsyncSessionLocal() as session:
result = await session.execute(
select(Video)
.where(Video.creatomate_render_id == creatomate_render_id)
.order_by(Video.created_at.desc())
.limit(1)
)
video = result.scalar_one_or_none()
if not video:
print(f"[download_and_upload_video_by_creatomate_render_id] Video NOT FOUND - creatomate_render_id: {creatomate_render_id}")
return
task_id = video.task_id
print(f"[download_and_upload_video_by_creatomate_render_id] Video found - creatomate_render_id: {creatomate_render_id}, task_id: {task_id}")
# 파일명에 사용할 수 없는 문자 제거
safe_store_name = "".join(
c for c in store_name if c.isalnum() or c in (" ", "_", "-")
).strip()
safe_store_name = safe_store_name or "video"
file_name = f"{safe_store_name}.mp4"
# 임시 저장 경로 생성
temp_dir = Path("media") / "temp" / task_id
temp_dir.mkdir(parents=True, exist_ok=True)
temp_file_path = temp_dir / file_name
print(f"[download_and_upload_video_by_creatomate_render_id] Temp directory created - path: {temp_file_path}")
# 영상 파일 다운로드
print(f"[download_and_upload_video_by_creatomate_render_id] Downloading video - creatomate_render_id: {creatomate_render_id}, url: {video_url}")
async with httpx.AsyncClient() as client:
response = await client.get(video_url, timeout=180.0)
response.raise_for_status()
async with aiofiles.open(str(temp_file_path), "wb") as f:
await f.write(response.content)
print(f"[download_and_upload_video_by_creatomate_render_id] File downloaded - creatomate_render_id: {creatomate_render_id}, path: {temp_file_path}")
# Azure Blob Storage에 업로드
uploader = AzureBlobUploader(task_id=task_id)
upload_success = await uploader.upload_video(file_path=str(temp_file_path))
if not upload_success:
raise Exception("Azure Blob Storage 업로드 실패")
# SAS 토큰이 제외된 public_url 사용
blob_url = uploader.public_url
print(f"[download_and_upload_video_by_creatomate_render_id] Uploaded to Blob - creatomate_render_id: {creatomate_render_id}, url: {blob_url}")
# Video 테이블 업데이트 (새 세션 사용)
async with AsyncSessionLocal() as session:
result = await session.execute(
select(Video)
.where(Video.creatomate_render_id == creatomate_render_id)
.order_by(Video.created_at.desc())
.limit(1)
)
video = result.scalar_one_or_none()
if video:
video.status = "completed"
video.result_movie_url = blob_url
await session.commit()
print(f"[download_and_upload_video_by_creatomate_render_id] SUCCESS - creatomate_render_id: {creatomate_render_id}, status: completed")
else:
print(f"[download_and_upload_video_by_creatomate_render_id] Video NOT FOUND in DB - creatomate_render_id: {creatomate_render_id}")
except Exception as e:
print(f"[download_and_upload_video_by_creatomate_render_id] EXCEPTION - creatomate_render_id: {creatomate_render_id}, error: {e}")
# 실패 시 Video 테이블 업데이트
if task_id:
async with AsyncSessionLocal() as session:
result = await session.execute(
select(Video)
.where(Video.creatomate_render_id == creatomate_render_id)
.order_by(Video.created_at.desc())
.limit(1)
)
video = result.scalar_one_or_none()
if video:
video.status = "failed"
await session.commit()
print(f"[download_and_upload_video_by_creatomate_render_id] FAILED - creatomate_render_id: {creatomate_render_id}, status updated to failed")
finally:
# 임시 파일 삭제
if temp_file_path and temp_file_path.exists():
try:
temp_file_path.unlink()
print(f"[download_and_upload_video_by_creatomate_render_id] Temp file deleted - path: {temp_file_path}")
except Exception as e:
print(f"[download_and_upload_video_by_creatomate_render_id] Failed to delete temp file: {e}")
# 임시 디렉토리 삭제 시도
if task_id:
temp_dir = Path("media") / "temp" / task_id
if temp_dir.exists():
try:
temp_dir.rmdir()
except Exception:
pass # 디렉토리가 비어있지 않으면 무시
View File
Whitespace-only changes.
+43
View File
@@ -127,6 +127,47 @@ class CrawlerSettings(BaseSettings):
model_config = _base_config
class AzureBlobSettings(BaseSettings):
"""Azure Blob Storage 설정"""
AZURE_BLOB_SAS_TOKEN: str = Field(
default="",
description="Azure Blob Storage SAS 토큰",
)
AZURE_BLOB_BASE_URL: str = Field(
default="https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original",
description="Azure Blob Storage 기본 URL",
)
model_config = _base_config
class CreatomateSettings(BaseSettings):
"""Creatomate 템플릿 설정"""
# 세로형 템플릿 (기본값)
TEMPLATE_ID_VERTICAL: str = Field(
default="e8c7b43f-de4b-4ba3-b8eb-5df688569193",
description="Creatomate 세로형 템플릿 ID",
)
TEMPLATE_DURATION_VERTICAL: float = Field(
default=90.0,
description="세로형 템플릿 기본 duration (초)",
)
# 가로형 템플릿
TEMPLATE_ID_HORIZONTAL: str = Field(
default="0f092a6a-f526-4ef0-9181-d4ad4426b9e7",
description="Creatomate 가로형 템플릿 ID",
)
TEMPLATE_DURATION_HORIZONTAL: float = Field(
default=30.0,
description="가로형 템플릿 기본 duration (초)",
)
model_config = _base_config
prj_settings = ProjectSettings()
apikey_settings = APIKeySettings()
db_settings = DatabaseSettings()
@@ -134,3 +175,5 @@ security_settings = SecuritySettings()
notification_settings = NotificationSettings()
cors_settings = CORSSettings()
crawler_settings = CrawlerSettings()
azure_blob_settings = AzureBlobSettings()
creatomate_settings = CreatomateSettings()
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,69 @@
from pathlib import Path
import requests
SAS_TOKEN = "sp=racwdl&st=2025-12-01T00:13:29Z&se=2026-07-31T08:28:29Z&spr=https&sv=2024-11-04&sr=c&sig=7fE2ozVBPu3Gq43%2FZDxEYdEcPLDXyNVfTf16IBasmVQ%3D"
URL = "https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/"
def upload_music_to_azure_blob(
file_path="스테이 머뭄_1.mp3",
url="https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/dev-user-idx/dev-task-idx/test_my_mp3_should_now_exist.mp3",
):
access_url = f"{url}?{SAS_TOKEN}"
headers = {"Content-Type": "audio/mpeg", "x-ms-blob-type": "BlockBlob"}
with open(file_path, "rb") as file:
response = requests.put(access_url, data=file, headers=headers)
if response.status_code in [200, 201]:
print(f"Success Status Code: {response.status_code}")
else:
print(f"Failed Status Code: {response.status_code}")
print(f"Response: {response.text}")
def upload_video_to_azure_blob(
file_path="스테이 머뭄.mp4",
url="https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/dev-user-idx/dev-task-idx/test_my_mp3_should_now_exist.mp4",
):
access_url = f"{url}?{SAS_TOKEN}"
headers = {"Content-Type": "video/mp4", "x-ms-blob-type": "BlockBlob"}
with open(file_path, "rb") as file:
response = requests.put(access_url, data=file, headers=headers)
if response.status_code in [200, 201]:
print(f"Success Status Code: {response.status_code}")
else:
print(f"Failed Status Code: {response.status_code}")
print(f"Response: {response.text}")
def upload_image_to_azure_blob(
file_path="스테이 머뭄.png",
url="https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/dev-user-idx/dev-task-idx/test_my_mp3_should_now_exist.png",
):
access_url = f"{url}?{SAS_TOKEN}"
extension = Path(file_path).suffix.lower()
content_types = {
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".gif": "image/gif",
".webp": "image/webp",
".bmp": "image/bmp",
}
content_type = content_types.get(extension, "image/jpeg")
headers = {"Content-Type": content_type, "x-ms-blob-type": "BlockBlob"}
with open(file_path, "rb") as file:
response = requests.put(access_url, data=file, headers=headers)
if response.status_code in [200, 201]:
print(f"Success Status Code: {response.status_code}")
else:
print(f"Failed Status Code: {response.status_code}")
print(f"Response: {response.text}")
upload_video_to_azure_blob()
upload_image_to_azure_blob()