Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
395b4dbbfb | ||
|
|
7da6ab6ec0 | ||
|
|
ce79cb5d04 | ||
|
|
d7a649809f | ||
|
|
41087b5fda | ||
|
|
6fba9c5362 | ||
|
|
d0334a5575 | ||
|
|
c705ce40f8 | ||
|
|
fa8ce3d071 |
No files matched your search
@@ -267,7 +267,7 @@ async def get_dashboard_stats(
|
|||||||
Dashboard.platform == "youtube",
|
Dashboard.platform == "youtube",
|
||||||
Dashboard.platform_user_id == social_account.platform_user_id,
|
Dashboard.platform_user_id == social_account.platform_user_id,
|
||||||
Dashboard.uploaded_at >= start_dt,
|
Dashboard.uploaded_at >= start_dt,
|
||||||
Dashboard.uploaded_at <= end_dt,
|
Dashboard.uploaded_at < today + timedelta(days=1),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
period_video_count = count_result.scalar() or 0
|
period_video_count = count_result.scalar() or 0
|
||||||
@@ -451,7 +451,7 @@ async def get_dashboard_stats(
|
|||||||
# 12. 업로드 영상 수 및 trend 주입 (캐시 저장 후 — 항상 DB에서 직접 집계)
|
# 12. 업로드 영상 수 및 trend 주입 (캐시 저장 후 — 항상 DB에서 직접 집계)
|
||||||
for metric in dashboard_data.content_metrics:
|
for metric in dashboard_data.content_metrics:
|
||||||
if metric.id == "uploaded-videos":
|
if metric.id == "uploaded-videos":
|
||||||
metric.value = str(period_video_count)
|
metric.value = float(period_video_count)
|
||||||
video_trend = float(period_video_count - prev_period_video_count)
|
video_trend = float(period_video_count - prev_period_video_count)
|
||||||
metric.trend = video_trend
|
metric.trend = video_trend
|
||||||
metric.trend_direction = "up" if video_trend > 0 else ("down" if video_trend < 0 else "-")
|
metric.trend_direction = "up" if video_trend > 0 else ("down" if video_trend < 0 else "-")
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ YouTube Analytics 데이터 가공 프로세서
|
|||||||
YouTube Analytics API의 원본 데이터를 프론트엔드용 Pydantic 스키마로 변환합니다.
|
YouTube Analytics API의 원본 데이터를 프론트엔드용 Pydantic 스키마로 변환합니다.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
from collections import defaultdict
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from typing import Any, Literal
|
from typing import Any, Literal
|
||||||
|
|
||||||
@@ -19,6 +20,46 @@ from app.utils.logger import get_logger
|
|||||||
|
|
||||||
logger = get_logger("dashboard")
|
logger = get_logger("dashboard")
|
||||||
|
|
||||||
|
_COUNTRY_CODE_MAP: dict[str, str] = {
|
||||||
|
"KR": "대한민국",
|
||||||
|
"US": "미국",
|
||||||
|
"JP": "일본",
|
||||||
|
"CN": "중국",
|
||||||
|
"GB": "영국",
|
||||||
|
"DE": "독일",
|
||||||
|
"FR": "프랑스",
|
||||||
|
"CA": "캐나다",
|
||||||
|
"AU": "호주",
|
||||||
|
"IN": "인도",
|
||||||
|
"ID": "인도네시아",
|
||||||
|
"TH": "태국",
|
||||||
|
"VN": "베트남",
|
||||||
|
"PH": "필리핀",
|
||||||
|
"MY": "말레이시아",
|
||||||
|
"SG": "싱가포르",
|
||||||
|
"TW": "대만",
|
||||||
|
"HK": "홍콩",
|
||||||
|
"BR": "브라질",
|
||||||
|
"MX": "멕시코",
|
||||||
|
"NL": "네덜란드",
|
||||||
|
"BE": "벨기에",
|
||||||
|
"SE": "스웨덴",
|
||||||
|
"NO": "노르웨이",
|
||||||
|
"FI": "핀란드",
|
||||||
|
"DK": "덴마크",
|
||||||
|
"IE": "아일랜드",
|
||||||
|
"PL": "폴란드",
|
||||||
|
"CZ": "체코",
|
||||||
|
"RO": "루마니아",
|
||||||
|
"HU": "헝가리",
|
||||||
|
"SK": "슬로바키아",
|
||||||
|
"SI": "슬로베니아",
|
||||||
|
"HR": "크로아티아",
|
||||||
|
"GR": "그리스",
|
||||||
|
"PT": "포르투갈",
|
||||||
|
"ES": "스페인",
|
||||||
|
"IT": "이탈리아",
|
||||||
|
}
|
||||||
|
|
||||||
class DataProcessor:
|
class DataProcessor:
|
||||||
"""YouTube Analytics 데이터 가공 프로세서
|
"""YouTube Analytics 데이터 가공 프로세서
|
||||||
@@ -90,6 +131,7 @@ class DataProcessor:
|
|||||||
monthly_data = self._merge_monthly_data(
|
monthly_data = self._merge_monthly_data(
|
||||||
raw_data.get("trend_recent", {}),
|
raw_data.get("trend_recent", {}),
|
||||||
raw_data.get("trend_previous", {}),
|
raw_data.get("trend_previous", {}),
|
||||||
|
end_date=end_date,
|
||||||
)
|
)
|
||||||
daily_data: list[DailyData] = []
|
daily_data: list[DailyData] = []
|
||||||
else: # mode == "day"
|
else: # mode == "day"
|
||||||
@@ -271,49 +313,49 @@ class DataProcessor:
|
|||||||
self,
|
self,
|
||||||
data_recent: dict[str, Any],
|
data_recent: dict[str, Any],
|
||||||
data_previous: dict[str, Any],
|
data_previous: dict[str, Any],
|
||||||
|
end_date: str = "",
|
||||||
) -> list[MonthlyData]:
|
) -> list[MonthlyData]:
|
||||||
"""최근 12개월과 이전 12개월의 월별 데이터를 병합
|
"""최근 12개월과 이전 12개월의 월별 데이터를 병합
|
||||||
|
|
||||||
최근 12개월 대비 이전 12개월의 월별 조회수 비교 차트를 위한 데이터를 생성합니다.
|
end_date 기준 12개월을 명시 생성하여 API가 반환하지 않은 월(당월 등)도 0으로 포함합니다.
|
||||||
실제 API 응답의 월 데이터를 기준으로 매핑합니다.
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
data_recent: 최근 12개월 월별 조회수 데이터
|
data_recent: 최근 12개월 월별 조회수 데이터
|
||||||
rows = [["2026-01", 150000], ["2026-02", 180000], ...]
|
rows = [["2026-01", 150000], ["2026-02", 180000], ...]
|
||||||
data_previous: 이전 12개월 월별 조회수 데이터
|
data_previous: 이전 12개월 월별 조회수 데이터
|
||||||
rows = [["2025-01", 120000], ["2025-02", 140000], ...]
|
rows = [["2025-01", 120000], ["2025-02", 140000], ...]
|
||||||
|
end_date: 기준 종료일 (YYYY-MM-DD). 미전달 시 오늘 사용
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
list[MonthlyData]: 월별 비교 데이터 (최대 12개)
|
list[MonthlyData]: 월별 비교 데이터 (12개, API 미반환 월은 0)
|
||||||
"""
|
"""
|
||||||
logger.debug("[DataProcessor._merge_monthly_data] START")
|
logger.debug("[DataProcessor._merge_monthly_data] START")
|
||||||
|
|
||||||
rows_recent = data_recent.get("rows", [])
|
rows_recent = data_recent.get("rows", [])
|
||||||
rows_previous = data_previous.get("rows", [])
|
rows_previous = data_previous.get("rows", [])
|
||||||
|
|
||||||
# 월별 맵 생성: {"2025-02": 150000, "2025-03": 180000}
|
|
||||||
map_recent = {row[0]: row[1] for row in rows_recent if len(row) >= 2}
|
map_recent = {row[0]: row[1] for row in rows_recent if len(row) >= 2}
|
||||||
map_previous = {row[0]: row[1] for row in rows_previous if len(row) >= 2}
|
map_previous = {row[0]: row[1] for row in rows_previous if len(row) >= 2}
|
||||||
|
|
||||||
# 최근 기간의 월 키만 기준으로 정렬 (24개 합집합 방지)
|
# end_date 기준 12개월 명시 생성 (API 미반환 당월도 0으로 포함)
|
||||||
# 각 월의 이전 연도 키는 1년 전으로 계산: "2025-02" → "2024-02"
|
if end_date:
|
||||||
recent_months = sorted(map_recent.keys())
|
end_dt = datetime.strptime(end_date, "%Y-%m-%d")
|
||||||
|
else:
|
||||||
|
end_dt = datetime.today()
|
||||||
|
|
||||||
# 월별 데이터 생성
|
|
||||||
result = []
|
result = []
|
||||||
for month_key in recent_months:
|
for i in range(11, -1, -1):
|
||||||
year, month = month_key.split("-")
|
m = end_dt.month - i
|
||||||
month_num = int(month)
|
y = end_dt.year
|
||||||
month_label = f"{month_num}월"
|
if m <= 0:
|
||||||
|
m += 12
|
||||||
# 이전 연도 동일 월: "2025-02" → "2024-02"
|
y -= 1
|
||||||
prev_year_key = f"{int(year) - 1}-{month}"
|
month_key = f"{y}-{m:02d}"
|
||||||
|
|
||||||
result.append(
|
result.append(
|
||||||
MonthlyData(
|
MonthlyData(
|
||||||
month=month_label,
|
month=f"{m}월",
|
||||||
this_year=map_recent.get(month_key, 0),
|
this_year=map_recent.get(month_key, 0),
|
||||||
last_year=map_previous.get(prev_year_key, 0),
|
last_year=map_previous.get(f"{y - 1}-{m:02d}", 0),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -437,9 +479,17 @@ class DataProcessor:
|
|||||||
if gender in gender_map_f:
|
if gender in gender_map_f:
|
||||||
gender_map_f[gender] += viewer_pct
|
gender_map_f[gender] += viewer_pct
|
||||||
|
|
||||||
|
# 연령대 5개로 통합: 13-17+18-24 → 13-24, 55-64+65- → 55+
|
||||||
|
merged_age: dict[str, float] = {
|
||||||
|
"13-24": age_map.get("13-17", 0.0) + age_map.get("18-24", 0.0),
|
||||||
|
"25-34": age_map.get("25-34", 0.0),
|
||||||
|
"35-44": age_map.get("35-44", 0.0),
|
||||||
|
"45-54": age_map.get("45-54", 0.0),
|
||||||
|
"55+": age_map.get("55-64", 0.0) + age_map.get("65-", 0.0),
|
||||||
|
}
|
||||||
age_groups = [
|
age_groups = [
|
||||||
{"label": age, "percentage": int(round(pct))}
|
{"label": age, "percentage": int(round(pct))}
|
||||||
for age, pct in sorted(age_map.items())
|
for age, pct in merged_age.items()
|
||||||
]
|
]
|
||||||
gender_map = {k: int(round(v)) for k, v in gender_map_f.items()}
|
gender_map = {k: int(round(v)) for k, v in gender_map_f.items()}
|
||||||
|
|
||||||
@@ -447,15 +497,17 @@ class DataProcessor:
|
|||||||
geo_rows = geography_data.get("rows", [])
|
geo_rows = geography_data.get("rows", [])
|
||||||
total_geo_views = sum(row[1] for row in geo_rows if len(row) >= 2)
|
total_geo_views = sum(row[1] for row in geo_rows if len(row) >= 2)
|
||||||
|
|
||||||
|
merged_geo: defaultdict[str, int] = defaultdict(int)
|
||||||
|
for row in geo_rows:
|
||||||
|
if len(row) >= 2:
|
||||||
|
merged_geo[self._translate_country_code(row[0])] += row[1]
|
||||||
|
|
||||||
top_regions = [
|
top_regions = [
|
||||||
{
|
{
|
||||||
"region": self._translate_country_code(row[0]),
|
"region": region,
|
||||||
"percentage": int(
|
"percentage": int((views / total_geo_views * 100) if total_geo_views > 0 else 0),
|
||||||
(row[1] / total_geo_views * 100) if total_geo_views > 0 else 0
|
|
||||||
),
|
|
||||||
}
|
}
|
||||||
for row in geo_rows[:5] # 상위 5개
|
for region, views in sorted(merged_geo.items(), key=lambda x: x[1], reverse=True)[:5]
|
||||||
if len(row) >= 2
|
|
||||||
]
|
]
|
||||||
|
|
||||||
logger.debug(
|
logger.debug(
|
||||||
@@ -487,26 +539,4 @@ class DataProcessor:
|
|||||||
>>> _translate_country_code("US")
|
>>> _translate_country_code("US")
|
||||||
"미국"
|
"미국"
|
||||||
"""
|
"""
|
||||||
country_map = {
|
return _COUNTRY_CODE_MAP.get(code, "기타")
|
||||||
"KR": "대한민국",
|
|
||||||
"US": "미국",
|
|
||||||
"JP": "일본",
|
|
||||||
"CN": "중국",
|
|
||||||
"GB": "영국",
|
|
||||||
"DE": "독일",
|
|
||||||
"FR": "프랑스",
|
|
||||||
"CA": "캐나다",
|
|
||||||
"AU": "호주",
|
|
||||||
"IN": "인도",
|
|
||||||
"ID": "인도네시아",
|
|
||||||
"TH": "태국",
|
|
||||||
"VN": "베트남",
|
|
||||||
"PH": "필리핀",
|
|
||||||
"MY": "말레이시아",
|
|
||||||
"SG": "싱가포르",
|
|
||||||
"TW": "대만",
|
|
||||||
"HK": "홍콩",
|
|
||||||
"BR": "브라질",
|
|
||||||
"MX": "멕시코",
|
|
||||||
}
|
|
||||||
return country_map.get(code, code)
|
|
||||||
@@ -6,6 +6,7 @@ from sqlalchemy.orm import DeclarativeBase
|
|||||||
|
|
||||||
from app.utils.logger import get_logger
|
from app.utils.logger import get_logger
|
||||||
from config import db_settings
|
from config import db_settings
|
||||||
|
import traceback
|
||||||
|
|
||||||
logger = get_logger("database")
|
logger = get_logger("database")
|
||||||
|
|
||||||
@@ -170,6 +171,7 @@ async def get_background_session() -> AsyncGenerator[AsyncSession, None]:
|
|||||||
f"error: {type(e).__name__}: {e}, "
|
f"error: {type(e).__name__}: {e}, "
|
||||||
f"duration: {(time.perf_counter() - start_time)*1000:.1f}ms"
|
f"duration: {(time.perf_counter() - start_time)*1000:.1f}ms"
|
||||||
)
|
)
|
||||||
|
logger.debug(traceback.format_exc())
|
||||||
raise e
|
raise e
|
||||||
finally:
|
finally:
|
||||||
total_time = time.perf_counter() - start_time
|
total_time = time.perf_counter() - start_time
|
||||||
|
|||||||
@@ -300,6 +300,12 @@ class MarketingIntel(Base):
|
|||||||
comment="마케팅 인텔리전스 결과물",
|
comment="마케팅 인텔리전스 결과물",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
subtitle : Mapped[dict[str, Any]] = mapped_column(
|
||||||
|
JSON,
|
||||||
|
nullable=True,
|
||||||
|
comment="자막 정보 생성 결과물",
|
||||||
|
)
|
||||||
|
|
||||||
created_at: Mapped[datetime] = mapped_column(
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
DateTime,
|
DateTime,
|
||||||
nullable=False,
|
nullable=False,
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ from app.lyric.schemas.lyric import (
|
|||||||
LyricListItem,
|
LyricListItem,
|
||||||
LyricStatusResponse,
|
LyricStatusResponse,
|
||||||
)
|
)
|
||||||
from app.lyric.worker.lyric_task import generate_lyric_background
|
from app.lyric.worker.lyric_task import generate_lyric_background, generate_subtitle_background
|
||||||
from app.utils.chatgpt_prompt import ChatgptService
|
from app.utils.chatgpt_prompt import ChatgptService
|
||||||
from app.utils.logger import get_logger
|
from app.utils.logger import get_logger
|
||||||
from app.utils.pagination import PaginatedResponse, get_paginated
|
from app.utils.pagination import PaginatedResponse, get_paginated
|
||||||
@@ -351,7 +351,7 @@ async def generate_lyric(
|
|||||||
# ========== Step 4: 백그라운드 태스크 스케줄링 ==========
|
# ========== Step 4: 백그라운드 태스크 스케줄링 ==========
|
||||||
step4_start = time.perf_counter()
|
step4_start = time.perf_counter()
|
||||||
logger.debug(f"[generate_lyric] Step 4: 백그라운드 태스크 스케줄링...")
|
logger.debug(f"[generate_lyric] Step 4: 백그라운드 태스크 스케줄링...")
|
||||||
|
orientation = request_body.orientation
|
||||||
background_tasks.add_task(
|
background_tasks.add_task(
|
||||||
generate_lyric_background,
|
generate_lyric_background,
|
||||||
task_id=task_id,
|
task_id=task_id,
|
||||||
@@ -359,6 +359,12 @@ async def generate_lyric(
|
|||||||
lyric_input_data=lyric_input_data,
|
lyric_input_data=lyric_input_data,
|
||||||
lyric_id=lyric.id,
|
lyric_id=lyric.id,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
background_tasks.add_task(
|
||||||
|
generate_subtitle_background,
|
||||||
|
orientation = orientation,
|
||||||
|
task_id=task_id
|
||||||
|
)
|
||||||
|
|
||||||
step4_elapsed = (time.perf_counter() - step4_start) * 1000
|
step4_elapsed = (time.perf_counter() - step4_start) * 1000
|
||||||
logger.debug(f"[generate_lyric] Step 4 완료 ({step4_elapsed:.1f}ms)")
|
logger.debug(f"[generate_lyric] Step 4 완료 ({step4_elapsed:.1f}ms)")
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ Lyric API Schemas
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Optional
|
from typing import Optional, Literal
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, Field
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
|
|
||||||
@@ -42,7 +42,8 @@ class GenerateLyricRequest(BaseModel):
|
|||||||
"region": "군산",
|
"region": "군산",
|
||||||
"detail_region_info": "군산 신흥동 말랭이 마을",
|
"detail_region_info": "군산 신흥동 말랭이 마을",
|
||||||
"language": "Korean",
|
"language": "Korean",
|
||||||
"m_id" : 1
|
"m_id" : 1,
|
||||||
|
"orientation" : "vertical"
|
||||||
}
|
}
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -54,7 +55,8 @@ class GenerateLyricRequest(BaseModel):
|
|||||||
"region": "군산",
|
"region": "군산",
|
||||||
"detail_region_info": "군산 신흥동 말랭이 마을",
|
"detail_region_info": "군산 신흥동 말랭이 마을",
|
||||||
"language": "Korean",
|
"language": "Korean",
|
||||||
"m_id" : 1
|
"m_id" : 1,
|
||||||
|
"orientation" : "vertical"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
@@ -68,7 +70,11 @@ class GenerateLyricRequest(BaseModel):
|
|||||||
language: str = Field(
|
language: str = Field(
|
||||||
default="Korean",
|
default="Korean",
|
||||||
description="가사 출력 언어 (Korean, English, Chinese, Japanese, Thai, Vietnamese)",
|
description="가사 출력 언어 (Korean, English, Chinese, Japanese, Thai, Vietnamese)",
|
||||||
)
|
),
|
||||||
|
orientation: Literal["horizontal", "vertical"] = Field(
|
||||||
|
default="vertical",
|
||||||
|
description="영상 방향 (horizontal: 가로형, vertical: 세로형)",
|
||||||
|
),
|
||||||
m_id : Optional[int] = Field(None, description="마케팅 인텔리전스 ID 값")
|
m_id : Optional[int] = Field(None, description="마케팅 인텔리전스 ID 값")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -7,11 +7,15 @@ Lyric Background Tasks
|
|||||||
import traceback
|
import traceback
|
||||||
|
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from sqlalchemy.exc import SQLAlchemyError
|
from sqlalchemy.exc import SQLAlchemyError
|
||||||
|
|
||||||
from app.database.session import BackgroundSessionLocal
|
from app.database.session import BackgroundSessionLocal
|
||||||
|
from app.home.models import Image, Project, MarketingIntel
|
||||||
from app.lyric.models import Lyric
|
from app.lyric.models import Lyric
|
||||||
from app.utils.chatgpt_prompt import ChatgptService, ChatGPTResponseError
|
from app.utils.chatgpt_prompt import ChatgptService, ChatGPTResponseError
|
||||||
|
from app.utils.subtitles import SubtitleContentsGenerator
|
||||||
|
from app.utils.creatomate import CreatomateService
|
||||||
from app.utils.prompts.prompts import Prompt
|
from app.utils.prompts.prompts import Prompt
|
||||||
from app.utils.logger import get_logger
|
from app.utils.logger import get_logger
|
||||||
|
|
||||||
@@ -158,3 +162,55 @@ async def generate_lyric_background(
|
|||||||
elapsed = (time.perf_counter() - task_start) * 1000
|
elapsed = (time.perf_counter() - task_start) * 1000
|
||||||
logger.error(f"[generate_lyric_background] EXCEPTION - task_id: {task_id}, error: {e} ({elapsed:.1f}ms)", exc_info=True)
|
logger.error(f"[generate_lyric_background] EXCEPTION - task_id: {task_id}, error: {e} ({elapsed:.1f}ms)", exc_info=True)
|
||||||
await _update_lyric_status(task_id, "failed", f"Error: {str(e)}", lyric_id)
|
await _update_lyric_status(task_id, "failed", f"Error: {str(e)}", lyric_id)
|
||||||
|
|
||||||
|
async def generate_subtitle_background(
|
||||||
|
orientation: str,
|
||||||
|
task_id: str
|
||||||
|
) -> None:
|
||||||
|
logger.info(f"[generate_subtitle_background] task_id: {task_id}, {orientation}")
|
||||||
|
creatomate_service = CreatomateService(orientation=orientation)
|
||||||
|
template = await creatomate_service.get_one_template_data_async(creatomate_service.template_id)
|
||||||
|
pitchings = creatomate_service.extract_text_format_from_template(template)
|
||||||
|
|
||||||
|
subtitle_generator = SubtitleContentsGenerator()
|
||||||
|
|
||||||
|
async with BackgroundSessionLocal() as session:
|
||||||
|
project_result = await session.execute(
|
||||||
|
select(Project)
|
||||||
|
.where(Project.task_id == task_id)
|
||||||
|
.order_by(Project.created_at.desc())
|
||||||
|
.limit(1)
|
||||||
|
)
|
||||||
|
project = project_result.scalar_one_or_none()
|
||||||
|
marketing_result = await session.execute(
|
||||||
|
select(MarketingIntel).where(MarketingIntel.id == project.marketing_intelligence)
|
||||||
|
)
|
||||||
|
marketing_intelligence = marketing_result.scalar_one_or_none()
|
||||||
|
|
||||||
|
store_address = project.detail_region_info
|
||||||
|
customer_name = project.store_name
|
||||||
|
logger.info(f"[generate_subtitle_background] customer_name: {customer_name}, {store_address}")
|
||||||
|
|
||||||
|
generated_subtitles = await subtitle_generator.generate_subtitle_contents(
|
||||||
|
marketing_intelligence = marketing_intelligence.intel_result,
|
||||||
|
pitching_label_list = pitchings,
|
||||||
|
customer_name = customer_name,
|
||||||
|
detail_region_info = store_address,
|
||||||
|
)
|
||||||
|
pitching_output_list = generated_subtitles.pitching_results
|
||||||
|
|
||||||
|
subtitle_modifications = {pitching_output.pitching_tag : pitching_output.pitching_data for pitching_output in pitching_output_list}
|
||||||
|
logger.info(f"[generate_subtitle_background] subtitle_modifications: {subtitle_modifications}")
|
||||||
|
|
||||||
|
async with BackgroundSessionLocal() as session:
|
||||||
|
marketing_result = await session.execute(
|
||||||
|
select(MarketingIntel).where(MarketingIntel.id == project.marketing_intelligence)
|
||||||
|
)
|
||||||
|
marketing_intelligence = marketing_result.scalar_one_or_none()
|
||||||
|
marketing_intelligence.subtitle = subtitle_modifications
|
||||||
|
await session.commit()
|
||||||
|
logger.info(f"[generate_subtitle_background] task_id: {task_id} DONE")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
return
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
"""
|
||||||
|
내부 전용 소셜 업로드 API
|
||||||
|
|
||||||
|
스케줄러 서버에서만 호출하는 내부 엔드포인트입니다.
|
||||||
|
X-Internal-Secret 헤더로 인증합니다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from fastapi import APIRouter, BackgroundTasks, Header, HTTPException, status
|
||||||
|
|
||||||
|
from app.social.worker.upload_task import process_social_upload
|
||||||
|
from config import internal_settings
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/internal/social", tags=["Internal"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/upload/{upload_id}",
|
||||||
|
summary="[내부] 예약 업로드 실행",
|
||||||
|
description="스케줄러 서버에서 호출하는 내부 전용 엔드포인트입니다.",
|
||||||
|
)
|
||||||
|
async def trigger_scheduled_upload(
|
||||||
|
upload_id: int,
|
||||||
|
background_tasks: BackgroundTasks,
|
||||||
|
x_internal_secret: str = Header(...),
|
||||||
|
) -> dict:
|
||||||
|
if x_internal_secret != internal_settings.INTERNAL_SECRET_KEY:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Invalid internal secret",
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info(f"[INTERNAL] 예약 업로드 실행 - upload_id: {upload_id}")
|
||||||
|
background_tasks.add_task(process_social_upload, upload_id)
|
||||||
|
|
||||||
|
return {"success": True, "upload_id": upload_id, "message": "업로드 작업이 시작되었습니다."}
|
||||||
@@ -238,7 +238,7 @@ async def get_account_by_platform(
|
|||||||
|
|
||||||
raise SocialAccountNotFoundError(platform=platform.value)
|
raise SocialAccountNotFoundError(platform=platform.value)
|
||||||
|
|
||||||
return social_account_service._to_response(account)
|
return social_account_service.to_response(account)
|
||||||
|
|
||||||
|
|
||||||
@router.delete(
|
@router.delete(
|
||||||
|
|||||||
@@ -1,131 +1,37 @@
|
|||||||
|
"""
|
||||||
|
소셜 SEO API 라우터
|
||||||
|
|
||||||
import logging, json
|
SEO 관련 엔드포인트를 제공합니다.
|
||||||
|
비즈니스 로직은 SeoService에 위임합니다.
|
||||||
|
"""
|
||||||
|
|
||||||
from redis.asyncio import Redis
|
import logging
|
||||||
|
|
||||||
from config import social_oauth_settings, db_settings
|
from fastapi import APIRouter, Depends
|
||||||
from app.social.constants import YOUTUBE_SEO_HASH
|
|
||||||
from sqlalchemy import select, func
|
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from app.social.schemas import (
|
|
||||||
YoutubeDescriptionRequest,
|
|
||||||
YoutubeDescriptionResponse,
|
|
||||||
)
|
|
||||||
|
|
||||||
from app.database.session import get_session
|
from app.database.session import get_session
|
||||||
|
from app.social.schemas import YoutubeDescriptionRequest, YoutubeDescriptionResponse
|
||||||
|
from app.social.services import seo_service
|
||||||
from app.user.dependencies import get_current_user
|
from app.user.dependencies import get_current_user
|
||||||
from app.user.models import User
|
from app.user.models import User
|
||||||
from app.home.models import Project, MarketingIntel
|
|
||||||
from fastapi import APIRouter, BackgroundTasks, Depends, Query
|
|
||||||
from fastapi import HTTPException, status
|
|
||||||
from app.utils.prompts.prompts import yt_upload_prompt
|
|
||||||
from app.utils.chatgpt_prompt import ChatgptService, ChatGPTResponseError
|
|
||||||
|
|
||||||
redis_seo_client = Redis(
|
|
||||||
host=db_settings.REDIS_HOST,
|
|
||||||
port=db_settings.REDIS_PORT,
|
|
||||||
db=0,
|
|
||||||
decode_responses=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
router = APIRouter(prefix="/seo", tags=["Social SEO"])
|
router = APIRouter(prefix="/seo", tags=["Social SEO"])
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
@router.post(
|
||||||
"/youtube",
|
"/youtube",
|
||||||
response_model=YoutubeDescriptionResponse,
|
response_model=YoutubeDescriptionResponse,
|
||||||
summary="유튜브 SEO descrption 생성",
|
summary="유튜브 SEO description 생성",
|
||||||
description="유튜브 업로드 시 사용할 descrption을 SEO 적용하여 생성",
|
description="유튜브 업로드 시 사용할 description을 SEO 적용하여 생성",
|
||||||
)
|
)
|
||||||
async def youtube_seo_description(
|
async def youtube_seo_description(
|
||||||
request_body: YoutubeDescriptionRequest,
|
request_body: YoutubeDescriptionRequest,
|
||||||
current_user: User = Depends(get_current_user),
|
current_user: User = Depends(get_current_user),
|
||||||
session: AsyncSession = Depends(get_session),
|
session: AsyncSession = Depends(get_session),
|
||||||
) -> YoutubeDescriptionResponse:
|
) -> YoutubeDescriptionResponse:
|
||||||
|
return await seo_service.get_youtube_seo_description(
|
||||||
# TODO : 나중에 Session Task_id 검증 미들웨어 만들면 추가해주세요.
|
request_body.task_id, current_user, session
|
||||||
|
|
||||||
logger.info(
|
|
||||||
f"[youtube_seo_description] Try Cache - user: {current_user.user_uuid} / task_id : {request_body.task_id}"
|
|
||||||
)
|
)
|
||||||
cached = await get_yt_seo_in_redis(request_body.task_id)
|
|
||||||
if cached: # redis hit
|
|
||||||
return cached
|
|
||||||
|
|
||||||
logger.info(
|
|
||||||
f"[youtube_seo_description] Cache miss - user: {current_user.user_uuid} "
|
|
||||||
)
|
|
||||||
updated_seo = await make_youtube_seo_description(request_body.task_id, current_user, session)
|
|
||||||
await set_yt_seo_in_redis(request_body.task_id, updated_seo)
|
|
||||||
|
|
||||||
return updated_seo
|
|
||||||
|
|
||||||
async def make_youtube_seo_description(
|
|
||||||
task_id: str,
|
|
||||||
current_user: User,
|
|
||||||
session: AsyncSession,
|
|
||||||
) -> YoutubeDescriptionResponse:
|
|
||||||
|
|
||||||
logger.info(
|
|
||||||
f"[make_youtube_seo_description] START - user: {current_user.user_uuid} "
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
project_query = await session.execute(
|
|
||||||
select(Project)
|
|
||||||
.where(
|
|
||||||
Project.task_id == task_id,
|
|
||||||
Project.user_uuid == current_user.user_uuid)
|
|
||||||
.order_by(Project.created_at.desc())
|
|
||||||
.limit(1)
|
|
||||||
)
|
|
||||||
|
|
||||||
project = project_query.scalar_one_or_none()
|
|
||||||
marketing_query = await session.execute(
|
|
||||||
select(MarketingIntel)
|
|
||||||
.where(MarketingIntel.id == project.marketing_intelligence)
|
|
||||||
)
|
|
||||||
marketing_intelligence = marketing_query.scalar_one_or_none()
|
|
||||||
|
|
||||||
hashtags = marketing_intelligence.intel_result["target_keywords"]
|
|
||||||
|
|
||||||
yt_seo_input_data = {
|
|
||||||
"customer_name" : project.store_name,
|
|
||||||
"detail_region_info" : project.detail_region_info,
|
|
||||||
"marketing_intelligence_summary" : json.dumps(marketing_intelligence.intel_result, ensure_ascii=False),
|
|
||||||
"language" : project.language,
|
|
||||||
"target_keywords" : hashtags
|
|
||||||
}
|
|
||||||
chatgpt = ChatgptService(timeout = 180)
|
|
||||||
yt_seo_output = await chatgpt.generate_structured_output(yt_upload_prompt, yt_seo_input_data)
|
|
||||||
result_dict = {
|
|
||||||
"title" : yt_seo_output.title,
|
|
||||||
"description" : yt_seo_output.description,
|
|
||||||
"keywords": hashtags
|
|
||||||
}
|
|
||||||
|
|
||||||
result = YoutubeDescriptionResponse(**result_dict)
|
|
||||||
return result
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"[youtube_seo_description] EXCEPTION - error: {e}")
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=500,
|
|
||||||
detail=f"유튜브 SEO 생성에 실패했습니다. : {str(e)}",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
async def get_yt_seo_in_redis(task_id:str) -> YoutubeDescriptionResponse | None:
|
|
||||||
field = f"task_id:{task_id}"
|
|
||||||
yt_seo_info = await redis_seo_client.hget(YOUTUBE_SEO_HASH, field)
|
|
||||||
if yt_seo_info:
|
|
||||||
yt_seo = json.loads(yt_seo_info)
|
|
||||||
else:
|
|
||||||
return None
|
|
||||||
return YoutubeDescriptionResponse(**yt_seo)
|
|
||||||
|
|
||||||
async def set_yt_seo_in_redis(task_id:str, yt_seo : YoutubeDescriptionResponse) -> None:
|
|
||||||
field = f"task_id:{task_id}"
|
|
||||||
yt_seo_info = json.dumps(yt_seo.model_dump(), ensure_ascii=False)
|
|
||||||
await redis_seo_client.hsetex(YOUTUBE_SEO_HASH, field, yt_seo_info, ex=3600)
|
|
||||||
return
|
|
||||||
|
|
||||||
@@ -2,38 +2,34 @@
|
|||||||
소셜 업로드 API 라우터
|
소셜 업로드 API 라우터
|
||||||
|
|
||||||
소셜 미디어 영상 업로드 관련 엔드포인트를 제공합니다.
|
소셜 미디어 영상 업로드 관련 엔드포인트를 제공합니다.
|
||||||
|
비즈니스 로직은 SocialUploadService에 위임합니다.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging, json
|
import logging
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, BackgroundTasks, Depends, Query
|
from fastapi import APIRouter, BackgroundTasks, Depends, Query
|
||||||
from fastapi import HTTPException, status
|
|
||||||
from sqlalchemy import select, func
|
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from app.database.session import get_session
|
from app.database.session import get_session
|
||||||
from app.social.constants import SocialPlatform, UploadStatus
|
from app.social.constants import SocialPlatform
|
||||||
from app.social.exceptions import SocialAccountNotFoundError, VideoNotFoundError
|
|
||||||
from app.social.models import SocialUpload
|
|
||||||
from app.social.schemas import (
|
from app.social.schemas import (
|
||||||
MessageResponse,
|
MessageResponse,
|
||||||
SocialUploadHistoryItem,
|
|
||||||
SocialUploadHistoryResponse,
|
SocialUploadHistoryResponse,
|
||||||
SocialUploadRequest,
|
SocialUploadRequest,
|
||||||
SocialUploadResponse,
|
SocialUploadResponse,
|
||||||
SocialUploadStatusResponse,
|
SocialUploadStatusResponse,
|
||||||
)
|
)
|
||||||
from app.social.services import social_account_service
|
from app.social.services import SocialUploadService, social_account_service
|
||||||
from app.social.worker.upload_task import process_social_upload
|
|
||||||
from app.user.dependencies import get_current_user
|
from app.user.dependencies import get_current_user
|
||||||
from app.user.models import User
|
from app.user.models import User
|
||||||
from app.video.models import Video
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
router = APIRouter(prefix="/upload", tags=["Social Upload"])
|
router = APIRouter(prefix="/upload", tags=["Social Upload"])
|
||||||
|
|
||||||
|
upload_service = SocialUploadService(account_service=social_account_service)
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
@router.post(
|
||||||
"",
|
"",
|
||||||
@@ -70,121 +66,7 @@ async def upload_to_social(
|
|||||||
current_user: User = Depends(get_current_user),
|
current_user: User = Depends(get_current_user),
|
||||||
session: AsyncSession = Depends(get_session),
|
session: AsyncSession = Depends(get_session),
|
||||||
) -> SocialUploadResponse:
|
) -> SocialUploadResponse:
|
||||||
"""
|
return await upload_service.request_upload(body, current_user, session, background_tasks)
|
||||||
소셜 플랫폼에 영상 업로드 요청
|
|
||||||
|
|
||||||
백그라운드에서 영상을 다운로드하고 소셜 플랫폼에 업로드합니다.
|
|
||||||
"""
|
|
||||||
logger.info(
|
|
||||||
f"[UPLOAD_API] 업로드 요청 - "
|
|
||||||
f"user_uuid: {current_user.user_uuid}, "
|
|
||||||
f"video_id: {body.video_id}, "
|
|
||||||
f"social_account_id: {body.social_account_id}"
|
|
||||||
)
|
|
||||||
|
|
||||||
# 1. 영상 조회 및 검증
|
|
||||||
video_result = await session.execute(
|
|
||||||
select(Video).where(Video.id == body.video_id)
|
|
||||||
)
|
|
||||||
video = video_result.scalar_one_or_none()
|
|
||||||
|
|
||||||
if not video:
|
|
||||||
logger.warning(f"[UPLOAD_API] 영상 없음 - video_id: {body.video_id}")
|
|
||||||
raise VideoNotFoundError(video_id=body.video_id)
|
|
||||||
|
|
||||||
if not video.result_movie_url:
|
|
||||||
logger.warning(f"[UPLOAD_API] 영상 URL 없음 - video_id: {body.video_id}")
|
|
||||||
raise VideoNotFoundError(
|
|
||||||
video_id=body.video_id,
|
|
||||||
detail="영상이 아직 준비되지 않았습니다. 영상 생성이 완료된 후 시도해주세요.",
|
|
||||||
)
|
|
||||||
|
|
||||||
# 2. 소셜 계정 조회 (social_account_id로 직접 조회, 소유권 검증 포함)
|
|
||||||
account = await social_account_service.get_account_by_id(
|
|
||||||
user_uuid=current_user.user_uuid,
|
|
||||||
account_id=body.social_account_id,
|
|
||||||
session=session,
|
|
||||||
)
|
|
||||||
|
|
||||||
if not account:
|
|
||||||
logger.warning(
|
|
||||||
f"[UPLOAD_API] 연동 계정 없음 - "
|
|
||||||
f"user_uuid: {current_user.user_uuid}, social_account_id: {body.social_account_id}"
|
|
||||||
)
|
|
||||||
raise SocialAccountNotFoundError()
|
|
||||||
|
|
||||||
# 3. 진행 중인 업로드 확인 (pending 또는 uploading 상태만)
|
|
||||||
in_progress_result = await session.execute(
|
|
||||||
select(SocialUpload).where(
|
|
||||||
SocialUpload.video_id == body.video_id,
|
|
||||||
SocialUpload.social_account_id == account.id,
|
|
||||||
SocialUpload.status.in_([UploadStatus.PENDING.value, UploadStatus.UPLOADING.value]),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
in_progress_upload = in_progress_result.scalar_one_or_none()
|
|
||||||
|
|
||||||
if in_progress_upload:
|
|
||||||
logger.info(
|
|
||||||
f"[UPLOAD_API] 진행 중인 업로드 존재 - upload_id: {in_progress_upload.id}"
|
|
||||||
)
|
|
||||||
return SocialUploadResponse(
|
|
||||||
success=True,
|
|
||||||
upload_id=in_progress_upload.id,
|
|
||||||
platform=account.platform,
|
|
||||||
status=in_progress_upload.status,
|
|
||||||
message="이미 업로드가 진행 중입니다.",
|
|
||||||
)
|
|
||||||
|
|
||||||
# 4. 업로드 순번 계산 (동일 video + account 조합에서 최대 순번 + 1)
|
|
||||||
max_seq_result = await session.execute(
|
|
||||||
select(func.coalesce(func.max(SocialUpload.upload_seq), 0)).where(
|
|
||||||
SocialUpload.video_id == body.video_id,
|
|
||||||
SocialUpload.social_account_id == account.id,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
max_seq = max_seq_result.scalar() or 0
|
|
||||||
next_seq = max_seq + 1
|
|
||||||
|
|
||||||
# 5. 새 업로드 레코드 생성 (항상 새로 생성하여 이력 보존)
|
|
||||||
social_upload = SocialUpload(
|
|
||||||
user_uuid=current_user.user_uuid,
|
|
||||||
video_id=body.video_id,
|
|
||||||
social_account_id=account.id,
|
|
||||||
upload_seq=next_seq,
|
|
||||||
platform=account.platform,
|
|
||||||
status=UploadStatus.PENDING.value,
|
|
||||||
upload_progress=0,
|
|
||||||
title=body.title,
|
|
||||||
description=body.description,
|
|
||||||
tags=body.tags,
|
|
||||||
privacy_status=body.privacy_status.value,
|
|
||||||
platform_options={
|
|
||||||
**(body.platform_options or {}),
|
|
||||||
"scheduled_at": body.scheduled_at.isoformat() if body.scheduled_at else None,
|
|
||||||
},
|
|
||||||
retry_count=0,
|
|
||||||
)
|
|
||||||
|
|
||||||
session.add(social_upload)
|
|
||||||
await session.commit()
|
|
||||||
await session.refresh(social_upload)
|
|
||||||
|
|
||||||
logger.info(
|
|
||||||
f"[UPLOAD_API] 업로드 레코드 생성 - "
|
|
||||||
f"upload_id: {social_upload.id}, video_id: {body.video_id}, "
|
|
||||||
f"account_id: {account.id}, upload_seq: {next_seq}, platform: {account.platform}"
|
|
||||||
)
|
|
||||||
|
|
||||||
# 6. 백그라운드 태스크 등록
|
|
||||||
background_tasks.add_task(process_social_upload, social_upload.id)
|
|
||||||
|
|
||||||
return SocialUploadResponse(
|
|
||||||
success=True,
|
|
||||||
upload_id=social_upload.id,
|
|
||||||
platform=account.platform,
|
|
||||||
status=social_upload.status,
|
|
||||||
message="업로드 요청이 접수되었습니다.",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
@@ -198,120 +80,35 @@ async def get_upload_status(
|
|||||||
current_user: User = Depends(get_current_user),
|
current_user: User = Depends(get_current_user),
|
||||||
session: AsyncSession = Depends(get_session),
|
session: AsyncSession = Depends(get_session),
|
||||||
) -> SocialUploadStatusResponse:
|
) -> SocialUploadStatusResponse:
|
||||||
"""
|
return await upload_service.get_upload_status(upload_id, current_user, session)
|
||||||
업로드 상태 조회
|
|
||||||
"""
|
|
||||||
logger.info(f"[UPLOAD_API] 상태 조회 - upload_id: {upload_id}")
|
|
||||||
|
|
||||||
result = await session.execute(
|
|
||||||
select(SocialUpload).where(
|
|
||||||
SocialUpload.id == upload_id,
|
|
||||||
SocialUpload.user_uuid == current_user.user_uuid,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
upload = result.scalar_one_or_none()
|
|
||||||
|
|
||||||
if not upload:
|
|
||||||
from fastapi import HTTPException, status
|
|
||||||
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_404_NOT_FOUND,
|
|
||||||
detail="업로드 정보를 찾을 수 없습니다.",
|
|
||||||
)
|
|
||||||
|
|
||||||
return SocialUploadStatusResponse(
|
|
||||||
upload_id=upload.id,
|
|
||||||
video_id=upload.video_id,
|
|
||||||
social_account_id=upload.social_account_id,
|
|
||||||
upload_seq=upload.upload_seq,
|
|
||||||
platform=upload.platform,
|
|
||||||
status=UploadStatus(upload.status),
|
|
||||||
upload_progress=upload.upload_progress,
|
|
||||||
title=upload.title,
|
|
||||||
platform_video_id=upload.platform_video_id,
|
|
||||||
platform_url=upload.platform_url,
|
|
||||||
error_message=upload.error_message,
|
|
||||||
retry_count=upload.retry_count,
|
|
||||||
created_at=upload.created_at,
|
|
||||||
uploaded_at=upload.uploaded_at,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/history",
|
"/history",
|
||||||
response_model=SocialUploadHistoryResponse,
|
response_model=SocialUploadHistoryResponse,
|
||||||
summary="업로드 이력 조회",
|
summary="업로드 이력 조회",
|
||||||
description="사용자의 소셜 미디어 업로드 이력을 조회합니다.",
|
description="""
|
||||||
|
사용자의 소셜 미디어 업로드 이력을 조회합니다.
|
||||||
|
|
||||||
|
## tab 파라미터
|
||||||
|
- `all`: 전체 (기본값)
|
||||||
|
- `completed`: 완료된 업로드
|
||||||
|
- `scheduled`: 예약 업로드 (pending + scheduled_at 있음)
|
||||||
|
- `failed`: 실패한 업로드
|
||||||
|
""",
|
||||||
)
|
)
|
||||||
async def get_upload_history(
|
async def get_upload_history(
|
||||||
current_user: User = Depends(get_current_user),
|
current_user: User = Depends(get_current_user),
|
||||||
session: AsyncSession = Depends(get_session),
|
session: AsyncSession = Depends(get_session),
|
||||||
|
tab: str = Query("all", description="탭 필터 (all/completed/scheduled/failed)"),
|
||||||
platform: Optional[SocialPlatform] = Query(None, description="플랫폼 필터"),
|
platform: Optional[SocialPlatform] = Query(None, description="플랫폼 필터"),
|
||||||
status: Optional[UploadStatus] = Query(None, description="상태 필터"),
|
year: Optional[int] = Query(None, description="조회 연도 (없으면 현재 연도)"),
|
||||||
|
month: Optional[int] = Query(None, ge=1, le=12, description="조회 월 (없으면 현재 월)"),
|
||||||
page: int = Query(1, ge=1, description="페이지 번호"),
|
page: int = Query(1, ge=1, description="페이지 번호"),
|
||||||
size: int = Query(20, ge=1, le=100, description="페이지 크기"),
|
size: int = Query(20, ge=1, le=100, description="페이지 크기"),
|
||||||
) -> SocialUploadHistoryResponse:
|
) -> SocialUploadHistoryResponse:
|
||||||
"""
|
return await upload_service.get_upload_history(
|
||||||
업로드 이력 조회
|
current_user, session, tab, platform, year, month, page, size
|
||||||
"""
|
|
||||||
logger.info(
|
|
||||||
f"[UPLOAD_API] 이력 조회 - "
|
|
||||||
f"user_uuid: {current_user.user_uuid}, page: {page}, size: {size}"
|
|
||||||
)
|
|
||||||
|
|
||||||
# 기본 쿼리
|
|
||||||
query = select(SocialUpload).where(
|
|
||||||
SocialUpload.user_uuid == current_user.user_uuid
|
|
||||||
)
|
|
||||||
|
|
||||||
count_query = select(func.count(SocialUpload.id)).where(
|
|
||||||
SocialUpload.user_uuid == current_user.user_uuid
|
|
||||||
)
|
|
||||||
|
|
||||||
# 필터 적용
|
|
||||||
if platform:
|
|
||||||
query = query.where(SocialUpload.platform == platform.value)
|
|
||||||
count_query = count_query.where(SocialUpload.platform == platform.value)
|
|
||||||
|
|
||||||
if status:
|
|
||||||
query = query.where(SocialUpload.status == status.value)
|
|
||||||
count_query = count_query.where(SocialUpload.status == status.value)
|
|
||||||
|
|
||||||
# 총 개수 조회
|
|
||||||
total_result = await session.execute(count_query)
|
|
||||||
total = total_result.scalar() or 0
|
|
||||||
|
|
||||||
# 페이지네이션 적용
|
|
||||||
query = (
|
|
||||||
query.order_by(SocialUpload.created_at.desc())
|
|
||||||
.offset((page - 1) * size)
|
|
||||||
.limit(size)
|
|
||||||
)
|
|
||||||
|
|
||||||
result = await session.execute(query)
|
|
||||||
uploads = result.scalars().all()
|
|
||||||
|
|
||||||
items = [
|
|
||||||
SocialUploadHistoryItem(
|
|
||||||
upload_id=upload.id,
|
|
||||||
video_id=upload.video_id,
|
|
||||||
social_account_id=upload.social_account_id,
|
|
||||||
upload_seq=upload.upload_seq,
|
|
||||||
platform=upload.platform,
|
|
||||||
status=upload.status,
|
|
||||||
title=upload.title,
|
|
||||||
platform_url=upload.platform_url,
|
|
||||||
created_at=upload.created_at,
|
|
||||||
uploaded_at=upload.uploaded_at,
|
|
||||||
)
|
|
||||||
for upload in uploads
|
|
||||||
]
|
|
||||||
|
|
||||||
return SocialUploadHistoryResponse(
|
|
||||||
items=items,
|
|
||||||
total=total,
|
|
||||||
page=page,
|
|
||||||
size=size,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -327,53 +124,7 @@ async def retry_upload(
|
|||||||
current_user: User = Depends(get_current_user),
|
current_user: User = Depends(get_current_user),
|
||||||
session: AsyncSession = Depends(get_session),
|
session: AsyncSession = Depends(get_session),
|
||||||
) -> SocialUploadResponse:
|
) -> SocialUploadResponse:
|
||||||
"""
|
return await upload_service.retry_upload(upload_id, current_user, session, background_tasks)
|
||||||
업로드 재시도
|
|
||||||
|
|
||||||
실패한 업로드를 다시 시도합니다.
|
|
||||||
"""
|
|
||||||
logger.info(f"[UPLOAD_API] 재시도 요청 - upload_id: {upload_id}")
|
|
||||||
|
|
||||||
result = await session.execute(
|
|
||||||
select(SocialUpload).where(
|
|
||||||
SocialUpload.id == upload_id,
|
|
||||||
SocialUpload.user_uuid == current_user.user_uuid,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
upload = result.scalar_one_or_none()
|
|
||||||
|
|
||||||
if not upload:
|
|
||||||
from fastapi import HTTPException, status
|
|
||||||
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_404_NOT_FOUND,
|
|
||||||
detail="업로드 정보를 찾을 수 없습니다.",
|
|
||||||
)
|
|
||||||
|
|
||||||
if upload.status not in [UploadStatus.FAILED.value, UploadStatus.CANCELLED.value]:
|
|
||||||
from fastapi import HTTPException, status
|
|
||||||
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_400_BAD_REQUEST,
|
|
||||||
detail="실패하거나 취소된 업로드만 재시도할 수 있습니다.",
|
|
||||||
)
|
|
||||||
|
|
||||||
# 상태 초기화
|
|
||||||
upload.status = UploadStatus.PENDING.value
|
|
||||||
upload.upload_progress = 0
|
|
||||||
upload.error_message = None
|
|
||||||
await session.commit()
|
|
||||||
|
|
||||||
# 백그라운드 태스크 등록
|
|
||||||
background_tasks.add_task(process_social_upload, upload.id)
|
|
||||||
|
|
||||||
return SocialUploadResponse(
|
|
||||||
success=True,
|
|
||||||
upload_id=upload.id,
|
|
||||||
platform=upload.platform,
|
|
||||||
status=upload.status,
|
|
||||||
message="업로드 재시도가 요청되었습니다.",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@router.delete(
|
@router.delete(
|
||||||
@@ -387,38 +138,4 @@ async def cancel_upload(
|
|||||||
current_user: User = Depends(get_current_user),
|
current_user: User = Depends(get_current_user),
|
||||||
session: AsyncSession = Depends(get_session),
|
session: AsyncSession = Depends(get_session),
|
||||||
) -> MessageResponse:
|
) -> MessageResponse:
|
||||||
"""
|
return await upload_service.cancel_upload(upload_id, current_user, session)
|
||||||
업로드 취소
|
|
||||||
|
|
||||||
대기 중인 업로드를 취소합니다.
|
|
||||||
이미 진행 중이거나 완료된 업로드는 취소할 수 없습니다.
|
|
||||||
"""
|
|
||||||
logger.info(f"[UPLOAD_API] 취소 요청 - upload_id: {upload_id}")
|
|
||||||
|
|
||||||
result = await session.execute(
|
|
||||||
select(SocialUpload).where(
|
|
||||||
SocialUpload.id == upload_id,
|
|
||||||
SocialUpload.user_uuid == current_user.user_uuid,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
upload = result.scalar_one_or_none()
|
|
||||||
|
|
||||||
if not upload:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_404_NOT_FOUND,
|
|
||||||
detail="업로드 정보를 찾을 수 없습니다.",
|
|
||||||
)
|
|
||||||
|
|
||||||
if upload.status != UploadStatus.PENDING.value:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_400_BAD_REQUEST,
|
|
||||||
detail="대기 중인 업로드만 취소할 수 있습니다.",
|
|
||||||
)
|
|
||||||
|
|
||||||
upload.status = UploadStatus.CANCELLED.value
|
|
||||||
await session.commit()
|
|
||||||
|
|
||||||
return MessageResponse(
|
|
||||||
success=True,
|
|
||||||
message="업로드가 취소되었습니다.",
|
|
||||||
)
|
|
||||||
@@ -190,6 +190,15 @@ class SocialUpload(Base):
|
|||||||
comment="플랫폼별 추가 옵션 (JSON)",
|
comment="플랫폼별 추가 옵션 (JSON)",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# ==========================================================================
|
||||||
|
# 예약 게시 시간
|
||||||
|
# ==========================================================================
|
||||||
|
scheduled_at: Mapped[Optional[datetime]] = mapped_column(
|
||||||
|
DateTime,
|
||||||
|
nullable=True,
|
||||||
|
comment="예약 게시 시간 (스케줄러가 이 시간 이후에 업로드 실행)",
|
||||||
|
)
|
||||||
|
|
||||||
# ==========================================================================
|
# ==========================================================================
|
||||||
# 에러 정보
|
# 에러 정보
|
||||||
# ==========================================================================
|
# ==========================================================================
|
||||||
|
|||||||
@@ -1,324 +0,0 @@
|
|||||||
"""
|
|
||||||
Social Media Schemas
|
|
||||||
|
|
||||||
소셜 미디어 연동 관련 Pydantic 스키마를 정의합니다.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from datetime import datetime
|
|
||||||
from typing import Any, Optional
|
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, Field
|
|
||||||
|
|
||||||
from app.social.constants import PrivacyStatus, SocialPlatform, UploadStatus
|
|
||||||
|
|
||||||
|
|
||||||
# =============================================================================
|
|
||||||
# OAuth 관련 스키마
|
|
||||||
# =============================================================================
|
|
||||||
|
|
||||||
|
|
||||||
class SocialConnectResponse(BaseModel):
|
|
||||||
"""소셜 계정 연동 시작 응답"""
|
|
||||||
|
|
||||||
auth_url: str = Field(..., description="OAuth 인증 URL")
|
|
||||||
state: str = Field(..., description="CSRF 방지용 state 토큰")
|
|
||||||
platform: str = Field(..., description="플랫폼명")
|
|
||||||
|
|
||||||
model_config = ConfigDict(
|
|
||||||
json_schema_extra={
|
|
||||||
"example": {
|
|
||||||
"auth_url": "https://accounts.google.com/o/oauth2/v2/auth?...",
|
|
||||||
"state": "abc123xyz",
|
|
||||||
"platform": "youtube",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class SocialAccountResponse(BaseModel):
|
|
||||||
"""연동된 소셜 계정 정보"""
|
|
||||||
|
|
||||||
id: int = Field(..., description="소셜 계정 ID")
|
|
||||||
platform: str = Field(..., description="플랫폼명")
|
|
||||||
platform_user_id: str = Field(..., description="플랫폼 내 사용자 ID")
|
|
||||||
platform_username: Optional[str] = Field(None, description="플랫폼 내 사용자명")
|
|
||||||
display_name: Optional[str] = Field(None, description="표시 이름")
|
|
||||||
profile_image_url: Optional[str] = Field(None, description="프로필 이미지 URL")
|
|
||||||
is_active: bool = Field(..., description="활성화 상태")
|
|
||||||
connected_at: datetime = Field(..., description="연동 일시")
|
|
||||||
platform_data: Optional[dict[str, Any]] = Field(
|
|
||||||
None, description="플랫폼별 추가 정보 (채널ID, 구독자 수 등)"
|
|
||||||
)
|
|
||||||
|
|
||||||
model_config = ConfigDict(
|
|
||||||
from_attributes=True,
|
|
||||||
json_schema_extra={
|
|
||||||
"example": {
|
|
||||||
"id": 1,
|
|
||||||
"platform": "youtube",
|
|
||||||
"platform_user_id": "UC1234567890",
|
|
||||||
"platform_username": "my_channel",
|
|
||||||
"display_name": "My Channel",
|
|
||||||
"profile_image_url": "https://...",
|
|
||||||
"is_active": True,
|
|
||||||
"connected_at": "2024-01-15T12:00:00",
|
|
||||||
"platform_data": {
|
|
||||||
"channel_id": "UC1234567890",
|
|
||||||
"channel_title": "My Channel",
|
|
||||||
"subscriber_count": 1000,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class SocialAccountListResponse(BaseModel):
|
|
||||||
"""연동된 소셜 계정 목록 응답"""
|
|
||||||
|
|
||||||
accounts: list[SocialAccountResponse] = Field(..., description="연동 계정 목록")
|
|
||||||
total: int = Field(..., description="총 연동 계정 수")
|
|
||||||
|
|
||||||
model_config = ConfigDict(
|
|
||||||
json_schema_extra={
|
|
||||||
"example": {
|
|
||||||
"accounts": [
|
|
||||||
{
|
|
||||||
"id": 1,
|
|
||||||
"platform": "youtube",
|
|
||||||
"platform_user_id": "UC1234567890",
|
|
||||||
"platform_username": "my_channel",
|
|
||||||
"display_name": "My Channel",
|
|
||||||
"is_active": True,
|
|
||||||
"connected_at": "2024-01-15T12:00:00",
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"total": 1,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# =============================================================================
|
|
||||||
# 내부 사용 스키마 (OAuth 토큰 응답)
|
|
||||||
# =============================================================================
|
|
||||||
|
|
||||||
|
|
||||||
class OAuthTokenResponse(BaseModel):
|
|
||||||
"""OAuth 토큰 응답 (내부 사용)"""
|
|
||||||
|
|
||||||
access_token: str
|
|
||||||
refresh_token: Optional[str] = None
|
|
||||||
expires_in: int
|
|
||||||
token_type: str = "Bearer"
|
|
||||||
scope: Optional[str] = None
|
|
||||||
|
|
||||||
|
|
||||||
class PlatformUserInfo(BaseModel):
|
|
||||||
"""플랫폼 사용자 정보 (내부 사용)"""
|
|
||||||
|
|
||||||
platform_user_id: str
|
|
||||||
username: Optional[str] = None
|
|
||||||
display_name: Optional[str] = None
|
|
||||||
profile_image_url: Optional[str] = None
|
|
||||||
platform_data: dict[str, Any] = Field(default_factory=dict)
|
|
||||||
|
|
||||||
|
|
||||||
# =============================================================================
|
|
||||||
# 업로드 관련 스키마
|
|
||||||
# =============================================================================
|
|
||||||
|
|
||||||
|
|
||||||
class SocialUploadRequest(BaseModel):
|
|
||||||
"""소셜 업로드 요청"""
|
|
||||||
|
|
||||||
video_id: int = Field(..., description="업로드할 영상 ID")
|
|
||||||
social_account_id: int = Field(..., description="업로드할 소셜 계정 ID (연동 계정 목록의 id)")
|
|
||||||
title: str = Field(..., min_length=1, max_length=100, description="영상 제목")
|
|
||||||
description: Optional[str] = Field(
|
|
||||||
None, max_length=5000, description="영상 설명"
|
|
||||||
)
|
|
||||||
tags: Optional[list[str]] = Field(None, description="태그 목록 (쉼표로 구분된 문자열도 가능)")
|
|
||||||
privacy_status: PrivacyStatus = Field(
|
|
||||||
default=PrivacyStatus.PRIVATE, description="공개 상태 (public, unlisted, private)"
|
|
||||||
)
|
|
||||||
scheduled_at: Optional[datetime] = Field(
|
|
||||||
None, description="예약 게시 시간 (없으면 즉시 게시)"
|
|
||||||
)
|
|
||||||
platform_options: Optional[dict[str, Any]] = Field(
|
|
||||||
None, description="플랫폼별 추가 옵션"
|
|
||||||
)
|
|
||||||
|
|
||||||
model_config = ConfigDict(
|
|
||||||
json_schema_extra={
|
|
||||||
"example": {
|
|
||||||
"video_id": 123,
|
|
||||||
"social_account_id": 1,
|
|
||||||
"title": "도그앤조이 애견펜션 2026.02.02",
|
|
||||||
"description": "영상 설명입니다.",
|
|
||||||
"tags": ["여행", "vlog", "애견펜션"],
|
|
||||||
"privacy_status": "public",
|
|
||||||
"scheduled_at": "2026-02-02T15:00:00",
|
|
||||||
"platform_options": {
|
|
||||||
"category_id": "22", # YouTube 카테고리
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class SocialUploadResponse(BaseModel):
|
|
||||||
"""소셜 업로드 요청 응답"""
|
|
||||||
|
|
||||||
success: bool = Field(..., description="요청 성공 여부")
|
|
||||||
upload_id: int = Field(..., description="업로드 작업 ID")
|
|
||||||
platform: str = Field(..., description="플랫폼명")
|
|
||||||
status: str = Field(..., description="업로드 상태")
|
|
||||||
message: str = Field(..., description="응답 메시지")
|
|
||||||
|
|
||||||
model_config = ConfigDict(
|
|
||||||
json_schema_extra={
|
|
||||||
"example": {
|
|
||||||
"success": True,
|
|
||||||
"upload_id": 456,
|
|
||||||
"platform": "youtube",
|
|
||||||
"status": "pending",
|
|
||||||
"message": "업로드 요청이 접수되었습니다.",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class SocialUploadStatusResponse(BaseModel):
|
|
||||||
"""업로드 상태 조회 응답"""
|
|
||||||
|
|
||||||
upload_id: int = Field(..., description="업로드 작업 ID")
|
|
||||||
video_id: int = Field(..., description="영상 ID")
|
|
||||||
social_account_id: int = Field(..., description="소셜 계정 ID")
|
|
||||||
upload_seq: int = Field(..., description="업로드 순번 (동일 영상+채널 조합 내 순번)")
|
|
||||||
platform: str = Field(..., description="플랫폼명")
|
|
||||||
status: UploadStatus = Field(..., description="업로드 상태")
|
|
||||||
upload_progress: int = Field(..., description="업로드 진행률 (0-100)")
|
|
||||||
title: str = Field(..., description="영상 제목")
|
|
||||||
platform_video_id: Optional[str] = Field(None, description="플랫폼 영상 ID")
|
|
||||||
platform_url: Optional[str] = Field(None, description="플랫폼 영상 URL")
|
|
||||||
error_message: Optional[str] = Field(None, description="에러 메시지")
|
|
||||||
retry_count: int = Field(default=0, description="재시도 횟수")
|
|
||||||
created_at: datetime = Field(..., description="생성 일시")
|
|
||||||
uploaded_at: Optional[datetime] = Field(None, description="업로드 완료 일시")
|
|
||||||
|
|
||||||
model_config = ConfigDict(
|
|
||||||
from_attributes=True,
|
|
||||||
json_schema_extra={
|
|
||||||
"example": {
|
|
||||||
"upload_id": 456,
|
|
||||||
"video_id": 123,
|
|
||||||
"social_account_id": 1,
|
|
||||||
"upload_seq": 2,
|
|
||||||
"platform": "youtube",
|
|
||||||
"status": "completed",
|
|
||||||
"upload_progress": 100,
|
|
||||||
"title": "나의 첫 영상",
|
|
||||||
"platform_video_id": "dQw4w9WgXcQ",
|
|
||||||
"platform_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
|
|
||||||
"error_message": None,
|
|
||||||
"retry_count": 0,
|
|
||||||
"created_at": "2024-01-15T12:00:00",
|
|
||||||
"uploaded_at": "2024-01-15T12:05:00",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class SocialUploadHistoryItem(BaseModel):
|
|
||||||
"""업로드 이력 아이템"""
|
|
||||||
|
|
||||||
upload_id: int = Field(..., description="업로드 작업 ID")
|
|
||||||
video_id: int = Field(..., description="영상 ID")
|
|
||||||
social_account_id: int = Field(..., description="소셜 계정 ID")
|
|
||||||
upload_seq: int = Field(..., description="업로드 순번 (동일 영상+채널 조합 내 순번)")
|
|
||||||
platform: str = Field(..., description="플랫폼명")
|
|
||||||
status: str = Field(..., description="업로드 상태")
|
|
||||||
title: str = Field(..., description="영상 제목")
|
|
||||||
platform_url: Optional[str] = Field(None, description="플랫폼 영상 URL")
|
|
||||||
created_at: datetime = Field(..., description="생성 일시")
|
|
||||||
uploaded_at: Optional[datetime] = Field(None, description="업로드 완료 일시")
|
|
||||||
|
|
||||||
model_config = ConfigDict(from_attributes=True)
|
|
||||||
|
|
||||||
|
|
||||||
class SocialUploadHistoryResponse(BaseModel):
|
|
||||||
"""업로드 이력 목록 응답"""
|
|
||||||
|
|
||||||
items: list[SocialUploadHistoryItem] = Field(..., description="업로드 이력 목록")
|
|
||||||
total: int = Field(..., description="전체 개수")
|
|
||||||
page: int = Field(..., description="현재 페이지")
|
|
||||||
size: int = Field(..., description="페이지 크기")
|
|
||||||
|
|
||||||
model_config = ConfigDict(
|
|
||||||
json_schema_extra={
|
|
||||||
"example": {
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"upload_id": 456,
|
|
||||||
"video_id": 123,
|
|
||||||
"platform": "youtube",
|
|
||||||
"status": "completed",
|
|
||||||
"title": "나의 첫 영상",
|
|
||||||
"platform_url": "https://www.youtube.com/watch?v=xxx",
|
|
||||||
"created_at": "2024-01-15T12:00:00",
|
|
||||||
"uploaded_at": "2024-01-15T12:05:00",
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"total": 1,
|
|
||||||
"page": 1,
|
|
||||||
"size": 20,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
class YoutubeDescriptionRequest(BaseModel):
|
|
||||||
"""유튜브 SEO Description 제안 (자동완성) Request 모델"""
|
|
||||||
|
|
||||||
model_config = ConfigDict(
|
|
||||||
json_schema_extra={
|
|
||||||
"example": {
|
|
||||||
"task_id" : "019c739f-65fc-7d15-8c88-b31be00e588e"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
task_id: str = Field(..., description="작업 고유 식별자")
|
|
||||||
|
|
||||||
class YoutubeDescriptionResponse(BaseModel):
|
|
||||||
"""유튜브 SEO Description 제안 (자동완성) Response 모델"""
|
|
||||||
title:str = Field(..., description="유튜브 영상 제목 - SEO/AEO 최적화")
|
|
||||||
description : str = Field(..., description="제안된 유튜브 SEO Description")
|
|
||||||
keywords : list[str] = Field(..., description="해시태그 리스트")
|
|
||||||
model_config = ConfigDict(
|
|
||||||
json_schema_extra={
|
|
||||||
"example": {
|
|
||||||
"title" : "여기에 더미 타이틀",
|
|
||||||
"description": "여기에 더미 텍스트",
|
|
||||||
"keywords": ["여기에", "더미", "해시태그"]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
# =============================================================================
|
|
||||||
# 공통 응답 스키마
|
|
||||||
# =============================================================================
|
|
||||||
|
|
||||||
|
|
||||||
class MessageResponse(BaseModel):
|
|
||||||
"""단순 메시지 응답"""
|
|
||||||
|
|
||||||
success: bool = Field(..., description="성공 여부")
|
|
||||||
message: str = Field(..., description="응답 메시지")
|
|
||||||
|
|
||||||
model_config = ConfigDict(
|
|
||||||
json_schema_extra={
|
|
||||||
"example": {
|
|
||||||
"success": True,
|
|
||||||
"message": "작업이 완료되었습니다.",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
from app.social.schemas.oauth_schema import (
|
||||||
|
SocialConnectResponse,
|
||||||
|
SocialAccountResponse,
|
||||||
|
SocialAccountListResponse,
|
||||||
|
OAuthTokenResponse,
|
||||||
|
PlatformUserInfo,
|
||||||
|
MessageResponse,
|
||||||
|
)
|
||||||
|
from app.social.schemas.upload_schema import (
|
||||||
|
SocialUploadRequest,
|
||||||
|
SocialUploadResponse,
|
||||||
|
SocialUploadStatusResponse,
|
||||||
|
SocialUploadHistoryItem,
|
||||||
|
SocialUploadHistoryResponse,
|
||||||
|
)
|
||||||
|
from app.social.schemas.seo_schema import (
|
||||||
|
YoutubeDescriptionRequest,
|
||||||
|
YoutubeDescriptionResponse,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"SocialConnectResponse",
|
||||||
|
"SocialAccountResponse",
|
||||||
|
"SocialAccountListResponse",
|
||||||
|
"OAuthTokenResponse",
|
||||||
|
"PlatformUserInfo",
|
||||||
|
"MessageResponse",
|
||||||
|
"SocialUploadRequest",
|
||||||
|
"SocialUploadResponse",
|
||||||
|
"SocialUploadStatusResponse",
|
||||||
|
"SocialUploadHistoryItem",
|
||||||
|
"SocialUploadHistoryResponse",
|
||||||
|
"YoutubeDescriptionRequest",
|
||||||
|
"YoutubeDescriptionResponse",
|
||||||
|
]
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
"""
|
||||||
|
소셜 OAuth 관련 Pydantic 스키마
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
|
|
||||||
|
|
||||||
|
class SocialConnectResponse(BaseModel):
|
||||||
|
"""소셜 계정 연동 시작 응답"""
|
||||||
|
|
||||||
|
auth_url: str = Field(..., description="OAuth 인증 URL")
|
||||||
|
state: str = Field(..., description="CSRF 방지용 state 토큰")
|
||||||
|
platform: str = Field(..., description="플랫폼명")
|
||||||
|
|
||||||
|
model_config = ConfigDict(
|
||||||
|
json_schema_extra={
|
||||||
|
"example": {
|
||||||
|
"auth_url": "https://accounts.google.com/o/oauth2/v2/auth?...",
|
||||||
|
"state": "abc123xyz",
|
||||||
|
"platform": "youtube",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class SocialAccountResponse(BaseModel):
|
||||||
|
"""연동된 소셜 계정 정보"""
|
||||||
|
|
||||||
|
id: int = Field(..., description="소셜 계정 ID")
|
||||||
|
platform: str = Field(..., description="플랫폼명")
|
||||||
|
platform_user_id: str = Field(..., description="플랫폼 내 사용자 ID")
|
||||||
|
platform_username: Optional[str] = Field(None, description="플랫폼 내 사용자명")
|
||||||
|
display_name: Optional[str] = Field(None, description="표시 이름")
|
||||||
|
profile_image_url: Optional[str] = Field(None, description="프로필 이미지 URL")
|
||||||
|
is_active: bool = Field(..., description="활성화 상태")
|
||||||
|
connected_at: datetime = Field(..., description="연동 일시")
|
||||||
|
platform_data: Optional[dict[str, Any]] = Field(
|
||||||
|
None, description="플랫폼별 추가 정보 (채널ID, 구독자 수 등)"
|
||||||
|
)
|
||||||
|
|
||||||
|
model_config = ConfigDict(
|
||||||
|
from_attributes=True,
|
||||||
|
json_schema_extra={
|
||||||
|
"example": {
|
||||||
|
"id": 1,
|
||||||
|
"platform": "youtube",
|
||||||
|
"platform_user_id": "UC1234567890",
|
||||||
|
"platform_username": "my_channel",
|
||||||
|
"display_name": "My Channel",
|
||||||
|
"profile_image_url": "https://...",
|
||||||
|
"is_active": True,
|
||||||
|
"connected_at": "2024-01-15T12:00:00",
|
||||||
|
"platform_data": {
|
||||||
|
"channel_id": "UC1234567890",
|
||||||
|
"channel_title": "My Channel",
|
||||||
|
"subscriber_count": 1000,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class SocialAccountListResponse(BaseModel):
|
||||||
|
"""연동된 소셜 계정 목록 응답"""
|
||||||
|
|
||||||
|
accounts: list[SocialAccountResponse] = Field(..., description="연동 계정 목록")
|
||||||
|
total: int = Field(..., description="총 연동 계정 수")
|
||||||
|
|
||||||
|
model_config = ConfigDict(
|
||||||
|
json_schema_extra={
|
||||||
|
"example": {
|
||||||
|
"accounts": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"platform": "youtube",
|
||||||
|
"platform_user_id": "UC1234567890",
|
||||||
|
"platform_username": "my_channel",
|
||||||
|
"display_name": "My Channel",
|
||||||
|
"is_active": True,
|
||||||
|
"connected_at": "2024-01-15T12:00:00",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"total": 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class OAuthTokenResponse(BaseModel):
|
||||||
|
"""OAuth 토큰 응답 (내부 사용)"""
|
||||||
|
|
||||||
|
access_token: str
|
||||||
|
refresh_token: Optional[str] = None
|
||||||
|
expires_in: int
|
||||||
|
token_type: str = "Bearer"
|
||||||
|
scope: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class PlatformUserInfo(BaseModel):
|
||||||
|
"""플랫폼 사용자 정보 (내부 사용)"""
|
||||||
|
|
||||||
|
platform_user_id: str
|
||||||
|
username: Optional[str] = None
|
||||||
|
display_name: Optional[str] = None
|
||||||
|
profile_image_url: Optional[str] = None
|
||||||
|
platform_data: dict[str, Any] = Field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
class MessageResponse(BaseModel):
|
||||||
|
"""단순 메시지 응답"""
|
||||||
|
|
||||||
|
success: bool = Field(..., description="성공 여부")
|
||||||
|
message: str = Field(..., description="응답 메시지")
|
||||||
|
|
||||||
|
model_config = ConfigDict(
|
||||||
|
json_schema_extra={
|
||||||
|
"example": {
|
||||||
|
"success": True,
|
||||||
|
"message": "작업이 완료되었습니다.",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""
|
||||||
|
소셜 SEO 관련 Pydantic 스키마
|
||||||
|
"""
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
|
|
||||||
|
|
||||||
|
class YoutubeDescriptionRequest(BaseModel):
|
||||||
|
"""유튜브 SEO Description 제안 요청"""
|
||||||
|
|
||||||
|
task_id: str = Field(..., description="작업 고유 식별자")
|
||||||
|
|
||||||
|
model_config = ConfigDict(
|
||||||
|
json_schema_extra={
|
||||||
|
"example": {
|
||||||
|
"task_id": "019c739f-65fc-7d15-8c88-b31be00e588e"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class YoutubeDescriptionResponse(BaseModel):
|
||||||
|
"""유튜브 SEO Description 제안 응답"""
|
||||||
|
|
||||||
|
title: str = Field(..., description="유튜브 영상 제목 - SEO/AEO 최적화")
|
||||||
|
description: str = Field(..., description="제안된 유튜브 SEO Description")
|
||||||
|
keywords: list[str] = Field(..., description="해시태그 리스트")
|
||||||
|
|
||||||
|
model_config = ConfigDict(
|
||||||
|
json_schema_extra={
|
||||||
|
"example": {
|
||||||
|
"title": "여기에 더미 타이틀",
|
||||||
|
"description": "여기에 더미 텍스트",
|
||||||
|
"keywords": ["여기에", "더미", "해시태그"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
"""
|
||||||
|
소셜 업로드 관련 Pydantic 스키마
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
|
|
||||||
|
from app.social.constants import PrivacyStatus, UploadStatus
|
||||||
|
|
||||||
|
|
||||||
|
class SocialUploadRequest(BaseModel):
|
||||||
|
"""소셜 업로드 요청"""
|
||||||
|
|
||||||
|
video_id: int = Field(..., description="업로드할 영상 ID")
|
||||||
|
social_account_id: int = Field(..., description="업로드할 소셜 계정 ID (연동 계정 목록의 id)")
|
||||||
|
title: str = Field(..., min_length=1, max_length=100, description="영상 제목")
|
||||||
|
description: Optional[str] = Field(
|
||||||
|
None, max_length=5000, description="영상 설명"
|
||||||
|
)
|
||||||
|
tags: Optional[list[str]] = Field(None, description="태그 목록 (쉼표로 구분된 문자열도 가능)")
|
||||||
|
privacy_status: PrivacyStatus = Field(
|
||||||
|
default=PrivacyStatus.PRIVATE, description="공개 상태 (public, unlisted, private)"
|
||||||
|
)
|
||||||
|
scheduled_at: Optional[datetime] = Field(
|
||||||
|
None, description="예약 게시 시간 (없으면 즉시 게시)"
|
||||||
|
)
|
||||||
|
platform_options: Optional[dict[str, Any]] = Field(
|
||||||
|
None, description="플랫폼별 추가 옵션"
|
||||||
|
)
|
||||||
|
|
||||||
|
model_config = ConfigDict(
|
||||||
|
json_schema_extra={
|
||||||
|
"example": {
|
||||||
|
"video_id": 123,
|
||||||
|
"social_account_id": 1,
|
||||||
|
"title": "도그앤조이 애견펜션 2026.02.02",
|
||||||
|
"description": "영상 설명입니다.",
|
||||||
|
"tags": ["여행", "vlog", "애견펜션"],
|
||||||
|
"privacy_status": "public",
|
||||||
|
"scheduled_at": "2026-02-02T15:00:00",
|
||||||
|
"platform_options": {
|
||||||
|
"category_id": "22",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class SocialUploadResponse(BaseModel):
|
||||||
|
"""소셜 업로드 요청 응답"""
|
||||||
|
|
||||||
|
success: bool = Field(..., description="요청 성공 여부")
|
||||||
|
upload_id: int = Field(..., description="업로드 작업 ID")
|
||||||
|
platform: str = Field(..., description="플랫폼명")
|
||||||
|
status: str = Field(..., description="업로드 상태")
|
||||||
|
message: str = Field(..., description="응답 메시지")
|
||||||
|
|
||||||
|
model_config = ConfigDict(
|
||||||
|
json_schema_extra={
|
||||||
|
"example": {
|
||||||
|
"success": True,
|
||||||
|
"upload_id": 456,
|
||||||
|
"platform": "youtube",
|
||||||
|
"status": "pending",
|
||||||
|
"message": "업로드 요청이 접수되었습니다.",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class SocialUploadStatusResponse(BaseModel):
|
||||||
|
"""업로드 상태 조회 응답"""
|
||||||
|
|
||||||
|
upload_id: int = Field(..., description="업로드 작업 ID")
|
||||||
|
video_id: int = Field(..., description="영상 ID")
|
||||||
|
social_account_id: int = Field(..., description="소셜 계정 ID")
|
||||||
|
upload_seq: int = Field(..., description="업로드 순번 (동일 영상+채널 조합 내 순번)")
|
||||||
|
platform: str = Field(..., description="플랫폼명")
|
||||||
|
status: UploadStatus = Field(..., description="업로드 상태")
|
||||||
|
upload_progress: int = Field(..., description="업로드 진행률 (0-100)")
|
||||||
|
title: str = Field(..., description="영상 제목")
|
||||||
|
platform_video_id: Optional[str] = Field(None, description="플랫폼 영상 ID")
|
||||||
|
platform_url: Optional[str] = Field(None, description="플랫폼 영상 URL")
|
||||||
|
error_message: Optional[str] = Field(None, description="에러 메시지")
|
||||||
|
retry_count: int = Field(default=0, description="재시도 횟수")
|
||||||
|
scheduled_at: Optional[datetime] = Field(None, description="예약 게시 시간 (있으면 예약 업로드)")
|
||||||
|
created_at: datetime = Field(..., description="생성 일시")
|
||||||
|
uploaded_at: Optional[datetime] = Field(None, description="업로드 완료 일시")
|
||||||
|
|
||||||
|
model_config = ConfigDict(
|
||||||
|
from_attributes=True,
|
||||||
|
json_schema_extra={
|
||||||
|
"example": {
|
||||||
|
"upload_id": 456,
|
||||||
|
"video_id": 123,
|
||||||
|
"social_account_id": 1,
|
||||||
|
"upload_seq": 2,
|
||||||
|
"platform": "youtube",
|
||||||
|
"status": "completed",
|
||||||
|
"upload_progress": 100,
|
||||||
|
"title": "나의 첫 영상",
|
||||||
|
"platform_video_id": "dQw4w9WgXcQ",
|
||||||
|
"platform_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
|
||||||
|
"error_message": None,
|
||||||
|
"retry_count": 0,
|
||||||
|
"created_at": "2024-01-15T12:00:00",
|
||||||
|
"uploaded_at": "2024-01-15T12:05:00",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class SocialUploadHistoryItem(BaseModel):
|
||||||
|
"""업로드 이력 아이템"""
|
||||||
|
|
||||||
|
upload_id: int = Field(..., description="업로드 작업 ID")
|
||||||
|
video_id: int = Field(..., description="영상 ID")
|
||||||
|
social_account_id: int = Field(..., description="소셜 계정 ID")
|
||||||
|
upload_seq: int = Field(..., description="업로드 순번 (동일 영상+채널 조합 내 순번)")
|
||||||
|
platform: str = Field(..., description="플랫폼명")
|
||||||
|
status: str = Field(..., description="업로드 상태")
|
||||||
|
title: str = Field(..., description="영상 제목")
|
||||||
|
platform_url: Optional[str] = Field(None, description="플랫폼 영상 URL")
|
||||||
|
error_message: Optional[str] = Field(None, description="에러 메시지")
|
||||||
|
scheduled_at: Optional[datetime] = Field(None, description="예약 게시 시간")
|
||||||
|
created_at: datetime = Field(..., description="생성 일시")
|
||||||
|
uploaded_at: Optional[datetime] = Field(None, description="업로드 완료 일시")
|
||||||
|
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
|
||||||
|
class SocialUploadHistoryResponse(BaseModel):
|
||||||
|
"""업로드 이력 목록 응답"""
|
||||||
|
|
||||||
|
items: list[SocialUploadHistoryItem] = Field(..., description="업로드 이력 목록")
|
||||||
|
total: int = Field(..., description="전체 개수")
|
||||||
|
page: int = Field(..., description="현재 페이지")
|
||||||
|
size: int = Field(..., description="페이지 크기")
|
||||||
|
|
||||||
|
model_config = ConfigDict(
|
||||||
|
json_schema_extra={
|
||||||
|
"example": {
|
||||||
|
"items": [
|
||||||
|
{
|
||||||
|
"upload_id": 456,
|
||||||
|
"video_id": 123,
|
||||||
|
"platform": "youtube",
|
||||||
|
"status": "completed",
|
||||||
|
"title": "나의 첫 영상",
|
||||||
|
"platform_url": "https://www.youtube.com/watch?v=xxx",
|
||||||
|
"created_at": "2024-01-15T12:00:00",
|
||||||
|
"uploaded_at": "2024-01-15T12:05:00",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"total": 1,
|
||||||
|
"page": 1,
|
||||||
|
"size": 20,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
from app.social.services.account_service import SocialAccountService, social_account_service
|
||||||
|
from app.social.services.upload_service import SocialUploadService
|
||||||
|
from app.social.services.seo_service import SeoService, seo_service
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"SocialAccountService",
|
||||||
|
"social_account_service",
|
||||||
|
"SocialUploadService",
|
||||||
|
"SeoService",
|
||||||
|
"seo_service",
|
||||||
|
]
|
||||||
@@ -188,7 +188,7 @@ class SocialAccountService:
|
|||||||
session=session,
|
session=session,
|
||||||
update_connected_at=is_reactivation, # 재활성화 시에만 연결 시간 업데이트
|
update_connected_at=is_reactivation, # 재활성화 시에만 연결 시간 업데이트
|
||||||
)
|
)
|
||||||
return self._to_response(existing_account)
|
return self.to_response(existing_account)
|
||||||
|
|
||||||
# 5. 새 소셜 계정 저장 (기존 계정이 없는 경우에만)
|
# 5. 새 소셜 계정 저장 (기존 계정이 없는 경우에만)
|
||||||
social_account = await self._create_social_account(
|
social_account = await self._create_social_account(
|
||||||
@@ -204,7 +204,7 @@ class SocialAccountService:
|
|||||||
f"account_id: {social_account.id}, platform: {platform.value}"
|
f"account_id: {social_account.id}, platform: {platform.value}"
|
||||||
)
|
)
|
||||||
|
|
||||||
return self._to_response(social_account)
|
return self.to_response(social_account)
|
||||||
|
|
||||||
async def get_connected_accounts(
|
async def get_connected_accounts(
|
||||||
self,
|
self,
|
||||||
@@ -241,7 +241,7 @@ class SocialAccountService:
|
|||||||
for account in accounts:
|
for account in accounts:
|
||||||
await self._try_refresh_token(account, session)
|
await self._try_refresh_token(account, session)
|
||||||
|
|
||||||
return [self._to_response(account) for account in accounts]
|
return [self.to_response(account) for account in accounts]
|
||||||
|
|
||||||
async def refresh_all_tokens(
|
async def refresh_all_tokens(
|
||||||
self,
|
self,
|
||||||
@@ -713,7 +713,7 @@ class SocialAccountService:
|
|||||||
|
|
||||||
return account
|
return account
|
||||||
|
|
||||||
def _to_response(self, account: SocialAccount) -> SocialAccountResponse:
|
def to_response(self, account: SocialAccount) -> SocialAccountResponse:
|
||||||
"""
|
"""
|
||||||
SocialAccount를 SocialAccountResponse로 변환
|
SocialAccount를 SocialAccountResponse로 변환
|
||||||
|
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
"""
|
||||||
|
소셜 서비스 베이스 클래스
|
||||||
|
"""
|
||||||
|
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
|
||||||
|
class BaseService:
|
||||||
|
"""서비스 레이어 베이스 클래스"""
|
||||||
|
|
||||||
|
def __init__(self, session: AsyncSession | None = None):
|
||||||
|
self.session = session
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
"""
|
||||||
|
유튜브 SEO 서비스
|
||||||
|
|
||||||
|
SEO description 생성 및 Redis 캐싱 로직을 처리합니다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from redis.asyncio import Redis
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from config import db_settings
|
||||||
|
from app.home.models import MarketingIntel, Project
|
||||||
|
from app.social.constants import YOUTUBE_SEO_HASH
|
||||||
|
from app.social.schemas import YoutubeDescriptionResponse
|
||||||
|
from app.user.models import User
|
||||||
|
from app.utils.chatgpt_prompt import ChatgptService
|
||||||
|
from app.utils.prompts.prompts import yt_upload_prompt
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
redis_seo_client = Redis(
|
||||||
|
host=db_settings.REDIS_HOST,
|
||||||
|
port=db_settings.REDIS_PORT,
|
||||||
|
db=0,
|
||||||
|
decode_responses=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class SeoService:
|
||||||
|
"""유튜브 SEO 비즈니스 로직 서비스"""
|
||||||
|
|
||||||
|
async def get_youtube_seo_description(
|
||||||
|
self,
|
||||||
|
task_id: str,
|
||||||
|
current_user: User,
|
||||||
|
session: AsyncSession,
|
||||||
|
) -> YoutubeDescriptionResponse:
|
||||||
|
"""
|
||||||
|
유튜브 SEO description 생성
|
||||||
|
|
||||||
|
Redis 캐시 확인 후 miss이면 GPT로 생성하고 캐싱.
|
||||||
|
"""
|
||||||
|
logger.info(
|
||||||
|
f"[SEO_SERVICE] Try Cache - user: {current_user.user_uuid} / task_id: {task_id}"
|
||||||
|
)
|
||||||
|
|
||||||
|
cached = await self._get_from_redis(task_id)
|
||||||
|
if cached:
|
||||||
|
return cached
|
||||||
|
|
||||||
|
logger.info(f"[SEO_SERVICE] Cache miss - user: {current_user.user_uuid}")
|
||||||
|
result = await self._generate_seo_description(task_id, current_user, session)
|
||||||
|
await self._set_to_redis(task_id, result)
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
async def _generate_seo_description(
|
||||||
|
self,
|
||||||
|
task_id: str,
|
||||||
|
current_user: User,
|
||||||
|
session: AsyncSession,
|
||||||
|
) -> YoutubeDescriptionResponse:
|
||||||
|
"""GPT를 사용하여 SEO description 생성"""
|
||||||
|
logger.info(f"[SEO_SERVICE] Generating SEO - user: {current_user.user_uuid}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
project_result = await session.execute(
|
||||||
|
select(Project)
|
||||||
|
.where(
|
||||||
|
Project.task_id == task_id,
|
||||||
|
Project.user_uuid == current_user.user_uuid,
|
||||||
|
)
|
||||||
|
.order_by(Project.created_at.desc())
|
||||||
|
.limit(1)
|
||||||
|
)
|
||||||
|
project = project_result.scalar_one_or_none()
|
||||||
|
|
||||||
|
marketing_result = await session.execute(
|
||||||
|
select(MarketingIntel).where(MarketingIntel.id == project.marketing_intelligence)
|
||||||
|
)
|
||||||
|
marketing_intelligence = marketing_result.scalar_one_or_none()
|
||||||
|
|
||||||
|
hashtags = marketing_intelligence.intel_result["target_keywords"]
|
||||||
|
|
||||||
|
yt_seo_input_data = {
|
||||||
|
"customer_name": project.store_name,
|
||||||
|
"detail_region_info": project.detail_region_info,
|
||||||
|
"marketing_intelligence_summary": json.dumps(
|
||||||
|
marketing_intelligence.intel_result, ensure_ascii=False
|
||||||
|
),
|
||||||
|
"language": project.language,
|
||||||
|
"target_keywords": hashtags,
|
||||||
|
}
|
||||||
|
|
||||||
|
chatgpt = ChatgptService(timeout=180)
|
||||||
|
yt_seo_output = await chatgpt.generate_structured_output(yt_upload_prompt, yt_seo_input_data)
|
||||||
|
|
||||||
|
return YoutubeDescriptionResponse(
|
||||||
|
title=yt_seo_output.title,
|
||||||
|
description=yt_seo_output.description,
|
||||||
|
keywords=hashtags,
|
||||||
|
)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"[SEO_SERVICE] EXCEPTION - error: {e}")
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=500,
|
||||||
|
detail=f"유튜브 SEO 생성에 실패했습니다. : {str(e)}",
|
||||||
|
)
|
||||||
|
|
||||||
|
async def _get_from_redis(self, task_id: str) -> YoutubeDescriptionResponse | None:
|
||||||
|
field = f"task_id:{task_id}"
|
||||||
|
yt_seo_info = await redis_seo_client.hget(YOUTUBE_SEO_HASH, field)
|
||||||
|
if yt_seo_info:
|
||||||
|
return YoutubeDescriptionResponse(**json.loads(yt_seo_info))
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def _set_to_redis(self, task_id: str, yt_seo: YoutubeDescriptionResponse) -> None:
|
||||||
|
field = f"task_id:{task_id}"
|
||||||
|
yt_seo_info = json.dumps(yt_seo.model_dump(), ensure_ascii=False)
|
||||||
|
await redis_seo_client.hset(YOUTUBE_SEO_HASH, field, yt_seo_info)
|
||||||
|
await redis_seo_client.expire(YOUTUBE_SEO_HASH, 3600)
|
||||||
|
|
||||||
|
|
||||||
|
seo_service = SeoService()
|
||||||
@@ -0,0 +1,391 @@
|
|||||||
|
"""
|
||||||
|
소셜 업로드 서비스
|
||||||
|
|
||||||
|
업로드 요청, 상태 조회, 이력 조회, 재시도, 취소 관련 비즈니스 로직을 처리합니다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from calendar import monthrange
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import BackgroundTasks, HTTPException, status
|
||||||
|
from sqlalchemy import func, select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from config import TIMEZONE
|
||||||
|
from app.social.constants import SocialPlatform, UploadStatus
|
||||||
|
from app.social.exceptions import SocialAccountNotFoundError, VideoNotFoundError
|
||||||
|
from app.social.models import SocialUpload
|
||||||
|
from app.social.schemas import (
|
||||||
|
MessageResponse,
|
||||||
|
SocialUploadHistoryItem,
|
||||||
|
SocialUploadHistoryResponse,
|
||||||
|
SocialUploadResponse,
|
||||||
|
SocialUploadStatusResponse,
|
||||||
|
SocialUploadRequest,
|
||||||
|
)
|
||||||
|
from app.social.services.account_service import SocialAccountService
|
||||||
|
from app.social.worker.upload_task import process_social_upload
|
||||||
|
from app.user.models import User
|
||||||
|
from app.video.models import Video
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class SocialUploadService:
|
||||||
|
"""소셜 업로드 비즈니스 로직 서비스"""
|
||||||
|
|
||||||
|
def __init__(self, account_service: SocialAccountService):
|
||||||
|
self._account_service = account_service
|
||||||
|
|
||||||
|
async def request_upload(
|
||||||
|
self,
|
||||||
|
body: SocialUploadRequest,
|
||||||
|
current_user: User,
|
||||||
|
session: AsyncSession,
|
||||||
|
background_tasks: BackgroundTasks,
|
||||||
|
) -> SocialUploadResponse:
|
||||||
|
"""
|
||||||
|
소셜 플랫폼 업로드 요청
|
||||||
|
|
||||||
|
영상 검증, 계정 확인, 중복 확인 후 업로드 레코드 생성.
|
||||||
|
즉시 업로드이면 백그라운드 태스크 등록, 예약이면 스케줄러가 처리.
|
||||||
|
"""
|
||||||
|
logger.info(
|
||||||
|
f"[UPLOAD_SERVICE] 업로드 요청 - "
|
||||||
|
f"user_uuid: {current_user.user_uuid}, "
|
||||||
|
f"video_id: {body.video_id}, "
|
||||||
|
f"social_account_id: {body.social_account_id}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 1. 영상 조회 및 검증
|
||||||
|
video_result = await session.execute(
|
||||||
|
select(Video).where(Video.id == body.video_id)
|
||||||
|
)
|
||||||
|
video = video_result.scalar_one_or_none()
|
||||||
|
|
||||||
|
if not video:
|
||||||
|
logger.warning(f"[UPLOAD_SERVICE] 영상 없음 - video_id: {body.video_id}")
|
||||||
|
raise VideoNotFoundError(video_id=body.video_id)
|
||||||
|
|
||||||
|
if not video.result_movie_url:
|
||||||
|
logger.warning(f"[UPLOAD_SERVICE] 영상 URL 없음 - video_id: {body.video_id}")
|
||||||
|
raise VideoNotFoundError(
|
||||||
|
video_id=body.video_id,
|
||||||
|
detail="영상이 아직 준비되지 않았습니다. 영상 생성이 완료된 후 시도해주세요.",
|
||||||
|
)
|
||||||
|
|
||||||
|
# 2. 소셜 계정 조회 및 소유권 검증
|
||||||
|
account = await self._account_service.get_account_by_id(
|
||||||
|
user_uuid=current_user.user_uuid,
|
||||||
|
account_id=body.social_account_id,
|
||||||
|
session=session,
|
||||||
|
)
|
||||||
|
|
||||||
|
if not account:
|
||||||
|
logger.warning(
|
||||||
|
f"[UPLOAD_SERVICE] 연동 계정 없음 - "
|
||||||
|
f"user_uuid: {current_user.user_uuid}, social_account_id: {body.social_account_id}"
|
||||||
|
)
|
||||||
|
raise SocialAccountNotFoundError()
|
||||||
|
|
||||||
|
# 3. 진행 중인 업로드 확인 (pending 또는 uploading 상태만)
|
||||||
|
in_progress_result = await session.execute(
|
||||||
|
select(SocialUpload).where(
|
||||||
|
SocialUpload.video_id == body.video_id,
|
||||||
|
SocialUpload.social_account_id == account.id,
|
||||||
|
SocialUpload.status.in_([UploadStatus.PENDING.value, UploadStatus.UPLOADING.value]),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
in_progress_upload = in_progress_result.scalar_one_or_none()
|
||||||
|
|
||||||
|
if in_progress_upload:
|
||||||
|
logger.info(
|
||||||
|
f"[UPLOAD_SERVICE] 진행 중인 업로드 존재 - upload_id: {in_progress_upload.id}"
|
||||||
|
)
|
||||||
|
return SocialUploadResponse(
|
||||||
|
success=True,
|
||||||
|
upload_id=in_progress_upload.id,
|
||||||
|
platform=account.platform,
|
||||||
|
status=in_progress_upload.status,
|
||||||
|
message="이미 업로드가 진행 중입니다.",
|
||||||
|
)
|
||||||
|
|
||||||
|
# 4. 업로드 순번 계산
|
||||||
|
max_seq_result = await session.execute(
|
||||||
|
select(func.coalesce(func.max(SocialUpload.upload_seq), 0)).where(
|
||||||
|
SocialUpload.video_id == body.video_id,
|
||||||
|
SocialUpload.social_account_id == account.id,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
next_seq = (max_seq_result.scalar() or 0) + 1
|
||||||
|
|
||||||
|
# 5. 새 업로드 레코드 생성
|
||||||
|
social_upload = SocialUpload(
|
||||||
|
user_uuid=current_user.user_uuid,
|
||||||
|
video_id=body.video_id,
|
||||||
|
social_account_id=account.id,
|
||||||
|
upload_seq=next_seq,
|
||||||
|
platform=account.platform,
|
||||||
|
status=UploadStatus.PENDING.value,
|
||||||
|
upload_progress=0,
|
||||||
|
title=body.title,
|
||||||
|
description=body.description,
|
||||||
|
tags=body.tags,
|
||||||
|
privacy_status=body.privacy_status.value,
|
||||||
|
scheduled_at=body.scheduled_at,
|
||||||
|
platform_options={
|
||||||
|
**(body.platform_options or {}),
|
||||||
|
"scheduled_at": body.scheduled_at.isoformat() if body.scheduled_at else None,
|
||||||
|
},
|
||||||
|
retry_count=0,
|
||||||
|
)
|
||||||
|
|
||||||
|
session.add(social_upload)
|
||||||
|
await session.commit()
|
||||||
|
await session.refresh(social_upload)
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
f"[UPLOAD_SERVICE] 업로드 레코드 생성 - "
|
||||||
|
f"upload_id: {social_upload.id}, video_id: {body.video_id}, "
|
||||||
|
f"account_id: {account.id}, upload_seq: {next_seq}, platform: {account.platform}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 6. 즉시 업로드이면 백그라운드 태스크 등록
|
||||||
|
now_kst_naive = datetime.now(TIMEZONE).replace(tzinfo=None)
|
||||||
|
is_scheduled = body.scheduled_at and body.scheduled_at > now_kst_naive
|
||||||
|
if not is_scheduled:
|
||||||
|
background_tasks.add_task(process_social_upload, social_upload.id)
|
||||||
|
|
||||||
|
message = "예약 업로드가 등록되었습니다." if is_scheduled else "업로드 요청이 접수되었습니다."
|
||||||
|
return SocialUploadResponse(
|
||||||
|
success=True,
|
||||||
|
upload_id=social_upload.id,
|
||||||
|
platform=account.platform,
|
||||||
|
status=social_upload.status,
|
||||||
|
message=message,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def get_upload_status(
|
||||||
|
self,
|
||||||
|
upload_id: int,
|
||||||
|
current_user: User,
|
||||||
|
session: AsyncSession,
|
||||||
|
) -> SocialUploadStatusResponse:
|
||||||
|
"""업로드 상태 조회"""
|
||||||
|
logger.info(f"[UPLOAD_SERVICE] 상태 조회 - upload_id: {upload_id}")
|
||||||
|
|
||||||
|
result = await session.execute(
|
||||||
|
select(SocialUpload).where(
|
||||||
|
SocialUpload.id == upload_id,
|
||||||
|
SocialUpload.user_uuid == current_user.user_uuid,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
upload = result.scalar_one_or_none()
|
||||||
|
|
||||||
|
if not upload:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="업로드 정보를 찾을 수 없습니다.",
|
||||||
|
)
|
||||||
|
|
||||||
|
return SocialUploadStatusResponse(
|
||||||
|
upload_id=upload.id,
|
||||||
|
video_id=upload.video_id,
|
||||||
|
social_account_id=upload.social_account_id,
|
||||||
|
upload_seq=upload.upload_seq,
|
||||||
|
platform=upload.platform,
|
||||||
|
status=UploadStatus(upload.status),
|
||||||
|
upload_progress=upload.upload_progress,
|
||||||
|
title=upload.title,
|
||||||
|
platform_video_id=upload.platform_video_id,
|
||||||
|
platform_url=upload.platform_url,
|
||||||
|
error_message=upload.error_message,
|
||||||
|
retry_count=upload.retry_count,
|
||||||
|
scheduled_at=upload.scheduled_at,
|
||||||
|
created_at=upload.created_at,
|
||||||
|
uploaded_at=upload.uploaded_at,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def get_upload_history(
|
||||||
|
self,
|
||||||
|
current_user: User,
|
||||||
|
session: AsyncSession,
|
||||||
|
tab: str = "all",
|
||||||
|
platform: Optional[SocialPlatform] = None,
|
||||||
|
year: Optional[int] = None,
|
||||||
|
month: Optional[int] = None,
|
||||||
|
page: int = 1,
|
||||||
|
size: int = 20,
|
||||||
|
) -> SocialUploadHistoryResponse:
|
||||||
|
"""업로드 이력 조회 (탭/년월/플랫폼 필터, 페이지네이션)"""
|
||||||
|
now_kst = datetime.now(TIMEZONE)
|
||||||
|
target_year = year or now_kst.year
|
||||||
|
target_month = month or now_kst.month
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
f"[UPLOAD_SERVICE] 이력 조회 - "
|
||||||
|
f"user_uuid: {current_user.user_uuid}, tab: {tab}, "
|
||||||
|
f"year: {target_year}, month: {target_month}, page: {page}, size: {size}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 월 범위 계산
|
||||||
|
last_day = monthrange(target_year, target_month)[1]
|
||||||
|
month_start = datetime(target_year, target_month, 1, 0, 0, 0)
|
||||||
|
month_end = datetime(target_year, target_month, last_day, 23, 59, 59)
|
||||||
|
|
||||||
|
# 기본 쿼리 (cancelled 제외)
|
||||||
|
base_conditions = [
|
||||||
|
SocialUpload.user_uuid == current_user.user_uuid,
|
||||||
|
SocialUpload.created_at >= month_start,
|
||||||
|
SocialUpload.created_at <= month_end,
|
||||||
|
SocialUpload.status != UploadStatus.CANCELLED.value,
|
||||||
|
]
|
||||||
|
|
||||||
|
query = select(SocialUpload).where(*base_conditions)
|
||||||
|
count_query = select(func.count(SocialUpload.id)).where(*base_conditions)
|
||||||
|
|
||||||
|
# 탭 필터 적용
|
||||||
|
if tab == "completed":
|
||||||
|
query = query.where(SocialUpload.status == UploadStatus.COMPLETED.value)
|
||||||
|
count_query = count_query.where(SocialUpload.status == UploadStatus.COMPLETED.value)
|
||||||
|
elif tab == "scheduled":
|
||||||
|
query = query.where(
|
||||||
|
SocialUpload.status == UploadStatus.PENDING.value,
|
||||||
|
SocialUpload.scheduled_at.isnot(None),
|
||||||
|
)
|
||||||
|
count_query = count_query.where(
|
||||||
|
SocialUpload.status == UploadStatus.PENDING.value,
|
||||||
|
SocialUpload.scheduled_at.isnot(None),
|
||||||
|
)
|
||||||
|
elif tab == "failed":
|
||||||
|
query = query.where(SocialUpload.status == UploadStatus.FAILED.value)
|
||||||
|
count_query = count_query.where(SocialUpload.status == UploadStatus.FAILED.value)
|
||||||
|
|
||||||
|
# 플랫폼 필터 적용
|
||||||
|
if platform:
|
||||||
|
query = query.where(SocialUpload.platform == platform.value)
|
||||||
|
count_query = count_query.where(SocialUpload.platform == platform.value)
|
||||||
|
|
||||||
|
# 총 개수 조회
|
||||||
|
total_result = await session.execute(count_query)
|
||||||
|
total = total_result.scalar() or 0
|
||||||
|
|
||||||
|
# 페이지네이션 적용
|
||||||
|
query = (
|
||||||
|
query.order_by(SocialUpload.created_at.desc())
|
||||||
|
.offset((page - 1) * size)
|
||||||
|
.limit(size)
|
||||||
|
)
|
||||||
|
|
||||||
|
result = await session.execute(query)
|
||||||
|
uploads = result.scalars().all()
|
||||||
|
|
||||||
|
items = [
|
||||||
|
SocialUploadHistoryItem(
|
||||||
|
upload_id=upload.id,
|
||||||
|
video_id=upload.video_id,
|
||||||
|
social_account_id=upload.social_account_id,
|
||||||
|
upload_seq=upload.upload_seq,
|
||||||
|
platform=upload.platform,
|
||||||
|
status=upload.status,
|
||||||
|
title=upload.title,
|
||||||
|
platform_url=upload.platform_url,
|
||||||
|
error_message=upload.error_message,
|
||||||
|
scheduled_at=upload.scheduled_at,
|
||||||
|
created_at=upload.created_at,
|
||||||
|
uploaded_at=upload.uploaded_at,
|
||||||
|
)
|
||||||
|
for upload in uploads
|
||||||
|
]
|
||||||
|
|
||||||
|
return SocialUploadHistoryResponse(
|
||||||
|
items=items,
|
||||||
|
total=total,
|
||||||
|
page=page,
|
||||||
|
size=size,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def retry_upload(
|
||||||
|
self,
|
||||||
|
upload_id: int,
|
||||||
|
current_user: User,
|
||||||
|
session: AsyncSession,
|
||||||
|
background_tasks: BackgroundTasks,
|
||||||
|
) -> SocialUploadResponse:
|
||||||
|
"""실패한 업로드 재시도"""
|
||||||
|
logger.info(f"[UPLOAD_SERVICE] 재시도 요청 - upload_id: {upload_id}")
|
||||||
|
|
||||||
|
result = await session.execute(
|
||||||
|
select(SocialUpload).where(
|
||||||
|
SocialUpload.id == upload_id,
|
||||||
|
SocialUpload.user_uuid == current_user.user_uuid,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
upload = result.scalar_one_or_none()
|
||||||
|
|
||||||
|
if not upload:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="업로드 정보를 찾을 수 없습니다.",
|
||||||
|
)
|
||||||
|
|
||||||
|
if upload.status not in [UploadStatus.FAILED.value, UploadStatus.CANCELLED.value]:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail="실패하거나 취소된 업로드만 재시도할 수 있습니다.",
|
||||||
|
)
|
||||||
|
|
||||||
|
# 상태 초기화
|
||||||
|
upload.status = UploadStatus.PENDING.value
|
||||||
|
upload.upload_progress = 0
|
||||||
|
upload.error_message = None
|
||||||
|
await session.commit()
|
||||||
|
|
||||||
|
background_tasks.add_task(process_social_upload, upload.id)
|
||||||
|
|
||||||
|
return SocialUploadResponse(
|
||||||
|
success=True,
|
||||||
|
upload_id=upload.id,
|
||||||
|
platform=upload.platform,
|
||||||
|
status=upload.status,
|
||||||
|
message="업로드 재시도가 요청되었습니다.",
|
||||||
|
)
|
||||||
|
|
||||||
|
async def cancel_upload(
|
||||||
|
self,
|
||||||
|
upload_id: int,
|
||||||
|
current_user: User,
|
||||||
|
session: AsyncSession,
|
||||||
|
) -> MessageResponse:
|
||||||
|
"""대기 중인 업로드 취소"""
|
||||||
|
logger.info(f"[UPLOAD_SERVICE] 취소 요청 - upload_id: {upload_id}")
|
||||||
|
|
||||||
|
result = await session.execute(
|
||||||
|
select(SocialUpload).where(
|
||||||
|
SocialUpload.id == upload_id,
|
||||||
|
SocialUpload.user_uuid == current_user.user_uuid,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
upload = result.scalar_one_or_none()
|
||||||
|
|
||||||
|
if not upload:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="업로드 정보를 찾을 수 없습니다.",
|
||||||
|
)
|
||||||
|
|
||||||
|
if upload.status != UploadStatus.PENDING.value:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail="대기 중인 업로드만 취소할 수 있습니다.",
|
||||||
|
)
|
||||||
|
|
||||||
|
upload.status = UploadStatus.CANCELLED.value
|
||||||
|
await session.commit()
|
||||||
|
|
||||||
|
return MessageResponse(
|
||||||
|
success=True,
|
||||||
|
message="업로드가 취소되었습니다.",
|
||||||
|
)
|
||||||
+76
-41
@@ -220,6 +220,27 @@ autotext_template_h_1 = {
|
|||||||
"stroke_color": "#333333",
|
"stroke_color": "#333333",
|
||||||
"stroke_width": "0.2 vmin"
|
"stroke_width": "0.2 vmin"
|
||||||
}
|
}
|
||||||
|
DVST0001 = "75161273-0422-4771-adeb-816bd7263fb0"
|
||||||
|
DVST0002 = "c68cf750-bc40-485a-a2c5-3f9fe301e386"
|
||||||
|
DVST0003 = "e1fb5b00-1f02-4f63-99fa-7524b433ba47"
|
||||||
|
DHST0001 = "660be601-080a-43ea-bf0f-adcf4596fa98"
|
||||||
|
DHST0002 = "3f194cc7-464e-4581-9db2-179d42d3e40f"
|
||||||
|
DHST0003 = "f45df555-2956-4a13-9004-ead047070b3d"
|
||||||
|
HST_LIST = [DHST0001,DHST0002,DHST0003]
|
||||||
|
VST_LIST = [DVST0001,DVST0002,DVST0003]
|
||||||
|
|
||||||
|
SCENE_TRACK = 1
|
||||||
|
AUDIO_TRACK = 2
|
||||||
|
SUBTITLE_TRACK = 3
|
||||||
|
KEYWORD_TRACK = 4
|
||||||
|
|
||||||
|
def select_template(orientation:OrientationType):
|
||||||
|
if orientation == "horizontal":
|
||||||
|
return DHST0001
|
||||||
|
elif orientation == "vertical":
|
||||||
|
return DVST0001
|
||||||
|
else:
|
||||||
|
raise
|
||||||
|
|
||||||
async def get_shared_client() -> httpx.AsyncClient:
|
async def get_shared_client() -> httpx.AsyncClient:
|
||||||
"""공유 HTTP 클라이언트를 반환합니다. 없으면 생성합니다."""
|
"""공유 HTTP 클라이언트를 반환합니다. 없으면 생성합니다."""
|
||||||
@@ -264,23 +285,10 @@ class CreatomateService:
|
|||||||
|
|
||||||
BASE_URL = "https://api.creatomate.com"
|
BASE_URL = "https://api.creatomate.com"
|
||||||
|
|
||||||
# 템플릿 설정 (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__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
api_key: str | None = None,
|
api_key: str | None = None,
|
||||||
orientation: OrientationType = "vertical",
|
orientation: OrientationType = "vertical"
|
||||||
target_duration: float | None = None,
|
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
Args:
|
Args:
|
||||||
@@ -294,14 +302,7 @@ class CreatomateService:
|
|||||||
self.orientation = orientation
|
self.orientation = orientation
|
||||||
|
|
||||||
# orientation에 따른 템플릿 설정 가져오기
|
# orientation에 따른 템플릿 설정 가져오기
|
||||||
config = self.TEMPLATE_CONFIG.get(
|
self.template_id = select_template(orientation)
|
||||||
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 = {
|
self.headers = {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
"Authorization": f"Bearer {self.api_key}",
|
"Authorization": f"Bearer {self.api_key}",
|
||||||
@@ -437,7 +438,6 @@ class CreatomateService:
|
|||||||
self,
|
self,
|
||||||
template_id: str,
|
template_id: str,
|
||||||
image_url_list: list[str],
|
image_url_list: list[str],
|
||||||
lyric: str,
|
|
||||||
music_url: str,
|
music_url: str,
|
||||||
address: str = None
|
address: str = None
|
||||||
) -> dict:
|
) -> dict:
|
||||||
@@ -452,9 +452,6 @@ class CreatomateService:
|
|||||||
template_component_data = self.parse_template_component_name(
|
template_component_data = self.parse_template_component_name(
|
||||||
template_data["source"]["elements"]
|
template_data["source"]["elements"]
|
||||||
)
|
)
|
||||||
|
|
||||||
lyric = lyric.replace("\r", "")
|
|
||||||
lyric_splited = lyric.split("\n")
|
|
||||||
modifications = {}
|
modifications = {}
|
||||||
|
|
||||||
for idx, (template_component_name, template_type) in enumerate(
|
for idx, (template_component_name, template_type) in enumerate(
|
||||||
@@ -477,7 +474,6 @@ class CreatomateService:
|
|||||||
self,
|
self,
|
||||||
elements: list,
|
elements: list,
|
||||||
image_url_list: list[str],
|
image_url_list: list[str],
|
||||||
lyric: str,
|
|
||||||
music_url: str,
|
music_url: str,
|
||||||
address: str = None
|
address: str = None
|
||||||
) -> dict:
|
) -> dict:
|
||||||
@@ -715,36 +711,54 @@ class CreatomateService:
|
|||||||
def calc_scene_duration(self, template: dict) -> float:
|
def calc_scene_duration(self, template: dict) -> float:
|
||||||
"""템플릿의 전체 장면 duration을 계산합니다."""
|
"""템플릿의 전체 장면 duration을 계산합니다."""
|
||||||
total_template_duration = 0.0
|
total_template_duration = 0.0
|
||||||
|
track_maximum_duration = {
|
||||||
|
SCENE_TRACK : 0,
|
||||||
|
SUBTITLE_TRACK : 0,
|
||||||
|
KEYWORD_TRACK : 0
|
||||||
|
}
|
||||||
for elem in template["source"]["elements"]:
|
for elem in template["source"]["elements"]:
|
||||||
try:
|
try:
|
||||||
if elem["type"] == "audio":
|
if elem["track"] not in track_maximum_duration:
|
||||||
continue
|
continue
|
||||||
total_template_duration += elem["duration"]
|
if elem["time"] == 0: # elem is auto / 만약 마지막 elem이 auto인데 그 앞에 time이 있는 elem 일 시 버그 발생 확률 있음
|
||||||
if "animations" not in elem:
|
track_maximum_duration[elem["track"]] += elem["duration"]
|
||||||
continue
|
|
||||||
for animation in elem["animations"]:
|
if "animations" not in elem:
|
||||||
assert animation["time"] == 0 # 0이 아닌 경우 확인 필요
|
continue
|
||||||
if animation["transition"]:
|
for animation in elem["animations"]:
|
||||||
total_template_duration -= animation["duration"]
|
assert animation["time"] == 0 # 0이 아닌 경우 확인 필요
|
||||||
|
if animation["transition"]:
|
||||||
|
track_maximum_duration[elem["track"]] -= animation["duration"]
|
||||||
|
else:
|
||||||
|
track_maximum_duration[elem["track"]] = max(track_maximum_duration[elem["track"]], elem["time"] + elem["duration"])
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"[calc_scene_duration] Error processing element: {elem}, {e}")
|
logger.error(f"[calc_scene_duration] Error processing element: {elem}, {e}")
|
||||||
|
|
||||||
|
total_template_duration = max(track_maximum_duration.values())
|
||||||
|
|
||||||
return total_template_duration
|
return total_template_duration
|
||||||
|
|
||||||
def extend_template_duration(self, template: dict, target_duration: float) -> dict:
|
def extend_template_duration(self, template: dict, target_duration: float) -> dict:
|
||||||
"""템플릿의 duration을 target_duration으로 확장합니다."""
|
"""템플릿의 duration을 target_duration으로 확장합니다."""
|
||||||
template["duration"] = target_duration + 0.5 # 늘린것보단 짧게
|
# template["duration"] = target_duration + 0.5 # 늘린것보단 짧게
|
||||||
target_duration += 1 # 수동으로 직접 변경 및 테스트 필요 : 파란박스 생기는것
|
# target_duration += 1 # 수동으로 직접 변경 및 테스트 필요 : 파란박스 생기는것
|
||||||
total_template_duration = self.calc_scene_duration(template)
|
total_template_duration = self.calc_scene_duration(template)
|
||||||
extend_rate = target_duration / total_template_duration
|
extend_rate = target_duration / total_template_duration
|
||||||
new_template = copy.deepcopy(template)
|
new_template = copy.deepcopy(template)
|
||||||
|
|
||||||
for elem in new_template["source"]["elements"]:
|
for elem in new_template["source"]["elements"]:
|
||||||
try:
|
try:
|
||||||
if elem["type"] == "audio":
|
# if elem["type"] == "audio":
|
||||||
|
# continue
|
||||||
|
if elem["track"] == AUDIO_TRACK : # audio track은 패스
|
||||||
continue
|
continue
|
||||||
elem["duration"] = elem["duration"] * extend_rate
|
|
||||||
|
if "time" in elem:
|
||||||
|
elem["time"] = elem["time"] * extend_rate
|
||||||
|
if "duration" in elem:
|
||||||
|
elem["duration"] = elem["duration"] * extend_rate
|
||||||
|
|
||||||
if "animations" not in elem:
|
if "animations" not in elem:
|
||||||
continue
|
continue
|
||||||
for animation in elem["animations"]:
|
for animation in elem["animations"]:
|
||||||
@@ -785,4 +799,25 @@ class CreatomateService:
|
|||||||
return autotext_template_v_1
|
return autotext_template_v_1
|
||||||
case "horizontal":
|
case "horizontal":
|
||||||
return autotext_template_h_1
|
return autotext_template_h_1
|
||||||
|
|
||||||
|
def extract_text_format_from_template(self, template:dict):
|
||||||
|
keyword_list = []
|
||||||
|
subtitle_list = []
|
||||||
|
for elem in template["source"]["elements"]:
|
||||||
|
try: #최상위 내 텍스트만 검사
|
||||||
|
if elem["type"] == "text":
|
||||||
|
if elem["track"] == SUBTITLE_TRACK:
|
||||||
|
subtitle_list.append(elem["name"])
|
||||||
|
elif elem["track"] == KEYWORD_TRACK:
|
||||||
|
keyword_list.append(elem["name"])
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(
|
||||||
|
f"[extend_template_duration] Error processing element: {elem}, {e}"
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
assert(len(keyword_list)==len(subtitle_list))
|
||||||
|
except Exception as E:
|
||||||
|
logger.error("this template does not have same amount of keyword and subtitle.")
|
||||||
|
pitching_list = keyword_list + subtitle_list
|
||||||
|
return pitching_list
|
||||||
@@ -3,6 +3,7 @@ from pydantic import BaseModel
|
|||||||
from config import prompt_settings
|
from config import prompt_settings
|
||||||
from app.utils.logger import get_logger
|
from app.utils.logger import get_logger
|
||||||
from app.utils.prompts.schemas import *
|
from app.utils.prompts.schemas import *
|
||||||
|
from functools import lru_cache
|
||||||
|
|
||||||
logger = get_logger("prompt")
|
logger = get_logger("prompt")
|
||||||
|
|
||||||
@@ -59,6 +60,15 @@ yt_upload_prompt = Prompt(
|
|||||||
prompt_model = prompt_settings.YOUTUBE_PROMPT_MODEL
|
prompt_model = prompt_settings.YOUTUBE_PROMPT_MODEL
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@lru_cache()
|
||||||
|
def create_dynamic_subtitle_prompt(length : int) -> Prompt:
|
||||||
|
prompt_template_path=os.path.join(prompt_settings.PROMPT_FOLDER_ROOT, prompt_settings.SUBTITLE_PROMPT_FILE_NAME)
|
||||||
|
prompt_input_class = SubtitlePromptInput
|
||||||
|
prompt_output_class = SubtitlePromptOutput[length]
|
||||||
|
prompt_model = prompt_settings.SUBTITLE_PROMPT_MODEL
|
||||||
|
return Prompt(prompt_template_path, prompt_input_class, prompt_output_class, prompt_model)
|
||||||
|
|
||||||
|
|
||||||
def reload_all_prompt():
|
def reload_all_prompt():
|
||||||
marketing_prompt._reload_prompt()
|
marketing_prompt._reload_prompt()
|
||||||
lyric_prompt._reload_prompt()
|
lyric_prompt._reload_prompt()
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
from .lyric import LyricPromptInput, LyricPromptOutput
|
from .lyric import LyricPromptInput, LyricPromptOutput
|
||||||
from .marketing import MarketingPromptInput, MarketingPromptOutput
|
from .marketing import MarketingPromptInput, MarketingPromptOutput
|
||||||
from .youtube import YTUploadPromptInput, YTUploadPromptOutput
|
from .youtube import YTUploadPromptInput, YTUploadPromptOutput
|
||||||
|
from .subtitle import SubtitlePromptInput, SubtitlePromptOutput
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
from pydantic import BaseModel, create_model, Field
|
||||||
|
from typing import List, Optional
|
||||||
|
from functools import lru_cache
|
||||||
|
|
||||||
|
# Input 정의
|
||||||
|
|
||||||
|
class SubtitlePromptInput(BaseModel):
|
||||||
|
marketing_intelligence : str = Field(..., description="마케팅 인텔리전스 정보")
|
||||||
|
pitching_tag_list_string : str = Field(..., description="필요한 피칭 레이블 리스트 stringify")
|
||||||
|
customer_name : str = Field(..., description = "마케팅 대상 사업체 이름")
|
||||||
|
detail_region_info : str = Field(..., description = "마케팅 대상 지역 상세")
|
||||||
|
|
||||||
|
#subtillecars :
|
||||||
|
# Output 정의
|
||||||
|
class PitchingOutput(BaseModel):
|
||||||
|
pitching_tag: str = Field(..., description="피칭 레이블")
|
||||||
|
pitching_data: str = Field(..., description = "피칭 내용물")
|
||||||
|
|
||||||
|
class SubtitlePromptOutput(BaseModel):
|
||||||
|
pitching_results: List[PitchingOutput] = Field(..., description = "피칭 리스트")
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
@lru_cache()
|
||||||
|
def __class_getitem__(cls, n: int):
|
||||||
|
return create_model(
|
||||||
|
cls.__name__,
|
||||||
|
pitching_results=(
|
||||||
|
List[PitchingOutput],
|
||||||
|
Field(..., min_length=n, max_length=n, description="피칭 리스트")
|
||||||
|
),
|
||||||
|
)
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
당신은 숙박 브랜드 숏폼 영상의 자막 콘텐츠를 추출하는 전문가입니다.
|
||||||
|
|
||||||
|
입력으로 주어지는 **1) 5가지 기준의 레이어 이름 리스트**와 **2) 마케팅 인텔리전스 분석 결과(JSON)**를 바탕으로, 각 레이어 이름의 의미에 정확히 1:1 매칭되는 텍스트 콘텐츠만을 추출하세요.
|
||||||
|
|
||||||
|
분석 결과에 없는 정보는 절대 지어내거나 추론하지 마세요. 오직 제공된 JSON 데이터 내에서만 텍스트를 구성해야 합니다.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 레이어 네이밍 규칙 해석 및 매핑 가이드
|
||||||
|
|
||||||
|
입력되는 모든 레이어 이름은 예외 없이 `<track_role>-<narrative_phase>-<content_type>-<tone>-<pair_id>` 의 5단계 구조로 되어 있습니다.
|
||||||
|
마지막의 3자리 숫자 ID(`-001`, `-002` 등)는 모든 레이어에 필수적으로 부여됩니다.
|
||||||
|
|
||||||
|
### [1] track_role (텍스트 형태)
|
||||||
|
- `subtitle`: 씬 상황을 설명하는 간결한 문장형 텍스트 (1줄 이내)
|
||||||
|
- `keyword`: 씬을 상징하고 시선을 끄는 단답형/명사형 텍스트 (1~2단어)
|
||||||
|
|
||||||
|
### [2] narrative_phase (영상 흐름)
|
||||||
|
- `intro`: 영상 도입부. 가장 시선을 끄는 정보를 배치.
|
||||||
|
- `core`: 핵심 매력이나 주요 편의 시설 어필.
|
||||||
|
- `highlight`: 세부적인 매력 포인트나 공간의 특별한 분위기 묘사.
|
||||||
|
- `outro`: 영상 마무리. 브랜드 명칭 복기 및 타겟/위치 정보 제공.
|
||||||
|
|
||||||
|
### [3] content_type (데이터 매핑 대상)
|
||||||
|
- `hook_claim` 👉 `selling_points`에서 점수가 가장 높은 1순위 소구점이나 `market_positioning.core_value`를 활용하여 가장 강력한 핵심 세일즈 포인트를 어필. (가장 강력한 셀링포인트를 의미함)
|
||||||
|
- `selling_point` 👉 `selling_points`의 `description`, `korean_category` 등을 narrative 흐름에 맞춰 순차적으로 추출.
|
||||||
|
- `brand_name` 👉 JSON의 `store_name`을 추출.
|
||||||
|
- `location_info` 👉 JSON의 `detail_region_info`를 요약.
|
||||||
|
- `target_tag` 👉 `target_persona`나 `target_keywords`에서 타겟 고객군 또는 해시태그 추출.
|
||||||
|
|
||||||
|
### [4] tone (텍스트 어조)
|
||||||
|
- `sensory`: 직관적이고 감각적인 단어 사용
|
||||||
|
- `factual`: 과장 없이 사실 정보를 담백하게 전달
|
||||||
|
- `empathic`: 고객의 상황에 공감하는 따뜻한 어조
|
||||||
|
- `aspirational`: 열망을 자극하고 기대감을 주는 느낌
|
||||||
|
|
||||||
|
### [5] pair_id (씬 묶음 식별 번호)
|
||||||
|
- 텍스트 레이어는 `subtitle`과 `keyword`가 하나의 페어(Pair)를 이뤄 하나의 씬(Scene)에서 함께 등장합니다.
|
||||||
|
- 따라서 **동일한 씬에 속하는 `subtitle`과 `keyword` 레이어는 동일한 3자리 순번 ID(예: `-001`)**를 공유합니다.
|
||||||
|
- 영상 전반적인 씬 전개 순서에 따라 **다음 씬으로 넘어갈 때마다 ID가 순차적으로 증가**합니다. (예: 씬1은 `-001`, 씬2는 `-002`, 씬3은 `-003`...)
|
||||||
|
- **중요**: ID가 달라진다는 것은 '새로운 씬' 혹은 '다른 텍스트 쌍'을 의미하므로, **ID가 바뀌면 반드시 JSON 내의 다른 소구점이나 데이터를 추출**하여 내용이 중복되지 않도록 해야 합니다.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 콘텐츠 추출 시 주의사항
|
||||||
|
|
||||||
|
1. 각 입력 레이어 이름 1개당 **오직 1개의 텍스트 콘텐츠**만 매핑하여 출력합니다. (레이어명 이름 자체를 수정하거나 새로 만들지 마세요.)
|
||||||
|
2. `content_type`이 `selling_point`로 동일하더라도, `narrative_phase`(core, highlight)나 `tone`이 달라지면 JSON 내의 2순위, 3순위 세일즈 포인트를 순차적으로 활용하여 내용 겹침을 방지하세요.
|
||||||
|
3. 같은 씬에 속하는(같은 ID 번호를 가진) keyword는 핵심 단어로, subtitle은 적절한 마케팅 문구가 되어야 하며, 자연스럽게 이어지는 문맥을 형성하도록 구성하세요.
|
||||||
|
4. keyword가 subtitle에 완전히 포함되는 단어가 되지 않도록 유의하세요.
|
||||||
|
5. 정보 태그가 같더라도 ID가 다르다면 중복되지 않는 새로운 텍스트를 도출해야 합니다.
|
||||||
|
6. 콘텐츠 추출 시 마케팅 인텔리전스의 내용을 그대로 사용하기보다는 paraphrase을 수행하세요.
|
||||||
|
7. keyword는 공백 포함 전각 8자 / 반각 16자내, subtitle은 전각 15자 / 반각 30자 내로 구성하세요.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 출력 결과 포맷 및 예시
|
||||||
|
|
||||||
|
입력된 레이어 이름 순서에 맞춰, 매핑된 텍스트 콘텐츠만 작성하세요. (반드시 intro, core, highlight, outro 등 모든 씬 단계가 명확하게 매핑되어야 합니다.)
|
||||||
|
|
||||||
|
### 입력 레이어 리스트 예시 및 출력 예시
|
||||||
|
|
||||||
|
| Layer Name | Text Content |
|
||||||
|
|---|---|
|
||||||
|
| subtitle-intro-hook_claim-aspirational-001 | 반려견과 눈치 없이 온전하게 쉬는 완벽한 휴식 |
|
||||||
|
| keyword-intro-brand_name-sensory-001 | 스테이펫 홍천 |
|
||||||
|
| subtitle-core-selling_point-empathic-002 | 우리만의 독립된 공간감이 주는 진정한 쉼 |
|
||||||
|
| keyword-core-selling_point-factual-002 | 프라이빗 독채 |
|
||||||
|
| subtitle-highlight-selling_point-sensory-003 | 탁 트인 야외 무드존과 포토 스팟의 감성 컷 |
|
||||||
|
| keyword-highlight-selling_point-factual-003 | 넓은 정원 |
|
||||||
|
| subtitle-outro-target_tag-empathic-004 | #강원도애견동반 #주말숏브레이크 |
|
||||||
|
| keyword-outro-location_info-factual-004 | 강원 홍천군 화촌면 |
|
||||||
|
|
||||||
|
|
||||||
|
# 입력
|
||||||
|
**입력 1: 레이어 이름 리스트**
|
||||||
|
{pitching_tag_list_string}
|
||||||
|
|
||||||
|
**입력 2: 마케팅 인텔리전스 JSON**
|
||||||
|
{marketing_intelligence}
|
||||||
|
|
||||||
|
**입력 3: 비즈니스 정보 **
|
||||||
|
Business Name: {customer_name}
|
||||||
|
Region Details: {detail_region_info}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import copy
|
||||||
|
import time
|
||||||
|
import json
|
||||||
|
from typing import Literal, Any
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.utils.logger import get_logger
|
||||||
|
from app.utils.chatgpt_prompt import ChatgptService
|
||||||
|
from app.utils.prompts.schemas import *
|
||||||
|
from app.utils.prompts.prompts import *
|
||||||
|
|
||||||
|
class SubtitleContentsGenerator():
|
||||||
|
def __init__(self):
|
||||||
|
self.chatgpt_service = ChatgptService()
|
||||||
|
|
||||||
|
async def generate_subtitle_contents(self, marketing_intelligence : dict[str, Any], pitching_label_list : list[Any], customer_name : str, detail_region_info : str) -> SubtitlePromptOutput:
|
||||||
|
dynamic_subtitle_prompt = create_dynamic_subtitle_prompt(len(pitching_label_list))
|
||||||
|
pitching_label_string = "\n".join(pitching_label_list)
|
||||||
|
marketing_intel_string = json.dumps(marketing_intelligence, ensure_ascii=False)
|
||||||
|
input_data = {
|
||||||
|
"marketing_intelligence" : marketing_intel_string ,
|
||||||
|
"pitching_tag_list_string" : pitching_label_string,
|
||||||
|
"customer_name" : customer_name,
|
||||||
|
"detail_region_info" : detail_region_info,
|
||||||
|
}
|
||||||
|
output_data = await self.chatgpt_service.generate_structured_output(dynamic_subtitle_prompt, input_data)
|
||||||
|
return output_data
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -14,6 +14,8 @@ Video API Router
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import asyncio
|
||||||
|
|
||||||
from typing import Literal
|
from typing import Literal
|
||||||
|
|
||||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query
|
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query
|
||||||
@@ -23,10 +25,11 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||||||
from app.database.session import get_session
|
from app.database.session import get_session
|
||||||
from app.user.dependencies.auth import get_current_user
|
from app.user.dependencies.auth import get_current_user
|
||||||
from app.user.models import User
|
from app.user.models import User
|
||||||
from app.home.models import Image, Project
|
from app.home.models import Image, Project, MarketingIntel
|
||||||
from app.lyric.models import Lyric
|
from app.lyric.models import Lyric
|
||||||
from app.song.models import Song, SongTimestamp
|
from app.song.models import Song, SongTimestamp
|
||||||
from app.utils.creatomate import CreatomateService
|
from app.utils.creatomate import CreatomateService
|
||||||
|
from app.utils.subtitles import SubtitleContentsGenerator
|
||||||
from app.utils.logger import get_logger
|
from app.utils.logger import get_logger
|
||||||
from app.video.models import Video
|
from app.video.models import Video
|
||||||
from app.video.schemas.video_schema import (
|
from app.video.schemas.video_schema import (
|
||||||
@@ -144,6 +147,34 @@ async def generate_video(
|
|||||||
image_urls: list[str] = []
|
image_urls: list[str] = []
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
subtitle_done = False
|
||||||
|
count = 0
|
||||||
|
async with AsyncSessionLocal() as session:
|
||||||
|
project_result = await session.execute(
|
||||||
|
select(Project)
|
||||||
|
.where(Project.task_id == task_id)
|
||||||
|
.order_by(Project.created_at.desc())
|
||||||
|
.limit(1)
|
||||||
|
)
|
||||||
|
project = project_result.scalar_one_or_none()
|
||||||
|
|
||||||
|
while not subtitle_done:
|
||||||
|
async with AsyncSessionLocal() as session:
|
||||||
|
logger.info(f"[generate_video] Checking subtitle- task_id: {task_id}, count : {count}")
|
||||||
|
marketing_result = await session.execute(
|
||||||
|
select(MarketingIntel).where(MarketingIntel.id == project.marketing_intelligence)
|
||||||
|
)
|
||||||
|
marketing_intelligence = marketing_result.scalar_one_or_none()
|
||||||
|
subtitle_done = bool(marketing_intelligence.subtitle)
|
||||||
|
if subtitle_done:
|
||||||
|
logger.info(f"[generate_video] Check subtitle done task_id: {task_id}")
|
||||||
|
break
|
||||||
|
await asyncio.sleep(5)
|
||||||
|
if count > 12 :
|
||||||
|
raise Exception("subtitle 결과 생성 실패")
|
||||||
|
count += 1
|
||||||
|
|
||||||
|
|
||||||
# 세션을 명시적으로 열고 DB 작업 후 바로 닫음
|
# 세션을 명시적으로 열고 DB 작업 후 바로 닫음
|
||||||
async with AsyncSessionLocal() as session:
|
async with AsyncSessionLocal() as session:
|
||||||
# ===== 순차 쿼리 실행: Project, Lyric, Song, Image =====
|
# ===== 순차 쿼리 실행: Project, Lyric, Song, Image =====
|
||||||
@@ -198,6 +229,12 @@ async def generate_video(
|
|||||||
)
|
)
|
||||||
project_id = project.id
|
project_id = project.id
|
||||||
store_address = project.detail_region_info
|
store_address = project.detail_region_info
|
||||||
|
# customer_name = project.store_name
|
||||||
|
|
||||||
|
marketing_result = await session.execute(
|
||||||
|
select(MarketingIntel).where(MarketingIntel.id == project.marketing_intelligence)
|
||||||
|
)
|
||||||
|
marketing_intelligence = marketing_result.scalar_one_or_none()
|
||||||
|
|
||||||
# ===== 결과 처리: Lyric =====
|
# ===== 결과 처리: Lyric =====
|
||||||
lyric = lyric_result.scalar_one_or_none()
|
lyric = lyric_result.scalar_one_or_none()
|
||||||
@@ -287,16 +324,16 @@ async def generate_video(
|
|||||||
# 2단계: 외부 API 호출 (세션 사용 안함 - 커넥션 풀 점유 없음)
|
# 2단계: 외부 API 호출 (세션 사용 안함 - 커넥션 풀 점유 없음)
|
||||||
# ==========================================================================
|
# ==========================================================================
|
||||||
stage2_start = time.perf_counter()
|
stage2_start = time.perf_counter()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
logger.info(
|
logger.info(
|
||||||
f"[generate_video] Stage 2 START - Creatomate API - task_id: {task_id}"
|
f"[generate_video] Stage 2 START - Creatomate API - task_id: {task_id}"
|
||||||
)
|
)
|
||||||
creatomate_service = CreatomateService(
|
creatomate_service = CreatomateService(
|
||||||
orientation=orientation,
|
orientation=orientation
|
||||||
target_duration=song_duration,
|
|
||||||
)
|
)
|
||||||
logger.debug(
|
logger.debug(
|
||||||
f"[generate_video] Using template_id: {creatomate_service.template_id}, duration: {creatomate_service.target_duration} (song duration: {song_duration})"
|
f"[generate_video] Using template_id: {creatomate_service.template_id}, (song duration: {song_duration})"
|
||||||
)
|
)
|
||||||
|
|
||||||
# 6-1. 템플릿 조회 (비동기)
|
# 6-1. 템플릿 조회 (비동기)
|
||||||
@@ -309,29 +346,32 @@ async def generate_video(
|
|||||||
modifications = creatomate_service.elements_connect_resource_blackbox(
|
modifications = creatomate_service.elements_connect_resource_blackbox(
|
||||||
elements=template["source"]["elements"],
|
elements=template["source"]["elements"],
|
||||||
image_url_list=image_urls,
|
image_url_list=image_urls,
|
||||||
lyric=lyrics,
|
|
||||||
music_url=music_url,
|
music_url=music_url,
|
||||||
address=store_address
|
address=store_address
|
||||||
)
|
)
|
||||||
logger.debug(f"[generate_video] Modifications created - task_id: {task_id}")
|
logger.debug(f"[generate_video] Modifications created - task_id: {task_id}")
|
||||||
|
|
||||||
|
subtitle_modifications = marketing_intelligence.subtitle
|
||||||
|
|
||||||
|
modifications.update(subtitle_modifications)
|
||||||
# 6-3. elements 수정
|
# 6-3. elements 수정
|
||||||
new_elements = creatomate_service.modify_element(
|
new_elements = creatomate_service.modify_element(
|
||||||
template["source"]["elements"],
|
template["source"]["elements"],
|
||||||
modifications,
|
modifications,
|
||||||
)
|
)
|
||||||
template["source"]["elements"] = new_elements
|
template["source"]["elements"] = new_elements
|
||||||
|
|
||||||
logger.debug(f"[generate_video] Elements modified - task_id: {task_id}")
|
logger.debug(f"[generate_video] Elements modified - task_id: {task_id}")
|
||||||
|
|
||||||
|
|
||||||
# 6-4. duration 확장
|
# 6-4. duration 확장
|
||||||
final_template = creatomate_service.extend_template_duration(
|
final_template = creatomate_service.extend_template_duration(
|
||||||
template,
|
template,
|
||||||
creatomate_service.target_duration,
|
song_duration,
|
||||||
)
|
|
||||||
logger.debug(
|
|
||||||
f"[generate_video] Duration extended to {creatomate_service.target_duration}s - task_id: {task_id}"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
logger.debug(f"[generate_video] Duration extended - task_id: {task_id}")
|
||||||
|
|
||||||
song_timestamp_result = await session.execute(
|
song_timestamp_result = await session.execute(
|
||||||
select(SongTimestamp).where(
|
select(SongTimestamp).where(
|
||||||
SongTimestamp.suno_audio_id == song.suno_audio_id
|
SongTimestamp.suno_audio_id == song.suno_audio_id
|
||||||
@@ -339,13 +379,10 @@ async def generate_video(
|
|||||||
)
|
)
|
||||||
song_timestamp_list = song_timestamp_result.scalars().all()
|
song_timestamp_list = song_timestamp_result.scalars().all()
|
||||||
|
|
||||||
logger.debug(
|
logger.debug(f"[generate_video] song_timestamp_list count: {len(song_timestamp_list)}")
|
||||||
f"[generate_video] song_timestamp_list count: {len(song_timestamp_list)}"
|
|
||||||
)
|
|
||||||
for i, ts in enumerate(song_timestamp_list):
|
for i, ts in enumerate(song_timestamp_list):
|
||||||
logger.debug(
|
logger.debug(f"[generate_video] timestamp[{i}]: lyric_line={ts.lyric_line}, start_time={ts.start_time}, end_time={ts.end_time}")
|
||||||
f"[generate_video] timestamp[{i}]: lyric_line={ts.lyric_line}, start_time={ts.start_time}, end_time={ts.end_time}"
|
|
||||||
)
|
|
||||||
|
|
||||||
match lyric_language:
|
match lyric_language:
|
||||||
case "English" :
|
case "English" :
|
||||||
@@ -355,33 +392,32 @@ async def generate_video(
|
|||||||
lyric_font = "Noto Sans"
|
lyric_font = "Noto Sans"
|
||||||
|
|
||||||
# LYRIC AUTO 결정부
|
# LYRIC AUTO 결정부
|
||||||
if (creatomate_settings.DEBUG_AUTO_LYRIC):
|
if (creatomate_settings.LYRIC_SUBTITLE):
|
||||||
auto_text_template = creatomate_service.get_auto_text_template()
|
if (creatomate_settings.DEBUG_AUTO_LYRIC):
|
||||||
final_template["source"]["elements"].append(creatomate_service.auto_lyric(auto_text_template))
|
auto_text_template = creatomate_service.get_auto_text_template()
|
||||||
else :
|
final_template["source"]["elements"].append(creatomate_service.auto_lyric(auto_text_template))
|
||||||
text_template = creatomate_service.get_text_template()
|
else :
|
||||||
for idx, aligned in enumerate(song_timestamp_list):
|
text_template = creatomate_service.get_text_template()
|
||||||
caption = creatomate_service.lining_lyric(
|
for idx, aligned in enumerate(song_timestamp_list):
|
||||||
text_template,
|
caption = creatomate_service.lining_lyric(
|
||||||
idx,
|
text_template,
|
||||||
aligned.lyric_line,
|
idx,
|
||||||
aligned.start_time,
|
aligned.lyric_line,
|
||||||
aligned.end_time,
|
aligned.start_time,
|
||||||
lyric_font
|
aligned.end_time,
|
||||||
)
|
lyric_font
|
||||||
final_template["source"]["elements"].append(caption)
|
)
|
||||||
|
final_template["source"]["elements"].append(caption)
|
||||||
# END - LYRIC AUTO 결정부
|
# END - LYRIC AUTO 결정부
|
||||||
# logger.debug(
|
# logger.debug(
|
||||||
# f"[generate_video] final_template: {json.dumps(final_template, indent=2, ensure_ascii=False)}"
|
# f"[generate_video] final_template: {json.dumps(final_template, indent=2, ensure_ascii=False)}"
|
||||||
# )
|
# )
|
||||||
|
|
||||||
# 6-5. 커스텀 렌더링 요청 (비동기)
|
# 6-5. 커스텀 렌더링 요청 (비동기)
|
||||||
render_response = await creatomate_service.make_creatomate_custom_call_async(
|
render_response = await creatomate_service.make_creatomate_custom_call_async(
|
||||||
final_template["source"],
|
final_template["source"],
|
||||||
)
|
)
|
||||||
logger.debug(
|
|
||||||
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 추출
|
# 렌더 ID 추출
|
||||||
if isinstance(render_response, list) and len(render_response) > 0:
|
if isinstance(render_response, list) and len(render_response) > 0:
|
||||||
@@ -402,6 +438,8 @@ async def generate_video(
|
|||||||
logger.error(
|
logger.error(
|
||||||
f"[generate_video] Creatomate API EXCEPTION - task_id: {task_id}, error: {e}"
|
f"[generate_video] Creatomate API EXCEPTION - task_id: {task_id}, error: {e}"
|
||||||
)
|
)
|
||||||
|
import traceback
|
||||||
|
logger.error(traceback.format_exc())
|
||||||
# 외부 API 실패 시 Video 상태를 failed로 업데이트
|
# 외부 API 실패 시 Video 상태를 failed로 업데이트
|
||||||
from app.database.session import AsyncSessionLocal
|
from app.database.session import AsyncSessionLocal
|
||||||
|
|
||||||
@@ -521,11 +559,7 @@ async def get_video_status(
|
|||||||
current_user: User = Depends(get_current_user),
|
current_user: User = Depends(get_current_user),
|
||||||
session: AsyncSession = Depends(get_session),
|
session: AsyncSession = Depends(get_session),
|
||||||
) -> PollingVideoResponse:
|
) -> PollingVideoResponse:
|
||||||
"""creatomate_render_id로 영상 생성 작업의 상태를 조회합니다.
|
|
||||||
|
|
||||||
succeeded 상태인 경우 백그라운드에서 MP4 파일을 다운로드하고
|
|
||||||
Video 테이블의 status를 completed로, result_movie_url을 업데이트합니다.
|
|
||||||
"""
|
|
||||||
logger.info(
|
logger.info(
|
||||||
f"[get_video_status] START - creatomate_render_id: {creatomate_render_id}"
|
f"[get_video_status] START - creatomate_render_id: {creatomate_render_id}"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -170,7 +170,11 @@ class CreatomateSettings(BaseSettings):
|
|||||||
)
|
)
|
||||||
DEBUG_AUTO_LYRIC: bool = Field(
|
DEBUG_AUTO_LYRIC: bool = Field(
|
||||||
default=False,
|
default=False,
|
||||||
description="Creatomate 자동 가사 생성 기능 사용 여부",
|
description="Creatomate 자체 자동 가사 생성 기능 사용 여부",
|
||||||
|
)
|
||||||
|
LYRIC_SUBTITLE: bool = Field(
|
||||||
|
default=False,
|
||||||
|
description="영상 가사 표기 여부"
|
||||||
)
|
)
|
||||||
|
|
||||||
model_config = _base_config
|
model_config = _base_config
|
||||||
@@ -186,6 +190,10 @@ class PromptSettings(BaseSettings):
|
|||||||
|
|
||||||
YOUTUBE_PROMPT_FILE_NAME : str = Field(default="yt_upload_prompt.txt")
|
YOUTUBE_PROMPT_FILE_NAME : str = Field(default="yt_upload_prompt.txt")
|
||||||
YOUTUBE_PROMPT_MODEL : str = Field(default="gpt-5-mini")
|
YOUTUBE_PROMPT_MODEL : str = Field(default="gpt-5-mini")
|
||||||
|
|
||||||
|
SUBTITLE_PROMPT_FILE_NAME : str = Field(...)
|
||||||
|
SUBTITLE_PROMPT_MODEL : str = Field(...)
|
||||||
|
|
||||||
model_config = _base_config
|
model_config = _base_config
|
||||||
|
|
||||||
|
|
||||||
@@ -566,6 +574,17 @@ class SocialOAuthSettings(BaseSettings):
|
|||||||
model_config = _base_config
|
model_config = _base_config
|
||||||
|
|
||||||
|
|
||||||
|
class InternalSettings(BaseSettings):
|
||||||
|
"""내부 서버 간 통신 설정"""
|
||||||
|
|
||||||
|
INTERNAL_SECRET_KEY: str = Field(
|
||||||
|
default="change-me-internal-secret-key",
|
||||||
|
description="스케줄러 서버 → 백엔드 내부 API 인증 키",
|
||||||
|
)
|
||||||
|
|
||||||
|
model_config = _base_config
|
||||||
|
|
||||||
|
|
||||||
class SocialUploadSettings(BaseSettings):
|
class SocialUploadSettings(BaseSettings):
|
||||||
"""소셜 미디어 업로드 설정
|
"""소셜 미디어 업로드 설정
|
||||||
|
|
||||||
@@ -613,4 +632,5 @@ kakao_settings = KakaoSettings()
|
|||||||
jwt_settings = JWTSettings()
|
jwt_settings = JWTSettings()
|
||||||
recovery_settings = RecoverySettings()
|
recovery_settings = RecoverySettings()
|
||||||
social_oauth_settings = SocialOAuthSettings()
|
social_oauth_settings = SocialOAuthSettings()
|
||||||
|
internal_settings = InternalSettings()
|
||||||
social_upload_settings = SocialUploadSettings()
|
social_upload_settings = SocialUploadSettings()
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
-- ============================================================
|
||||||
|
-- Migration: social_upload 테이블에 scheduled_at 컬럼 추가
|
||||||
|
-- Date: 2026-03-05
|
||||||
|
-- Description: SNS 예약 업로드 스케줄러를 위한 예약 게시 시간 컬럼 추가
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
ALTER TABLE social_upload
|
||||||
|
ADD COLUMN scheduled_at DATETIME NULL COMMENT '예약 게시 시간 (스케줄러가 이 시간 이후에 업로드 실행)'
|
||||||
|
AFTER privacy_status;
|
||||||
@@ -23,6 +23,7 @@ from app.video.api.routers.v1.video import router as video_router
|
|||||||
from app.social.api.routers.v1.oauth import router as social_oauth_router
|
from app.social.api.routers.v1.oauth import router as social_oauth_router
|
||||||
from app.social.api.routers.v1.upload import router as social_upload_router
|
from app.social.api.routers.v1.upload import router as social_upload_router
|
||||||
from app.social.api.routers.v1.seo import router as social_seo_router
|
from app.social.api.routers.v1.seo import router as social_seo_router
|
||||||
|
from app.social.api.routers.v1.internal import router as social_internal_router
|
||||||
from app.utils.cors import CustomCORSMiddleware
|
from app.utils.cors import CustomCORSMiddleware
|
||||||
from config import prj_settings
|
from config import prj_settings
|
||||||
|
|
||||||
@@ -391,6 +392,7 @@ app.include_router(archive_router) # Archive API 라우터 추가
|
|||||||
app.include_router(social_oauth_router, prefix="/social") # Social OAuth 라우터 추가
|
app.include_router(social_oauth_router, prefix="/social") # Social OAuth 라우터 추가
|
||||||
app.include_router(social_upload_router, prefix="/social") # Social Upload 라우터 추가
|
app.include_router(social_upload_router, prefix="/social") # Social Upload 라우터 추가
|
||||||
app.include_router(social_seo_router, prefix="/social") # Social Upload 라우터 추가
|
app.include_router(social_seo_router, prefix="/social") # Social Upload 라우터 추가
|
||||||
|
app.include_router(social_internal_router) # 내부 스케줄러 전용 라우터
|
||||||
app.include_router(sns_router) # SNS API 라우터 추가
|
app.include_router(sns_router) # SNS API 라우터 추가
|
||||||
app.include_router(dashboard_router) # Dashboard API 라우터 추가
|
app.include_router(dashboard_router) # Dashboard API 라우터 추가
|
||||||
|
|
||||||
|
|||||||
@@ -1,422 +0,0 @@
|
|||||||
# 서버 JWT 토큰 라이프사이클 로깅 강화 계획
|
|
||||||
|
|
||||||
## 1. 토큰 라이프사이클 개요
|
|
||||||
|
|
||||||
서버가 직접 발급/관리하는 JWT 토큰의 전체 흐름:
|
|
||||||
|
|
||||||
```
|
|
||||||
[발급] kakao_login() / generate_test_token()
|
|
||||||
├── Access Token 생성 (sub=user_uuid, type=access, exp=60분)
|
|
||||||
├── Refresh Token 생성 (sub=user_uuid, type=refresh, exp=7일)
|
|
||||||
└── Refresh Token DB 저장 (token_hash, user_id, expires_at)
|
|
||||||
│
|
|
||||||
▼
|
|
||||||
[검증] get_current_user() — 매 요청마다 Access Token 검증
|
|
||||||
├── Bearer 헤더에서 토큰 추출
|
|
||||||
├── decode_token() → payload (sub, type, exp)
|
|
||||||
├── type == "access" 확인
|
|
||||||
└── user_uuid로 사용자 조회/활성 확인
|
|
||||||
│
|
|
||||||
▼
|
|
||||||
[갱신] refresh_tokens() — Access Token 만료 시 Refresh Token으로 갱신
|
|
||||||
├── 기존 Refresh Token 디코딩 → payload
|
|
||||||
├── token_hash로 DB 조회 → is_revoked / expires_at 확인
|
|
||||||
├── 기존 Refresh Token 폐기 (is_revoked=True)
|
|
||||||
├── 새 Access Token + 새 Refresh Token 발급
|
|
||||||
└── 새 Refresh Token DB 저장
|
|
||||||
│
|
|
||||||
▼
|
|
||||||
[폐기] logout() / logout_all()
|
|
||||||
├── 단일: token_hash로 해당 Refresh Token 폐기
|
|
||||||
└── 전체: user_id로 모든 Refresh Token 폐기
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. 현황 분석 — 로깅 공백 지점
|
|
||||||
|
|
||||||
### 발급 단계
|
|
||||||
| 위치 | 함수 | 현재 로깅 | 부족한 정보 |
|
|
||||||
|------|------|----------|------------|
|
|
||||||
| `jwt.py` | `create_access_token()` | 없음 | 발급 대상(user_uuid), 만료시간 |
|
|
||||||
| `jwt.py` | `create_refresh_token()` | 없음 | 발급 대상(user_uuid), 만료시간 |
|
|
||||||
| `auth.py` (service) | `_save_refresh_token()` | 없음 | DB 저장 결과(token_hash, expires_at) |
|
|
||||||
| `auth.py` (service) | `kakao_login()` | `debug`로 토큰 앞 30자 출력 | 충분 (변경 불필요) |
|
|
||||||
|
|
||||||
### 검증 단계
|
|
||||||
| 위치 | 함수 | 현재 로깅 | 부족한 정보 |
|
|
||||||
|------|------|----------|------------|
|
|
||||||
| `jwt.py` | `decode_token()` | 없음 | 디코딩 성공 시 payload 내용, 실패 시 원인 |
|
|
||||||
| `auth.py` (dependency) | `get_current_user()` | 없음 | 검증 각 단계 통과/실패 사유, 토큰 내 정보 |
|
|
||||||
| `auth.py` (dependency) | `get_current_user_optional()` | 없음 | 위와 동일 |
|
|
||||||
|
|
||||||
### 갱신 단계
|
|
||||||
| 위치 | 함수 | 현재 로깅 | 부족한 정보 |
|
|
||||||
|------|------|----------|------------|
|
|
||||||
| `auth.py` (router) | `refresh_token()` | 없음 | 수신 토큰 정보, 갱신 결과 |
|
|
||||||
| `auth.py` (service) | `refresh_tokens()` | 진입/완료 `info` 1줄씩 | 각 단계 실패 사유, DB 토큰 상태, 신규 토큰 정보 |
|
|
||||||
|
|
||||||
### 폐기 단계
|
|
||||||
| 위치 | 함수 | 현재 로깅 | 부족한 정보 |
|
|
||||||
|------|------|----------|------------|
|
|
||||||
| `auth.py` (router) | `logout()`, `logout_all()` | 없음 | 요청 수신, 대상 사용자 |
|
|
||||||
| `auth.py` (service) | `logout()`, `logout_all()` | 없음 | 폐기 대상, 폐기 결과 |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. 수정 대상 파일
|
|
||||||
|
|
||||||
| # | 파일 | 수정 내용 |
|
|
||||||
|---|------|----------|
|
|
||||||
| 1 | `app/user/services/jwt.py` | 토큰 발급 로그 + `decode_token()` 실패 원인 분류 |
|
|
||||||
| 2 | `app/user/dependencies/auth.py` | Access Token 검증 과정 로깅 |
|
|
||||||
| 3 | `app/user/services/auth.py` | `refresh_tokens()`, `_save_refresh_token()`, `logout()`, `logout_all()` 로깅 |
|
|
||||||
| 4 | `app/user/api/routers/v1/auth.py` | `refresh_token()`, `logout()`, `logout_all()` 라우터 로깅 |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. 상세 구현 계획
|
|
||||||
|
|
||||||
### 4-1. `jwt.py` — 토큰 발급 로그 + 디코딩 실패 원인 분류
|
|
||||||
|
|
||||||
**import 추가:**
|
|
||||||
```python
|
|
||||||
import logging
|
|
||||||
from jose import JWTError, ExpiredSignatureError, JWTClaimsError, jwt
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
```
|
|
||||||
|
|
||||||
**`create_access_token()` — 발급 로그 추가:**
|
|
||||||
```python
|
|
||||||
def create_access_token(user_uuid: str) -> str:
|
|
||||||
expire = now() + timedelta(minutes=jwt_settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES)
|
|
||||||
to_encode = {"sub": user_uuid, "exp": expire, "type": "access"}
|
|
||||||
token = jwt.encode(to_encode, jwt_settings.JWT_SECRET, algorithm=jwt_settings.JWT_ALGORITHM)
|
|
||||||
logger.debug(f"[JWT] Access Token 발급 - user_uuid: {user_uuid}, expires: {expire}, token: ...{token[-20:]}")
|
|
||||||
return token
|
|
||||||
```
|
|
||||||
|
|
||||||
**`create_refresh_token()` — 발급 로그 추가:**
|
|
||||||
```python
|
|
||||||
def create_refresh_token(user_uuid: str) -> str:
|
|
||||||
expire = now() + timedelta(days=jwt_settings.JWT_REFRESH_TOKEN_EXPIRE_DAYS)
|
|
||||||
to_encode = {"sub": user_uuid, "exp": expire, "type": "refresh"}
|
|
||||||
token = jwt.encode(to_encode, jwt_settings.JWT_SECRET, algorithm=jwt_settings.JWT_ALGORITHM)
|
|
||||||
logger.debug(f"[JWT] Refresh Token 발급 - user_uuid: {user_uuid}, expires: {expire}, token: ...{token[-20:]}")
|
|
||||||
return token
|
|
||||||
```
|
|
||||||
|
|
||||||
**`decode_token()` — 성공/실패 분류 로그:**
|
|
||||||
```python
|
|
||||||
def decode_token(token: str) -> Optional[dict]:
|
|
||||||
try:
|
|
||||||
payload = jwt.decode(token, jwt_settings.JWT_SECRET, algorithms=[jwt_settings.JWT_ALGORITHM])
|
|
||||||
logger.debug(
|
|
||||||
f"[JWT] 토큰 디코딩 성공 - type: {payload.get('type')}, "
|
|
||||||
f"sub: {payload.get('sub')}, exp: {payload.get('exp')}, "
|
|
||||||
f"token: ...{token[-20:]}"
|
|
||||||
)
|
|
||||||
return payload
|
|
||||||
except ExpiredSignatureError:
|
|
||||||
logger.info(f"[JWT] 토큰 만료 - token: ...{token[-20:]}")
|
|
||||||
return None
|
|
||||||
except JWTClaimsError as e:
|
|
||||||
logger.warning(f"[JWT] 클레임 검증 실패 - error: {e}, token: ...{token[-20:]}")
|
|
||||||
return None
|
|
||||||
except JWTError as e:
|
|
||||||
logger.warning(f"[JWT] 토큰 디코딩 실패 - error: {type(e).__name__}: {e}, token: ...{token[-20:]}")
|
|
||||||
return None
|
|
||||||
```
|
|
||||||
|
|
||||||
### 4-2. `dependencies/auth.py` — Access Token 검증 로깅
|
|
||||||
|
|
||||||
**import 추가:**
|
|
||||||
```python
|
|
||||||
import logging
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
```
|
|
||||||
|
|
||||||
**`get_current_user()` — 검증 과정 로그:**
|
|
||||||
```python
|
|
||||||
async def get_current_user(...) -> User:
|
|
||||||
if credentials is None:
|
|
||||||
logger.info("[AUTH-DEP] 토큰 없음 - MissingTokenError")
|
|
||||||
raise MissingTokenError()
|
|
||||||
|
|
||||||
token = credentials.credentials
|
|
||||||
logger.debug(f"[AUTH-DEP] Access Token 검증 시작 - token: ...{token[-20:]}")
|
|
||||||
|
|
||||||
payload = decode_token(token)
|
|
||||||
if payload is None:
|
|
||||||
logger.warning(f"[AUTH-DEP] Access Token 디코딩 실패 - token: ...{token[-20:]}")
|
|
||||||
raise InvalidTokenError()
|
|
||||||
|
|
||||||
if payload.get("type") != "access":
|
|
||||||
logger.warning(f"[AUTH-DEP] 토큰 타입 불일치 - expected: access, got: {payload.get('type')}, sub: {payload.get('sub')}")
|
|
||||||
raise InvalidTokenError("액세스 토큰이 아닙니다.")
|
|
||||||
|
|
||||||
user_uuid = payload.get("sub")
|
|
||||||
if user_uuid is None:
|
|
||||||
logger.warning(f"[AUTH-DEP] 토큰에 sub 클레임 없음 - token: ...{token[-20:]}")
|
|
||||||
raise InvalidTokenError()
|
|
||||||
|
|
||||||
# 사용자 조회
|
|
||||||
result = await session.execute(...)
|
|
||||||
user = result.scalar_one_or_none()
|
|
||||||
|
|
||||||
if user is None:
|
|
||||||
logger.warning(f"[AUTH-DEP] 사용자 미존재 - user_uuid: {user_uuid}")
|
|
||||||
raise UserNotFoundError()
|
|
||||||
|
|
||||||
if not user.is_active:
|
|
||||||
logger.warning(f"[AUTH-DEP] 비활성 사용자 접근 - user_uuid: {user_uuid}, user_id: {user.id}")
|
|
||||||
raise UserInactiveError()
|
|
||||||
|
|
||||||
logger.debug(f"[AUTH-DEP] Access Token 검증 성공 - user_uuid: {user_uuid}, user_id: {user.id}")
|
|
||||||
return user
|
|
||||||
```
|
|
||||||
|
|
||||||
**`get_current_user_optional()` — 동일 패턴, `debug` 레벨:**
|
|
||||||
```python
|
|
||||||
async def get_current_user_optional(...) -> Optional[User]:
|
|
||||||
if credentials is None:
|
|
||||||
logger.debug("[AUTH-DEP] 선택적 인증 - 토큰 없음")
|
|
||||||
return None
|
|
||||||
|
|
||||||
token = credentials.credentials
|
|
||||||
payload = decode_token(token)
|
|
||||||
if payload is None:
|
|
||||||
logger.debug(f"[AUTH-DEP] 선택적 인증 - 디코딩 실패, token: ...{token[-20:]}")
|
|
||||||
return None
|
|
||||||
|
|
||||||
if payload.get("type") != "access":
|
|
||||||
logger.debug(f"[AUTH-DEP] 선택적 인증 - 타입 불일치 (type={payload.get('type')})")
|
|
||||||
return None
|
|
||||||
|
|
||||||
user_uuid = payload.get("sub")
|
|
||||||
if user_uuid is None:
|
|
||||||
logger.debug("[AUTH-DEP] 선택적 인증 - sub 없음")
|
|
||||||
return None
|
|
||||||
|
|
||||||
result = await session.execute(...)
|
|
||||||
user = result.scalar_one_or_none()
|
|
||||||
|
|
||||||
if user is None or not user.is_active:
|
|
||||||
logger.debug(f"[AUTH-DEP] 선택적 인증 - 사용자 미존재 또는 비활성, user_uuid: {user_uuid}")
|
|
||||||
return None
|
|
||||||
|
|
||||||
logger.debug(f"[AUTH-DEP] 선택적 인증 성공 - user_uuid: {user_uuid}, user_id: {user.id}")
|
|
||||||
return user
|
|
||||||
```
|
|
||||||
|
|
||||||
### 4-3. `services/auth.py` — Refresh Token 갱신/폐기 로깅
|
|
||||||
|
|
||||||
**`refresh_tokens()` — 전체 흐름 로그:**
|
|
||||||
```python
|
|
||||||
async def refresh_tokens(self, refresh_token: str, session: AsyncSession) -> TokenResponse:
|
|
||||||
logger.info(f"[AUTH] 토큰 갱신 시작 (Rotation) - token: ...{refresh_token[-20:]}")
|
|
||||||
|
|
||||||
# 1. 디코딩
|
|
||||||
payload = decode_token(refresh_token)
|
|
||||||
if payload is None:
|
|
||||||
logger.warning(f"[AUTH] 토큰 갱신 실패 [1/8 디코딩] - token: ...{refresh_token[-20:]}")
|
|
||||||
raise InvalidTokenError()
|
|
||||||
|
|
||||||
if payload.get("type") != "refresh":
|
|
||||||
logger.warning(f"[AUTH] 토큰 갱신 실패 [1/8 타입] - type={payload.get('type')}, sub: {payload.get('sub')}")
|
|
||||||
raise InvalidTokenError("리프레시 토큰이 아닙니다.")
|
|
||||||
|
|
||||||
logger.debug(f"[AUTH] 토큰 갱신 [1/8] 디코딩 성공 - sub: {payload.get('sub')}, exp: {payload.get('exp')}")
|
|
||||||
|
|
||||||
# 2. DB 조회
|
|
||||||
token_hash = get_token_hash(refresh_token)
|
|
||||||
db_token = await self._get_refresh_token_by_hash(token_hash, session)
|
|
||||||
|
|
||||||
if db_token is None:
|
|
||||||
logger.warning(f"[AUTH] 토큰 갱신 실패 [2/8 DB조회] - DB에 없음, token_hash: {token_hash[:16]}...")
|
|
||||||
raise InvalidTokenError()
|
|
||||||
|
|
||||||
logger.debug(f"[AUTH] 토큰 갱신 [2/8] DB 조회 성공 - token_hash: {token_hash[:16]}..., user_uuid: {db_token.user_uuid}, is_revoked: {db_token.is_revoked}, expires_at: {db_token.expires_at}")
|
|
||||||
|
|
||||||
# 3. 폐기 여부
|
|
||||||
if db_token.is_revoked:
|
|
||||||
logger.warning(f"[AUTH] 토큰 갱신 실패 [3/8 폐기됨] - 이미 폐기된 토큰 (replay attack 의심), token_hash: {token_hash[:16]}..., user_uuid: {db_token.user_uuid}, revoked_at: {db_token.revoked_at}")
|
|
||||||
raise TokenRevokedError()
|
|
||||||
|
|
||||||
# 4. 만료 확인
|
|
||||||
if db_token.expires_at < now().replace(tzinfo=None):
|
|
||||||
logger.info(f"[AUTH] 토큰 갱신 실패 [4/8 만료] - expires_at: {db_token.expires_at}, user_uuid: {db_token.user_uuid}")
|
|
||||||
raise TokenExpiredError()
|
|
||||||
|
|
||||||
# 5. 사용자 확인
|
|
||||||
user_uuid = payload.get("sub")
|
|
||||||
user = await self._get_user_by_uuid(user_uuid, session)
|
|
||||||
|
|
||||||
if user is None:
|
|
||||||
logger.warning(f"[AUTH] 토큰 갱신 실패 [5/8 사용자] - 사용자 미존재, user_uuid: {user_uuid}")
|
|
||||||
raise UserNotFoundError()
|
|
||||||
|
|
||||||
if not user.is_active:
|
|
||||||
logger.warning(f"[AUTH] 토큰 갱신 실패 [5/8 비활성] - user_uuid: {user_uuid}, user_id: {user.id}")
|
|
||||||
raise UserInactiveError()
|
|
||||||
|
|
||||||
# 6. 기존 토큰 폐기
|
|
||||||
db_token.is_revoked = True
|
|
||||||
db_token.revoked_at = now().replace(tzinfo=None)
|
|
||||||
logger.debug(f"[AUTH] 토큰 갱신 [6/8] 기존 토큰 폐기 - token_hash: {token_hash[:16]}...")
|
|
||||||
|
|
||||||
# 7. 새 토큰 발급
|
|
||||||
new_access_token = create_access_token(user.user_uuid)
|
|
||||||
new_refresh_token = create_refresh_token(user.user_uuid)
|
|
||||||
logger.debug(f"[AUTH] 토큰 갱신 [7/8] 새 토큰 발급 - new_access: ...{new_access_token[-20:]}, new_refresh: ...{new_refresh_token[-20:]}")
|
|
||||||
|
|
||||||
# 8. 새 Refresh Token DB 저장 + 커밋
|
|
||||||
await self._save_refresh_token(user_id=user.id, user_uuid=user.user_uuid, token=new_refresh_token, session=session)
|
|
||||||
await session.commit()
|
|
||||||
|
|
||||||
logger.info(f"[AUTH] 토큰 갱신 완료 [8/8] - user_uuid: {user.user_uuid}, user_id: {user.id}, old_hash: {token_hash[:16]}..., new_refresh: ...{new_refresh_token[-20:]}")
|
|
||||||
return TokenResponse(...)
|
|
||||||
```
|
|
||||||
|
|
||||||
**`_save_refresh_token()` — DB 저장 로그:**
|
|
||||||
```python
|
|
||||||
async def _save_refresh_token(self, ...) -> RefreshToken:
|
|
||||||
token_hash = get_token_hash(token)
|
|
||||||
expires_at = get_refresh_token_expires_at()
|
|
||||||
|
|
||||||
refresh_token = RefreshToken(...)
|
|
||||||
session.add(refresh_token)
|
|
||||||
await session.flush()
|
|
||||||
|
|
||||||
logger.debug(f"[AUTH] Refresh Token DB 저장 - user_uuid: {user_uuid}, token_hash: {token_hash[:16]}..., expires_at: {expires_at}")
|
|
||||||
return refresh_token
|
|
||||||
```
|
|
||||||
|
|
||||||
**`logout()` — 단일 로그아웃 로그:**
|
|
||||||
```python
|
|
||||||
async def logout(self, user_id: int, refresh_token: str, session: AsyncSession) -> None:
|
|
||||||
token_hash = get_token_hash(refresh_token)
|
|
||||||
logger.info(f"[AUTH] 로그아웃 - user_id: {user_id}, token_hash: {token_hash[:16]}..., token: ...{refresh_token[-20:]}")
|
|
||||||
await self._revoke_refresh_token_by_hash(token_hash, session)
|
|
||||||
logger.info(f"[AUTH] 로그아웃 완료 - user_id: {user_id}")
|
|
||||||
```
|
|
||||||
|
|
||||||
**`logout_all()` — 전체 로그아웃 로그:**
|
|
||||||
```python
|
|
||||||
async def logout_all(self, user_id: int, session: AsyncSession) -> None:
|
|
||||||
logger.info(f"[AUTH] 전체 로그아웃 - user_id: {user_id}")
|
|
||||||
await self._revoke_all_user_tokens(user_id, session)
|
|
||||||
logger.info(f"[AUTH] 전체 로그아웃 완료 - user_id: {user_id}")
|
|
||||||
```
|
|
||||||
|
|
||||||
### 4-4. `routers/v1/auth.py` — 라우터 진입/완료 로깅
|
|
||||||
|
|
||||||
```python
|
|
||||||
# POST /auth/refresh
|
|
||||||
async def refresh_token(body, session) -> TokenResponse:
|
|
||||||
logger.info(f"[ROUTER] POST /auth/refresh - token: ...{body.refresh_token[-20:]}")
|
|
||||||
result = await auth_service.refresh_tokens(refresh_token=body.refresh_token, session=session)
|
|
||||||
logger.info(f"[ROUTER] POST /auth/refresh 완료 - new_access: ...{result.access_token[-20:]}, new_refresh: ...{result.refresh_token[-20:]}")
|
|
||||||
return result
|
|
||||||
|
|
||||||
# POST /auth/logout
|
|
||||||
async def logout(body, current_user, session) -> Response:
|
|
||||||
logger.info(f"[ROUTER] POST /auth/logout - user_id: {current_user.id}, user_uuid: {current_user.user_uuid}, token: ...{body.refresh_token[-20:]}")
|
|
||||||
await auth_service.logout(user_id=current_user.id, refresh_token=body.refresh_token, session=session)
|
|
||||||
logger.info(f"[ROUTER] POST /auth/logout 완료 - user_id: {current_user.id}")
|
|
||||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
|
||||||
|
|
||||||
# POST /auth/logout/all
|
|
||||||
async def logout_all(current_user, session) -> Response:
|
|
||||||
logger.info(f"[ROUTER] POST /auth/logout/all - user_id: {current_user.id}, user_uuid: {current_user.user_uuid}")
|
|
||||||
await auth_service.logout_all(user_id=current_user.id, session=session)
|
|
||||||
logger.info(f"[ROUTER] POST /auth/logout/all 완료 - user_id: {current_user.id}")
|
|
||||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. 보안 원칙
|
|
||||||
|
|
||||||
| 원칙 | 적용 방법 | 이유 |
|
|
||||||
|------|----------|------|
|
|
||||||
| 토큰 전체 노출 금지 | 뒷 20자만: `...{token[-20:]}` | 토큰 탈취 시 세션 하이재킹 가능 |
|
|
||||||
| 해시값 부분 노출 | 앞 16자만: `{hash[:16]}...` | DB 레코드 식별에 충분 |
|
|
||||||
| user_uuid 전체 허용 | 전체 출력 | 내부 식별자, 토큰이 아님 |
|
|
||||||
| 페이로드 내용 출력 | `sub`, `type`, `exp` 출력 | 디버깅에 필수, 민감정보 아님 |
|
|
||||||
| DB 토큰 상태 출력 | `is_revoked`, `expires_at`, `revoked_at` | 토큰 라이프사이클 추적 |
|
|
||||||
| 로그 레벨 구분 | 하단 표 참조 | 운영 환경에서 불필요한 로그 억제 |
|
|
||||||
|
|
||||||
### 로그 레벨 기준
|
|
||||||
|
|
||||||
| 레벨 | 사용 기준 | 예시 |
|
|
||||||
|------|----------|------|
|
|
||||||
| `debug` | 정상 처리 과정 상세 (운영환경에서 비활성) | 토큰 발급, 디코딩 성공, 검증 통과 |
|
|
||||||
| `info` | 주요 이벤트 (운영환경에서 활성) | 갱신 시작/완료, 로그아웃, 만료로 인한 실패 |
|
|
||||||
| `warning` | 비정상/의심 상황 | 디코딩 실패, 폐기된 토큰 사용, 사용자 미존재 |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. 구현 순서
|
|
||||||
|
|
||||||
| 순서 | 파일 | 이유 |
|
|
||||||
|------|------|------|
|
|
||||||
| 1 | `app/user/services/jwt.py` | 최하위 유틸리티. 토큰 발급/디코딩의 기본 로그 |
|
|
||||||
| 2 | `app/user/dependencies/auth.py` | 모든 인증 API의 공통 진입점 |
|
|
||||||
| 3 | `app/user/services/auth.py` | 갱신/폐기 비즈니스 로직 |
|
|
||||||
| 4 | `app/user/api/routers/v1/auth.py` | 라우터 진입/완료 + 응답 토큰 정보 |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. 기대 효과 — 시나리오별 로그 출력 예시
|
|
||||||
|
|
||||||
### 시나리오 1: 정상 토큰 갱신
|
|
||||||
```
|
|
||||||
[ROUTER] POST /auth/refresh - token: ...7d90-aac8-ecf1385c
|
|
||||||
[AUTH] 토큰 갱신 시작 (Rotation) - token: ...7d90-aac8-ecf1385c
|
|
||||||
[JWT] 토큰 디코딩 성공 - type: refresh, sub: 019c5452-b1cf-7d90-aac8-ecf1385c9dc4, exp: 1739450400
|
|
||||||
[AUTH] 토큰 갱신 [1/8] 디코딩 성공 - sub: 019c5452-..., exp: 1739450400
|
|
||||||
[AUTH] 토큰 갱신 [2/8] DB 조회 성공 - token_hash: a1b2c3d4e5f6g7h8..., is_revoked: False, expires_at: 2026-02-20 11:46:36
|
|
||||||
[AUTH] 토큰 갱신 [6/8] 기존 토큰 폐기 - token_hash: a1b2c3d4e5f6g7h8...
|
|
||||||
[JWT] Access Token 발급 - user_uuid: 019c5452-..., expires: 2026-02-13 12:46:36
|
|
||||||
[JWT] Refresh Token 발급 - user_uuid: 019c5452-..., expires: 2026-02-20 11:46:36
|
|
||||||
[AUTH] 토큰 갱신 [7/8] 새 토큰 발급 - new_access: ...xNewAccess12345, new_refresh: ...xNewRefresh6789
|
|
||||||
[AUTH] Refresh Token DB 저장 - user_uuid: 019c5452-..., token_hash: f8e9d0c1b2a3..., expires_at: 2026-02-20 11:46:36
|
|
||||||
[AUTH] 토큰 갱신 완료 [8/8] - user_uuid: 019c5452-..., user_id: 42, old_hash: a1b2c3d4e5f6g7h8..., new_refresh: ...xNewRefresh6789
|
|
||||||
[ROUTER] POST /auth/refresh 완료 - new_access: ...xNewAccess12345, new_refresh: ...xNewRefresh6789
|
|
||||||
```
|
|
||||||
|
|
||||||
### 시나리오 2: 만료된 Refresh Token으로 갱신 시도
|
|
||||||
```
|
|
||||||
[ROUTER] POST /auth/refresh - token: ...expiredToken12345
|
|
||||||
[AUTH] 토큰 갱신 시작 (Rotation) - token: ...expiredToken12345
|
|
||||||
[JWT] 토큰 만료 - token: ...expiredToken12345
|
|
||||||
[AUTH] 토큰 갱신 실패 [1/8 디코딩] - token: ...expiredToken12345
|
|
||||||
→ 401 InvalidTokenError 응답
|
|
||||||
```
|
|
||||||
|
|
||||||
### 시나리오 3: 이미 폐기된 Refresh Token 재사용 (Replay Attack)
|
|
||||||
```
|
|
||||||
[ROUTER] POST /auth/refresh - token: ...revokedToken98765
|
|
||||||
[AUTH] 토큰 갱신 시작 (Rotation) - token: ...revokedToken98765
|
|
||||||
[JWT] 토큰 디코딩 성공 - type: refresh, sub: 019c5452-..., exp: 1739450400
|
|
||||||
[AUTH] 토큰 갱신 [2/8] DB 조회 성공 - token_hash: c3d4e5f6..., is_revoked: True, expires_at: 2026-02-20
|
|
||||||
[AUTH] 토큰 갱신 실패 [3/8 폐기됨] - replay attack 의심, token_hash: c3d4e5f6..., user_uuid: 019c5452-..., revoked_at: 2026-02-13 10:30:00
|
|
||||||
→ 401 TokenRevokedError 응답
|
|
||||||
```
|
|
||||||
|
|
||||||
### 시나리오 4: Access Token 검증 (매 API 요청)
|
|
||||||
```
|
|
||||||
[AUTH-DEP] Access Token 검증 시작 - token: ...validAccess12345
|
|
||||||
[JWT] 토큰 디코딩 성공 - type: access, sub: 019c5452-..., exp: 1739450400
|
|
||||||
[AUTH-DEP] Access Token 검증 성공 - user_uuid: 019c5452-..., user_id: 42
|
|
||||||
```
|
|
||||||
|
|
||||||
### 시나리오 5: 로그아웃
|
|
||||||
```
|
|
||||||
[ROUTER] POST /auth/logout - user_id: 42, user_uuid: 019c5452-..., token: ...refreshToRevoke99
|
|
||||||
[AUTH] 로그아웃 - user_id: 42, token_hash: d5e6f7g8..., token: ...refreshToRevoke99
|
|
||||||
[AUTH] 로그아웃 완료 - user_id: 42
|
|
||||||
[ROUTER] POST /auth/logout 완료 - user_id: 42
|
|
||||||
```
|
|
||||||
Reference in new issue
Block a user