Spaces:
Running
Running
import os | |
import json | |
import re | |
import logging | |
import requests | |
import markdown | |
import time | |
import io | |
import random | |
import hashlib | |
from datetime import datetime | |
from dataclasses import dataclass | |
from itertools import combinations, product | |
from typing import Iterator | |
import streamlit as st | |
import pandas as pd | |
import PyPDF2 # For handling PDF files | |
from collections import Counter | |
from openai import OpenAI # OpenAI 라이브러리 | |
from gradio_client import Client | |
from kaggle.api.kaggle_api_extended import KaggleApi | |
import tempfile | |
import glob | |
import shutil | |
# ─── 추가된 라이브러리(절대 누락 금지) ─────────────────────────────── | |
import pyarrow.parquet as pq | |
from sklearn.feature_extraction.text import TfidfVectorizer | |
from sklearn.metrics.pairwise import cosine_similarity | |
# ─────────────────────────────── Environment Variables / Constants ───────────────────────── | |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "") | |
BRAVE_KEY = os.getenv("SERPHOUSE_API_KEY", "") # Brave Search API | |
KAGGLE_USERNAME = os.getenv("KAGGLE_USERNAME", "") | |
KAGGLE_KEY = os.getenv("KAGGLE_KEY", "") | |
KAGGLE_API_KEY = KAGGLE_KEY | |
if not (KAGGLE_USERNAME and KAGGLE_KEY): | |
raise RuntimeError("⚠️ KAGGLE_USERNAME과 KAGGLE_KEY 환경변수를 먼저 설정하세요.") | |
os.environ["KAGGLE_USERNAME"] = KAGGLE_USERNAME | |
os.environ["KAGGLE_KEY"] = KAGGLE_KEY | |
BRAVE_ENDPOINT = "https://api.search.brave.com/res/v1/web/search" | |
IMAGE_API_URL = "http://211.233.58.201:7896" # 예시 이미지 생성용 API | |
MAX_TOKENS = 7999 | |
# ─────────────────────────────── Logging ─────────────────────────────── | |
logging.basicConfig( | |
level=logging.INFO, | |
format="%(asctime)s - %(levelname)s - %(message)s" | |
) | |
# ─────────────────────────────── 군사(밀리터리) 전술 데이터셋 로드 ───────────────── | |
def load_military_dataset(): | |
""" | |
mil.parquet (index, scenario_description, attack_reasoning, defense_reasoning) | |
""" | |
path = os.path.join(os.path.dirname(__file__), "mil.parquet") | |
if not os.path.exists(path): | |
logging.warning("mil.parquet not found – military support disabled.") | |
return None | |
try: | |
df = pq.read_table(path).to_pandas() | |
return df | |
except Exception as e: | |
logging.error(f"Failed to read mil.parquet: {e}") | |
return None | |
MIL_DF = load_military_dataset() | |
def is_military_query(text: str) -> bool: | |
"""군사/전술 관련 키워드가 등장하면 True 반환""" | |
kw = [ | |
"군사", "전술", "전투", "전쟁", "작전", "무기", "병력", | |
"military", "tactic", "warfare", "battle", "operation" | |
] | |
return any(k.lower() in text.lower() for k in kw) | |
def military_search(query: str, top_k: int = 3): | |
""" | |
mil.parquet의 scenario_description 열과 코사인 유사도 분석하여 | |
query와 가장 유사한 상위 시나리오를 반환 | |
""" | |
if MIL_DF is None: | |
return [] | |
try: | |
corpus = MIL_DF["scenario_description"].tolist() | |
vec = TfidfVectorizer().fit_transform([query] + corpus) | |
sims = cosine_similarity(vec[0:1], vec[1:]).flatten() | |
top_idx = sims.argsort()[-top_k:][::-1] | |
return MIL_DF.iloc[top_idx][[ | |
"scenario_description", | |
"attack_reasoning", | |
"defense_reasoning" | |
]].to_dict("records") | |
except Exception as e: | |
logging.error(f"military_search error: {e}") | |
return [] | |
# ─────────────────────────────── Kaggle Datasets ──────────────────────── | |
KAGGLE_DATASETS = { | |
"general_business": { | |
"ref": "mohammadgharaei77/largest-2000-global-companies", | |
"title": "Largest 2000 Global Companies", | |
"subtitle": "Comprehensive data about the world's largest companies", | |
"url": "https://www.kaggle.com/datasets/mohammadgharaei77/largest-2000-global-companies", | |
"keywords": ["business", "company", "corporation", "enterprise", "global", "비즈니스", "기업", "회사", "글로벌", "기업가치"] | |
}, | |
"global_development": { | |
"ref": "michaelmatta0/global-development-indicators-2000-2020", | |
"title": "Global Development Indicators (2000-2020)", | |
"subtitle": "Economic and social indicators for countries worldwide", | |
"url": "https://www.kaggle.com/datasets/michaelmatta0/global-development-indicators-2000-2020", | |
"keywords": ["development", "economy", "global", "indicators", "social", "경제", "발전", "지표", "사회", "국가", "글로벌"] | |
}, | |
"startup_ideas": { | |
"ref": "rohitsahoo/100-startup-ideas", | |
"title": "Startup Idea Generator Dataset", | |
"subtitle": "A variety of startup ideas", | |
"url": "https://www.kaggle.com/datasets/rohitsahoo/100-startup-ideas", | |
"keywords": ["startup", "innovation", "business idea", "entrepreneurship", "스타트업", "창업", "혁신", "아이디어", "기업가"] | |
}, | |
"legal_terms": { | |
"ref": "gu05087/korean-legal-terms", | |
"title": "Korean Legal Terms", | |
"subtitle": "Database of Korean legal terminology", | |
"url": "https://www.kaggle.com/datasets/gu05087/korean-legal-terms", | |
"keywords": ["legal", "law", "terms", "korean", "legislation", "법률", "법적", "한국", "용어", "규제"] | |
}, | |
"billionaires": { | |
"ref": "vincentcampanaro/forbes-worlds-billionaires-list-2024", | |
"title": "Forbes World's Billionaires List 2024", | |
"subtitle": "Comprehensive data on the world's wealthiest individuals", | |
"url": "https://www.kaggle.com/datasets/vincentcampanaro/forbes-worlds-billionaires-list-2024", | |
"keywords": ["billionaire", "wealth", "rich", "forbes", "finance", "부자", "억만장자", "포브스", "부", "재테크"] | |
}, | |
"financial_news": { | |
"ref": "thedevastator/uncovering-financial-insights-with-the-reuters-2", | |
"title": "Reuters Financial News Insights", | |
"subtitle": "Financial news and market analysis from Reuters", | |
"url": "https://www.kaggle.com/datasets/thedevastator/uncovering-financial-insights-with-the-reuters-2", | |
"keywords": ["finance", "market", "stock", "investment", "news", "금융", "시장", "주식", "투자", "뉴스"] | |
}, | |
"ecommerce": { | |
"ref": "oleksiimartusiuk/80000-products-e-commerce-data-clean", | |
"title": "80,000 Products E-Commerce Data", | |
"subtitle": "Clean dataset of e-commerce products information", | |
"url": "https://www.kaggle.com/datasets/oleksiimartusiuk/80000-products-e-commerce-data-clean", | |
"keywords": ["ecommerce", "product", "retail", "shopping", "online", "이커머스", "제품", "소매", "쇼핑", "온라인"] | |
}, | |
"world_development_indicators": { | |
"ref": "georgejdinicola/world-bank-indicators", | |
"title": "World Development Indicators", | |
"subtitle": "Long-run socio-economic indicators for 200+ countries", | |
"url": "https://www.kaggle.com/datasets/georgejdinicola/world-bank-indicators", | |
"keywords": [ | |
"wdi", "macro", "economy", "gdp", "population", | |
"개발지표", "거시경제", "세계은행", "경제지표", "인구" | |
] | |
}, | |
"commodity_prices": { | |
"ref": "debashish311601/commodity-prices", | |
"title": "Commodity Prices (2000-2023)", | |
"subtitle": "Daily prices for crude oil, gold, grains, metals, etc.", | |
"url": "https://www.kaggle.com/datasets/debashish311601/commodity-prices", | |
"keywords": [ | |
"commodity", "oil", "gold", "raw material", "price", | |
"원자재", "유가", "금", "가격", "시장" | |
] | |
}, | |
"world_trade": { | |
"ref": "muhammadtalhaawan/world-export-and-import-dataset", | |
"title": "World Export & Import Dataset", | |
"subtitle": "34-year historical trade flows by country & product", | |
"url": "https://www.kaggle.com/datasets/muhammadtalhaawan/world-export-and-import-dataset", | |
"keywords": [ | |
"trade", "export", "import", "commerce", "flow", | |
"무역", "수출", "수입", "국제교역", "관세" | |
] | |
}, | |
"us_business_reports": { | |
"ref": "census/business-and-industry-reports", | |
"title": "US Business & Industry Reports", | |
"subtitle": "Key monthly economic indicators from the US Census Bureau", | |
"url": "https://www.kaggle.com/datasets/census/business-and-industry-reports", | |
"keywords": [ | |
"us", "economy", "retail sales", "construction", "manufacturing", | |
"미국", "경제지표", "소매판매", "산업생산", "건설" | |
] | |
}, | |
"us_industrial_production": { | |
"ref": "federalreserve/industrial-production-index", | |
"title": "Industrial Production Index (US)", | |
"subtitle": "Monthly Fed index for manufacturing, mining & utilities", | |
"url": "https://www.kaggle.com/datasets/federalreserve/industrial-production-index", | |
"keywords": [ | |
"industry", "production", "index", "fed", "us", | |
"산업생산", "제조업", "미국", "경기", "지수" | |
] | |
}, | |
"us_stock_market": { | |
"ref": "borismarjanovic/price-volume-data-for-all-us-stocks-etfs", | |
"title": "Huge Stock Market Dataset", | |
"subtitle": "Historical prices & volumes for all US stocks and ETFs", | |
"url": "https://www.kaggle.com/datasets/borismarjanovic/price-volume-data-for-all-us-stocks-etfs", | |
"keywords": [ | |
"stock", "market", "finance", "equity", "price", | |
"주식", "미국증시", "시세", "ETF", "데이터" | |
] | |
}, | |
"company_financials": { | |
"ref": "rish59/financial-statements-of-major-companies2009-2023", | |
"title": "Financial Statements of Major Companies (2009-2023)", | |
"subtitle": "15-year income sheet & balance sheet data for global firms", | |
"url": "https://www.kaggle.com/datasets/rish59/financial-statements-of-major-companies2009-2023", | |
"keywords": [ | |
"financials", "income", "balance sheet", "cashflow", | |
"재무제표", "매출", "수익성", "기업재무", "포트폴리오" | |
] | |
}, | |
"startup_investments": { | |
"ref": "justinas/startup-investments", | |
"title": "Crunchbase Startup Investments", | |
"subtitle": "Funding rounds & investor info for global startups", | |
"url": "https://www.kaggle.com/datasets/justinas/startup-investments", | |
"keywords": [ | |
"startup", "venture", "funding", "crunchbase", | |
"투자", "VC", "스타트업", "라운드", "신규진입" | |
] | |
}, | |
"global_energy": { | |
"ref": "atharvasoundankar/global-energy-consumption-2000-2024", | |
"title": "Global Energy Consumption (2000-2024)", | |
"subtitle": "Country-level energy usage by source & sector", | |
"url": "https://www.kaggle.com/datasets/atharvasoundankar/global-energy-consumption-2000-2024", | |
"keywords": [ | |
"energy", "consumption", "renewable", "oil", "utility", | |
"에너지", "소비", "재생에너지", "전력수요", "화석연료" | |
] | |
}, | |
"co2_emissions": { | |
"ref": "ulrikthygepedersen/co2-emissions-by-country", | |
"title": "CO₂ Emissions by Country", | |
"subtitle": "Annual CO₂ emissions & per-capita data since 1960s", | |
"url": "https://www.kaggle.com/datasets/ulrikthygepedersen/co2-emissions-by-country", | |
"keywords": [ | |
"co2", "emission", "climate", "environment", "carbon", | |
"탄소배출", "기후변화", "환경", "온실가스", "지속가능" | |
] | |
}, | |
"crop_climate": { | |
"ref": "thedevastator/the-relationship-between-crop-production-and-cli", | |
"title": "Crop Production & Climate Change", | |
"subtitle": "Yield & area stats for wheat, corn, rice, soybean vs climate", | |
"url": "https://www.kaggle.com/datasets/thedevastator/the-relationship-between-crop-production-and-cli", | |
"keywords": [ | |
"agriculture", "crop", "climate", "yield", "food", | |
"농업", "작물", "기후", "수확량", "식품" | |
] | |
}, | |
"esg_ratings": { | |
"ref": "alistairking/public-company-esg-ratings-dataset", | |
"title": "Public Company ESG Ratings", | |
"subtitle": "Environment, Social & Governance scores for listed firms", | |
"url": "https://www.kaggle.com/datasets/alistairking/public-company-esg-ratings-dataset", | |
"keywords": [ | |
"esg", "sustainability", "governance", "csr", | |
"환경", "사회", "지배구조", "지속가능", "평가" | |
] | |
}, | |
"global_health": { | |
"ref": "malaiarasugraj/global-health-statistics", | |
"title": "Global Health Statistics", | |
"subtitle": "Comprehensive health indicators & disease prevalence by country", | |
"url": "https://www.kaggle.com/datasets/malaiarasugraj/global-health-statistics", | |
"keywords": [ | |
"health", "disease", "life expectancy", "WHO", | |
"보건", "질병", "기대수명", "의료", "공중보건" | |
] | |
}, | |
"housing_market": { | |
"ref": "atharvasoundankar/global-housing-market-analysis-2015-2024", | |
"title": "Global Housing Market Analysis (2015-2024)", | |
"subtitle": "House price index, mortgage rates, rent data by country", | |
"url": "https://www.kaggle.com/datasets/atharvasoundankar/global-housing-market-analysis-2015-2024", | |
"keywords": [ | |
"housing", "real estate", "price index", "mortgage", | |
"부동산", "주택가격", "임대료", "시장", "금리" | |
] | |
}, | |
"pharma_sales": { | |
"ref": "milanzdravkovic/pharma-sales-data", | |
"title": "Pharma Sales Data (2014-2019)", | |
"subtitle": "600k sales records across 8 ATC drug categories", | |
"url": "https://www.kaggle.com/datasets/milanzdravkovic/pharma-sales-data", | |
"keywords": [ | |
"pharma", "sales", "drug", "healthcare", "medicine", | |
"제약", "의약품", "매출", "헬스케어", "시장" | |
] | |
}, | |
"ev_sales": { | |
"ref": "muhammadehsan000/global-electric-vehicle-sales-data-2010-2024", | |
"title": "Global EV Sales Data (2010-2024)", | |
"subtitle": "Electric vehicle unit sales by region & model year", | |
"url": "https://www.kaggle.com/datasets/muhammadehsan000/global-electric-vehicle-sales-data-2010-2024", | |
"keywords": [ | |
"ev", "electric vehicle", "automotive", "mobility", | |
"전기차", "판매량", "자동차산업", "친환경모빌리티", "시장성장" | |
] | |
}, | |
"hr_attrition": { | |
"ref": "pavansubhasht/ibm-hr-analytics-attrition-dataset", | |
"title": "IBM HR Analytics: Attrition & Performance", | |
"subtitle": "Employee demographics, satisfaction & attrition flags", | |
"url": "https://www.kaggle.com/datasets/pavansubhasht/ibm-hr-analytics-attrition-dataset", | |
"keywords": [ | |
"hr", "attrition", "employee", "people analytics", | |
"인사", "이직률", "직원", "HR분석", "조직관리" | |
] | |
}, | |
"employee_satisfaction": { | |
"ref": "redpen12/employees-satisfaction-analysis", | |
"title": "Employee Satisfaction Survey Data", | |
"subtitle": "Department-level survey scores on satisfaction & engagement", | |
"url": "https://www.kaggle.com/datasets/redpen12/employees-satisfaction-analysis", | |
"keywords": [ | |
"satisfaction", "engagement", "survey", "workplace", | |
"직원만족도", "조직문화", "설문", "근무환경", "HR" | |
] | |
}, | |
"world_bank_indicators": { | |
"ref": "georgejdinicola/world-bank-indicators", | |
"title": "World Bank Indicators by Topic (1960-Present)", | |
"subtitle": "Macro-economic, 사회·인구 통계 등 200+개국 장기 시계열 지표", | |
"url": "https://www.kaggle.com/datasets/georgejdinicola/world-bank-indicators", | |
"keywords": ["world bank", "development", "economy", "global", "indicator", "세계은행", "경제", "지표", "개발", "거시"] | |
}, | |
"physical_chem_properties": { | |
"ref": "ivanyakovlevg/physical-and-chemical-properties-of-substances", | |
"title": "Physical & Chemical Properties of Substances", | |
"subtitle": "8만여 화합물의 물리·화학 특성 및 분류 정보", | |
"url": "https://www.kaggle.com/datasets/ivanyakovlevg/physical-and-chemical-properties-of-substances", | |
"keywords": ["chemistry", "materials", "property", "substance", "화학", "물성", "소재", "데이터", "R&D"] | |
}, | |
"global_weather_repository": { | |
"ref": "nelgiriyewithana/global-weather-repository", | |
"title": "Global Weather Repository", | |
"subtitle": "전 세계 기상 관측치(기온·강수·풍속 등) 일별 업데이트", | |
"url": "https://www.kaggle.com/datasets/nelgiriyewithana/global-weather-repository", | |
"keywords": ["weather", "climate", "meteorology", "global", "forecast", "기상", "날씨", "기후", "관측", "환경"] | |
}, | |
"amazon_best_seller_softwares": { | |
"ref": "kaverappa/amazon-best-seller-softwares", | |
"title": "Amazon Best Seller – Software Category", | |
"subtitle": "아마존 소프트웨어 베스트셀러 순위 및 리뷰 데이터", | |
"url": "https://www.kaggle.com/datasets/kaverappa/amazon-best-seller-softwares", | |
"keywords": ["amazon", "e-commerce", "software", "review", "ranking", "아마존", "이커머스", "소프트웨어", "베스트셀러", "리뷰"] | |
}, | |
"world_stock_prices": { | |
"ref": "nelgiriyewithana/world-stock-prices-daily-updating", | |
"title": "World Stock Prices (Daily Updating)", | |
"subtitle": "30,000여 글로벌 상장사의 일간 주가·시총·섹터 정보 실시간 갱신", | |
"url": "https://www.kaggle.com/datasets/nelgiriyewithana/world-stock-prices-daily-updating", | |
"keywords": ["stock", "finance", "market", "equity", "price", "글로벌", "주가", "금융", "시장", "투자"] | |
} | |
} | |
SUN_TZU_STRATEGIES = [ | |
{"계": "만천과해", "요약": "평범한 척, 몰래 진행", "조건": "상대가 지켜보고 있을 때", "행동": "루틴·평온함 과시", "목적": "경계 무력화", "예시": "규제기관 눈치 보는 신사업 파일럿"}, | |
{"계": "위위구조", "요약": "뒤통수 치면 포위 풀린다", "조건": "우리 측이 압박받을 때", "행동": "적 본진 급습", "목적": "압박 해소", "예시": "경쟁사 핵심 고객 뺏기"}, | |
{"계": "차도살인", "요약": "내 손 더럽히지 마", "조건": "직접 공격 부담", "행동": "제3자 활용", "목적": "책임 전가", "예시": "언론을 통한 경쟁사 비판"}, | |
{"계": "이일대우", "요약": "우리가 쉬면 적이 지친다", "조건": "상대가 과로 중", "행동": "버티며 체력 보존", "목적": "역전 타이밍 확보", "예시": "협상 지연 후 헐값 인수"}, | |
{"계": "진화타겁", "요약": "불날 때 주워 담기", "조건": "시장 혼란·위기", "행동": "저가 매수", "목적": "저비용 고이익", "예시": "금융위기 때 우량자산 매입"}, | |
{"계": "성동격서", "요약": "소음은 왼쪽, 공격은 오른쪽", "조건": "정면 방어 견고", "행동": "가짜 신호 → 우회", "목적": "방어 분산", "예시": "신제품 A 홍보, 실제는 B 확장"}, | |
{"계": "무중생유", "요약": "없는 것도 있는 척", "조건": "자원 부족", "행동": "허세·연막", "목적": "상대 혼란", "예시": "스타트업 과장 로드맵"}, | |
{"계": "암도진창", "요약": "뒷문으로 돌아가라", "조건": "우회로 존재", "행동": "비밀 루트 침투", "목적": "허를 찌름", "예시": "관세 피해 제3국 생산"}, | |
{"계": "격안관화", "요약": "남 싸움 구경", "조건": "두 경쟁자 충돌", "행동": "관망", "목적": "둘 다 소모", "예시": "플랫폼 전쟁 중 중립 유지"}, | |
{"계": "소리장도", "요약": "웃으며 칼 숨기기", "조건": "친밀 분위기", "행동": "우호 제스처 후 기습", "목적": "경계 붕괴", "예시": "합작 후 핵심 기술 탈취"}, | |
{"계": "이대도강", "요약": "덜 중요한 걸 내줘라", "조건": "뭔가 잃었을 때", "행동": "부속 희생", "목적": "핵심 보호", "예시": "제품 라인 하나 단종"}, | |
{"계": "순수견양", "요약": "방치된 것 챙기기", "조건": "경계 허술", "행동": "자연스럽게 수집", "목적": "무혈 이득", "예시": "공공 API 데이터 긁기"}, | |
{"계": "타초경사", "요약": "풀 쳐서 뱀 나온다", "조건": "적이 숨을 때", "행동": "일부러 소란", "목적": "위치 노출", "예시": "이사회 반대파 의중 파악"}, | |
{"계": "차시환혼", "요약": "죽은 카드 재활용", "조건": "폐기 자원", "행동": "리브랜딩", "목적": "새 전력 확보", "예시": "실패 앱 재출시"}, | |
{"계": "조호이산", "요약": "호랑이 산 밖으로", "조건": "강적 거점", "행동": "유인 이동", "목적": "빈집 공략", "예시": "경쟁 VC 행사 유도 후 딜 선점"}, | |
{"계": "욕금고종", "요약": "잡으려면 놓아줘라", "조건": "인재·적 포획", "행동": "일부러 풀어줌", "목적": "저항 약화", "예시": "핵심 인재 재계약 유도"}, | |
{"계": "포전인옥", "요약": "벽돌 던져 옥 얻기", "조건": "큰 보상 필요", "행동": "작은 미끼", "목적": "참여 유도", "예시": "무료 → 유료 전환"}, | |
{"계": "금적금왕", "요약": "도둑 잡으려면 두목부터", "조건": "조직 복잡", "행동": "수뇌 공격", "목적": "조직 붕괴", "예시": "최대 주주 지분 매입"}, | |
{"계": "부저이지", "요약": "가마 밑 불 끄기", "조건": "적 의존성 존재", "행동": "보급 차단", "목적": "전력 급감", "예시": "핵심 공급업체 선점"}, | |
{"계": "혼수모어", "요약": "물 흐려 놓고 낚시", "조건": "판세 불투명", "행동": "혼탁 유지", "목적": "어부지리", "예시": "입법 지연 로비"}, | |
{"계": "금선탈각", "요약": "허물 벗고 도망", "조건": "추적 심함", "행동": "외피만 남김", "목적": "추적 무효", "예시": "부실 자회사 떼어내기"}, | |
{"계": "관문잡적", "요약": "문 닫고 잡아라", "조건": "퇴로 예측", "행동": "출구 봉쇄", "목적": "완전 포획", "예시": "락업 조항으로 지분 매집"}, | |
{"계": "원교근공", "요약": "먼 데와 친해지고 가까운 데 친다", "조건": "다국 간 경쟁", "행동": "원거리 동맹", "목적": "단계적 확장", "예시": "원거리 FTA 체결 후 인근 M&A"}, | |
{"계": "가도벌괵", "요약": "길 빌려 공격", "조건": "중간 세력 장벽", "행동": "통로 명분 → 제압", "목적": "장애 제거", "예시": "총판 빌미 시장 진입"}, | |
{"계": "투량환주", "요약": "들보 몰래 바꿔치기", "조건": "감시 존재", "행동": "내부 교체", "목적": "인식 왜곡", "예시": "백엔드 갈아끼우기"}, | |
{"계": "지상매괴", "요약": "뽕나무 가리켜 회초리 욕", "조건": "직접 비판 곤란", "행동": "제3자 지적", "목적": "메시지 전달", "예시": "싱크탱크 보고서 압박"}, | |
{"계": "가치불전", "요약": "바보 연기", "조건": "상대 의심 많음", "행동": "일부러 허술", "목적": "방심 유도", "예시": "저평가 가이던스"}, | |
{"계": "상옥추제", "요약": "사다리 걷어차기", "조건": "길 열어준 뒤", "행동": "퇴로 차단", "목적": "고립", "예시": "투자자 초청 후 정보 차단"}, | |
{"계": "수상개화", "요약": "나무에 꽃 핀 척", "조건": "실력 부족", "행동": "외형 부풀림", "목적": "영향력 확대", "예시": "MOU ·공동 로고 홍보"}, | |
{"계": "반객위주", "요약": "손님에서 주인으로", "조건": "부차적 위치", "행동": "주도권 장악", "목적": "역전 지휘", "예시": "플랫폼 입점사 자체 마켓"}, | |
{"계": "미인계", "요약": "매력으로 판단 흐리기", "조건": "유혹 가능", "행동": "감정·매력 활용", "목적": "결정 왜곡", "예시": "지역 투자로 정치인 호감 얻기"}, | |
{"계": "공성계", "요약": "텅 빈 성문 열어놓기", "조건": "병력 부족", "행동": "과감히 공개", "목적": "상대 의심", "예시": "내부자료 전면 공개"}, | |
{"계": "반간계", "요약": "가짜 스파이 역이용", "조건": "내부 불신 요소", "행동": "교란 정보", "목적": "분열", "예시": "경쟁사에 가짜 루머"}, | |
{"계": "고육계", "요약": "살 내주고 뼈 취하기", "조건": "신뢰 상실", "행동": "스스로 손실", "목적": "진정성 증명", "예시": "CEO 보너스 반납"}, | |
{"계": "연환계", "요약": "사슬로 한꺼번에", "조건": "복수 대상 다수", "행동": "연결 묶기", "목적": "효율 타격", "예시": "패키지 제재안"}, | |
{"계": "주위상계", "요약": "도망이 상책", "조건": "승산 없음", "행동": "즉시 후퇴", "목적": "손실 최소·재기", "예시": "적자 시장 철수"} | |
] | |
physical_transformation_categories = { | |
"센서 기능": [ | |
"시각 센서", "시각 감지", "청각 센서", "청각 감지", "촉각 센서", "촉각 감지", | |
"미각 센서", "미각 감지", "후각 센서", "후각 감지", "온도 센서", "온도 감지", | |
"습도 센서", "습도 감지", "압력 센서", "압력 감지", "가속도 센서", "가속도 감지", | |
"회전 센서", "회전 감지", "근접 센서", "근접 감지", "위치 센서", "위치 감지", | |
"운동 센서", "운동 감지", "가스 센서", "가스 감지", "적외선 센서", "적외선 감지", | |
"자외선 센서", "자외선 감지", "방사선 센서", "방사선 감지", "자기장 센서", "자기장 감지", | |
"전기장 센서", "전기장 감지", "화학물질 센서", "화학물질 감지", "생체신호 센서", "생체신호 감지", | |
"진동 센서", "진동 감지", "소음 센서", "소음 감지", "빛 세기 센서", "빛 세기 감지", | |
"빛 파장 센서", "빛 파장 감지", "기울기 센서", "기울기 감지", "pH 센서", "pH 감지", | |
"전류 센서", "전류 감지", "전압 센서", "전압 감지", "이미지 센서", "이미지 감지", | |
"거리 센서", "거리 감지", "깊이 센서", "깊이 감지", "중력 센서", "중력 감지", | |
"속도 센서", "속도 감지", "흐름 센서", "흐름 감지", "수위 센서", "수위 감지", | |
"탁도 센서", "탁도 감지", "염도 센서", "염도 감지", "금속 감지", "압전 센서", | |
"압전 감지", "광전 센서", "광전 감지", "열전대 센서", "열전대 감지", "홀 효과 센서", | |
"홀 효과 감지", "초음파 센서", "초음파 감지", "레이더 센서", "레이더 감지", | |
"라이다 센서", "라이다 감지", "터치 센서", "터치 감지", "제스처 센서", "제스처 감지", | |
"심박 센서", "심박 감지", "혈압 센서", "혈압 감지" | |
], | |
"크기와 형태 변화": [ | |
"부피 늘어남", "부피 줄어듦", "길이 늘어남", "길이 줄어듦", "너비 늘어남", "너비 줄어남", | |
"높이 늘어남", "높이 줄어듦", "밀도 변화", "무게 증가", "무게 감소", "모양 변형", | |
"상태 변화", "불균등 변형", "복잡한 형태 변형", "비틀림", "꼬임", "불균일한 확장", | |
"불균일한 축소", "모서리 둥글게", "모서리 날카롭게", "깨짐", "갈라짐", "여러 조각 나눠짐", | |
"물 저항", "먼지 저항", "찌그러짐", "복원", "접힘", "펼쳐짐", "압착", "팽창", | |
"늘어남", "수축", "구겨짐", "평평해짐", "뭉개짐", "단단해짐", "말림", "펴짐", | |
"꺾임", "구부러짐" | |
], | |
"표면 및 외관 변화": [ | |
"색상 변화", "질감 변화", "투명 변화", "불투명 변화", "반짝임 변화", "무광 변화", | |
"빛 반사 정도 변화", "무늬 변화", "각도에 따른 색상 변화", "빛에 따른 색상 변화", | |
"온도에 따른 색상 변화", "홀로그램 효과", "표면 각도별 빛 반사", "표면 모양 변형", | |
"초미세 표면 구조 변화", "자가 세정 효과", "얼룩 생성", "패턴 생성", "흐림 변화", | |
"선명함 변화", "광택 변화", "윤기 변화", "색조 변화", "채도 변화", "발광", | |
"형광", "빛 산란 효과", "빛 흡수 변화", "반투명 효과", "그림자 효과 변화", | |
"자외선 반응 변화", "야광 효과" | |
], | |
"물질의 상태 변화": [ | |
"고체 전환", "액체 전환", "기체 전환", "결정화", "용해", "산화", "부식", | |
"딱딱해짐", "부드러워짐", "특수 상태 전환", "무정형 전환", "결정형 전환", "성분 분리", | |
"미세 입자 형성", "미세 입자 분해", "젤 형성", "젤 풀어짐", "준안정 상태 변화", | |
"분자 자가 정렬", "분자 자가 분해", "상태변화 지연 현상", "녹음", "굳음", | |
"증발", "응축", "승화", "증착", "침전", "부유", "분산", "응집", | |
"건조", "습윤", "팽윤", "수축", "동결", "해동", "풍화", "침식", | |
"충전", "방전", "결합", "분리", "발효", "부패" | |
], | |
"움직임 특성 변화": [ | |
"가속", "감속", "일정 속도 유지", "진동", "진동 감소", "부딪힘", "튕김", | |
"회전 속도 증가", "회전 속도 감소", "회전 방향 변화", "불규칙 움직임", "멈췄다", "미끄러지는 현상", | |
"공진", "반공진", "유체 속 저항 변화", "유체 속 양력 변화", "움직임 저항 변화", | |
"복합 진동 움직임", "특수 유체 속 움직임", "회전-이동 연계 움직임", "관성 정지", | |
"충격 흡수", "충격 전달", "운동량 보존", "마찰력 변화", "관성 탈출", "불안정 균형", | |
"동적 안정성", "흔들림 감쇠", "경로 예측성", "회피 움직임" | |
], | |
"구조적 변화": [ | |
"부품 추가", "부품 제거", "조립", "분해", "접기", "펴기", "변형", "원상복구", | |
"최적 구조 변화", "자가 재배열", "자연 패턴 형성", "자연 패턴 소멸", "규칙적 패턴 변화", | |
"모듈식 변형", "복잡성 증가 구조", "원래 모양 기억 효과", "시간에 따른 형태 변화", | |
"부분 제거", "부분 교체", "결합", "분리", "분할", "통합", "중첩", "겹침", | |
"내부 구조 변화", "외부 구조 변화", "중심축 이동", "균형점 변화", "계층 구조 변화", | |
"지지 구조 변화", "응력 분산 구조", "충격 흡수 구조", "그리드 구조 변화", "매트릭스 구조 변화", | |
"상호 연결성 변화" | |
], | |
"공간 이동": [ | |
"앞 이동", "뒤 이동", "좌 이동", "우 이동", "위 이동", "아래 이동", | |
"세로축 회전(고개 끄덕임)", "가로축 회전(고개 젓기)", "길이축 회전(옆으로 기울임)", "원 운동", | |
"나선형 이동", "관성에 의한 미끄러짐", "회전축 변화", "불규칙 회전", "흔들림 운동", | |
"포물선 이동", "무중력 부유", "수면 위 부유", "점프", "도약", "슬라이딩", "롤링", | |
"자유 낙하", "왕복 운동", "탄성 튕김", "관통", "회피 움직임", "지그재그 이동", "스윙 운동" | |
], | |
"시간 관련 변화": [ | |
"노화", "풍화", "마모", "부식", "색 바램", "변색", "손상", "회복", | |
"수명 주기 변화", "사용자 상호작용에 따른 적응", "학습 기반 형태 최적화", "시간에 따른 물성 변화", | |
"집단 기억 효과", "문화적 의미 변화", "지연 반응", "이전 상태 의존 변화", "점진적 시간 변화", | |
"진화적 변화", "주기적 재생", "계절 변화 적응", "생체리듬 변화", "생애 주기 단계", | |
"성장", "퇴화", "자가 복구", "자가 재생", "자연 순환 적응", "지속성", "일시성", | |
"기억 효과", "지연된 작용", "누적 효과" | |
], | |
"빛과 시각 효과": [ | |
"발광", "소등", "빛 투과", "빛 차단", "빛 산란", "빛 집중", "색상 스펙트럼 변화", | |
"빛 회절", "빛 간섭", "홀로그램 생성", "레이저 효과", "빛 편광", "형광", "인광", | |
"자외선 발광", "적외선 발광", "광학적 착시", "빛 굴절", "그림자 생성", "그림자 제거", | |
"색수차 효과", "무지개 효과", "글로우 효과", "플래시 효과", "조명 패턴", "빔 효과", | |
"광 필터 효과", "빛의 방향성 변화", "투영 효과", "빛 감지", "빛 반응", "광도 변화" | |
], | |
"소리와 진동 효과": [ | |
"소리 발생", "소리 소멸", "음 높낮이 변화", "음량 변화", "음색 변화", "공명", | |
"반공명", "음향 진동", "초음파 발생", "저음파 발생", "소리 집중", "소리 분산", | |
"음향 반사", "음향 흡수", "음향 도플러 효과", "음파 간섭", "음향 공진", "진동 패턴 변화", | |
"타악 효과", "음향 피드백", "음향 차폐", "음향 증폭", "소리 지향성", "소리 왜곡", | |
"비트 생성", "배음 생성", "주파수 변조", "음향 충격파", "음향 필터링" | |
], | |
"열 관련 변화": [ | |
"온도 상승", "온도 하강", "열 팽창", "열 수축", "열 전달", "열 차단", "압력 상승", | |
"압력 하강", "열 변화에 따른 자화", "엔트로피 변화", "열전기 효과", "자기장에 의한 열 변화", | |
"상태 변화 중 열 저장", "상태 변화 중 열 방출", "열 스트레스 발생", "열 스트레스 해소", | |
"급격한 온도 변화 영향", "복사 냉각", "복사 가열", "발열", "흡열", "열 분포 변화", | |
"열 반사", "열 흡수", "냉각 응축", "열 활성화", "열 변색", "열 팽창 계수 변화", | |
"열 안정성 변화", "내열성", "내한성", "자가 발열", "열적 평형", "열적 불균형", | |
"열적 변형", "열 분산", "열 집중" | |
], | |
"전기 및 자기 변화": [ | |
"자성 생성", "자성 소멸", "전하량 증가", "전하량 감소", "전기장 생성", "전기장 소멸", | |
"자기장 생성", "자기장 소멸", "초전도 상태 전환", "강유전체 특성 변화", "양자 상태 변화", | |
"플라즈마 형성", "플라즈마 소멸", "스핀파 전달", "빛에 의한 전기 발생", "압력에 의한 전기 발생", | |
"자기장 내 전류 변화", "전기 저항 변화", "전기 전도성 변화", "정전기 발생", "정전기 방전", | |
"전자기 유도", "전자기파 방출", "전자기파 흡수", "전기 용량 변화", "자기 이력 현상", | |
"전기적 분극", "전자 흐름 방향 변화", "전기적 공명", "전기적 차폐", "전기적 노출", | |
"자기 차폐", "자기 노출", "자기장 정렬" | |
], | |
"화학적 변화": [ | |
"표면 코팅 변화", "물질 성분 변화", "화학 반응 변화", "촉매 작용 시작/중단", | |
"빛에 의한 화학 반응", "전기에 의한 화학 반응", "단분자막 형성", "분자 수준 구조 변화", | |
"생체 모방 표면 변화", "환경 반응형 물질 변화", "주기적 화학 반응", "산화", "환원", | |
"고분자화", "물 분해", "화합", "방사선 영향", "산-염기 반응", "중화 반응", | |
"이온화", "화학적 흡착/탈착", "촉매 효율 변화", "효소 활성 변화", "발색 반응", | |
"pH 변화", "화학적 평형 이동", "결합 형성/분해", "용해도 변화" | |
], | |
"생물학적 변화": [ | |
"성장/위축", "세포 분열/사멸", "생물 발광", "신진대사 변화", "면역 반응", | |
"호르몬 분비", "신경 반응", "유전적 발현", "적응/진화", "생체리듬 변화", | |
"재생/치유", "노화/성숙", "생체 모방 변화", "바이오필름 형성", "생물학적 분해", | |
"효소 활성화/비활성화", "생물학적 신호 전달", "스트레스 반응", "체온 조절", "생물학적 시계 변화", | |
"세포외 기질 변화", "생체 역학적 반응", "세포 운동성", "세포 극성 변화", "영양 상태 변화" | |
], | |
"환경 상호작용": [ | |
"온도 반응", "습도 반응", "기압 반응", "중력 반응", "자기장 반응", | |
"빛 반응", "소리 반응", "화학 물질 감지", "기계적 자극 감지", "전기 자극 반응", | |
"방사선 반응", "진동 감지", "pH 반응", "용매 반응", "기체 교환", | |
"환경 오염 반응", "날씨 반응", "계절 반응", "일주기 반응", "생태계 상호작용", | |
"공생/경쟁 반응", "포식/피식 관계", "군집 형성", "영역 설정", "이주 패턴", "정착 패턴" | |
], | |
"비즈니스 아이디어": [ | |
"시장 재정의/신규 시장 개척", | |
"비즈니스 모델 혁신/디지털 전환", | |
"고객 경험 혁신/서비스 혁신", | |
"협력 및 파트너십 강화/생태계 구축", | |
"글로벌 확장/지역화 전략", | |
"운영 효율성 증대/원가 절감", | |
"브랜드 리포지셔닝/이미지 전환", | |
"지속 가능한 성장/사회적 가치 창출", | |
"데이터 기반 의사결정/AI 도입", | |
"신기술 융합/혁신 투자" | |
] | |
} | |
physical_transformation_categories_en = {} # (영문 카테고리는 사용하지 않아도 되므로 비워둠) | |
SWOT_FRAMEWORK = { | |
"strengths": { | |
"title": "강점 (Strengths)", | |
"description": "내부적 긍정 요소 - 조직이 가진 경쟁 우위 요소", | |
"prompt_keywords": ["강점", "장점", "우위", "역량", "자산", "전문성", "strength", "advantage"] | |
}, | |
"weaknesses": { | |
"title": "약점 (Weaknesses)", | |
"description": "내부적 부정 요소 - 개선이 필요한 내부 한계", | |
"prompt_keywords": ["약점", "단점", "부족", "한계", "취약점", "weakness", "limitation", "deficit"] | |
}, | |
"opportunities": { | |
"title": "기회 (Opportunities)", | |
"description": "외부적 긍정 요소 - 활용 가능한 외부 환경 변화", | |
"prompt_keywords": ["기회", "가능성", "트렌드", "변화", "성장", "opportunity", "trend", "potential"] | |
}, | |
"threats": { | |
"title": "위협 (Threats)", | |
"description": "외부적 부정 요소 - 대응이 필요한 외부 위험 요소", | |
"prompt_keywords": ["위협", "리스크", "경쟁", "위험", "장벽", "threat", "risk", "competition", "barrier"] | |
} | |
} | |
PORTER_FRAMEWORK = { | |
"rivalry": { | |
"title": "기존 경쟁자 간의 경쟁", | |
"description": "동일 산업 내 경쟁 강도 분석", | |
"prompt_keywords": ["경쟁", "경쟁사", "시장점유율", "가격경쟁", "competition", "rival", "market share"] | |
}, | |
"new_entrants": { | |
"title": "신규 진입자의 위협", | |
"description": "새로운 기업의 시장 진입 난이도 분석", | |
"prompt_keywords": ["진입장벽", "신규", "스타트업", "entry barrier", "newcomer", "startup"] | |
}, | |
"substitutes": { | |
"title": "대체재의 위협", | |
"description": "대체 가능한 제품/서비스의 위협 분석", | |
"prompt_keywords": ["대체재", "대안", "substitute", "alternative", "replacement"] | |
}, | |
"buyer_power": { | |
"title": "구매자의 교섭력", | |
"description": "고객의 가격 협상력 분석", | |
"prompt_keywords": ["고객", "구매자", "가격민감도", "협상력", "customer", "buyer power"] | |
}, | |
"supplier_power": { | |
"title": "공급자의 교섭력", | |
"description": "공급업체의 가격/조건 협상력 분석", | |
"prompt_keywords": ["공급자", "벤더", "원재료", "supplier", "vendor", "raw material"] | |
} | |
} | |
BCG_FRAMEWORK = { | |
"stars": { | |
"title": "스타 (Stars)", | |
"description": "높은 성장률, 높은 시장점유율 - 추가 투자 필요", | |
"prompt_keywords": ["성장", "점유율", "중점", "투자", "star", "growth", "investment"] | |
}, | |
"cash_cows": { | |
"title": "현금젖소 (Cash Cows)", | |
"description": "낮은 성장률, 높은 시장점유율 - 현금흐름 창출", | |
"prompt_keywords": ["안정", "수익", "현금", "전통", "cash cow", "profit", "mature"] | |
}, | |
"question_marks": { | |
"title": "물음표 (Question Marks)", | |
"description": "높은 성장률, 낮은 시장점유율 - 선택적 투자/철수", | |
"prompt_keywords": ["가능성", "위험", "불확실", "잠재", "question mark", "uncertain", "potential"] | |
}, | |
"dogs": { | |
"title": "개 (Dogs)", | |
"description": "낮은 성장률, 낮은 시장점유율 - 철수 고려", | |
"prompt_keywords": ["회수", "철수", "저성장", "비효율", "dog", "divest", "low growth"] | |
} | |
} | |
BUSINESS_FRAMEWORKS = { | |
"sunzi": "손자병법 36계", | |
"swot": "SWOT 분석", | |
"porter": "Porter의 5 Forces", | |
"bcg": "BCG 매트릭스" | |
} | |
class Category: | |
"""통일된 카테고리 및 항목 구조""" | |
name_ko: str | |
name_en: str | |
tags: list[str] | |
items: list[str] | |
# ──────────────────────────────── 프레임워크 분석 함수들 ───────────────────────── | |
def analyze_with_swot(prompt: str) -> dict: | |
prompt_lower = prompt.lower() | |
results = {} | |
for category, info in SWOT_FRAMEWORK.items(): | |
score = sum(1 for keyword in info["prompt_keywords"] if keyword.lower() in prompt_lower) | |
keywords = [] | |
for keyword in info["prompt_keywords"]: | |
if keyword.lower() in prompt_lower: | |
pattern = f".{{0,15}}{keyword}.{{0,15}}" | |
matches = re.findall(pattern, prompt_lower, re.IGNORECASE) | |
for match in matches[:2]: | |
keywords.append(match.strip()) | |
results[category] = { | |
"title": info["title"], | |
"description": info["description"], | |
"score": score, | |
"keywords": keywords[:5] | |
} | |
return results | |
def analyze_with_porter(prompt: str) -> dict: | |
prompt_lower = prompt.lower() | |
results = {} | |
for category, info in PORTER_FRAMEWORK.items(): | |
score = sum(1 for keyword in info["prompt_keywords"] if keyword.lower() in prompt_lower) | |
keywords = [] | |
for keyword in info["prompt_keywords"]: | |
if keyword.lower() in prompt_lower: | |
pattern = f".{{0,15}}{keyword}.{{0,15}}" | |
matches = re.findall(pattern, prompt_lower, re.IGNORECASE) | |
for match in matches[:2]: | |
keywords.append(match.strip()) | |
results[category] = { | |
"title": info["title"], | |
"description": info["description"], | |
"score": score, | |
"keywords": keywords[:5] | |
} | |
return results | |
def analyze_with_bcg(prompt: str) -> dict: | |
prompt_lower = prompt.lower() | |
results = {} | |
for category, info in BCG_FRAMEWORK.items(): | |
score = sum(1 for keyword in info["prompt_keywords"] if keyword.lower() in prompt_lower) | |
keywords = [] | |
for keyword in info["prompt_keywords"]: | |
if keyword.lower() in prompt_lower: | |
pattern = f".{{0,15}}{keyword}.{{0,15}}" | |
matches = re.findall(pattern, prompt_lower, re.IGNORECASE) | |
for match in matches[:2]: | |
keywords.append(match.strip()) | |
results[category] = { | |
"title": info["title"], | |
"description": info["description"], | |
"score": score, | |
"keywords": keywords[:5] | |
} | |
return results | |
def format_business_framework_analysis(framework_type: str, analysis_result: dict) -> str: | |
if not analysis_result: | |
return "" | |
titles = { | |
'swot': '# SWOT 분석 결과', | |
'porter': '# Porter의 5 Forces 분석 결과', | |
'bcg': '# BCG 매트릭스 분석 결과' | |
} | |
md = f"{titles.get(framework_type, '# 경영 프레임워크 분석')}\n\n" | |
md += "각 요소별 텍스트 분석 점수와 관련 키워드입니다.\n\n" | |
for category, info in analysis_result.items(): | |
md += f"## {info['title']}\n\n" | |
md += f"{info['description']}\n\n" | |
md += f"**관련성 점수**: {info['score']}\n\n" | |
if info['keywords']: | |
md += "**관련 키워드 및 컨텍스트**:\n" | |
for keyword in info['keywords']: | |
md += f"- *{keyword}*\n" | |
md += "\n" | |
else: | |
md += "관련 키워드가 발견되지 않았습니다.\n\n" | |
return md | |
# ──────────────────────────────── 마크다운 → HTML 변환 ───────────────────────── | |
def md_to_html(md_text: str, title: str = "Output") -> str: | |
html_content = markdown.markdown( | |
md_text, | |
extensions=['tables', 'fenced_code', 'codehilite'] | |
) | |
return f"""<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<title>{title}</title> | |
<style> | |
body {{ | |
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; | |
line-height: 1.6; | |
color: #333; | |
max-width: 800px; | |
margin: 0 auto; | |
padding: 20px; | |
}} | |
h1, h2, h3, h4, h5, h6 {{ | |
margin-top: 24px; | |
margin-bottom: 16px; | |
font-weight: 600; | |
line-height: 1.25; | |
}} | |
h1 {{ font-size: 2em; color: #0366d6; }} | |
h2 {{ font-size: 1.5em; color: #0366d6; border-bottom: 1px solid #eaecef; padding-bottom: .3em; }} | |
h3 {{ font-size: 1.25em; color: #0366d6; }} | |
p, ul, ol {{ margin-bottom: 16px; }} | |
a {{ color: #0366d6; text-decoration: none; }} | |
a:hover {{ text-decoration: underline; }} | |
code {{ | |
font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, monospace; | |
background-color: rgba(27, 31, 35, 0.05); | |
border-radius: 3px; | |
font-size: 85%; | |
padding: 0.2em 0.4em; | |
}} | |
pre {{ | |
background-color: #f6f8fa; | |
border-radius: 3px; | |
font-size: 85%; | |
line-height: 1.45; | |
overflow: auto; | |
padding: 16px; | |
}} | |
pre code {{ | |
background-color: transparent; | |
padding: 0; | |
}} | |
blockquote {{ | |
border-left: 4px solid #dfe2e5; | |
color: #6a737d; | |
margin: 0; | |
padding: 0 1em; | |
}} | |
table {{ | |
border-collapse: collapse; | |
width: 100%; | |
margin-bottom: 16px; | |
}} | |
table th, table td {{ | |
border: 1px solid #dfe2e5; | |
padding: 6px 13px; | |
}} | |
table th {{ | |
background-color: #f6f8fa; | |
font-weight: 600; | |
}} | |
img {{ | |
max-width: 100%; | |
height: auto; | |
}} | |
hr {{ | |
border: 0; | |
height: 1px; | |
background-color: #dfe2e5; | |
margin: 24px 0; | |
}} | |
</style> | |
</head> | |
<body> | |
{html_content} | |
<hr> | |
<footer> | |
<p><small>Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} | | |
Created by <a href="https://discord.gg/openfreeai" target="_blank">VIDraft</a> | |
</small></p> | |
</footer> | |
</body> | |
</html> | |
""" | |
# ──────────────────────────────── 업로드 파일 처리 함수 ───────────────────── | |
def process_text_file(uploaded_file): | |
try: | |
content = uploaded_file.read().decode('utf-8') | |
return f"""# 업로드된 텍스트 파일: {uploaded_file.name} | |
{content} | |
""" | |
except Exception as e: | |
logging.error(f"텍스트 파일 처리 오류: {str(e)}") | |
return f"**Error processing {uploaded_file.name}**: {str(e)}" | |
def process_csv_file(uploaded_file): | |
try: | |
df = pd.read_csv(uploaded_file) | |
return f"""# 업로드된 CSV 파일: {uploaded_file.name} | |
## 기본 정보 | |
- 행 수: {df.shape[0]} | |
- 열 수: {df.shape[1]} | |
- 열 이름: {', '.join(df.columns.tolist())} | |
## 첫 5행 데이터 미리보기 | |
{df.head(5).to_markdown(index=False)} | |
## 기본 통계 | |
{df.describe().to_markdown()} | |
""" | |
except Exception as e: | |
logging.error(f"CSV 파일 처리 오류: {str(e)}") | |
return f"**Error processing {uploaded_file.name}**: {str(e)}" | |
def process_pdf_file(uploaded_file): | |
try: | |
file_bytes = uploaded_file.read() | |
pdf_file = io.BytesIO(file_bytes) | |
reader = PyPDF2.PdfReader(pdf_file, strict=False) | |
pages_preview = [] | |
for page_num in range(min(5, len(reader.pages))): | |
page = reader.pages[page_num] | |
pages_preview.append(f"--- Page {page_num+1} ---\n{page.extract_text()}") | |
preview_text = "\n\n".join(pages_preview) | |
return f"""# 업로드된 PDF 파일: {uploaded_file.name} | |
## 기본 정보 | |
- 총 페이지 수: {len(reader.pages)} | |
## 처음 5개 페이지 내용 미리보기 | |
{preview_text} | |
""" | |
except Exception as e: | |
logging.error(f"PDF 파일 처리 오류: {str(e)}") | |
return f"**Error processing {uploaded_file.name}**: {str(e)}" | |
def process_uploaded_files(uploaded_files): | |
"""Process all uploaded files and return their content as markdown.""" | |
if not uploaded_files: | |
return "" | |
file_contents = [] | |
for file in uploaded_files: | |
try: | |
ext = file.name.split('.')[-1].lower() | |
if ext == 'txt': | |
file_contents.append(process_text_file(file)) | |
file.seek(0) | |
elif ext == 'csv': | |
file_contents.append(process_csv_file(file)) | |
file.seek(0) | |
elif ext == 'pdf': | |
file_contents.append(process_pdf_file(file)) | |
file.seek(0) | |
else: | |
file_contents.append( | |
f"# Unsupported file: {file.name}\n\nThis file type is not supported for processing." | |
) | |
except Exception as e: | |
logging.error(f"파일 처리 오류 {file.name}: {str(e)}") | |
file_contents.append(f"# Error processing file: {file.name}\n\n{str(e)}") | |
return "\n\n# 사용자 업로드 파일 분석\n\n" + "\n\n---\n\n".join(file_contents) | |
# ──────────────────────────────── 이미지 생성 함수 ────────────────────── | |
def generate_image(prompt: str): | |
if not prompt: | |
return None, None | |
try: | |
clean_prompt = prompt.strip("\"'").strip() | |
if len(clean_prompt) < 3: | |
return None, None | |
logging.info(f"Sending image generation request with prompt: {clean_prompt}") | |
res = Client(IMAGE_API_URL).predict( | |
prompt=clean_prompt, | |
width=768, | |
height=768, | |
guidance=3.5, | |
inference_steps=30, | |
seed=3, | |
do_img2img=False, | |
init_image=None, | |
image2image_strength=0.8, | |
resize_img=True, | |
api_name="/generate_image" | |
) | |
if res and len(res) >= 2 and res[0]: | |
logging.info("Successfully received image data") | |
return res[0], clean_prompt | |
else: | |
logging.warning(f"Invalid response format from image API: {res}") | |
return None, None | |
except Exception as e: | |
logging.error(f"Image generation error: {str(e)}", exc_info=True) | |
return None, None | |
# ──────────────────────────────── Kaggle API 관련 ─────────────────────── | |
def check_kaggle_availability(): | |
if not KAGGLE_API_KEY: | |
logging.warning("Kaggle API를 사용할 수 없습니다. (KAGGLE_KEY가 비어 있음)") | |
return False | |
return True | |
def extract_kaggle_search_keywords(prompt, top=3): | |
clean_text = re.sub(r'[^\w\s]', ' ', prompt.lower()) | |
stop_words = { | |
'the', 'a', 'an', 'in', 'on', 'at', 'of', 'for', 'to', 'by', | |
'와', '과', '은', '는', '이', '가', '을', '를', '에', '에서', '으로' | |
} | |
words = [word for word in clean_text.split() if word not in stop_words and len(word) > 1] | |
word_freq = Counter(words) | |
top_words = [word for word, _ in word_freq.most_common(top)] | |
if not top_words and words: | |
top_words = words[:min(top, len(words))] | |
return " ".join(top_words) | |
def search_kaggle_datasets(query: str, top: int = 5) -> list[dict]: | |
if not query: | |
return [] | |
q_tokens = set(re.findall(r'[a-zA-Z가-힣]{2,}', query.lower())) | |
scored = [] | |
for ds in KAGGLE_DATASETS.values(): | |
tokens = set(t.lower() for t in ds["keywords"]) | |
score = len(q_tokens & tokens) | |
title_hit = any(tok in ds["title"].lower() for tok in q_tokens) | |
sub_hit = any(tok in ds["subtitle"].lower() for tok in q_tokens) | |
if title_hit: | |
score += 2 | |
if sub_hit: | |
score += 1 | |
if score > 0: | |
scored.append((score, ds)) | |
scored.sort(key=lambda x: (-x[0], x[1]["ref"])) | |
return [ds for _, ds in scored[:top]] | |
def download_and_analyze_dataset(dataset_ref: str, max_rows: int = 1000): | |
if not (os.getenv("KAGGLE_USERNAME") and os.getenv("KAGGLE_KEY")): | |
return "Kaggle API 인증정보가 없습니다." | |
api = KaggleApi() | |
api.authenticate() | |
tmpdir = tempfile.mkdtemp() | |
try: | |
api.dataset_download_files(dataset_ref, path=tmpdir, unzip=True) | |
except Exception as e: | |
logging.error(f"Dataset download failed ({dataset_ref}): {e}") | |
shutil.rmtree(tmpdir) | |
return f"데이터셋 다운로드 오류: {e}" | |
csv_files = glob.glob(f"{tmpdir}/**/*.csv", recursive=True) | |
if not csv_files: | |
shutil.rmtree(tmpdir) | |
return "CSV 파일을 찾을 수 없습니다." | |
try: | |
df = pd.read_csv(csv_files[0], nrows=max_rows) | |
analysis = { | |
"shape": df.shape, | |
"columns": df.columns.tolist(), | |
"head": df.head().to_dict("records"), | |
"describe": df.describe().to_dict(), | |
"missing_values": df.isnull().sum().to_dict() | |
} | |
except Exception as e: | |
analysis = f"CSV 파싱 오류: {e}" | |
shutil.rmtree(tmpdir) | |
return analysis | |
def format_kaggle_analysis_markdown_multi(analyses: list[dict]) -> str: | |
""" | |
여러 Kaggle 데이터셋(최대 3개) 메타‧분석 결과를 한꺼번에 마크다운으로 반환 | |
analyses = [ {"meta": {...}, "analysis": {... or str}}, ... ] | |
""" | |
if not analyses: | |
return "# Kaggle 데이터셋\n\n관련 데이터셋을 찾을 수 없습니다.\n\n" | |
md = "# Kaggle 데이터셋 분석 결과\n\n" | |
md += "다음 데이터셋을 검토하여 의사 결정에 참고하세요.\n\n" | |
for i, item in enumerate(analyses, 1): | |
ds = item["meta"] | |
ana = item["analysis"] | |
md += f"## {i}. {ds['title']}\n\n" | |
md += f"{ds['subtitle']}\n\n" | |
md += f"- **참조** : {ds['ref']}\n" | |
md += f"- **URL** : [{ds['url']}]({ds['url']})\n\n" | |
if isinstance(ana, dict): | |
md += f"**행 × 열** : {ana['shape'][0]} × {ana['shape'][1]}\n\n" | |
md += "<details><summary>미리보기 & 통계 (펼치기)</summary>\n\n" | |
try: | |
md += pd.DataFrame(ana["head"]).to_markdown(index=False) + "\n\n" | |
except: | |
pass | |
try: | |
md += pd.DataFrame(ana["describe"]).to_markdown() + "\n\n" | |
except: | |
pass | |
md += "</details>\n\n" | |
else: | |
md += f"{ana}\n\n" | |
md += "---\n\n" | |
return md | |
# ──────────────────────────────── OpenAI Client ────────────────────────── | |
def get_openai_client(): | |
if not OPENAI_API_KEY: | |
raise RuntimeError("⚠️ OPENAI_API_KEY 환경 변수가 설정되지 않았습니다.") | |
return OpenAI( | |
api_key=OPENAI_API_KEY, | |
timeout=60.0, | |
max_retries=3 | |
) | |
# ──────────────────────────────── 의사결정 목적/제약 식별 ───────────────────── | |
def identify_decision_purpose(prompt: str) -> dict: | |
purpose_patterns = { | |
'cost_reduction': [r'비용(\s*절감)?', r'예산', r'효율', r'저렴', r'경제', r'cost', r'saving', r'budget'], | |
'innovation': [r'혁신', r'새로운', r'창의', r'개발', r'발명', r'innovation', r'creative', r'develop'], | |
'risk_management': [r'위험', r'리스크', r'안전', r'예방', r'대비', r'risk', r'safety', r'prevent'], | |
'growth': [r'성장', r'확장', r'증가', r'확대', r'매출', r'growth', r'expand', r'increase', r'scale'], | |
'customer': [r'고객', r'사용자', r'만족', r'경험', r'서비스', r'customer', r'user', r'experience'] | |
} | |
constraint_patterns = { | |
'time': [r'시간', r'빠르게', r'긴급', r'마감', r'기한', r'time', r'deadline', r'urgent'], | |
'budget': [r'저예산', r'자금', r'투자', r'재정', r'budget', r'finance', r'fund', r'investment'], | |
'resources': [r'자원', r'인력', r'장비', r'제한', r'resource', r'staff', r'equipment', r'limited'], | |
'regulation': [r'규제', r'법률', r'규정', r'준수', r'법적', r'regulation', r'legal', r'compliance'] | |
} | |
purpose_scores = {} | |
for purpose, patterns in purpose_patterns.items(): | |
score = sum(1 for pattern in patterns if re.search(pattern, prompt, re.IGNORECASE)) | |
if score > 0: | |
purpose_scores[purpose] = score | |
constraint_scores = {} | |
for constraint, patterns in constraint_patterns.items(): | |
score = sum(1 for pattern in patterns if re.search(pattern, prompt, re.IGNORECASE)) | |
if score > 0: | |
constraint_scores[constraint] = score | |
main_purposes = sorted(purpose_scores.items(), key=lambda x: x[1], reverse=True)[:2] | |
main_constraints = sorted(constraint_scores.items(), key=lambda x: x[1], reverse=True)[:2] | |
return { | |
'purposes': main_purposes, | |
'constraints': main_constraints, | |
'all_purpose_scores': purpose_scores, | |
'all_constraint_scores': constraint_scores | |
} | |
# ──────────────────────────────── 카테고리 유틸 ───────────────────────── | |
def keywords(text: str, top: int = 8) -> str: | |
words = re.findall(r'\b[a-zA-Z가-힣]{2,}\b', text.lower()) | |
stopwords = { | |
'the', 'a', 'an', 'of', 'to', 'in', 'for', 'on', 'by', 'and', 'is', 'are', 'was', 'were', | |
'be', 'been', 'being', 'with', 'as', 'at', 'that', 'this', 'these', 'those', 'from', 'not', | |
'이', '그', '저', '것', '수', '등', '를', '을', '에', '에서', '그리고', '하는', '있는', '것은', | |
'있다', '그것', '또한', '또', '및', '이런', '그런', '무엇', '어떤', '많은', '한', '두', '몇' | |
} | |
words = [word for word in words if word not in stopwords] | |
word_freq = {} | |
for word in words: | |
word_freq[word] = word_freq.get(word, 0) + 1 | |
sorted_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True) | |
top_words = [word for word, _ in sorted_words[:top]] | |
return ' '.join(top_words) | |
def compute_relevance_scores(prompt: str, categories: list[Category]) -> dict: | |
prompt_lower = prompt.lower() | |
prompt_tokens = set(re.findall(r'\b[a-zA-Z가-힣]{2,}\b', prompt_lower)) | |
purpose_keywords = { | |
'cost_reduction': ['비용', '절감', '효율', '예산', 'cost', 'saving', 'budget', 'efficiency'], | |
'innovation': ['혁신', '창의', '신규', '개발', 'innovation', 'creative', 'novel', 'development'], | |
'risk_management': ['위험', '리스크', '관리', '예방', 'risk', 'management', 'prevention', 'mitigation'], | |
'growth': ['성장', '확장', '증가', '규모', 'growth', 'expansion', 'increase', 'scale'], | |
'customer': ['고객', '사용자', '만족', '경험', 'customer', 'user', 'satisfaction', 'experience'] | |
} | |
purpose_scores = {} | |
for purpose, keywords_ in purpose_keywords.items(): | |
score = sum(1 for kw in keywords_ if kw in prompt_lower) | |
if score > 0: | |
purpose_scores[purpose] = score | |
main_purpose = max(purpose_scores.items(), key=lambda x: x[1])[0] if purpose_scores else None | |
relevance_scores = {} | |
for category in categories: | |
cat_score = sum(1 for tag in category.tags if tag in prompt_lower) * 0.5 | |
if category.name_ko in prompt or category.name_en.lower() in prompt_lower: | |
cat_score += 1 | |
if main_purpose: | |
purpose_category_weights = { | |
'cost_reduction': { | |
'구조적 변화': 1.5, '화학적 변화': 1.3, '비즈니스 아이디어': 1.5, | |
'Structural Change': 1.5, 'Chemical Change': 1.3, 'Business Ideas': 1.5 | |
}, | |
'innovation': { | |
'센서 기능': 1.5, '표면 및 외관 변화': 1.3, '비즈니스 아이디어': 1.5, | |
'Sensor Functions': 1.5, 'Surface and Appearance Change': 1.3, 'Business Ideas': 1.5 | |
}, | |
'risk_management': { | |
'환경 상호작용': 1.5, '시간 관련 변화': 1.3, '비즈니스 아이디어': 1.4, | |
'Environmental Interaction': 1.5, 'Time-Related Change': 1.3, 'Business Ideas': 1.4 | |
}, | |
'growth': { | |
'크기와 형태 변화': 1.4, '비즈니스 아이디어': 1.6, '구조적 변화': 1.3, | |
'Size and Shape Change': 1.4, 'Business Ideas': 1.6, 'Structural Change': 1.3 | |
}, | |
'customer': { | |
'표면 및 외관 변화': 1.5, '센서 기능': 1.4, '빛과 시각 효과': 1.3, '비즈니스 아이디어': 1.4, | |
'Surface and Appearance Change': 1.5, 'Sensor Functions': 1.4, | |
'Light and Visual Effects': 1.3, 'Business Ideas': 1.4 | |
} | |
} | |
if category.name_ko in purpose_category_weights.get(main_purpose, {}): | |
cat_score *= purpose_category_weights[main_purpose][category.name_ko] | |
elif category.name_en in purpose_category_weights.get(main_purpose, {}): | |
cat_score *= purpose_category_weights[main_purpose][category.name_en] | |
for item in category.items: | |
item_score = cat_score | |
item_tokens = set(re.findall(r'\b[a-zA-Z가-힣]{2,}\b', item.lower())) | |
matches = item_tokens.intersection(prompt_tokens) | |
if matches: | |
item_score += len(matches) * 0.3 | |
if item_score > 0: | |
relevance_scores[(category.name_ko, item)] = item_score | |
return relevance_scores | |
def compute_score(weight: int, impact: int, confidence: float) -> float: | |
return round(weight * impact * confidence, 2) | |
def generate_comparison_matrix( | |
categories: list[Category], | |
relevance_scores: dict = None, | |
max_depth: int = 3, | |
max_combinations: int = 100, | |
relevance_threshold: float = 0.2 | |
) -> list[tuple]: | |
if relevance_scores is None: | |
pool = [(c.name_ko, item) for c in categories for item in c.items] | |
basic_combos = [] | |
for depth in range(2, max_depth + 1): | |
for combo in combinations(pool, depth): | |
basic_combos.append((1, 1, 1.0, 1.0, combo)) | |
if len(basic_combos) >= max_combinations: | |
break | |
return basic_combos[:max_combinations] | |
filtered_pool = [ | |
(cat, item) for (cat, item), score in relevance_scores.items() | |
if score >= relevance_threshold | |
] | |
if not filtered_pool: | |
pool = [(c.name_ko, i) for c in categories for i in c.items] | |
if len(pool) > 200: | |
import random | |
filtered_pool = random.sample(pool, 200) | |
else: | |
filtered_pool = pool | |
evaluated_combinations = [] | |
for depth in range(2, max_depth + 1): | |
for combo in combinations(filtered_pool, depth): | |
if len({item[0] for item in combo}) == depth: | |
combo_relevance = sum(relevance_scores.get((item[0], item[1]), 0) for item in combo) / depth | |
weight = min(5, max(1, int(combo_relevance * 2))) | |
impact = min(5, depth) | |
confidence = min(1.0, combo_relevance / 2.5) | |
total_score = compute_score(weight, impact, confidence) | |
evaluated_combinations.append((weight, impact, confidence, total_score, combo)) | |
evaluated_combinations.sort(key=lambda x: x[3], reverse=True) | |
return evaluated_combinations[:max_combinations] | |
# ──────────────────────────────── Diverse Matrix Generator ──────────────────── | |
def smart_weight(cat_name, item, relevance, global_cnt, T): | |
rare_boost = 1 / (global_cnt.get(item, 0) + 0.5) | |
noise = random.random() ** (1 / T) # T가 클수록 noise 분포가 1에 가깝게 | |
relevance_weight = 1 - (T - 0.1) / 3.0 | |
return ((relevance * relevance_weight) + 0.1) * rare_boost * noise | |
def generate_random_comparison_matrix( | |
categories: list[Category], | |
relevance_scores: dict | None = None, | |
k_cat=(8, 12), | |
n_item=(6, 10), | |
depth_range=(3, 6), | |
max_combos=1000, | |
seed: int | None = None, | |
T: float = 1.3, | |
): | |
if seed is None: | |
seed = random.randrange(2 ** 32) | |
random.seed(seed) | |
if "GLOBAL_PICK_COUNT" not in st.session_state: | |
st.session_state.GLOBAL_PICK_COUNT = {} | |
global_cnt = st.session_state.GLOBAL_PICK_COUNT | |
k = random.randint(*k_cat) | |
sampled_cats = random.sample(categories, k) | |
pool = [] | |
for cat in sampled_cats: | |
items = cat.items | |
weights = [ | |
smart_weight( | |
cat.name_ko, | |
it, | |
relevance_scores.get((cat.name_ko, it), 0.05) if relevance_scores else 0.05, | |
global_cnt, | |
T | |
) | |
for it in items | |
] | |
n = min(len(items), random.randint(*n_item)) | |
sampled_items = random.choices(items, weights=weights, k=n) | |
for it in sampled_items: | |
global_cnt[it] = global_cnt.get(it, 0) + 1 | |
pool.append((cat.name_ko, it)) | |
combos = [] | |
for d in range(depth_range[0], depth_range[1] + 1): | |
for combo in combinations(pool, d): | |
if len({c for c, _ in combo}) != d: | |
continue | |
w = sum(relevance_scores.get((c, i), 0.2) if relevance_scores else 1 for c, i in combo) / d | |
imp = d | |
conf = 0.5 + random.random() * 0.5 | |
total = compute_score(w, imp, conf) | |
combos.append((w, imp, conf, total, combo)) | |
combos.sort(key=lambda x: x[3], reverse=True) | |
return combos[:max_combos] | |
# ──────────────────────────────── PHYS_CATEGORIES ──────────────────────── | |
PHYS_CATEGORIES: list[Category] = [ | |
Category( | |
name_ko="센서 기능", | |
name_en="Sensor Functions", | |
tags=["sensor", "detection", "감지"], | |
items=physical_transformation_categories["센서 기능"] | |
), | |
Category( | |
name_ko="크기와 형태 변화", | |
name_en="Size and Shape Change", | |
tags=["shape", "geometry", "크기"], | |
items=physical_transformation_categories["크기와 형태 변화"] | |
), | |
Category( | |
name_ko="표면 및 외관 변화", | |
name_en="Surface and Appearance Change", | |
tags=["surface", "appearance", "표면"], | |
items=physical_transformation_categories["표면 및 외관 변화"] | |
), | |
Category( | |
name_ko="물질의 상태 변화", | |
name_en="Material State Change", | |
tags=["material", "state", "상태"], | |
items=physical_transformation_categories["물질의 상태 변화"] | |
), | |
Category( | |
name_ko="움직임 특성 변화", | |
name_en="Movement Characteristics Change", | |
tags=["motion", "dynamics", "움직임"], | |
items=physical_transformation_categories["움직임 특성 변화"] | |
), | |
Category( | |
name_ko="구조적 변화", | |
name_en="Structural Change", | |
tags=["structure", "form", "구조"], | |
items=physical_transformation_categories["구조적 변화"] | |
), | |
Category( | |
name_ko="공간 이동", | |
name_en="Spatial Movement", | |
tags=["movement", "space", "이동"], | |
items=physical_transformation_categories["공간 이동"] | |
), | |
Category( | |
name_ko="시간 관련 변화", | |
name_en="Time-Related Change", | |
tags=["time", "aging", "시간"], | |
items=physical_transformation_categories["시간 관련 변화"] | |
), | |
Category( | |
name_ko="빛과 시각 효과", | |
name_en="Light and Visual Effects", | |
tags=["light", "visual", "빛"], | |
items=physical_transformation_categories["빛과 시각 효과"] | |
), | |
Category( | |
name_ko="소리와 진동 효과", | |
name_en="Sound and Vibration Effects", | |
tags=["sound", "vibration", "소리"], | |
items=physical_transformation_categories["소리와 진동 효과"] | |
), | |
Category( | |
name_ko="열 관련 변화", | |
name_en="Thermal Changes", | |
tags=["heat", "thermal", "온도"], | |
items=physical_transformation_categories["열 관련 변화"] | |
), | |
Category( | |
name_ko="전기 및 자기 변화", | |
name_en="Electrical and Magnetic Changes", | |
tags=["electric", "magnetic", "전기"], | |
items=physical_transformation_categories["전기 및 자기 변화"] | |
), | |
Category( | |
name_ko="화학적 변화", | |
name_en="Chemical Change", | |
tags=["chemical", "reaction", "화학"], | |
items=physical_transformation_categories["화학적 변화"] | |
), | |
Category( | |
name_ko="생물학적 변화", | |
name_en="Biological Change", | |
tags=["bio", "living", "생물"], | |
items=physical_transformation_categories["생물학적 변화"] | |
), | |
Category( | |
name_ko="환경 상호작용", | |
name_en="Environmental Interaction", | |
tags=["environment", "interaction", "환경"], | |
items=physical_transformation_categories["환경 상호작용"] | |
), | |
Category( | |
name_ko="비즈니스 아이디어", | |
name_en="Business Ideas", | |
tags=["business", "idea", "비즈니스"], | |
items=physical_transformation_categories["비즈니스 아이디어"] | |
), | |
] | |
# ──────────────────────────────── 시스템 프롬프트 생성 ───────────────────── | |
def get_idea_system_prompt(selected_category: str | None = None, | |
selected_frameworks: list | None = None) -> str: | |
cat_clause = ( | |
f'\n**추가 지침**: 선택된 카테고리 "{selected_category}"에 특별한 주의를 기울이십시오. ' | |
f'이 카테고리의 항목들을 2단계와 3단계 모두에서 우선적으로 고려하십시오.\n' | |
) if selected_category else "" | |
if not selected_frameworks: | |
selected_frameworks = ["sunzi"] | |
framework_instruction = "\n\n### 선택된 분석 프레임워크\n" | |
framework_output_format = "" | |
if "sunzi" in selected_frameworks: | |
framework_instruction += "- **손자병법 36계**: 의사 결정 상황에 적용 가능한 손자병법 전략을 분석하여 통찰 제공\n" | |
framework_output_format += """ | |
## 4️⃣ 손자병법 관점의 전략적 통찰 | |
### 적용 가능한 손자병법 36계 | |
[현 상황에 적합한 손자병법 전략 2-3개 선정하여 분석] | |
| 병법 | 원리 | 현대적 해석 | 적용 방안 | | |
|-----|------|------------|----------| | |
| [병법 이름] | [핵심 원리] | [비즈니스 관점 해석] | [구체적 적용 전략] | | |
| [병법 이름] | [핵심 원리] | [비즈니스 관점 해석] | [구체적 적용 전략] | | |
... | |
### 손자병법 측면 의견 | |
[손자병법의 지혜를 활용한, 이 의사 결정에 대한 전략적 통찰과 조언 - 3-5개 단락] | |
""" | |
if "swot" in selected_frameworks: | |
framework_instruction += "- **SWOT 분석**: 내부 강점/약점 및 외부 기회/위협 요소를 체계적으로 분석\n" | |
framework_output_format += """ | |
## SWOT 분석 기반 전략적 통찰 | |
### SWOT 요소 분석 | |
| 구분 | 요소 | 전략적 시사점 | | |
|-----|------|------------| | |
| 강점(S) | [주요 강점 3-5개] | [강점을 활용한 전략적 방향] | | |
| 약점(W) | [주요 약점 3-5개] | [약점 극복/최소화 방안] | | |
| 기회(O) | [주요 기회 3-5개] | [기회 활용 전략] | | |
| 위협(T) | [주요 위협 3-5개] | [위협 대응/완화 전략] | | |
### SWOT 통합 전략 | |
- **SO 전략(강점-기회)**: [강점을 활용하여 기회를 극대화] | |
- **WO 전략(약점-기회)**: [약점을 보완하며 기회를 활용] | |
- **ST 전략(강점-위협)**: [강점을 활용하여 위협에 대응] | |
- **WT 전략(약점-위협)**: [약점과 위협을 동시에 최소화] | |
""" | |
if "porter" in selected_frameworks: | |
framework_instruction += "- **Porter의 5 Forces**: 산업 구조 및 경쟁 환경 분석\n" | |
framework_output_format += """ | |
## Porter의 5 Forces 분석 기반 통찰 | |
### 산업 구조 분석 | |
| 경쟁요소 | 강도 | 주요 특징 및 요인 | 전략적 대응방안 | | |
|--------|------|----------------|--------------| | |
| 기존 경쟁자 간 경쟁 | [상/중/하] | [주요 특징] | [대응 전략] | | |
| 신규 진입자의 위협 | [상/중/하] | [주요 특징] | [대응 전략] | | |
| 대체재의 위협 | [상/중/하] | [주요 특징] | [대응 전략] | | |
| 구매자의 교섭력 | [상/중/하] | [주요 특징] | [대응 전략] | | |
| 공급자의 교섭력 | [상/중/하] | [주요 특징] | [대응 전략] | | |
### 전략적 포지셔닝 권장사항 | |
[3-4 단락으로 종합 포지셔닝 / 대응 전략] | |
""" | |
if "bcg" in selected_frameworks: | |
framework_instruction += "- **BCG 매트릭스**: 제품/사업 포트폴리오 관리를 통한 자원 배분 전략\n" | |
framework_output_format += """ | |
## BCG 매트릭스 기반 포트폴리오 분석 | |
### 사업/제품 영역별 포지셔닝 | |
| 영역 | 해당 제품/사업 | 권장 전략 | 자원 배분 방향 | | |
|-----|--------------|----------|--------------| | |
| 스타 (Stars) | [해당 제품/사업] | [권장 전략] | [투자/자원 배분 방향] | | |
| 현금젖소 (Cash Cows) | [해당 제품/사업] | [권장 전략] | [투자/자원 배분 방향] | | |
| 물음표 (Question Marks) | [해당 제품/사업] | [권장 전략] | [투자/자원 배분 방향] | | |
| 개 (Dogs) | [해당 제품/사업] | [권장 전략] | [투자/자원 배분 방향] | | |
### 포트폴리오 최적화 방안 | |
[BCG 매트릭스 분석 기반 자원 배분·관리 권장 - 3-4 단락] | |
""" | |
base_prompt = f""" | |
You are a deep thinking AI, you may use extremely long chains of thought to deeply consider the problem and deliberate with yourself via systematic reasoning processes to help come to a correct solution prior to answering. You should enclose your thoughts and internal monologue inside tags, and then provide your solution or response to the problem. Extract key search terms from the user's question that would be effective for web searches. Provide these as a search query with words separated by spaces only, without commas. For example: 'Prime Minister Han Duck-soo impeachment results'. | |
반드시 한글(한국어)로 답변하라. 당신은 의사 결정 지원 컨설턴트로서 CCM(크로스 카테고리 매트릭스) 방법론과 다양한 경영 프레임워크를 활용하여 사용자의 의사 결정을 체계적으로 지원합니다. | |
### CCM 기반 의사 결정 지원 프로세스 | |
다음 단계를 통해 체계적으로 의사 결정을 분석하십시오: | |
1. **의사 결정 문제 분석 및 지식 베이스 구축** | |
- 입력된 의사 결정 문제의 핵심을 명확히 정의하고 관련 요소 추출 | |
- 웹검색 결과를 분석하여 관련 트렌드, 선례, 사례 파악 | |
- Kaggle 데이터셋 분석 결과가 있다면 이를 활용하여 데이터 기반 통찰 도출 | |
- 의사 결정에 필요한 핵심 요소와 고려사항 식별 | |
2. **카테고리별 분석 매핑** | |
- 다양한 카테고리에서 의사 결정에 영향을 미치는 요소 식별 | |
- 각 카테고리별로 최소 1개 이상의 관련 요소 선정 | |
- 선정 요소와 의사 결정 간의 연결성 설명 | |
3. **종합 매트릭스 생성 및 의사 결정 지원** | |
- 여러 카테고리에서 중요한 요소를 선택하여 종합적 분석 | |
- 각 요소가 의사 결정에 미치는 영향과 중요도 평가 | |
- 다양한 요소를 고려한 최적의 의사 결정 제안 | |
{framework_instruction} | |
### 출력 형식 | |
최종 보고서를 다음 구조로 마크다운 형식으로 작성하십시오: | |
## 1️⃣ 의사 결정 문제 분석 | |
- **문제 정의**: [의사 결정 상황 요약] | |
- **핵심 고려사항**: [불릿 3-5개로 주요 고려요소 리스트] | |
- **현황 분석**: [웹검색, 데이터셋 분석, 배경지식 기반 현재 상황 요약] | |
## 2️⃣ 카테고리별 의사 결정 요소 분석 | |
[각 카테고리별로 가장 관련있는 요소들을 표 형식으로 정리] | |
| 카테고리 | 관련 요소 | 의사 결정과의 연관성 | | |
|---------|----------|-------------------| | |
| [카테고리1] | [선정 요소] | [의사 결정과의 연관성 설명] | | |
| [카테고리2] | [선정 요소] | [의사 결정과의 연관성 설명] | | |
(관련 카테고리에 대해 작성) | |
## 3️⃣ 종합적 의사 결정 분석 | |
### 주요 결정 요소 및 영향 평가 | |
[다양한 카테고리를 고려한 종합적 접근] | |
| 주요 요소 | 긍정적 영향 | 부정적 영향 | 중요도 | | |
|----------|------------|------------|--------| | |
| [요소1] | [긍정적 영향 설명] | [부정적 영향 설명] | [상/중/하] | | |
| [요소2] | [긍정적 영향 설명] | [부정적 영향 설명] | [상/중/하] | | |
... | |
### 의사 결정 대안 분석 | |
| 대안 | 장점 | 단점 | 종합 평가 | | |
|-----|------|------|----------| | |
| [대안1] | [장점 리스트] | [단점 리스트] | [전반적 평가] | | |
| [대안2] | [장점 리스트] | [단점 리스트] | [전반적 평가] | | |
... | |
{framework_output_format} | |
## 5️⃣ 권장 의사 결정 및 실행 계획 (3개 안) | |
### Plan A : [권장 결정 제목 A] | |
- **개요** : 2‒3줄 핵심 요약 | |
- **WHY – 전략적 근거** : 데이터/프레임워크 인용 2‒3개 | |
- **WHAT – SMART 목표** : 구체·측정·달성·관련·기한 | |
- **HOW – 실행 로드맵** : 단계별 일정 + RACI 요약표 | |
- **RISK & MITIGATION** : 주요 리스크 × 대응 전략 | |
- **KPI & 모니터링** : 선행·후행 KPI, 측정 주기 | |
- **TIME IMPACT** : 단기 / 중기 / 장기 영향 | |
- **Plan-B Trigger** : 재점검·피벗 조건 | |
### Plan B : [권장 결정 제목 B] | |
- **개요** : 2‒3줄 핵심 요약 | |
- **WHY – 전략적 근거** : 데이터/프레임워크 인용 2‒3개 | |
- **WHAT – SMART 목표** : 구체·측정·달성·관련·기한 | |
- **HOW – 실행 로드맵** : 단계별 일정 + RACI 요약표 | |
- **RISK & MITIGATION** : 주요 리스크 × 대응 전략 | |
- **KPI & 모니터링** : 선행·후행 KPI, 측정 주기 | |
- **TIME IMPACT** : 단기 / 중기 / 장기 영향 | |
- **Plan-B Trigger** : 재점검·피벗 조건 | |
### Plan C : [권장 결정 제목 C] | |
- **개요** : 2‒3줄 핵심 요약 | |
- **WHY – 전략적 근거** : 데이터/프레임워크 인용 2‒3개 | |
- **WHAT – SMART 목표** : 구체·측정·달성·관련·기한 | |
- **HOW – 실행 로드맵** : 단계별 일정 + RACI 요약표 | |
- **RISK & MITIGATION** : 주요 리스크 × 대응 전략 | |
- **KPI & 모니터링** : 선행·후행 KPI, 측정 주기 | |
- **TIME IMPACT** : 단기 / 중기 / 장기 영향 | |
- **Plan-B Trigger** : 재점검·피벗 조건 | |
## 6️⃣ 참고 정보 | |
### 데이터 출처 | |
- **Kaggle 데이터셋**: [분석에 사용된 Kaggle 데이터셋 정보] | |
- **웹 검색 정보**: [주요 참고한 웹 정보 출처 3-5개] | |
### 이미지 프롬프트 | |
[의사 결정의 핵심을 시각화할 수 있는 영문 이미지 프롬프트 1줄] | |
{cat_clause} | |
Step-by-step 사고 과정을 따르되, 출력에는 최종 보고서만 표시하십시오. 주요 의사 결정 요소와 대안은 단순한 개요가 아닌, 구체적이고 실질적인 분석과 함께 제시하십시오. 웹 검색 결과와 Kaggle 데이터셋 분석은 참고 정보에 반드시 포함하여 의사 결정의 근거로 활용하십시오. | |
""" | |
return base_prompt.strip() | |
# ──────────────────────────────── Brave Search API ─────────────────────── | |
def brave_search(query: str, count: int = 20): | |
if not BRAVE_KEY: | |
raise RuntimeError("⚠️ SERPHOUSE_API_KEY (Brave API Key) 환경 변수가 비어있습니다.") | |
headers = { | |
"Accept": "application/json", | |
"Accept-Encoding": "gzip", | |
"X-Subscription-Token": BRAVE_KEY | |
} | |
params = {"q": query, "count": str(count)} | |
for attempt in range(3): | |
try: | |
r = requests.get(BRAVE_ENDPOINT, headers=headers, params=params, timeout=15) | |
r.raise_for_status() | |
data = r.json() | |
raw = data.get("web", {}).get("results") or data.get("results", []) | |
if not raw: | |
raise ValueError("No search results found.") | |
arts = [] | |
for i, res in enumerate(raw[:count], 1): | |
url = res.get("url", res.get("link", "")) | |
host = re.sub(r"https?://(www\.)?", "", url).split("/")[0] | |
arts.append({ | |
"index": i, | |
"title": res.get("title", "No title"), | |
"link": url, | |
"snippet": res.get("description", res.get("text", "No snippet")), | |
"displayed_link": host | |
}) | |
return arts | |
except Exception as e: | |
logging.error(f"Brave search failure (attempt {attempt+1}/3): {e}") | |
time.sleep(1) | |
return [] | |
def mock_results(query: str) -> str: | |
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S") | |
return ( | |
f"# Fallback Search Content (Generated: {ts})\n\n" | |
f"The web search API request failed. Please generate the ideas based on '{query}' using general knowledge.\n\n" | |
f"You may consider aspects such as:\n\n" | |
f"- Basic concept or definition of {query}\n" | |
f"- Common facts or challenges\n" | |
f"- Potential categories from transformation list\n\n" | |
f"Note: This is fallback text, not real-time data.\n\n" | |
) | |
def do_web_search(query: str) -> str: | |
try: | |
arts = brave_search(query, 20) | |
if not arts: | |
logging.warning("No search results from Brave. Using fallback.") | |
return mock_results(query) | |
hdr = "# Web Search Results\nUse the information below...\n\n" | |
body = "\n".join( | |
f"### Result {a['index']}: {a['title']}\n\n{a['snippet']}\n\n**Source**: [{a['displayed_link']}]({a['link']})\n\n---\n" | |
for a in arts | |
) | |
return hdr + body | |
except Exception as e: | |
logging.error(f"Web search process failed: {str(e)}") | |
return mock_results(query) | |
# ──────────────────────────────── Streamlit 메인 앱 ────────────────────── | |
def idea_generator_app(): | |
st.title("Ilúvatar(일루바타르) : Decision Support AI") | |
st.caption("'일루바타르'는 빅데이터를 자율적으로 수집·분석하여 12억 개 이상의 복합 의사결정 변수를 실시간 병렬 처리, 전략적 통찰을 도출하는 초지능형 의사결정 시스템입니다.") | |
default_vals = { | |
"ai_model": "gpt-4.1-mini", | |
"messages": [], | |
"auto_save": True, | |
"generate_image": True, | |
"web_search_enabled": True, | |
"kaggle_enabled": True, | |
"selected_frameworks": ["sunzi"], | |
"GLOBAL_PICK_COUNT": {}, | |
"_skip_dup_idx": None | |
} | |
for k, v in default_vals.items(): | |
if k not in st.session_state: | |
st.session_state[k] = v | |
sb = st.sidebar | |
st.session_state.temp = sb.slider( | |
"Diversity temperature", 0.1, 3.0, 1.3, 0.1, | |
help="0.1 = 연관성 위주, 3.0 = 매우 높은 다양성" | |
) | |
sb.title("Decision Support Settings") | |
sb.toggle("Auto Save", key="auto_save") | |
sb.toggle("Auto Image Generation", key="generate_image") | |
st.session_state.web_search_enabled = sb.toggle( | |
"Use Web Search", value=st.session_state.web_search_enabled | |
) | |
st.session_state.kaggle_enabled = sb.toggle( | |
"Use Kaggle Datasets", value=st.session_state.kaggle_enabled | |
) | |
if st.session_state.web_search_enabled: | |
sb.info("✅ Web search results will be integrated.") | |
if st.session_state.kaggle_enabled: | |
if KAGGLE_KEY: | |
sb.info("✅ Kaggle datasets will be analyzed.") | |
else: | |
sb.error("⚠️ KAGGLE_KEY not set. Kaggle integration disabled.") | |
st.session_state.kaggle_enabled = False | |
# 분석 프레임워크 선택 | |
sb.subheader("분석 프레임워크 설정") | |
selected_frameworks = sb.multiselect( | |
"사용할 경영 프레임워크 선택", | |
options=list(BUSINESS_FRAMEWORKS.keys()), | |
default=st.session_state.selected_frameworks, | |
format_func=lambda x: BUSINESS_FRAMEWORKS[x] | |
) | |
st.session_state.selected_frameworks = selected_frameworks or ["sunzi"] | |
# 예시 토픽 | |
example_topics = { | |
"example1": "스마트홈 환경에서 사용자 경험을 개선할 수 있는 새로운 가전제품 디자인 의사결정", | |
"example2": "친환경 에너지 분야 진출을 위한 최적 비즈니스 모델 선택 의사결정", | |
"example3": "2030년 의료 헬스케어 산업의 기술 발전 방향과 투자 전략 의사결정" | |
} | |
sb.subheader("Example Decision Topics") | |
c1, c2, c3 = sb.columns(3) | |
if c1.button("제품 디자인 의사결정", key="ex1"): | |
process_example(example_topics["example1"]) | |
if c2.button("신사업 진출 전략", key="ex2"): | |
process_example(example_topics["example2"]) | |
if c3.button("산업 미래 전망", key="ex3"): | |
process_example(example_topics["example3"]) | |
# 최근 결과 다운로드 | |
latest_ideas = next( | |
(m["content"] for m in reversed(st.session_state.messages) | |
if m["role"] == "assistant" and m["content"].strip()), | |
None | |
) | |
if latest_ideas: | |
title_match = re.search(r"# (.*?)(\n|$)", latest_ideas) | |
title = (title_match.group(1) if title_match else "ideas").strip() | |
sb.subheader("Download Latest Ideas") | |
d1, d2 = sb.columns(2) | |
d1.download_button("Download as Markdown", latest_ideas, | |
file_name=f"{title}.md", mime="text/markdown") | |
d2.download_button("Download as HTML", md_to_html(latest_ideas, title), | |
file_name=f"{title}.html", mime="text/html") | |
# 대화 히스토리 업로드/다운로드 | |
up = sb.file_uploader("Load Conversation History (.json)", | |
type=["json"], key="json_uploader") | |
if up: | |
try: | |
st.session_state.messages = json.load(up) | |
sb.success("Conversation history loaded successfully") | |
except Exception as e: | |
sb.error(f"Failed to load: {e}") | |
if sb.button("Download Conversation as JSON"): | |
sb.download_button( | |
"Save JSON", | |
data=json.dumps(st.session_state.messages, ensure_ascii=False, indent=2), | |
file_name="chat_history.json", | |
mime="application/json" | |
) | |
# 파일 업로드 | |
st.subheader("File Upload (Optional)") | |
uploaded_files = st.file_uploader( | |
"Upload files to reference in the idea generation (txt, csv, pdf)", | |
type=["txt", "csv", "pdf"], | |
accept_multiple_files=True, | |
key="file_uploader" | |
) | |
if uploaded_files: | |
st.success(f"{len(uploaded_files)} files uploaded.") | |
with st.expander("Preview Uploaded Files", expanded=False): | |
for idx, file in enumerate(uploaded_files): | |
st.write(f"**File Name:** {file.name}") | |
ext = file.name.split('.')[-1].lower() | |
try: | |
if ext == 'txt': | |
preview = file.read(1000).decode('utf-8', errors='ignore') | |
file.seek(0) | |
st.text_area("Preview", preview + ("..." if len(preview) >= 1000 else ""), height=150) | |
elif ext == 'csv': | |
df = pd.read_csv(file) | |
file.seek(0) | |
st.dataframe(df.head(5)) | |
elif ext == 'pdf': | |
reader = PyPDF2.PdfReader(io.BytesIO(file.read()), strict=False) | |
file.seek(0) | |
pg_txt = reader.pages[0].extract_text() if reader.pages else "(No text)" | |
st.text_area("Preview", (pg_txt[:500] + "...") if pg_txt else "(No text)", height=150) | |
except Exception as e: | |
st.error(f"Preview failed: {e}") | |
if idx < len(uploaded_files) - 1: | |
st.divider() | |
# 이미 렌더된 메시지(중복 방지) | |
skip_idx = st.session_state.get("_skip_dup_idx") | |
for i, m in enumerate(st.session_state.messages): | |
if skip_idx is not None and i == skip_idx: | |
continue | |
with st.chat_message(m["role"]): | |
st.markdown(m["content"]) | |
if "image" in m: | |
st.image(m["image"], caption=m.get("image_caption", "")) | |
st.session_state["_skip_dup_idx"] = None | |
# 채팅 입력 | |
prompt = st.chat_input("의사 결정에 도움이 필요한 상황이나 문제를 설명해 주세요.") | |
if prompt: | |
process_input(prompt, uploaded_files) | |
sb.markdown("---") | |
sb.markdown("Created by [VIDraft](https://discord.gg/openfreeai)") | |
def process_example(topic): | |
process_input(topic, []) | |
def process_input(prompt: str, uploaded_files): | |
if not any(m["role"] == "user" and m["content"] == prompt for m in st.session_state.messages): | |
st.session_state.messages.append({"role": "user", "content": prompt}) | |
with st.chat_message("user"): | |
st.markdown(prompt) | |
for i in range(len(st.session_state.messages) - 1): | |
if (st.session_state.messages[i]["role"] == "user" | |
and st.session_state.messages[i]["content"] == prompt | |
and st.session_state.messages[i + 1]["role"] == "assistant"): | |
return | |
with st.chat_message("assistant"): | |
status = st.status("Preparing to generate ideas…") | |
stream_placeholder = st.empty() | |
full_response = "" | |
try: | |
client = get_openai_client() | |
status.update(label="Initializing model…") | |
selected_cat = st.session_state.get("category_focus", None) | |
selected_frameworks = st.session_state.get("selected_frameworks", ["sunzi"]) | |
sys_prompt = get_idea_system_prompt( | |
selected_category=selected_cat, | |
selected_frameworks=selected_frameworks | |
) | |
def category_context(sel): | |
if sel: | |
return json.dumps({sel: physical_transformation_categories[sel]}, ensure_ascii=False) | |
return "ALL_CATEGORIES: " + ", ".join(physical_transformation_categories.keys()) | |
use_web_search = st.session_state.web_search_enabled | |
use_kaggle = st.session_state.kaggle_enabled | |
has_uploaded = bool(uploaded_files) | |
search_content = None | |
kaggle_content = None | |
file_content = None | |
# ① 웹검색 | |
if use_web_search: | |
status.update(label="Searching the web…") | |
with st.spinner("Searching…"): | |
search_content = do_web_search(keywords(prompt, top=5)) | |
# ② Kaggle | |
if use_kaggle and check_kaggle_availability(): | |
status.update(label="Kaggle 데이터셋 분석 중…") | |
with st.spinner("Searching Kaggle…"): | |
kaggle_kw = extract_kaggle_search_keywords(prompt) | |
try: | |
datasets = search_kaggle_datasets(kaggle_kw) | |
except Exception as e: | |
logging.warning(f"search_kaggle_datasets 오류 무시: {e}") | |
datasets = [] | |
analyses = [] | |
if datasets: | |
status.update(label="Downloading & analysing datasets…") | |
for ds in datasets: | |
try: | |
ana = download_and_analyze_dataset(ds["ref"]) | |
except Exception as e: | |
logging.error(f"Kaggle 분석 오류({ds['ref']}) : {e}") | |
ana = f"데이터셋 분석 오류: {e}" | |
analyses.append({"meta": ds, "analysis": ana}) | |
if analyses: | |
kaggle_content = format_kaggle_analysis_markdown_multi(analyses) | |
# ③ 파일 업로드 | |
if has_uploaded: | |
status.update(label="Reading uploaded files…") | |
with st.spinner("Processing files…"): | |
file_content = process_uploaded_files(uploaded_files) | |
# ④ Military Tactics Dataset (신규 추가) | |
mil_content = None | |
if is_military_query(prompt): | |
status.update(label="Searching military tactics dataset…") | |
with st.spinner("Loading military insights…"): | |
mil_rows = military_search(prompt) | |
if mil_rows: | |
mil_content = "# Military Tactics Dataset Reference\n\n" | |
for i, row in enumerate(mil_rows, 1): | |
mil_content += ( | |
f"### Case {i}\n" | |
f"**Scenario:** {row['scenario_description']}\n\n" | |
f"**Attack Reasoning:** {row['attack_reasoning']}\n\n" | |
f"**Defense Reasoning:** {row['defense_reasoning']}\n\n---\n" | |
) | |
user_content = prompt | |
if search_content: | |
user_content += "\n\n" + search_content | |
if kaggle_content: | |
user_content += "\n\n" + kaggle_content | |
if file_content: | |
user_content += "\n\n" + file_content | |
if mil_content: | |
user_content += "\n\n" + mil_content | |
# 내부 분석 | |
status.update(label="의사 결정 문제 분석 중…") | |
decision_purpose = identify_decision_purpose(prompt) | |
relevance_scores = compute_relevance_scores(prompt, PHYS_CATEGORIES) | |
status.update(label="의사 결정 매트릭스 생성 중…") | |
T = st.session_state.temp | |
k_cat_range = (4, 8) if T < 1.0 else (6, 10) if T < 2.0 else (8, 12) | |
n_item_range = (2, 4) if T < 1.0 else (3, 6) if T < 2.0 else (4, 8) | |
depth_range = (2, 3) if T < 1.0 else (2, 5) if T < 2.0 else (2, 6) | |
combos = generate_random_comparison_matrix( | |
PHYS_CATEGORIES, | |
relevance_scores, | |
k_cat=k_cat_range, | |
n_item=n_item_range, | |
depth_range=depth_range, | |
seed=hash(prompt) & 0xFFFFFFFF, | |
T=T, | |
) | |
combos_table = "| 조합 | 가중치 | 영향도 | 신뢰도 | 총점 |\n|------|--------|--------|--------|-----|\n" | |
for w, imp, conf, tot, cmb in combos: | |
combo_str = " + ".join(f"{c[0]}-{c[1]}" for c in cmb) | |
combos_table += f"| {combo_str} | {w} | {imp} | {conf:.1f} | {tot} |\n" | |
purpose_info = "\n\n## 의사 결정 목적 분석\n" | |
if decision_purpose['purposes']: | |
purpose_info += "### 주요 목적\n" | |
for p, s in decision_purpose['purposes']: | |
purpose_info += f"- **{p}** (관련성: {s})\n" | |
if decision_purpose['constraints']: | |
purpose_info += "\n### 주요 제약 조건\n" | |
for c, s in decision_purpose['constraints']: | |
purpose_info += f"- **{c}** (관련성: {s})\n" | |
framework_contents = [] | |
if "swot" in selected_frameworks: | |
swot_res = analyze_with_swot(prompt) | |
framework_contents.append(format_business_framework_analysis("swot", swot_res)) | |
if "porter" in selected_frameworks: | |
porter_res = analyze_with_porter(prompt) | |
framework_contents.append(format_business_framework_analysis("porter", porter_res)) | |
if "bcg" in selected_frameworks: | |
bcg_res = analyze_with_bcg(prompt) | |
framework_contents.append(format_business_framework_analysis("bcg", bcg_res)) | |
if framework_contents: | |
user_content += "\n\n## 경영 프레임워크 분석 결과\n\n" + "\n\n".join(framework_contents) | |
user_content += f"\n\n## 의사 결정 매트릭스 분석{purpose_info}\n{combos_table}" | |
status.update(label="Generating ideas…") | |
api_messages = [ | |
{"role": "system", "content": sys_prompt}, | |
{"role": "system", "name": "category_db", "content": category_context(selected_cat)}, | |
{"role": "user", "content": user_content}, | |
] | |
stream = client.chat.completions.create( | |
model="gpt-4.1-mini", | |
messages=api_messages, | |
temperature=1, | |
max_tokens=MAX_TOKENS, | |
top_p=1, | |
stream=True | |
) | |
for chunk in stream: | |
if chunk.choices and chunk.choices[0].delta.content: | |
full_response += chunk.choices[0].delta.content | |
stream_placeholder.markdown(full_response + "▌") | |
stream_placeholder.markdown(full_response) | |
status.update(label="Ideas created!", state="complete") | |
# 이미지 생성 | |
img_data = img_caption = None | |
if st.session_state.generate_image and full_response: | |
match = re.search(r"###\s*이미지\s*프롬프트\s*\n+([^\n]+)", full_response, re.I) | |
if not match: | |
match = re.search(r"Image\s+Prompt\s*[:\-]\s*([^\n]+)", full_response, re.I) | |
if match: | |
raw_prompt = re.sub(r'[\r\n"\'\\]', " ", match.group(1)).strip() | |
with st.spinner("아이디어 이미지 생성 중…"): | |
img_data, img_caption = generate_image(raw_prompt) | |
if img_data: | |
st.image(img_data, caption=f"아이디어 시각화 – {img_caption}") | |
answer_msg = {"role": "assistant", "content": full_response} | |
if img_data: | |
answer_msg["image"] = img_data | |
answer_msg["image_caption"] = img_caption | |
st.session_state["_skip_dup_idx"] = len(st.session_state.messages) | |
st.session_state.messages.append(answer_msg) | |
# 다운로드 버튼 | |
st.subheader("Download This Output") | |
col_md, col_html = st.columns(2) | |
col_md.download_button( | |
"Markdown", | |
data=full_response, | |
file_name=f"{prompt[:30]}.md", | |
mime="text/markdown" | |
) | |
col_html.download_button( | |
"HTML", | |
data=md_to_html(full_response, prompt[:30]), | |
file_name=f"{prompt[:30]}.html", | |
mime="text/html" | |
) | |
if st.session_state.auto_save: | |
fn = f"chat_history_auto_{datetime.now():%Y%m%d_%H%M%S}.json" | |
with open(fn, "w", encoding="utf-8") as fp: | |
json.dump(st.session_state.messages, fp, ensure_ascii=False, indent=2) | |
except Exception as e: | |
logging.error("process_input error", exc_info=True) | |
st.error(f"⚠️ 작업 중 오류가 발생했습니다: {e}") | |
st.session_state.messages.append( | |
{"role": "assistant", "content": f"⚠️ 오류: {e}"} | |
) | |
def main(): | |
idea_generator_app() | |
if __name__ == "__main__": | |
main() | |