ginipick commited on
Commit
0f10845
·
verified ·
1 Parent(s): 180d48a

Create app-backup.py

Browse files
Files changed (1) hide show
  1. app-backup.py +1896 -0
app-backup.py ADDED
@@ -0,0 +1,1896 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import re
4
+ import logging
5
+ import requests
6
+ import markdown
7
+ import time
8
+ import io
9
+ import random
10
+ import hashlib
11
+ from datetime import datetime
12
+ from dataclasses import dataclass
13
+ from itertools import combinations, product
14
+ from typing import Iterator
15
+
16
+ import streamlit as st
17
+ import pandas as pd
18
+ import PyPDF2 # For handling PDF files
19
+ from collections import Counter
20
+
21
+ from openai import OpenAI # OpenAI 라이브러리
22
+ from gradio_client import Client
23
+ from kaggle.api.kaggle_api_extended import KaggleApi
24
+ import tempfile
25
+ import glob
26
+ import shutil
27
+
28
+ # ─── 추가된 라이브러리(절대 누락 금지) ───────────────────────────────
29
+ import pyarrow.parquet as pq
30
+ from sklearn.feature_extraction.text import TfidfVectorizer
31
+ from sklearn.metrics.pairwise import cosine_similarity
32
+
33
+ # ─────────────────────────────── Environment Variables / Constants ─────────────────────────
34
+
35
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
36
+ BRAVE_KEY = os.getenv("SERPHOUSE_API_KEY", "") # Brave Search API
37
+ KAGGLE_USERNAME = os.getenv("KAGGLE_USERNAME", "")
38
+ KAGGLE_KEY = os.getenv("KAGGLE_KEY", "")
39
+ KAGGLE_API_KEY = KAGGLE_KEY
40
+
41
+ if not (KAGGLE_USERNAME and KAGGLE_KEY):
42
+ raise RuntimeError("⚠️ KAGGLE_USERNAME과 KAGGLE_KEY 환경변수를 먼저 설정하세요.")
43
+
44
+ os.environ["KAGGLE_USERNAME"] = KAGGLE_USERNAME
45
+ os.environ["KAGGLE_KEY"] = KAGGLE_KEY
46
+
47
+ BRAVE_ENDPOINT = "https://api.search.brave.com/res/v1/web/search"
48
+ IMAGE_API_URL = "http://211.233.58.201:7896" # 예시 이미지 생성용 API
49
+ MAX_TOKENS = 7999
50
+
51
+ # ─────────────────────────────── Logging ───────────────────────────────
52
+ logging.basicConfig(
53
+ level=logging.INFO,
54
+ format="%(asctime)s - %(levelname)s - %(message)s"
55
+ )
56
+
57
+ # ─────────────────────────────── 군사(밀리터리) 전술 데이터셋 로드 ─────────────────
58
+ @st.cache_resource
59
+ def load_military_dataset():
60
+ """
61
+ mil.parquet (index, scenario_description, attack_reasoning, defense_reasoning)
62
+ """
63
+ path = os.path.join(os.path.dirname(__file__), "mil.parquet")
64
+ if not os.path.exists(path):
65
+ logging.warning("mil.parquet not found – military support disabled.")
66
+ return None
67
+ try:
68
+ df = pq.read_table(path).to_pandas()
69
+ return df
70
+ except Exception as e:
71
+ logging.error(f"Failed to read mil.parquet: {e}")
72
+ return None
73
+
74
+ MIL_DF = load_military_dataset()
75
+
76
+ def is_military_query(text: str) -> bool:
77
+ """군사/전술 관련 키워드가 등장하면 True 반환"""
78
+ kw = [
79
+ "군사", "전술", "전투", "전쟁", "작전", "무기", "병력",
80
+ "military", "tactic", "warfare", "battle", "operation"
81
+ ]
82
+ return any(k.lower() in text.lower() for k in kw)
83
+
84
+ def military_search(query: str, top_k: int = 3):
85
+ """
86
+ mil.parquet의 scenario_description 열과 코사인 유사도 분석하여
87
+ query와 가장 유사한 상위 시나리오를 반환
88
+ """
89
+ if MIL_DF is None:
90
+ return []
91
+ try:
92
+ corpus = MIL_DF["scenario_description"].tolist()
93
+ vec = TfidfVectorizer().fit_transform([query] + corpus)
94
+ sims = cosine_similarity(vec[0:1], vec[1:]).flatten()
95
+ top_idx = sims.argsort()[-top_k:][::-1]
96
+ return MIL_DF.iloc[top_idx][[
97
+ "scenario_description",
98
+ "attack_reasoning",
99
+ "defense_reasoning"
100
+ ]].to_dict("records")
101
+ except Exception as e:
102
+ logging.error(f"military_search error: {e}")
103
+ return []
104
+
105
+ # ─────────────────────────────── Kaggle Datasets ────────────────────────
106
+ KAGGLE_DATASETS = {
107
+ "general_business": {
108
+ "ref": "mohammadgharaei77/largest-2000-global-companies",
109
+ "title": "Largest 2000 Global Companies",
110
+ "subtitle": "Comprehensive data about the world's largest companies",
111
+ "url": "https://www.kaggle.com/datasets/mohammadgharaei77/largest-2000-global-companies",
112
+ "keywords": ["business", "company", "corporation", "enterprise", "global", "비즈니스", "기업", "회사", "글로벌", "기업가치"]
113
+ },
114
+ "global_development": {
115
+ "ref": "michaelmatta0/global-development-indicators-2000-2020",
116
+ "title": "Global Development Indicators (2000-2020)",
117
+ "subtitle": "Economic and social indicators for countries worldwide",
118
+ "url": "https://www.kaggle.com/datasets/michaelmatta0/global-development-indicators-2000-2020",
119
+ "keywords": ["development", "economy", "global", "indicators", "social", "경제", "발전", "지표", "사회", "국가", "글로벌"]
120
+ },
121
+ "startup_ideas": {
122
+ "ref": "rohitsahoo/100-startup-ideas",
123
+ "title": "Startup Idea Generator Dataset",
124
+ "subtitle": "A variety of startup ideas",
125
+ "url": "https://www.kaggle.com/datasets/rohitsahoo/100-startup-ideas",
126
+ "keywords": ["startup", "innovation", "business idea", "entrepreneurship", "스타트업", "창업", "혁신", "아이디어", "기업가"]
127
+ },
128
+ "legal_terms": {
129
+ "ref": "gu05087/korean-legal-terms",
130
+ "title": "Korean Legal Terms",
131
+ "subtitle": "Database of Korean legal terminology",
132
+ "url": "https://www.kaggle.com/datasets/gu05087/korean-legal-terms",
133
+ "keywords": ["legal", "law", "terms", "korean", "legislation", "법률", "법적", "한국", "용어", "규제"]
134
+ },
135
+ "billionaires": {
136
+ "ref": "vincentcampanaro/forbes-worlds-billionaires-list-2024",
137
+ "title": "Forbes World's Billionaires List 2024",
138
+ "subtitle": "Comprehensive data on the world's wealthiest individuals",
139
+ "url": "https://www.kaggle.com/datasets/vincentcampanaro/forbes-worlds-billionaires-list-2024",
140
+ "keywords": ["billionaire", "wealth", "rich", "forbes", "finance", "부자", "억만장자", "포브스", "부", "재테크"]
141
+ },
142
+ "financial_news": {
143
+ "ref": "thedevastator/uncovering-financial-insights-with-the-reuters-2",
144
+ "title": "Reuters Financial News Insights",
145
+ "subtitle": "Financial news and market analysis from Reuters",
146
+ "url": "https://www.kaggle.com/datasets/thedevastator/uncovering-financial-insights-with-the-reuters-2",
147
+ "keywords": ["finance", "market", "stock", "investment", "news", "금융", "시장", "주식", "투자", "뉴스"]
148
+ },
149
+ "ecommerce": {
150
+ "ref": "oleksiimartusiuk/80000-products-e-commerce-data-clean",
151
+ "title": "80,000 Products E-Commerce Data",
152
+ "subtitle": "Clean dataset of e-commerce products information",
153
+ "url": "https://www.kaggle.com/datasets/oleksiimartusiuk/80000-products-e-commerce-data-clean",
154
+ "keywords": ["ecommerce", "product", "retail", "shopping", "online", "이커머스", "제품", "소매", "쇼핑", "온라인"]
155
+ },
156
+ "world_development_indicators": {
157
+ "ref": "georgejdinicola/world-bank-indicators",
158
+ "title": "World Development Indicators",
159
+ "subtitle": "Long-run socio-economic indicators for 200+ countries",
160
+ "url": "https://www.kaggle.com/datasets/georgejdinicola/world-bank-indicators",
161
+ "keywords": [
162
+ "wdi", "macro", "economy", "gdp", "population",
163
+ "개발지표", "거시경제", "세계은행", "경제지표", "인구"
164
+ ]
165
+ },
166
+ "commodity_prices": {
167
+ "ref": "debashish311601/commodity-prices",
168
+ "title": "Commodity Prices (2000-2023)",
169
+ "subtitle": "Daily prices for crude oil, gold, grains, metals, etc.",
170
+ "url": "https://www.kaggle.com/datasets/debashish311601/commodity-prices",
171
+ "keywords": [
172
+ "commodity", "oil", "gold", "raw material", "price",
173
+ "원자재", "유가", "금", "가격", "시장"
174
+ ]
175
+ },
176
+ "world_trade": {
177
+ "ref": "muhammadtalhaawan/world-export-and-import-dataset",
178
+ "title": "World Export & Import Dataset",
179
+ "subtitle": "34-year historical trade flows by country & product",
180
+ "url": "https://www.kaggle.com/datasets/muhammadtalhaawan/world-export-and-import-dataset",
181
+ "keywords": [
182
+ "trade", "export", "import", "commerce", "flow",
183
+ "무역", "수출", "수입", "국제교역", "관세"
184
+ ]
185
+ },
186
+ "us_business_reports": {
187
+ "ref": "census/business-and-industry-reports",
188
+ "title": "US Business & Industry Reports",
189
+ "subtitle": "Key monthly economic indicators from the US Census Bureau",
190
+ "url": "https://www.kaggle.com/datasets/census/business-and-industry-reports",
191
+ "keywords": [
192
+ "us", "economy", "retail sales", "construction", "manufacturing",
193
+ "미국", "경제지표", "소매판매", "산업생산", "건설"
194
+ ]
195
+ },
196
+ "us_industrial_production": {
197
+ "ref": "federalreserve/industrial-production-index",
198
+ "title": "Industrial Production Index (US)",
199
+ "subtitle": "Monthly Fed index for manufacturing, mining & utilities",
200
+ "url": "https://www.kaggle.com/datasets/federalreserve/industrial-production-index",
201
+ "keywords": [
202
+ "industry", "production", "index", "fed", "us",
203
+ "산업생산", "제조업", "미국", "경기", "지수"
204
+ ]
205
+ },
206
+ "us_stock_market": {
207
+ "ref": "borismarjanovic/price-volume-data-for-all-us-stocks-etfs",
208
+ "title": "Huge Stock Market Dataset",
209
+ "subtitle": "Historical prices & volumes for all US stocks and ETFs",
210
+ "url": "https://www.kaggle.com/datasets/borismarjanovic/price-volume-data-for-all-us-stocks-etfs",
211
+ "keywords": [
212
+ "stock", "market", "finance", "equity", "price",
213
+ "주식", "미국증시", "시세", "ETF", "데이터"
214
+ ]
215
+ },
216
+ "company_financials": {
217
+ "ref": "rish59/financial-statements-of-major-companies2009-2023",
218
+ "title": "Financial Statements of Major Companies (2009-2023)",
219
+ "subtitle": "15-year income sheet & balance sheet data for global firms",
220
+ "url": "https://www.kaggle.com/datasets/rish59/financial-statements-of-major-companies2009-2023",
221
+ "keywords": [
222
+ "financials", "income", "balance sheet", "cashflow",
223
+ "재무제표", "매출", "수익성", "기업재무", "포트폴리오"
224
+ ]
225
+ },
226
+ "startup_investments": {
227
+ "ref": "justinas/startup-investments",
228
+ "title": "Crunchbase Startup Investments",
229
+ "subtitle": "Funding rounds & investor info for global startups",
230
+ "url": "https://www.kaggle.com/datasets/justinas/startup-investments",
231
+ "keywords": [
232
+ "startup", "venture", "funding", "crunchbase",
233
+ "투자", "VC", "스타트업", "라운드", "신규진입"
234
+ ]
235
+ },
236
+ "global_energy": {
237
+ "ref": "atharvasoundankar/global-energy-consumption-2000-2024",
238
+ "title": "Global Energy Consumption (2000-2024)",
239
+ "subtitle": "Country-level energy usage by source & sector",
240
+ "url": "https://www.kaggle.com/datasets/atharvasoundankar/global-energy-consumption-2000-2024",
241
+ "keywords": [
242
+ "energy", "consumption", "renewable", "oil", "utility",
243
+ "에너지", "소비", "재생에너지", "전력수요", "화석연료"
244
+ ]
245
+ },
246
+ "co2_emissions": {
247
+ "ref": "ulrikthygepedersen/co2-emissions-by-country",
248
+ "title": "CO₂ Emissions by Country",
249
+ "subtitle": "Annual CO₂ emissions & per-capita data since 1960s",
250
+ "url": "https://www.kaggle.com/datasets/ulrikthygepedersen/co2-emissions-by-country",
251
+ "keywords": [
252
+ "co2", "emission", "climate", "environment", "carbon",
253
+ "탄소배출", "기후변화", "환경", "온실가스", "지속가능"
254
+ ]
255
+ },
256
+ "crop_climate": {
257
+ "ref": "thedevastator/the-relationship-between-crop-production-and-cli",
258
+ "title": "Crop Production & Climate Change",
259
+ "subtitle": "Yield & area stats for wheat, corn, rice, soybean vs climate",
260
+ "url": "https://www.kaggle.com/datasets/thedevastator/the-relationship-between-crop-production-and-cli",
261
+ "keywords": [
262
+ "agriculture", "crop", "climate", "yield", "food",
263
+ "농업", "작물", "기후", "수확량", "식품"
264
+ ]
265
+ },
266
+ "esg_ratings": {
267
+ "ref": "alistairking/public-company-esg-ratings-dataset",
268
+ "title": "Public Company ESG Ratings",
269
+ "subtitle": "Environment, Social & Governance scores for listed firms",
270
+ "url": "https://www.kaggle.com/datasets/alistairking/public-company-esg-ratings-dataset",
271
+ "keywords": [
272
+ "esg", "sustainability", "governance", "csr",
273
+ "환경", "사회", "지배구조", "지속가능", "평가"
274
+ ]
275
+ },
276
+ "global_health": {
277
+ "ref": "malaiarasugraj/global-health-statistics",
278
+ "title": "Global Health Statistics",
279
+ "subtitle": "Comprehensive health indicators & disease prevalence by country",
280
+ "url": "https://www.kaggle.com/datasets/malaiarasugraj/global-health-statistics",
281
+ "keywords": [
282
+ "health", "disease", "life expectancy", "WHO",
283
+ "보건", "질병", "기대수명", "의료", "공중보건"
284
+ ]
285
+ },
286
+ "housing_market": {
287
+ "ref": "atharvasoundankar/global-housing-market-analysis-2015-2024",
288
+ "title": "Global Housing Market Analysis (2015-2024)",
289
+ "subtitle": "House price index, mortgage rates, rent data by country",
290
+ "url": "https://www.kaggle.com/datasets/atharvasoundankar/global-housing-market-analysis-2015-2024",
291
+ "keywords": [
292
+ "housing", "real estate", "price index", "mortgage",
293
+ "부동산", "주택가격", "임대료", "시장", "금리"
294
+ ]
295
+ },
296
+ "pharma_sales": {
297
+ "ref": "milanzdravkovic/pharma-sales-data",
298
+ "title": "Pharma Sales Data (2014-2019)",
299
+ "subtitle": "600k sales records across 8 ATC drug categories",
300
+ "url": "https://www.kaggle.com/datasets/milanzdravkovic/pharma-sales-data",
301
+ "keywords": [
302
+ "pharma", "sales", "drug", "healthcare", "medicine",
303
+ "제약", "의약품", "매출", "헬스케어", "시장"
304
+ ]
305
+ },
306
+ "ev_sales": {
307
+ "ref": "muhammadehsan000/global-electric-vehicle-sales-data-2010-2024",
308
+ "title": "Global EV Sales Data (2010-2024)",
309
+ "subtitle": "Electric vehicle unit sales by region & model year",
310
+ "url": "https://www.kaggle.com/datasets/muhammadehsan000/global-electric-vehicle-sales-data-2010-2024",
311
+ "keywords": [
312
+ "ev", "electric vehicle", "automotive", "mobility",
313
+ "전기차", "판매량", "자동차산업", "친환경모빌리티", "시장성장"
314
+ ]
315
+ },
316
+ "hr_attrition": {
317
+ "ref": "pavansubhasht/ibm-hr-analytics-attrition-dataset",
318
+ "title": "IBM HR Analytics: Attrition & Performance",
319
+ "subtitle": "Employee demographics, satisfaction & attrition flags",
320
+ "url": "https://www.kaggle.com/datasets/pavansubhasht/ibm-hr-analytics-attrition-dataset",
321
+ "keywords": [
322
+ "hr", "attrition", "employee", "people analytics",
323
+ "인사", "이직률", "직원", "HR분석", "조직관리"
324
+ ]
325
+ },
326
+ "employee_satisfaction": {
327
+ "ref": "redpen12/employees-satisfaction-analysis",
328
+ "title": "Employee Satisfaction Survey Data",
329
+ "subtitle": "Department-level survey scores on satisfaction & engagement",
330
+ "url": "https://www.kaggle.com/datasets/redpen12/employees-satisfaction-analysis",
331
+ "keywords": [
332
+ "satisfaction", "engagement", "survey", "workplace",
333
+ "직원만족도", "조직문화", "설문", "근무환경", "HR"
334
+ ]
335
+ },
336
+ "world_bank_indicators": {
337
+ "ref": "georgejdinicola/world-bank-indicators",
338
+ "title": "World Bank Indicators by Topic (1960-Present)",
339
+ "subtitle": "Macro-economic, 사회·인구 통계 등 200+개국 장기 시계열 지표",
340
+ "url": "https://www.kaggle.com/datasets/georgejdinicola/world-bank-indicators",
341
+ "keywords": ["world bank", "development", "economy", "global", "indicator", "세계은행", "경제", "지표", "개발", "거시"]
342
+ },
343
+ "physical_chem_properties": {
344
+ "ref": "ivanyakovlevg/physical-and-chemical-properties-of-substances",
345
+ "title": "Physical & Chemical Properties of Substances",
346
+ "subtitle": "8만여 화합물의 물리·화학 특성 및 분류 정보",
347
+ "url": "https://www.kaggle.com/datasets/ivanyakovlevg/physical-and-chemical-properties-of-substances",
348
+ "keywords": ["chemistry", "materials", "property", "substance", "화학", "물성", "소재", "데이터", "R&D"]
349
+ },
350
+ "global_weather_repository": {
351
+ "ref": "nelgiriyewithana/global-weather-repository",
352
+ "title": "Global Weather Repository",
353
+ "subtitle": "전 세계 기상 관측치(기온·강수·풍속 등) 일별 업데이트",
354
+ "url": "https://www.kaggle.com/datasets/nelgiriyewithana/global-weather-repository",
355
+ "keywords": ["weather", "climate", "meteorology", "global", "forecast", "기상", "날씨", "기후", "관측", "환경"]
356
+ },
357
+ "amazon_best_seller_softwares": {
358
+ "ref": "kaverappa/amazon-best-seller-softwares",
359
+ "title": "Amazon Best Seller – Software Category",
360
+ "subtitle": "아마존 소프트웨어 베스트셀러 순위 및 리뷰 데이터",
361
+ "url": "https://www.kaggle.com/datasets/kaverappa/amazon-best-seller-softwares",
362
+ "keywords": ["amazon", "e-commerce", "software", "review", "ranking", "아마존", "이커머스", "소프트웨어", "베스트셀러", "리뷰"]
363
+ },
364
+ "world_stock_prices": {
365
+ "ref": "nelgiriyewithana/world-stock-prices-daily-updating",
366
+ "title": "World Stock Prices (Daily Updating)",
367
+ "subtitle": "30,000여 글로벌 상장사의 일간 주가·시총·섹터 정보 실시간 갱신",
368
+ "url": "https://www.kaggle.com/datasets/nelgiriyewithana/world-stock-prices-daily-updating",
369
+ "keywords": ["stock", "finance", "market", "equity", "price", "글로벌", "주가", "금융", "시장", "투자"]
370
+ }
371
+ }
372
+
373
+ SUN_TZU_STRATEGIES = [
374
+ {"계": "만천과해", "요약": "평범한 척, 몰래 진행", "조건": "상대가 지켜보고 있을 때", "행동": "루틴·평온함 과시", "목적": "경계 무력화", "예시": "규제기관 눈치 보는 신사업 파일럿"},
375
+ {"계": "위위구조", "요약": "뒤통수 치면 포위 풀린다", "조건": "우리 측이 압박받을 때", "행동": "적 본진 급습", "목적": "압박 해소", "예시": "경쟁사 핵심 고객 뺏기"},
376
+ {"계": "차도살인", "요약": "내 손 더럽히지 마", "조건": "직접 공격 부담", "행동": "제3자 활용", "목적": "책임 전가", "예시": "언론을 통한 경쟁사 비판"},
377
+ {"계": "이일대우", "요약": "우리가 쉬면 적이 지친다", "조건": "상대가 과로 중", "행동": "버티며 체력 보존", "목적": "역전 타이밍 확보", "예시": "협상 지연 후 헐값 인수"},
378
+ {"계": "진화타겁", "요약": "불날 때 주워 담기", "조건": "시장 혼란·위기", "행동": "저가 매수", "목적": "저비용 고이익", "예시": "금융위기 때 우량자산 매입"},
379
+ {"계": "성동격서", "요약": "소음은 왼쪽, 공격은 오른쪽", "조건": "정면 방어 견고", "행동": "가짜 신호 → 우회", "목적": "방어 분산", "예시": "신제품 A 홍보, 실제는 B 확장"},
380
+ {"계": "무중생유", "요약": "없는 것도 있는 척", "조건": "자원 부족", "행동": "허세��연막", "목적": "상대 혼란", "예시": "스타트업 과장 로드맵"},
381
+ {"계": "암도진창", "요약": "뒷문으로 돌아가라", "조건": "우회로 존재", "행동": "비밀 루트 침투", "목적": "허를 찌름", "예시": "관세 피해 제3국 생산"},
382
+ {"계": "격안관화", "요약": "남 싸움 구경", "조건": "두 경쟁자 충돌", "행동": "관망", "목적": "둘 다 소모", "예시": "플랫폼 전쟁 중 중립 유지"},
383
+ {"계": "소리장도", "요약": "웃으며 칼 숨기기", "조건": "친밀 분위기", "행동": "우호 제스처 후 기습", "목적": "경계 붕괴", "예시": "합작 후 핵심 기술 탈취"},
384
+ {"계": "이대도강", "요약": "덜 중요한 걸 내줘라", "조건": "뭔가 잃었을 때", "행동": "부속 희생", "목적": "핵심 보호", "예시": "제품 라인 하나 단종"},
385
+ {"계": "순수견양", "요약": "방치된 것 챙기기", "조건": "경계 허술", "행동": "자연스럽게 수집", "목적": "무혈 이득", "예시": "공공 API 데이터 긁기"},
386
+ {"계": "타초경사", "요약": "풀 쳐서 뱀 나온다", "조건": "적이 숨을 때", "행동": "일부러 소란", "목적": "위치 노출", "예시": "이사회 반대파 의중 파악"},
387
+ {"계": "차시환혼", "요약": "죽은 카드 재활용", "조건": "폐기 자원", "행동": "리브랜딩", "목적": "새 전력 확보", "예시": "실패 앱 재출시"},
388
+ {"계": "조호이산", "요약": "호랑이 산 밖으로", "조건": "강적 거점", "행동": "유인 이동", "목적": "빈집 공략", "예시": "경쟁 VC 행사 유도 후 딜 선점"},
389
+ {"계": "욕금고종", "요약": "잡으려면 놓아줘라", "조건": "인재·적 포획", "행동": "일부러 풀어줌", "목적": "저항 약화", "예시": "핵심 인재 재계약 유도"},
390
+ {"계": "포전인옥", "요약": "벽돌 던져 옥 얻기", "조건": "큰 보상 필요", "행동": "작은 미끼", "목적": "참여 유도", "예시": "무료 → 유료 전환"},
391
+ {"계": "금적금왕", "요약": "도둑 잡으려면 두목부터", "조건": "조직 복잡", "행동": "수뇌 공격", "목적": "조직 붕괴", "예시": "최대 주주 지분 매입"},
392
+ {"계": "부저이지", "요약": "가마 밑 불 끄기", "조건": "적 의존성 존재", "행동": "보급 차단", "목적": "전력 급감", "예시": "핵심 공급업체 선점"},
393
+ {"계": "혼수모어", "요약": "물 흐려 놓고 낚시", "조건": "판세 불투명", "행동": "혼탁 유지", "목적": "어부지리", "예시": "입법 지연 로비"},
394
+ {"계": "금선탈각", "요약": "허물 벗고 도망", "조건": "추적 심함", "행동": "외피만 남김", "목적": "추적 무효", "예시": "부실 자회사 떼어내기"},
395
+ {"계": "관문잡적", "요약": "문 닫고 잡아라", "조건": "퇴로 예측", "행동": "출구 봉쇄", "목적": "완전 포획", "예시": "락업 조항으로 지분 매집"},
396
+ {"계": "원교근공", "요약": "먼 데와 친해지고 가까운 데 친다", "조건": "다국 간 경쟁", "행동": "원거리 동맹", "목적": "단계적 확장", "예시": "원거리 FTA 체결 후 인근 M&A"},
397
+ {"계": "가도벌괵", "요약": "길 빌려 공격", "조건": "중간 세력 장벽", "행동": "통로 명분 → 제압", "목적": "장애 제거", "예시": "총판 빌미 시장 진입"},
398
+ {"계": "투량환주", "요약": "들보 몰래 바꿔치기", "조건": "감시 존재", "행동": "내부 교체", "목적": "인식 왜곡", "예시": "백엔드 갈아끼우기"},
399
+ {"계": "지상매괴", "요약": "뽕나무 가리켜 회초리 욕", "조건": "직접 비판 곤란", "행동": "제3자 지적", "목적": "메시지 전달", "예시": "싱크탱크 보고서 압박"},
400
+ {"계": "가치불전", "요약": "바보 연기", "조건": "상대 의심 많음", "행동": "일부러 허술", "목적": "방심 유도", "예시": "저평가 가이던스"},
401
+ {"계": "상옥추제", "요약": "사다리 걷어차기", "조건": "길 열어준 뒤", "행동": "퇴로 차단", "목적": "고립", "예시": "투자자 초청 후 정보 차단"},
402
+ {"계": "수상개화", "요약": "나무에 꽃 핀 척", "조건": "실력 부족", "행동": "외형 부풀림", "목적": "영향력 확대", "예시": "MOU ·공동 로고 홍보"},
403
+ {"계": "반객위주", "요약": "손님에서 주인으로", "조건": "부차적 위치", "행동": "주도권 장악", "목적": "역전 지휘", "예시": "플랫폼 입점사 자체 마켓"},
404
+ {"계": "미인계", "요약": "매력으로 판단 흐리기", "조건": "유혹 가능", "행동": "감정·매력 활용", "목적": "결정 왜곡", "예시": "지역 투자로 정치인 호감 얻기"},
405
+ {"계": "공성계", "요약": "텅 빈 성문 열어놓기", "조건": "병력 부족", "행동": "과감히 공개", "목적": "상대 의심", "예시": "내부자료 전면 공개"},
406
+ {"계": "반간계", "요약": "가짜 스파이 역이용", "조건": "내부 불��� 요소", "행동": "교란 정보", "목적": "분열", "예시": "경쟁사에 가짜 루머"},
407
+ {"계": "고육계", "요약": "살 내주고 뼈 취하기", "조건": "신뢰 상실", "행동": "스스로 손실", "목적": "진정성 증명", "예시": "CEO 보너스 반납"},
408
+ {"계": "연환계", "요약": "사슬로 한꺼번에", "조건": "복수 대상 다수", "행동": "연결 묶기", "목적": "효율 타격", "예시": "패키지 제재안"},
409
+ {"계": "주위상계", "요약": "도망이 상책", "조건": "승산 없음", "행동": "즉시 후퇴", "목적": "손실 최소·재기", "예시": "적자 시장 철수"}
410
+ ]
411
+
412
+ physical_transformation_categories = {
413
+ # (카테고리 + 항목 대량 추가됨)
414
+ # ... (생략 없이 전체 포함)
415
+ "센서 기능": [
416
+ "시각 센서", "시각 감지", "청각 센서", "청각 감지", "촉각 센서", "촉각 감지",
417
+ "미각 센서", "미각 감지", "후각 센서", "후각 감지", "온도 센서", "온도 감지",
418
+ "습도 센서", "습도 감지", "압력 센서", "압력 감지", "가속도 센서", "가속도 감지",
419
+ "회전 센서", "회전 감지", "근접 센서", "근접 감지", "위치 센서", "위치 감지",
420
+ "운동 센서", "운동 감지", "가스 센서", "가스 감지", "적외선 센서", "적외선 감지",
421
+ "자외선 센서", "자외선 감지", "방사선 센서", "방사선 감지", "자기장 센서", "자기장 감지",
422
+ "전기장 센서", "전기장 감지", "화학물질 센서", "화학물질 감지", "생체신호 센서", "생체신호 감지",
423
+ "진동 센서", "진동 감지", "소음 센서", "소음 감지", "빛 세기 센서", "빛 세기 감지",
424
+ "빛 파장 센서", "빛 파장 감지", "기울기 센서", "기울기 감지", "pH 센서", "pH 감지",
425
+ "전류 센서", "전류 감지", "전압 센서", "전압 감지", "이미지 센서", "이미지 감지",
426
+ "거리 센서", "거리 감지", "깊이 센서", "깊이 감지", "중력 센서", "중력 감지",
427
+ "속도 센서", "속도 감지", "흐름 센서", "흐름 감지", "수위 센서", "수위 감지",
428
+ "탁도 센서", "탁도 감지", "염도 센서", "염도 감지", "금속 감지", "압전 센서",
429
+ "압전 감지", "광전 센서", "광전 감지", "열전대 센서", "열전대 감지", "홀 효과 센서",
430
+ "홀 효과 감지", "초음파 센서", "초음파 감지", "레이더 센서", "레이더 감지",
431
+ "라이다 센서", "라이다 감지", "터치 센서", "터치 감지", "제스처 센서", "제스처 감지",
432
+ "심박 센서", "심박 감지", "혈압 센서", "혈압 감지", "LAN", "WIFI", "블루투스", "생체 인증",
433
+ "다중 스펙트럼 센서", "다중 스펙트럼 감지", "깊이 인식 센서", "깊이 인식 감지",
434
+ "퀀텀 센서", "퀀텀 감지", "웨어러블 센서", "웨어러블 감지", "바이오마커 센서", "바이오마커 감지",
435
+ "임베디드 센서", "임베디드 감지", "IoT 센서 네트워크", "스트레인 센서", "스트레인 감지",
436
+ "경도/연도 센서", "경도/연도 감지", "5G/6G 연결성", "NFC", "양자암호화 통신",
437
+ "스마트 먼지 센서", "환경 센서 그리드", "신경형태학적 센서", "두뇌-기계 인터페이스"
438
+ ],
439
+ # ... (다른 카테고리 전체 항목들도 추가/수정된 상태로 포함)
440
+ "사용자 인터페이스 및 상호작용": [
441
+ "제스처 인식", "제스처 제어", "음성 인식", "음성 제어", "시선 추적", "시선 제어",
442
+ "촉각 피드백", "햅틱 인터페이스", "뇌-컴퓨터 인터페이스", "증강 현실 인터페이스",
443
+ "가상 현실 인터페이스", "혼합 현실 인터페이스", "주변 인텔리전스", "상황 인식 인터페이스",
444
+ "자연어 처리 인터페이스", "생체인식 인증", "다중 모달 인터페이스", "암묵적 상호작용",
445
+ "명시적 상호작용", "인지적 부하 최소화", "지능형 적응 인터페이스", "감정 인식 인터페이스",
446
+ "소셜 인터페이스", "공간 인터페이스", "신체 증강 인터페이스", "피부 인터페이스",
447
+ "안구 내 인터페이스", "신경 인터페이스", "근전도 인터페이스", "후각 인터페이스"
448
+ ],
449
+ # ...
450
+ }
451
+
452
+ physical_transformation_categories_en = {} # (영문 카테고리는 사용하지 않아도 되므로 비워둠)
453
+
454
+ SWOT_FRAMEWORK = {
455
+ "strengths": {
456
+ "title": "강점 (Strengths)",
457
+ "description": "내부적 긍정 요소 - 조직이 가진 경쟁 우위 요소",
458
+ "prompt_keywords": ["강점", "장점", "우위", "역량", "자산", "전문성", "strength", "advantage"]
459
+ },
460
+ "weaknesses": {
461
+ "title": "약점 (Weaknesses)",
462
+ "description": "내부적 부정 요소 - 개선이 필요한 내부 한계",
463
+ "prompt_keywords": ["약점", "단점", "부족", "한계", "취약점", "weakness", "limitation", "deficit"]
464
+ },
465
+ "opportunities": {
466
+ "title": "기회 (Opportunities)",
467
+ "description": "외부적 긍정 요소 - 활용 가능한 외부 환경 변화",
468
+ "prompt_keywords": ["기회", "가능성", "트렌드", "변화", "성장", "opportunity", "trend", "potential"]
469
+ },
470
+ "threats": {
471
+ "title": "위협 (Threats)",
472
+ "description": "외부적 부정 요소 - 대응이 필요한 외부 위험 요소",
473
+ "prompt_keywords": ["위협", "리스크", "경쟁", "위험", "장벽", "threat", "risk", "competition", "barrier"]
474
+ }
475
+ }
476
+
477
+ PORTER_FRAMEWORK = {
478
+ "rivalry": {
479
+ "title": "기존 경쟁자 간의 경쟁",
480
+ "description": "동일 산업 내 경쟁 강도 분석",
481
+ "prompt_keywords": ["경쟁", "경쟁사", "시장점유율", "가격경쟁", "competition", "rival", "market share"]
482
+ },
483
+ "new_entrants": {
484
+ "title": "신규 진입자의 위협",
485
+ "description": "새로운 기업의 시장 진입 난이도 분석",
486
+ "prompt_keywords": ["진입장벽", "신규", "스타트업", "entry barrier", "newcomer", "startup"]
487
+ },
488
+ "substitutes": {
489
+ "title": "대체재의 위협",
490
+ "description": "대체 가능한 제품/서비스의 위협 분석",
491
+ "prompt_keywords": ["대체재", "대안", "substitute", "alternative", "replacement"]
492
+ },
493
+ "buyer_power": {
494
+ "title": "구매자의 교섭력",
495
+ "description": "고객의 가격 협상력 분석",
496
+ "prompt_keywords": ["고객", "구매자", "가격민감도", "협상력", "customer", "buyer power"]
497
+ },
498
+ "supplier_power": {
499
+ "title": "공급자의 교섭력",
500
+ "description": "공급업체의 가격/조건 협상력 분석",
501
+ "prompt_keywords": ["공급자", "벤더", "원재료", "supplier", "vendor", "raw material"]
502
+ }
503
+ }
504
+
505
+ BCG_FRAMEWORK = {
506
+ "stars": {
507
+ "title": "스타 (Stars)",
508
+ "description": "높은 성장률, 높은 시장점유율 - 추가 투자 필요",
509
+ "prompt_keywords": ["성장", "점유율", "중점", "투자", "star", "growth", "investment"]
510
+ },
511
+ "cash_cows": {
512
+ "title": "현금젖소 (Cash Cows)",
513
+ "description": "낮은 성장률, 높은 시장점유율 - 현금흐름 창출",
514
+ "prompt_keywords": ["안정", "수익", "현금", "전통", "cash cow", "profit", "mature"]
515
+ },
516
+ "question_marks": {
517
+ "title": "물음표 (Question Marks)",
518
+ "description": "높은 성장률, 낮은 시장점유율 - 선택적 투자/철수",
519
+ "prompt_keywords": ["가능성", "위험", "불확실", "잠재", "question mark", "uncertain", "potential"]
520
+ },
521
+ "dogs": {
522
+ "title": "개 (Dogs)",
523
+ "description": "낮은 성장률, 낮은 시장점유율 - 철수 고려",
524
+ "prompt_keywords": ["회수", "철수", "저성장", "비효율", "dog", "divest", "low growth"]
525
+ }
526
+ }
527
+
528
+ BUSINESS_FRAMEWORKS = {
529
+ "sunzi": "손자병법 36계",
530
+ "swot": "SWOT 분석",
531
+ "porter": "Porter의 5 Forces",
532
+ "bcg": "BCG 매트릭스"
533
+ }
534
+
535
+ @dataclass
536
+ class Category:
537
+ """통일된 카테고리 및 항목 구조"""
538
+ name_ko: str
539
+ name_en: str
540
+ tags: list[str]
541
+ items: list[str]
542
+
543
+ # ──────────────────────────────── 프레임워크 분석 함수들 ─────────────────────────
544
+ def analyze_with_swot(prompt: str) -> dict:
545
+ prompt_lower = prompt.lower()
546
+ results = {}
547
+ for category, info in SWOT_FRAMEWORK.items():
548
+ score = sum(1 for keyword in info["prompt_keywords"] if keyword.lower() in prompt_lower)
549
+ keywords = []
550
+ for keyword in info["prompt_keywords"]:
551
+ if keyword.lower() in prompt_lower:
552
+ pattern = f".{{0,15}}{keyword}.{{0,15}}"
553
+ matches = re.findall(pattern, prompt_lower, re.IGNORECASE)
554
+ for match in matches[:2]:
555
+ keywords.append(match.strip())
556
+ results[category] = {
557
+ "title": info["title"],
558
+ "description": info["description"],
559
+ "score": score,
560
+ "keywords": keywords[:5]
561
+ }
562
+ return results
563
+
564
+ def analyze_with_porter(prompt: str) -> dict:
565
+ prompt_lower = prompt.lower()
566
+ results = {}
567
+ for category, info in PORTER_FRAMEWORK.items():
568
+ score = sum(1 for keyword in info["prompt_keywords"] if keyword.lower() in prompt_lower)
569
+ keywords = []
570
+ for keyword in info["prompt_keywords"]:
571
+ if keyword.lower() in prompt_lower:
572
+ pattern = f".{{0,15}}{keyword}.{{0,15}}"
573
+ matches = re.findall(pattern, prompt_lower, re.IGNORECASE)
574
+ for match in matches[:2]:
575
+ keywords.append(match.strip())
576
+ results[category] = {
577
+ "title": info["title"],
578
+ "description": info["description"],
579
+ "score": score,
580
+ "keywords": keywords[:5]
581
+ }
582
+ return results
583
+
584
+ def analyze_with_bcg(prompt: str) -> dict:
585
+ prompt_lower = prompt.lower()
586
+ results = {}
587
+ for category, info in BCG_FRAMEWORK.items():
588
+ score = sum(1 for keyword in info["prompt_keywords"] if keyword.lower() in prompt_lower)
589
+ keywords = []
590
+ for keyword in info["prompt_keywords"]:
591
+ if keyword.lower() in prompt_lower:
592
+ pattern = f".{{0,15}}{keyword}.{{0,15}}"
593
+ matches = re.findall(pattern, prompt_lower, re.IGNORECASE)
594
+ for match in matches[:2]:
595
+ keywords.append(match.strip())
596
+ results[category] = {
597
+ "title": info["title"],
598
+ "description": info["description"],
599
+ "score": score,
600
+ "keywords": keywords[:5]
601
+ }
602
+ return results
603
+
604
+ def format_business_framework_analysis(framework_type: str, analysis_result: dict) -> str:
605
+ if not analysis_result:
606
+ return ""
607
+ titles = {
608
+ 'swot': '# SWOT 분석 결과',
609
+ 'porter': '# Porter의 5 Forces 분석 결과',
610
+ 'bcg': '# BCG 매트릭스 분석 결과'
611
+ }
612
+ md = f"{titles.get(framework_type, '# 경영 프레임워크 분석')}\n\n"
613
+ md += "각 요소별 텍스트 분석 점수와 관련 키워드입니다.\n\n"
614
+ for category, info in analysis_result.items():
615
+ md += f"## {info['title']}\n\n"
616
+ md += f"{info['description']}\n\n"
617
+ md += f"**관련성 점수**: {info['score']}\n\n"
618
+ if info['keywords']:
619
+ md += "**관련 키워드 및 컨텍스트**:\n"
620
+ for keyword in info['keywords']:
621
+ md += f"- *{keyword}*\n"
622
+ md += "\n"
623
+ else:
624
+ md += "관련 키워드가 발견되지 않았습니다.\n\n"
625
+ return md
626
+
627
+ # ──────────────────────────────── 마크다운 → HTML 변환 ─────────────────────────
628
+ def md_to_html(md_text: str, title: str = "Output") -> str:
629
+ html_content = markdown.markdown(
630
+ md_text,
631
+ extensions=['tables', 'fenced_code', 'codehilite']
632
+ )
633
+ return f"""<!DOCTYPE html>
634
+ <html>
635
+ <head>
636
+ <meta charset="UTF-8">
637
+ <title>{title}</title>
638
+ <style>
639
+ body {{
640
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
641
+ line-height: 1.6;
642
+ color: #333;
643
+ max-width: 800px;
644
+ margin: 0 auto;
645
+ padding: 20px;
646
+ }}
647
+ h1, h2, h3, h4, h5, h6 {{
648
+ margin-top: 24px;
649
+ margin-bottom: 16px;
650
+ font-weight: 600;
651
+ line-height: 1.25;
652
+ }}
653
+ h1 {{ font-size: 2em; color: #0366d6; }}
654
+ h2 {{ font-size: 1.5em; color: #0366d6; border-bottom: 1px solid #eaecef; padding-bottom: .3em; }}
655
+ h3 {{ font-size: 1.25em; color: #0366d6; }}
656
+ p, ul, ol {{ margin-bottom: 16px; }}
657
+ a {{ color: #0366d6; text-decoration: none; }}
658
+ a:hover {{ text-decoration: underline; }}
659
+ code {{
660
+ font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, monospace;
661
+ background-color: rgba(27, 31, 35, 0.05);
662
+ border-radius: 3px;
663
+ font-size: 85%;
664
+ padding: 0.2em 0.4em;
665
+ }}
666
+ pre {{
667
+ background-color: #f6f8fa;
668
+ border-radius: 3px;
669
+ font-size: 85%;
670
+ line-height: 1.45;
671
+ overflow: auto;
672
+ padding: 16px;
673
+ }}
674
+ pre code {{
675
+ background-color: transparent;
676
+ padding: 0;
677
+ }}
678
+ blockquote {{
679
+ border-left: 4px solid #dfe2e5;
680
+ color: #6a737d;
681
+ margin: 0;
682
+ padding: 0 1em;
683
+ }}
684
+ table {{
685
+ border-collapse: collapse;
686
+ width: 100%;
687
+ margin-bottom: 16px;
688
+ }}
689
+ table th, table td {{
690
+ border: 1px solid #dfe2e5;
691
+ padding: 6px 13px;
692
+ }}
693
+ table th {{
694
+ background-color: #f6f8fa;
695
+ font-weight: 600;
696
+ }}
697
+ img {{
698
+ max-width: 100%;
699
+ height: auto;
700
+ }}
701
+ hr {{
702
+ border: 0;
703
+ height: 1px;
704
+ background-color: #dfe2e5;
705
+ margin: 24px 0;
706
+ }}
707
+ </style>
708
+ </head>
709
+ <body>
710
+ {html_content}
711
+ <hr>
712
+ <footer>
713
+ <p><small>Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} |
714
+ Created by <a href="https://discord.gg/openfreeai" target="_blank">VIDraft</a>
715
+ </small></p>
716
+ </footer>
717
+ </body>
718
+ </html>
719
+ """
720
+
721
+ # ──────────────────────────────── 업로드 파일 처리 함수 ─────────────────────
722
+ def process_text_file(uploaded_file):
723
+ try:
724
+ content = uploaded_file.read().decode('utf-8')
725
+ return f"""# 업로드된 텍스트 파일: {uploaded_file.name}
726
+
727
+ {content}
728
+ """
729
+ except Exception as e:
730
+ logging.error(f"텍스트 파일 처리 오류: {str(e)}")
731
+ return f"**Error processing {uploaded_file.name}**: {str(e)}"
732
+
733
+ def process_csv_file(uploaded_file):
734
+ try:
735
+ df = pd.read_csv(uploaded_file)
736
+ return f"""# 업로드된 CSV 파일: {uploaded_file.name}
737
+
738
+ ## 기본 정보
739
+ - 행 수: {df.shape[0]}
740
+ - 열 수: {df.shape[1]}
741
+ - 열 이름: {', '.join(df.columns.tolist())}
742
+
743
+ ## 첫 5행 데이터 미리보기
744
+ {df.head(5).to_markdown(index=False)}
745
+
746
+ ## 기본 통계
747
+ {df.describe().to_markdown()}
748
+ """
749
+ except Exception as e:
750
+ logging.error(f"CSV 파일 처리 오류: {str(e)}")
751
+ return f"**Error processing {uploaded_file.name}**: {str(e)}"
752
+
753
+ def process_pdf_file(uploaded_file):
754
+ try:
755
+ file_bytes = uploaded_file.read()
756
+ pdf_file = io.BytesIO(file_bytes)
757
+ reader = PyPDF2.PdfReader(pdf_file, strict=False)
758
+
759
+ pages_preview = []
760
+ for page_num in range(min(5, len(reader.pages))):
761
+ page = reader.pages[page_num]
762
+ pages_preview.append(f"--- Page {page_num+1} ---\n{page.extract_text()}")
763
+
764
+ preview_text = "\n\n".join(pages_preview)
765
+ return f"""# 업로드된 PDF 파일: {uploaded_file.name}
766
+
767
+ ## 기본 정보
768
+ - 총 페이지 수: {len(reader.pages)}
769
+
770
+ ## 처음 5개 페이지 내용 미리보기
771
+ {preview_text}
772
+ """
773
+ except Exception as e:
774
+ logging.error(f"PDF 파일 처리 오류: {str(e)}")
775
+ return f"**Error processing {uploaded_file.name}**: {str(e)}"
776
+
777
+ def process_uploaded_files(uploaded_files):
778
+ """Process all uploaded files and return their content as markdown."""
779
+ if not uploaded_files:
780
+ return ""
781
+ file_contents = []
782
+ for file in uploaded_files:
783
+ try:
784
+ ext = file.name.split('.')[-1].lower()
785
+ if ext == 'txt':
786
+ file_contents.append(process_text_file(file))
787
+ file.seek(0)
788
+ elif ext == 'csv':
789
+ file_contents.append(process_csv_file(file))
790
+ file.seek(0)
791
+ elif ext == 'pdf':
792
+ file_contents.append(process_pdf_file(file))
793
+ file.seek(0)
794
+ else:
795
+ file_contents.append(
796
+ f"# Unsupported file: {file.name}\n\nThis file type is not supported for processing."
797
+ )
798
+ except Exception as e:
799
+ logging.error(f"파일 처리 오류 {file.name}: {str(e)}")
800
+ file_contents.append(f"# Error processing file: {file.name}\n\n{str(e)}")
801
+
802
+ return "\n\n# 사용자 업로드 파일 분석\n\n" + "\n\n---\n\n".join(file_contents)
803
+
804
+ # ──────────────────────────────── 이미지 생성 함수 ──────────────────────
805
+ def generate_image(prompt: str):
806
+ if not prompt:
807
+ return None, None
808
+ try:
809
+ clean_prompt = prompt.strip("\"'").strip()
810
+ if len(clean_prompt) < 3:
811
+ return None, None
812
+ logging.info(f"Sending image generation request with prompt: {clean_prompt}")
813
+
814
+ res = Client(IMAGE_API_URL).predict(
815
+ prompt=clean_prompt,
816
+ width=768,
817
+ height=768,
818
+ guidance=3.5,
819
+ inference_steps=30,
820
+ seed=3,
821
+ do_img2img=False,
822
+ init_image=None,
823
+ image2image_strength=0.8,
824
+ resize_img=True,
825
+ api_name="/generate_image"
826
+ )
827
+ if res and len(res) >= 2 and res[0]:
828
+ logging.info("Successfully received image data")
829
+ return res[0], clean_prompt
830
+ else:
831
+ logging.warning(f"Invalid response format from image API: {res}")
832
+ return None, None
833
+ except Exception as e:
834
+ logging.error(f"Image generation error: {str(e)}", exc_info=True)
835
+ return None, None
836
+
837
+ # ──────────────────────────────── Kaggle API 관련 ───────────────────────
838
+ @st.cache_resource
839
+ def check_kaggle_availability():
840
+ if not KAGGLE_API_KEY:
841
+ logging.warning("Kaggle API를 사용할 수 없습니다. (KAGGLE_KEY가 비어 있음)")
842
+ return False
843
+ return True
844
+
845
+ def extract_kaggle_search_keywords(prompt, top=3):
846
+ clean_text = re.sub(r'[^\w\s]', ' ', prompt.lower())
847
+ stop_words = {
848
+ 'the', 'a', 'an', 'in', 'on', 'at', 'of', 'for', 'to', 'by',
849
+ '와', '과', '은', '는', '이', '가', '을', '를', '에', '에서', '으로'
850
+ }
851
+ words = [word for word in clean_text.split() if word not in stop_words and len(word) > 1]
852
+ word_freq = Counter(words)
853
+ top_words = [word for word, _ in word_freq.most_common(top)]
854
+ if not top_words and words:
855
+ top_words = words[:min(top, len(words))]
856
+ return " ".join(top_words)
857
+
858
+ def search_kaggle_datasets(query: str, top: int = 5) -> list[dict]:
859
+ if not query:
860
+ return []
861
+ q_tokens = set(re.findall(r'[a-zA-Z가-힣]{2,}', query.lower()))
862
+ scored = []
863
+ for ds in KAGGLE_DATASETS.values():
864
+ tokens = set(t.lower() for t in ds["keywords"])
865
+ score = len(q_tokens & tokens)
866
+ title_hit = any(tok in ds["title"].lower() for tok in q_tokens)
867
+ sub_hit = any(tok in ds["subtitle"].lower() for tok in q_tokens)
868
+ if title_hit:
869
+ score += 2
870
+ if sub_hit:
871
+ score += 1
872
+ if score > 0:
873
+ scored.append((score, ds))
874
+ scored.sort(key=lambda x: (-x[0], x[1]["ref"]))
875
+ return [ds for _, ds in scored[:top]]
876
+
877
+ @st.cache_data
878
+ def download_and_analyze_dataset(dataset_ref: str, max_rows: int = 1000):
879
+ if not (os.getenv("KAGGLE_USERNAME") and os.getenv("KAGGLE_KEY")):
880
+ return "Kaggle API 인증정보가 없습니다."
881
+ api = KaggleApi()
882
+ api.authenticate()
883
+ tmpdir = tempfile.mkdtemp()
884
+ try:
885
+ api.dataset_download_files(dataset_ref, path=tmpdir, unzip=True)
886
+ except Exception as e:
887
+ logging.error(f"Dataset download failed ({dataset_ref}): {e}")
888
+ shutil.rmtree(tmpdir)
889
+ return f"데이터셋 다운로드 오류: {e}"
890
+
891
+ csv_files = glob.glob(f"{tmpdir}/**/*.csv", recursive=True)
892
+ if not csv_files:
893
+ shutil.rmtree(tmpdir)
894
+ return "CSV 파일을 찾을 수 없습니다."
895
+
896
+ try:
897
+ df = pd.read_csv(csv_files[0], nrows=max_rows)
898
+ analysis = {
899
+ "shape": df.shape,
900
+ "columns": df.columns.tolist(),
901
+ "head": df.head().to_dict("records"),
902
+ "describe": df.describe().to_dict(),
903
+ "missing_values": df.isnull().sum().to_dict()
904
+ }
905
+ except Exception as e:
906
+ analysis = f"CSV 파싱 오류: {e}"
907
+
908
+ shutil.rmtree(tmpdir)
909
+ return analysis
910
+
911
+ def format_kaggle_analysis_markdown_multi(analyses: list[dict]) -> str:
912
+ """
913
+ 여러 Kaggle 데이터셋(최대 3개) 메타‧분석 결과를 한꺼번에 마크다운으로 반환
914
+ analyses = [ {"meta": {...}, "analysis": {... or str}}, ... ]
915
+ """
916
+ if not analyses:
917
+ return "# Kaggle 데이터셋\n\n관련 데이터셋을 찾을 수 없습니다.\n\n"
918
+ md = "# Kaggle 데이터셋 분석 결과\n\n"
919
+ md += "다음 데이터셋을 검토하여 아이디어 형성에 참고하세요.\n\n"
920
+ for i, item in enumerate(analyses, 1):
921
+ ds = item["meta"]
922
+ ana = item["analysis"]
923
+ md += f"## {i}. {ds['title']}\n\n"
924
+ md += f"{ds['subtitle']}\n\n"
925
+ md += f"- **참조** : {ds['ref']}\n"
926
+ md += f"- **URL** : [{ds['url']}]({ds['url']})\n\n"
927
+ if isinstance(ana, dict):
928
+ md += f"**행 × 열** : {ana['shape'][0]} × {ana['shape'][1]}\n\n"
929
+ md += "<details><summary>미리보기 & 통계 (펼치기)</summary>\n\n"
930
+ try:
931
+ md += pd.DataFrame(ana["head"]).to_markdown(index=False) + "\n\n"
932
+ except:
933
+ pass
934
+ try:
935
+ md += pd.DataFrame(ana["describe"]).to_markdown() + "\n\n"
936
+ except:
937
+ pass
938
+ md += "</details>\n\n"
939
+ else:
940
+ md += f"{ana}\n\n"
941
+ md += "---\n\n"
942
+ return md
943
+
944
+ # ──────────────────────────────── OpenAI Client ──────────────────────────
945
+ @st.cache_resource
946
+ def get_openai_client():
947
+ if not OPENAI_API_KEY:
948
+ raise RuntimeError("⚠️ OPENAI_API_KEY 환경 변수가 설정되지 않았습니다.")
949
+ return OpenAI(
950
+ api_key=OPENAI_API_KEY,
951
+ timeout=60.0,
952
+ max_retries=3
953
+ )
954
+
955
+ # ──────────────────────────────── 의사결정 목적/제약 식별 (이제 디자인/발명 목적) ─────────────────────
956
+ def identify_decision_purpose(prompt: str) -> dict:
957
+ """
958
+ 디자인/발명과 관련된 주요 목적이나 제약을 대략적으로 식별.
959
+ (기존의 의사결정 목적/제약 식별 로직을 재활용하되,
960
+ design/invention 관련 키워드도 추가로 고려할 수 있음.)
961
+ """
962
+ purpose_patterns = {
963
+ 'cost_reduction': [r'비용(\s*절감)?', r'예산', r'효율', r'저렴', r'경제', r'cost', r'saving', r'budget'],
964
+ 'innovation': [r'혁신', r'새로운', r'창의', r'개발', r'발명', r'innovation', r'creative', r'develop'],
965
+ 'risk_management': [r'위험', r'리스크', r'안전', r'예방', r'대비', r'risk', r'safety', r'prevent'],
966
+ 'growth': [r'성장', r'확장', r'증가', r'확대', r'매출', r'growth', r'expand', r'increase', r'scale'],
967
+ 'customer': [r'고객', r'사용자', r'만족', r'경험', r'서비스', r'customer', r'user', r'experience']
968
+ }
969
+ constraint_patterns = {
970
+ 'time': [r'시간', r'빠르게', r'긴급', r'마감', r'기한', r'time', r'deadline', r'urgent'],
971
+ 'budget': [r'저예산', r'자금', r'투자', r'재정', r'budget', r'finance', r'fund', r'investment'],
972
+ 'resources': [r'자원', r'인력', r'장비', r'제한', r'resource', r'staff', r'equipment', r'limited'],
973
+ 'regulation': [r'규제', r'법률', r'규정', r'준수', r'법적', r'regulation', r'legal', r'compliance']
974
+ }
975
+ purpose_scores = {}
976
+ for purpose, patterns in purpose_patterns.items():
977
+ score = sum(1 for pattern in patterns if re.search(pattern, prompt, re.IGNORECASE))
978
+ if score > 0:
979
+ purpose_scores[purpose] = score
980
+ constraint_scores = {}
981
+ for constraint, patterns in constraint_patterns.items():
982
+ score = sum(1 for pattern in patterns if re.search(pattern, prompt, re.IGNORECASE))
983
+ if score > 0:
984
+ constraint_scores[constraint] = score
985
+ main_purposes = sorted(purpose_scores.items(), key=lambda x: x[1], reverse=True)[:2]
986
+ main_constraints = sorted(constraint_scores.items(), key=lambda x: x[1], reverse=True)[:2]
987
+ return {
988
+ 'purposes': main_purposes,
989
+ 'constraints': main_constraints,
990
+ 'all_purpose_scores': purpose_scores,
991
+ 'all_constraint_scores': constraint_scores
992
+ }
993
+
994
+ # ──────────────────────────────── 카테고리 유틸 ─────────────────────────
995
+ def keywords(text: str, top: int = 8) -> str:
996
+ words = re.findall(r'\b[a-zA-Z가-힣]{2,}\b', text.lower())
997
+ stopwords = {
998
+ 'the', 'a', 'an', 'of', 'to', 'in', 'for', 'on', 'by', 'and', 'is', 'are', 'was', 'were',
999
+ 'be', 'been', 'being', 'with', 'as', 'at', 'that', 'this', 'these', 'those', 'from', 'not',
1000
+ '이', '그', '저', '것', '수', '등', '를', '을', '에', '에서', '그리고', '하는', '있는', '것은',
1001
+ '있다', '그것', '또한', '또', '및', '이런', '그런', '무엇', '어떤', '많은', '한', '두', '몇'
1002
+ }
1003
+ words = [word for word in words if word not in stopwords]
1004
+ word_freq = {}
1005
+ for word in words:
1006
+ word_freq[word] = word_freq.get(word, 0) + 1
1007
+ sorted_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)
1008
+ top_words = [word for word, _ in sorted_words[:top]]
1009
+ return ' '.join(top_words)
1010
+
1011
+ def compute_relevance_scores(prompt: str, categories: list[Category]) -> dict:
1012
+ """
1013
+ 디자인/발명 관점에서, 입력 프롬프트가 어떤 카테고리의 항목들과 관련성이 높은지 스코어링.
1014
+ """
1015
+ prompt_lower = prompt.lower()
1016
+ prompt_tokens = set(re.findall(r'\b[a-zA-Z가-힣]{2,}\b', prompt_lower))
1017
+ purpose_keywords = {
1018
+ 'cost_reduction': ['비용', '절감', '효율', '예산', 'cost', 'saving', 'budget', 'efficiency'],
1019
+ 'innovation': ['혁신', '창의', '신규', '개발', 'innovation', 'creative', 'novel', 'development', '발명', '디자인'],
1020
+ 'risk_management': ['위험', '리스크', '관리', '예방', 'risk', 'management', 'prevention', 'mitigation'],
1021
+ 'growth': ['성장', '확장', '증가', '규모', 'growth', 'expansion', 'increase', 'scale'],
1022
+ 'customer': ['사용자', '고객', '만족', '경험', 'user', 'customer', 'satisfaction', 'experience']
1023
+ }
1024
+ purpose_scores = {}
1025
+ for purpose, keywords_ in purpose_keywords.items():
1026
+ score = sum(1 for kw in keywords_ if kw in prompt_lower)
1027
+ if score > 0:
1028
+ purpose_scores[purpose] = score
1029
+ main_purpose = max(purpose_scores.items(), key=lambda x: x[1])[0] if purpose_scores else None
1030
+
1031
+ relevance_scores = {}
1032
+ for category in categories:
1033
+ cat_score = sum(1 for tag in category.tags if tag in prompt_lower) * 0.5
1034
+ if category.name_ko in prompt or category.name_en.lower() in prompt_lower:
1035
+ cat_score += 1
1036
+
1037
+ # 약간의 목적별 가중치 적용
1038
+ if main_purpose:
1039
+ purpose_category_weights = {
1040
+ 'cost_reduction': {
1041
+ '구조적 변화': 1.5, '화학적 변화': 1.3, '비즈니스 아이디어': 1.5,
1042
+ },
1043
+ 'innovation': {
1044
+ '센서 기능': 1.5, '표면 및 외관 변화': 1.3, '비즈니스 아이디어': 1.5,
1045
+ },
1046
+ 'risk_management': {
1047
+ '환경 상호작용': 1.5, '시간 관련 변화': 1.3, '비즈니스 아이디어': 1.4,
1048
+ },
1049
+ 'growth': {
1050
+ '크기와 형태 변화': 1.4, '비즈니스 아이디어': 1.6, '구조적 변화': 1.3,
1051
+ },
1052
+ 'customer': {
1053
+ '표면 및 외관 변화': 1.5, '센서 기능': 1.4, '빛과 시각 효과': 1.3, '비즈니스 아이디어': 1.4,
1054
+ }
1055
+ }
1056
+ if category.name_ko in purpose_category_weights.get(main_purpose, {}):
1057
+ cat_score *= purpose_category_weights[main_purpose][category.name_ko]
1058
+ elif category.name_en in purpose_category_weights.get(main_purpose, {}):
1059
+ cat_score *= purpose_category_weights[main_purpose][category.name_en]
1060
+
1061
+ # 항목별 토큰 매칭
1062
+ for item in category.items:
1063
+ item_score = cat_score
1064
+ item_tokens = set(re.findall(r'\b[a-zA-Z가-힣]{2,}\b', item.lower()))
1065
+ matches = item_tokens.intersection(prompt_tokens)
1066
+ if matches:
1067
+ item_score += len(matches) * 0.3
1068
+ if item_score > 0:
1069
+ relevance_scores[(category.name_ko, item)] = item_score
1070
+ return relevance_scores
1071
+
1072
+ def compute_score(weight: int, impact: int, confidence: float) -> float:
1073
+ return round(weight * impact * confidence, 2)
1074
+
1075
+ def generate_comparison_matrix(
1076
+ categories: list[Category],
1077
+ relevance_scores: dict = None,
1078
+ max_depth: int = 3,
1079
+ max_combinations: int = 100,
1080
+ relevance_threshold: float = 0.2
1081
+ ) -> list[tuple]:
1082
+ """
1083
+ 여러 카테고리의 요소를 복합적으로 조합한 '아이디어' 후보를 뽑아내는 매트릭스.
1084
+ (본래 의사결정 매트릭스였으나, 디자인/발명에 맞게 재활용)
1085
+ """
1086
+ if relevance_scores is None:
1087
+ pool = [(c.name_ko, item) for c in categories for item in c.items]
1088
+ basic_combos = []
1089
+ for depth in range(2, max_depth + 1):
1090
+ for combo in combinations(pool, depth):
1091
+ basic_combos.append((1, 1, 1.0, 1.0, combo))
1092
+ if len(basic_combos) >= max_combinations:
1093
+ break
1094
+ return basic_combos[:max_combinations]
1095
+
1096
+ filtered_pool = [
1097
+ (cat, item) for (cat, item), score in relevance_scores.items()
1098
+ if score >= relevance_threshold
1099
+ ]
1100
+ if not filtered_pool:
1101
+ pool = [(c.name_ko, i) for c in categories for i in c.items]
1102
+ if len(pool) > 200:
1103
+ import random
1104
+ filtered_pool = random.sample(pool, 200)
1105
+ else:
1106
+ filtered_pool = pool
1107
+
1108
+ evaluated_combinations = []
1109
+ for depth in range(2, max_depth + 1):
1110
+ for combo in combinations(filtered_pool, depth):
1111
+ if len({item[0] for item in combo}) == depth:
1112
+ combo_relevance = sum(relevance_scores.get((item[0], item[1]), 0) for item in combo) / depth
1113
+ weight = min(5, max(1, int(combo_relevance * 2)))
1114
+ impact = min(5, depth)
1115
+ confidence = min(1.0, combo_relevance / 2.5)
1116
+ total_score = compute_score(weight, impact, confidence)
1117
+ evaluated_combinations.append((weight, impact, confidence, total_score, combo))
1118
+ evaluated_combinations.sort(key=lambda x: x[3], reverse=True)
1119
+ return evaluated_combinations[:max_combinations]
1120
+
1121
+ # ──────────────────────────────── Diverse Matrix Generator ────────────────────
1122
+ def smart_weight(cat_name, item, relevance, global_cnt, T):
1123
+ rare_boost = 1 / (global_cnt.get(item, 0) + 0.5)
1124
+ noise = random.random() ** (1 / T) # T가 클수록 noise가 1에 가까움
1125
+ relevance_weight = 1 - (T - 0.1) / 3.0
1126
+ return ((relevance * relevance_weight) + 0.1) * rare_boost * noise
1127
+
1128
+ def generate_random_comparison_matrix(
1129
+ categories: list[Category],
1130
+ relevance_scores: dict | None = None,
1131
+ k_cat=(8, 12),
1132
+ n_item=(6, 10),
1133
+ depth_range=(3, 6),
1134
+ max_combos=1000,
1135
+ seed: int | None = None,
1136
+ T: float = 1.3,
1137
+ ):
1138
+ """
1139
+ 다양성 있게 여러 카테고리/항목들을 조합하여 무작위 매트릭스를 생성.
1140
+ (디자인/발명 아이디어 확장 시 유용)
1141
+ """
1142
+ if seed is None:
1143
+ seed = random.randrange(2 ** 32)
1144
+ random.seed(seed)
1145
+ if "GLOBAL_PICK_COUNT" not in st.session_state:
1146
+ st.session_state.GLOBAL_PICK_COUNT = {}
1147
+ global_cnt = st.session_state.GLOBAL_PICK_COUNT
1148
+
1149
+ k = random.randint(*k_cat)
1150
+ sampled_cats = random.sample(categories, k)
1151
+ pool = []
1152
+ for cat in sampled_cats:
1153
+ items = cat.items
1154
+ weights = [
1155
+ smart_weight(
1156
+ cat.name_ko,
1157
+ it,
1158
+ relevance_scores.get((cat.name_ko, it), 0.05) if relevance_scores else 0.05,
1159
+ global_cnt,
1160
+ T
1161
+ )
1162
+ for it in items
1163
+ ]
1164
+ n = min(len(items), random.randint(*n_item))
1165
+ sampled_items = random.choices(items, weights=weights, k=n)
1166
+ for it in sampled_items:
1167
+ global_cnt[it] = global_cnt.get(it, 0) + 1
1168
+ pool.append((cat.name_ko, it))
1169
+ combos = []
1170
+ for d in range(depth_range[0], depth_range[1] + 1):
1171
+ for combo in combinations(pool, d):
1172
+ if len({c for c, _ in combo}) != d:
1173
+ continue
1174
+ w = sum(relevance_scores.get((c, i), 0.2) if relevance_scores else 1 for c, i in combo) / d
1175
+ imp = d
1176
+ conf = 0.5 + random.random() * 0.5
1177
+ total = compute_score(w, imp, conf)
1178
+ combos.append((w, imp, conf, total, combo))
1179
+ combos.sort(key=lambda x: x[3], reverse=True)
1180
+ return combos[:max_combos]
1181
+
1182
+ # ──────────────────────────────── PHYS_CATEGORIES ────────────────────────
1183
+ PHYS_CATEGORIES: list[Category] = [
1184
+ Category(
1185
+ name_ko="센서 기능",
1186
+ name_en="Sensor Functions",
1187
+ tags=["sensor", "detection", "감지"],
1188
+ items=physical_transformation_categories["센서 기능"]
1189
+ ),
1190
+ Category(
1191
+ name_ko="크기와 형태 변화",
1192
+ name_en="Size and Shape Change",
1193
+ tags=["shape", "geometry", "크기"],
1194
+ items=physical_transformation_categories["크기와 형태 변화"]
1195
+ ),
1196
+ Category(
1197
+ name_ko="표면 및 외관 변화",
1198
+ name_en="Surface and Appearance Change",
1199
+ tags=["surface", "appearance", "표면"],
1200
+ items=physical_transformation_categories["표면 및 외관 변화"]
1201
+ ),
1202
+ Category(
1203
+ name_ko="물질의 상태 변화",
1204
+ name_en="Material State Change",
1205
+ tags=["material", "state", "상태"],
1206
+ items=physical_transformation_categories["물질의 상태 변화"]
1207
+ ),
1208
+ Category(
1209
+ name_ko="움직임 특성 변화",
1210
+ name_en="Movement Characteristics Change",
1211
+ tags=["motion", "dynamics", "움직임"],
1212
+ items=physical_transformation_categories["움직임 특성 변화"]
1213
+ ),
1214
+ Category(
1215
+ name_ko="구조적 변화",
1216
+ name_en="Structural Change",
1217
+ tags=["structure", "form", "구조"],
1218
+ items=physical_transformation_categories["구조적 변화"]
1219
+ ),
1220
+ Category(
1221
+ name_ko="공간 이동",
1222
+ name_en="Spatial Movement",
1223
+ tags=["movement", "space", "이동"],
1224
+ items=physical_transformation_categories["공간 이동"]
1225
+ ),
1226
+ Category(
1227
+ name_ko="시간 관련 변화",
1228
+ name_en="Time-Related Change",
1229
+ tags=["time", "aging", "시간"],
1230
+ items=physical_transformation_categories["시간 관련 변화"]
1231
+ ),
1232
+ Category(
1233
+ name_ko="빛과 시각 효과",
1234
+ name_en="Light and Visual Effects",
1235
+ tags=["light", "visual", "빛"],
1236
+ items=physical_transformation_categories["빛과 시각 효과"]
1237
+ ),
1238
+ Category(
1239
+ name_ko="소리와 진동 효과",
1240
+ name_en="Sound and Vibration Effects",
1241
+ tags=["sound", "vibration", "소리"],
1242
+ items=physical_transformation_categories["소리와 진동 효과"]
1243
+ ),
1244
+ Category(
1245
+ name_ko="열 관련 변화",
1246
+ name_en="Thermal Changes",
1247
+ tags=["heat", "thermal", "온도"],
1248
+ items=physical_transformation_categories["열 관련 변화"]
1249
+ ),
1250
+ Category(
1251
+ name_ko="전기 및 자기 변화",
1252
+ name_en="Electrical and Magnetic Changes",
1253
+ tags=["electric", "magnetic", "전기"],
1254
+ items=physical_transformation_categories["전기 및 자기 변화"]
1255
+ ),
1256
+ Category(
1257
+ name_ko="화학적 변화",
1258
+ name_en="Chemical Change",
1259
+ tags=["chemical", "reaction", "화학"],
1260
+ items=physical_transformation_categories["화학적 변화"]
1261
+ ),
1262
+ Category(
1263
+ name_ko="생물학적 변화",
1264
+ name_en="Biological Change",
1265
+ tags=["bio", "living", "생물"],
1266
+ items=physical_transformation_categories["생물학적 변화"]
1267
+ ),
1268
+ Category(
1269
+ name_ko="환경 상호작용",
1270
+ name_en="Environmental Interaction",
1271
+ tags=["environment", "interaction", "환경"],
1272
+ items=physical_transformation_categories["환경 상호작용"]
1273
+ ),
1274
+ Category(
1275
+ name_ko="비즈니스 아이디어",
1276
+ name_en="Business Ideas",
1277
+ tags=["business", "idea", "비즈니스"],
1278
+ items=physical_transformation_categories["비즈니스 아이디어"]
1279
+ ),
1280
+ Category(
1281
+ name_ko="사용자 인터페이스 및 상호작용",
1282
+ name_en="User Interface and Interaction",
1283
+ tags=["interface", "interaction", "인터페이스"],
1284
+ items=physical_transformation_categories["사용자 인터페이스 및 상호작용"]
1285
+ ),
1286
+ Category(
1287
+ name_ko="데이터 및 정보 변환",
1288
+ name_en="Data and Information Transformation",
1289
+ tags=["data", "information", "데이터"],
1290
+ items=physical_transformation_categories["데이터 및 정보 변환"]
1291
+ ),
1292
+ Category(
1293
+ name_ko="인지 및 심리적 변화",
1294
+ name_en="Cognitive and Psychological Changes",
1295
+ tags=["cognitive", "psychology", "인지"],
1296
+ items=physical_transformation_categories["인지 및 심리적 변화"]
1297
+ ),
1298
+ Category(
1299
+ name_ko="에너지 변환 및 관리",
1300
+ name_en="Energy Conversion and Management",
1301
+ tags=["energy", "power", "에너지"],
1302
+ items=physical_transformation_categories["에너지 변환 및 관리"]
1303
+ ),
1304
+ Category(
1305
+ name_ko="지속가��성 및 환경 영향",
1306
+ name_en="Sustainability and Environmental Impact",
1307
+ tags=["sustainability", "eco", "지속가능"],
1308
+ items=physical_transformation_categories["지속가능성 및 환경 영향"]
1309
+ ),
1310
+ Category(
1311
+ name_ko="보안 및 프라이버시",
1312
+ name_en="Security and Privacy",
1313
+ tags=["security", "privacy", "보안"],
1314
+ items=physical_transformation_categories["보안 및 프라이버시"]
1315
+ ),
1316
+ Category(
1317
+ name_ko="사회적 상호작용 및 협업",
1318
+ name_en="Social Interaction and Collaboration",
1319
+ tags=["social", "collaboration", "협업"],
1320
+ items=physical_transformation_categories["사회적 상호작용 및 협업"]
1321
+ ),
1322
+ Category(
1323
+ name_ko="미학 및 감성 경험",
1324
+ name_en="Aesthetics and Emotional Experience",
1325
+ tags=["aesthetics", "emotion", "감성"],
1326
+ items=physical_transformation_categories["미학 및 감성 경험"]
1327
+ )
1328
+ ]
1329
+
1330
+ # ──────────────────────────────── 시스템 프롬프트 생성 ─────────────────────
1331
+ def get_idea_system_prompt(selected_category: str | None = None,
1332
+ selected_frameworks: list | None = None) -> str:
1333
+ """
1334
+ [디자인/발명 전용] 시스템 프롬프트.
1335
+ """
1336
+ cat_clause = (
1337
+ f'\n**추가 지침**: 선택된 카테고리 "{selected_category}"에 특별한 주의를 기울이십시오. '
1338
+ f'이 카테고리의 항목들을 아이디어 발상 전 과정에 우선 고려하세요.\n'
1339
+ ) if selected_category else ""
1340
+
1341
+ # (기존에 'sunzi','swot','porter','bcg' 등 사용했으나, 이제 디자인/발명 위주이므로 최소화)
1342
+ if not selected_frameworks:
1343
+ selected_frameworks = []
1344
+
1345
+ # 새 목적: 디자인/발명 아이디어 착안
1346
+ framework_instruction = "\n\n### (디자인/발명) 활용 프레임워크\n"
1347
+ framework_output_format = ""
1348
+
1349
+ # 프레임워크 사용 예시(원한다면 "sunzi" 등 사용 가능)
1350
+ for fw in selected_frameworks:
1351
+ if fw == "sunzi":
1352
+ framework_instruction += "- **손자병법 36계**: 창의적 전략으로 발명 아이디어에 적용\n"
1353
+ framework_output_format += """
1354
+ ## 손자병법 관점에서의 창의 아이디어
1355
+ (원하는 경우에 사용)
1356
+ """
1357
+ elif fw == "swot":
1358
+ framework_instruction += "- **SWOT 분석**: 내부/외부 요소 고려하여 발명 방향성 탐색\n"
1359
+ elif fw == "porter":
1360
+ framework_instruction += "- **Porter의 5 Forces**: 시장/환경 관점에서 디자인 요구 파악\n"
1361
+ elif fw == "bcg":
1362
+ framework_instruction += "- **BCG 매트릭스**: 발명 아이템 포트폴리오적 관점으로 접근\n"
1363
+
1364
+ base_prompt = f"""
1365
+ 당신은 창의적 디자인/발명 전문가 AI입니다.
1366
+ 사용자의 텍스트(질문이나 아이디어 방향)를 분석하여, **새로운 발명/디자인 아이디어**를 구체적으로 제시하고,
1367
+ 필요하다면 여러 관련 **데이터/자료**를 활용하여 통찰력을 보강하십시오.
1368
+
1369
+ 1) 문제/목표 분석:
1370
+ - 사용자가 말한 디자인/발명 목적·키워드를 파악,
1371
+ - 연관되는 카테고리 및 항목 식별
1372
+
1373
+ 2) 카테고리 매핑 및 아이디어 스케치:
1374
+ - 다양한 물리적/화학적/구조적/환경적 범주의 요소가 어떻게 아이디어에 적용 가능한지 서술
1375
+ - 관련 데이터(웹검색, Kaggle 등)도 참조 가능
1376
+
1377
+ 3) 종합 아이디어 제안:
1378
+ - 상위 2~3가지 주요 디자인/발명 방향 제시
1379
+ - 구체적으로 구현 가능성, 예상 기능, 장단점, 확장성, 위험 요소 등 분석
1380
+
1381
+ {framework_instruction}
1382
+
1383
+ ### 최종 출력 형식 (마크다운)
1384
+ - **핵심 목표/키워드**: (사용자 질문 요약)
1385
+ - **연관 카테고리 요소**: 표 형식 또는 나열
1386
+ - **아이디어 스케치**: (각 아이디어별 개념, 특징, 시나리오)
1387
+ - **예상 문제/리스크**: (기술·비용·윤리 등)
1388
+ - **실행 단계**: (프로토타입, 테스트, 검증, 런칭)
1389
+ - **추가 아이디어/참고**: (옵션)
1390
+
1391
+ {framework_output_format}
1392
+ {cat_clause}
1393
+
1394
+ **모든 답변은 한국어**로 작성.
1395
+ 중간 사고 과정을 내부적으로 수행하되, 최종 답변만 출력.
1396
+ 웹 검색 및 Kaggle 데이터셋 분석도 통합하여 아이디어 품질을 높이십시오.
1397
+ """
1398
+ return base_prompt.strip()
1399
+
1400
+ # ──────────────────────────────── Brave Search API ───────────────────────
1401
+ @st.cache_data(ttl=3600)
1402
+ def brave_search(query: str, count: int = 20):
1403
+ if not BRAVE_KEY:
1404
+ raise RuntimeError("⚠️ SERPHOUSE_API_KEY (Brave API Key) 환경 변수가 비어있습니다.")
1405
+ headers = {
1406
+ "Accept": "application/json",
1407
+ "Accept-Encoding": "gzip",
1408
+ "X-Subscription-Token": BRAVE_KEY
1409
+ }
1410
+ params = {"q": query, "count": str(count)}
1411
+ for attempt in range(3):
1412
+ try:
1413
+ r = requests.get(BRAVE_ENDPOINT, headers=headers, params=params, timeout=15)
1414
+ r.raise_for_status()
1415
+ data = r.json()
1416
+ raw = data.get("web", {}).get("results") or data.get("results", [])
1417
+ if not raw:
1418
+ raise ValueError("No search results found.")
1419
+ arts = []
1420
+ for i, res in enumerate(raw[:count], 1):
1421
+ url = res.get("url", res.get("link", ""))
1422
+ host = re.sub(r"https?://(www\.)?", "", url).split("/")[0]
1423
+ arts.append({
1424
+ "index": i,
1425
+ "title": res.get("title", "No title"),
1426
+ "link": url,
1427
+ "snippet": res.get("description", res.get("text", "No snippet")),
1428
+ "displayed_link": host
1429
+ })
1430
+ return arts
1431
+ except Exception as e:
1432
+ logging.error(f"Brave search failure (attempt {attempt+1}/3): {e}")
1433
+ time.sleep(1)
1434
+ return []
1435
+
1436
+ def mock_results(query: str) -> str:
1437
+ ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
1438
+ return (
1439
+ f"# Fallback Search Content (Generated: {ts})\n\n"
1440
+ f"The web search API request failed. Please generate the invention/design ideas based on '{query}' using general knowledge.\n\n"
1441
+ f"You may consider aspects such as:\n\n"
1442
+ f"- Basic concept or definition of {query}\n"
1443
+ f"- Potential expansions or improvements\n"
1444
+ f"- Category-based transformations\n\n"
1445
+ f"Note: This is fallback text, not real-time data.\n\n"
1446
+ )
1447
+
1448
+ def do_web_search(query: str) -> str:
1449
+ try:
1450
+ arts = brave_search(query, 20)
1451
+ if not arts:
1452
+ logging.warning("No search results from Brave. Using fallback.")
1453
+ return mock_results(query)
1454
+ hdr = "# Web Search Results\nUse the information below to spark new design/invention insights.\n\n"
1455
+ body = "\n".join(
1456
+ f"### Result {a['index']}: {a['title']}\n\n{a['snippet']}\n\n**Source**: [{a['displayed_link']}]({a['link']})\n\n---\n"
1457
+ for a in arts
1458
+ )
1459
+ return hdr + body
1460
+ except Exception as e:
1461
+ logging.error(f"Web search process failed: {str(e)}")
1462
+ return mock_results(query)
1463
+
1464
+ # ──────────────────────────────── (신규) 디자인/발명 아이디어 처리 함수 ─────────────────
1465
+ def process_invention_ideas(keyword: str):
1466
+ """
1467
+ (이전에는 별도 버튼/프롬프트가 있었으나,
1468
+ 이제 메인 프롬프트로 일원화되어 사실상 사용되지 않을 수도 있음.)
1469
+ """
1470
+ if not keyword.strip():
1471
+ st.warning("키워드를 입력하세요.")
1472
+ return
1473
+
1474
+ st.info(f"디자인/발명 아이디어 생성 중... (키워드: **{keyword}**)")
1475
+
1476
+ # 모든 카테고리와 항목을 리스트업
1477
+ categories_text = []
1478
+ for cat_name, items in physical_transformation_categories.items():
1479
+ joined_items = ", ".join(items)
1480
+ categories_text.append(f"- {cat_name}: {joined_items}")
1481
+ categories_joined = "\n".join(categories_text)
1482
+
1483
+ prompt = f"""
1484
+ 당신은 디자인/발명 전문가입니다.
1485
+ 키워드: "{keyword}"
1486
+ 아래는 카테고리+항목 목록입니다.
1487
+ {categories_joined}
1488
+
1489
+ 이 키워드를 각 항목과 결합한 아이디어를 생각하고,
1490
+ 타당한 것과 배제할 것을 분류하여 마크다운으로 출력하세요.
1491
+ """
1492
+ try:
1493
+ client = get_openai_client()
1494
+ with st.spinner("Generating invention ideas..."):
1495
+ response = client.chat.completions.create(
1496
+ model="gpt-4.1-mini",
1497
+ messages=[{"role": "user", "content": prompt}],
1498
+ temperature=0.9,
1499
+ max_tokens=2500,
1500
+ )
1501
+ result_text = response.choices[0].message.content
1502
+ st.markdown(result_text)
1503
+ except Exception as e:
1504
+ st.error(f"오류 발생: {e}")
1505
+
1506
+ # ──────────────────────────────── Streamlit 메인 앱 ──────────────────────
1507
+ def idea_generator_app():
1508
+ st.title("Ilúvatar(일루바타르) : Creative Design & Invention AI")
1509
+ st.caption("이 시스템은 빅데이터를 자율적으로 수집·분석하여, 복합적인 디자인/발명 아이디어를 제안합니다.")
1510
+
1511
+ default_vals = {
1512
+ "ai_model": "gpt-4.1-mini",
1513
+ "messages": [],
1514
+ "auto_save": True,
1515
+ "generate_image": True,
1516
+ "web_search_enabled": True,
1517
+ "kaggle_enabled": True,
1518
+ "selected_frameworks": [],
1519
+ "GLOBAL_PICK_COUNT": {},
1520
+ "_skip_dup_idx": None
1521
+ }
1522
+ for k, v in default_vals.items():
1523
+ if k not in st.session_state:
1524
+ st.session_state[k] = v
1525
+
1526
+ sb = st.sidebar
1527
+ st.session_state.temp = sb.slider(
1528
+ "Diversity temperature", 0.1, 3.0, 1.3, 0.1,
1529
+ help="0.1 = 매우 보수적, 3.0 = 매우 창의/무작위"
1530
+ )
1531
+
1532
+ sb.title("Settings")
1533
+ sb.toggle("Auto Save", key="auto_save")
1534
+ sb.toggle("Auto Image Generation", key="generate_image")
1535
+
1536
+ st.session_state.web_search_enabled = sb.toggle(
1537
+ "Use Web Search", value=st.session_state.web_search_enabled
1538
+ )
1539
+ st.session_state.kaggle_enabled = sb.toggle(
1540
+ "Use Kaggle Datasets", value=st.session_state.kaggle_enabled
1541
+ )
1542
+
1543
+ if st.session_state.web_search_enabled:
1544
+ sb.info("✅ Web search results enabled")
1545
+ if st.session_state.kaggle_enabled:
1546
+ if KAGGLE_KEY:
1547
+ sb.info("✅ Kaggle data integration enabled")
1548
+ else:
1549
+ sb.error("⚠️ KAGGLE_KEY not set.")
1550
+ st.session_state.kaggle_enabled = False
1551
+
1552
+ # (디자인/발명용 사이드바 항목은 삭제됨, 메인 prompt에서 처리)
1553
+
1554
+ # 예시 주제
1555
+ example_topics = {
1556
+ "example1": "스마트홈에서 사용할 차세대 가전제품 발명 아이디어",
1557
+ "example2": "지속가능한 소재를 활용한 패션 디자인 컨셉",
1558
+ "example3": "사용자 인터페이스(UI/UX) 혁신을 위한 웨어러블 기기 아이디어"
1559
+ }
1560
+ sb.subheader("Example Topics")
1561
+ c1, c2, c3 = sb.columns(3)
1562
+ if c1.button("가전제품 발명", key="ex1"):
1563
+ process_example(example_topics["example1"])
1564
+ if c2.button("친환경 패션 디자인", key="ex2"):
1565
+ process_example(example_topics["example2"])
1566
+ if c3.button("UI/UX 혁신", key="ex3"):
1567
+ process_example(example_topics["example3"])
1568
+
1569
+ # 대화 히스토리 다운로드
1570
+ latest_ideas = next(
1571
+ (m["content"] for m in reversed(st.session_state.messages)
1572
+ if m["role"] == "assistant" and m["content"].strip()),
1573
+ None
1574
+ )
1575
+ if latest_ideas:
1576
+ title_match = re.search(r"# (.*?)(\n|$)", latest_ideas)
1577
+ title = (title_match.group(1) if title_match else "design_invention").strip()
1578
+ sb.subheader("Download Latest Ideas")
1579
+ d1, d2 = sb.columns(2)
1580
+ d1.download_button("Download as Markdown", latest_ideas,
1581
+ file_name=f"{title}.md", mime="text/markdown")
1582
+ d2.download_button("Download as HTML", md_to_html(latest_ideas, title),
1583
+ file_name=f"{title}.html", mime="text/html")
1584
+
1585
+ # 대화 히스토리 로드/저장
1586
+ up = sb.file_uploader("Load Conversation (.json)", type=["json"], key="json_uploader")
1587
+ if up:
1588
+ try:
1589
+ st.session_state.messages = json.load(up)
1590
+ sb.success("Conversation history loaded successfully")
1591
+ except Exception as e:
1592
+ sb.error(f"Failed to load: {e}")
1593
+
1594
+ if sb.button("Download Conversation as JSON"):
1595
+ sb.download_button(
1596
+ "Save JSON",
1597
+ data=json.dumps(st.session_state.messages, ensure_ascii=False, indent=2),
1598
+ file_name="chat_history.json",
1599
+ mime="application/json"
1600
+ )
1601
+
1602
+ # 파일 업로드
1603
+ st.subheader("File Upload (Optional)")
1604
+ uploaded_files = st.file_uploader(
1605
+ "Upload reference files (txt, csv, pdf)",
1606
+ type=["txt", "csv", "pdf"],
1607
+ accept_multiple_files=True,
1608
+ key="file_uploader"
1609
+ )
1610
+ if uploaded_files:
1611
+ st.success(f"{len(uploaded_files)} files uploaded.")
1612
+ with st.expander("Preview Uploaded Files", expanded=False):
1613
+ for idx, file in enumerate(uploaded_files):
1614
+ st.write(f"**File Name:** {file.name}")
1615
+ ext = file.name.split('.')[-1].lower()
1616
+ try:
1617
+ if ext == 'txt':
1618
+ preview = file.read(1000).decode('utf-8', errors='ignore')
1619
+ file.seek(0)
1620
+ st.text_area("Preview", preview + ("..." if len(preview) >= 1000 else ""), height=150)
1621
+ elif ext == 'csv':
1622
+ df = pd.read_csv(file)
1623
+ file.seek(0)
1624
+ st.dataframe(df.head(5))
1625
+ elif ext == 'pdf':
1626
+ reader = PyPDF2.PdfReader(io.BytesIO(file.read()), strict=False)
1627
+ file.seek(0)
1628
+ pg_txt = reader.pages[0].extract_text() if reader.pages else "(No text)"
1629
+ st.text_area("Preview", (pg_txt[:500] + "...") if pg_txt else "(No text)", height=150)
1630
+ except Exception as e:
1631
+ st.error(f"Preview failed: {e}")
1632
+ if idx < len(uploaded_files) - 1:
1633
+ st.divider()
1634
+
1635
+ # 이미 렌더된 메시지(중복 방지)
1636
+ skip_idx = st.session_state.get("_skip_dup_idx")
1637
+ for i, m in enumerate(st.session_state.messages):
1638
+ if skip_idx is not None and i == skip_idx:
1639
+ continue
1640
+ with st.chat_message(m["role"]):
1641
+ st.markdown(m["content"])
1642
+ if "image" in m:
1643
+ st.image(m["image"], caption=m.get("image_caption", ""))
1644
+ st.session_state["_skip_dup_idx"] = None
1645
+
1646
+ # 메인 채팅 입력
1647
+ prompt = st.chat_input("새로운 디자인/발명 아이디어가 필요하신가요? 여기에 상황이나 목표를 작성하세요!")
1648
+ if prompt:
1649
+ process_input(prompt, uploaded_files)
1650
+
1651
+ sb.markdown("---")
1652
+ sb.markdown("Created by [VIDraft](https://discord.gg/openfreeai)")
1653
+
1654
+ def process_example(topic):
1655
+ process_input(topic, [])
1656
+
1657
+ def process_input(prompt: str, uploaded_files):
1658
+ """
1659
+ 메인 채팅 입력을 받아 디자인/발명 아이디어를 생성한다.
1660
+ """
1661
+ if not any(m["role"] == "user" and m["content"] == prompt for m in st.session_state.messages):
1662
+ st.session_state.messages.append({"role": "user", "content": prompt})
1663
+ with st.chat_message("user"):
1664
+ st.markdown(prompt)
1665
+
1666
+ for i in range(len(st.session_state.messages) - 1):
1667
+ if (st.session_state.messages[i]["role"] == "user"
1668
+ and st.session_state.messages[i]["content"] == prompt
1669
+ and st.session_state.messages[i + 1]["role"] == "assistant"):
1670
+ return
1671
+
1672
+ with st.chat_message("assistant"):
1673
+ status = st.status("Preparing to generate invention ideas…")
1674
+ stream_placeholder = st.empty()
1675
+ full_response = ""
1676
+
1677
+ try:
1678
+ client = get_openai_client()
1679
+ status.update(label="Initializing model…")
1680
+
1681
+ selected_cat = st.session_state.get("category_focus", None)
1682
+ selected_frameworks = st.session_state.get("selected_frameworks", [])
1683
+
1684
+ # 목적이 "디자인/발명"이므로, system prompt 변경
1685
+ sys_prompt = get_idea_system_prompt(
1686
+ selected_category=selected_cat,
1687
+ selected_frameworks=selected_frameworks
1688
+ )
1689
+
1690
+ def category_context(sel):
1691
+ if sel:
1692
+ return json.dumps({sel: physical_transformation_categories[sel]}, ensure_ascii=False)
1693
+ return "ALL_CATEGORIES: " + ", ".join(physical_transformation_categories.keys())
1694
+
1695
+ use_web_search = st.session_state.web_search_enabled
1696
+ use_kaggle = st.session_state.kaggle_enabled
1697
+ has_uploaded = bool(uploaded_files)
1698
+
1699
+ search_content = None
1700
+ kaggle_content = None
1701
+ file_content = None
1702
+
1703
+ # ① 웹검색
1704
+ if use_web_search:
1705
+ status.update(label="Searching the web…")
1706
+ with st.spinner("Searching…"):
1707
+ search_content = do_web_search(keywords(prompt, top=5))
1708
+
1709
+ # ② Kaggle
1710
+ if use_kaggle and check_kaggle_availability():
1711
+ status.update(label="Kaggle 데이터셋 분석 중…")
1712
+ with st.spinner("Searching Kaggle…"):
1713
+ kaggle_kw = extract_kaggle_search_keywords(prompt)
1714
+ try:
1715
+ datasets = search_kaggle_datasets(kaggle_kw)
1716
+ except Exception as e:
1717
+ logging.warning(f"search_kaggle_datasets 오류 무시: {e}")
1718
+ datasets = []
1719
+ analyses = []
1720
+ if datasets:
1721
+ status.update(label="Downloading & analysing datasets…")
1722
+ for ds in datasets:
1723
+ try:
1724
+ ana = download_and_analyze_dataset(ds["ref"])
1725
+ except Exception as e:
1726
+ logging.error(f"Kaggle 분석 오류({ds['ref']}) : {e}")
1727
+ ana = f"데이터셋 분석 오류: {e}"
1728
+ analyses.append({"meta": ds, "analysis": ana})
1729
+ if analyses:
1730
+ kaggle_content = format_kaggle_analysis_markdown_multi(analyses)
1731
+
1732
+ # ③ 파일 업로드
1733
+ if has_uploaded:
1734
+ status.update(label="Reading uploaded files…")
1735
+ with st.spinner("Processing files…"):
1736
+ file_content = process_uploaded_files(uploaded_files)
1737
+
1738
+ # ④ 군사 전술 데이터 (필요 시)
1739
+ mil_content = None
1740
+ if is_military_query(prompt):
1741
+ status.update(label="Searching military tactics dataset…")
1742
+ with st.spinner("Loading military insights…"):
1743
+ mil_rows = military_search(prompt)
1744
+ if mil_rows:
1745
+ mil_content = "# Military Tactics Dataset Reference\n\n"
1746
+ for i, row in enumerate(mil_rows, 1):
1747
+ mil_content += (
1748
+ f"### Case {i}\n"
1749
+ f"**Scenario:** {row['scenario_description']}\n\n"
1750
+ f"**Attack Reasoning:** {row['attack_reasoning']}\n\n"
1751
+ f"**Defense Reasoning:** {row['defense_reasoning']}\n\n---\n"
1752
+ )
1753
+
1754
+ user_content = prompt
1755
+ if search_content:
1756
+ user_content += "\n\n" + search_content
1757
+ if kaggle_content:
1758
+ user_content += "\n\n" + kaggle_content
1759
+ if file_content:
1760
+ user_content += "\n\n" + file_content
1761
+ if mil_content:
1762
+ user_content += "\n\n" + mil_content
1763
+
1764
+ # 내부 분석
1765
+ status.update(label="분석 중…")
1766
+ decision_purpose = identify_decision_purpose(prompt)
1767
+ relevance_scores = compute_relevance_scores(prompt, PHYS_CATEGORIES)
1768
+
1769
+ status.update(label="카테고리 조합 아이디어 생성 중…")
1770
+ T = st.session_state.temp
1771
+ k_cat_range = (4, 8) if T < 1.0 else (6, 10) if T < 2.0 else (8, 12)
1772
+ n_item_range = (2, 4) if T < 1.0 else (3, 6) if T < 2.0 else (4, 8)
1773
+ depth_range = (2, 3) if T < 1.0 else (2, 5) if T < 2.0 else (2, 6)
1774
+ combos = generate_random_comparison_matrix(
1775
+ PHYS_CATEGORIES,
1776
+ relevance_scores,
1777
+ k_cat=k_cat_range,
1778
+ n_item=n_item_range,
1779
+ depth_range=depth_range,
1780
+ seed=hash(prompt) & 0xFFFFFFFF,
1781
+ T=T,
1782
+ )
1783
+
1784
+ combos_table = "| 조합 | 가중치 | 영향도 | 신뢰도 | 총점 |\n|------|--------|--------|--------|-----|\n"
1785
+ for w, imp, conf, tot, cmb in combos:
1786
+ combo_str = " + ".join(f"{c[0]}-{c[1]}" for c in cmb)
1787
+ combos_table += f"| {combo_str} | {w} | {imp} | {conf:.1f} | {tot} |\n"
1788
+
1789
+ purpose_info = "\n\n## 디자인/발명 목표 분석\n"
1790
+ if decision_purpose['purposes']:
1791
+ purpose_info += "### 핵심 목적\n"
1792
+ for p, s in decision_purpose['purposes']:
1793
+ purpose_info += f"- **{p}** (관련성: {s})\n"
1794
+ if decision_purpose['constraints']:
1795
+ purpose_info += "\n### 제약 조건\n"
1796
+ for c, s in decision_purpose['constraints']:
1797
+ purpose_info += f"- **{c}** (관련성: {s})\n"
1798
+
1799
+ # 프레임워크 적용 결과 (현재 목적이 디자인/발명 -> 선택적으로 표시)
1800
+ framework_contents = []
1801
+ for fw in selected_frameworks:
1802
+ if fw == "swot":
1803
+ swot_res = analyze_with_swot(prompt)
1804
+ framework_contents.append(format_business_framework_analysis("swot", swot_res))
1805
+ elif fw == "porter":
1806
+ porter_res = analyze_with_porter(prompt)
1807
+ framework_contents.append(format_business_framework_analysis("porter", porter_res))
1808
+ elif fw == "bcg":
1809
+ bcg_res = analyze_with_bcg(prompt)
1810
+ framework_contents.append(format_business_framework_analysis("bcg", bcg_res))
1811
+ elif fw == "sunzi":
1812
+ # 손자병법 예시
1813
+ # (실제로는 별도 로직이 필요하나 여기선 생략)
1814
+ pass
1815
+
1816
+ if framework_contents:
1817
+ user_content += "\n\n## (Optional) 기타 프레임워크 분석\n\n" + "\n\n".join(framework_contents)
1818
+
1819
+ user_content += f"\n\n## 카테고리 매트릭스 분석{purpose_info}\n{combos_table}"
1820
+
1821
+ status.update(label="Generating final design/invention ideas…")
1822
+ api_messages = [
1823
+ {"role": "system", "content": sys_prompt},
1824
+ {"role": "system", "name": "category_db", "content": category_context(selected_cat)},
1825
+ {"role": "user", "content": user_content},
1826
+ ]
1827
+ stream = client.chat.completions.create(
1828
+ model="gpt-4.1-mini",
1829
+ messages=api_messages,
1830
+ temperature=1,
1831
+ max_tokens=MAX_TOKENS,
1832
+ top_p=1,
1833
+ stream=True
1834
+ )
1835
+
1836
+ for chunk in stream:
1837
+ if chunk.choices and chunk.choices[0].delta.content:
1838
+ full_response += chunk.choices[0].delta.content
1839
+ stream_placeholder.markdown(full_response + "▌")
1840
+
1841
+ stream_placeholder.markdown(full_response)
1842
+ status.update(label="Invention ideas created!", state="complete")
1843
+
1844
+ # 이미지 생성
1845
+ img_data = img_caption = None
1846
+ if st.session_state.generate_image and full_response:
1847
+ match = re.search(r"###\s*이미지\s*프롬프트\s*\n+([^\n]+)", full_response, re.I)
1848
+ if not match:
1849
+ match = re.search(r"Image\s+Prompt\s*[:\-]\s*([^\n]+)", full_response, re.I)
1850
+ if match:
1851
+ raw_prompt = re.sub(r'[\r\n"\'\\]', " ", match.group(1)).strip()
1852
+ with st.spinner("Generating illustrative image…"):
1853
+ img_data, img_caption = generate_image(raw_prompt)
1854
+ if img_data:
1855
+ st.image(img_data, caption=f"Visualized Concept – {img_caption}")
1856
+
1857
+ answer_msg = {"role": "assistant", "content": full_response}
1858
+ if img_data:
1859
+ answer_msg["image"] = img_data
1860
+ answer_msg["image_caption"] = img_caption
1861
+ st.session_state["_skip_dup_idx"] = len(st.session_state.messages)
1862
+ st.session_state.messages.append(answer_msg)
1863
+
1864
+ # 다운로드 버튼
1865
+ st.subheader("Download This Output")
1866
+ col_md, col_html = st.columns(2)
1867
+ col_md.download_button(
1868
+ "Markdown",
1869
+ data=full_response,
1870
+ file_name=f"{prompt[:30]}.md",
1871
+ mime="text/markdown"
1872
+ )
1873
+ col_html.download_button(
1874
+ "HTML",
1875
+ data=md_to_html(full_response, prompt[:30]),
1876
+ file_name=f"{prompt[:30]}.html",
1877
+ mime="text/html"
1878
+ )
1879
+
1880
+ if st.session_state.auto_save:
1881
+ fn = f"chat_history_auto_{datetime.now():%Y%m%d_%H%M%S}.json"
1882
+ with open(fn, "w", encoding="utf-8") as fp:
1883
+ json.dump(st.session_state.messages, fp, ensure_ascii=False, indent=2)
1884
+
1885
+ except Exception as e:
1886
+ logging.error("process_input error", exc_info=True)
1887
+ st.error(f"⚠️ 작업 중 오류가 발생했습니다: {e}")
1888
+ st.session_state.messages.append(
1889
+ {"role": "assistant", "content": f"⚠️ 오류: {e}"}
1890
+ )
1891
+
1892
+ def main():
1893
+ idea_generator_app()
1894
+
1895
+ if __name__ == "__main__":
1896
+ main()