emotion-chatbot-app / scripts /migrate_recommendations.py
hfexample's picture
Deploy clean snapshot of the repository
e221c83
import os
import sys
import logging
# --- ํ”„๋กœ์ ํŠธ ๋ฃจํŠธ ๊ฒฝ๋กœ ์„ค์ • ---
# ์ด ์Šคํฌ๋ฆฝํŠธ๊ฐ€ 'scripts' ํด๋” ์•ˆ์— ์žˆ์œผ๋ฏ€๋กœ, ๋ถ€๋ชจ ๋””๋ ‰ํ† ๋ฆฌ(ํ”„๋กœ์ ํŠธ ๋ฃจํŠธ)๋ฅผ ๊ฒฝ๋กœ์— ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค.
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if project_root not in sys.path:
sys.path.insert(0, project_root)
from src import create_app, db
from src.models import Diary
from src.main import generate_recommendation, recommender # generate_recommendation ์‚ฌ์šฉ
import datetime
# --- ๋กœ๊น… ์„ค์ • ---
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def migrate_diaries_with_recommendations():
"""
๊ธฐ์กด์˜ ๋ชจ๋“  ์ผ๊ธฐ๋ฅผ ์ˆœํšŒํ•˜๋ฉฐ 'recommendation' ํ•„๋“œ๊ฐ€ ๋น„์–ด์žˆ๋Š” ๊ฒฝ์šฐ,
์ƒˆ๋กœ์šด ์ถ”์ฒœ์„ ์ƒ์„ฑํ•˜์—ฌ ์ฑ„์›Œ๋„ฃ์Šต๋‹ˆ๋‹ค.
"""
app = create_app()
with app.app_context():
logging.info("๋ฐ์ดํ„ฐ ๋งˆ์ด๊ทธ๋ ˆ์ด์…˜์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค...")
# ์ถ”์ฒœ์ด ๋น„์–ด์žˆ๋Š” ๋ชจ๋“  ์ผ๊ธฐ๋ฅผ ์กฐํšŒํ•ฉ๋‹ˆ๋‹ค.
diaries_to_update = Diary.query.filter((Diary.recommendation == None) | (Diary.recommendation == '')).all()
if not diaries_to_update:
logging.info("์—…๋ฐ์ดํŠธํ•  ์ผ๊ธฐ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ๋ชจ๋“  ์ผ๊ธฐ์— ์ถ”์ฒœ์ด ์ด๋ฏธ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค.")
return
logging.info(f"์ด {len(diaries_to_update)}๊ฐœ์˜ ์ผ๊ธฐ๋ฅผ ์—…๋ฐ์ดํŠธํ•ฉ๋‹ˆ๋‹ค.")
updated_count = 0
failed_count = 0
for diary in diaries_to_update:
try:
logging.info(f"ID: {diary.id} ์ผ๊ธฐ ์ฒ˜๋ฆฌ ์ค‘...")
# 1. Gemini API๋ฅผ ํ†ตํ•ด ์ถ”์ฒœ ์ƒ์„ฑ ์‹œ๋„
recommendation_text = generate_recommendation(diary.content, diary.emotion)
# 2. ์‹คํŒจ ์‹œ, Recommender ํด๋ž˜์Šค๋กœ ๋Œ€์ฒด
if recommendation_text is None:
logging.warning(f"ID: {diary.id} - Gemini ์ถ”์ฒœ ์‹คํŒจ. Recommender ํด๋ž˜์Šค๋กœ ๋Œ€์ฒดํ•ฉ๋‹ˆ๋‹ค.")
su_yoong_recs = recommender.recommend(diary.emotion, '์ˆ˜์šฉ')
jeon_hwan_recs = recommender.recommend(diary.emotion, '์ „ํ™˜')
# diary_logic.js๊ฐ€ ํŒŒ์‹ฑํ•  ์ˆ˜ ์žˆ๋Š” ํ˜•์‹์œผ๋กœ ๋งŒ๋“ญ๋‹ˆ๋‹ค.
recommendation_text = f"## [์ˆ˜์šฉ]\n"
for rec in su_yoong_recs:
recommendation_text += f"* {rec}\n"
recommendation_text += f"\n## [์ „ํ™˜]\n"
for rec in jeon_hwan_recs:
recommendation_text += f"* {rec}\n"
# 3. ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ๋ฐ˜์˜
diary.recommendation = recommendation_text
updated_count += 1
logging.info(f"ID: {diary.id} - ์ถ”์ฒœ ์ƒ์„ฑ ์™„๋ฃŒ.")
except Exception as e:
failed_count += 1
logging.error(f"ID: {diary.id} ์ฒ˜๋ฆฌ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {e}")
if updated_count > 0:
try:
db.session.commit()
logging.info(f"์„ฑ๊ณต: {updated_count}๊ฐœ ์ผ๊ธฐ์˜ ์ถ”์ฒœ ์ •๋ณด ์—…๋ฐ์ดํŠธ ์™„๋ฃŒ.")
except Exception as e:
db.session.rollback()
logging.error(f"๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์ปค๋ฐ‹ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {e}")
if failed_count > 0:
logging.warning(f"์‹คํŒจ: {failed_count}๊ฐœ ์ผ๊ธฐ ์ฒ˜๋ฆฌ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ.")
logging.info("๋งˆ์ด๊ทธ๋ ˆ์ด์…˜ ์™„๋ฃŒ.")
if __name__ == '__main__':
migrate_diaries_with_recommendations()