# -*- 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}")