execute_creation_once.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. """模块 B 创意搭建子系统 — 主循环入口(P0-A / P0-C / P0-E,2026-06-09)。
  2. 数据流(三阶段,先审后挂):
  3. Phase 1 — 准备:
  4. 扫账户 → 关联点过滤(读调控当日 latest_decisions 排除 pause)
  5. → find_ads_needing_creatives
  6. → 对每条广告 prepare_one_creative_for_ad(召回 + 上传图 + xcx/save + build body)
  7. → pending_records (含完整 Phase 3 用的 _request_body)
  8. → 写 outputs/data/creation_pending_{date}.json(追溯 + 独立 apply 用)
  9. Phase 2 — 审批(若 CREATION_APPROVAL_REQUIRED=True):
  10. run_approval_workflow 生成 20 列 xlsx → 上传飞书 sheet → 发链接 → 轮询读决策列
  11. actions {row_idx: approve/reject/hold}
  12. → 写回 records["action"]
  13. Phase 3 — 执行:
  14. 对 action=approve 的 → POST /dynamic_creatives/add
  15. → 写 outputs/data/creation_run_{date}.json
  16. → 发飞书"执行汇报"消息
  17. 开关 CREATION_APPROVAL_REQUIRED=False 时跳过 Phase 2,全 records 直接 approve。
  18. """
  19. import json
  20. import logging
  21. import sys
  22. import time
  23. from pathlib import Path
  24. _HERE = Path(__file__).parent
  25. sys.path.insert(0, str(_HERE.parent.parent))
  26. sys.path.insert(0, str(_HERE))
  27. from dotenv import load_dotenv # noqa: E402
  28. load_dotenv(_HERE / ".env")
  29. from config import ( # noqa: E402
  30. ADS_PER_ACCOUNT,
  31. CREATION_APPROVAL_REQUIRED,
  32. CREATION_APPROVAL_TIMEOUT_MINUTES,
  33. MAX_SAME_LANDING_PER_AD_IN_RUN,
  34. TARGET_CREATIVES_PER_AD,
  35. WHITELIST_ACCOUNTS,
  36. get_creation_account_ids,
  37. now_in_timezone,
  38. )
  39. # config import 副作用会改 sys.path(把 im-client / agent/tools/builtin 顶到前面),
  40. # 强占 sys.path[0],只影响本入口自己的 import resolution。
  41. while str(_HERE) in sys.path:
  42. sys.path.remove(str(_HERE))
  43. sys.path.insert(0, str(_HERE))
  44. from tools.ad_creation import ( # noqa: E402
  45. build_ad_request_body,
  46. compute_fingerprint,
  47. enumerate_new_ad_candidates,
  48. post_ad_with_prepared_body,
  49. )
  50. from tools.audience_grant import ensure_account_audience_grant # noqa: E402
  51. from tools.creative_creation import ( # noqa: E402
  52. find_ads_needing_creatives,
  53. load_excluded_ad_ids_from_adjustment,
  54. prepare_one_creative_for_ad,
  55. )
  56. from tools.creative_material_usage import record_prepared_material_usage # noqa: E402
  57. from tools.video_recall import get_account_crowd_package # noqa: E402
  58. from execute_creation_apply import ( # noqa: E402
  59. apply_pending_records,
  60. write_summary as write_apply_summary,
  61. _send_apply_summary_to_feishu,
  62. )
  63. logger = logging.getLogger("execute_creation_once")
  64. def _setup_logging() -> None:
  65. """配置日志格式与级别,挂载 SLS 上报(配置缺失时自动降级)。"""
  66. logging.basicConfig(
  67. level=logging.INFO,
  68. format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
  69. datefmt="%H:%M:%S",
  70. )
  71. for noisy in ("httpx", "httpcore", "config", "db.config"):
  72. logging.getLogger(noisy).setLevel(logging.WARNING)
  73. # SLS 上报(2026-06-11 接入,K8s pod 直发)— 配置缺失自动降级,不阻塞主链路
  74. try:
  75. from tools.sls_setup import attach_sls_handler
  76. attach_sls_handler()
  77. except Exception as e:
  78. logger.warning("[sls] 挂载异常(降级为本地 only):%s", e)
  79. def _fetch_existing_fingerprints_for_account(account_id: int) -> set[str]:
  80. """Task 27:拉账户下所有非 DELETED 广告 → 反推 fingerprint 集合(预校验唯一性)。
  81. 腾讯文档:NORMAL + SUSPEND 状态广告均占用唯一性槽位,DENIED 也算占用。
  82. list 接口默认返回所有非 DELETED 状态 ad,故无需显式 filter status。
  83. 若腾讯 list 接口某些字段不返回(field 实测差异),降级:跳过该条 + log 警告。
  84. 返回空集 → 上层退化为"不预校验",enumerate 仍能跑(原有行为)。
  85. """
  86. from tools.ad_api import _get
  87. fingerprints: set[str] = set()
  88. skipped = 0
  89. page = 1
  90. try:
  91. while True:
  92. r = _get("/adgroups/get", {
  93. "account_id": account_id, "page": page, "page_size": 100,
  94. "fields": [
  95. "adgroup_id", "configured_status", "site_set",
  96. "targeting", "scene_spec",
  97. ],
  98. })
  99. ads = (r.get("data") or {}).get("list") or []
  100. if not ads:
  101. break
  102. for ad in ads:
  103. tgt = ad.get("targeting") or {}
  104. sc = ad.get("scene_spec") or {}
  105. wp = sc.get("wechat_position") if sc else None
  106. site_set = ad.get("site_set") or []
  107. age = tgt.get("age") or []
  108. geo_regions = (tgt.get("geo_location") or {}).get("regions") or []
  109. custom_audience = tgt.get("custom_audience")
  110. if not site_set or not age:
  111. skipped += 1
  112. continue
  113. try:
  114. fp = compute_fingerprint(
  115. account_id=account_id,
  116. site_set=site_set,
  117. custom_audience=custom_audience,
  118. age=age,
  119. geo_regions=geo_regions,
  120. wechat_position=wp,
  121. )
  122. fingerprints.add(fp)
  123. except Exception as e:
  124. skipped += 1
  125. logger.debug(
  126. "[phase0] fingerprint 算失败 ad=%s: %s",
  127. ad.get("adgroup_id"), e,
  128. )
  129. if len(ads) < 100:
  130. break
  131. page += 1
  132. except Exception as e:
  133. logger.warning(
  134. "[phase0] account=%d 拉 fingerprint 集失败(降级为不预校验): %s",
  135. account_id, e,
  136. )
  137. return set()
  138. logger.info(
  139. "[phase0] 已存在 fingerprint=%d 个(skip 缺字段广告 %d 条)",
  140. len(fingerprints), skipped,
  141. )
  142. return fingerprints
  143. def phase0_create_ads(target_ads: int = ADS_PER_ACCOUNT) -> list[dict]:
  144. """Phase 0:对每账户检查广告数,不足则建到 target_ads 条(模块 A,2026-06-09 P1-G)。
  145. 流程:
  146. account → 查当前广告数(NORMAL+SUSPEND 算占用)→ 不足 target_ads →
  147. → 反查 fingerprint 集 → enumerate candidates(排除已有 fp)→
  148. → 飞书审批 → approve 项 → 真 POST /adgroups/add → 返回新建的 adgroup_id 列表
  149. Returns: 本次新建成功的广告 list[dict],每项含 {account_id, adgroup_id, adgroup_name, wechat_position}
  150. """
  151. from tools.ad_api import _get
  152. from tools.im_approval_ad_creation import run_ad_approval_workflow
  153. creation_accounts = get_creation_account_ids()
  154. if not creation_accounts:
  155. logger.error("[phase0] 待投放账户配置为空,退出")
  156. return []
  157. # Task 26:NORMAL + SUSPEND 都算占用唯一性槽位(腾讯文档:删除前历史广告占槽位)
  158. OCCUPIED_STATUSES = {"AD_STATUS_NORMAL", "AD_STATUS_SUSPEND"}
  159. pending_ad_records: list[dict] = []
  160. for account_id in creation_accounts:
  161. logger.info("=" * 60)
  162. logger.info("[phase0] 账户 %d 处理开始", account_id)
  163. try:
  164. grant_result = ensure_account_audience_grant(account_id)
  165. logger.info(
  166. "[phase0] 人群包校验完成: status=%s audience_id=%s audience=%r",
  167. grant_result.get("status"),
  168. grant_result.get("audience_id"),
  169. grant_result.get("audience_name"),
  170. )
  171. except Exception as e:
  172. logger.exception("[phase0] account=%d 人群包授权/验证失败,跳过:%s", account_id, e)
  173. continue
  174. # Task 26:查所有非 DELETED 广告,NORMAL+SUSPEND 都算占用槽位
  175. try:
  176. r = _get("/adgroups/get", {
  177. "account_id": account_id, "page": 1, "page_size": 100,
  178. "fields": ["adgroup_id", "configured_status"],
  179. })
  180. all_ads = (r.get("data") or {}).get("list") or []
  181. normal_n = sum(1 for a in all_ads if a.get("configured_status") == "AD_STATUS_NORMAL")
  182. suspend_n = sum(1 for a in all_ads if a.get("configured_status") == "AD_STATUS_SUSPEND")
  183. occupied = [a for a in all_ads if a.get("configured_status") in OCCUPIED_STATUSES]
  184. logger.info(
  185. "[phase0] 广告数: 总 %d,NORMAL %d + SUSPEND %d = 占用 %d / 目标 %d",
  186. len(all_ads), normal_n, suspend_n, len(occupied), target_ads,
  187. )
  188. except Exception as e:
  189. logger.exception("[phase0] account=%d 查广告数失败: %s", account_id, e)
  190. continue
  191. to_create = max(0, target_ads - len(occupied))
  192. if to_create == 0:
  193. logger.info("[phase0] 占用槽位已满,跳过")
  194. continue
  195. # Task 27:fingerprint 预校验 — 反查现存广告的 fp 集合,enumerate 时排除
  196. existing_fps = _fetch_existing_fingerprints_for_account(account_id)
  197. # enumerate 候选(模块 A,差异化 wechat_position 有/无)
  198. try:
  199. candidates = enumerate_new_ad_candidates(
  200. account_id, count=to_create,
  201. existing_fingerprints=existing_fps,
  202. )
  203. except Exception as e:
  204. logger.exception("[phase0] account=%d enumerate 失败: %s", account_id, e)
  205. continue
  206. if not candidates:
  207. logger.warning("[phase0] enumerate 返回 0 条候选,跳过")
  208. continue
  209. today = now_in_timezone().strftime("%Y-%m-%d")
  210. for c in candidates:
  211. age_range = ",".join(
  212. f"{a.get('min')}-{a.get('max')}" for a in c.age
  213. )
  214. # 新建广告默认开启;实际投放仍受创意审核/账户/预算控制。
  215. # 这里显式传 NORMAL,避免未来默认值变化影响端到端创建语义。
  216. body = build_ad_request_body(c, configured_status="AD_STATUS_NORMAL")
  217. rec = {
  218. "approval_date": today,
  219. "account_id": c.account_id,
  220. "audience_tier_label": c.audience_tier_label,
  221. "adgroup_name": c.adgroup_name,
  222. "site_set": c.site_set,
  223. "delivery_version": c.delivery_version,
  224. "wechat_position": c.wechat_position,
  225. "bid_amount_fen": c.bid_amount_fen,
  226. "age_range": age_range,
  227. "fingerprint": c.fingerprint,
  228. "_request_body": body,
  229. }
  230. pending_ad_records.append(rec)
  231. if not pending_ad_records:
  232. logger.info("[phase0] 无广告需新建,Phase 0 结束")
  233. return []
  234. # 飞书审批(如需要)
  235. data_dir = _HERE / "outputs" / "data"
  236. if CREATION_APPROVAL_REQUIRED:
  237. logger.info(
  238. "[phase0] CREATION_APPROVAL_REQUIRED=True → 飞书审批 %d 条广告候选",
  239. len(pending_ad_records),
  240. )
  241. sheet_meta, actions = run_ad_approval_workflow(
  242. records=pending_ad_records,
  243. xlsx_output_dir=data_dir,
  244. timeout_minutes=CREATION_APPROVAL_TIMEOUT_MINUTES,
  245. )
  246. for i, rec in enumerate(pending_ad_records, start=1):
  247. rec["action"] = actions.get(i, "skip")
  248. else:
  249. for rec in pending_ad_records:
  250. rec["action"] = "approve"
  251. # POST 真建 approve 项
  252. created: list[dict] = []
  253. for rec in pending_ad_records:
  254. if rec.get("action") != "approve":
  255. continue
  256. adgroup_id = post_ad_with_prepared_body(
  257. account_id=int(rec["account_id"]),
  258. body=rec["_request_body"],
  259. )
  260. if adgroup_id:
  261. created.append({
  262. "account_id": rec["account_id"],
  263. "adgroup_id": adgroup_id,
  264. "adgroup_name": rec["adgroup_name"],
  265. "wechat_position": rec.get("wechat_position"),
  266. })
  267. logger.info(
  268. "[phase0] 完成:候选 %d 条,approve %d 条,实际建 %d 条",
  269. len(pending_ad_records),
  270. sum(1 for r in pending_ad_records if r.get("action") == "approve"),
  271. len(created),
  272. )
  273. return created
  274. def _wait_created_ads_visible(created_ads: list[dict], timeout_seconds: int = 60) -> None:
  275. """等待刚创建的广告在 /adgroups/get 中可见。
  276. 腾讯 adgroups/add 成功后,list 接口存在短暂一致性延迟。若立刻进入 Phase 1,
  277. 可能只扫到部分新广告,导致同一轮只给一条广告补创意。
  278. """
  279. if not created_ads:
  280. return
  281. from tools.ad_api import _get
  282. by_account: dict[int, set[int]] = {}
  283. for ad in created_ads:
  284. by_account.setdefault(int(ad["account_id"]), set()).add(int(ad["adgroup_id"]))
  285. deadline = time.time() + timeout_seconds
  286. remaining = {acct: set(ids) for acct, ids in by_account.items()}
  287. while time.time() < deadline and any(remaining.values()):
  288. for account_id, ids in list(remaining.items()):
  289. if not ids:
  290. continue
  291. try:
  292. resp = _get("/adgroups/get", {
  293. "account_id": account_id,
  294. "page": 1,
  295. "page_size": 100,
  296. "fields": ["adgroup_id", "configured_status", "system_status"],
  297. })
  298. visible = {
  299. int(item["adgroup_id"])
  300. for item in ((resp.get("data") or {}).get("list") or [])
  301. if item.get("adgroup_id") is not None
  302. }
  303. ids.difference_update(visible)
  304. except Exception as e:
  305. logger.warning(
  306. "[phase0] 等待新广告可见失败 account=%d: %s",
  307. account_id, e,
  308. )
  309. if any(remaining.values()):
  310. logger.info("[phase0] 等待新广告在列表接口可见: %s", remaining)
  311. time.sleep(5)
  312. not_visible = {acct: sorted(ids) for acct, ids in remaining.items() if ids}
  313. if not_visible:
  314. logger.warning("[phase0] 部分新广告仍未在 list 可见,继续 Phase 1: %s", not_visible)
  315. else:
  316. logger.info("[phase0] 新建广告均已在 list 接口可见")
  317. def phase1_prepare(target_creatives: int = TARGET_CREATIVES_PER_AD) -> list[dict]:
  318. """Phase 1:扫账户 → 关联点过滤 → 准备 pending records(不 POST 腾讯)。
  319. Returns:
  320. pending_records — 每个元素是 prepare_one_creative_for_ad 返回的 dict
  321. """
  322. creation_accounts = get_creation_account_ids()
  323. if not creation_accounts:
  324. logger.error("[phase1] 待投放账户配置为空,Phase 1 退出")
  325. return []
  326. excluded_ad_ids = load_excluded_ad_ids_from_adjustment()
  327. logger.info("[phase1] 关联点过滤集合 size=%d", len(excluded_ad_ids))
  328. pending_records: list[dict] = []
  329. # 素材排重只读取已有明确结果的 DB 记录。
  330. # pending/prepared 没有审批或投放结果,不进入排重。
  331. # 但同一轮审批候选需要做展示去重,避免表格里同 crowd_package 反复出现同一素材。
  332. # 这个 set 只存在内存里,不写历史排重库;进程结束即失效。
  333. display_used_material_ids_by_crowd: dict[str, set[str]] = {}
  334. # landing_video 不进历史排重库,只在同一广告本轮候选内做限频。
  335. for account_id in creation_accounts:
  336. logger.info("=" * 60)
  337. logger.info("[phase1] 账户 %d 处理开始", account_id)
  338. try:
  339. ads = find_ads_needing_creatives(account_id, min_creatives=target_creatives)
  340. except Exception as e:
  341. logger.exception("[phase1] account=%d find_ads 失败,跳过:%s", account_id, e)
  342. continue
  343. ads_after_filter = [a for a in ads if a["adgroup_id"] not in excluded_ad_ids]
  344. excluded_count = len(ads) - len(ads_after_filter)
  345. if excluded_count:
  346. logger.info(
  347. "[phase1] account=%d 关联点过滤排除 %d 条",
  348. account_id, excluded_count,
  349. )
  350. if not ads_after_filter:
  351. logger.info("[phase1] account=%d 无广告需补创意", account_id)
  352. continue
  353. try:
  354. crowd_package = get_account_crowd_package(account_id)
  355. except Exception as e:
  356. logger.exception(
  357. "[phase1] account=%d 读取 crowd_package 失败,跳过:%s",
  358. account_id, e,
  359. )
  360. continue
  361. display_excluded_material_ids = display_used_material_ids_by_crowd.setdefault(
  362. crowd_package, set(),
  363. )
  364. for ad in ads_after_filter:
  365. adgroup_id = ad["adgroup_id"]
  366. already_have = ad["creative_count"]
  367. to_add = max(0, target_creatives - already_have)
  368. landing_counts_for_ad: dict[int, int] = {}
  369. logger.info(
  370. "[phase1] adgroup=%d(have=%d need=%d)",
  371. adgroup_id, already_have, to_add,
  372. )
  373. for _ in range(to_add):
  374. landing_excluded_for_ad = {
  375. vid
  376. for vid, count in landing_counts_for_ad.items()
  377. if count >= MAX_SAME_LANDING_PER_AD_IN_RUN
  378. }
  379. try:
  380. rec = prepare_one_creative_for_ad(
  381. account_id, adgroup_id,
  382. excluded_material_ids=display_excluded_material_ids,
  383. excluded_landing_ids=landing_excluded_for_ad,
  384. )
  385. except Exception as e:
  386. logger.exception(
  387. "[phase1] adgroup=%d 准备失败:%s", adgroup_id, e,
  388. )
  389. rec = None
  390. if rec:
  391. pending_records.append(rec)
  392. material_id = rec.get("_material_id")
  393. if material_id:
  394. display_excluded_material_ids.add(str(material_id))
  395. logger.info(
  396. "[phase1] 本轮展示去重登记 crowd=%r material=%s size=%d",
  397. crowd_package, material_id,
  398. len(display_excluded_material_ids),
  399. )
  400. landing_video_id = rec.get("landing_video_id")
  401. if landing_video_id is not None:
  402. landing_video_id = int(landing_video_id)
  403. landing_counts_for_ad[landing_video_id] = (
  404. landing_counts_for_ad.get(landing_video_id, 0) + 1
  405. )
  406. logger.info(
  407. "[phase1] 本轮同广告 landing 计数 adgroup=%d landing=%d count=%d limit=%d",
  408. adgroup_id, landing_video_id,
  409. landing_counts_for_ad[landing_video_id],
  410. MAX_SAME_LANDING_PER_AD_IN_RUN,
  411. )
  412. try:
  413. record_prepared_material_usage(rec)
  414. except Exception as e:
  415. logger.warning(
  416. "[phase1] material usage 记录失败 account=%d adgroup=%d material=%s:%s",
  417. account_id, adgroup_id, rec.get("_material_id"), e,
  418. )
  419. else:
  420. # 2026-06-10 用户要求:单条 prepare 失败 → continue 不 break
  421. # 同广告剩余 to_add 创意还能继续试,不被一次失败拖累
  422. logger.info(
  423. "[phase1] adgroup=%d 本条创意 prepare 失败,试下一条",
  424. adgroup_id,
  425. )
  426. logger.info("=" * 60)
  427. logger.info("[phase1] 准备完成,共 %d 条 pending records", len(pending_records))
  428. return pending_records
  429. def _write_pending_records(records: list[dict], output_dir: Path) -> Path:
  430. """落 Phase 1 产物 JSON(供 Phase 3 独立 apply 用 / 追溯)。"""
  431. output_dir.mkdir(parents=True, exist_ok=True)
  432. now = now_in_timezone()
  433. date_str = now.strftime("%Y%m%d")
  434. ts = now.strftime("%H%M%S")
  435. out_path = output_dir / f"creation_pending_{date_str}_{ts}.json"
  436. with open(out_path, "w", encoding="utf-8") as f:
  437. json.dump(records, f, ensure_ascii=False, indent=2)
  438. return out_path
  439. def phase2_approval(records: list[dict], xlsx_output_dir: Path) -> dict[int, str]:
  440. """Phase 2:飞书审批(若需要)。
  441. Returns: actions {row_idx: action}, 1-based row_idx
  442. """
  443. from tools.im_approval_creation import run_approval_workflow
  444. sheet_meta, actions = run_approval_workflow(
  445. records=records,
  446. xlsx_output_dir=xlsx_output_dir,
  447. timeout_minutes=CREATION_APPROVAL_TIMEOUT_MINUTES,
  448. )
  449. logger.info(
  450. "[phase2] 审批完成 sheet_url=%s actions=%d/%d",
  451. sheet_meta.get("url"), len(actions), len(records),
  452. )
  453. return actions
  454. def run_once() -> dict:
  455. """完整主循环:Phase 0 → Phase 1 → Phase 2(若开关 True)→ Phase 3。"""
  456. run_started = now_in_timezone().isoformat()
  457. sync_stats: dict = {}
  458. # Phase -1:每日主流程启动时先同步飞书「自动化账户」配置表。
  459. logger.info("=" * 60)
  460. logger.info("[main] Phase -1 启动 — 同步飞书自动化账户配置")
  461. try:
  462. from sync_feishu_account_config import sync_from_feishu
  463. sync_stats = sync_from_feishu()
  464. logger.info("[main] Phase -1 完成: %s", sync_stats)
  465. except Exception as e:
  466. logger.exception("[main] Phase -1 同步飞书配置失败,本轮停止:%s", e)
  467. return {
  468. "run_started": run_started,
  469. "run_finished": now_in_timezone().isoformat(),
  470. "approval_required": CREATION_APPROVAL_REQUIRED,
  471. "sync_stats": {"error": str(e)},
  472. "phase0_created_ads": 0,
  473. "total": {"phase1_prepared": 0},
  474. }
  475. # Phase 0:模块 A 建广告(满足每账户 ADS_PER_ACCOUNT 条)
  476. logger.info("=" * 60)
  477. logger.info("[main] Phase 0 启动 — 模块 A 检查 + 建广告")
  478. created_ads = phase0_create_ads()
  479. logger.info("[main] Phase 0 完成:本轮新建广告 %d 条", len(created_ads))
  480. _wait_created_ads_visible(created_ads)
  481. # Phase 1:模块 B 给所有广告(新+旧)补创意
  482. logger.info("=" * 60)
  483. logger.info("[main] Phase 1 启动 — 模块 B 给广告补创意")
  484. pending_records = phase1_prepare()
  485. if not pending_records:
  486. logger.info("[main] Phase 1 无 pending records,主循环退出")
  487. return {
  488. "run_started": run_started,
  489. "run_finished": now_in_timezone().isoformat(),
  490. "approval_required": CREATION_APPROVAL_REQUIRED,
  491. "sync_stats": sync_stats,
  492. "phase0_created_ads": len(created_ads),
  493. "total": {"phase1_prepared": 0},
  494. }
  495. data_dir = _HERE / "outputs" / "data"
  496. pending_path = _write_pending_records(pending_records, data_dir)
  497. logger.info("[main] pending records 已写入: %s", pending_path)
  498. # Phase 2:审批(或 skip)
  499. if CREATION_APPROVAL_REQUIRED:
  500. logger.info("[main] CREATION_APPROVAL_REQUIRED=True → 进 Phase 2 飞书审批")
  501. actions = phase2_approval(pending_records, data_dir)
  502. for i, rec in enumerate(pending_records, start=1):
  503. rec["action"] = actions.get(i, "skip")
  504. else:
  505. logger.info("[main] CREATION_APPROVAL_REQUIRED=False → 全 records approve")
  506. for rec in pending_records:
  507. rec["action"] = "approve"
  508. # Phase 3:执行
  509. logger.info("=" * 60)
  510. logger.info("[main] Phase 3 执行启动")
  511. summary = apply_pending_records(pending_records)
  512. summary["approval_required"] = CREATION_APPROVAL_REQUIRED
  513. summary["pending_records_path"] = str(pending_path)
  514. summary_path = write_apply_summary(summary, data_dir)
  515. logger.info("[main] summary 已写入: %s", summary_path)
  516. # 发执行汇报
  517. _send_apply_summary_to_feishu(summary)
  518. summary["run_started"] = run_started
  519. summary["run_finished"] = now_in_timezone().isoformat()
  520. summary["sync_stats"] = sync_stats
  521. summary["phase0_created_ads"] = len(created_ads)
  522. summary["phase0_ads"] = created_ads
  523. return summary
  524. def main() -> int:
  525. """模块 B 创意搭建子系统主入口:初始化日志 → 运行主循环 → 输出汇总。"""
  526. _setup_logging()
  527. logger.info("=" * 60)
  528. logger.info("模块 B 创意搭建子系统 — 主循环启动")
  529. logger.info("TARGET_CREATIVES_PER_AD = %d", TARGET_CREATIVES_PER_AD)
  530. logger.info("CREATION_APPROVAL_REQUIRED = %s", CREATION_APPROVAL_REQUIRED)
  531. logger.info("WHITELIST_ACCOUNTS = %s", WHITELIST_ACCOUNTS)
  532. logger.info("=" * 60)
  533. summary = run_once()
  534. t = summary.get("total") or {}
  535. logger.info("=" * 60)
  536. logger.info("[main] 主循环结束")
  537. if "phase1_prepared" in t:
  538. logger.info(" phase1_prepared = %d", t["phase1_prepared"])
  539. else:
  540. logger.info(" records = %d", t.get("records", 0))
  541. logger.info(" approved = %d", t.get("approved", 0))
  542. logger.info(" posted_ok = %d", t.get("posted_ok", 0))
  543. logger.info(" posted_failed = %d", t.get("posted_failed", 0))
  544. logger.info("=" * 60)
  545. return 0 if t.get("posted_failed", 0) == 0 else 1
  546. if __name__ == "__main__":
  547. sys.exit(main())