Spaces:
Runtime error
Runtime error
wen Qiu commited on
Commit ·
164fe15
1
Parent(s): a9f3229
feat: add GitHub Actions workflow for Meta data sync
Browse filesHF Spaces blocks graph.facebook.com, so Meta data is synced via
GitHub Actions instead. Runs daily at 09:00 Beijing time.
Also refactored Google auth in loader.py to support OAuth refresh
token (via GOOGLE_OAUTH_* env vars) in addition to service account,
enabling GitHub Actions to write to Sheets without a service account
key file.
Made-with: Cursor
- .github/workflows/sync-meta.yml +53 -0
- src/loader.py +60 -51
.github/workflows/sync-meta.yml
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Sync Meta Ads Data
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
schedule:
|
| 5 |
+
- cron: "0 1 * * *" # UTC 01:00 = 北京时间 09:00
|
| 6 |
+
workflow_dispatch:
|
| 7 |
+
inputs:
|
| 8 |
+
days_back:
|
| 9 |
+
description: "拉取最近几天的数据"
|
| 10 |
+
required: false
|
| 11 |
+
default: "7"
|
| 12 |
+
|
| 13 |
+
jobs:
|
| 14 |
+
sync:
|
| 15 |
+
runs-on: ubuntu-latest
|
| 16 |
+
steps:
|
| 17 |
+
- uses: actions/checkout@v4
|
| 18 |
+
|
| 19 |
+
- uses: actions/setup-python@v5
|
| 20 |
+
with:
|
| 21 |
+
python-version: "3.12"
|
| 22 |
+
|
| 23 |
+
- name: Install dependencies
|
| 24 |
+
run: pip install requests pandas gspread google-auth pyyaml python-dotenv openpyxl
|
| 25 |
+
|
| 26 |
+
- name: Sync Meta data to Google Sheets
|
| 27 |
+
env:
|
| 28 |
+
META_ACCESS_TOKEN: ${{ secrets.META_ACCESS_TOKEN }}
|
| 29 |
+
META_AD_ACCOUNTS: ${{ secrets.META_AD_ACCOUNTS }}
|
| 30 |
+
GOOGLE_OAUTH_REFRESH_TOKEN: ${{ secrets.GOOGLE_OAUTH_REFRESH_TOKEN }}
|
| 31 |
+
GOOGLE_OAUTH_CLIENT_ID: ${{ secrets.GOOGLE_OAUTH_CLIENT_ID }}
|
| 32 |
+
GOOGLE_OAUTH_CLIENT_SECRET: ${{ secrets.GOOGLE_OAUTH_CLIENT_SECRET }}
|
| 33 |
+
run: |
|
| 34 |
+
python -c "
|
| 35 |
+
import sys, os, logging
|
| 36 |
+
sys.path.insert(0, '.')
|
| 37 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
|
| 38 |
+
|
| 39 |
+
from src.meta_api import fetch_meta_data
|
| 40 |
+
from src.loader import write_api_data_to_sheets
|
| 41 |
+
|
| 42 |
+
days = int('${{ github.event.inputs.days_back || 7 }}')
|
| 43 |
+
print(f'Fetching Meta data (last {days} days)...')
|
| 44 |
+
df = fetch_meta_data(days_back=days)
|
| 45 |
+
|
| 46 |
+
if df.empty:
|
| 47 |
+
print('No data fetched.')
|
| 48 |
+
sys.exit(0)
|
| 49 |
+
|
| 50 |
+
print(f'Fetched {len(df)} rows, date range: {df[\"date\"].min()} ~ {df[\"date\"].max()}')
|
| 51 |
+
result = write_api_data_to_sheets(df)
|
| 52 |
+
print(f'Written to Sheets: {result[\"added\"]} new rows')
|
| 53 |
+
"
|
src/loader.py
CHANGED
|
@@ -29,12 +29,61 @@ def load_config(config_path: Path | None = None) -> dict[str, Any]:
|
|
| 29 |
# Google Sheets 数据源
|
| 30 |
# ─────────────────────────────────────────────
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
def _load_from_google_sheets(config: dict[str, Any]) -> pd.DataFrame | None:
|
| 33 |
"""
|
| 34 |
从 Google Sheets 读取数据。
|
| 35 |
-
支持
|
| 36 |
-
1. credentials.json 文件(本地开发)
|
| 37 |
-
2. GOOGLE_CREDENTIALS 环境变量(云端部署,值为 JSON 字符串)
|
| 38 |
"""
|
| 39 |
gs_cfg = config.get("google_sheets", {})
|
| 40 |
if not gs_cfg.get("enabled"):
|
|
@@ -47,33 +96,11 @@ def _load_from_google_sheets(config: dict[str, Any]) -> pd.DataFrame | None:
|
|
| 47 |
|
| 48 |
try:
|
| 49 |
import gspread
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
"https://www.googleapis.com/auth/drive",
|
| 56 |
-
]
|
| 57 |
-
|
| 58 |
-
creds = None
|
| 59 |
-
# 方式一:环境变量(云端部署推荐)
|
| 60 |
-
creds_json = os.environ.get("GOOGLE_CREDENTIALS", "").strip()
|
| 61 |
-
if creds_json:
|
| 62 |
-
info = json.loads(creds_json)
|
| 63 |
-
creds = Credentials.from_service_account_info(info, scopes=scopes)
|
| 64 |
-
log.info("使用环境变量 GOOGLE_CREDENTIALS 认证")
|
| 65 |
-
else:
|
| 66 |
-
# 方式二:本地文件
|
| 67 |
-
creds_file = gs_cfg.get("credentials_file", "credentials.json")
|
| 68 |
-
creds_path = Path(creds_file)
|
| 69 |
-
if not creds_path.is_absolute():
|
| 70 |
-
creds_path = _project_root() / creds_path
|
| 71 |
-
if creds_path.exists():
|
| 72 |
-
creds = Credentials.from_service_account_file(str(creds_path), scopes=scopes)
|
| 73 |
-
log.info(f"使用凭证文件 {creds_path} 认证")
|
| 74 |
-
else:
|
| 75 |
-
log.warning(f"凭证文件 {creds_path} 不存在,回退到本地 Excel")
|
| 76 |
-
return None
|
| 77 |
|
| 78 |
gc = gspread.authorize(creds)
|
| 79 |
sh = gc.open_by_url(url)
|
|
@@ -162,33 +189,15 @@ def _load_from_excel(config: dict[str, Any]) -> pd.DataFrame:
|
|
| 162 |
def _get_spreadsheet(config: dict[str, Any]):
|
| 163 |
"""获取 gspread spreadsheet 对象(读写权限)。"""
|
| 164 |
import gspread
|
| 165 |
-
from google.oauth2.service_account import Credentials
|
| 166 |
-
import json
|
| 167 |
|
| 168 |
gs_cfg = config.get("google_sheets", {})
|
| 169 |
url = gs_cfg.get("spreadsheet_url", "").strip()
|
| 170 |
if not url:
|
| 171 |
raise RuntimeError("未配置 spreadsheet_url")
|
| 172 |
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
"
|
| 176 |
-
]
|
| 177 |
-
|
| 178 |
-
creds = None
|
| 179 |
-
creds_json = os.environ.get("GOOGLE_CREDENTIALS", "").strip()
|
| 180 |
-
if creds_json:
|
| 181 |
-
info = json.loads(creds_json)
|
| 182 |
-
creds = Credentials.from_service_account_info(info, scopes=scopes)
|
| 183 |
-
else:
|
| 184 |
-
creds_file = gs_cfg.get("credentials_file", "credentials.json")
|
| 185 |
-
creds_path = Path(creds_file)
|
| 186 |
-
if not creds_path.is_absolute():
|
| 187 |
-
creds_path = _project_root() / creds_path
|
| 188 |
-
if creds_path.exists():
|
| 189 |
-
creds = Credentials.from_service_account_file(str(creds_path), scopes=scopes)
|
| 190 |
-
else:
|
| 191 |
-
raise RuntimeError(f"凭证文件 {creds_path} 不存在")
|
| 192 |
|
| 193 |
gc = gspread.authorize(creds)
|
| 194 |
return gc.open_by_url(url)
|
|
|
|
| 29 |
# Google Sheets 数据源
|
| 30 |
# ─────────────────────────────────────────────
|
| 31 |
|
| 32 |
+
def _build_google_creds(config: dict[str, Any]):
|
| 33 |
+
"""
|
| 34 |
+
构建 Google API 凭证,支持三种认证方式(按优先级):
|
| 35 |
+
1. GOOGLE_CREDENTIALS 环境变量(服务账号 JSON 字符串,云端部署推荐)
|
| 36 |
+
2. GOOGLE_OAUTH_REFRESH_TOKEN 环境变量(OAuth refresh token,GitHub Actions 等场景)
|
| 37 |
+
3. credentials.json 本地文件(本地开发)
|
| 38 |
+
"""
|
| 39 |
+
from google.oauth2.service_account import Credentials as SACredentials
|
| 40 |
+
from google.oauth2.credentials import Credentials as OAuthCredentials
|
| 41 |
+
import json
|
| 42 |
+
|
| 43 |
+
scopes = [
|
| 44 |
+
"https://www.googleapis.com/auth/spreadsheets",
|
| 45 |
+
"https://www.googleapis.com/auth/drive",
|
| 46 |
+
]
|
| 47 |
+
|
| 48 |
+
creds_json = os.environ.get("GOOGLE_CREDENTIALS", "").strip()
|
| 49 |
+
if creds_json:
|
| 50 |
+
info = json.loads(creds_json)
|
| 51 |
+
creds = SACredentials.from_service_account_info(info, scopes=scopes)
|
| 52 |
+
log.info("使用环境变量 GOOGLE_CREDENTIALS(服务账号)认证")
|
| 53 |
+
return creds
|
| 54 |
+
|
| 55 |
+
refresh_token = os.environ.get("GOOGLE_OAUTH_REFRESH_TOKEN", "").strip()
|
| 56 |
+
client_id = os.environ.get("GOOGLE_OAUTH_CLIENT_ID", "").strip()
|
| 57 |
+
client_secret = os.environ.get("GOOGLE_OAUTH_CLIENT_SECRET", "").strip()
|
| 58 |
+
if refresh_token and client_id and client_secret:
|
| 59 |
+
creds = OAuthCredentials(
|
| 60 |
+
token=None,
|
| 61 |
+
refresh_token=refresh_token,
|
| 62 |
+
client_id=client_id,
|
| 63 |
+
client_secret=client_secret,
|
| 64 |
+
token_uri="https://oauth2.googleapis.com/token",
|
| 65 |
+
scopes=scopes,
|
| 66 |
+
)
|
| 67 |
+
log.info("使用 OAuth refresh token 认证")
|
| 68 |
+
return creds
|
| 69 |
+
|
| 70 |
+
gs_cfg = config.get("google_sheets", {})
|
| 71 |
+
creds_file = gs_cfg.get("credentials_file", "credentials.json")
|
| 72 |
+
creds_path = Path(creds_file)
|
| 73 |
+
if not creds_path.is_absolute():
|
| 74 |
+
creds_path = _project_root() / creds_path
|
| 75 |
+
if creds_path.exists():
|
| 76 |
+
creds = SACredentials.from_service_account_file(str(creds_path), scopes=scopes)
|
| 77 |
+
log.info(f"使用凭证文件 {creds_path} 认证")
|
| 78 |
+
return creds
|
| 79 |
+
|
| 80 |
+
return None
|
| 81 |
+
|
| 82 |
+
|
| 83 |
def _load_from_google_sheets(config: dict[str, Any]) -> pd.DataFrame | None:
|
| 84 |
"""
|
| 85 |
从 Google Sheets 读取数据。
|
| 86 |
+
支持服务账号、OAuth refresh token、本地文件三种认证方式。
|
|
|
|
|
|
|
| 87 |
"""
|
| 88 |
gs_cfg = config.get("google_sheets", {})
|
| 89 |
if not gs_cfg.get("enabled"):
|
|
|
|
| 96 |
|
| 97 |
try:
|
| 98 |
import gspread
|
| 99 |
+
|
| 100 |
+
creds = _build_google_creds(config)
|
| 101 |
+
if creds is None:
|
| 102 |
+
log.warning("无可用 Google 认证凭证,回退到本地 Excel")
|
| 103 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
gc = gspread.authorize(creds)
|
| 106 |
sh = gc.open_by_url(url)
|
|
|
|
| 189 |
def _get_spreadsheet(config: dict[str, Any]):
|
| 190 |
"""获取 gspread spreadsheet 对象(读写权限)。"""
|
| 191 |
import gspread
|
|
|
|
|
|
|
| 192 |
|
| 193 |
gs_cfg = config.get("google_sheets", {})
|
| 194 |
url = gs_cfg.get("spreadsheet_url", "").strip()
|
| 195 |
if not url:
|
| 196 |
raise RuntimeError("未配置 spreadsheet_url")
|
| 197 |
|
| 198 |
+
creds = _build_google_creds(config)
|
| 199 |
+
if creds is None:
|
| 200 |
+
raise RuntimeError("无可用 Google 认证凭证(需要 GOOGLE_CREDENTIALS、GOOGLE_OAUTH_REFRESH_TOKEN 或 credentials.json)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
|
| 202 |
gc = gspread.authorize(creds)
|
| 203 |
return gc.open_by_url(url)
|