Spaces:
Runtime error
Runtime error
File size: 7,928 Bytes
e8146db 06276af b54f963 06276af b54f963 06276af 0e2ee51 06276af 0e2ee51 06276af 0e2ee51 06276af 0e2ee51 06276af 0e2ee51 06276af 0e2ee51 06276af 0e2ee51 06276af 0e2ee51 06276af 0e2ee51 06276af 0e2ee51 06276af b54f963 0e2ee51 b54f963 0e2ee51 b54f963 0e2ee51 06276af 0e2ee51 06276af 0e2ee51 06276af 0e2ee51 06276af 0e2ee51 06276af 0e2ee51 06276af 0e2ee51 06276af 0e2ee51 06276af 0e2ee51 06276af 0e2ee51 06276af | 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 | # -*- coding: utf-8 -*-
import pandas as pd
import requests
import uvicorn
import os
from fastapi import FastAPI, Request, Depends, HTTPException, Header, status
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from io import StringIO
from functools import lru_cache
# ---
# 0. 보안 설정: HF Secret에서 API 토큰 읽기
# (이 토큰은 HF Space 설정에서 'HF_API_TOKEN'이라는 이름으로 저장해야 합니다)
# ---
API_TOKEN = os.environ.get("HF_API_TOKEN")
async def verify_token(authorization: str = Header(..., description="Bearer {token} 형식의 인증 토큰")):
"""API 토큰을 검증하는 의존성 함수"""
if not API_TOKEN:
# 서버(HF Space)에 토큰이 설정되지 않은 경우
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="API token not configured on server. Check HF Space Secrets."
)
# "Bearer hf_..." 형식 검사
try:
token_type, token = authorization.split()
if token_type != "Bearer" or token != API_TOKEN:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authorization token."
)
except ValueError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authorization header format. Expected 'Bearer {token}'."
)
return True
# FastAPI 앱 초기화. 이제 모든 API 경로는 'verify_token' 검사를 통과해야 합니다.
app = FastAPI(
title="Global MD Tool API (v3)",
dependencies=[Depends(verify_token)]
)
# ---
# 1. 데이터 소스 (v3 - "결과" 시트)
# - 'main.py'의 ETL 작업이 이 시트에 데이터를 씁니다.
# - API는 이 시트를 읽기만 합니다.
# - 원본 URL: https://docs.google.com/spreadsheets/d/134B_oQVXrW1x9fop10ZgsnwOTGmZZ4y-T5lTxecEp5w/
# ---
SHEET_ID = "134B_oQVXrW1x9fop10ZgsnwOTGmZZ4y-T5lTxecEp5w" # 🛑 "결과" 시트 Key
GID_STG_SALES = "133043142" # 🛑 'stg_Sales' 시트의 GID
GID_STG_ADS = "1527581504" # 🛑 'stg_Ads' 시트의 GID (이 값은 확인 필요)
GSHEET_SALES_CSV_URL = f"https://docs.google.com/spreadsheets/d/{SHEET_ID}/export?format=csv&gid={GID_STG_SALES}"
GSHEET_ADS_CSV_URL = f"https://docs.google.com/spreadsheets/d/{SHEET_ID}/export?format=csv&gid={GID_STG_ADS}"
# ---
# 2. Pydantic 모델 (요청 Body 검증용)
# ---
class FilterPayload(BaseModel):
countries: list[str] = Field(default_factory=list)
channels: list[str] = Field(default_factory=list)
# ---
# 3. 데이터 로딩 (캐시)
# ---
def load_and_prepare_sheet(url):
"""CSV URL에서 데이터를 로드하고 기본 타입을 변환합니다."""
try:
csv_text = requests.get(url).text
df = pd.read_csv(StringIO(csv_text))
# 'Date' 열을 datetime으로 변환
if "Date" in df.columns:
df["Date"] = pd.to_datetime(df["Date"], errors='coerce')
# 숫자형 컬럼 변환
for col in ["Amount_Local", "Amount_KRW", "PerUnit_KRW", "Units", "Orders", "Clicks", "Impressions", "FxRate"]:
if col in df.columns:
df[col] = pd.to_numeric(df[col], errors='coerce').fillna(0)
return df.dropna(subset=["Date"]) # 날짜 없는 행 제거
except Exception as e:
print(f"Error loading data from {url}: {e}")
return pd.DataFrame()
@lru_cache(maxsize=1) # 1개의 결과만 캐시 (가장 최근 데이터)
def get_sales_data():
"""stg_Sales 시트 데이터를 로드 (캐시 사용)"""
return load_and_prepare_sheet(GSHEET_SALES_CSV_URL)
@lru_cache(maxsize=1)
def get_ads_data():
"""stg_Ads 시트 데이터를 로드 (캐시 사용)"""
return load_and_prepare_sheet(GSHEET_ADS_CSV_URL)
# ---
# 4. API 엔드포인트
# ---
@app.get("/")
async def read_root():
"""루트 경로는 토큰 검사 없이 상태만 반환 (의존성 제거)"""
return {"status": "Global MD Tool API (v3) is running."}
# 루트 경로는 dependencies를 제거하거나 별도로 설정 (Kube-probe 등)
app.router.routes[-1].dependencies = [] # 마지막에 추가된 / 경로의 의존성 제거
@app.get("/clear_cache")
async def clear_api_cache():
"""
Streamlit에서 ETL 실행 후 이 엔드포인트를 호출하여
API의 캐시를 지우고 새 데이터를 강제로 다시 로드합니다.
"""
get_sales_data.cache_clear()
get_ads_data.cache_clear()
return {"status": "API cache cleared. Ready to load fresh data."}
@app.post("/main_dashboard")
async def get_main_dashboard_data():
"""
메인 대시보드에 필요한 핵심 KPI, 날짜별 추이, 국가별 요약 데이터를 반환합니다.
"""
df_sales = get_sales_data()
df_ads = get_ads_data()
if df_sales.empty:
return JSONResponse(status_code=500, content={"error": "Sales data is empty. Run ETL?"})
if df_ads.empty:
return JSONResponse(status_code=500, content={"error": "Ads data is empty. Run ETL?"})
# 1. Total KPI 계산 (Amount_KRW 기준)
total_sales = df_sales["Amount_KRW"].sum()
total_ads = df_ads["Amount_KRW"].sum()
total_roas = (total_sales / total_ads) * 100 if total_ads else 0
# 2. 일자별 추이 (Total 기준)
date_trend_sales = df_sales.set_index("Date").resample('D')['Amount_KRW'].sum().rename("Total 매출")
date_trend_ads = df_ads.set_index("Date").resample('D')['Amount_KRW'].sum().rename("Total 지출")
date_trend_df = pd.merge(date_trend_sales, date_trend_ads, left_index=True, right_index=True, how='outer').fillna(0).reset_index()
# 3. 국가별 성과 요약 (데이터에 있는 모든 국가 자동 집계)
country_sales = df_sales.groupby("Country")["Amount_KRW"].sum().rename("매출")
country_ads = df_ads.groupby("Country")["Amount_KRW"].sum().rename("광고비")
country_summary_df = pd.merge(country_sales, country_ads, left_index=True, right_index=True, how='outer').fillna(0)
country_summary_df["ROAS"] = (country_summary_df["매출"] / country_summary_df["광고비"]) * 100
country_summary_df = country_summary_df.replace([float('inf'), float('-inf')], 0).fillna(0).reset_index()
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_table")
async def get_filtered_data_table(payload: FilterPayload):
"""
사용자 필터(국가, 채널)에 맞는 'Sales'와 'Ads' 데이터를 반환합니다.
"""
df_sales = get_sales_data().copy()
df_ads = get_ads_data().copy()
countries = payload.countries
channels = payload.channels
if countries:
df_sales = df_sales[df_sales["Country"].isin(countries)]
df_ads = df_ads[df_ads["Country"].isin(countries)]
if channels:
df_sales = df_sales[df_sales["Channel"].isin(channels)]
df_ads = df_ads[df_ads["Channel"].isin(channels)]
# 하단 그래프용 요약
sales_summary = df_sales.groupby("Channel")["Amount_KRW"].sum().reset_index().rename(columns={"Amount_KRW": "매출"})
ads_summary = df_ads.groupby("Channel")["Amount_KRW"].sum().reset_index().rename(columns={"Amount_KRW": "광고비"})
return JSONResponse({
"sales_data": df_sales.to_dict(orient="records"),
"ads_data": df_ads.to_dict(orient="records"),
"summary_chart_sales": sales_summary.to_dict(orient="records"),
"summary_chart_ads": ads_summary.to_dict(orient="records")
})
# (로컬 테스트용)
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000) |