execute_creation_once.py 25 KB

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