execute_creation_once.py 26 KB

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