Spaces:
Runtime error
Runtime error
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