Spaces:
Sleeping
Sleeping
SimHS98 commited on
Commit ยท
06276af
1
Parent(s): fc9113f
Files changed (4)
- .gitignore+7-9
- hf_api.pyAdded+170
- main.py+192-130
- requirmenets.txtAdded+20
12345678910111213# .gitignore# Hugging Face API ํ ํฐhf_api_token.txt# ๊ตฌ๊ธ ์๋น์ค ๊ณ์ JSON ํ์ผDooly_credentials.json# .env ํ์ผ (ํ๊ฒฝ ๋ณ์).env# Streamlit secrets.toml ํ์ผ (๋น๋ฐ ์ ๋ณด).streamlit/secrets.toml1234567891011# .gitignore (์ด ํ์ผ์ ๊ผญ ๋ง๋์ธ์)# Google ์ธ์ฆ ํ์ผ (์ ๋ ์ ๋ก๋ ๊ธ์ง)Dooly_credentials.json# Streamlit ๋น๋ฐ ํค ํ์ผ (๋ก์ปฌ์ฉ).streamlit/secrets.toml# Python ์บ์ ํ์ผ__pycache__/*.pyc
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170# hf_api.py
import pandas as pdimport requestsimport uvicornfrom fastapi import FastAPI, Requestfrom fastapi.responses import JSONResponsefrom pydantic import BaseModel, Fieldfrom io import StringIOfrom functools import lru_cache
app = FastAPI(title="Global MD Tool API")
# ---# 1. ๋ฐ์ดํฐ ์์ค (Google Sheet)# (๋ธ๋ผ์ฐ์ URL์ด ์๋ CSV ๋ด๋ณด๋ด๊ธฐ URL์ ์ฌ์ฉํด์ผ ํฉ๋๋ค.)# ์๋ณธ URL: https://docs.google.com/spreadsheets/d/1smCvYAOffV7Z6jdEjitH47PXAHwTK7-KejcMztwbt54/edit?gid=1467483093# ---SHEET_ID = "1smCvYAOffV7Z6jdEjitH47PXAHwTK7-KejcMztwbt54"GID = "1467483093"GSHEET_CSV_URL = f"https://docs.google.com/spreadsheets/d/{SHEET_ID}/export?format=csv&gid={GID}"
# ---# 2. Pydantic ๋ชจ๋ธ (์์ฒญ Body ๊ฒ์ฆ์ฉ)# ---class FilterPayload(BaseModel): country: str = "Total" metrics: list[str] = Field(default_factory=list) channels: list[str] = Field(default_factory=list)
# ---# 3. ๋ฐ์ดํฐ ๋ก๋ฉ ๋ฐ ํด๋ฆฌ๋# (lru_cache: API ํธ์ถ ์๋ง๋ค GSheet์ ์ฝ์ง ์๊ณ , ๋ฉ๋ชจ๋ฆฌ์ ์บ์ํ์ฌ ์๋ ํฅ์)# ---@lru_cache(maxsize=1)def get_cleaned_data(): """ Google Sheet์์ ๋ฐ์ดํฐ๋ฅผ ์ฝ๊ณ 3๋จ ํค๋๋ฅผ ์ฒ๋ฆฌํ์ฌ ๋ ์ง ๋ณํ ๋ฐ ์ซ์ ๋ณํ๊น์ง ์๋ฃํ DataFrame์ ๋ฐํํฉ๋๋ค. """ try: csv_text = requests.get(GSHEET_CSV_URL).text # 3์ค ํค๋๋ก CSV ์ฝ๊ธฐ df = pd.read_csv(StringIO(csv_text), header=[0, 1, 2]) # 1. ๋ค๋จ ํค๋๋ฅผ '_'๋ก ๊ฒฐํฉ new_cols = [] for col in df.columns: # ('SG', '๋งค์ถ', '์ผํผํ์ด') -> "SG_๋งค์ถ_์ผํผํ์ด" col_name = "_".join([str(x) for x in col if str(x).lower() != "nan"]).strip() new_cols.append(col_name) df.columns = new_cols
# 2. ๋ ์ง ์ด(์ฒซ ๋ฒ์งธ ์ด) ์ด๋ฆ ๋ณ๊ฒฝ ๋ฐ ํ์
๋ณํ # ('Unnamed: 0_nan_nan' -> 'Unnamed: 0') date_col = df.columns[0] df = df.rename(columns={date_col: "Date"}) df["Date"] = pd.to_datetime(df["Date"], errors='coerce') df = df.dropna(subset=["Date"]) # ๋ ์ง ์๋ ํ ์ ๊ฑฐ # 3. ๋ ์ง ์ด์ ์ ์ธํ ๋ชจ๋ ์ด์ ์ซ์๋ก ๋ณํ 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) return df
except Exception as e: print(f"Error loading data: {e}") return pd.DataFrame()
# ---# 4. API ์๋ํฌ์ธํธ# ---
@app.get("/")def read_root(): return {"status": "Global MD Tool API is running."}
@app.post("/main_dashboard")async def get_main_dashboard_data(): """ ๋ฉ์ธ ๋์๋ณด๋์ ํ์ํ ํต์ฌ KPI, ๋ ์ง๋ณ ์ถ์ด, ๊ตญ๊ฐ๋ณ ์์ฝ ๋ฐ์ดํฐ๋ฅผ ๋ฐํํฉ๋๋ค. """ df = get_cleaned_data() if df.empty: return JSONResponse(status_code=500, content={"error": "Data loading failed"})
# 1. Total KPI ๊ณ์ฐ total_sales = df.filter(like="๋งค์ถ").sum().sum() total_ads = df.filter(like="์ง์ถ").sum().sum() total_roas = (total_sales / total_ads) * 100 if total_ads else 0
# 2. ์ผ์๋ณ ์ถ์ด (Total ๊ธฐ์ค) date_trend = df.set_index("Date") date_trend_sales = date_trend.filter(like="๋งค์ถ").sum(axis=1).resample('D').sum().reset_index() date_trend_ads = date_trend.filter(like="์ง์ถ").sum(axis=1).resample('D').sum().reset_index() date_trend_df = pd.merge( date_trend_sales.rename(columns={0: "Total ๋งค์ถ"}), date_trend_ads.rename(columns={0: "Total ์ง์ถ"}), on="Date" )
# 3. ๊ตญ๊ฐ๋ณ ์ฑ๊ณผ ์์ฝ (SG, MY, PH...) countries = ["SG", "MY", "PH", "TW", "TH", "VN"] country_summary = [] for country in countries: country_sales = df.filter(regex=f"^{country}_.*๋งค์ถ").sum().sum() country_ads = df.filter(regex=f"^{country}_.*์ง์ถ").sum().sum() country_roas = (country_sales / country_ads) * 100 if country_ads else 0 country_summary.append({ "๊ตญ๊ฐ": country, "๋งค์ถ": country_sales, "๊ด๊ณ ๋น": country_ads, "ROAS": country_roas }) country_summary_df = pd.DataFrame(country_summary)
return JSONResponse({ "total_kpi": { "total_sales": total_sales, "total_ads": total_ads, "total_roas": total_roas }, "date_trend": date_trend_df.to_dict(orient="records"), "country_summary": country_summary_df.to_dict(orient="records") })
@app.post("/filtered_data")async def get_filtered_data(payload: FilterPayload): """ ์ฌ์ฉ์ ํํฐ(๊ตญ๊ฐ, ์งํ, ์ฑ๋)์ ๋ง๋ ๋ฐ์ดํฐ๋ฅผ ํํฐ๋งํ์ฌ ๋ฐํํฉ๋๋ค. """ df = get_cleaned_data() if df.empty: return JSONResponse(status_code=500, content={"error": "Data loading failed"})
filtered_df = df.copy() # 1. ๋ ์ง ์ด(๏ฟฝ๏ฟฝ์) + ํํฐ๋ง๋ ์ด ์ ํ cols_to_keep = ["Date"] data_cols = [col for col in df.columns if col != "Date"]
# 2. ๊ตญ๊ฐ ํํฐ๋ง if payload.country and payload.country != "Total": data_cols = [c for c in data_cols if c.startswith(f"{payload.country}_")] # 3. ์งํ ํํฐ๋ง if payload.metrics: data_cols = [c for c in data_cols if any(metric in c for metric in payload.metrics)] # 4. ์ฑ๋ ํํฐ๋ง if payload.channels: data_cols = [c for c in data_cols if any(channel in c for channel in payload.channels)]
final_cols = cols_to_keep + data_cols filtered_df = df[final_cols] # 5. ํํฐ๋ง๋ ๋ฐ์ดํฐ์ ์์ฝ (ํ๋จ ๊ทธ๋ํ์ฉ) summary = filtered_df.drop(columns="Date").sum().reset_index() summary.columns = ["Column", "Total"]
return JSONResponse({ "table_data": filtered_df.to_dict(orient="records"), "summary_chart_data": summary.to_dict(orient="records") })
# (๋ก์ปฌ ํ
์คํธ์ฉ)if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8000)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138import streamlit as stfrom transformers import pipelineimport gspreadfrom google.oauth2.service_account import Credentialsimport pandas as pd# 1. Streamlit Secrets์์ ๋น๋ฐ ์ ๋ณด ๊ฐ์ ธ์ค๊ธฐhf_api_token = st.secrets["huggingface"]["api_token"] # Hugging Face API ํ ํฐservice_account_json = st.secrets["google"]["service_account_json"] # Google ์๋น์ค ๊ณ์ JSON ํ์ผ ๊ฒฝ๋ก# 2. Hugging Face ๋ชจ๋ธ ๋ก๋ (API ํ ํฐ์ ์ฌ์ฉํ์ฌ ์ธ์ฆ)model = pipeline('sentiment-analysis', use_auth_token=hf_api_token)# 3. ๊ตฌ๊ธ ์คํ๋ ๋์ํธ ์ธ์ฆdef authenticate_google_sheets():"""๊ตฌ๊ธ ์คํ๋ ๋์ํธ ์ธ์ฆ ๋ฐ ํด๋ผ์ด์ธํธ ๋ฐํ"""scopes = ["https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive"]creds = Credentials.from_service_account_file(service_account_json, scopes=scopes)client = gspread.authorize(creds)return client# 4. ๊ตฌ๊ธ ์ํธ์์ ๋ฐ์ดํฐ ์ฝ๊ธฐdef read_from_google_sheet(client, spreadsheet_url, sheet_name, header_row):"""์ฃผ์ด์ง ์คํ๋ ๋์ํธ URL๊ณผ ์ํธ์ด๋ฆ์ผ๋ก ๋ฐ์ดํฐ๋ฅผ ์ฝ๊ณ DataFrame ์ผ๋ก ๋ฐํ.ํค๋๊ฐ ์์ผ๋ฉด ์๋์ผ๋ก ์์ฑ."""spreadsheet = client.open_by_url(spreadsheet_url)try:worksheet = spreadsheet.worksheet(sheet_name)except gspread.exceptions.WorksheetNotFound:# ์ํธ๊ฐ ์์ผ๋ฉด ์์ฑspreadsheet.add_worksheet(title=sheet_name, rows="1000", cols="50")worksheet = spreadsheet.worksheet(sheet_name)# ํค๋ ์๋ ์์ฑworksheet.append_row(header_row)st.info(f"์ํธ '{sheet_name}'์ด(๊ฐ) ์๋ ์์ฑ๋๊ณ ํค๋๊ฐ ์ค์ ๋์์ต๋๋ค.")values = worksheet.get_all_records()df = pd.DataFrame(values)return df, worksheet# 5. ๊ตฌ๊ธ ์ํธ์ ๋ฐ์ดํฐ ์ฐ๊ธฐdef write_to_google_sheet(worksheet, df):"""DataFrame ๋ฐ์ดํฐ๋ฅผ ํด๋น ์ํฌ์ํธ์ ์จ์ ๋ฎ์ด์."""worksheet.clear()worksheet.update([df.columns.values.tolist()] + df.values.tolist())# 6. Hugging Face ๋ชจ๋ธ์ ์ฌ์ฉํ ์์ ํ ์คํธ ๋ถ์def analyze_sentiment(text):"""Hugging Face ๋ชจ๋ธ์ ์ฌ์ฉํ์ฌ ํ ์คํธ ๋ถ์ ๊ฒฐ๊ณผ ๋ฐํ"""result = model(text)return result# 7. Streamlit ๋์๋ณด๋ ๊ตฌ์ฑdef display_dashboard():st.title("ํ๋งคยท๊ด๊ณ ์๋ํ ๋์๋ณด๋")# ๊ตฌ๊ธ ์คํ๋ ๋์ํธ ์ค์ spreadsheet_url = "https://docs.google.com/spreadsheets/d/134B_oQVXrW1x9fop10ZgsnwOTGmZZ4y-T5lTxecEp5w/edit?gid=0#gid=0"# ํ์ค ๋ฐ์ดํฐ ์ํธ๋คsales_sheet_name = "stg_Sales"ads_sheet_name = "stg_Ads"fx_sheet_name = "dim_FX"costs_sheet_name = "stg_Costs"product_sheet_name = "dim_Product"channel_sheet_name = "dim_Channel"report_sheet_name = "rpt_Dashboard"# ๊ฐ ์ํธ์ ํค๋ ์ ์sales_header = ["Date", "Country", "Channel", "OrderID", "SKU", "ASIN", "Units", "Amount_Local", "Currency", "Amount_KRW"]ads_header = ["Date", "Country", "Channel", "Campaign", "Amount_Local", "Currency", "Amount_KRW"]fx_header = ["Date", "Currency", "RateToKRW"]costs_header = ["CostID", "CostType", "Amount", "Currency", "Date"]product_header = ["SKU", "ProductName", "Category", "Price"]channel_header = ["ChannelID", "ChannelName", "Commission"]report_header = ["Date", "TotalSales", "TotalAds", "TotalCosts", "NetProfit"]client = authenticate_google_sheets()# ๊ฐ ๋ฐ์ดํฐ ์ฝ๊ธฐ + ์ํธ ์๋ ์์ฑ/ํค๋ ์๋ ์ค์ df_sales, ws_sales = read_from_google_sheet(client, spreadsheet_url, sales_sheet_name, sales_header)df_ads, ws_ads = read_from_google_sheet(client, spreadsheet_url, ads_sheet_name, ads_header)df_fx, ws_fx = read_from_google_sheet(client, spreadsheet_url, fx_sheet_name, fx_header)df_costs, ws_costs = read_from_google_sheet(client, spreadsheet_url, costs_sheet_name, costs_header)df_product, ws_product = read_from_google_sheet(client, spreadsheet_url, product_sheet_name, product_header)df_channel, ws_channel = read_from_google_sheet(client, spreadsheet_url, channel_sheet_name, channel_header)df_report, ws_report = read_from_google_sheet(client, spreadsheet_url, report_sheet_name, report_header)# Streamlit ํญ์ ํตํด ๋ฆฌํฌํธ ํ์tab1, tab2, tab3, tab4 = st.tabs(["ํ๋งค ๋ฐ์ดํฐ", "๊ด๊ณ ๋ฐ์ดํฐ", "ํ์จ ๋ฐ์ดํฐ", "๋ฆฌํฌํธ"])with tab1:st.subheader("ํ๋งค ๋ฐ์ดํฐ (์๋ณธ)")st.dataframe(df_sales)with tab2:st.subheader("๊ด๊ณ ๋ฐ์ดํฐ (์๋ณธ)")st.dataframe(df_ads)with tab3:st.subheader("ํ์จ ๋ฐ์ดํฐ (์๋ณธ)")st.dataframe(df_fx)with tab4:st.subheader("๋ฆฌํฌํธ ๋ฐ์ดํฐ (์๋ณธ)")st.dataframe(df_report)# ์์: ์ฌ์ฉ์ ์ ๋ ฅ์ผ๋ก ํ ์คํธ ๋ถ์user_input = st.text_input("๋ถ์ํ ํ ์คํธ๋ฅผ ์ ๋ ฅํ์ธ์:")if user_input:prediction = analyze_sentiment(user_input)st.write("๋ชจ๋ธ ์์ธก ๊ฒฐ๊ณผ:", prediction)# ๋ฒํผ์ผ๋ก ๋ฐ์ดํฐ ์ ์ฅ/๊ฐฑ์ ํ ์คํธif st.button("ํ ์คํธ ๋ฐ์ดํฐ ์ ์ฅ"):# ์์๋ก, ํ๋งค ๋ฐ์ดํฐ์ ํ ์ค ์ถ๊ฐnew_row = {"Date": pd.Timestamp.now().strftime("%Y-%m-%d"),"Country": "US","Channel": "Amazon","OrderID": "TEST1234","SKU": "SKU_TEST","ASIN": "","Units": 1,"Amount_Local": 100,"Currency": "USD","Amount_KRW": 100 * 1400 # ์์ ํ์จ}df_sales2 = df_sales.append(new_row, ignore_index=True)write_to_google_sheet(ws_sales, df_sales2)st.success("ํ ์คํธ ํ๋งค ๋ฐ์ดํฐ๊ฐ ์ ์ฅ/๊ฐฑ์ ๋์์ต๋๋ค.")# 8. ์ฑ ์คํif __name__ == "__main__":display_dashboard()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200# main.pyimport streamlit as stimport pandas as pdimport requestsimport gspreadimport plotly.express as pxfrom google.oauth2.service_account import Credentials# ---# ๐จ 1. ์ค์ ์ค์ : Hugging Face API URL# (Hugging Face Space ๋ฐฐํฌ ํ, 'hf-space-์ด๋ฆ.hf.space' ํ์์ URL์ ์ฌ๊ธฐ์ ์ ๋ ฅํ์ธ์)# ---HF_API_URL = "https://YOUR-HF-SPACE-NAME.hf.space" # ๐ ๋ฐ๋์ ์์ !# ---# 2. Google Sheet ๋ฐ API ์ธ์ฆ (st.secrets ํ์ฉ)# ---try:# Hugging Face API ์ธ์ฆ ํค๋HF_API_TOKEN = st.secrets["huggingface"]["api_token"]HF_HEADERS = {"Authorization": f"Bearer {HF_API_TOKEN}"}# Google Sheets ์ธ์ฆ (JSON '๋ด์ฉ'์ st.secrets์์ ์ง์ ์ฝ๊ธฐ)GOOGLE_CREDS_DICT = st.secrets["google"]GSHEET_URL = "https://docs.google.com/spreadsheets/d/1smCvYAOffV7Z6jdEjitH47PXAHwTK7-KejcMztwbt54/edit"except KeyError as e:st.error(f"โ ๏ธ st.secrets์ ํ์ํ ํค๊ฐ ์์ต๋๋ค: {e}")st.info("`.streamlit/secrets.toml` ํ์ผ์ [huggingface] ๋ฐ [google] ์น์ ์ ์ฌ๋ฐ๋ฅด๊ฒ ์ค์ ํ๋์ง ํ์ธํ์ธ์.")st.stop()# ---# 3. Google Sheets ์ธ์ฆ ํจ์# ---@st.cache_resource(ttl=3600)def authenticate_google_sheets():"""st.secrets์ ์ธ์ฆ ์ ๋ณด๋ฅผ ์ฌ์ฉํ์ฌ gspread ํด๋ผ์ด์ธํธ๋ฅผ ๋ฐํํฉ๋๋ค."""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 clientexcept 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("๋ฉ๋ด",["๐ ๋ฉ์ธ ๋์๋ณด๋", "๐ ์์ธ ๋ฐ์ดํฐ ํ ์ด๋ธ", "โ๏ธ ์ํธ ๊ด๋ฆฌ"],label_visibility="collapsed")# ---# 5. ํญ 1: ๋ฉ์ธ ๋์๋ณด๋# ---if menu == "๐ ๋ฉ์ธ ๋์๋ณด๋":st.title("๐ ๋ฉ์ธ ๋์๋ณด๋")# HF API์์ ๋ฉ์ธ ๋์๋ณด๋ ๋ฐ์ดํฐ ๋ก๋api_endpoint = f"{HF_API_URL}/main_dashboard"try:with st.spinner("๋ฉ์ธ ๋์๋ณด๋ ๋ฐ์ดํฐ๋ฅผ ๋ถ๋ฌ์ค๋ ์ค์ ๋๋ค..."):res = requests.post(api_endpoint, headers=HF_HEADERS)res.raise_for_status() # 200 OK๊ฐ ์๋๋ฉด ์ค๋ฅ ๋ฐ์data = res.json()# 1. KPI ์น์ st.header("๐ Total ๊ธฐ์ค ํต์ฌ ์ฑ๊ณผ")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} %")# 2. ์ผ์๋ณ ์ถ์ด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("์ผ์๋ณ ์ถ์ด ๋ฐ์ดํฐ๊ฐ ์์ต๋๋ค.")# 3. ๊ตญ๊ฐ๋ณ ์ฑ๊ณผst.header("๐ ๊ตญ๊ฐ๋ณ ์ฑ๊ณผ ๋น๊ต")country_summary_df = pd.DataFrame(data.get("country_summary", []))if not country_summary_df.empty:st.dataframe(country_summary_df.set_index("๊ตญ๊ฐ"))# ๊ตญ๊ฐ๋ณ ๋งค์ถ ๊ทธ๋ํfig = px.bar(country_summary_df, x="๊ตญ๊ฐ", y="๋งค์ถ", title="๊ตญ๊ฐ๋ณ ๋งค์ถ")st.plotly_chart(fig, use_container_width=True)else:st.info("๊ตญ๊ฐ๋ณ ์์ฝ ๋ฐ์ดํฐ๊ฐ ์์ต๋๋ค.")except requests.exceptions.RequestException as e:st.error(f"โ Hugging Face API ํธ์ถ ์คํจ: {e}")st.info(f"HF_API_URL์ด ์ฌ๋ฐ๋ฅธ์ง ํ์ธํ์ธ์: {HF_API_URL}")# ---# 6. ํญ 2: ์์ธ ๋ฐ์ดํฐ ํ ์ด๋ธ# ---elif menu == "๐ ์์ธ ๋ฐ์ดํฐ ํ ์ด๋ธ":st.title("๐ ์์ธ ๋ฐ์ดํฐ ํ ์ด๋ธ ๋ฐ ํํฐ๋ง")# ํํฐ ์ต์ ์ ์countries = ["Total", "SG", "MY", "PH", "TW", "TH", "VN"]metrics = ["๋งค์ถ", "์ง์ถ", "ROAS", "๊ณตํ์ด์ต"] # (GSheet์ ์๋ ์งํ ๊ธฐ์ค)channels = ["์ผํผํ์ด", "ํฑํก", "Meta", "ํ๋ ฅ ๊ด๊ณ ", "๋ด๋ถ ๊ด๊ณ "] # (GSheet์ ์๋ ์ฑ๋ ๊ธฐ์ค)st.subheader("๋ฐ์ดํฐ ํํฐ")filter_cols = st.columns(3)selected_country = filter_cols[0].selectbox("๊ตญ๊ฐ ์ ํ", countries)selected_metrics = filter_cols[1].multiselect("์งํ ์ ํ (AND)", metrics)selected_channels = filter_cols[2].multiselect("์ฑ๋ ์ ํ (AND)", channels)if st.button("๐ ๋ฐ์ดํฐ ์กฐํ"):# HF API์ ํํฐ๋ง๋ ๋ฐ์ดํฐ ์์ฒญapi_endpoint = f"{HF_API_URL}/filtered_data"payload = {"country": selected_country,"metrics": selected_metrics,"channels": selected_channels}try:with st.spinner("ํํฐ๋ง๋ ๋ฐ์ดํฐ๋ฅผ ์กฐํ ์ค์ ๋๋ค..."):res = requests.post(api_endpoint, headers=HF_HEADERS, json=payload)res.raise_for_status()data = res.json()# 1. ๋ฐ์ดํฐ ํ ์ด๋ธ ํ์st.subheader("ํํฐ๋ง๋ ๋ฐ์ดํฐ")table_df = pd.DataFrame(data.get("table_data", []))if not table_df.empty:table_df["Date"] = pd.to_datetime(table_df["Date"]).dt.datest.dataframe(table_df.set_index("Date"))else:st.warning("์กฐํ๋ ๋ฐ์ดํฐ๊ฐ ์์ต๋๋ค.")# 2. ํ๋จ ๊ทธ๋ํ (์์ฝ)st.subheader("ํํฐ๋ง๋ ๋ฐ์ดํฐ ์ปฌ๋ผ๋ณ ํฉ๊ณ")chart_df = pd.DataFrame(data.get("summary_chart_data", []))if not chart_df.empty:fig = px.bar(chart_df, x="Column", y="Total", title="์ปฌ๋ผ๋ณ ํฉ๊ณ")st.plotly_chart(fig, use_container_width=True)except requests.exceptions.RequestException as e:st.error(f"โ Hugging Face API ํธ์ถ ์คํจ: {e}")# ---# 7. ํญ 3: ์ํธ ๊ด๋ฆฌ# ---elif menu == "โ๏ธ ์ํธ ๊ด๋ฆฌ":st.title("โ๏ธ Google Sheet ๊ด๋ฆฌ")st.info("์ธ์์ธ๊ณ ๋ฌธ์(v1.0) ๊ธฐ์ค, ์ด๊ธฐ ์ํธ๋ฅผ ์์ฑํฉ๋๋ค.")if st.button("๐ stg/dim ์ํธ ๋ฐ ํค๋ ์์ฑ"):client = authenticate_google_sheets()if client:try:with st.spinner("Google Sheets์ ์ฐ๊ฒฐํ๊ณ ์ํธ๋ฅผ ์์ฑ ์ค์ ๋๋ค..."):spreadsheet = client.open_by_url(GSHEET_URL)# ์์ฑํ ์ํธ์ ํค๋ ์ ์ (v1.0 ๋ฌธ์ ๊ธฐ์ค)sheets_to_create = {"stg_Costs": ["CostID", "CostType", "Amount", "Currency", "Date"],"dim_Product": ["SKU", "ProductName", "Category", "Price"],"dim_Channel": ["ChannelID", "ChannelName", "Commission"]}log = []for name, header in sheets_to_create.items():try:# ์ํธ๊ฐ ์ด๋ฏธ ์๋์ง ํ์ธws = spreadsheet.worksheet(name)log.append(f"โน๏ธ ์ํธ '{name}' (์)๋ ์ด๋ฏธ ์กด์ฌํฉ๋๋ค.")except gspread.exceptions.WorksheetNotFound:# ์์ผ๋ฉด ์๋ก ์์ฑws = spreadsheet.add_worksheet(title=name, rows="1000", cols="50")ws.append_row(header) # ํค๋ ์ถ๊ฐlog.append(f"โ ์ํธ '{name}' ์์ฑ ๋ฐ ํค๋ ์ถ๊ฐ ์๋ฃ!")st.success("์ํธ ๊ด๋ฆฌ ์์ ์๋ฃ!")st.json(log)except Exception as e:st.error(f"Google Sheet ์์ ์ค ์ค๋ฅ ๋ฐ์: {e}")
1234567891011121314151617181920# requirements.txt
# Streamlit (Frontend)streamlitplotly
# FastAPI (Backend)fastapiuvicorn
# Data Handlingpandasrequests
# Google Sheetsgspreadgoogle-authgoogle-auth-oauthlibgoogle-auth-httplib2google-api-python-client.gitignore+7-9
hf_api.pyAdded+170
main.py+192-130
requirmenets.txtAdded+20