add logger
This commit is contained in:
1 parent
1acd8846ab
commit
bf7b53c8e8
41 files changed
+1832
-694
No files matched your search
@@ -14,6 +14,10 @@ from app.lyric.schemas.lyrics_schema import (
|
||||
StoreData,
|
||||
)
|
||||
from app.utils.chatgpt_prompt import chatgpt_api
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
# 로거 설정
|
||||
logger = get_logger("lyric")
|
||||
|
||||
|
||||
async def get_store_info(conn: Connection) -> List[StoreData]:
|
||||
@@ -38,13 +42,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"Database 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 +73,13 @@ async def get_attribute(conn: Connection) -> List[AttributeData]:
|
||||
result.close()
|
||||
return all_attribute
|
||||
except SQLAlchemyError as e:
|
||||
print(e)
|
||||
logger.error(f"Database 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 +104,13 @@ async def get_attribute(conn: Connection) -> List[AttributeData]:
|
||||
result.close()
|
||||
return all_attribute
|
||||
except SQLAlchemyError as e:
|
||||
print(e)
|
||||
logger.error(f"Database 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 +136,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"Database 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 +166,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"Database 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 +196,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"Database 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 +214,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 +247,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 +255,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 +274,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 +287,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 +314,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 +333,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 +352,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 +399,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 +433,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 +487,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 +511,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 +542,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 +587,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 +615,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 +626,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 +655,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 +670,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 +680,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 +701,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 +717,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.info(f"[최종 프롬프트 길이: {len(updated_prompt)} 자]")
|
||||
|
||||
# 7. 모델에게 요청
|
||||
generated_lyrics = await chatgpt_api.generate(prompt=updated_prompt)
|
||||
@@ -763,10 +754,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 +782,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 +816,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="서비스 처리 중 오류가 발생했습니다.",
|
||||
|
||||
Reference in new issue
Block a user