Spaces:
Running
Running
File size: 15,542 Bytes
ff27984 68fece7 ed0deaf 8702770 43f1594 68fece7 43f1594 8702770 43f1594 f5b5cdc 8702770 43f1594 8702770 43f1594 8702770 43f1594 f5b5cdc 43f1594 f5b5cdc 8702770 43f1594 f5b5cdc 43f1594 f5b5cdc 43f1594 f5b5cdc 43f1594 28c3672 43f1594 8702770 a63a0bc 43f1594 a63a0bc 43f1594 e9b7506 43f1594 e9b7506 43f1594 a63a0bc 8702770 43f1594 8702770 43f1594 e9b7506 43f1594 a63a0bc 43f1594 e9b7506 f5b5cdc 8702770 43f1594 f5b5cdc 8702770 43f1594 f5b5cdc 43f1594 f5b5cdc 43f1594 f5b5cdc 43f1594 f5b5cdc 8702770 f5b5cdc 8702770 43f1594 f5b5cdc 43f1594 f5b5cdc 43f1594 f5b5cdc 8702770 43f1594 e9b7506 43f1594 8702770 43f1594 8702770 43f1594 8702770 43f1594 68fece7 8702770 43f1594 8702770 43f1594 8702770 43f1594 f5b5cdc 43f1594 f5b5cdc 43f1594 68fece7 43f1594 8702770 43f1594 8702770 a63a0bc 43f1594 8702770 43f1594 8702770 43f1594 8702770 a63a0bc 43f1594 a63a0bc 43f1594 8702770 43f1594 8702770 43f1594 8702770 43f1594 a63a0bc 43f1594 8702770 43f1594 ff27984 68fece7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 |
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import norm, skew
import platform
import os
import matplotlib.font_manager as fm
import warnings
warnings.filterwarnings('ignore')
# ์ ์ญ ํฐํธ ์ค์ - ์ฑ ์์ ์ฆ์ ์คํ
def configure_matplotlib_korean():
"""matplotlib ํ๊ธ ํฐํธ ๊ฐ์ ์ค์ """
# matplotlib ๋ฐฑ์๋ ์ค์
plt.switch_backend('Agg')
# ๊ธฐ์กด ์ค์ ์์ ์ด๊ธฐํ
plt.rcdefaults()
# ํฐํธ ์บ์ ์์ ์ญ์ ๋ฐ ์ฌ๊ตฌ์ฑ
try:
fm._load_fontmanager(try_read_cache=False)
except:
pass
# ์ด์์ฒด์ ๋ณ ํ๊ธ ํฐํธ ๊ฒฝ๋ก ์ง์ ์ง์
korean_font_paths = []
if platform.system() == 'Windows':
korean_font_paths = [
'C:/Windows/Fonts/malgun.ttf',
'C:/Windows/Fonts/gulim.ttc',
'C:/Windows/Fonts/batang.ttc',
]
fallback_font = 'Malgun Gothic'
elif platform.system() == 'Darwin': # macOS
korean_font_paths = [
'/System/Library/Fonts/AppleGothic.ttf',
'/System/Library/Fonts/Helvetica.ttc',
]
fallback_font = 'AppleGothic'
else: # Linux
korean_font_paths = [
'/usr/share/fonts/truetype/nanum/NanumGothic.ttf',
'/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf',
]
fallback_font = 'DejaVu Sans'
# ์ฌ์ฉ์ ์ ์ ํฐํธ ํ์ผ ๊ฒฝ๋ก๋ ์ถ๊ฐ
user_font = os.path.join(os.getcwd(), "NanumGaRamYeonGgoc.ttf")
if os.path.exists(user_font):
korean_font_paths.insert(0, user_font)
selected_font_path = None
selected_font_name = fallback_font
# ์ค์ ์กด์ฌํ๋ ํฐํธ ํ์ผ ์ฐพ๊ธฐ
for font_path in korean_font_paths:
if os.path.exists(font_path):
try:
font_prop = fm.FontProperties(fname=font_path)
selected_font_name = font_prop.get_name()
selected_font_path = font_path
# ํฐํธ ๋งค๋์ ์ ๊ฐ์ ๋ฑ๋ก
fm.fontManager.addfont(font_path)
break
except Exception as e:
continue
# matplotlib rcParams ๊ฐ์ ์ค์
plt.rcParams.update({
'font.family': 'sans-serif',
'font.sans-serif': [selected_font_name, 'DejaVu Sans', 'Arial', 'sans-serif'],
'axes.unicode_minus': False,
'font.size': 12,
'figure.dpi': 100,
'savefig.dpi': 100,
'figure.facecolor': 'white',
'axes.facecolor': 'white'
})
# ์ ์ญ ํฐํธ ์์ฑ ๊ฐ์ฒด ์์ฑ
if selected_font_path:
global KOREAN_FONT_PROP
KOREAN_FONT_PROP = fm.FontProperties(fname=selected_font_path)
else:
KOREAN_FONT_PROP = fm.FontProperties(family=selected_font_name)
return selected_font_name, selected_font_path
# ์ฑ ์์ ์ ์ฆ์ ํฐํธ ์ค์
FONT_NAME, FONT_PATH = configure_matplotlib_korean()
KOREAN_FONT_PROP = None
def apply_korean_font_to_plot():
"""๊ฐ๋ณ ํ๋กฏ์ ํ๊ธ ํฐํธ ์ง์ ์ ์ฉ"""
if FONT_PATH and os.path.exists(FONT_PATH):
font_prop = fm.FontProperties(fname=FONT_PATH)
return font_prop
else:
return fm.FontProperties(family=FONT_NAME)
def analyze_scores(df):
"""๋ฐ์ดํฐํ๋ ์์ ๋ฐ์ ๋ถ์ ๊ฒฐ๊ณผ๋ฅผ ํ์ํ๋ ํจ์"""
st.subheader("๐ ๋ฐ์ดํฐ ๋ฏธ๋ฆฌ๋ณด๊ธฐ (์์ 5๊ฐ)")
st.dataframe(df.head())
# ์ซ์ ํ์์ ์ด๋ง ์ ํ์ง๋ก ์ ๊ณต
numeric_columns = df.select_dtypes(include=np.number).columns.tolist()
if not numeric_columns:
st.error("โ ๋ฐ์ดํฐ์์ ๋ถ์ ๊ฐ๋ฅํ ์ซ์ ํ์์ ์ด์ ์ฐพ์ ์ ์์ต๋๋ค.")
return
score_column = st.selectbox("๐ ๋ถ์ํ ์ ์ ์ด(column)์ ์ ํํ์ธ์:", numeric_columns)
if score_column:
scores = df[score_column].dropna()
if len(scores) == 0:
st.error("โ ์ ํํ ์ด์ ์ ํจํ ๋ฐ์ดํฐ๊ฐ ์์ต๋๋ค.")
return
st.subheader(f"๐ '{score_column}' ์ ์ ๋ถํฌ ๋ถ์ ๊ฒฐ๊ณผ")
# 1. ๊ธฐ์ ํต๊ณ๋
st.write("#### ๐ ๊ธฐ๋ณธ ํต๊ณ๋")
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("ํ๊ท ", f"{scores.mean():.2f}")
with col2:
st.metric("ํ์คํธ์ฐจ", f"{scores.std():.2f}")
with col3:
st.metric("์ต์๊ฐ", f"{scores.min():.2f}")
with col4:
st.metric("์ต๋๊ฐ", f"{scores.max():.2f}")
# ์์ธ ํต๊ณ
st.write("#### ๐ ์์ธ ํต๊ณ๋")
st.dataframe(scores.describe().to_frame().T)
# 2. ๋ถํฌ ์๊ฐํ - ๊ฐํ๋ ํ๊ธ ํฐํธ ์ ์ฉ
st.write("#### ๐จ ์ ์ ๋ถํฌ ์๊ฐํ")
try:
# ํฐํธ ์์ฑ ๊ฐ์ฒด ์์ฑ
korean_font = apply_korean_font_to_plot()
# Figure ์์ฑ ๋ฐ ์ค์
fig, ax = plt.subplots(figsize=(14, 8))
fig.patch.set_facecolor('white')
# ํ์คํ ๊ทธ๋จ ์์ฑ
n, bins, patches = ax.hist(scores, bins=20, density=True, alpha=0.7,
color='skyblue', edgecolor='navy', linewidth=0.8)
# KDE ๊ณก์ ์ถ๊ฐ
try:
from scipy.stats import gaussian_kde
kde = gaussian_kde(scores)
x_range = np.linspace(scores.min(), scores.max(), 200)
ax.plot(x_range, kde(x_range), 'orange', linewidth=3, label='์ค์ ๋ถํฌ ๊ณก์ ')
except:
pass
# ์ ๊ท๋ถํฌ ๊ณก์ ์ถ๊ฐ
mu, std = norm.fit(scores)
x_norm = np.linspace(scores.min(), scores.max(), 100)
y_norm = norm.pdf(x_norm, mu, std)
ax.plot(x_norm, y_norm, 'red', linewidth=2, linestyle='--',
label=f'์ ๊ท๋ถํฌ (ํ๊ท ={mu:.1f}, ํ์คํธ์ฐจ={std:.1f})')
# ํ๊ท ์ ์ถ๊ฐ
ax.axvline(mu, color='red', linestyle=':', linewidth=2, alpha=0.8, label=f'ํ๊ท : {mu:.1f}')
# ์ ๋ชฉ๊ณผ ๋ผ๋ฒจ - ํ๊ธ ํฐํธ ์ง์ ์ ์ฉ
ax.set_title(f'{score_column} ์ ์ ๋ถํฌ ๋ถ์', fontproperties=korean_font, fontsize=18, pad=20)
ax.set_xlabel('์ ์', fontproperties=korean_font, fontsize=14)
ax.set_ylabel('๋ฐ๋', fontproperties=korean_font, fontsize=14)
# ๋ฒ๋ก ์ค์
legend = ax.legend(prop=korean_font, fontsize=11, loc='upper right')
legend.get_frame().set_alpha(0.9)
# ๊ฒฉ์ ์ถ๊ฐ
ax.grid(True, alpha=0.3, linestyle='-', linewidth=0.5)
# ํต๊ณ ์ ๋ณด ๋ฐ์ค
stats_text = f'์ํ ์: {len(scores)}\nํ๊ท : {mu:.2f}\nํ์คํธ์ฐจ: {std:.2f}\n์ต์๊ฐ: {scores.min():.1f}\n์ต๋๊ฐ: {scores.max():.1f}'
ax.text(0.02, 0.98, stats_text, transform=ax.transAxes,
fontproperties=korean_font, fontsize=10, verticalalignment='top',
bbox=dict(boxstyle='round,pad=0.5', facecolor='lightblue', alpha=0.8))
plt.tight_layout()
st.pyplot(fig)
except Exception as e:
st.error(f"โ ์์ธ ๊ทธ๋ํ ์์ฑ ์ค ์ค๋ฅ: {e}")
# ๋์ฒด ๊ทธ๋ํ (์์ด๋ง ์ฌ์ฉ)
st.write("**Alternative Chart (English only):**")
fig2, ax2 = plt.subplots(figsize=(10, 6))
ax2.hist(scores, bins=15, alpha=0.7, color='lightcoral', edgecolor='black')
ax2.set_title(f'Distribution of {score_column}', fontsize=14)
ax2.set_xlabel('Score')
ax2.set_ylabel('Frequency')
ax2.grid(True, alpha=0.3)
st.pyplot(fig2)
plt.close(fig2)
finally:
if 'fig' in locals():
plt.close(fig)
# 3. ์๋ ๋ถ์
st.write("#### ๐ ๋ถํฌ ํํ ๋ถ์ (์๋)")
try:
skewness = skew(scores)
col1, col2 = st.columns([1, 2])
with col1:
st.metric("์๋ (Skewness)", f"{skewness:.4f}")
with col2:
if skewness > 0.5:
st.success("๐ด **์์ ์๋ (Right Skewed)**: ๋๋ถ๋ถ ํ์์ด ๋ฎ์ ์ ์๋์ ๋ถํฌํ๊ณ , ์์์ ๊ณ ๋์ ์๊ฐ ์กด์ฌํฉ๋๋ค.")
elif skewness < -0.5:
st.success("๐ต **์์ ์๋ (Left Skewed)**: ๋๋ถ๋ถ ํ์์ด ๋์ ์ ์๋์ ๋ถํฌํ๊ณ , ์์์ ์ ๋์ ์๊ฐ ์กด์ฌํฉ๋๋ค.")
else:
st.success("๐ข **๋์นญ ๋ถํฌ**: ์ ์๊ฐ ํ๊ท ์ ์ค์ฌ์ผ๋ก ๊ณ ๋ฅด๊ฒ ๋ถํฌ๋์ด ์์ต๋๋ค.")
except Exception as e:
st.error(f"์๋ ๊ณ์ฐ ์ค ์ค๋ฅ: {e}")
# 4. ์ถ๊ฐ ๋ถ์
st.write("#### ๐ ๊ตฌ๊ฐ๋ณ ๋ถํฌ")
# ์ ์ ๊ตฌ๊ฐ ๋๋๊ธฐ
if scores.max() <= 100: # 100์ ๋ง์ ๊ฐ์
bins_labels = ['0-60', '61-70', '71-80', '81-90', '91-100']
bins_edges = [0, 60, 70, 80, 90, 100]
else:
# ๋์ ๊ตฌ๊ฐ ์์ฑ
min_score, max_score = scores.min(), scores.max()
interval = (max_score - min_score) / 5
bins_edges = [min_score + i * interval for i in range(6)]
bins_labels = [f'{bins_edges[i]:.0f}-{bins_edges[i+1]:.0f}' for i in range(5)]
try:
score_counts = pd.cut(scores, bins=bins_edges, labels=bins_labels, include_lowest=True).value_counts().sort_index()
score_percentages = (score_counts / len(scores) * 100).round(1)
result_df = pd.DataFrame({
'๊ตฌ๊ฐ': score_counts.index,
'ํ์ ์': score_counts.values,
'๋น์จ (%)': score_percentages.values
})
st.dataframe(result_df)
except Exception as e:
st.warning(f"๊ตฌ๊ฐ ๋ถ์ ์ค ์ค๋ฅ: {e}")
def main():
st.set_page_config(
page_title="ํ์ ์ ์ ๋ถ์ ๋๊ตฌ",
page_icon="๐",
layout="wide",
initial_sidebar_state="expanded"
)
# ์ ๋ชฉ
st.title("๐ ํ์ ์ ์ ๋ถํฌ ๋ถ์ ๋๊ตฌ")
st.markdown("**CSV ํ์ผ์ ์
๋ก๋ํ๊ฑฐ๋ Google Sheets URL์ ์
๋ ฅํ์ฌ ์ ์ ๋ถํฌ๋ฅผ ๋ถ์ํ์ธ์**")
# ํฐํธ ์ ๋ณด ํ์
with st.expander("๐ง ํฐํธ ์ค์ ์ ๋ณด"):
st.write(f"**ํ์ฌ ํฐํธ**: {FONT_NAME}")
st.write(f"**ํฐํธ ๊ฒฝ๋ก**: {FONT_PATH if FONT_PATH else '์์คํ
๊ธฐ๋ณธ'}")
# ํฐํธ ํ
์คํธ
if st.button("ํฐํธ ํ
์คํธ"):
try:
test_fig, test_ax = plt.subplots(figsize=(8, 3))
korean_font = apply_korean_font_to_plot()
test_ax.text(0.5, 0.7, 'ํ๊ธ ํฐํธ ํ
์คํธ', ha='center', va='center',
fontproperties=korean_font, fontsize=16)
test_ax.text(0.5, 0.3, '์ ์ ๋ถํฌ ๋ถ์ ๊ทธ๋ํ', ha='center', va='center',
fontproperties=korean_font, fontsize=14)
test_ax.set_xlim(0, 1)
test_ax.set_ylim(0, 1)
test_ax.axis('off')
st.pyplot(test_fig)
plt.close(test_fig)
except Exception as e:
st.error(f"ํฐํธ ํ
์คํธ ์คํจ: {e}")
st.markdown("---")
# ์ฌ์ด๋๋ฐ - ๋ฐ์ดํฐ ์
๋ ฅ
st.sidebar.title("๐ ๋ฐ์ดํฐ ๊ฐ์ ธ์ค๊ธฐ")
source_option = st.sidebar.radio(
"๋ฐ์ดํฐ ์์ค ์ ํ:",
("๐ค CSV ํ์ผ ์
๋ก๋", "๐ Google Sheets URL", "๐ฒ ์ํ ๋ฐ์ดํฐ")
)
df = None
if source_option == "๐ค CSV ํ์ผ ์
๋ก๋":
uploaded_file = st.sidebar.file_uploader(
"CSV ํ์ผ์ ์ ํํ์ธ์",
type=["csv"],
help="UTF-8, CP949 ๋ฑ ๋ค์ํ ์ธ์ฝ๋ฉ์ ์๋์ผ๋ก ๊ฐ์งํฉ๋๋ค"
)
if uploaded_file:
encodings = ['utf-8-sig', 'utf-8', 'cp949', 'euc-kr', 'latin1']
for encoding in encodings:
try:
df = pd.read_csv(uploaded_file, encoding=encoding)
st.sidebar.success(f"โ
ํ์ผ ๋ก๋ฉ ์ฑ๊ณต! (์ธ์ฝ๋ฉ: {encoding})")
break
except UnicodeDecodeError:
continue
except Exception as e:
st.sidebar.error(f"ํ์ผ ์ฝ๊ธฐ ์ค๋ฅ: {e}")
break
if df is None:
st.sidebar.error("โ ํ์ผ ์ธ์ฝ๋ฉ์ ์ธ์ํ ์ ์์ต๋๋ค.")
elif source_option == "๐ Google Sheets URL":
st.sidebar.info("๐ก Google Sheets๋ฅผ '์น์ ๊ฒ์'ํ ํ CSV URL์ ์
๋ ฅํ์ธ์")
url = st.sidebar.text_input(
"Google Sheets CSV URL",
placeholder="https://docs.google.com/spreadsheets/d/..."
)
if url and "docs.google.com" in url:
try:
with st.spinner("๐ฅ ๋ฐ์ดํฐ ๋ก๋ฉ ์ค..."):
df = pd.read_csv(url)
st.sidebar.success("โ
Google Sheets ๋ก๋ฉ ์ฑ๊ณต!")
except Exception as e:
st.sidebar.error(f"โ URL ๋ก๋ฉ ์คํจ: {e}")
elif url:
st.sidebar.warning("โ ๏ธ ์ฌ๋ฐ๋ฅธ Google Sheets URL์ ์
๋ ฅํ์ธ์")
elif source_option == "๐ฒ ์ํ ๋ฐ์ดํฐ":
if st.sidebar.button("์ํ ๋ฐ์ดํฐ ์์ฑ"):
np.random.seed(42)
sample_size = st.sidebar.slider("์ํ ํฌ๊ธฐ", 50, 500, 100)
df = pd.DataFrame({
'ํ์๋ฒํธ': range(1, sample_size + 1),
'์ํ์ ์': np.random.normal(75, 15, sample_size).clip(0, 100).round(1),
'์์ด์ ์': np.random.normal(80, 12, sample_size).clip(0, 100).round(1),
'๊ณผํ์ ์': np.random.normal(70, 18, sample_size).clip(0, 100).round(1),
'๊ตญ์ด์ ์': np.random.normal(77, 14, sample_size).clip(0, 100).round(1)
})
st.sidebar.success(f"โ
{sample_size}๋ช
์ ์ํ ๋ฐ์ดํฐ ์์ฑ!")
# ๋ฉ์ธ ๋ถ์
if df is not None and not df.empty:
st.success(f"๐ ๋ฐ์ดํฐ ๋ก๋ฉ ์๋ฃ! **{len(df)}๊ฐ ํ, {len(df.columns)}๊ฐ ์ด**")
analyze_scores(df)
else:
st.info("๐ **์ฌ์ด๋๋ฐ์์ ๋ฐ์ดํฐ๋ฅผ ์ ํํ์ธ์**")
# ๊ธฐ๋ฅ ์๋ด
st.markdown("""
### ๐ ์ฃผ์ ๊ธฐ๋ฅ
- **๐ ๊ธฐ๋ณธ ํต๊ณ**: ํ๊ท , ํ์คํธ์ฐจ, ์ต์๊ฐ, ์ต๋๊ฐ ๋ฑ
- **๐ ๋ถํฌ ์๊ฐํ**: ํ์คํ ๊ทธ๋จ, KDE ๊ณก์ , ์ ๊ท๋ถํฌ ๋น๊ต
- **๐ ์๋ ๋ถ์**: ๋ถํฌ์ ๋น๋์นญ์ฑ ์ธก์
- **๐ ๊ตฌ๊ฐ๋ณ ๋ถํฌ**: ์ ์ ๊ตฌ๊ฐ๋ณ ํ์ ์ ๋ฐ ๋น์จ
### ๐ ์ง์ ํ์
- **CSV ํ์ผ**: UTF-8, CP949, EUC-KR ๋ฑ ์๋ ์ธ์ฝ๋ฉ ๊ฐ์ง
- **Google Sheets**: ์น์ ๊ฒ์๋ ์ํธ์ CSV URL
- **์ํ ๋ฐ์ดํฐ**: ํ
์คํธ์ฉ ๊ฐ์ ์ ์ ๋ฐ์ดํฐ
""")
if __name__ == '__main__':
main() |