add logger

This commit is contained in:
Dohyun Lim committed 2026-01-14 17:46:45 +09:00
1 parent 1acd8846ab
commit bf7b53c8e8
41 files changed
+1832 -694

No files matched your search

+40 -38
View File
@@ -39,7 +39,9 @@ from app.video.schemas.video_schema import (
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 app.utils.logger import get_logger
logger = get_logger("video")
router = APIRouter(prefix="/video", tags=["video"])
@@ -115,7 +117,7 @@ async def generate_video(
from app.database.session import AsyncSessionLocal
request_start = time.perf_counter()
print(f"[generate_video] START - task_id: {task_id}, orientation: {orientation}")
logger.info(f"[generate_video] START - task_id: {task_id}, orientation: {orientation}")
# ==========================================================================
# 1단계: DB 조회 및 초기 데이터 저장 (세션을 명시적으로 열고 닫음)
@@ -168,13 +170,13 @@ async def generate_video(
)
query_time = time.perf_counter()
print(f"[generate_video] Queries completed - task_id: {task_id}, "
logger.debug(f"[generate_video] Queries completed - task_id: {task_id}, "
f"elapsed: {(query_time - request_start)*1000:.1f}ms")
# ===== 결과 처리: Project =====
project = project_result.scalar_one_or_none()
if not project:
print(f"[generate_video] Project NOT FOUND - task_id: {task_id}")
logger.warning(f"[generate_video] Project NOT FOUND - task_id: {task_id}")
raise HTTPException(
status_code=404,
detail=f"task_id '{task_id}'에 해당하는 Project를 찾을 수 없습니다.",
@@ -184,7 +186,7 @@ async def generate_video(
# ===== 결과 처리: Lyric =====
lyric = lyric_result.scalar_one_or_none()
if not lyric:
print(f"[generate_video] Lyric NOT FOUND - task_id: {task_id}")
logger.warning(f"[generate_video] Lyric NOT FOUND - task_id: {task_id}")
raise HTTPException(
status_code=404,
detail=f"task_id '{task_id}'에 해당하는 Lyric을 찾을 수 없습니다.",
@@ -194,7 +196,7 @@ async def generate_video(
# ===== 결과 처리: Song =====
song = song_result.scalar_one_or_none()
if not song:
print(f"[generate_video] Song NOT FOUND - task_id: {task_id}")
logger.warning(f"[generate_video] Song NOT FOUND - task_id: {task_id}")
raise HTTPException(
status_code=404,
detail=f"task_id '{task_id}'에 해당하는 Song을 찾을 수 없습니다.",
@@ -220,14 +222,14 @@ async def generate_video(
# ===== 결과 처리: Image =====
images = image_result.scalars().all()
if not images:
print(f"[generate_video] Image NOT FOUND - task_id: {task_id}")
logger.warning(f"[generate_video] Image NOT FOUND - task_id: {task_id}")
raise HTTPException(
status_code=404,
detail=f"task_id '{task_id}'에 해당하는 이미지를 찾을 수 없습니다.",
)
image_urls = [img.img_url for img in images]
print(
logger.info(
f"[generate_video] Data loaded - task_id: {task_id}, "
f"project_id: {project_id}, lyric_id: {lyric_id}, "
f"song_id: {song_id}, images: {len(image_urls)}"
@@ -246,14 +248,14 @@ async def generate_video(
await session.commit()
video_id = video.id
stage1_time = time.perf_counter()
print(f"[generate_video] Video saved - task_id: {task_id}, id: {video_id}, "
logger.info(f"[generate_video] Video saved - task_id: {task_id}, id: {video_id}, "
f"stage1_elapsed: {(stage1_time - request_start)*1000:.1f}ms")
# 세션이 여기서 자동으로 닫힘 (async with 블록 종료)
except HTTPException:
raise
except Exception as e:
print(f"[generate_video] DB EXCEPTION - task_id: {task_id}, error: {e}")
logger.error(f"[generate_video] DB EXCEPTION - task_id: {task_id}, error: {e}")
return GenerateVideoResponse(
success=False,
task_id=task_id,
@@ -267,16 +269,16 @@ async def generate_video(
# ==========================================================================
stage2_start = time.perf_counter()
try:
print(f"[generate_video] Stage 2 START - Creatomate API - task_id: {task_id}")
logger.info(f"[generate_video] Stage 2 START - Creatomate API - task_id: {task_id}")
creatomate_service = CreatomateService(
orientation=orientation,
target_duration=song_duration,
)
print(f"[generate_video] Using template_id: {creatomate_service.template_id}, duration: {creatomate_service.target_duration} (song duration: {song_duration})")
logger.debug(f"[generate_video] Using template_id: {creatomate_service.template_id}, duration: {creatomate_service.target_duration} (song duration: {song_duration})")
# 6-1. 템플릿 조회 (비동기)
template = await creatomate_service.get_one_template_data_async(creatomate_service.template_id)
print(f"[generate_video] Template fetched - task_id: {task_id}")
logger.debug(f"[generate_video] Template fetched - task_id: {task_id}")
# 6-2. elements에서 리소스 매핑 생성
modifications = creatomate_service.elements_connect_resource_blackbox(
@@ -285,7 +287,7 @@ async def generate_video(
lyric=lyrics,
music_url=music_url,
)
print(f"[generate_video] Modifications created - task_id: {task_id}")
logger.debug(f"[generate_video] Modifications created - task_id: {task_id}")
# 6-3. elements 수정
new_elements = creatomate_service.modify_element(
@@ -293,20 +295,20 @@ async def generate_video(
modifications,
)
template["source"]["elements"] = new_elements
print(f"[generate_video] Elements modified - task_id: {task_id}")
logger.debug(f"[generate_video] Elements modified - task_id: {task_id}")
# 6-4. 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}")
logger.debug(f"[generate_video] Duration extended to {creatomate_service.target_duration}s - task_id: {task_id}")
# 6-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}")
logger.debug(f"[generate_video] Creatomate API response - task_id: {task_id}, response: {render_response}")
# 렌더 ID 추출
if isinstance(render_response, list) and len(render_response) > 0:
@@ -317,14 +319,14 @@ async def generate_video(
creatomate_render_id = None
stage2_time = time.perf_counter()
print(
logger.info(
f"[generate_video] Stage 2 DONE - task_id: {task_id}, "
f"render_id: {creatomate_render_id}, "
f"stage2_elapsed: {(stage2_time - stage2_start)*1000:.1f}ms"
)
except Exception as e:
print(f"[generate_video] Creatomate API EXCEPTION - task_id: {task_id}, error: {e}")
logger.error(f"[generate_video] Creatomate API EXCEPTION - task_id: {task_id}, error: {e}")
# 외부 API 실패 시 Video 상태를 failed로 업데이트
from app.database.session import AsyncSessionLocal
async with AsyncSessionLocal() as update_session:
@@ -347,7 +349,7 @@ async def generate_video(
# 3단계: creatomate_render_id 업데이트 (새 세션으로 빠르게 처리)
# ==========================================================================
stage3_start = time.perf_counter()
print(f"[generate_video] Stage 3 START - DB update - task_id: {task_id}")
logger.info(f"[generate_video] Stage 3 START - DB update - task_id: {task_id}")
try:
from app.database.session import AsyncSessionLocal
async with AsyncSessionLocal() as update_session:
@@ -361,11 +363,11 @@ async def generate_video(
stage3_time = time.perf_counter()
total_time = stage3_time - request_start
print(
logger.debug(
f"[generate_video] Stage 3 DONE - task_id: {task_id}, "
f"stage3_elapsed: {(stage3_time - stage3_start)*1000:.1f}ms"
)
print(
logger.info(
f"[generate_video] SUCCESS - task_id: {task_id}, "
f"render_id: {creatomate_render_id}, "
f"total_time: {total_time*1000:.1f}ms"
@@ -380,7 +382,7 @@ async def generate_video(
)
except Exception as e:
print(f"[generate_video] Update EXCEPTION - task_id: {task_id}, error: {e}")
logger.error(f"[generate_video] Update EXCEPTION - task_id: {task_id}, error: {e}")
return GenerateVideoResponse(
success=False,
task_id=task_id,
@@ -439,11 +441,11 @@ async def get_video_status(
succeeded 상태인 경우 백그라운드에서 MP4 파일을 다운로드하고
Video 테이블의 status를 completed로, result_movie_url을 업데이트합니다.
"""
print(f"[get_video_status] START - creatomate_render_id: {creatomate_render_id}")
logger.info(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')}")
logger.debug(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")
@@ -481,7 +483,7 @@ async def get_video_status(
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}")
logger.info(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,
@@ -489,7 +491,7 @@ async def get_video_status(
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}")
logger.debug(f"[get_video_status] SKIPPED - Video already completed, creatomate_render_id: {creatomate_render_id}")
render_data = VideoRenderData(
id=result.get("id"),
@@ -498,7 +500,7 @@ async def get_video_status(
snapshot_url=result.get("snapshot_url"),
)
print(f"[get_video_status] SUCCESS - creatomate_render_id: {creatomate_render_id}")
logger.info(f"[get_video_status] SUCCESS - creatomate_render_id: {creatomate_render_id}")
return PollingVideoResponse(
success=True,
status=status,
@@ -511,7 +513,7 @@ async def get_video_status(
except Exception as e:
import traceback
print(f"[get_video_status] EXCEPTION - creatomate_render_id: {creatomate_render_id}, error: {e}")
logger.error(f"[get_video_status] EXCEPTION - creatomate_render_id: {creatomate_render_id}, error: {e}")
return PollingVideoResponse(
success=False,
status="error",
@@ -563,7 +565,7 @@ async def download_video(
session: AsyncSession = Depends(get_session),
) -> DownloadVideoResponse:
"""task_id로 Video 상태를 polling하고 completed 시 Project 정보와 영상 URL을 반환합니다."""
print(f"[download_video] START - task_id: {task_id}")
logger.info(f"[download_video] START - task_id: {task_id}")
try:
# task_id로 Video 조회 (여러 개 있을 경우 가장 최근 것 선택)
video_result = await session.execute(
@@ -575,7 +577,7 @@ async def download_video(
video = video_result.scalar_one_or_none()
if not video:
print(f"[download_video] Video NOT FOUND - task_id: {task_id}")
logger.warning(f"[download_video] Video NOT FOUND - task_id: {task_id}")
return DownloadVideoResponse(
success=False,
status="not_found",
@@ -583,11 +585,11 @@ async def download_video(
error_message="Video not found",
)
print(f"[download_video] Video found - task_id: {task_id}, status: {video.status}")
logger.debug(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}")
logger.debug(f"[download_video] PROCESSING - task_id: {task_id}")
return DownloadVideoResponse(
success=True,
status="processing",
@@ -597,7 +599,7 @@ async def download_video(
# failed 상태인 경우
if video.status == "failed":
print(f"[download_video] FAILED - task_id: {task_id}")
logger.error(f"[download_video] FAILED - task_id: {task_id}")
return DownloadVideoResponse(
success=False,
status="failed",
@@ -612,7 +614,7 @@ async def download_video(
)
project = project_result.scalar_one_or_none()
print(f"[download_video] COMPLETED - task_id: {task_id}, result_movie_url: {video.result_movie_url}")
logger.info(f"[download_video] COMPLETED - task_id: {task_id}, result_movie_url: {video.result_movie_url}")
return DownloadVideoResponse(
success=True,
status="completed",
@@ -625,7 +627,7 @@ async def download_video(
)
except Exception as e:
print(f"[download_video] EXCEPTION - task_id: {task_id}, error: {e}")
logger.error(f"[download_video] EXCEPTION - task_id: {task_id}, error: {e}")
return DownloadVideoResponse(
success=False,
status="error",
@@ -674,7 +676,7 @@ async def get_videos(
pagination: PaginationParams = Depends(get_pagination_params),
) -> PaginatedResponse[VideoListItem]:
"""완료된 영상 목록을 페이지네이션하여 반환합니다."""
print(f"[get_videos] START - page: {pagination.page}, page_size: {pagination.page_size}")
logger.info(f"[get_videos] START - page: {pagination.page}, page_size: {pagination.page_size}")
try:
offset = (pagination.page - 1) * pagination.page_size
@@ -732,14 +734,14 @@ async def get_videos(
page_size=pagination.page_size,
)
print(
logger.info(
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}")
logger.error(f"[get_videos] EXCEPTION - error: {e}")
raise HTTPException(
status_code=500,
detail=f"영상 목록 조회에 실패했습니다: {str(e)}",
+77 -94
View File
@@ -14,6 +14,9 @@ from app.lyrics.schemas.lyrics_schema import (
StoreData,
)
from app.utils.chatgpt_prompt import chatgpt_api
from app.utils.logger import get_logger
logger = get_logger("video")
async def get_store_info(conn: Connection) -> List[StoreData]:
@@ -38,13 +41,13 @@ async def get_store_info(conn: Connection) -> List[StoreData]:
result.close()
return all_store_info
except SQLAlchemyError as e:
print(e)
logger.error(f"SQLAlchemy error in get_store_info: {e}")
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="요청하신 서비스가 잠시 내부적으로 문제가 발생하였습니다.",
)
except Exception as e:
print(e)
logger.error(f"Unexpected error in get_store_info: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="알수없는 이유로 서비스 오류가 발생하였습니다",
@@ -69,13 +72,13 @@ async def get_attribute(conn: Connection) -> List[AttributeData]:
result.close()
return all_attribute
except SQLAlchemyError as e:
print(e)
logger.error(f"SQLAlchemy error in get_attribute: {e}")
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="요청하신 서비스가 잠시 내부적으로 문제가 발생하였습니다.",
)
except Exception as e:
print(e)
logger.error(f"Unexpected error in get_attribute: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="알수없는 이유로 서비스 오류가 발생하였습니다",
@@ -100,13 +103,13 @@ async def get_attribute(conn: Connection) -> List[AttributeData]:
result.close()
return all_attribute
except SQLAlchemyError as e:
print(e)
logger.error(f"SQLAlchemy error in get_attribute: {e}")
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="요청하신 서비스가 잠시 내부적으로 문제가 발생하였습니다.",
)
except Exception as e:
print(e)
logger.error(f"Unexpected error in get_attribute: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="알수없는 이유로 서비스 오류가 발생하였습니다",
@@ -132,13 +135,13 @@ async def get_sample_song(conn: Connection) -> List[SongSampleData]:
result.close()
return all_sample_song
except SQLAlchemyError as e:
print(e)
logger.error(f"SQLAlchemy error in get_sample_song: {e}")
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="요청하신 서비스가 잠시 내부적으로 문제가 발생하였습니다.",
)
except Exception as e:
print(e)
logger.error(f"Unexpected error in get_sample_song: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="알수없는 이유로 서비스 오류가 발생하였습니다",
@@ -162,13 +165,13 @@ async def get_prompt_template(conn: Connection) -> List[PromptTemplateData]:
result.close()
return all_prompt_template
except SQLAlchemyError as e:
print(e)
logger.error(f"SQLAlchemy error in get_prompt_template: {e}")
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="요청하신 서비스가 잠시 내부적으로 문제가 발생하였습니다.",
)
except Exception as e:
print(e)
logger.error(f"Unexpected error in get_prompt_template: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="알수없는 이유로 서비스 오류가 발생하였습니다",
@@ -192,13 +195,13 @@ async def get_song_result(conn: Connection) -> List[PromptTemplateData]:
result.close()
return all_prompt_template
except SQLAlchemyError as e:
print(e)
logger.error(f"SQLAlchemy error in get_song_result: {e}")
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="요청하신 서비스가 잠시 내부적으로 문제가 발생하였습니다.",
)
except Exception as e:
print(e)
logger.error(f"Unexpected error in get_song_result: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="알수없는 이유로 서비스 오류가 발생하였습니다",
@@ -210,11 +213,11 @@ async def make_song_result(request: Request, conn: Connection):
# 1. Form 데이터 파싱
form_data = await SongFormData.from_form(request)
print(f"\n{'=' * 60}")
print(f"Store ID: {form_data.store_id}")
print(f"Lyrics IDs: {form_data.lyrics_ids}")
print(f"Prompt IDs: {form_data.prompts}")
print(f"{'=' * 60}\n")
logger.info(f"{'=' * 60}")
logger.info(f"Store ID: {form_data.store_id}")
logger.info(f"Lyrics IDs: {form_data.lyrics_ids}")
logger.info(f"Prompt IDs: {form_data.prompts}")
logger.info(f"{'=' * 60}")
# 2. Store 정보 조회
store_query = """
@@ -243,7 +246,7 @@ async def make_song_result(request: Request, conn: Connection):
)
store_info = all_store_info[0]
print(f"Store: {store_info.store_name}")
logger.info(f"Store: {store_info.store_name}")
# 3. 속성 조회 -- 단계별 선택 프로세서시 구현 필요 없음
@@ -251,7 +254,7 @@ async def make_song_result(request: Request, conn: Connection):
combined_sample_song = None
if form_data.lyrics_ids:
print(f"\n[샘플 가사 조회] - {len(form_data.lyrics_ids)}개")
logger.info(f"[샘플 가사 조회] - {len(form_data.lyrics_ids)}개")
lyrics_query = """
SELECT sample_song FROM song_sample
@@ -270,11 +273,11 @@ async def make_song_result(request: Request, conn: Connection):
combined_sample_song = "\n\n".join(
[f"[샘플 {i + 1}]\n{song}" for i, song in enumerate(sample_songs)]
)
print(f"{len(sample_songs)}개의 샘플 가사 조회 완료")
logger.info(f"{len(sample_songs)}개의 샘플 가사 조회 완료")
else:
print("샘플 가사가 비어있습니다")
logger.info("샘플 가사가 비어있습니다")
else:
print("선택된 lyrics가 없습니다")
logger.info("선택된 lyrics가 없습니다")
# 5. 템플릿 가져오기
if not form_data.prompts:
@@ -283,7 +286,7 @@ async def make_song_result(request: Request, conn: Connection):
detail="프롬프트 ID가 필요합니다",
)
print("템플릿 가져오기")
logger.info("템플릿 가져오기")
prompts_query = """
SELECT * FROM prompt_template WHERE id=:id;
@@ -310,7 +313,7 @@ async def make_song_result(request: Request, conn: Connection):
)
prompt = prompts_info[0]
print(f"Prompt Template: {prompt.prompt}")
logger.debug(f"Prompt Template: {prompt.prompt}")
# ✅ 6. 프롬프트 조합
updated_prompt = prompt.prompt.replace("###", form_data.attributes_str).format(
@@ -329,7 +332,7 @@ async def make_song_result(request: Request, conn: Connection):
{combined_sample_song}
"""
print(f"\n[업데이트된 프롬프트]\n{updated_prompt}\n")
logger.debug(f"[업데이트된 프롬프트]\n{updated_prompt}")
# 7. 모델에게 요청
generated_lyrics = await chatgpt_api.generate(prompt=updated_prompt)
@@ -348,13 +351,12 @@ async def make_song_result(request: Request, conn: Connection):
전체 글자 수 (공백 포함): {total_chars_with_space}자
전체 글자 수 (공백 제외): {total_chars_without_space}자\r\n\r\n{generated_lyrics}"""
print("=" * 40)
print("[translate:form_data.attributes_str:] ", form_data.attributes_str)
print("[translate:total_chars_with_space:] ", total_chars_with_space)
print("[translate:total_chars_without_space:] ", total_chars_without_space)
print("[translate:final_lyrics:]")
print(final_lyrics)
print("=" * 40)
logger.debug("=" * 40)
logger.debug(f"[translate:form_data.attributes_str:] {form_data.attributes_str}")
logger.debug(f"[translate:total_chars_with_space:] {total_chars_with_space}")
logger.debug(f"[translate:total_chars_without_space:] {total_chars_without_space}")
logger.debug(f"[translate:final_lyrics:]\n{final_lyrics}")
logger.debug("=" * 40)
# 8. DB 저장
insert_query = """
@@ -396,13 +398,13 @@ async def make_song_result(request: Request, conn: Connection):
await conn.execute(text(insert_query), insert_params)
await conn.commit()
print("결과 저장 완료")
logger.info("결과 저장 완료")
print("\n전체 결과 조회 중...")
logger.info("전체 결과 조회 중...")
# 9. 생성 결과 가져오기 (created_at 역순)
select_query = """
SELECT * FROM song_results_all
SELECT * FROM song_results_all
ORDER BY created_at DESC;
"""
@@ -430,26 +432,20 @@ async def make_song_result(request: Request, conn: Connection):
for row in all_results.fetchall()
]
print(f"전체 {len(results_list)}개의 결과 조회 완료\n")
logger.info(f"전체 {len(results_list)}개의 결과 조회 완료")
return results_list
except HTTPException:
raise
except SQLAlchemyError as e:
print(f"Database Error: {e}")
import traceback
traceback.print_exc()
logger.error(f"Database Error: {e}", exc_info=True)
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="데이터베이스 연결에 문제가 발생했습니다.",
)
except Exception as e:
print(f"Unexpected Error: {e}")
import traceback
traceback.print_exc()
logger.error(f"Unexpected Error: {e}", exc_info=True)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="서비스 처리 중 오류가 발생했습니다.",
@@ -490,25 +486,19 @@ async def get_song_result(conn: Connection): # 반환 타입 수정
for row in all_results.fetchall()
]
print(f"전체 {len(results_list)}개의 결과 조회 완료\n")
logger.info(f"전체 {len(results_list)}개의 결과 조회 완료")
return results_list
except HTTPException: # HTTPException은 그대로 raise
raise
except SQLAlchemyError as e:
print(f"Database Error: {e}")
import traceback
traceback.print_exc()
logger.error(f"Database Error: {e}", exc_info=True)
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="데이터베이스 연결에 문제가 발생했습니다.",
)
except Exception as e:
print(f"Unexpected Error: {e}")
import traceback
traceback.print_exc()
logger.error(f"Unexpected Error: {e}", exc_info=True)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="서비스 처리 중 오류가 발생했습니다.",
@@ -520,9 +510,9 @@ async def make_automation(request: Request, conn: Connection):
# 1. Form 데이터 파싱
form_data = await SongFormData.from_form(request)
print(f"\n{'=' * 60}")
print(f"Store ID: {form_data.store_id}")
print(f"{'=' * 60}\n")
logger.info(f"{'=' * 60}")
logger.info(f"Store ID: {form_data.store_id}")
logger.info(f"{'=' * 60}")
# 2. Store 정보 조회
store_query = """
@@ -551,7 +541,7 @@ async def make_automation(request: Request, conn: Connection):
)
store_info = all_store_info[0]
print(f"Store: {store_info.store_name}")
logger.info(f"Store: {store_info.store_name}")
# 3. 속성 조회 -- 단계별 선택 프로세서시 구현 필요 없음
attribute_query = """
@@ -596,13 +586,13 @@ async def make_automation(request: Request, conn: Connection):
# 최종 문자열 생성
formatted_attributes = "\n".join(formatted_pairs)
print(f"\n[포맷팅된 문자열 속성 정보]\n{formatted_attributes}\n")
logger.debug(f"[포맷팅된 문자열 속성 정보]\n{formatted_attributes}")
else:
print("속성 데이터가 없습니다")
logger.info("속성 데이터가 없습니다")
formatted_attributes = ""
# 4. 템플릿 가져오기
print("템플릿 가져오기 (ID=1)")
logger.info("템플릿 가져오기 (ID=1)")
prompts_query = """
SELECT * FROM prompt_template WHERE id=1;
@@ -624,7 +614,7 @@ async def make_automation(request: Request, conn: Connection):
prompt=row[2],
)
print(f"Prompt Template: {prompt.prompt}")
logger.debug(f"Prompt Template: {prompt.prompt}")
# 5. 템플릿 조합
@@ -635,17 +625,17 @@ async def make_automation(request: Request, conn: Connection):
description=store_info.store_info or "",
)
print("\n" + "=" * 80)
print("업데이트된 프롬프트")
print("=" * 80)
print(updated_prompt)
print("=" * 80 + "\n")
logger.debug("=" * 80)
logger.debug("업데이트된 프롬프트")
logger.debug("=" * 80)
logger.debug(updated_prompt)
logger.debug("=" * 80)
# 4. Sample Song 조회 및 결합
combined_sample_song = None
if form_data.lyrics_ids:
print(f"\n[샘플 가사 조회] - {len(form_data.lyrics_ids)}개")
logger.info(f"[샘플 가사 조회] - {len(form_data.lyrics_ids)}개")
lyrics_query = """
SELECT sample_song FROM song_sample
@@ -664,14 +654,14 @@ async def make_automation(request: Request, conn: Connection):
combined_sample_song = "\n\n".join(
[f"[샘플 {i + 1}]\n{song}" for i, song in enumerate(sample_songs)]
)
print(f"{len(sample_songs)}개의 샘플 가사 조회 완료")
logger.info(f"{len(sample_songs)}개의 샘플 가사 조회 완료")
else:
print("샘플 가사가 비어있습니다")
logger.info("샘플 가사가 비어있습니다")
else:
print("선택된 lyrics가 없습니다")
logger.info("선택된 lyrics가 없습니다")
# 1. song_sample 테이블의 모든 ID 조회
print("\n[샘플 가사 랜덤 선택]")
logger.info("[샘플 가사 랜덤 선택]")
all_ids_query = """
SELECT id FROM song_sample;
@@ -679,7 +669,7 @@ async def make_automation(request: Request, conn: Connection):
ids_result = await conn.execute(text(all_ids_query))
all_ids = [row.id for row in ids_result.fetchall()]
print(f"전체 샘플 가사 개수: {len(all_ids)}개")
logger.info(f"전체 샘플 가사 개수: {len(all_ids)}개")
# 2. 랜덤하게 3개 선택 (또는 전체 개수가 3개 미만이면 전체)
combined_sample_song = None
@@ -689,7 +679,7 @@ async def make_automation(request: Request, conn: Connection):
sample_count = min(3, len(all_ids))
selected_ids = random.sample(all_ids, sample_count)
print(f"랜덤 선택된 ID: {selected_ids}")
logger.info(f"랜덤 선택된 ID: {selected_ids}")
# 3. 선택된 ID로 샘플 가사 조회
lyrics_query = """
@@ -710,11 +700,11 @@ async def make_automation(request: Request, conn: Connection):
combined_sample_song = "\n\n".join(
[f"[샘플 {i + 1}]\n{song}" for i, song in enumerate(sample_songs)]
)
print(f"{len(sample_songs)}개의 샘플 가사 조회 완료")
logger.info(f"{len(sample_songs)}개의 샘플 가사 조회 완료")
else:
print("샘플 가사가 비어있습니다")
logger.info("샘플 가사가 비어있습니다")
else:
print("song_sample 테이블에 데이터가 없습니다")
logger.info("song_sample 테이블에 데이터가 없습니다")
# 5. 프롬프트에 샘플 가사 추가
if combined_sample_song:
@@ -726,11 +716,11 @@ async def make_automation(request: Request, conn: Connection):
{combined_sample_song}
"""
print("샘플 가사 정보가 프롬프트에 추가되었습니다")
logger.info("샘플 가사 정보가 프롬프트에 추가되었습니다")
else:
print("샘플 가사가 없어 기본 프롬프트만 사용합니다")
logger.info("샘플 가사가 없어 기본 프롬프트만 사용합니다")
print(f"\n[최종 프롬프트 길이: {len(updated_prompt)} 자]\n")
logger.debug(f"[최종 프롬프트 길이: {len(updated_prompt)} 자]")
# 7. 모델에게 요청
generated_lyrics = await chatgpt_api.generate(prompt=updated_prompt)
@@ -763,10 +753,9 @@ async def make_automation(request: Request, conn: Connection):
:sample_song, :result_song, NOW()
);
"""
print("\n[insert_params 선택된 속성 확인]")
print(f"Categories: {selected_categories}")
print(f"Values: {selected_values}")
print()
logger.debug("[insert_params 선택된 속성 확인]")
logger.debug(f"Categories: {selected_categories}")
logger.debug(f"Values: {selected_values}")
# attr_category, attr_value
insert_params = {
@@ -792,9 +781,9 @@ async def make_automation(request: Request, conn: Connection):
await conn.execute(text(insert_query), insert_params)
await conn.commit()
print("결과 저장 완료")
logger.info("결과 저장 완료")
print("\n전체 결과 조회 중...")
logger.info("전체 결과 조회 중...")
# 9. 생성 결과 가져오기 (created_at 역순)
select_query = """
@@ -826,26 +815,20 @@ async def make_automation(request: Request, conn: Connection):
for row in all_results.fetchall()
]
print(f"전체 {len(results_list)}개의 결과 조회 완료\n")
logger.info(f"전체 {len(results_list)}개의 결과 조회 완료")
return results_list
except HTTPException:
raise
except SQLAlchemyError as e:
print(f"Database Error: {e}")
import traceback
traceback.print_exc()
logger.error(f"Database Error: {e}", exc_info=True)
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="데이터베이스 연결에 문제가 발생했습니다.",
)
except Exception as e:
print(f"Unexpected Error: {e}")
import traceback
traceback.print_exc()
logger.error(f"Unexpected Error: {e}", exc_info=True)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="서비스 처리 중 오류가 발생했습니다.",
+12 -48
View File
@@ -4,7 +4,6 @@ Video Background Tasks
영상 생성 관련 백그라운드 태스크를 정의합니다.
"""
import logging
import traceback
from pathlib import Path
@@ -16,9 +15,10 @@ from sqlalchemy.exc import SQLAlchemyError
from app.database.session import BackgroundSessionLocal
from app.video.models import Video
from app.utils.upload_blob_as_request import AzureBlobUploader
from app.utils.logger import get_logger
# 로거 설정
logger = logging.getLogger(__name__)
logger = get_logger("video")
# HTTP 요청 설정
REQUEST_TIMEOUT = 300.0 # 초 (영상은 용량이 크므로 5분)
@@ -66,20 +66,16 @@ async def _update_video_status(
video.result_movie_url = video_url
await session.commit()
logger.info(f"[Video] Status updated - task_id: {task_id}, status: {status}")
print(f"[Video] Status updated - task_id: {task_id}, status: {status}")
return True
else:
logger.warning(f"[Video] NOT FOUND in DB - task_id: {task_id}")
print(f"[Video] NOT FOUND in DB - task_id: {task_id}")
return False
except SQLAlchemyError as e:
logger.error(f"[Video] DB Error while updating status - task_id: {task_id}, error: {e}")
print(f"[Video] DB Error while updating status - task_id: {task_id}, error: {e}")
return False
except Exception as e:
logger.error(f"[Video] Unexpected error while updating status - task_id: {task_id}, error: {e}")
print(f"[Video] Unexpected error while updating status - task_id: {task_id}, error: {e}")
return False
@@ -97,14 +93,12 @@ async def _download_video(url: str, task_id: str) -> bytes:
httpx.HTTPError: 다운로드 실패 시
"""
logger.info(f"[VideoDownload] Downloading - task_id: {task_id}")
print(f"[VideoDownload] Downloading - task_id: {task_id}")
async with httpx.AsyncClient() as client:
response = await client.get(url, timeout=REQUEST_TIMEOUT)
response.raise_for_status()
logger.info(f"[VideoDownload] SUCCESS - task_id: {task_id}, size: {len(response.content)} bytes")
print(f"[VideoDownload] SUCCESS - task_id: {task_id}, size: {len(response.content)} bytes")
return response.content
@@ -121,7 +115,6 @@ async def download_and_upload_video_to_blob(
store_name: 저장할 파일명에 사용할 업체명
"""
logger.info(f"[download_and_upload_video_to_blob] START - task_id: {task_id}, store_name: {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:
@@ -136,12 +129,10 @@ async def download_and_upload_video_to_blob(
temp_dir = Path("media") / "temp" / task_id
temp_dir.mkdir(parents=True, exist_ok=True)
temp_file_path = temp_dir / file_name
logger.info(f"[download_and_upload_video_to_blob] Temp directory created - path: {temp_file_path}")
print(f"[download_and_upload_video_to_blob] Temp directory created - path: {temp_file_path}")
logger.debug(f"[download_and_upload_video_to_blob] Temp directory created - path: {temp_file_path}")
# 영상 파일 다운로드
logger.info(f"[download_and_upload_video_to_blob] Downloading video - task_id: {task_id}, url: {video_url}")
print(f"[download_and_upload_video_to_blob] Downloading video - task_id: {task_id}, url: {video_url}")
content = await _download_video(video_url, task_id)
@@ -149,7 +140,6 @@ async def download_and_upload_video_to_blob(
await f.write(content)
logger.info(f"[download_and_upload_video_to_blob] File downloaded - task_id: {task_id}, path: {temp_file_path}")
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)
@@ -161,29 +151,21 @@ async def download_and_upload_video_to_blob(
# SAS 토큰이 제외된 public_url 사용
blob_url = uploader.public_url
logger.info(f"[download_and_upload_video_to_blob] Uploaded to Blob - task_id: {task_id}, url: {blob_url}")
print(f"[download_and_upload_video_to_blob] Uploaded to Blob - task_id: {task_id}, url: {blob_url}")
# Video 테이블 업데이트
await _update_video_status(task_id, "completed", blob_url)
logger.info(f"[download_and_upload_video_to_blob] SUCCESS - task_id: {task_id}")
print(f"[download_and_upload_video_to_blob] SUCCESS - task_id: {task_id}")
except httpx.HTTPError as e:
logger.error(f"[download_and_upload_video_to_blob] DOWNLOAD ERROR - task_id: {task_id}, error: {e}")
print(f"[download_and_upload_video_to_blob] DOWNLOAD ERROR - task_id: {task_id}, error: {e}")
traceback.print_exc()
logger.error(f"[download_and_upload_video_to_blob] DOWNLOAD ERROR - task_id: {task_id}, error: {e}", exc_info=True)
await _update_video_status(task_id, "failed")
except SQLAlchemyError as e:
logger.error(f"[download_and_upload_video_to_blob] DB ERROR - task_id: {task_id}, error: {e}")
print(f"[download_and_upload_video_to_blob] DB ERROR - task_id: {task_id}, error: {e}")
traceback.print_exc()
logger.error(f"[download_and_upload_video_to_blob] DB ERROR - task_id: {task_id}, error: {e}", exc_info=True)
await _update_video_status(task_id, "failed")
except Exception as e:
logger.error(f"[download_and_upload_video_to_blob] EXCEPTION - task_id: {task_id}, error: {e}")
print(f"[download_and_upload_video_to_blob] EXCEPTION - task_id: {task_id}, error: {e}")
traceback.print_exc()
logger.error(f"[download_and_upload_video_to_blob] EXCEPTION - task_id: {task_id}, error: {e}", exc_info=True)
await _update_video_status(task_id, "failed")
finally:
@@ -191,11 +173,9 @@ async def download_and_upload_video_to_blob(
if temp_file_path and temp_file_path.exists():
try:
temp_file_path.unlink()
logger.info(f"[download_and_upload_video_to_blob] Temp file deleted - path: {temp_file_path}")
print(f"[download_and_upload_video_to_blob] Temp file deleted - path: {temp_file_path}")
logger.debug(f"[download_and_upload_video_to_blob] Temp file deleted - path: {temp_file_path}")
except Exception as e:
logger.warning(f"[download_and_upload_video_to_blob] Failed to delete temp file: {e}")
print(f"[download_and_upload_video_to_blob] Failed to delete temp file: {e}")
# 임시 디렉토리 삭제 시도
temp_dir = Path("media") / "temp" / task_id
@@ -219,7 +199,6 @@ async def download_and_upload_video_by_creatomate_render_id(
store_name: 저장할 파일명에 사용할 업체명
"""
logger.info(f"[download_and_upload_video_by_creatomate_render_id] START - creatomate_render_id: {creatomate_render_id}, store_name: {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
@@ -236,12 +215,10 @@ async def download_and_upload_video_by_creatomate_render_id(
if not video:
logger.warning(f"[download_and_upload_video_by_creatomate_render_id] Video NOT FOUND - creatomate_render_id: {creatomate_render_id}")
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
logger.info(f"[download_and_upload_video_by_creatomate_render_id] Video found - creatomate_render_id: {creatomate_render_id}, task_id: {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(
@@ -254,12 +231,10 @@ async def download_and_upload_video_by_creatomate_render_id(
temp_dir = Path("media") / "temp" / task_id
temp_dir.mkdir(parents=True, exist_ok=True)
temp_file_path = temp_dir / file_name
logger.info(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] Temp directory created - path: {temp_file_path}")
logger.debug(f"[download_and_upload_video_by_creatomate_render_id] Temp directory created - path: {temp_file_path}")
# 영상 파일 다운로드
logger.info(f"[download_and_upload_video_by_creatomate_render_id] Downloading video - creatomate_render_id: {creatomate_render_id}, url: {video_url}")
print(f"[download_and_upload_video_by_creatomate_render_id] Downloading video - creatomate_render_id: {creatomate_render_id}, url: {video_url}")
content = await _download_video(video_url, task_id)
@@ -267,7 +242,6 @@ async def download_and_upload_video_by_creatomate_render_id(
await f.write(content)
logger.info(f"[download_and_upload_video_by_creatomate_render_id] File downloaded - creatomate_render_id: {creatomate_render_id}, path: {temp_file_path}")
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)
@@ -279,7 +253,6 @@ async def download_and_upload_video_by_creatomate_render_id(
# SAS 토큰이 제외된 public_url 사용
blob_url = uploader.public_url
logger.info(f"[download_and_upload_video_by_creatomate_render_id] Uploaded to Blob - creatomate_render_id: {creatomate_render_id}, url: {blob_url}")
print(f"[download_and_upload_video_by_creatomate_render_id] Uploaded to Blob - creatomate_render_id: {creatomate_render_id}, url: {blob_url}")
# Video 테이블 업데이트
await _update_video_status(
@@ -289,26 +262,19 @@ async def download_and_upload_video_by_creatomate_render_id(
creatomate_render_id=creatomate_render_id,
)
logger.info(f"[download_and_upload_video_by_creatomate_render_id] SUCCESS - creatomate_render_id: {creatomate_render_id}")
print(f"[download_and_upload_video_by_creatomate_render_id] SUCCESS - creatomate_render_id: {creatomate_render_id}")
except httpx.HTTPError as e:
logger.error(f"[download_and_upload_video_by_creatomate_render_id] DOWNLOAD ERROR - creatomate_render_id: {creatomate_render_id}, error: {e}")
print(f"[download_and_upload_video_by_creatomate_render_id] DOWNLOAD ERROR - creatomate_render_id: {creatomate_render_id}, error: {e}")
traceback.print_exc()
logger.error(f"[download_and_upload_video_by_creatomate_render_id] DOWNLOAD ERROR - creatomate_render_id: {creatomate_render_id}, error: {e}", exc_info=True)
if task_id:
await _update_video_status(task_id, "failed", creatomate_render_id=creatomate_render_id)
except SQLAlchemyError as e:
logger.error(f"[download_and_upload_video_by_creatomate_render_id] DB ERROR - creatomate_render_id: {creatomate_render_id}, error: {e}")
print(f"[download_and_upload_video_by_creatomate_render_id] DB ERROR - creatomate_render_id: {creatomate_render_id}, error: {e}")
traceback.print_exc()
logger.error(f"[download_and_upload_video_by_creatomate_render_id] DB ERROR - creatomate_render_id: {creatomate_render_id}, error: {e}", exc_info=True)
if task_id:
await _update_video_status(task_id, "failed", creatomate_render_id=creatomate_render_id)
except Exception as e:
logger.error(f"[download_and_upload_video_by_creatomate_render_id] EXCEPTION - creatomate_render_id: {creatomate_render_id}, error: {e}")
print(f"[download_and_upload_video_by_creatomate_render_id] EXCEPTION - creatomate_render_id: {creatomate_render_id}, error: {e}")
traceback.print_exc()
logger.error(f"[download_and_upload_video_by_creatomate_render_id] EXCEPTION - creatomate_render_id: {creatomate_render_id}, error: {e}", exc_info=True)
if task_id:
await _update_video_status(task_id, "failed", creatomate_render_id=creatomate_render_id)
@@ -317,11 +283,9 @@ async def download_and_upload_video_by_creatomate_render_id(
if temp_file_path and temp_file_path.exists():
try:
temp_file_path.unlink()
logger.info(f"[download_and_upload_video_by_creatomate_render_id] Temp file deleted - path: {temp_file_path}")
print(f"[download_and_upload_video_by_creatomate_render_id] Temp file deleted - path: {temp_file_path}")
logger.debug(f"[download_and_upload_video_by_creatomate_render_id] Temp file deleted - path: {temp_file_path}")
except Exception as e:
logger.warning(f"[download_and_upload_video_by_creatomate_render_id] Failed to delete temp file: {e}")
print(f"[download_and_upload_video_by_creatomate_render_id] Failed to delete temp file: {e}")
# 임시 디렉토리 삭제 시도
if task_id: