Spaces:
Sleeping
Sleeping
Download hf_api.py from LeeChang1/Global-MD-Tool-API: direct link, hf CLI and curl.
- Browser
- Download file 8.4 kB
-
https://huggingface.co/spaces/LeeChang1/Global-MD-Tool-API/resolve/main/hf_api.py
- Command line
-
hf download hf://spaces/LeeChang1/Global-MD-Tool-API/hf_api.py
-
curl -L -o hf_api.py https://huggingface.co/spaces/LeeChang1/Global-MD-Tool-API/resolve/main/hf_api.py
8.4 kB
| # -*- coding: utf-8 -*- | |
| import os, json, re, traceback | |
| import pandas as pd | |
| import gspread | |
| from fastapi import FastAPI, Header, HTTPException, Depends | |
| from fastapi.responses import JSONResponse | |
| from google.oauth2.service_account import Credentials | |
| from pydantic import BaseModel, Field | |
| API_TOKEN = os.environ.get("HF_API_TOKEN") | |
| GOOGLE_CREDS_JSON = os.environ.get("GOOGLE_SERVICE_ACCOUNT", "") | |
| DEST_SHEET_ID = "134B_oQVXrW1x9fop10ZgsnwOTGmZZ4y-T5lTxecEp5w" | |
| WS_SALES = "stg_Sales" | |
| WS_ADS = "stg_Ads" | |
| async def verify_token(authorization: str = Header(...)): | |
| if not API_TOKEN: | |
| raise HTTPException(status_code=503, detail="API token not configured.") | |
| try: | |
| tt, tk = authorization.split() | |
| if tt != "Bearer" or tk != API_TOKEN: | |
| raise HTTPException(status_code=401, detail="Invalid token") | |
| except ValueError: | |
| raise HTTPException(status_code=401, detail="Invalid header format.") | |
| return True | |
| app = FastAPI(title="Global MD Tool API (v3)") | |
| def health_check(): | |
| return {"status": "Global MD Tool API (v3) is running."} | |
| # ---------- helpers ---------- | |
| def ok(data): return JSONResponse(data) | |
| def err(stage: str, msg: str, extra: dict | None = None): | |
| payload = {"error": True, "stage": stage, "message": msg} | |
| if extra: payload["extra"] = extra | |
| return JSONResponse(payload) | |
| def _authorize_client(): | |
| if not GOOGLE_CREDS_JSON: | |
| raise RuntimeError("GOOGLE_SERVICE_ACCOUNT secret not set") | |
| try: | |
| creds_dict = json.loads(GOOGLE_CREDS_JSON) | |
| except Exception as e: | |
| raise RuntimeError(f"GOOGLE_SERVICE_ACCOUNT parse error: {e}") | |
| scopes = [ | |
| "https://www.googleapis.com/auth/spreadsheets", | |
| "https://www.googleapis.com/auth/drive", | |
| ] | |
| creds = Credentials.from_service_account_info(creds_dict, scopes=scopes) | |
| return gspread.authorize(creds) | |
| def _to_number(s): | |
| if pd.isna(s): return 0.0 | |
| x = str(s) | |
| x = re.sub(r"[^\d\.\-]", "", x) # โฉ, , ๊ณต๋ฐฑ ์ ๊ฑฐ | |
| if x in ("", "-"): return 0.0 | |
| try: | |
| return float(x) | |
| except Exception: | |
| return 0.0 | |
| def load_ws_df(worksheet_name: str): | |
| try: | |
| client = _authorize_client() | |
| ws = client.open_by_key(DEST_SHEET_ID).worksheet(worksheet_name) | |
| except Exception as e: | |
| raise RuntimeError(f"open worksheet failed: {worksheet_name} / {e}") | |
| try: | |
| df = pd.DataFrame(ws.get_all_records()) | |
| except Exception as e: | |
| raise RuntimeError(f"read data failed: {worksheet_name} / {e}") | |
| if df.empty: | |
| return df | |
| # Date | |
| if "Date" in df.columns: | |
| df["Date"] = pd.to_datetime(df["Date"], errors="coerce") | |
| else: | |
| # Date ์์ผ๋ฉด ์ง๊ณ๋จ๊ณ๊ฐ ํฐ์ง๋ฏ๋ก ์์ ๋ณดํธ | |
| df["Date"] = pd.NaT | |
| # ์ซ์ ๋ณํ | |
| for col in ("Amount_KRW", "Amount_Local"): | |
| if col in df.columns: | |
| df[col] = df[col].apply(_to_number) | |
| else: | |
| # ๋๋ฝ ๋ณดํธ | |
| df[col] = 0.0 | |
| # Country ๋๋ฝ ๋ณดํธ | |
| if "Country" not in df.columns: | |
| df["Country"] = "Unknown" | |
| return df | |
| # ---------- endpoints ---------- | |
| def main_dashboard(): | |
| try: | |
| df_sales = load_ws_df(WS_SALES) | |
| df_ads = load_ws_df(WS_ADS) | |
| except Exception as e: | |
| return err("load_sheets", str(e)) | |
| try: | |
| # KPI | |
| total_sales = float(df_sales["Amount_KRW"].sum()) if not df_sales.empty else 0.0 | |
| total_ads = float(df_ads["Amount_KRW"].sum()) if not df_ads.empty else 0.0 | |
| total_roas = round((total_sales / total_ads) * 100, 1) if total_ads else 0.0 | |
| # ์ผ์๋ณ ์ถ์ด | |
| # --- ์ผ์๋ณ ์ถ์ด (๋๋ฝ์ผ 0์ ๋๋ฏธ ์ถ๊ฐ) --- | |
| if not df_sales.empty: | |
| trend_sales = df_sales.groupby("Date")["Amount_KRW"].sum().rename("Total ๋งค์ถ").reset_index() | |
| else: | |
| trend_sales = pd.DataFrame(columns=["Date", "Total ๋งค์ถ"]) | |
| if not df_ads.empty: | |
| trend_ads = df_ads.groupby("Date")["Amount_KRW"].sum().rename("Total ์ง์ถ").reset_index() | |
| else: | |
| trend_ads = pd.DataFrame(columns=["Date", "Total ์ง์ถ"]) | |
| # ๋ ์ง ๋ณํฉ | |
| date_trend = pd.merge(trend_sales, trend_ads, on="Date", how="outer").fillna(0) | |
| # ๐ ์ ์ฒด ์ผ์ ๋ฒ์ ์์ฑ (๋๋ฏธ 0 ์ฑ์๋ฃ๊ธฐ) | |
| if not date_trend.empty: | |
| all_dates = pd.date_range(date_trend["Date"].min(), date_trend["Date"].max(), freq="D") | |
| date_trend = ( | |
| pd.DataFrame({"Date": all_dates}) | |
| .merge(date_trend, on="Date", how="left") | |
| .fillna(0) | |
| ) | |
| else: | |
| # ๋ง์ฝ ๋ฐ์ดํฐ๊ฐ ์์ ํ ๋น์ด์์ ๋ โ ์ต๊ทผ 7์ผ ๋๋ฏธ ์์ฑ | |
| all_dates = pd.date_range(pd.Timestamp.today() - pd.Timedelta(days=6), pd.Timestamp.today(), freq="D") | |
| date_trend = pd.DataFrame({"Date": all_dates, "Total ๋งค์ถ": 0, "Total ์ง์ถ": 0}) | |
| # ๊ตญ๊ฐ๋ณ ์์ฝ | |
| cs = (df_sales.groupby("Country")["Amount_KRW"].sum() | |
| .rename("๋งค์ถ").reset_index()) if not df_sales.empty else pd.DataFrame(columns=["Country","๋งค์ถ"]) | |
| ca = (df_ads.groupby("Country")["Amount_KRW"].sum() | |
| .rename("๊ด๊ณ ๋น").reset_index()) if not df_ads.empty else pd.DataFrame(columns=["Country","๊ด๊ณ ๋น"]) | |
| country = pd.merge(cs, ca, on="Country", how="outer").fillna(0) | |
| country["ROAS"] = country.apply(lambda r: (r["๋งค์ถ"]/r["๊ด๊ณ ๋น"]*100) if r["๊ด๊ณ ๋น"] else 0.0, axis=1) | |
| country.replace([float("inf"), -float("inf")], 0, inplace=True) | |
| return { | |
| "total_kpi": { | |
| "total_sales": total_sales, | |
| "total_ads": total_ads, | |
| "total_roas": total_roas | |
| }, | |
| "date_trend": date_trend.to_dict(orient="records"), # โ ์ฌ๋ฐ๋ฅธ ๋ณ์๋ช | |
| "country_summary": country.to_dict(orient="records") | |
| } | |
| except Exception as e: | |
| # ๋ด๋ถ ์คํ ๊ฐ๋จ ์์ฝ ๋ฐํ | |
| return err("aggregate", f"{e}", {"trace": traceback.format_exc()[:800]}) | |
| class FilterPayload(BaseModel): | |
| countries: list[str] = Field(default_factory=list) | |
| channels: list[str] = Field(default_factory=list) | |
| def filtered_data_table(payload: FilterPayload): | |
| """์์ธ ํ ์ด๋ธ์ฉ ํํฐ ๊ธฐ๋ฐ ๋ฐ์ดํฐ ๋ฐํ""" | |
| try: | |
| df_sales = load_ws_df(WS_SALES) | |
| df_ads = load_ws_df(WS_ADS) | |
| except Exception as e: | |
| return { | |
| "error": True, | |
| "stage": "load_failed", | |
| "message": f"๋ฐ์ดํฐ ๋ก๋ ์คํจ: {e}" | |
| } | |
| # โ ํํฐ ์ ์ฉ | |
| if payload.countries: | |
| df_sales = df_sales[df_sales["Country"].isin(payload.countries)] | |
| df_ads = df_ads[df_ads["Country"].isin(payload.countries)] | |
| if payload.channels: | |
| if "Channel" in df_sales.columns: | |
| df_sales = df_sales[df_sales["Channel"].isin(payload.channels)] | |
| if "Channel" in df_ads.columns: | |
| df_ads = df_ads[df_ads["Channel"].isin(payload.channels)] | |
| # โ ์ฑ๋๋ณ ์์ฝ | |
| summary_sales = ( | |
| df_sales.groupby("Channel")["Amount_KRW"].sum() | |
| .rename("๋งค์ถ").reset_index() | |
| ) if not df_sales.empty else pd.DataFrame(columns=["Channel", "๋งค์ถ"]) | |
| summary_ads = ( | |
| df_ads.groupby("Channel")["Amount_KRW"].sum() | |
| .rename("๊ด๊ณ ๋น").reset_index() | |
| ) if not df_ads.empty else pd.DataFrame(columns=["Channel", "๊ด๊ณ ๋น"]) | |
| return { | |
| "sales_data": df_sales.to_dict(orient="records"), | |
| "ads_data": df_ads.to_dict(orient="records"), | |
| "summary_chart_sales": summary_sales.to_dict(orient="records"), | |
| "summary_chart_ads": summary_ads.to_dict(orient="records") | |
| } | |
| def refresh_dashboard(): | |
| """ | |
| ๐ ๊ฐ์ ์๋ก๊ณ ์นจ ์๋ํฌ์ธํธ | |
| Streamlit์ด ETL ์๋ฃ ์งํ ์ด๊ฑธ ํธ์ถํ๋ฉด ์ต์ ๋ฐ์ดํฐ๋ก ๊ฐ์ ๊ฐฑ์ ๋จ. | |
| """ | |
| try: | |
| df_sales = load_ws_df(WS_SALES) | |
| df_ads = load_ws_df(WS_ADS) | |
| return {"status": "ok", "sales_rows": len(df_sales), "ads_rows": len(df_ads)} | |
| except Exception as e: | |
| return err("refresh_failed", str(e)) | |