Spaces:
Runtime error

SimHS98
s
9b72184
Raw History Blame Contribute Delete
14.7 kB
# -*- coding: utf-8 -*-
import streamlit as st
import pandas as pd
import requests
import gspread
import plotly.express as px
from google.oauth2.service_account import Credentials
from gspread_dataframe import set_with_dataframe
# ============================================================
# 🚀 Global MD Tool — Streamlit Frontend (v4)
# 병합 완전 대응 / 환율 제거 / 전체 구조 유지형
# ============================================================
# ------------------------------------------------------------
# 1️⃣ Hugging Face API URL 설정
# ------------------------------------------------------------
HF_API_URL = "https://ceostaff-global-md-tool-api.hf.space" # 🛑 실제 Hugging Face Space URL로 교체
# ------------------------------------------------------------
# 2️⃣ Google Sheet 및 API 인증
# ------------------------------------------------------------
try:
HF_API_TOKEN = st.secrets["huggingface"]["api_token"]
HF_HEADERS = {"Authorization": f"Bearer {HF_API_TOKEN}"}
GOOGLE_CREDS_DICT = st.secrets["google_service_account"]
SOURCE_GSHEET_KEY = "1E7_qeS7l6T58b2C9xPse0kHalillbv2uz6xMKBLAHQ8"
SOURCE_SHEET_NAME = "Total_Sales Report"
DEST_GSHEET_KEY = "134B_oQVXrW1x9fop10ZgsnwOTGmZZ4y-T5lTxecEp5w"
DEST_SHEET_STG_SALES = "stg_Sales"
DEST_SHEET_STG_ADS = "stg_Ads"
except KeyError as e:
st.error(f"⚠️ st.secrets에 필요한 키가 없습니다: {e}")
st.stop()
# ------------------------------------------------------------
# 3️⃣ Google Sheets 인증 함수
# ------------------------------------------------------------
@st.cache_resource(ttl=3600)
def authenticate_google_sheets():
try:
scopes = [
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/drive"
]
creds = Credentials.from_service_account_info(GOOGLE_CREDS_DICT, scopes=scopes)
client = gspread.authorize(creds)
return client
except Exception as e:
st.error(f"Google Sheets 인증 실패: {e}")
return None
# ------------------------------------------------------------
# 4️⃣ Streamlit 페이지 설정 및 사이드바
# ------------------------------------------------------------
st.set_page_config(page_title="Global MD Tool", layout="wide")
st.sidebar.title("📈 Global MD Tool")
menu = st.sidebar.radio(
"메뉴",
["🏠 메인 대시보드", "🔍 상세 데이터 테이블", "⚙️ 데이터 관리 (ETL)"],
label_visibility="collapsed"
)
# ------------------------------------------------------------
# 5️⃣ 메인 대시보드
# ------------------------------------------------------------
if menu == "🏠 메인 대시보드":
st.title("🏠 메인 대시보드")
api_endpoint = f"{HF_API_URL}/main_dashboard"
try:
with st.spinner("메인 대시보드 데이터를 불러오는 중입니다..."):
res = requests.post(api_endpoint, headers=HF_HEADERS)
res.raise_for_status()
data = res.json()
st.header("📊 Total 기준 핵심 성과 (KRW)")
kpi = data.get("total_kpi", {})
kpi_cols = st.columns(3)
kpi_cols[0].metric("총 매출 (Total Sales)", f"₩ {kpi.get('total_sales', 0):,.0f}")
kpi_cols[1].metric("총 광고비 (Total Ads)", f"₩ {kpi.get('total_ads', 0):,.0f}")
kpi_cols[2].metric("총 ROAS", f"{kpi.get('total_roas', 0):.1f} %")
st.header("📈 일자별 매출 및 광고비 추이 (Total)")
date_trend_df = pd.DataFrame(data.get("date_trend", []))
if not date_trend_df.empty:
date_trend_df["Date"] = pd.to_datetime(date_trend_df["Date"])
st.line_chart(date_trend_df.set_index("Date"))
else:
st.info("일자별 추이 데이터가 없습니다.")
st.header("🌍 국가별 성과 비교 (KRW)")
country_summary_df = pd.DataFrame(data.get("country_summary", []))
if not country_summary_df.empty:
fig_sales = px.bar(country_summary_df, x="Country", y="매출", title="국가별 매출")
st.plotly_chart(fig_sales, use_container_width=True)
fig_ads = px.bar(country_summary_df, x="Country", y="광고비", title="국가별 광고비")
st.plotly_chart(fig_ads, use_container_width=True)
fig_roas = px.bar(country_summary_df, x="Country", y="ROAS", title="국가별 ROAS")
st.plotly_chart(fig_roas, use_container_width=True)
else:
st.info("국가별 요약 데이터가 없습니다.")
except requests.exceptions.RequestException as e:
st.error(f"❌ Hugging Face API 호출 실패: {e}")
# ------------------------------------------------------------
# 6️⃣ 상세 데이터 테이블
# ------------------------------------------------------------
elif menu == "🔍 상세 데이터 테이블":
st.title("🔍 상세 데이터 테이블")
countries = ["SG", "MY", "PH", "TW", "TH", "VN", "US", "Unknown"]
channels = ["Shopee", "Shopify", "Amazon", "TikTok", "Meta", "Unknown"]
st.subheader("데이터 필터")
filter_cols = st.columns(2)
selected_countries = filter_cols[0].multiselect("국가 선택", countries, default=countries)
selected_channels = filter_cols[1].multiselect("채널 선택", channels, default=channels)
if st.button("🔍 데이터 조회"):
api_endpoint = f"{HF_API_URL}/filtered_data_table"
payload = {"countries": selected_countries, "channels": selected_channels}
try:
with st.spinner("필터링된 데이터를 조회 중입니다..."):
res = requests.post(api_endpoint, headers=HF_HEADERS, json=payload)
res.raise_for_status()
data = res.json()
st.subheader("📊 요약 차트")
col1, col2 = st.columns(2)
sales_summary_df = pd.DataFrame(data.get("summary_chart_sales", []))
ads_summary_df = pd.DataFrame(data.get("summary_chart_ads", []))
if not sales_summary_df.empty:
col1.bar_chart(sales_summary_df.set_index("Channel"))
else:
col1.info("매출 데이터 없음")
if not ads_summary_df.empty:
col2.bar_chart(ads_summary_df.set_index("Channel"))
else:
col2.info("광고 데이터 없음")
st.subheader("Sales 상세 데이터")
sales_df = pd.DataFrame(data.get("sales_data", []))
if not sales_df.empty:
st.dataframe(sales_df)
else:
st.warning("조회된 Sales 데이터가 없습니다.")
st.subheader("Ads 상세 데이터")
ads_df = pd.DataFrame(data.get("ads_data", []))
if not ads_df.empty:
st.dataframe(ads_df)
else:
st.warning("조회된 Ads 데이터가 없습니다.")
except requests.exceptions.RequestException as e:
st.error(f"❌ Hugging Face API 호출 실패: {e}")
# ------------------------------------------------------------
# 7️⃣ 데이터 관리 (ETL)
# ------------------------------------------------------------
elif menu == "⚙️ 데이터 관리 (ETL)":
st.title("⚙️ 데이터 관리 (Google Sheet-to-Sheet ETL)")
st.info("이 기능은 '원본' 멀티헤더 시트를 '결과' 표준 시트로 변환(ETL)하여 덮어씁니다.")
# --------------------------------------------------------
# 병합 완전 대응형 원본 데이터 로드 함수
# --------------------------------------------------------
@st.cache_data(ttl=600)
def load_source_data(_client):
"""가로+세로 병합을 자동 확장하여 DataFrame으로 반환"""
try:
spreadsheet = _client.open_by_key(SOURCE_GSHEET_KEY)
ws = spreadsheet.worksheet(SOURCE_SHEET_NAME)
header_rows = ws.get('1:3')
data = ws.get('4:' + str(ws.row_count))
if not data:
st.error("원본 시트에 데이터가 없습니다.")
return pd.DataFrame()
# 1️⃣ 행 길이 보정
max_len = max(len(r) for r in header_rows)
header_rows = [r + [''] * (max_len - len(r)) for r in header_rows]
data = [r + [''] * (max_len - len(r)) for r in data]
# 2️⃣ 가로 병합 확장
def fill_left_merge(row):
last_val = ''
new_row = []
for cell in row:
if cell.strip() != '':
last_val = cell.strip()
new_row.append(last_val)
return new_row
header_rows = [fill_left_merge(r) for r in header_rows]
# 3️⃣ 세로 병합 확장
header_df = pd.DataFrame(header_rows).T
header_df = header_df.replace('', pd.NA).ffill(axis=1)
header_rows_filled = header_df.T.values.tolist()
# 4️⃣ MultiIndex 생성
header_l1 = [h if h else pd.NA for h in header_rows_filled[0]]
header_l2 = [h if h else pd.NA for h in header_rows_filled[1]]
header_l3 = [h if h else pd.NA for h in header_rows_filled[2]]
df = pd.DataFrame(data)
df.columns = pd.MultiIndex.from_arrays([header_l1, header_l2, header_l3])
df.columns = (
df.columns.to_frame()
.fillna(method='ffill')
.apply(tuple, axis=1)
.values
)
df.columns = pd.MultiIndex.from_tuples(df.columns)
date_col_tuple = df.columns[0]
df = df.rename(columns={date_col_tuple: ("일자", "일자", "일자")})
return df
except Exception as e:
st.error(f"원본 데이터 로드 중 오류: {e}")
return pd.DataFrame()
# --------------------------------------------------------
# 데이터 변환 함수 (기존 transform_to_long_format 유지)
# --------------------------------------------------------
def transform_to_long_format(df_wide):
"""병합된 멀티헤더를 인식하여 stg_Sales / stg_Ads로 분리 변환"""
if df_wide.empty:
return pd.DataFrame(), pd.DataFrame()
df = df_wide.copy()
# 1️⃣ 헤더 단일화 (의미 있는 레벨만 유지)
new_cols = []
for col in df.columns:
# ('일자','일자','일자') → Date
if col[0] == "일자":
new_cols.append("Date")
continue
# 중복된 텍스트(예: Units_Units_Units)는 하나만 남김
unique_parts = []
for part in col:
if pd.notna(part) and part not in unique_parts:
unique_parts.append(str(part))
col_name = "_".join(unique_parts).strip("_")
new_cols.append(col_name)
df.columns = new_cols
# 2️⃣ 날짜 및 숫자형 변환
df["Date"] = pd.to_datetime(df["Date"], errors='coerce')
numeric_cols = [col for col in df.columns if col != "Date"]
df[numeric_cols] = df[numeric_cols].apply(pd.to_numeric, errors='coerce').fillna(0)
# 3️⃣ Long Format 변환
df_long = df.melt(id_vars=["Date"], var_name="Metric_Raw", value_name="Value")
# 4️⃣ 헤더 분해 (패턴 인식: SG_매출_쇼피파이(KRW))
split_cols = df_long["Metric_Raw"].str.split('_', n=3, expand=True)
while len(split_cols.columns) < 4:
split_cols[len(split_cols.columns)] = None
split_cols.columns = ["Country", "Metric_Type", "Channel", "Currency_Raw"]
# 5️⃣ 통화 분리 (예: 쇼피파이(KRW) → 쇼피파이 / KRW)
currency_split = split_cols["Channel"].str.extract(r'(.+)\((.+)\)')
split_cols["Channel"] = currency_split[0].fillna(split_cols["Channel"])
split_cols["Currency"] = currency_split[1].fillna(split_cols["Currency_Raw"])
df_long = pd.concat([df_long, split_cols[["Country", "Metric_Type", "Channel", "Currency"]]], axis=1)
# 6️⃣ Sales / Ads 분리
df_sales = df_long[df_long["Metric_Type"].str.contains("매출|Sales|Units", na=False)].copy()
df_ads = df_long[df_long["Metric_Type"].str.contains("지출|Ads|광고비|Impressions|Clicks", na=False)].copy()
# 7️⃣ 표준 컬럼 구성
df_sales = df_sales.rename(columns={"Value": "Amount_Local"})
df_sales["Units"] = 0
df_sales = df_sales[["Date", "Country", "Channel", "Amount_Local", "Currency", "Metric_Type", "Units"]]
df_ads = df_ads.rename(columns={"Value": "Amount_Local"})
df_ads["Campaign"] = ""
df_ads = df_ads[["Date", "Country", "Channel", "Amount_Local", "Currency", "Metric_Type", "Campaign"]]
return df_sales, df_ads
# --------------------------------------------------------
# ETL 실행
# --------------------------------------------------------
if st.button("🚀 ETL 실행 (원본 → 결과)"):
client = authenticate_google_sheets()
if not client:
st.stop()
logs = []
with st.spinner(f"`{SOURCE_SHEET_NAME}` 시트 로드 중..."):
df_wide = load_source_data(client)
if df_wide.empty:
st.stop()
logs.append("✅ 원본 시트 로드 완료")
with st.spinner("데이터 표준화(Long Format) 중..."):
stg_sales_df, stg_ads_df = transform_to_long_format(df_wide)
logs.append("✅ 데이터 변환 완료")
try:
spreadsheet = client.open_by_key(DEST_GSHEET_KEY)
if not stg_sales_df.empty:
ws_sales = spreadsheet.worksheet(DEST_SHEET_STG_SALES)
ws_sales.clear()
set_with_dataframe(ws_sales, stg_sales_df, include_index=False, resize=True)
logs.append(f"✅ {DEST_SHEET_STG_SALES} 업로드 완료 ({len(stg_sales_df)}행)")
if not stg_ads_df.empty:
ws_ads = spreadsheet.worksheet(DEST_SHEET_STG_ADS)
ws_ads.clear()
set_with_dataframe(ws_ads, stg_ads_df, include_index=False, resize=True)
logs.append(f"✅ {DEST_SHEET_STG_ADS} 업로드 완료 ({len(stg_ads_df)}행)")
st.success("🎉 모든 ETL 작업 완료!")
st.json(logs)
except Exception as e:
st.error(f"Google Sheet 업로드 중 오류: {e}")