Spaces:
Runtime error
Runtime error
File size: 16,182 Bytes
ebb46dc 8d0d365 ebb46dc 8d0d365 ebb46dc | 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 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 | from __future__ import annotations
"""
P3 ๆๆพๅๆๅผๆ โ L1-L4 ๅๅฑ่ๅใ
L1 ๅธๅบ: Budget Pacing + Revenue vs Target
L2 funnelรไผๅ็ฎๆ : Spend Share + ๅ็ฎๆ ๆ็ๆๆ
L3 ๅนณๅฐ: Spend/Revenue Share + ้็จๆ็ๆๆ
L4 Campaign: ๅไธช campaign ๆ็ป + ็ฏๆฏ
"""
import logging
from datetime import date, timedelta
from pathlib import Path
from typing import Any
import pandas as pd
from .loader import load_config, load_daily_data
from .campaign_parser import enrich_dataframe
from .p3_metrics import compute_group_metrics, get_core_metrics_for_objective
from .p3_config import load_all_p3_config
log = logging.getLogger("ad-agent")
def _safe_div(n: float, d: float) -> float:
if d == 0 or pd.isna(d):
return 0.0
return n / d
def _filter_period(
df: pd.DataFrame,
period_type: str,
target_year: int | None,
target_period: int | None,
start_date: date | None,
end_date: date | None,
) -> tuple[pd.DataFrame, str]:
"""ๆ นๆฎๅจๆ็ฑปๅ็ญ้ๆฐๆฎ๏ผ่ฟๅ (filtered_df, period_label)ใ"""
if period_type == "range" and start_date and end_date:
mask = (df["date"].dt.date >= start_date) & (df["date"].dt.date <= end_date)
label = f"{start_date} ~ {end_date}"
return df[mask].copy(), label
if period_type == "day" and start_date:
mask = df["date"].dt.date == start_date
label = str(start_date)
return df[mask].copy(), label
if period_type == "month" and target_year and target_period:
cal_year = df["date"].dt.year
mask = (cal_year == target_year) & (df["month"] == target_period)
label = f"{target_year}ๅนด{target_period}ๆ"
return df[mask].copy(), label
# default: week
if target_year and target_period:
mask = (df["year"] == target_year) & (df["week"] == target_period)
label = f"{target_year} W{target_period}"
return df[mask].copy(), label
# latest week
latest_year = df["year"].max()
latest_week = df[df["year"] == latest_year]["week"].max()
mask = (df["year"] == latest_year) & (df["week"] == latest_week)
label = f"{latest_year} W{latest_week}"
return df[mask].copy(), label
def _get_prev_period(
df: pd.DataFrame,
period_type: str,
target_year: int | None,
target_period: int | None,
start_date: date | None,
end_date: date | None,
) -> tuple[pd.DataFrame, str | None]:
"""่ทๅไธไธๆๆฐๆฎ็จไบ็ฏๆฏใ"""
if period_type == "range" and start_date and end_date:
days = (end_date - start_date).days + 1
prev_end = start_date - timedelta(days=1)
prev_start = prev_end - timedelta(days=days - 1)
return _filter_period(df, "range", None, None, prev_start, prev_end)
if period_type == "day" and start_date:
prev = start_date - timedelta(days=1)
return _filter_period(df, "day", None, None, prev, None)
if period_type == "month" and target_year and target_period:
pm = target_period - 1
py = target_year
if pm < 1:
pm = 12
py -= 1
return _filter_period(df, "month", py, pm, None, None)
# week
weeks = (
df[["year", "week"]]
.drop_duplicates()
.sort_values(["year", "week"])
.values.tolist()
)
curr = [target_year, target_period] if target_year and target_period else None
if not curr and weeks:
curr = weeks[-1]
if curr and curr in weeks:
idx = weeks.index(curr)
if idx > 0:
py, pw = weeks[idx - 1]
return _filter_period(df, "week", py, pw, None, None)
return pd.DataFrame(), None
def _infer_month(period_df: pd.DataFrame) -> int | None:
"""ไปๅฝๆๆฐๆฎๆจๆญๆๅฑๆไปฝ๏ผๅไธญไฝๆฅๆ็ๆไปฝ๏ผใ"""
if period_df.empty or "date" not in period_df.columns:
return None
dates = period_df["date"].dropna()
if dates.empty:
return None
mid = dates.sort_values().iloc[len(dates) // 2]
return mid.month
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# L1 ๅธๅบๅฑ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _build_l1(
curr_df: pd.DataFrame,
prev_df: pd.DataFrame | None,
p3_config: dict,
target_month: int | None,
) -> list[dict[str, Any]]:
if curr_df.empty or "market" not in curr_df.columns:
return []
targets = p3_config.get("monthly_targets", {})
rows = []
for mkt, grp in curr_df.groupby("market"):
m = compute_group_metrics(grp)
cost = m["Cost"]
revenue = m["Revenue"]
roas = m["ROAS"]
row: dict[str, Any] = {
"market": mkt,
"spend": cost,
"revenue": revenue,
"roas": roas,
"cpa": m["CPA"],
"impressions": m.get("Impressions", 0),
}
mkt_targets = targets.get(mkt, {}).get(target_month, {}) if target_month else {}
budget = mkt_targets.get("dm_budget")
dm_target = mkt_targets.get("dm_target")
target_roas = mkt_targets.get("target_roas")
row["budget"] = budget
row["budget_pacing"] = _safe_div(cost, budget) * 100 if budget else None
row["dm_target"] = dm_target
row["revenue_vs_target"] = _safe_div(revenue, dm_target) * 100 if dm_target else None
row["target_roas"] = target_roas
if prev_df is not None and not prev_df.empty:
prev_grp = prev_df[prev_df["market"] == mkt] if "market" in prev_df.columns else pd.DataFrame()
if not prev_grp.empty:
pm = compute_group_metrics(prev_grp)
row["prev_spend"] = pm["Cost"]
row["prev_revenue"] = pm["Revenue"]
row["prev_roas"] = pm["ROAS"]
row["spend_chg"] = _safe_div(cost - pm["Cost"], pm["Cost"]) * 100 if pm["Cost"] else None
row["revenue_chg"] = _safe_div(revenue - pm["Revenue"], pm["Revenue"]) * 100 if pm["Revenue"] else None
row["roas_chg"] = _safe_div(roas - pm["ROAS"], pm["ROAS"]) * 100 if pm["ROAS"] else None
rows.append(row)
return rows
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# L2 funnelรไผๅ็ฎๆ ๅฑ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _build_l2(
curr_df: pd.DataFrame,
prev_df: pd.DataFrame | None,
p3_config: dict,
target_month: int | None,
) -> list[dict[str, Any]]:
needed_cols = {"ad_objective", "audience_type", "objective_group", "funnel"}
if not needed_cols.issubset(curr_df.columns):
return []
total_cost = curr_df["Cost"].fillna(0).sum() if "Cost" in curr_df.columns else 0
rows = []
for obj_group, grp in curr_df.groupby("objective_group"):
objective = grp["ad_objective"].iloc[0] if not grp.empty else None
audience = grp["audience_type"].iloc[0] if not grp.empty else "cold"
funnel = grp["funnel"].iloc[0] if not grp.empty else ""
m = compute_group_metrics(grp, objective=objective)
cost = m["Cost"]
row: dict[str, Any] = {
"objective_group": obj_group,
"ad_objective": objective,
"audience_type": audience,
"funnel": funnel,
"spend": cost,
"spend_share": _safe_div(cost, total_cost) * 100,
**{k: m.get(k) for k in get_core_metrics_for_objective(objective or "")},
"impressions": m.get("Impressions", 0),
"clicks": m.get("Clicks", 0),
}
if prev_df is not None and not prev_df.empty and "objective_group" in prev_df.columns:
prev_grp = prev_df[prev_df["objective_group"] == obj_group]
if not prev_grp.empty:
pm = compute_group_metrics(prev_grp, objective=objective)
for key in get_core_metrics_for_objective(objective or ""):
curr_val = m.get(key, 0)
prev_val = pm.get(key, 0)
row[f"{key}_chg"] = (
_safe_div(curr_val - prev_val, prev_val) * 100
if prev_val else None
)
rows.append(row)
rows.sort(key=lambda r: r.get("spend", 0), reverse=True)
return rows
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# L3 ๅนณๅฐๅฑ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _build_l3(
curr_df: pd.DataFrame,
prev_df: pd.DataFrame | None,
p3_config: dict,
target_month: int | None,
) -> list[dict[str, Any]]:
plat_col = "parsed_platform" if "parsed_platform" in curr_df.columns else "platform"
if plat_col not in curr_df.columns:
return []
total_cost = curr_df["Cost"].fillna(0).sum() if "Cost" in curr_df.columns else 0
total_revenue = curr_df["Ads.Sales"].fillna(0).sum() if "Ads.Sales" in curr_df.columns else 0
channel_budgets = p3_config.get("channel_budgets", {})
rows = []
for plat, grp in curr_df.groupby(plat_col):
m = compute_group_metrics(grp)
cost = m["Cost"]
revenue = m["Revenue"]
row: dict[str, Any] = {
"platform": plat,
"spend": cost,
"spend_share": _safe_div(cost, total_cost) * 100,
"revenue": revenue,
"revenue_share": _safe_div(revenue, total_revenue) * 100,
"roas": m["ROAS"],
"impressions": m.get("Impressions", 0),
"cpm": m["CPM"],
"clicks": m["Clicks"],
"ctr": m["CTR"],
"cpc": m["CPC"],
"cpa": m["CPA"],
"conversions": m["Conversions"],
}
# ไธๆธ ้้ข็ฎๅฏน็
ง
us_budgets = channel_budgets.get("US", {}).get("channel_budgets", {})
if target_month and target_month in us_budgets:
planned = us_budgets[target_month].get(plat)
row["planned_budget"] = planned
row["budget_pacing"] = _safe_div(cost, planned) * 100 if planned else None
if prev_df is not None and not prev_df.empty and plat_col in prev_df.columns:
prev_grp = prev_df[prev_df[plat_col] == plat]
if not prev_grp.empty:
pm = compute_group_metrics(prev_grp)
row["prev_spend"] = pm["Cost"]
row["prev_roas"] = pm["ROAS"]
row["spend_chg"] = _safe_div(cost - pm["Cost"], pm["Cost"]) * 100 if pm["Cost"] else None
row["roas_chg"] = _safe_div(m["ROAS"] - pm["ROAS"], pm["ROAS"]) * 100 if pm["ROAS"] else None
row["cpc_chg"] = _safe_div(m["CPC"] - pm["CPC"], pm["CPC"]) * 100 if pm["CPC"] else None
rows.append(row)
rows.sort(key=lambda r: r.get("spend", 0), reverse=True)
return rows
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# L4 Campaign ๅฑ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _build_l4(
curr_df: pd.DataFrame,
prev_df: pd.DataFrame | None,
) -> list[dict[str, Any]]:
if "campaign_name" not in curr_df.columns:
return []
rows = []
dim_cols = [
"campaign_name", "market", "funnel", "parsed_platform",
"ad_objective", "product_line", "audience_type", "objective_group",
]
existing_dims = [c for c in dim_cols if c in curr_df.columns]
for name, grp in curr_df.groupby("campaign_name"):
objective = grp["ad_objective"].iloc[0] if "ad_objective" in grp.columns else None
m = compute_group_metrics(grp, objective=objective)
row: dict[str, Any] = {"campaign_name": name}
for c in existing_dims:
if c != "campaign_name":
row[c] = grp[c].iloc[0] if c in grp.columns else None
row.update({
"spend": m["Cost"],
"impressions": m.get("Impressions", 0),
"cpm": m["CPM"],
"clicks": m["Clicks"],
"ctr": m["CTR"],
"cpc": m["CPC"],
"conversions": m["Conversions"],
"revenue": m["Revenue"],
"cpa": m["CPA"],
"roas": m["ROAS"],
})
if objective:
for key in get_core_metrics_for_objective(objective):
if key not in row:
row[key] = m.get(key)
if prev_df is not None and not prev_df.empty and "campaign_name" in prev_df.columns:
prev_grp = prev_df[prev_df["campaign_name"] == name]
if not prev_grp.empty:
pm = compute_group_metrics(prev_grp, objective=objective)
row["prev_roas"] = pm["ROAS"]
row["roas_chg"] = (
_safe_div(m["ROAS"] - pm["ROAS"], pm["ROAS"]) * 100
if pm["ROAS"] else None
)
row["prev_spend"] = pm["Cost"]
row["spend_chg"] = (
_safe_div(m["Cost"] - pm["Cost"], pm["Cost"]) * 100
if pm["Cost"] else None
)
rows.append(row)
rows.sort(key=lambda r: r.get("spend", 0), reverse=True)
return rows
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ไธปๅ
ฅๅฃ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def run_p3_analysis(
config_path: Path | None = None,
period_type: str = "week",
target_year: int | None = None,
target_period: int | None = None,
start_date: date | None = None,
end_date: date | None = None,
market: str | None = None,
) -> dict[str, Any]:
"""
P3 ๆๆพๅๆไธปๅ
ฅๅฃใ
ๅ ่ฝฝๆฐๆฎ -> ่งฃๆ campaign name -> ๅๅฑ่ๅ -> ่ฟๅ L1-L4 ็ปๆใ
"""
config_path = config_path or (Path(__file__).resolve().parent.parent / "config.yaml")
df = load_daily_data(config_path)
df = enrich_dataframe(df)
if market and "market" in df.columns:
df = df[df["market"] == market].copy()
curr_df, period_label = _filter_period(
df, period_type, target_year, target_period, start_date, end_date
)
if curr_df.empty:
return {
"period_label": period_label,
"error": f"{period_label} ๆ ๅฏ็จๆฐๆฎ",
"L1": [], "L2": [], "L3": [], "L4": [],
}
prev_df, prev_label = _get_prev_period(
df, period_type, target_year, target_period, start_date, end_date
)
prev_enriched = enrich_dataframe(prev_df) if prev_df is not None and not prev_df.empty else None
p3_config = load_all_p3_config(config_path)
target_month = _infer_month(curr_df)
l1 = _build_l1(curr_df, prev_enriched, p3_config, target_month)
l2 = _build_l2(curr_df, prev_enriched, p3_config, target_month)
l3 = _build_l3(curr_df, prev_enriched, p3_config, target_month)
l4 = _build_l4(curr_df, prev_enriched)
parse_ok = curr_df["parse_ok"].sum() if "parse_ok" in curr_df.columns else 0
parse_total = len(curr_df)
return {
"period_label": period_label,
"prev_label": prev_label,
"period_type": period_type,
"target_month": target_month,
"market_filter": market,
"parse_rate": _safe_div(parse_ok, parse_total) * 100 if parse_total else 0,
"row_count": parse_total,
"L1": l1,
"L2": l2,
"L3": l3,
"L4": l4,
"p3_config": p3_config,
}
|