Compare commits

..
4 Commits
Author SHA1 Message Date
jaehwang f1dd675ecb Merge branch 'main' into youtube-description 2026-02-12 05:10:32 +00:00
jaehwang ada5dfeeb4 가사 marketing Intel 삽입 2026-02-12 05:10:08 +00:00
jaehwang 18635d7995 update crawler retry and timeout setting 2026-02-11 07:09:34 +00:00
jaehwang 54e66e4682 add marketing intelligence db 2026-02-11 05:21:00 +00:00
14 changed files with 461 additions and 59 deletions

No files matched your search

+2 -1
View File
@@ -73,7 +73,7 @@ async def create_db_tables():
# 모델 import (테이블 메타데이터 등록용) # 모델 import (테이블 메타데이터 등록용)
from app.user.models import User, RefreshToken, SocialAccount # noqa: F401 from app.user.models import User, RefreshToken, SocialAccount # noqa: F401
from app.home.models import Image, Project # noqa: F401 from app.home.models import Image, Project, MarketingIntel # noqa: F401
from app.lyric.models import Lyric # noqa: F401 from app.lyric.models import Lyric # noqa: F401
from app.song.models import Song, SongTimestamp # noqa: F401 from app.song.models import Song, SongTimestamp # noqa: F401
from app.video.models import Video # noqa: F401 from app.video.models import Video # noqa: F401
@@ -93,6 +93,7 @@ async def create_db_tables():
Video.__table__, Video.__table__,
SNSUploadTask.__table__, SNSUploadTask.__table__,
SocialUpload.__table__, SocialUpload.__table__,
MarketingIntel.__table__,
] ]
logger.info("Creating database tables...") logger.info("Creating database tables...")
+23 -7
View File
@@ -11,7 +11,7 @@ from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from app.database.session import get_session, AsyncSessionLocal from app.database.session import get_session, AsyncSessionLocal
from app.home.models import Image from app.home.models import Image, MarketingIntel
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.schemas.home_schema import ( from app.home.schemas.home_schema import (
@@ -153,8 +153,10 @@ def _extract_region_from_address(road_address: str | None) -> str:
}, },
tags=["Crawling"], tags=["Crawling"],
) )
async def crawling(request_body: CrawlingRequest): async def crawling(
return await _crawling_logic(request_body.url) request_body: CrawlingRequest,
session: AsyncSession = Depends(get_session)):
return await _crawling_logic(request_body.url, session)
@router.post( @router.post(
"/autocomplete", "/autocomplete",
@@ -187,11 +189,15 @@ async def crawling(request_body: CrawlingRequest):
}, },
tags=["Crawling"], tags=["Crawling"],
) )
async def autocomplete_crawling(request_body: AutoCompleteRequest): async def autocomplete_crawling(
url = await _autocomplete_logic(request_body.dict()) request_body: AutoCompleteRequest,
return await _crawling_logic(url) session: AsyncSession = Depends(get_session)):
url = await _autocomplete_logic(request_body.model_dump())
return await _crawling_logic(url, session)
async def _crawling_logic(url:str): async def _crawling_logic(
url:str,
session: AsyncSession):
request_start = time.perf_counter() request_start = time.perf_counter()
logger.info("[crawling] ========== START ==========") logger.info("[crawling] ========== START ==========")
logger.info(f"[crawling] URL: {url[:80]}...") logger.info(f"[crawling] URL: {url[:80]}...")
@@ -281,6 +287,15 @@ async def _crawling_logic(url:str):
structured_report = await chatgpt_service.generate_structured_output( structured_report = await chatgpt_service.generate_structured_output(
marketing_prompt, input_marketing_data marketing_prompt, input_marketing_data
) )
marketing_intelligence = MarketingIntel(
place_id = scraper.place_id,
intel_result = structured_report.model_dump()
)
session.add(marketing_intelligence)
await session.commit()
await session.refresh(marketing_intelligence)
m_id = marketing_intelligence.id
logger.debug(f"[MarketingPrompt] INSERT placeid {marketing_intelligence.place_id}")
step3_3_elapsed = (time.perf_counter() - step3_3_start) * 1000 step3_3_elapsed = (time.perf_counter() - step3_3_start) * 1000
logger.info( logger.info(
f"[crawling] Step 3-3: GPT API 호출 완료 - ({step3_3_elapsed:.1f}ms)" f"[crawling] Step 3-3: GPT API 호출 완료 - ({step3_3_elapsed:.1f}ms)"
@@ -360,6 +375,7 @@ async def _crawling_logic(url:str):
"image_count": len(scraper.image_link_list) if scraper.image_link_list else 0, "image_count": len(scraper.image_link_list) if scraper.image_link_list else 0,
"processed_info": processed_info, "processed_info": processed_info,
"marketing_analysis": marketing_analysis, "marketing_analysis": marketing_analysis,
"m_id" : m_id
} }
+71 -2
View File
@@ -7,9 +7,9 @@ Home 모듈 SQLAlchemy 모델 정의
""" """
from datetime import datetime from datetime import datetime
from typing import TYPE_CHECKING, List, Optional from typing import TYPE_CHECKING, List, Optional, Any
from sqlalchemy import Boolean, DateTime, ForeignKey, Index, Integer, String, Text, func from sqlalchemy import Boolean, DateTime, ForeignKey, Index, Integer, String, Text, JSON, func
from sqlalchemy.orm import Mapped, mapped_column, relationship from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.database.session import Base from app.database.session import Base
@@ -107,6 +107,12 @@ class Project(Base):
comment="상세 지역 정보", comment="상세 지역 정보",
) )
marketing_inteligence: Mapped[Optional[str]] = mapped_column(
Integer,
nullable=True,
comment="마케팅 인텔리전스 결과 정보 저장",
)
language: Mapped[str] = mapped_column( language: Mapped[str] = mapped_column(
String(50), String(50),
nullable=False, nullable=False,
@@ -249,3 +255,66 @@ class Image(Base):
return ( return (
f"<Image(id={self.id}, task_id='{task_id_str}', img_name='{img_name_str}')>" f"<Image(id={self.id}, task_id='{task_id_str}', img_name='{img_name_str}')>"
) )
class MarketingIntel(Base):
"""
마케팅 인텔리전스 결과물 테이블
마케팅 분석 결과물 저장합니다.
Attributes:
id: 고유 식별자 (자동 증가)
place_id : 데이터 소스별 식별자
intel_result : 마케팅 분석 결과물 json
created_at: 생성 일시 (자동 설정)
"""
__tablename__ = "marketing"
__table_args__ = (
Index("idx_place_id", "place_id"),
{
"mysql_engine": "InnoDB",
"mysql_charset": "utf8mb4",
"mysql_collate": "utf8mb4_unicode_ci",
}
)
id: Mapped[int] = mapped_column(
Integer,
primary_key=True,
nullable=False,
autoincrement=True,
comment="고유 식별자",
)
place_id: Mapped[str] = mapped_column(
String(36),
nullable=False,
comment="매장 소스별 고유 식별자",
)
intel_result : Mapped[dict[str, Any]] = mapped_column(
JSON,
nullable=False,
comment="마케팅 인텔리전스 결과물",
)
created_at: Mapped[datetime] = mapped_column(
DateTime,
nullable=False,
server_default=func.now(),
comment="생성 일시",
)
def __repr__(self) -> str:
task_id_str = (
(self.task_id[:10] + "...") if len(self.task_id) > 10 else self.task_id
)
img_name_str = (
(self.img_name[:10] + "...") if len(self.img_name) > 10 else self.img_name
)
return (
f"<Image(id={self.id}, task_id='{task_id_str}', img_name='{img_name_str}')>"
)
+3 -1
View File
@@ -329,7 +329,8 @@ class CrawlingResponse(BaseModel):
"힐링스테이", "힐링스테이",
"스테이머뭄" "스테이머뭄"
] ]
} },
"m_id" : 1
} }
} }
) )
@@ -346,6 +347,7 @@ class CrawlingResponse(BaseModel):
marketing_analysis: Optional[MarketingPromptOutput] = Field( marketing_analysis: Optional[MarketingPromptOutput] = Field(
None, description="마케팅 분석 결과 . 실패 시 null" None, description="마케팅 분석 결과 . 실패 시 null"
) )
m_id : int = Field(..., description="마케팅 분석 결과 ID")
class ErrorResponse(BaseModel): class ErrorResponse(BaseModel):
+8 -2
View File
@@ -30,7 +30,7 @@ from sqlalchemy import select
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.home.models import Project from app.home.models import Project, MarketingIntel
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.lyric.models import Lyric from app.lyric.models import Lyric
@@ -48,6 +48,7 @@ from app.utils.pagination import PaginatedResponse, get_paginated
from app.utils.prompts.prompts import lyric_prompt from app.utils.prompts.prompts import lyric_prompt
import traceback as tb import traceback as tb
import json
# 로거 설정 # 로거 설정
logger = get_logger("lyric") logger = get_logger("lyric")
@@ -278,11 +279,15 @@ async def generate_lyric(
Full verse flow, immersive mood Full verse flow, immersive mood
""" """
} }
marketing_intel_result = await session.execute(select(MarketingIntel).where(MarketingIntel.id == request_body.m_id))
marketing_intel = marketing_intel_result.scalar_one_or_none()
lyric_input_data = { lyric_input_data = {
"customer_name" : request_body.customer_name, "customer_name" : request_body.customer_name,
"region" : request_body.region, "region" : request_body.region,
"detail_region_info" : request_body.detail_region_info or "", "detail_region_info" : request_body.detail_region_info or "",
"marketing_intelligence_summary" : None, # task_idx 변경 후 marketing intelligence summary DB에 저장하고 사용할 필요가 있음 "marketing_intelligence_summary" : json.dumps(marketing_intel.intel_result, ensure_ascii = False),
"language" : request_body.language, "language" : request_body.language,
"promotional_expression_example" : promotional_expressions[request_body.language], "promotional_expression_example" : promotional_expressions[request_body.language],
"timing_rules" : timing_rules["60s"], # 아직은 선택지 하나 "timing_rules" : timing_rules["60s"], # 아직은 선택지 하나
@@ -314,6 +319,7 @@ async def generate_lyric(
detail_region_info=request_body.detail_region_info, detail_region_info=request_body.detail_region_info,
language=request_body.language, language=request_body.language,
user_uuid=current_user.user_uuid, user_uuid=current_user.user_uuid,
marketing_inteligence = request_body.m_id
) )
session.add(project) session.add(project)
await session.commit() await session.commit()
+4 -1
View File
@@ -41,7 +41,8 @@ class GenerateLyricRequest(BaseModel):
"customer_name": "스테이 머뭄", "customer_name": "스테이 머뭄",
"region": "군산", "region": "군산",
"detail_region_info": "군산 신흥동 말랭이 마을", "detail_region_info": "군산 신흥동 말랭이 마을",
"language": "Korean" "language": "Korean",
"m_id" : 1
} }
""" """
@@ -53,6 +54,7 @@ class GenerateLyricRequest(BaseModel):
"region": "군산", "region": "군산",
"detail_region_info": "군산 신흥동 말랭이 마을", "detail_region_info": "군산 신흥동 말랭이 마을",
"language": "Korean", "language": "Korean",
"m_id" : 1
} }
} }
) )
@@ -67,6 +69,7 @@ class GenerateLyricRequest(BaseModel):
default="Korean", default="Korean",
description="가사 출력 언어 (Korean, English, Chinese, Japanese, Thai, Vietnamese)", description="가사 출력 언어 (Korean, English, Chinese, Japanese, Thai, Vietnamese)",
) )
m_id : Optional[int] = Field(None, description="마케팅 인텔리전스 ID 값")
class GenerateLyricResponse(BaseModel): class GenerateLyricResponse(BaseModel):
+7 -8
View File
@@ -28,7 +28,6 @@ from app.user.schemas.user_schema import (
KakaoLoginResponse, KakaoLoginResponse,
LoginResponse, LoginResponse,
RefreshTokenRequest, RefreshTokenRequest,
TokenResponse,
UserResponse, UserResponse,
) )
from app.user.services import auth_service, kakao_client from app.user.services import auth_service, kakao_client
@@ -241,19 +240,19 @@ async def kakao_verify(
@router.post( @router.post(
"/refresh", "/refresh",
response_model=TokenResponse, response_model=AccessTokenResponse,
summary="토큰 갱신 (Refresh Token Rotation)", summary="토큰 갱신",
description="리프레시 토큰으로 새 액세스 토큰과 새 리프레시 토큰을 함께 발급합니다. 사용된 기존 리프레시 토큰은 즉시 폐기됩니다.", description="리프레시 토큰으로 새 액세스 토큰을 발급합니다.",
) )
async def refresh_token( async def refresh_token(
body: RefreshTokenRequest, body: RefreshTokenRequest,
session: AsyncSession = Depends(get_session), session: AsyncSession = Depends(get_session),
) -> TokenResponse: ) -> AccessTokenResponse:
""" """
토큰 갱신 (Refresh Token Rotation) 액세스 토큰 갱신
유효한 리프레시 토큰을 제출하면 새 액세스 토큰과 새 리프레시 토큰을 발급합니다. 유효한 리프레시 토큰을 제출하면 새 액세스 토큰을 발급합니다.
사용된 기존 리프레시 토큰은 즉시 폐기(revoke)됩니다. 리프레시 토큰은 변경되지 않습니다.
""" """
return await auth_service.refresh_tokens( return await auth_service.refresh_tokens(
refresh_token=body.refresh_token, refresh_token=body.refresh_token,
+5 -30
View File
@@ -84,7 +84,6 @@ from app.user.schemas.user_schema import (
AccessTokenResponse, AccessTokenResponse,
KakaoUserInfo, KakaoUserInfo,
LoginResponse, LoginResponse,
TokenResponse,
) )
from app.user.services.jwt import ( from app.user.services.jwt import (
create_access_token, create_access_token,
@@ -189,27 +188,22 @@ class AuthService:
self, self,
refresh_token: str, refresh_token: str,
session: AsyncSession, session: AsyncSession,
) -> TokenResponse: ) -> AccessTokenResponse:
""" """
리프레시 토큰으로 액세스 토큰 + 리프레시 토큰 갱신 (Refresh Token Rotation) 리프레시 토큰으로 액세스 토큰 갱신
기존 리프레시 토큰을 폐기하고, 새 액세스 토큰과 새 리프레시 토큰을 함께 발급합니다.
사용자가 서비스를 지속 사용하는 한 세션이 자동 유지됩니다.
Args: Args:
refresh_token: 리프레시 토큰 refresh_token: 리프레시 토큰
session: DB 세션 session: DB 세션
Returns: Returns:
TokenResponse: 새 액세스 토큰 + 새 리프레시 토큰 AccessTokenResponse: 새 액세스 토큰
Raises: Raises:
InvalidTokenError: 토큰이 유효하지 않은 경우 InvalidTokenError: 토큰이 유효하지 않은 경우
TokenExpiredError: 토큰이 만료된 경우 TokenExpiredError: 토큰이 만료된 경우
TokenRevokedError: 토큰이 폐기된 경우 TokenRevokedError: 토큰이 폐기된 경우
""" """
logger.info("[AUTH] 토큰 갱신 시작 (Refresh Token Rotation)")
# 1. 토큰 디코딩 및 검증 # 1. 토큰 디코딩 및 검증
payload = decode_token(refresh_token) payload = decode_token(refresh_token)
if payload is None: if payload is None:
@@ -242,30 +236,11 @@ class AuthService:
if not user.is_active: if not user.is_active:
raise UserInactiveError() raise UserInactiveError()
# 5. 기존 리프레시 토큰 폐기 (ORM 직접 수정 — _revoke_refresh_token_by_hash는 내부 commit이 있어 사용하지 않음) # 5. 새 액세스 토큰 발급
db_token.is_revoked = True
db_token.revoked_at = now().replace(tzinfo=None)
# 6. 새 토큰 발급
new_access_token = create_access_token(user.user_uuid) new_access_token = create_access_token(user.user_uuid)
new_refresh_token = create_refresh_token(user.user_uuid)
# 7. 새 리프레시 토큰 DB 저장 (_save_refresh_token은 flush만 수행) return AccessTokenResponse(
await self._save_refresh_token(
user_id=user.id,
user_uuid=user.user_uuid,
token=new_refresh_token,
session=session,
)
# 8. 폐기 + 저장을 하나의 트랜잭션으로 커밋
await session.commit()
logger.info(f"[AUTH] 토큰 갱신 완료 - user_uuid: {user.user_uuid}")
return TokenResponse(
access_token=new_access_token, access_token=new_access_token,
refresh_token=new_refresh_token,
token_type="Bearer", token_type="Bearer",
expires_in=get_access_token_expire_seconds(), expires_in=get_access_token_expire_seconds(),
) )
+12 -6
View File
@@ -15,7 +15,8 @@ class NvMapPwScraper():
_context = None _context = None
_win_width = 1280 _win_width = 1280
_win_height = 720 _win_height = 720
_max_retry = 60 # place id timeout threshold seconds _max_retry = 3
_timeout = 60 # place id timeout threshold seconds
# instance var # instance var
page = None page = None
@@ -97,7 +98,7 @@ patchedGetter.toString();''')
async def get_place_id_url(self, selected): async def get_place_id_url(self, selected):
count = 0 count = 0
get_place_id_url_start = time.perf_counter() get_place_id_url_start = time.perf_counter()
while (count <= 1): while (count <= self._max_retry):
title = selected['title'].replace("<b>", "").replace("</b>", "") title = selected['title'].replace("<b>", "").replace("</b>", "")
address = selected.get('roadAddress', selected['address']).replace("<b>", "").replace("</b>", "") address = selected.get('roadAddress', selected['address']).replace("<b>", "").replace("</b>", "")
encoded_query = parse.quote(f"{address} {title}") encoded_query = parse.quote(f"{address} {title}")
@@ -106,9 +107,12 @@ patchedGetter.toString();''')
wait_first_start = time.perf_counter() wait_first_start = time.perf_counter()
try: try:
await self.goto_url(url, wait_until="networkidle",timeout = self._max_retry/2*1000) await self.goto_url(url, wait_until="networkidle",timeout = self._timeout*1000)
except: except:
await self.page.reload(wait_until="networkidle", timeout = self._max_retry/2*1000) if "/place/" in self.page.url:
return self.page.url
logger.error(f"[ERROR] Can't Finish networkidle")
wait_first_time = (time.perf_counter() - wait_first_start) * 1000 wait_first_time = (time.perf_counter() - wait_first_start) * 1000
@@ -123,9 +127,11 @@ patchedGetter.toString();''')
url = self.page.url.replace("?","?isCorrectAnswer=true&") url = self.page.url.replace("?","?isCorrectAnswer=true&")
try: try:
await self.goto_url(url, wait_until="networkidle",timeout = self._max_retry/2*1000) await self.goto_url(url, wait_until="networkidle",timeout = self._timeout*1000)
except: except:
await self.page.reload(wait_until="networkidle", timeout = self._max_retry/2*1000) if "/place/" in self.page.url:
return self.page.url
logger.error(f"[ERROR] Can't Finish networkidle")
wait_forced_correct_time = (time.perf_counter() - wait_forced_correct_start) * 1000 wait_forced_correct_time = (time.perf_counter() - wait_forced_correct_start) * 1000
logger.debug(f"[DEBUG] Try {count+1} : Wait for forced isCorrectAnswer flag : {wait_forced_correct_time}ms") logger.debug(f"[DEBUG] Try {count+1} : Wait for forced isCorrectAnswer flag : {wait_forced_correct_time}ms")
+3 -1
View File
@@ -30,7 +30,7 @@ class NvMapScraper:
GRAPHQL_URL: str = "https://pcmap-api.place.naver.com/graphql" GRAPHQL_URL: str = "https://pcmap-api.place.naver.com/graphql"
REQUEST_TIMEOUT = 120 # 초 REQUEST_TIMEOUT = 120 # 초
data_source_identifier = "nv"
OVERVIEW_QUERY: str = """ OVERVIEW_QUERY: str = """
query getAccommodation($id: String!, $deviceType: String) { query getAccommodation($id: String!, $deviceType: String) {
business: placeDetail(input: {id: $id, isNx: true, deviceType: $deviceType}) { business: placeDetail(input: {id: $id, isNx: true, deviceType: $deviceType}) {
@@ -99,6 +99,8 @@ query getAccommodation($id: String!, $deviceType: String) {
data = await self._call_get_accommodation(place_id) data = await self._call_get_accommodation(place_id)
self.rawdata = data self.rawdata = data
fac_data = await self._get_facility_string(place_id) fac_data = await self._get_facility_string(place_id)
# Naver 기준임, 구글 등 다른 데이터 소스의 경우 고유 Identifier 사용할 것.
self.place_id = self.data_source_identifier + place_id
self.rawdata["facilities"] = fac_data self.rawdata["facilities"] = fac_data
self.image_link_list = [ self.image_link_list = [
nv_image["origin"] nv_image["origin"]
+16
View File
@@ -0,0 +1,16 @@
from pydantic import BaseModel, Field
from typing import List, Optional
# Input 정의
class YTUploadPromptInput(BaseModel):
customer_name : str = Field(..., description = "마케팅 대상 사업체 이름")
detail_region_info : str = Field(..., description = "마케팅 대상 지역 상세")
marketing_intelligence_summary : Optional[str] = Field(None, description = "마케팅 분석 정보 보고서")
language : str= Field(..., description = "영상 언어")
target_keywords: List[str] = Field(..., description="태그 키워드 리스트")
# Output 정의
class YTUploadPromptOutput(BaseModel):
title:str = Field(..., description="유튜브 영상 제목 - SEO/AEO 최적화")
description: str = Field(..., description = "유튜브 영상 설명 - SEO/AEO 최적화")
@@ -4,6 +4,7 @@ You are a content marketing expert, brand strategist, and creative songwriter
specializing in Korean pension / accommodation businesses. specializing in Korean pension / accommodation businesses.
You create lyrics strictly based on Brand & Marketing Intelligence analysis You create lyrics strictly based on Brand & Marketing Intelligence analysis
and optimized for viral short-form video content. and optimized for viral short-form video content.
Marketing Intelligence Report is background reference.
[INPUT] [INPUT]
Business Name: {customer_name} Business Name: {customer_name}
@@ -0,0 +1,143 @@
[ROLE]
You are a YouTube SEO/AEO content strategist specialized in local stay, pension, and accommodation brands in Korea.
You create search-optimized, emotionally appealing, and action-driving titles and descriptions based on Brand & Marketing Intelligence.
Your goal is to:
Increase search visibility
Improve click-through rate
Reflect the brand’s positioning
Trigger emotional interest
Encourage booking or inquiry actions through subtle CTA
[INPUT]
Business Name: {customer_name}
Region Details: {detail_region_info}
Brand & Marketing Intelligence Report: {marketing_intelligence_summary}
Target Keywords: {target_keywords}
Output Language: {language}
[INTERNAL ANALYSIS – DO NOT OUTPUT]
Analyze the following from the marketing intelligence:
Core brand concept
Main emotional promise
Primary target persona
Top 2–3 USP signals
Stay context (date, healing, local trip, etc.)
Search intent behind the target keywords
Main booking trigger
Emotional moment that would make the viewer want to stay
Use these to guide:
Title tone
Opening CTA line
Emotional hook in the first sentences
[TITLE GENERATION RULES]
The title must:
Include the business name or region when natural
Always wrap the business name in quotation marks
Example: “스테이 머뭄”
Include 1–2 high-intent keywords
Reflect emotional positioning
Suggest a desirable stay moment
Sound like a natural YouTube title, not an advertisement
Length rules:
Hard limit: 100 characters
Target range: 45–65 characters
Place primary keyword in the first half
Avoid:
ALL CAPS
Excessive symbols
Price or promotion language
Hard-sell expressions
[DESCRIPTION GENERATION RULES]
Character rules:
Maximum length: 1,000 characters
Critical information must appear within the first 150 characters
Language style rules (mandatory):
Use polite Korean honorific style
Replace “있나요?” with “있으신가요?”
Do not start sentences with “이곳은”
Replace “선택이 됩니다” with “추천 드립니다”
Always wrap the business name in quotation marks
Example: “스테이 머뭄”
Avoid vague location words like “근대거리” alone
Use specific phrasing such as:
“군산 근대역사문화거리 일대”
Structure:
Opening CTA (first line)
Must be a question or gentle suggestion
Must use honorific tone
Example:
“조용히 쉴 수 있는 군산숙소를 찾고 있으신가요?”
Core Stay Introduction (within first 150 characters total)
Mention business name with quotation marks
Mention region
Include main keyword
Briefly describe the stay experience
Brand Experience
Core value and emotional promise
Based on marketing intelligence positioning
Key Highlights (3–4 short lines)
Derived from USP signals
Natural sentences
Focus on booking-trigger moments
Local Context
Mention nearby experiences
Use specific local references
Example:
“군산 근대역사문화거리 일대 산책이나 로컬 카페 투어”
Soft Closing Line
One gentle, non-salesy closing sentence
Must end with a recommendation tone
Example:
“군산에서 조용한 시간을 보내고 싶다면 ‘스테이 머뭄’을 추천 드립니다.”
[SEO & AEO RULES]
Naturally integrate 3–5 keywords from {target_keywords}
Avoid keyword stuffing
Use conversational, search-like phrasing
Optimize for:
YouTube search
Google video results
AI answer summaries
Keywords should appear in:
Title (1–2)
First 150 characters of description
Highlight or context sections
[LANGUAGE RULE]
All output must be written entirely in {language}.
No mixed languages.
[OUTPUT FORMAT – STRICT]
title:
description:
No explanations.
No headings.
No extra text.
+163
View File
@@ -0,0 +1,163 @@
# 타임존 검수 보고서
**검수일**: 2026-02-10
**대상**: o2o-castad-backend 전체 프로젝트
**기준**: 서울 타임존(Asia/Seoul, KST +09:00)
---
## 1. 타임존 설정 현황
### 1.1 FastAPI 전역 타임존 (`config.py:15`)
```python
TIMEZONE = ZoneInfo(os.getenv("TIMEZONE", "Asia/Seoul"))
```
- `ZoneInfo`를 사용한 aware datetime 기반
- `.env`로 오버라이드 가능 (기본값: `Asia/Seoul`)
### 1.2 타임존 유틸리티 (`app/utils/timezone.py`)
```python
def now() -> datetime:
return datetime.now(TIMEZONE) # aware datetime (tzinfo=Asia/Seoul)
def today_str(fmt="%Y-%m-%d") -> str:
return datetime.now(TIMEZONE).strftime(fmt)
```
- 모든 모듈에서 `from app.utils.timezone import now` 사용 권장
- 반환값은 **aware datetime** (tzinfo 포함)
### 1.3 데이터베이스 타임존
- MySQL `server_default=func.now()` → DB 서버의 시스템 타임존 사용
- DB 생성 시 서울 타임존으로 설정됨 → `func.now()`는 KST 반환
---
## 2. 검수 결과 요약
| 구분 | 상태 | 비고 |
|------|------|------|
| `datetime.now()` 직접 호출 | ✅ 정상 | 앱 코드에서 bare `datetime.now()` 사용 없음 |
| `datetime.utcnow()` 사용 | ✅ 정상 | 프로젝트 전체에서 사용하지 않음 |
| `app.utils.timezone.now()` 사용 | ✅ 정상 | 필요한 모든 곳에서 사용 중 |
| 모델 `server_default=func.now()` | ✅ 정상 | DB 서버 타임존(서울) 기준 |
| naive/aware datetime 혼합 비교 | ⚠️ 주의 | `now().replace(tzinfo=None)` 패턴으로 처리됨 |
---
## 3. 모듈별 상세 검수
### 3.1 `app/user/services/jwt.py` — ✅ 정상
| 위치 | 코드 | 판정 |
|------|------|------|
| L27 | `now() + timedelta(minutes=...)` | ✅ 토큰 만료시간 계산에 서울 타임존 사용 |
| L52 | `now() + timedelta(days=...)` | ✅ 리프레시 토큰 만료시간 |
| L110 | `now().replace(tzinfo=None) + timedelta(days=...)` | ✅ DB 저장용 naive datetime 변환 |
### 3.2 `app/user/services/auth.py` — ✅ 정상
| 위치 | 코드 | 판정 |
|------|------|------|
| L171 | `user.last_login_at = now().replace(tzinfo=None)` | ✅ DB 저장용 naive 변환 |
| L226 | `db_token.expires_at < now().replace(tzinfo=None)` | ✅ naive datetime끼리 비교 |
| L486 | `revoked_at=now().replace(tzinfo=None)` | ✅ DB 저장용 naive 변환 |
| L511 | `revoked_at=now().replace(tzinfo=None)` | ✅ DB 저장용 naive 변환 |
### 3.3 `app/user/api/routers/v1/auth.py` — ✅ 정상
| 위치 | 코드 | 판정 |
|------|------|------|
| L464 | `user.last_login_at = now().replace(tzinfo=None)` | ✅ 테스트 엔드포인트, DB 저장용 |
### 3.4 `app/social/services.py` — ✅ 정상
| 위치 | 코드 | 판정 |
|------|------|------|
| L308 | `current_time = now().replace(tzinfo=None)` | ✅ DB datetime과 비교용 |
| L506 | `current_time = now().replace(tzinfo=None)` | ✅ 토큰 만료 확인 |
| L577 | `now().replace(tzinfo=None) + timedelta(seconds=...)` | ✅ 토큰 만료시간 DB 저장 |
| L639 | `now().replace(tzinfo=None) + timedelta(seconds=...)` | ✅ 신규 계정 토큰 만료시간 |
| L693 | `now().replace(tzinfo=None) + timedelta(seconds=...)` | ✅ 토큰 업데이트 시 만료시간 |
| L709 | `account.connected_at = now().replace(tzinfo=None)` | ✅ 재연결 시간 DB 저장 |
### 3.5 `app/social/worker/upload_task.py` — ✅ 정상
| 위치 | 코드 | 판정 |
|------|------|------|
| L74 | `upload.uploaded_at = now().replace(tzinfo=None)` | ✅ 업로드 완료시간 DB 저장 |
### 3.6 `app/utils/logger.py` — ✅ 정상
| 위치 | 코드 | 판정 |
|------|------|------|
| L27 | `from app.utils.timezone import today_str` | ✅ 로그 파일명에 서울 기준 날짜 사용 |
| L89 | `today = today_str()` | ✅ `{날짜}_app.log` 파일명 |
---
## 4. 모델 `created_at` / `updated_at` 패턴 검수
모든 모델의 `created_at`, `updated_at` 컬럼은 `server_default=func.now()`를 사용합니다.
| 모델 | 파일 | `created_at` | `updated_at` | 판정 |
|------|------|:---:|:---:|:---:|
| User | `app/user/models.py` | `func.now()` | `func.now()` + `onupdate` | ✅ |
| RefreshToken | `app/user/models.py` | `func.now()` | — | ✅ |
| SocialAccount | `app/user/models.py` | `func.now()` | `func.now()` + `onupdate` | ✅ |
| Project | `app/home/models.py` | `func.now()` | — | ✅ |
| Image | `app/home/models.py` | `func.now()` | — | ✅ |
| Lyric | `app/lyric/models.py` | `func.now()` | — | ✅ |
| Song | `app/song/models.py` | `func.now()` | — | ✅ |
| SongTimestamp | `app/song/models.py` | `func.now()` | — | ✅ |
| Video | `app/video/models.py` | `func.now()` | — | ✅ |
| SNSUploadTask | `app/sns/models.py` | `func.now()` | — | ✅ |
| SocialUpload | `app/social/models.py` | `func.now()` | `func.now()` + `onupdate` | ✅ |
> `func.now()`는 MySQL 서버의 `NOW()` 함수를 호출하므로 DB 서버 타임존(서울)이 적용됩니다.
---
## 5. `now().replace(tzinfo=None)` 패턴 분석
이 프로젝트에서는 **aware datetime → naive datetime** 변환 패턴이 일관되게 사용됩니다:
```python
now().replace(tzinfo=None) # Asia/Seoul aware → naive (값은 KST 유지)
```
**이유**: MySQL의 `DateTime` 타입은 타임존 정보를 저장하지 않으므로(naive datetime), DB에 저장하거나 DB 값과 비교할 때 `tzinfo`를 제거해야 합니다.
**검증**: 이 패턴은 `now()`가 이미 서울 타임존 기준이므로, `.replace(tzinfo=None)` 후에도 **값 자체는 KST 시간**을 유지합니다. DB의 `func.now()`도 KST이므로 비교 시 일관성이 보장됩니다.
| 사용처 | 목적 | 일관성 |
|--------|------|:------:|
| `jwt.py:110` | refresh token 만료시간 DB 저장 | ✅ |
| `auth.py:171` | 마지막 로그인 시간 DB 저장 | ✅ |
| `auth.py:226` | refresh token 만료 여부 비교 | ✅ |
| `auth.py:486,511` | token 폐기 시간 DB 저장 | ✅ |
| `auth.py(router):464` | 테스트 엔드포인트 로그인 시간 | ✅ |
| `social/services.py:308,506` | 토큰 만료 비교 | ✅ |
| `social/services.py:577,639,693` | 토큰 만료시간 DB 저장 | ✅ |
| `social/services.py:709` | 재연결 시간 DB 저장 | ✅ |
| `social/worker/upload_task.py:74` | 업로드 완료시간 DB 저장 | ✅ |
---
## 6. 최종 결론
### ✅ 전체 판정: 정상 (PASS)
프로젝트 전반에 걸쳐 타임존 처리가 **일관되게** 구현되어 있습니다:
1. **bare `datetime.now()` 미사용** — 앱 코드에서 타임존 없는 `datetime.now()` 직접 호출이 없음
2. **`datetime.utcnow()` 미사용** — UTC 기반 시간 생성 없음
3. **`app.utils.timezone.now()` 일관 사용** — 모든 서비스/라우터에서 유틸리티 함수 사용
4. **DB 저장 시 naive 변환 일관** — `now().replace(tzinfo=None)` 패턴 통일
5. **모델 기본값 `func.now()` 통일** — DB 서버 타임존(서울) 기준으로 자동 설정
6. **비교 연산 안전** — DB의 naive datetime과 비교 시 항상 naive로 변환 후 비교
### 주의사항 (현재 문제 아님, 향후 참고용)
1. **DB 서버 타임존 변경 주의**: `func.now()`는 DB 서버 타임존에 의존하므로, DB 서버의 타임존이 변경되면 `created_at`/`updated_at` 등의 자동 생성 시간이 영향을 받습니다.
2. **다중 타임존 확장 시**: 현재는 단일 타임존(서울)만 사용하므로 문제없지만, 다국적 서비스 확장 시 UTC 기반 저장 + 표시 시 변환 패턴으로 전환을 고려할 수 있습니다.
3. **`replace(tzinfo=None)` 패턴**: 값은 유지하면서 타임존 정보만 제거하므로 안전하지만, 코드 리뷰 시 의도를 명확히 하기 위해 주석을 유지하는 것이 좋습니다(현재 `social/services.py:307`에 주석 존재).