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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AI κΈ°λ° μκΆ λΆμ μμ€ν
- κ°ν λ²μ
|
| 3 |
+
Dataset: https://huggingface.co/datasets/ginipick/market
|
| 4 |
+
"""
|
| 5 |
+
import gradio as gr
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import numpy as np
|
| 8 |
+
from typing import Dict, List, Tuple
|
| 9 |
+
import json
|
| 10 |
+
from datasets import load_dataset
|
| 11 |
+
import plotly.express as px
|
| 12 |
+
import plotly.graph_objects as go
|
| 13 |
+
from plotly.subplots import make_subplots
|
| 14 |
+
import folium
|
| 15 |
+
from folium.plugins import HeatMap, MarkerCluster
|
| 16 |
+
import requests
|
| 17 |
+
from collections import Counter
|
| 18 |
+
import re
|
| 19 |
+
import os
|
| 20 |
+
import time
|
| 21 |
+
|
| 22 |
+
# ============================================================================
|
| 23 |
+
# λ°μ΄ν° λ‘λ ν΄λμ€
|
| 24 |
+
# ============================================================================
|
| 25 |
+
|
| 26 |
+
class MarketDataLoader:
|
| 27 |
+
"""νκΉ
νμ΄μ€ μκΆ λ°μ΄ν° λ‘λ"""
|
| 28 |
+
|
| 29 |
+
REGIONS = {
|
| 30 |
+
'μμΈ': 'μμΈ_202506', 'κ²½κΈ°': 'κ²½κΈ°_202506', 'λΆμ°': 'λΆμ°_202506',
|
| 31 |
+
'λꡬ': 'λꡬ_202506', 'μΈμ²': 'μΈμ²_202506', 'κ΄μ£Ό': 'κ΄μ£Ό_202506',
|
| 32 |
+
'λμ ': 'λμ _202506', 'μΈμ°': 'μΈμ°_202506', 'μΈμ’
': 'μΈμ’
_202506',
|
| 33 |
+
'κ²½λ¨': 'κ²½λ¨_202506', 'κ²½λΆ': 'κ²½λΆ_202506', 'μ λ¨': 'μ λ¨_202506',
|
| 34 |
+
'μ λΆ': 'μ λΆ_202506', 'μΆ©λ¨': 'μΆ©λ¨_202506', 'μΆ©λΆ': 'μΆ©λΆ_202506',
|
| 35 |
+
'κ°μ': 'κ°μ_202506', 'μ μ£Ό': 'μ μ£Ό_202506'
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
# μ
μ’
λΆλ₯ λ§€ν
|
| 39 |
+
CATEGORY_MAPPING = {
|
| 40 |
+
'G2': 'μλ§€μ
',
|
| 41 |
+
'I1': 'μλ°μ
',
|
| 42 |
+
'I2': 'μμμ μ
',
|
| 43 |
+
'L1': 'λΆλμ°μ
',
|
| 44 |
+
'M1': 'μ λ¬Έ/κ³Όν/κΈ°μ ',
|
| 45 |
+
'N1': 'μ¬μ
μ§μ/μλ',
|
| 46 |
+
'P1': 'κ΅μ‘μλΉμ€',
|
| 47 |
+
'Q1': '보건μλ£',
|
| 48 |
+
'R1': 'μμ /μ€ν¬μΈ /μ¬κ°',
|
| 49 |
+
'S2': 'μ리/κ°μΈμλΉμ€'
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
@staticmethod
|
| 53 |
+
def load_region_data(region: str, sample_size: int = 30000) -> pd.DataFrame:
|
| 54 |
+
"""μ§μλ³ λ°μ΄ν° λ‘λ"""
|
| 55 |
+
try:
|
| 56 |
+
file_name = f"μμ곡μΈμμ₯μ§ν₯곡λ¨_μκ°(μκΆ)μ 보_{MarketDataLoader.REGIONS[region]}.csv"
|
| 57 |
+
dataset = load_dataset("ginipick/market", data_files=file_name, split="train")
|
| 58 |
+
df = dataset.to_pandas()
|
| 59 |
+
|
| 60 |
+
if len(df) > sample_size:
|
| 61 |
+
df = df.sample(n=sample_size, random_state=42)
|
| 62 |
+
|
| 63 |
+
return df
|
| 64 |
+
except Exception as e:
|
| 65 |
+
print(f"λ°μ΄ν° λ‘λ μ€ν¨: {str(e)}")
|
| 66 |
+
return pd.DataFrame()
|
| 67 |
+
|
| 68 |
+
@staticmethod
|
| 69 |
+
def load_multiple_regions(regions: List[str], sample_per_region: int = 30000) -> pd.DataFrame:
|
| 70 |
+
"""μ¬λ¬ μ§μ λ°μ΄ν° λ‘λ"""
|
| 71 |
+
dfs = []
|
| 72 |
+
for region in regions:
|
| 73 |
+
df = MarketDataLoader.load_region_data(region, sample_per_region)
|
| 74 |
+
if not df.empty:
|
| 75 |
+
dfs.append(df)
|
| 76 |
+
|
| 77 |
+
if dfs:
|
| 78 |
+
return pd.concat(dfs, ignore_index=True)
|
| 79 |
+
return pd.DataFrame()
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
# ============================================================================
|
| 83 |
+
# μκΆ λΆμ ν΄λμ€
|
| 84 |
+
# ============================================================================
|
| 85 |
+
|
| 86 |
+
class MarketAnalyzer:
|
| 87 |
+
"""μκΆ λ°μ΄ν° λΆμ μμ§"""
|
| 88 |
+
|
| 89 |
+
def __init__(self, df: pd.DataFrame):
|
| 90 |
+
self.df = df
|
| 91 |
+
self.prepare_data()
|
| 92 |
+
|
| 93 |
+
def prepare_data(self):
|
| 94 |
+
"""λ°μ΄ν° μ μ²λ¦¬"""
|
| 95 |
+
if 'κ²½λ' in self.df.columns:
|
| 96 |
+
self.df['κ²½λ'] = pd.to_numeric(self.df['κ²½λ'], errors='coerce')
|
| 97 |
+
if 'μλ' in self.df.columns:
|
| 98 |
+
self.df['μλ'] = pd.to_numeric(self.df['μλ'], errors='coerce')
|
| 99 |
+
self.df = self.df.dropna(subset=['κ²½λ', 'μλ'])
|
| 100 |
+
|
| 101 |
+
# μΈ΅ μ 보 μ μ
|
| 102 |
+
if 'μΈ΅μ 보' in self.df.columns:
|
| 103 |
+
self.df['μΈ΅μ 보_μ«μ'] = self.df['μΈ΅μ 보'].apply(self._parse_floor)
|
| 104 |
+
|
| 105 |
+
def _parse_floor(self, floor_str):
|
| 106 |
+
"""μΈ΅ μ 보λ₯Ό μ«μλ‘ λ³ν"""
|
| 107 |
+
if pd.isna(floor_str):
|
| 108 |
+
return None
|
| 109 |
+
floor_str = str(floor_str)
|
| 110 |
+
if 'μ§ν' in floor_str or 'B' in floor_str:
|
| 111 |
+
match = re.search(r'\d+', floor_str)
|
| 112 |
+
return -int(match.group()) if match else -1
|
| 113 |
+
elif '1μΈ΅' in floor_str or floor_str == '1':
|
| 114 |
+
return 1
|
| 115 |
+
else:
|
| 116 |
+
match = re.search(r'\d+', floor_str)
|
| 117 |
+
return int(match.group()) if match else None
|
| 118 |
+
|
| 119 |
+
def get_comprehensive_insights(self) -> List[Dict]:
|
| 120 |
+
"""ν¬κ΄μ μΈ μΈμ¬μ΄νΈ μμ±"""
|
| 121 |
+
insights = []
|
| 122 |
+
|
| 123 |
+
# 1. μ
μ’
λ³ μ ν¬ μ (μκΆμ
μ’
μ€λΆλ₯)
|
| 124 |
+
insights.append(self._create_top_categories_chart())
|
| 125 |
+
|
| 126 |
+
# 2. λλΆλ₯λ³ λΆν¬ (νμ΄ μ°¨νΈ)
|
| 127 |
+
insights.append(self._create_major_category_pie())
|
| 128 |
+
|
| 129 |
+
# 3. μΈ΅λ³ λΆν¬ μμΈ λΆμ
|
| 130 |
+
insights.append(self._create_floor_analysis())
|
| 131 |
+
|
| 132 |
+
# 4. μ§μλ³ μ
μ’
λ€μμ± μ§μ
|
| 133 |
+
insights.append(self._create_diversity_index())
|
| 134 |
+
|
| 135 |
+
# 5. νλμ°¨μ΄μ¦ vs κ°μΈμ¬μ
μ λΆμ
|
| 136 |
+
insights.append(self._create_franchise_analysis())
|
| 137 |
+
|
| 138 |
+
# 6. μ
μ’
λ³ μΈ΅ μ νΈλ
|
| 139 |
+
insights.append(self._create_floor_preference())
|
| 140 |
+
|
| 141 |
+
# 7. μκ΅°κ΅¬λ³ μκΆ λ°μ§λ TOP 20
|
| 142 |
+
insights.append(self._create_district_density())
|
| 143 |
+
|
| 144 |
+
# 8. μ
μ’
μκ΄κ΄κ³ (κ°μ μ§μμ μμ£Ό λνλλ μ
μ’
)
|
| 145 |
+
insights.append(self._create_category_correlation())
|
| 146 |
+
|
| 147 |
+
# 9. μλΆλ₯ νΈλ λ (μμ 20κ°)
|
| 148 |
+
insights.append(self._create_subcategory_trends())
|
| 149 |
+
|
| 150 |
+
# 10. μ§μλ³ νΉν μ
μ’
|
| 151 |
+
insights.append(self._create_regional_specialization())
|
| 152 |
+
|
| 153 |
+
return insights
|
| 154 |
+
|
| 155 |
+
def _create_top_categories_chart(self) -> Dict:
|
| 156 |
+
"""μ
μ’
λ³ μ ν¬ μ μ°¨νΈ"""
|
| 157 |
+
if 'μκΆμ
μ’
μ€λΆλ₯λͺ
' not in self.df.columns:
|
| 158 |
+
return None
|
| 159 |
+
|
| 160 |
+
top_categories = self.df['μκΆμ
μ’
μ€λΆλ₯λͺ
'].value_counts().head(15)
|
| 161 |
+
fig = px.bar(
|
| 162 |
+
x=top_categories.values,
|
| 163 |
+
y=top_categories.index,
|
| 164 |
+
orientation='h',
|
| 165 |
+
labels={'x': 'μ ν¬ μ', 'y': 'μ
μ’
'},
|
| 166 |
+
title='π μμ μ
μ’
TOP 15',
|
| 167 |
+
color=top_categories.values,
|
| 168 |
+
color_continuous_scale='blues'
|
| 169 |
+
)
|
| 170 |
+
fig.update_layout(showlegend=False, height=500)
|
| 171 |
+
return {'type': 'plot', 'data': fig, 'title': 'μ
μ’
λ³ μ ν¬ μ λΆμ'}
|
| 172 |
+
|
| 173 |
+
def _create_major_category_pie(self) -> Dict:
|
| 174 |
+
"""λλΆλ₯λ³ λΆν¬"""
|
| 175 |
+
if 'μκΆμ
μ’
λλΆλ₯μ½λ' not in self.df.columns:
|
| 176 |
+
return None
|
| 177 |
+
|
| 178 |
+
major_counts = self.df['μκΆμ
μ’
λλΆλ₯μ½λ'].value_counts()
|
| 179 |
+
labels = [MarketDataLoader.CATEGORY_MAPPING.get(code, code) for code in major_counts.index]
|
| 180 |
+
|
| 181 |
+
fig = px.pie(
|
| 182 |
+
values=major_counts.values,
|
| 183 |
+
names=labels,
|
| 184 |
+
title='π μ
μ’
λλΆλ₯ λΆν¬',
|
| 185 |
+
hole=0.4,
|
| 186 |
+
color_discrete_sequence=px.colors.qualitative.Set3
|
| 187 |
+
)
|
| 188 |
+
fig.update_traces(textposition='inside', textinfo='percent+label')
|
| 189 |
+
return {'type': 'plot', 'data': fig, 'title': 'λλΆλ₯λ³ μκΆ κ΅¬μ±'}
|
| 190 |
+
|
| 191 |
+
def _create_floor_analysis(self) -> Dict:
|
| 192 |
+
"""μΈ΅λ³ λΆν¬ μμΈ λΆμ"""
|
| 193 |
+
if 'μΈ΅μ 보_μ«μ' not in self.df.columns:
|
| 194 |
+
return None
|
| 195 |
+
|
| 196 |
+
floor_data = self.df['μΈ΅μ 보_μ«μ'].dropna()
|
| 197 |
+
floor_counts = floor_data.value_counts().sort_index()
|
| 198 |
+
|
| 199 |
+
# μ§ν, 1μΈ΅, 2μΈ΅ μ΄μμΌλ‘ κ·Έλ£Ήν
|
| 200 |
+
underground = floor_counts[floor_counts.index < 0].sum()
|
| 201 |
+
first_floor = floor_counts.get(1, 0)
|
| 202 |
+
upper_floors = floor_counts[floor_counts.index > 1].sum()
|
| 203 |
+
|
| 204 |
+
fig = go.Figure(data=[
|
| 205 |
+
go.Bar(
|
| 206 |
+
x=['μ§ν', '1μΈ΅', '2μΈ΅ μ΄μ'],
|
| 207 |
+
y=[underground, first_floor, upper_floors],
|
| 208 |
+
text=[f'{underground:,}<br>({underground/len(floor_data)*100:.1f}%)',
|
| 209 |
+
f'{first_floor:,}<br>({first_floor/len(floor_data)*100:.1f}%)',
|
| 210 |
+
f'{upper_floors:,}<br>({upper_floors/len(floor_data)*100:.1f}%)'],
|
| 211 |
+
textposition='auto',
|
| 212 |
+
marker_color=['#e74c3c', '#3498db', '#95a5a6']
|
| 213 |
+
)
|
| 214 |
+
])
|
| 215 |
+
fig.update_layout(
|
| 216 |
+
title='π’ μΈ΅λ³ μ ν¬ λΆν¬ (μ§ν vs 1μΈ΅ vs μμΈ΅)',
|
| 217 |
+
xaxis_title='μΈ΅ ꡬλΆ',
|
| 218 |
+
yaxis_title='μ ν¬ μ',
|
| 219 |
+
height=400
|
| 220 |
+
)
|
| 221 |
+
return {'type': 'plot', 'data': fig, 'title': 'μΈ΅λ³ μ
μ§ λΆμ'}
|
| 222 |
+
|
| 223 |
+
def _create_diversity_index(self) -> Dict:
|
| 224 |
+
"""μ§μλ³ μ
μ’
λ€μμ± μ§μ"""
|
| 225 |
+
if 'μꡰꡬλͺ
' not in self.df.columns or 'μκΆμ
μ’
μ€λΆλ₯λͺ
' not in self.df.columns:
|
| 226 |
+
return None
|
| 227 |
+
|
| 228 |
+
# κ° μκ΅°κ΅¬λ³ μ
μ’
λ€μμ± κ³μ° (μ
μ’
μ / μ 체 μ ν¬ μ)
|
| 229 |
+
diversity_data = []
|
| 230 |
+
for district in self.df['μꡰꡬλͺ
'].unique()[:20]: # μμ 20κ°
|
| 231 |
+
district_df = self.df[self.df['μꡰꡬλͺ
'] == district]
|
| 232 |
+
num_categories = district_df['μκΆμ
μ’
μ€λΆλ₯λͺ
'].nunique()
|
| 233 |
+
total_stores = len(district_df)
|
| 234 |
+
diversity_score = (num_categories / total_stores) * 100
|
| 235 |
+
diversity_data.append({
|
| 236 |
+
'μꡰꡬ': district,
|
| 237 |
+
'λ€μμ± μ§μ': diversity_score,
|
| 238 |
+
'μ
μ’
μ': num_categories,
|
| 239 |
+
'μ΄ μ ν¬': total_stores
|
| 240 |
+
})
|
| 241 |
+
|
| 242 |
+
diversity_df = pd.DataFrame(diversity_data).sort_values('λ€μμ± μ§μ', ascending=False).head(15)
|
| 243 |
+
|
| 244 |
+
fig = px.bar(
|
| 245 |
+
diversity_df,
|
| 246 |
+
x='λ€μμ± μ§μ',
|
| 247 |
+
y='μꡰꡬ',
|
| 248 |
+
orientation='h',
|
| 249 |
+
title='π μ§μλ³ μ
μ’
λ€μμ± μ§μ (μμ 15κ°)',
|
| 250 |
+
labels={'λ€μμ± μ§μ': 'λ€μμ± μ§μ (%)', 'μꡰꡬ': 'μ§μ'},
|
| 251 |
+
color='λ€μμ± μ§μ',
|
| 252 |
+
color_continuous_scale='viridis',
|
| 253 |
+
hover_data=['μ
μ’
μ', 'μ΄ μ ν¬']
|
| 254 |
+
)
|
| 255 |
+
fig.update_layout(height=500)
|
| 256 |
+
return {'type': 'plot', 'data': fig, 'title': 'μ
μ’
λ€μμ± λΆμ'}
|
| 257 |
+
|
| 258 |
+
def _create_franchise_analysis(self) -> Dict:
|
| 259 |
+
"""νλμ°¨μ΄μ¦ vs κ°μΈμ¬μ
μ λΆμ"""
|
| 260 |
+
if 'μνΈλͺ
' not in self.df.columns:
|
| 261 |
+
return None
|
| 262 |
+
|
| 263 |
+
# μ£Όμ νλμ°¨μ΄μ¦ ν€μλ
|
| 264 |
+
franchise_keywords = [
|
| 265 |
+
'CU', 'GS25', 'μΈλΈμΌλ λΈ', 'μ΄λ§νΈ24', 'λ―Έλμ€ν±',
|
| 266 |
+
'μ€νλ²
μ€', 'ν¬μΈνλ μ΄μ€', 'μ΄λμΌ', 'νμ€νμ€', '컀νΌλΉ',
|
| 267 |
+
'λ§₯λλ λ', 'λ²κ±°νΉ', 'λ‘―λ°λ¦¬μ', 'KFC', 'λ§μ€ν°μΉ',
|
| 268 |
+
'BBQ', 'κ΅μ΄', 'κ΅½λ€', 'bhc', 'λ€λ€μΉν¨'
|
| 269 |
+
]
|
| 270 |
+
|
| 271 |
+
franchise_counts = {}
|
| 272 |
+
for keyword in franchise_keywords:
|
| 273 |
+
count = self.df['μνΈλͺ
'].str.contains(keyword, case=False, na=False).sum()
|
| 274 |
+
if count > 0:
|
| 275 |
+
franchise_counts[keyword] = count
|
| 276 |
+
|
| 277 |
+
total_franchise = sum(franchise_counts.values())
|
| 278 |
+
total_stores = len(self.df)
|
| 279 |
+
individual_stores = total_stores - total_franchise
|
| 280 |
+
|
| 281 |
+
# νμ΄ μ°¨νΈ
|
| 282 |
+
fig = make_subplots(
|
| 283 |
+
rows=1, cols=2,
|
| 284 |
+
specs=[[{'type': 'pie'}, {'type': 'bar'}]],
|
| 285 |
+
subplot_titles=('μ 체 λΉμ¨', 'νλμ°¨μ΄μ¦λ³ μ ν¬ μ')
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
# μ 체 λΉμ¨
|
| 289 |
+
fig.add_trace(
|
| 290 |
+
go.Pie(
|
| 291 |
+
labels=['κ°μΈμ¬μ
μ', 'νλμ°¨μ΄μ¦'],
|
| 292 |
+
values=[individual_stores, total_franchise],
|
| 293 |
+
hole=0.3,
|
| 294 |
+
marker_colors=['#3498db', '#e74c3c']
|
| 295 |
+
),
|
| 296 |
+
row=1, col=1
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
# νλμ°¨μ΄μ¦λ³
|
| 300 |
+
top_franchises = dict(sorted(franchise_counts.items(), key=lambda x: x[1], reverse=True)[:10])
|
| 301 |
+
fig.add_trace(
|
| 302 |
+
go.Bar(
|
| 303 |
+
x=list(top_franchises.keys()),
|
| 304 |
+
y=list(top_franchises.values()),
|
| 305 |
+
marker_color='#e74c3c'
|
| 306 |
+
),
|
| 307 |
+
row=1, col=2
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
fig.update_layout(
|
| 311 |
+
title_text='πͺ νλμ°¨μ΄μ¦ vs κ°μΈμ¬μ
μ λΆμ',
|
| 312 |
+
showlegend=True,
|
| 313 |
+
height=400
|
| 314 |
+
)
|
| 315 |
+
return {'type': 'plot', 'data': fig, 'title': 'νλμ°¨μ΄μ¦ μ μ μ¨'}
|
| 316 |
+
|
| 317 |
+
def _create_floor_preference(self) -> Dict:
|
| 318 |
+
"""μ
μ’
λ³ μΈ΅ μ νΈλ"""
|
| 319 |
+
if 'μκΆμ
μ’
μ€λΆλ₯λͺ
' not in self.df.columns or 'μΈ΅μ 보_μ«μ' not in self.df.columns:
|
| 320 |
+
return None
|
| 321 |
+
|
| 322 |
+
# μμ 10κ° μ
μ’
μ μΈ΅λ³ λΆν¬
|
| 323 |
+
top_categories = self.df['μκΆμ
μ’
μ€λΆλ₯λͺ
'].value_counts().head(10).index
|
| 324 |
+
|
| 325 |
+
floor_pref_data = []
|
| 326 |
+
for category in top_categories:
|
| 327 |
+
cat_df = self.df[self.df['μκΆμ
μ’
μ€λΆλ₯λͺ
'] == category]
|
| 328 |
+
underground = (cat_df['μΈ΅μ 보_μ«μ'] < 0).sum()
|
| 329 |
+
first_floor = (cat_df['μΈ΅μ 보_μ«μ'] == 1).sum()
|
| 330 |
+
upper_floors = (cat_df['μΈ΅μ 보_μ«μ'] > 1).sum()
|
| 331 |
+
|
| 332 |
+
total = underground + first_floor + upper_floors
|
| 333 |
+
if total > 0:
|
| 334 |
+
floor_pref_data.append({
|
| 335 |
+
'μ
μ’
': category,
|
| 336 |
+
'μ§ν': (underground / total) * 100,
|
| 337 |
+
'1μΈ΅': (first_floor / total) * 100,
|
| 338 |
+
'2μΈ΅ μ΄μ': (upper_floors / total) * 100
|
| 339 |
+
})
|
| 340 |
+
|
| 341 |
+
pref_df = pd.DataFrame(floor_pref_data)
|
| 342 |
+
|
| 343 |
+
fig = go.Figure(data=[
|
| 344 |
+
go.Bar(name='μ§ν', x=pref_df['μ
μ’
'], y=pref_df['μ§ν'], marker_color='#e74c3c'),
|
| 345 |
+
go.Bar(name='1μΈ΅', x=pref_df['μ
μ’
'], y=pref_df['1μΈ΅'], marker_color='#3498db'),
|
| 346 |
+
go.Bar(name='2μΈ΅ μ΄μ', x=pref_df['μ
μ’
'], y=pref_df['2μΈ΅ μ΄μ'], marker_color='#95a5a6')
|
| 347 |
+
])
|
| 348 |
+
|
| 349 |
+
fig.update_layout(
|
| 350 |
+
title='π― μ
μ’
λ³ μΈ΅ μ νΈλ (μμ 10κ°)',
|
| 351 |
+
xaxis_title='μ
μ’
',
|
| 352 |
+
yaxis_title='λΉμ¨ (%)',
|
| 353 |
+
barmode='stack',
|
| 354 |
+
height=500,
|
| 355 |
+
xaxis_tickangle=-45
|
| 356 |
+
)
|
| 357 |
+
return {'type': 'plot', 'data': fig, 'title': 'μΈ΅λ³ μ
μ§ μ νΈλ'}
|
| 358 |
+
|
| 359 |
+
def _create_district_density(self) -> Dict:
|
| 360 |
+
"""μκ΅°κ΅¬λ³ μκΆ λ°μ§λ"""
|
| 361 |
+
if 'μꡰꡬλͺ
' not in self.df.columns:
|
| 362 |
+
return None
|
| 363 |
+
|
| 364 |
+
district_counts = self.df['μꡰꡬλͺ
'].value_counts().head(20)
|
| 365 |
+
|
| 366 |
+
fig = px.bar(
|
| 367 |
+
x=district_counts.values,
|
| 368 |
+
y=district_counts.index,
|
| 369 |
+
orientation='h',
|
| 370 |
+
title='π μκ΅°κ΅¬λ³ μκΆ λ°μ§λ TOP 20',
|
| 371 |
+
labels={'x': 'μ ν¬ μ', 'y': 'μꡰꡬ'},
|
| 372 |
+
color=district_counts.values,
|
| 373 |
+
color_continuous_scale='reds'
|
| 374 |
+
)
|
| 375 |
+
fig.update_layout(showlegend=False, height=600)
|
| 376 |
+
return {'type': 'plot', 'data': fig, 'title': 'μ§μλ³ λ°μ§λ'}
|
| 377 |
+
|
| 378 |
+
def _create_category_correlation(self) -> Dict:
|
| 379 |
+
"""μ
μ’
μκ΄κ΄κ³ (κ°μ λμ μμ£Ό λνλλ μ
μ’
)"""
|
| 380 |
+
if 'νμ λλͺ
' not in self.df.columns or 'μκΆμ
μ’
μ€λΆλ₯λͺ
' not in self.df.columns:
|
| 381 |
+
return None
|
| 382 |
+
|
| 383 |
+
# μμ 10κ° μ
μ’
λ§ λΆμ
|
| 384 |
+
top_categories = self.df['μκΆμ
μ’
μ€λΆλ₯λͺ
'].value_counts().head(10).index.tolist()
|
| 385 |
+
|
| 386 |
+
# κ° λλ³λ‘ μ
μ’
μΉ΄μ΄νΈ
|
| 387 |
+
correlation_matrix = []
|
| 388 |
+
for cat1 in top_categories:
|
| 389 |
+
row = []
|
| 390 |
+
for cat2 in top_categories:
|
| 391 |
+
# λ μ
μ’
μ΄ κ°μ λμ μλ κ²½μ°μ μ
|
| 392 |
+
cat1_dongs = set(self.df[self.df['μκΆμ
μ’
μ€λΆλ₯λͺ
'] == cat1]['νμ λλͺ
'].unique())
|
| 393 |
+
cat2_dongs = set(self.df[self.df['μκΆμ
μ’
μ€λΆλ₯λͺ
'] == cat2]['νμ λλͺ
'].unique())
|
| 394 |
+
intersection = len(cat1_dongs & cat2_dongs)
|
| 395 |
+
union = len(cat1_dongs | cat2_dongs)
|
| 396 |
+
similarity = (intersection / union * 100) if union > 0 else 0
|
| 397 |
+
row.append(similarity)
|
| 398 |
+
correlation_matrix.append(row)
|
| 399 |
+
|
| 400 |
+
fig = go.Figure(data=go.Heatmap(
|
| 401 |
+
z=correlation_matrix,
|
| 402 |
+
x=top_categories,
|
| 403 |
+
y=top_categories,
|
| 404 |
+
colorscale='Blues',
|
| 405 |
+
text=np.round(correlation_matrix, 1),
|
| 406 |
+
texttemplate='%{text}',
|
| 407 |
+
textfont={"size": 10}
|
| 408 |
+
))
|
| 409 |
+
|
| 410 |
+
fig.update_layout(
|
| 411 |
+
title='π μ
μ’
μκ΄κ΄κ³ λ§€νΈλ¦μ€ (κ°μ μ§μ λμ μΆνμ¨)',
|
| 412 |
+
xaxis_title='μ
μ’
',
|
| 413 |
+
yaxis_title='μ
μ’
',
|
| 414 |
+
height=600,
|
| 415 |
+
xaxis_tickangle=-45
|
| 416 |
+
)
|
| 417 |
+
return {'type': 'plot', 'data': fig, 'title': 'μ
μ’
곡쑴 λΆμ'}
|
| 418 |
+
|
| 419 |
+
def _create_subcategory_trends(self) -> Dict:
|
| 420 |
+
"""μλΆλ₯ νΈλ λ"""
|
| 421 |
+
if 'μκΆμ
μ’
μλΆλ₯λͺ
' not in self.df.columns:
|
| 422 |
+
return None
|
| 423 |
+
|
| 424 |
+
subcat_counts = self.df['μκΆμ
μ’
μλΆλ₯λͺ
'].value_counts().head(20)
|
| 425 |
+
|
| 426 |
+
fig = px.treemap(
|
| 427 |
+
names=subcat_counts.index,
|
| 428 |
+
parents=[''] * len(subcat_counts),
|
| 429 |
+
values=subcat_counts.values,
|
| 430 |
+
title='π μλΆλ₯ μ
μ’
νΈλ λ TOP 20',
|
| 431 |
+
color=subcat_counts.values,
|
| 432 |
+
color_continuous_scale='greens'
|
| 433 |
+
)
|
| 434 |
+
fig.update_layout(height=600)
|
| 435 |
+
return {'type': 'plot', 'data': fig, 'title': 'μΈλΆ μ
μ’
λΆμ'}
|
| 436 |
+
|
| 437 |
+
def _create_regional_specialization(self) -> Dict:
|
| 438 |
+
"""μ§μλ³ νΉν μ
μ’
"""
|
| 439 |
+
if 'μλλͺ
' not in self.df.columns or 'μκΆμ
μ’
μ€λΆλ₯λͺ
' not in self.df.columns:
|
| 440 |
+
return None
|
| 441 |
+
|
| 442 |
+
# κ° μλλ³ μμ 3κ° μ
μ’
|
| 443 |
+
specialization_data = []
|
| 444 |
+
for region in self.df['μλλͺ
'].unique():
|
| 445 |
+
region_df = self.df[self.df['μλλͺ
'] == region]
|
| 446 |
+
top_categories = region_df['μκΆμ
μ’
μ€λΆλ₯λͺ
'].value_counts().head(3)
|
| 447 |
+
for category, count in top_categories.items():
|
| 448 |
+
specialization_data.append({
|
| 449 |
+
'μ§μ': region,
|
| 450 |
+
'νΉνμ
μ’
': category,
|
| 451 |
+
'μ ν¬μ': count
|
| 452 |
+
})
|
| 453 |
+
|
| 454 |
+
spec_df = pd.DataFrame(specialization_data)
|
| 455 |
+
|
| 456 |
+
fig = px.sunburst(
|
| 457 |
+
spec_df,
|
| 458 |
+
path=['μ§μ', 'νΉνμ
μ’
'],
|
| 459 |
+
values='μ ν¬μ',
|
| 460 |
+
title='π― μ§μλ³ νΉν μ
μ’
(κ° μ§μ TOP 3)',
|
| 461 |
+
color='μ ν¬μ',
|
| 462 |
+
color_continuous_scale='oranges'
|
| 463 |
+
)
|
| 464 |
+
fig.update_layout(height=700)
|
| 465 |
+
return {'type': 'plot', 'data': fig, 'title': 'μ§μ νΉν λΆμ'}
|
| 466 |
+
|
| 467 |
+
def create_density_map(self, sample_size: int = 1000) -> str:
|
| 468 |
+
"""μ ν¬ λ°μ§λ μ§λ μμ±"""
|
| 469 |
+
df_sample = self.df.sample(n=min(sample_size, len(self.df)), random_state=42)
|
| 470 |
+
|
| 471 |
+
center_lat = df_sample['μλ'].mean()
|
| 472 |
+
center_lon = df_sample['κ²½λ'].mean()
|
| 473 |
+
|
| 474 |
+
m = folium.Map(location=[center_lat, center_lon], zoom_start=11, tiles='OpenStreetMap')
|
| 475 |
+
|
| 476 |
+
# ννΈλ§΅
|
| 477 |
+
heat_data = [[row['μλ'], row['κ²½λ']] for _, row in df_sample.iterrows()]
|
| 478 |
+
HeatMap(heat_data, radius=15, blur=25, max_zoom=13).add_to(m)
|
| 479 |
+
|
| 480 |
+
return m._repr_html_()
|
| 481 |
+
|
| 482 |
+
def analyze_for_llm(self) -> Dict:
|
| 483 |
+
"""LLM 컨ν
μ€νΈμ© λΆμ λ°μ΄ν°"""
|
| 484 |
+
context = {
|
| 485 |
+
'μ΄_μ ν¬_μ': len(self.df),
|
| 486 |
+
'μ§μ_μ': self.df['μλλͺ
'].nunique() if 'μλλͺ
' in self.df.columns else 0,
|
| 487 |
+
'μ
μ’
_μ': self.df['μκΆμ
μ’
μ€λΆλ₯λͺ
'].nunique() if 'μκΆμ
μ’
μ€λΆλ₯λͺ
' in self.df.columns else 0,
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
if 'μκΆμ
μ’
μ€λΆλ₯λͺ
' in self.df.columns:
|
| 491 |
+
context['μμ_μ
μ’
_5'] = self.df['μκΆμ
μ’
μ€λΆλ₯λͺ
'].value_counts().head(5).to_dict()
|
| 492 |
+
|
| 493 |
+
if 'μΈ΅μ 보_μ«μ' in self.df.columns:
|
| 494 |
+
first_floor_ratio = (self.df['μΈ΅μ 보_μ«μ'] == 1).sum() / len(self.df) * 100
|
| 495 |
+
context['1μΈ΅_λΉμ¨'] = f"{first_floor_ratio:.1f}%"
|
| 496 |
+
|
| 497 |
+
return context
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
# ============================================================================
|
| 501 |
+
# LLM 쿼리 νλ‘μΈμ
|
| 502 |
+
# ============================================================================
|
| 503 |
+
|
| 504 |
+
class LLMQueryProcessor:
|
| 505 |
+
"""Fireworks AI κΈ°λ° μμ°μ΄ μ²λ¦¬"""
|
| 506 |
+
|
| 507 |
+
def __init__(self, api_key: str = None):
|
| 508 |
+
# νκ²½λ³μμμ API ν€ κ°μ Έμ€κΈ°
|
| 509 |
+
self.api_key = api_key or os.getenv("FIREWORKS_API_KEY")
|
| 510 |
+
self.base_url = "https://api.fireworks.ai/inference/v1/chat/completions"
|
| 511 |
+
|
| 512 |
+
if not self.api_key:
|
| 513 |
+
raise ValueError("β FIREWORKS_API_KEY νκ²½λ³μλ₯Ό μ€μ νκ±°λ API ν€λ₯Ό μ
λ ₯ν΄μ£ΌμΈμ!")
|
| 514 |
+
|
| 515 |
+
def process_query(self, query: str, data_context: Dict, chat_history: List = None, max_retries: int = 3) -> str:
|
| 516 |
+
"""μμ°μ΄ 쿼리 μ²λ¦¬ (μ¬μλ λ‘μ§ ν¬ν¨)"""
|
| 517 |
+
system_prompt = f"""λΉμ μ νκ΅ μκΆ λ°μ΄ν° λΆμ μ λ¬Έκ°μ
λλ€.
|
| 518 |
+
|
| 519 |
+
π **νμ¬ λΆμ λ°μ΄ν°**
|
| 520 |
+
{json.dumps(data_context, ensure_ascii=False, indent=2)}
|
| 521 |
+
|
| 522 |
+
ꡬ체μ μΈ μ«μμ λΉμ¨λ‘ μ λμ λΆμμ μ 곡νμΈμ.
|
| 523 |
+
μ°½μ
, ν¬μ, κ²½μ λΆμ κ΄μ μμ μ€μ©μ μΈμ¬μ΄νΈλ₯Ό μ 곡νμΈμ."""
|
| 524 |
+
|
| 525 |
+
messages = [{"role": "system", "content": system_prompt}]
|
| 526 |
+
if chat_history:
|
| 527 |
+
messages.extend(chat_history[-6:])
|
| 528 |
+
messages.append({"role": "user", "content": query})
|
| 529 |
+
|
| 530 |
+
payload = {
|
| 531 |
+
"model": "accounts/fireworks/models/qwen3-235b-a22b-instruct-2507",
|
| 532 |
+
"max_tokens": 2000,
|
| 533 |
+
"temperature": 0.7,
|
| 534 |
+
"messages": messages
|
| 535 |
+
}
|
| 536 |
+
|
| 537 |
+
headers = {
|
| 538 |
+
"Authorization": f"Bearer {self.api_key}",
|
| 539 |
+
"Content-Type": "application/json"
|
| 540 |
+
}
|
| 541 |
+
|
| 542 |
+
# μ¬μλ λ‘μ§
|
| 543 |
+
for attempt in range(max_retries):
|
| 544 |
+
try:
|
| 545 |
+
# νμμμμ 60μ΄λ‘ μ¦κ°
|
| 546 |
+
response = requests.post(
|
| 547 |
+
self.base_url,
|
| 548 |
+
headers=headers,
|
| 549 |
+
json=payload,
|
| 550 |
+
timeout=60
|
| 551 |
+
)
|
| 552 |
+
|
| 553 |
+
if response.status_code == 200:
|
| 554 |
+
return response.json()['choices'][0]['message']['content']
|
| 555 |
+
elif response.status_code == 429:
|
| 556 |
+
# Rate limit - μ¬μλ
|
| 557 |
+
wait_time = (attempt + 1) * 2
|
| 558 |
+
time.sleep(wait_time)
|
| 559 |
+
continue
|
| 560 |
+
else:
|
| 561 |
+
return f"β οΈ API μ€λ₯: {response.status_code} - {response.text[:200]}"
|
| 562 |
+
|
| 563 |
+
except requests.exceptions.Timeout:
|
| 564 |
+
if attempt < max_retries - 1:
|
| 565 |
+
time.sleep(2)
|
| 566 |
+
continue
|
| 567 |
+
else:
|
| 568 |
+
return "β οΈ API μλ΅ μκ° μ΄κ³Ό. μ μ ν λ€μ μλν΄μ£ΌμΈμ."
|
| 569 |
+
|
| 570 |
+
except requests.exceptions.ConnectionError:
|
| 571 |
+
if attempt < max_retries - 1:
|
| 572 |
+
time.sleep(2)
|
| 573 |
+
continue
|
| 574 |
+
else:
|
| 575 |
+
return "β οΈ λ€νΈμν¬ μ°κ²° μ€λ₯. μΈν°λ· μ°κ²°μ νμΈν΄μ£ΌμΈμ."
|
| 576 |
+
|
| 577 |
+
except Exception as e:
|
| 578 |
+
if attempt < max_retries - 1:
|
| 579 |
+
time.sleep(1)
|
| 580 |
+
continue
|
| 581 |
+
else:
|
| 582 |
+
return f"β μ€λ₯: {str(e)}"
|
| 583 |
+
|
| 584 |
+
return "β οΈ μ΅λ μ¬μλ νμ μ΄κ³Ό. μ μ ν λ€μ μλν΄μ£ΌμΈμ."
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
# ============================================================================
|
| 588 |
+
# μ μ μν
|
| 589 |
+
# ============================================================================
|
| 590 |
+
|
| 591 |
+
class AppState:
|
| 592 |
+
def __init__(self):
|
| 593 |
+
self.analyzer = None
|
| 594 |
+
self.llm_processor = None
|
| 595 |
+
self.chat_history = []
|
| 596 |
+
|
| 597 |
+
app_state = AppState()
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
# ============================================================================
|
| 601 |
+
# Gradio μΈν°νμ΄μ€ ν¨μ
|
| 602 |
+
# ============================================================================
|
| 603 |
+
|
| 604 |
+
def load_data(regions):
|
| 605 |
+
"""λ°μ΄ν° λ‘λ"""
|
| 606 |
+
if not regions:
|
| 607 |
+
return "β μ΅μ 1κ° μ§μμ μ νν΄μ£ΌμΈμ!", None, None, None
|
| 608 |
+
|
| 609 |
+
try:
|
| 610 |
+
df = MarketDataLoader.load_multiple_regions(regions, sample_per_region=30000)
|
| 611 |
+
if df.empty:
|
| 612 |
+
return "β λ°μ΄ν° λ‘λ μ€ν¨!", None, None, None
|
| 613 |
+
|
| 614 |
+
app_state.analyzer = MarketAnalyzer(df)
|
| 615 |
+
|
| 616 |
+
# κΈ°λ³Έ ν΅κ³
|
| 617 |
+
stats = f"""
|
| 618 |
+
β
**λ°μ΄ν° λ‘λ μλ£!**
|
| 619 |
+
|
| 620 |
+
π **ν΅κ³**
|
| 621 |
+
- μ΄ μ ν¬: {len(df):,}κ°
|
| 622 |
+
- λΆμ μ§μ: {', '.join(regions)}
|
| 623 |
+
- μ
μ’
μ: {df['μκΆμ
μ’
μ€λΆλ₯λͺ
'].nunique()}κ°
|
| 624 |
+
- λλΆλ₯: {df['μκΆμ
μ’
λλΆλ₯λͺ
'].nunique()}κ°
|
| 625 |
+
"""
|
| 626 |
+
|
| 627 |
+
return stats, gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)
|
| 628 |
+
except Exception as e:
|
| 629 |
+
return f"β μ€λ₯: {str(e)}", None, None, None
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
def generate_insights():
|
| 633 |
+
"""μΈμ¬μ΄νΈ μμ±"""
|
| 634 |
+
if app_state.analyzer is None:
|
| 635 |
+
return [None] * 11
|
| 636 |
+
|
| 637 |
+
insights = app_state.analyzer.get_comprehensive_insights()
|
| 638 |
+
map_html = app_state.analyzer.create_density_map(sample_size=2000)
|
| 639 |
+
|
| 640 |
+
result = [map_html]
|
| 641 |
+
for insight in insights:
|
| 642 |
+
if insight and insight['type'] == 'plot':
|
| 643 |
+
result.append(insight['data'])
|
| 644 |
+
else:
|
| 645 |
+
result.append(None)
|
| 646 |
+
|
| 647 |
+
# λΆμ‘±ν μ°¨νΈλ NoneμΌλ‘ μ±μ°κΈ°
|
| 648 |
+
while len(result) < 11:
|
| 649 |
+
result.append(None)
|
| 650 |
+
|
| 651 |
+
return result[:11]
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
def chat_respond(message, history):
|
| 655 |
+
"""μ±λ΄ μλ΅"""
|
| 656 |
+
if app_state.analyzer is None:
|
| 657 |
+
return history + [[message, "β λ¨Όμ λ°μ΄ν°λ₯Ό λ‘λν΄μ£ΌμΈμ!"]]
|
| 658 |
+
|
| 659 |
+
data_context = app_state.analyzer.analyze_for_llm()
|
| 660 |
+
|
| 661 |
+
# LLM νλ‘μΈμ μ΄κΈ°ν (νκ²½λ³μμμ API ν€ μλ λ‘λ)
|
| 662 |
+
try:
|
| 663 |
+
if app_state.llm_processor is None:
|
| 664 |
+
app_state.llm_processor = LLMQueryProcessor()
|
| 665 |
+
|
| 666 |
+
chat_hist = []
|
| 667 |
+
for user_msg, bot_msg in history:
|
| 668 |
+
chat_hist.append({"role": "user", "content": user_msg})
|
| 669 |
+
chat_hist.append({"role": "assistant", "content": bot_msg})
|
| 670 |
+
|
| 671 |
+
response = app_state.llm_processor.process_query(message, data_context, chat_hist)
|
| 672 |
+
|
| 673 |
+
except ValueError as e:
|
| 674 |
+
# API ν€κ° μλ κ²½μ° κΈ°λ³Έ ν΅κ³ μ 곡
|
| 675 |
+
response = f"""π **κΈ°λ³Έ λ°μ΄ν° λΆμ κ²°κ³Ό**
|
| 676 |
+
|
| 677 |
+
**μ 체 νν©**
|
| 678 |
+
- μ΄ μ ν¬ μ: {data_context['μ΄_μ ν¬_μ']:,}κ°
|
| 679 |
+
- μ
μ’
μ’
λ₯: {data_context['μ
μ’
_μ']}κ°
|
| 680 |
+
- 1μΈ΅ λΉμ¨: {data_context.get('1μΈ΅_λΉμ¨', 'N/A')}
|
| 681 |
+
|
| 682 |
+
β οΈ **AI λΆμ μ¬μ© λ°©λ²**
|
| 683 |
+
νκ²½λ³μλ₯Ό μ€μ νμΈμ:
|
| 684 |
+
```bash
|
| 685 |
+
export FIREWORKS_API_KEY="your_api_key_here"
|
| 686 |
+
```
|
| 687 |
+
|
| 688 |
+
λλ Hugging Face Spaceμμλ Settings > Variables μμ μ€μ νμΈμ."""
|
| 689 |
+
|
| 690 |
+
history.append([message, response])
|
| 691 |
+
return history
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
# ============================================================================
|
| 695 |
+
# Gradio UI
|
| 696 |
+
# ============================================================================
|
| 697 |
+
|
| 698 |
+
with gr.Blocks(title="AI μκΆ λΆμ μμ€ν
Pro", theme=gr.themes.Soft()) as demo:
|
| 699 |
+
gr.Markdown("""
|
| 700 |
+
# πͺ AI μκΆ λΆμ μμ€ν
Pro
|
| 701 |
+
*μ κ΅ μκ°(μκΆ) λ°μ΄ν° κΈ°λ° μ€μκ° λΆμ | Powered by Fireworks AI*
|
| 702 |
+
|
| 703 |
+
**β¨ 10κ°μ§ μ¬μΈ΅ λΆμ μ 곡**: μ
μ’
νΈλ λ, κ²½μ κ°λ, μ
μ§ λΆμ, νλμ°¨μ΄μ¦ λΉμ¨, μ§μ νΉν, μΈ΅λ³ μ νΈλ λ±
|
| 704 |
+
""")
|
| 705 |
+
|
| 706 |
+
with gr.Row():
|
| 707 |
+
with gr.Column(scale=1):
|
| 708 |
+
gr.Markdown("### βοΈ μ€μ ")
|
| 709 |
+
|
| 710 |
+
# νκ²½λ³μ μν νμ
|
| 711 |
+
api_status = "β
API ν€ μ€μ λ¨" if os.getenv("FIREWORKS_API_KEY") else "β οΈ API ν€ λ―Έμ€μ (κΈ°λ³Έ ν΅κ³λ§ μ 곡)"
|
| 712 |
+
gr.Markdown(f"**π API μν**: {api_status}")
|
| 713 |
+
|
| 714 |
+
region_select = gr.CheckboxGroup(
|
| 715 |
+
choices=list(MarketDataLoader.REGIONS.keys()),
|
| 716 |
+
value=['μμΈ'],
|
| 717 |
+
label="π λΆμ μ§μ μ ν (μ΅λ 5κ° κΆμ₯)"
|
| 718 |
+
)
|
| 719 |
+
|
| 720 |
+
load_btn = gr.Button("π λ°μ΄ν° λ‘λ", variant="primary", size="lg")
|
| 721 |
+
|
| 722 |
+
status_box = gr.Markdown("π μ§μμ μ ννκ³ λ°μ΄ν°λ₯Ό λ‘λνμΈμ!")
|
| 723 |
+
|
| 724 |
+
with gr.Column(scale=3):
|
| 725 |
+
with gr.Tabs() as tabs:
|
| 726 |
+
with gr.Tab("π μΈμ¬μ΄νΈ λμ보λ", id=0) as tab1:
|
| 727 |
+
insights_content = gr.Column(visible=False)
|
| 728 |
+
|
| 729 |
+
with insights_content:
|
| 730 |
+
gr.Markdown("### πΊοΈ μ ν¬ λ°μ§λ ννΈλ§΅")
|
| 731 |
+
map_output = gr.HTML()
|
| 732 |
+
|
| 733 |
+
gr.Markdown("---")
|
| 734 |
+
gr.Markdown("### π 10κ°μ§ μ¬μΈ΅ μκΆ μΈμ¬μ΄νΈ")
|
| 735 |
+
|
| 736 |
+
with gr.Row():
|
| 737 |
+
chart1 = gr.Plot(label="μ
μ’
λ³ μ ν¬ μ")
|
| 738 |
+
chart2 = gr.Plot(label="λλΆλ₯ λΆν¬")
|
| 739 |
+
|
| 740 |
+
with gr.Row():
|
| 741 |
+
chart3 = gr.Plot(label="μΈ΅λ³ λΆν¬")
|
| 742 |
+
chart4 = gr.Plot(label="μ
μ’
λ€μμ±")
|
| 743 |
+
|
| 744 |
+
with gr.Row():
|
| 745 |
+
chart5 = gr.Plot(label="νλμ°¨μ΄μ¦ λΆμ")
|
| 746 |
+
chart6 = gr.Plot(label="μΈ΅ μ νΈλ")
|
| 747 |
+
|
| 748 |
+
with gr.Row():
|
| 749 |
+
chart7 = gr.Plot(label="μ§μ λ°μ§λ")
|
| 750 |
+
chart8 = gr.Plot(label="μ
μ’
μκ΄κ΄κ³")
|
| 751 |
+
|
| 752 |
+
with gr.Row():
|
| 753 |
+
chart9 = gr.Plot(label="μλΆλ₯ νΈλ λ")
|
| 754 |
+
chart10 = gr.Plot(label="μ§μ νΉν")
|
| 755 |
+
|
| 756 |
+
with gr.Tab("π€ AI λΆμ μ±λ΄", id=1) as tab2:
|
| 757 |
+
chat_content = gr.Column(visible=False)
|
| 758 |
+
|
| 759 |
+
with chat_content:
|
| 760 |
+
gr.Markdown("""
|
| 761 |
+
### π‘ μν μ§λ¬Έ
|
| 762 |
+
κ°λ¨μμ μΉ΄ν μ°½μ
? | μΉν¨μ§ ν¬ν μ§μ? | 1μΈ΅μ΄ μ 리ν μ
μ’
? | νλμ°¨μ΄μ¦ μ μ μ¨?
|
| 763 |
+
""")
|
| 764 |
+
|
| 765 |
+
chatbot = gr.Chatbot(height=400, label="AI μκΆ λΆμ μ΄μμ€ν΄νΈ")
|
| 766 |
+
|
| 767 |
+
with gr.Row():
|
| 768 |
+
msg_input = gr.Textbox(
|
| 769 |
+
placeholder="무μμ΄λ λ¬Όμ΄λ³΄μΈμ! (μ: κ°λ¨μμ μΉ΄ν μ°½μ
νλ €λ©΄?)",
|
| 770 |
+
show_label=False,
|
| 771 |
+
scale=4
|
| 772 |
+
)
|
| 773 |
+
submit_btn = gr.Button("μ μ‘", variant="primary", scale=1)
|
| 774 |
+
|
| 775 |
+
# μν λ²νΌλ€
|
| 776 |
+
with gr.Row():
|
| 777 |
+
sample_btn1 = gr.Button("κ°λ¨μμ μΉ΄ν μ°½μ
?", size="sm")
|
| 778 |
+
sample_btn2 = gr.Button("μΉν¨μ§ ν¬ν μ§μ?", size="sm")
|
| 779 |
+
sample_btn3 = gr.Button("1μΈ΅μ΄ μ 리ν μ
μ’
?", size="sm")
|
| 780 |
+
sample_btn4 = gr.Button("νλμ°¨μ΄μ¦ μ μ μ¨?", size="sm")
|
| 781 |
+
|
| 782 |
+
# μ΄λ²€νΈ νΈλ€λ¬
|
| 783 |
+
load_btn.click(
|
| 784 |
+
fn=load_data,
|
| 785 |
+
inputs=[region_select],
|
| 786 |
+
outputs=[status_box, insights_content, chat_content, tab1]
|
| 787 |
+
).then(
|
| 788 |
+
fn=generate_insights,
|
| 789 |
+
outputs=[map_output, chart1, chart2, chart3, chart4, chart5, chart6, chart7, chart8, chart9, chart10]
|
| 790 |
+
)
|
| 791 |
+
|
| 792 |
+
# μ±λ΄ μ΄λ²€νΈ (API ν€ νλΌλ―Έν° μ κ±°)
|
| 793 |
+
submit_btn.click(
|
| 794 |
+
fn=chat_respond,
|
| 795 |
+
inputs=[msg_input, chatbot],
|
| 796 |
+
outputs=[chatbot]
|
| 797 |
+
).then(
|
| 798 |
+
fn=lambda: "",
|
| 799 |
+
outputs=[msg_input]
|
| 800 |
+
)
|
| 801 |
+
|
| 802 |
+
msg_input.submit(
|
| 803 |
+
fn=chat_respond,
|
| 804 |
+
inputs=[msg_input, chatbot],
|
| 805 |
+
outputs=[chatbot]
|
| 806 |
+
).then(
|
| 807 |
+
fn=lambda: "",
|
| 808 |
+
outputs=[msg_input]
|
| 809 |
+
)
|
| 810 |
+
|
| 811 |
+
# μν λ²νΌ μ΄λ²€νΈ
|
| 812 |
+
for btn, text in [
|
| 813 |
+
(sample_btn1, "κ°λ¨μμ μΉ΄ν μ°½μ
?"),
|
| 814 |
+
(sample_btn2, "μΉν¨μ§ ν¬ν μ§μ?"),
|
| 815 |
+
(sample_btn3, "1μΈ΅μ΄ μ 리ν μ
μ’
?"),
|
| 816 |
+
(sample_btn4, "νλμ°¨μ΄μ¦ μ μ μ¨?")
|
| 817 |
+
]:
|
| 818 |
+
btn.click(
|
| 819 |
+
fn=lambda t=text, h=chatbot: chat_respond(t, h.value or []),
|
| 820 |
+
outputs=[chatbot]
|
| 821 |
+
)
|
| 822 |
+
|
| 823 |
+
gr.Markdown("""
|
| 824 |
+
---
|
| 825 |
+
### π μ¬μ© κ°μ΄λ
|
| 826 |
+
1. μ§μ μ ν β 2. λ°μ΄ν° λ‘λ β 3. 10κ°μ§ μΈμ¬μ΄νΈ νμΈ λλ AIμκ² μ§λ¬Έ
|
| 827 |
+
|
| 828 |
+
### π AI μ±λ΄ νμ±ν λ°©λ²
|
| 829 |
+
νκ²½λ³μ μ€μ :
|
| 830 |
+
```bash
|
| 831 |
+
export FIREWORKS_API_KEY="your_api_key_here"
|
| 832 |
+
```
|
| 833 |
+
|
| 834 |
+
Hugging Face Spaceμμλ:
|
| 835 |
+
1. Settings λ©λ΄ ν΄λ¦
|
| 836 |
+
2. Variables ν μ ν
|
| 837 |
+
3. New variable μΆκ°: `FIREWORKS_API_KEY`
|
| 838 |
+
|
| 839 |
+
### π μ 곡λλ 10κ°μ§ λΆμ
|
| 840 |
+
1. **μ
μ’
λ³ μ ν¬ μ**: κ°μ₯ λ§μ μ
μ’
TOP 15
|
| 841 |
+
2. **λλΆλ₯ λΆν¬**: μλ§€/μμ/μλΉμ€ λ± λλΆλ₯ λΉμ¨
|
| 842 |
+
3. **μΈ΅λ³ λΆν¬**: μ§ν/1μΈ΅/μμΈ΅ μ
μ§ λΆμ
|
| 843 |
+
4. **μ
μ’
λ€μμ±**: μ§μλ³ μ
μ’
λ€μμ± μ§μ
|
| 844 |
+
5. **νλμ°¨μ΄μ¦ λΆμ**: κ°μΈ vs νλμ°¨μ΄μ¦ λΉμ¨
|
| 845 |
+
6. **μΈ΅ μ νΈλ**: μ
μ’
λ³ μ νΈ μΈ΅μ
|
| 846 |
+
7. **μ§μ λ°μ§λ**: μ ν¬ μ μμ μ§μ
|
| 847 |
+
8. **μ
μ’
μκ΄κ΄κ³**: κ°μ΄ λνλλ μ
μ’
ν¨ν΄
|
| 848 |
+
9. **μλΆλ₯ νΈλ λ**: μΈλΆ μ
μ’
λΆν¬
|
| 849 |
+
10. **μ§μ νΉν**: κ° μ§μμ νΉν μ
μ’
|
| 850 |
+
|
| 851 |
+
π‘ **Tip**: API ν€ μμ΄λ 10κ°μ§ μκ°ν λΆμκ³Ό κΈ°λ³Έ ν΅κ³λ₯Ό νμΈν μ μμ΅λλ€!
|
| 852 |
+
""")
|
| 853 |
+
|
| 854 |
+
# μ€ν
|
| 855 |
+
if __name__ == "__main__":
|
| 856 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
|