| import google.generativeai as genai |
| import pandas as pd |
| import json |
| import os |
| import time |
| import re |
| import logging |
| import numpy as np |
| import random |
| from pathlib import Path |
| import warnings |
|
|
| warnings.filterwarnings('ignore', category=FutureWarning) |
|
|
| |
| VERSION_NAME = "0904" |
| timestamp = time.strftime("%Y%m%d_%H%M%S") |
|
|
| DATA_PATH = './data/' |
| SUBMISSION_PATH = './submission/' |
| SAVE_PATH = './save/' |
|
|
| PERSONA_CACHE_PATH = os.path.join(SAVE_PATH, f'personas_cache_{VERSION_NAME}') |
| os.makedirs(SUBMISSION_PATH, exist_ok=True) |
| os.makedirs(PERSONA_CACHE_PATH, exist_ok=True) |
| os.makedirs(SAVE_PATH, exist_ok=True) |
|
|
| |
| log_filename = os.path.join(SAVE_PATH, f'log_{VERSION_NAME}_{timestamp}.log') |
| logger = logging.getLogger(__name__) |
| if logger.hasHandlers(): |
| logger.handlers.clear() |
| logger.setLevel(logging.INFO) |
| formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') |
|
|
| stream_handler = logging.StreamHandler() |
| stream_handler.setFormatter(formatter) |
| logger.addHandler(stream_handler) |
|
|
| file_handler = logging.FileHandler(log_filename, encoding='utf-8') |
| file_handler.setFormatter(formatter) |
| logger.addHandler(file_handler) |
| logger.info("✔️ 로깅 설정 완료.") |
|
|
| |
| USE_API_TO_GENERATE_PERSONAS = False |
| SIMULATION_RUNS = 10 |
|
|
| RANDOM_SEED = 3314 |
| random.seed(RANDOM_SEED) |
| np.random.seed(RANDOM_SEED) |
|
|
| if USE_API_TO_GENERATE_PERSONAS: |
| try: |
| GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY", "") |
| if not GEMINI_API_KEY: |
| raise ValueError("환경변수 GEMINI_API_KEY가 설정되어 있지 않습니다.") |
| |
| genai.configure(api_key=GEMINI_API_KEY) |
| model = genai.GenerativeModel( |
| model_name='gemini-2.5-flash-lite', |
| generation_config={"temperature": 0, "top_p": 1.0, "response_mime_type": "application/json"} |
| ) |
| logger.info("✔️ Gemini API 키 설정 완료.") |
| except Exception as e: |
| logger.error(f"✖️ API 키 설정 중 오류 발생: {e}") |
| USE_API_TO_GENERATE_PERSONAS = False |
| logger.warning("✖️ API 사용 불가. [캐시/샘플 사용 모드]로 전환.") |
|
|
| |
| DEFAULT_MODIFIERS = [1.0] * 12 |
| NEW_PRODUCT_LAUNCH_DATES = { |
| '덴마크 하이그릭요거트 400g': '2025-02-07', |
| '소화가 잘되는 우유로 만든 바닐라라떼 250mL': '2025-02-21', |
| '소화가 잘되는 우유로 만든 카페라떼 250mL': '2025-02-21', |
| '리챔 오믈레햄 200g': '2025-05-22', |
| '리챔 오믈레햄 340g': '2025-05-22', |
| } |
| |
| MARKET_DATA = { |
| '덴마크 하이그릭요거트 400g': {"launch_date": (2024, 2, 7), "price": 3980, "features": "프리미엄, 덴마크산 유산균, 고단백(28g), 락토프리, 무첨가, 아연/칼슘 함유.", "marketing": "2025년 6월부터 TV CF/소셜미디어 대규모 캠페인. 2024년 6-7월 TV/Youtube/SNS 광고, 6-8월 수도권 아파트 엘리베이터 광고. 광고모델: 일반인", "target": "건강과 자기관리에 관심 많은 20-40대, 1인 가구, 중상 소득층.", "insights": "론칭 1년 만에 누적 매출 200억 원 돌파. 연 매출 1,000억 원 메가 브랜드 목표."}, |
| '리챔 오믈레햄 200g': {"launch_date": (2024, 5, 22), "price": 5080, "features": "오믈렛(케첩, 계란)과 햄의 결합, 저나트륨, 내열성 케첩 소스, 간편조리.", "marketing": "출시 초기 집중 마케팅 예상됨.", "target": "편의성 추구 1인 가구, 학생, 직장인, 요리 초보자.", "insights": "소비자들이 캔햄을 케첩, 계란과 함께 즐긴다는 점에서 착안."}, |
| '리챔 오믈레햄 340g': {"launch_date": (2024, 5, 22), "price": 7480, "features": "오믈렛(케첩, 계란)과 햄의 결합, 저나트륨, 내열성 케첩 소스, 간편조리.", "marketing": "출시 초기 집중 마케팅 예상됨.", "target": "3-4인 가구 주부, 캠핑족.", "insights": "200g 제품과 동일한 컨셉이나, 용량이 커 가족 단위 소비자를 타겟."}, |
| '소화가 잘되는 우유로 만든 바닐라라떼 250mL': {"launch_date": (2024, 2, 21), "price": 2800, "features": "락토프리(유당 100% 제거), 1등급 국산 원유, 저당 트렌드 반영.", "marketing": "별도 광고 없이 SNS 바이럴로 급성장.", "target": "유당불내증을 겪는 20-50대, 달콤한 커피 선호 젊은 층, 직장인.", "insights": "출시 2개월 만에 300만 개 돌파. 편의점 채널에서 특히 인기."}, |
| '소화가 잘되는 우유로 만든 카페라떼 250mL': {"launch_date": (2024, 2, 21), "price": 2800, "features": "락토프리(유당 100% 제거), 1등급 국산 원유, 저당 트렌드 반영.", "marketing": "별도 광고 없이 SNS 바이럴로 급성장.", "target": "유당불내증을 겪는 20-50대, 부드러운 커피 선호층, 직장인.", "insights": "출시 2개월 만에 300만 개 돌파. 바닐라라떼와 함께 시장 견인."}, |
| '동원맛참 고소참기름 135g': {"launch_date": (2023, 8, 22), "price": 2880, "features": "바로 먹는 밥반찬 컨셉, 고소한 참기름, 고단백(24g), HMR.", "marketing": "모델 안유진 활용 TV CF, SNS 챌린지. 2024년 대한민국광고대상 금상 수상. 2025년 3월 '마요참기름' 파생 신제품 출시.", "target": "MZ세대, 1-2인 가구, 자취생, 바쁜 직장인.", "insights": "출시 1년 만에 매출 3배 성장. 추석 등 명절 선물세트로도 인기."}, |
| '동원맛참 고소참기름 90g': {"launch_date": (2023, 8, 22), "price": 2380, "features": "바로 먹는 밥반찬 컨셉, 고소한 참기름, 고단백, HMR, 1인용 소용량.", "marketing": "135g 제품과 동일한 마케팅 활동.", "target": "1인 가구, 학생 등 소용량 선호 소비자.", "insights": "135g 제품의 성공에 힘입어 라인업 확대."}, |
| '동원맛참 매콤참기름 135g': {"launch_date": (2023, 8, 22), "price": 2880, "features": "바로 먹는 밥반찬 컨셉, 매콤한 특제소스, 고단백(24g), HMR.", "marketing": "모델 안유진 활용 TV CF, SNS 챌린지.", "target": "매운맛 선호 MZ세대, 1-2인 가구.", "insights": "고소참기름 맛과 함께 맛참 브랜드의 양대 축."}, |
| '동원맛참 매콤참기름 90g': {"launch_date": (2023, 8, 22), "price": 2380, "features": "바로 먹는 밥반찬 컨셉, 매콤한 특제소스, 고단백, HMR, 1인용 소용량.", "marketing": "135g 제품과 동일한 마케팅 활동.", "target": "1인 가구, 매운맛 선호 학생 등 소용량 선호 소비자.", "insights": "소용량 시장 공략을 위한 라인업."}, |
| '동원참치액 순 500g': {"launch_date": None, "price": 7980, "features": "훈연참치추출물 80%, 깔끔한 맛, 멸치 숙성액 함유.", "marketing": "참치 명가 노하우 강조. 명절 선물세트 포함.", "target": "요리 초보자, 맑은 국물 요리 선호 주부.", "insights": "참치액 시장 연 42% 성장. 2024년 참치액 매출 50% 이상 증가. 동원F&B의 핵심 성장 동력."}, |
| '동원참치액 진 500g': {"launch_date": None, "price": 7980, "features": "훈연참치추출물 80%, 진한 가쓰오 풍미.", "marketing": "참치 명가 노하우 강조. 명절 선물세트 포함.", "target": "요리 애호가, 깊은 맛 선호 주부, 자영업자(식당).", "insights": "순 제품과 함께 시장 점유율 확대. 2025년 1분기 조미식품 사업 두 자릿수 성장."}, |
| '프리미엄 동원참치액 500g': {"launch_date": None, "price": 14990, "features": "황다랑어 추출물, 훈연참치추출물 85%, 사양벌꿀 등 고급 부재료.", "marketing": "프리미엄 포지셔닝.", "target": "미식가, 요리 고관여자, 소득 수준 높은 주부, 선물용.", "insights": "고가 라인업으로 브랜드 이미지 제고 및 수익성 강화."}, |
| '동원참치액 순 900g': {"launch_date": None, "price": 12990, "features": "순 500g과 동일, 대용량.", "target": "헤비 유저, 4인 이상 가구.", "insights": "참치액 시장의 성장세에 따른 대용량 수요 충족."}, |
| '동원참치액 진 900g': {"launch_date": None, "price": 12990, "features": "진 500g과 동일, 대용량.", "target": "헤비 유저, 자영업자.", "insights": "업소용 및 다빈도 사용 가구를 위한 제품."}, |
| '프리미엄 동원참치액 900g': {"launch_date": None, "price": 22990, "features": "프리미엄 500g과 동일, 대용량.", "target": "선물용, 고급 식당.", "insights": "프리미엄 제품군의 구색 강화."}, |
| } |
|
|
| MARKET_CONTEXT = { |
| "market_definitions": { |
| "health_conscious_market": {"size": 300000}, "convenience_seekers_market": {"size": 500000}, |
| "lacto_free_market": {"size": 150000}, "premium_cooking_market": {"size": 100000}, |
| "fan_consumption_market": {"size": 100000}, "camping_outdoor_market": {"size": 100000}, |
| "b2b_foodservice_market": {"size": 100000} |
| }, |
| "persona_segmentations": { |
| |
| |
| |
| |
| |
| |
| "health_focused_segment": { |
| "적극적 헬스인": {"share": 0.1, "description": "주 3회 이상 운동, 단백질 섭취에 적극적"}, |
| "가벼운 유지어터": {"share": 0.5, "description": "주 1-2회 가볍게 운동, 저당/저칼로리 간편식 선호"}, |
| "건강 관심 중년": {"share": 0.15, "description": "근감소증 예방 등 건강 유지를 위해 단백질 섭취 필요"}, |
| "저당 선호층": {"share": 0.25, "description": "건강·다이어트 이유로 저당 제품을 선택하는 20~40대 여성"} |
| }, |
|
|
| |
| |
| |
| |
| |
| |
| "convenience_focused_segment": { |
| "바쁜 1인 가구 직장인": {"share": 0.3, "description": "시간 절약을 위해 간편한 식사를 선호하는 2040 직장인"}, |
| "자취생/대학생": {"share": 0.3, "description": "저렴하고 간단하게 한 끼를 해결하려는 10~20대"}, |
| "간편 요리 선호 주부": {"share": 0.1, "description": "직접 요리하되, 조리 과정을 최소화하는 밀키트/반조리 제품 선호"}, |
| "맞벌이 부부" : {"share" : 0.3, "description" : "시간 절약을 위해 간편한 식사를 선호하는 2인 이상 가구"} |
| }, |
| |
| |
| |
| |
| |
| "b2b_segment": { |
| "요식업 사업자": {"share": 0.3, "description": "식당 운영자 (참치액 대량구매)"}, |
| "단체급식 담당자": {"share": 0.15, "description": "학교, 기업 급식소 (참치액, 참치캔)"}, |
| "기업 복지담당자": {"share": 0.55, "description": "명절 선물세트 구매 결정권자"} |
| }, |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| "lifestyle_segment": { |
| "프리미엄 요리족": {"share": 0.05, "description": "고급 조리재료에 투자하는 3040 주부·가정요리층"}, |
| "가성비커피족": {"share": 0.15, "description": "카페 대신 편의점·RTD 커피로 합리적으로 즐기는 10~50대"}, |
| "유당불내증": {"share": 0.2, "description": "락토프리 제품 필수 구매층"}, |
| "캠핑족": {"share": 0.15, "description": "주말 캠핑, 간편조리 선호 (리챔, 맛참)"}, |
| "광고 친화 MZ": {"share": 0.15, "description": "광고·SNS에서 본 제품을 빠르게 소비하는 2030"}, |
| "팬덤소비층": {"share": 0.15, "description": "광고모델 팬덤 및 MZ 브랜드 충성 기반 소비"}, |
| "신제품 체험러": {"share": 0.15, "description": "신제품·한정판 제품을 꼭 시도하는 얼리어답터형 소비자"} |
| } |
| }, |
| "persona_framework": { |
| "attributes": { |
| "운동 빈도": {}, "건강 관심도": {}, "핵심 니즈": {}, "성별": {}, "가구 형태": {}, |
| "직업": {}, "가격 민감도": {}, "식단 관리 여부": {}, "브랜드 선호도": {}, "간편식 선호도": {}, |
| "연령대": {}, "소득 수준": {}, "주 사용 쇼핑 채널": {}, "신제품 수용성": {}, "광고 모델 영향력": {} |
| } |
| }, |
| "seasonal_and_events": { |
| "event_effects": { |
| "2024-08": {"name": "동원 40주년 + 추석 선물세트", "uplift": 0.02, "products": ["맛참", "참치액"]}, |
| "2024-09": {"name": "동원 40주년 + 추석 선물세트", "uplift": 0.05, "products": ["맛참", "참치액"]}, |
| "2025-01": {"name": "설 선물세트", "uplift": 0.03, "products": ["맛참", "참치액"]}, |
| "2025-03": {"name": "마요참기름 신제품 출시", "uplift": 0.02, "products": ["맛참"]}, |
| "2025-06": {"name": "하이그릭 대규모 캠페인", "uplift": 0.03, "products": ["하이그릭요거트"]} |
| } |
| } |
| } |
| logger.info("✔️ 1. 마켓 및 제품 데이터 정의 완료.") |
|
|
| |
| PRODUCT_PARAMS = { |
| '덴마크 하이그릭요거트 400g': { |
| 'tam': 9500000, 'market_share': 0.15, |
| 'modifiers': [0, 0, 0, 0, 0, 0, 0, 1.08, 1.02, 0.85, 0.7, 1.4], |
| 'initial_rate': 0.12, 'p_churn': 0.005 |
| }, |
| '소화가 잘되는 우유로 만든 바닐라라떼 250mL': { |
| 'tam': 2800000, 'market_share': 0.33, |
| 'modifiers': [0, 0, 0, 0, 0, 0, 0, 1.0, 1.2, 1.25, 1.3, 2.0], |
| 'initial_rate': 0.16, 'p_churn': 0.003,'jump_factor': {8: 7} |
| }, |
| '소화가 잘되는 우유로 만든 카페라떼 250mL': { |
| 'tam': 2800000, 'market_share': 0.33, |
| 'modifiers': [0, 0, 0, 0, 0, 0, 0, 1.0, 1.4, 1.5, 1.7, 2.8], |
| 'initial_rate': 0.2, 'p_churn': 0.003,'jump_factor': {8: 7.5} |
| }, |
| '동원맛참 고소참기름 135g': { |
| 'tam': 8500000 , 'market_share': 0.148, |
| 'modifiers': [0.85, 0.87, 0.89, 0.91, 0.93, 0.99, 1.0, 1.1, 1.5,0.78, 0.75, 0.73], |
| 'initial_rate': 0.53, 'p_churn': 0.025 |
| }, |
| '동원맛참 고소참기름 90g': { |
| 'tam': 8500000 , 'market_share': 0.102, |
| 'modifiers': [0.85, 0.87, 0.89, 0.91, 0.93, 0.97, 1.0, 1.1, 1.5, 0.78, 0.75,0.73], |
| 'initial_rate': 0.52, 'p_churn': 0.03 |
| }, |
| '동원맛참 매콤참기름 135g': { |
| 'tam': 8500000 , 'market_share': 0.14, |
| 'modifiers': [0.85, 0.87, 0.89, 0.91, 0.93, 0.99, 1.0, 1.1, 1.5, 0.78, 0.75,0.73], |
| 'initial_rate': 0.53,'p_churn': 0.028 |
| }, |
| '동원맛참 매콤참기름 90g': { |
| 'tam': 8500000 , 'market_share': 0.1, |
| 'modifiers': [0.85, 0.87, 0.89, 0.91, 0.93, 0.99, 1.0, 1.1, 1.5, 0.78, 0.75,0.73], |
| 'initial_rate': 0.52,'p_churn': 0.03 |
| }, |
| '리챔 오믈레햄 200g': { |
| 'tam': 800000, 'market_share': 0.32, |
| 'modifiers': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0, 1.0], |
| 'initial_rate': 0.17, 'p_churn': 0.0001, 'jump_factor': {11: 4.2} |
| }, |
| '리챔 오믈레햄 340g': { |
| 'tam': 800000, 'market_share': 0.30, |
| 'modifiers': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0, 1.0], |
| 'initial_rate': 0.025, 'p_churn': 0.0001,'jump_factor': {11: 2.5} |
| }, |
| '동원참치액 순 500g': { |
| 'tam': 3000000, 'market_share': 0.08, |
| 'modifiers': [2.5, 0.9, 1.0, 1.2, 1.3, 1.5, 1.0, 1.2, 3.3, 1.1, 1.1, 1.1], |
| 'initial_rate': 0.33, 'p_churn': 0.0008, |
| }, |
| '동원참치액 순 900g': { |
| 'tam': 2000000, 'market_share': 0.08, |
| 'modifiers': [ |
| 2.5, 0.9, 1.0, 1.2, 1.3, 1.5, 1.0, 1.2, 3.3, 1.1, 1.1, 1.1], |
| 'initial_rate': 0.36, 'p_churn': 0.0001, |
| }, |
| '동원참치액 진 500g': { |
| 'tam': 4200000, 'market_share': 0.08, |
| 'modifiers': [ |
| 2.5, 0.9, 1.0, 1.2, 1.3, 1.5, 1.0, 1.2, 3.3, 1.2, 1.3, 1.5], |
| 'initial_rate': 0.4, 'p_churn': 0.0008, |
| }, |
| '동원참치액 진 900g': { |
| 'tam': 2800000, 'market_share': 0.08, |
| 'modifiers': [ |
| 2.5, 0.9, 1.0, 1.2, 1.3, 1.5, 1.0, 1.2, 3.3, 1.2, 1.3, 1.5], |
| 'initial_rate': 0.4, 'p_churn': 0.0004, |
| }, |
| '프리미엄 동원참치액 500g': { |
| 'tam': 1250000, |
| 'market_share': 0.072, |
| 'modifiers': [1.9, 0.8, 1.0, 1.2, 1.3, 1.5, 1.0, 1.1, 3.5, 0.85, 1.0, 1.1], |
| 'initial_rate': 0.155, 'p_churn': 0.00001, 'jump_factor': {0: 2.2, 6: 1.4 |
| } |
| }, |
| '프리미엄 동원참치액 900g': { |
| 'tam': 850000, |
| 'market_share': 0.072, |
| 'modifiers': [1.9, 0.9, 1.0, 1.2, 1.3, 1.5, 1.0, 1.1, 3.5, 1.5, 1.6, 1.7], |
| 'initial_rate': 0.16, 'p_churn': 0.0001, 'jump_factor': {0: 3, 6: 1.4} |
| }, |
| |
| 'default': {'tam': 1000000, 'market_share': 0.10, 'modifiers': DEFAULT_MODIFIERS, 'initial_rate': 0.1, 'p_churn': 0.01} |
| } |
|
|
| |
| START_MONTH_INDEX = 6 |
| for product, params in PRODUCT_PARAMS.items(): |
| if product not in NEW_PRODUCT_LAUNCH_DATES: |
| original_modifiers = params['modifiers'] |
| reordered_modifiers = original_modifiers[START_MONTH_INDEX:] + original_modifiers[:START_MONTH_INDEX] |
| PRODUCT_PARAMS[product]['modifiers'] = reordered_modifiers |
| logger.info("✔️ 2. SKU 파라미터 설정 완료.") |
|
|
| |
| |
| def sanitize_filename(name): |
| return re.sub(r'[\\/*?:"<>|]', '_', name) |
|
|
| def get_target_market_size(product_info): |
| """제품명에 따라 타겟 시장 규모를 반환합니다.""" |
| product_name = product_info['product_name'] |
| if "하이그릭요거트" in product_name: return 40000 |
| elif "라떼" in product_name: return 97500 |
| else: return 50000 |
|
|
| def get_product_segments(product_info): |
| """제품명에 따라 페르소나 세그먼트 그룹을 반환합니다.""" |
| product_name = product_info['product_name'] |
| if "하이그릭요거트" in product_name: return MARKET_CONTEXT['persona_segmentations']['health_focused_segment'] |
| elif "맛참" in product_name: return MARKET_CONTEXT['persona_segmentations']['convenience_focused_segment'] |
| else: return MARKET_CONTEXT['persona_segmentations']['lifestyle_segment'] |
|
|
| def create_single_persona_generation_prompt(product_info, persona_id, target_segment_name): |
| """Gemini API에 전송할 단일 페르소나 생성용 프롬프트를 만듭니다.""" |
| market_size = get_target_market_size(product_info) |
| max_population = min(market_size // 10, 10000) |
| |
| prompt = f""" |
| [제품 정보] |
| - 제품명: {product_info['product_name']} |
| - 특징: {product_info.get('features', 'N/A')} |
| |
| [생성 목표] |
| - 페르소나 ID: {persona_id} |
| - 타겟 세그먼트: "{target_segment_name}" |
| |
| [지시사항] |
| 1. 반드시 아래 JSON 스키마를 준수하여 **단 하나의 페르소나 객체만**을 생성하고, 다른 설명 없이 JSON만 출력하세요. |
| 2. `population_estimate` 값은 100부터 {max_population} 사이의 숫자로 설정하세요. |
| 3. `monthly_freq` 값은 0.1부터 1.5 사이의 소수로 설정하세요. |
| 4. `core_attributes`에는 정의된 15개 속성을 모두 포함하여 구체적인 값을 할당하세요. |
| |
| [출력 JSON 스키마] |
| {{ |
| "persona_id": "{persona_id}", |
| "population_estimate": 1000, |
| "monthly_freq": 0.8, |
| "core_attributes": {{ |
| "성별": "여성", |
| "연령대": "30대", |
| "가구 형태": "1인 가구", |
| "직업": "직장인", |
| "소득 수준": "중상", |
| "운동 빈도": "주 3-4회", |
| "건강 관심도": "높음", |
| "식단 관리 여부": "철저하게 관리", |
| "핵심 니즈": "고단백질 간식", |
| "간편식 선호도": "보통", |
| "가격 민감도": "낮음", |
| "브랜드 선호도": "품질 우선", |
| "주 사용 쇼핑 채널": "온라인", |
| "신제품 수용성": "높음", |
| "광고 모델 영향력": "보통" |
| }} |
| }} |
| """ |
| return prompt |
|
|
| def get_or_generate_personas(product_info, num_personas=10): |
| """캐시된 페르소나를 로드하거나, API를 통해 새로 생성합니다.""" |
| safe_product_name = sanitize_filename(product_info['product_name']) |
| persona_cache_file = os.path.join(PERSONA_CACHE_PATH, f'{safe_product_name}_personas.json') |
|
|
| |
| if not USE_API_TO_GENERATE_PERSONAS and os.path.exists(persona_cache_file): |
| try: |
| with open(persona_cache_file, 'r', encoding='utf-8') as f: |
| personas = json.load(f) |
| logger.info(f"✔️ [캐시 파일 사용] '{product_info['product_name']}' 페르소나 {len(personas)}명 로드 완료") |
| return personas |
| except json.JSONDecodeError: |
| logger.warning(f"✖️ 캐시 파일 손상: {persona_cache_file}. API로 생성 시도.") |
| pass |
|
|
| |
| if USE_API_TO_GENERATE_PERSONAS: |
| logger.info(f"'{product_info['product_name']}' 페르소나 생성 시작...") |
| all_personas = [] |
| segments = get_product_segments(product_info) |
| segment_names = list(segments.keys()) |
|
|
| for i in range(num_personas): |
| persona_id = f"{safe_product_name}_P{i+1:03d}" |
| segment_name = random.choice(segment_names) |
| logger.info(f" 페르소나 {i+1}/{num_personas} 생성 중 (세그먼트: {segment_name})...") |
| try: |
| prompt = create_single_persona_generation_prompt(product_info, persona_id, segment_name) |
| response = model.generate_content(prompt) |
| cleaned_text = re.sub(r'```json\n?|```', '', response.text).strip() |
| single_persona = json.loads(cleaned_text) |
| all_personas.append(single_persona) |
| time.sleep(1) |
| except Exception as e: |
| logger.error(f" ✖️ 페르소나 {persona_id} 생성 실패: {e}") |
| logger.error(f" - 실패한 응답 내용: {response.text if 'response' in locals() else 'N/A'}") |
| |
| if all_personas: |
| with open(persona_cache_file, 'w', encoding='utf-8') as f: |
| json.dump(all_personas, f, ensure_ascii=False, indent=4) |
| logger.info(f" 페르소나 {len(all_personas)}명 생성 및 캐시 저장 완료") |
| return all_personas |
|
|
| |
| logger.warning(f"✖️ API 사용이 비활성화되었고 캐시 파일도 없어 페르소나를 생성할 수 없습니다.") |
| return [] |
|
|
| |
| class PersonaAgent: |
| """개별 페르소나 그룹을 대표하는 에이전트""" |
| def __init__(self, persona_data): |
| self.id = persona_data.get('persona_id', 'N/A') |
| self.attributes = persona_data.get('core_attributes', {}) |
| self.population = persona_data.get('population_estimate', 0) |
| |
| self.base_purchase_rate = persona_data.get('monthly_freq', 0) / 30.0 |
| self.state = 'Unaware' |
| self.p_churn = 0.01 |
|
|
| def update_state(self, p_innovation, p_imitation, adoption_rate): |
| """Bass Model에 따라 에이전트의 상태(인지/활성/이탈)를 업데이트합니다.""" |
| if self.state == 'Unaware': |
| |
| prob_aware = p_innovation + p_imitation * adoption_rate |
| if np.random.rand() < prob_aware: |
| self.state = 'Active' |
| elif self.state == 'Active': |
| if np.random.rand() < self.p_churn: |
| self.state = 'Churned' |
|
|
| def attempt_purchase(self, month_modifier): |
| """이번 달에 구매를 시도하는 인구 수를 계산합니다.""" |
| if self.state == 'Active' and self.population > 0: |
| |
| modified_daily_rate = self.base_purchase_rate * month_modifier |
| |
| monthly_purchase_prob = 1 - (1 - modified_daily_rate)**30 |
| |
| num_purchases = np.random.binomial(n=self.population, p=min(monthly_purchase_prob, 1.0)) |
| return num_purchases |
| return 0 |
|
|
| class MarketSimulation: |
| """여러 페르소나 에이전트를 관리하며 시장 전체의 시뮬레이션을 실행합니다.""" |
| def __init__(self, personas, initial_adoption_rate, p_churn=0.01): |
| self.agents = [PersonaAgent(p) for p in personas if p] |
| self.total_population = sum(agent.population for agent in self.agents) |
| self.p_innovation = 0.01 |
| self.q_imitation = 0.15 |
| self.initial_adoption_rate = initial_adoption_rate |
|
|
| for agent in self.agents: |
| agent.p_churn = p_churn |
|
|
| self.active_population = 0 |
| logger.info(f" - 시뮬레이션 초기화. 총 페르소나 인구: {self.total_population}") |
|
|
| def run_simulation(self, months=12, modifiers=None, jump_factors=None): |
| monthly_sales_results = [] |
| if not self.agents: return [0] * months |
|
|
| is_launched = False |
|
|
| for month_index in range(months): |
| |
| is_selling_this_month = modifiers[month_index] > 0 |
| if is_selling_this_month and not is_launched: |
| is_launched = True |
| logger.info(f" {month_index + 1}개월차에 제품 출시!") |
| |
| target_active_population = self.total_population * self.initial_adoption_rate |
| current_active_population = 0 |
| |
| shuffled_agents = list(self.agents) |
| random.shuffle(shuffled_agents) |
| activated_agent_count = 0 |
| |
| for agent in shuffled_agents: |
| if current_active_population >= target_active_population: |
| break |
| if agent.state == 'Unaware': |
| agent.state = 'Active' |
| current_active_population += agent.population |
| activated_agent_count += 1 |
| |
| self.active_population = current_active_population |
| logger.info(f" - 초기 활성 인구: {self.active_population} (에이전트 {activated_agent_count}명 활성화)") |
|
|
| |
| |
| if is_launched and jump_factors and month_index in jump_factors: |
| jump_multiplier = jump_factors[month_index] |
| if self.active_population > 0: |
| logger.info(f" {month_index + 1}개월차에 Jump Event 발생! (배율: {jump_multiplier}x)") |
| |
| |
| target_jump_population = min( |
| int(self.active_population * jump_multiplier), |
| self.total_population) |
| |
| |
| population_to_activate = target_jump_population - self.active_population |
|
|
| if population_to_activate > 0: |
| |
| unaware_agents = [agent for agent in self.agents if agent.state == 'Unaware'] |
| random.shuffle(unaware_agents) |
| |
| newly_activated_population = 0 |
| |
| for agent in unaware_agents: |
| if newly_activated_population >= population_to_activate: |
| break |
| agent.state = 'Active' |
| newly_activated_population += agent.population |
| |
| |
| |
| self.active_population = sum(agent.population for agent in self.agents if agent.state == 'Active') |
| logger.info(f" - Jump 결과: 활성 인구가 {self.active_population}으로 증가했습니다.") |
|
|
| |
| adoption_rate = self.active_population / self.total_population if self.total_population > 0 else 0 |
| |
| current_month_sales = 0 |
| next_month_active_population = 0 |
| for agent in self.agents: |
| if not is_launched: |
| continue |
|
|
| |
| agent.update_state(self.p_innovation, self.q_imitation, adoption_rate) |
| |
| |
| month_modifier = modifiers[month_index] if modifiers else 1.0 |
| current_month_sales += agent.attempt_purchase(month_modifier) |
| |
| |
| if agent.state == 'Active': |
| next_month_active_population += agent.population |
|
|
| self.active_population = next_month_active_population |
| monthly_sales_results.append(int(current_month_sales)) |
| |
| return monthly_sales_results |
| |
| |
| try: |
| submission_df = pd.read_csv(os.path.join(DATA_PATH, 'sample_submission.csv')) |
| except FileNotFoundError: |
| exit() |
|
|
| results_df = submission_df.copy() |
|
|
| |
| for index, row in results_df.iterrows(): |
| product_name = row['product_name'] |
|
|
| product_info = { |
| 'product_name': product_name, |
| 'features': MARKET_DATA.get(product_name, {}).get('features', '제품 특징 정보 없음') |
| } |
| |
| product_personas = get_or_generate_personas(product_info) |
|
|
| if not product_personas: |
| logger.error(f" ✖️ 페르소나 데이터 없음") |
| results_df.iloc[index, 1:] = [0] * 12 |
| continue |
|
|
| params = PRODUCT_PARAMS.get(product_name, PRODUCT_PARAMS['default']) |
| |
| all_runs_sales = [] |
| logger.info(f" [ {product_name} ] 몬테카를로 시뮬레이션 {SIMULATION_RUNS}회 실행 시작...") |
|
|
| for i in range(SIMULATION_RUNS): |
| |
| market_sim = MarketSimulation( |
| personas=product_personas, |
| initial_adoption_rate=params['initial_rate'], |
| p_churn=params.get('p_churn', 0.01) |
| ) |
| |
| |
| monthly_sales = market_sim.run_simulation( |
| months=12, |
| modifiers=params['modifiers'], |
| jump_factors=params.get('jump_factor') |
| ) |
| all_runs_sales.append(monthly_sales) |
| logger.info(f" - 실행 {i+1}/{SIMULATION_RUNS} 완료. 첫 달 판매량: {monthly_sales[7] if len(monthly_sales) > 7 else 0}") |
|
|
| |
| average_sales = np.mean(all_runs_sales, axis=0) |
| |
| |
| total_persona_population = sum(p.get('population_estimate', 0) for p in product_personas) |
| target_market_size = params.get('tam', 1000000) * params.get('market_share', 0.1) |
| scaling_factor = target_market_size / total_persona_population if total_persona_population > 0 else 0 |
| |
| final_scaled_sales = (average_sales * scaling_factor).astype(int) |
| |
| logger.info(f" - 스케일링 적용: TAM({target_market_size:.0f}) / 페르소나 인구({total_persona_population}) = 팩터({scaling_factor:.2f})") |
| |
| results_df.iloc[index, 1:] = final_scaled_sales |
| logger.info(f"[ {product_name} ] {SIMULATION_RUNS}회 평균 최종 예측 완료") |
| logger.info(f" 판매량 : {final_scaled_sales.tolist()}") |
|
|
| if index < len(results_df) - 1: |
| wait_time = 1 |
| time.sleep(wait_time) |
|
|
|
|
| |
| submission_filename = os.path.join(SUBMISSION_PATH, f'submission_{VERSION_NAME}_{timestamp}.csv') |
| results_df.to_csv(submission_filename, index=False, encoding='utf-8-sig') |
| logger.info(f"\n\n 모든 제품의 시뮬레이션 완료 ") |
| logger.info(f" 최종 제출 파일 '{submission_filename}' 생성 완료.") |