creative_creation.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242
  1. """创意搭建主入口(模块 B)。
  2. 数据流(2026-06-08 用户确认 + 端到端打通):
  3. 承接视频(piaoquantv) → 多路召回素材(vector) → top 1 → 上传素材图(MD5 幂等)
  4. → 调 xcx/save 注册落地计划(拿 page_url + creative_name)→ 读账户 brand
  5. → 构造 body → POST /dynamic_creatives/add → 绑到广告
  6. 决策落地(已验证):
  7. - image 组件:**必须用 image_id**(image_url 会 reject code=18001)
  8. → 实现:下载 cover URL → MD5 → POST /v3.0/images/add multipart → 拿 image_id
  9. → MD5 幂等:同账户重复上传返回同 ID(无需本地缓存)
  10. - brand 组件:**必填**(漏传会 reject code=1800269)
  11. → brand_image_id 跨账户不可复用(reject code=1530003)
  12. → 优先从 DB account_whitelist 读账户级 brand_name/brand_image_id
  13. → 若缺失,按 ad_creation_account_config.brand_key 读取 brand_asset_template,上传并写回账户
  14. - dynamic_creative_type: DYNAMIC_CREATIVE_TYPE_PROGRAM(参考样本 9744753978)
  15. - description: 素材 title 一条(MVP)
  16. - jump_info / 命名:**piaoquantv xcx/save 接口统一管**
  17. → page_url(mini_program_path)和 root_source_id(creative_name)都来自服务侧
  18. → 客户端不本地拼接、不本地命名,保证归因锚点跨系统一致
  19. - 配置 NORMAL 状态,挂上后腾讯进入 PENDING(普通素材审核 2-4 小时)
  20. """
  21. import logging
  22. import random
  23. from dataclasses import asdict, dataclass
  24. from typing import Iterator, Optional
  25. from config import (
  26. CREATIVE_DESCRIPTION_COUNT_PER_AD,
  27. CREATIVE_DESCRIPTION_POOL,
  28. LANDING_EXCLUDED_CATEGORIES,
  29. MARKETING_CARRIER_GH_ID,
  30. MAX_LANDING_ATTEMPTS_PER_AD,
  31. MAX_MATERIAL_PER_LANDING,
  32. TARGET_CREATIVES_PER_AD,
  33. )
  34. from tools.ad_api import _check, _get, _post, images_add
  35. from tools.account_material_strategy import load_account_material_strategy
  36. from tools.ai_generated_material import (
  37. get_or_generate_assets_for_landing,
  38. update_generated_material_status,
  39. )
  40. from tools.external_recalled_material import (
  41. prepare_external_material_for_landing,
  42. update_external_material_status,
  43. )
  44. from tools.landing_plan import LandingPlanResult, create_landing_plan
  45. from tools.material_recall import Material, recall_materials_for_video
  46. from tools.creative_material_usage import (
  47. load_recent_used_material_ids,
  48. merge_used_material_ids,
  49. )
  50. from tools.video_recall import (
  51. LandingVideo,
  52. PIAOQUANTV_HOT_FALLBACK_SOURCE,
  53. PIAOQUANTV_VIDEO_SOURCE,
  54. fetch_landing_videos_for_account,
  55. get_account_crowd_package,
  56. map_crowd_package_for_video_recall,
  57. )
  58. from tools.video_feature_query import VideoElementFeature, fetch_video_element_features
  59. from tools.video_risk import VideoRiskResult, check_video_risk
  60. logger = logging.getLogger(__name__)
  61. def _landing_category_values(v: LandingVideo) -> set[str]:
  62. raw = v.category or ""
  63. return {part.strip() for part in raw.replace(",", ",").split(",") if part.strip()}
  64. def _is_landing_candidate(v: LandingVideo) -> bool:
  65. """承接视频基础预筛:内容品类不在黑名单。
  66. 素材召回特征统一通过 video_id 查 ODPS,不再依赖 videoContentList 返回的
  67. pointType / standardElement。
  68. """
  69. excluded = _landing_category_values(v) & LANDING_EXCLUDED_CATEGORIES
  70. if excluded:
  71. logger.info(
  72. "[creative_creation] landing=%d category=%r 命中排除品类,跳过",
  73. v.video_id, v.category,
  74. )
  75. return False
  76. return True
  77. def _pick_image_url(material: Material) -> str:
  78. """从素材里取 image URL — material.cover 优先,fallback 到 raw.imageList[0]"""
  79. if material.cover:
  80. return material.cover
  81. images = (material.raw or {}).get("imageList") or []
  82. return images[0] if images else ""
  83. @dataclass
  84. class _LandingSourceState:
  85. videos: list[LandingVideo]
  86. features_by_vid: dict[int, list[VideoElementFeature]]
  87. stats: dict
  88. class LandingCandidatePool:
  89. """一次运行内复用的承接视频候选池。
  90. 只缓存无外部副作用的步骤:视频拉取、品类过滤、ODPS 特征读取。
  91. 风险审核按实际遍历到的 landing 懒执行并缓存,避免一次性审核用不到的视频。
  92. 图片上传、AI 生图、xcx/save 仍由 prepare_one_creative_for_ad 串行执行。
  93. """
  94. def __init__(self, account_id: int, max_landings: int = MAX_LANDING_ATTEMPTS_PER_AD):
  95. self.account_id = account_id
  96. self.max_landings = max_landings
  97. self.crowd_package = get_account_crowd_package(account_id)
  98. self.video_crowd_package = map_crowd_package_for_video_recall(self.crowd_package)
  99. self._source_state_by_label: dict[str, _LandingSourceState] = {}
  100. self._risk_by_vid: dict[int, VideoRiskResult] = {}
  101. self._no_features_logged: set[tuple[str, int]] = set()
  102. @property
  103. def source_plan(self) -> list[tuple[str, str]]:
  104. plan = [("primary", PIAOQUANTV_VIDEO_SOURCE)]
  105. if PIAOQUANTV_HOT_FALLBACK_SOURCE != PIAOQUANTV_VIDEO_SOURCE:
  106. plan.append(("hot", PIAOQUANTV_HOT_FALLBACK_SOURCE))
  107. return plan
  108. def iter_featured_landings(self) -> Iterator[tuple[str, LandingVideo, list[VideoElementFeature]]]:
  109. for source_label, source in self.source_plan:
  110. state = self._load_source(source_label, source)
  111. for v in state.videos:
  112. element_features = state.features_by_vid.get(v.video_id) or []
  113. if not element_features:
  114. if (source_label, v.video_id) not in self._no_features_logged:
  115. state.stats["no_features"] += 1
  116. self._no_features_logged.add((source_label, v.video_id))
  117. logger.info(
  118. "[landing_candidate_pool] landing=%d 无 ODPS 召回特征,跳过",
  119. v.video_id,
  120. )
  121. continue
  122. state.stats["feature_candidates_yielded"] += 1
  123. yield source_label, v, element_features
  124. def check_risk(self, source_label: str, landing: LandingVideo) -> VideoRiskResult:
  125. risk = self._risk_by_vid.get(landing.video_id)
  126. if risk is not None:
  127. return risk
  128. state = self._source_state_by_label[source_label]
  129. risk = check_video_risk(landing.video_id)
  130. self._risk_by_vid[landing.video_id] = risk
  131. state.stats["risk_checked"] += 1
  132. if not risk.passed:
  133. state.stats["risk_blocked"] += 1
  134. state.stats["risk_blocked_by_vid"][landing.video_id] = risk.reason
  135. logger.warning(
  136. "[landing_candidate_pool] landing=%d 风险拦截:%s",
  137. landing.video_id, risk.reason,
  138. )
  139. return risk
  140. def _load_source(self, source_label: str, source: str) -> _LandingSourceState:
  141. if source_label in self._source_state_by_label:
  142. return self._source_state_by_label[source_label]
  143. videos = fetch_landing_videos_for_account(
  144. self.account_id,
  145. page_size=100,
  146. source=source,
  147. enable_hot_fallback=False,
  148. )
  149. valid = [v for v in videos if _is_landing_candidate(v)]
  150. features_by_vid = fetch_video_element_features(v.video_id for v in valid)
  151. stats = {
  152. "fetched": len(videos),
  153. "valid": len(valid),
  154. "category_filtered": max(len(videos) - len(valid), 0),
  155. "risk_checked": 0,
  156. "risk_blocked": 0,
  157. "risk_blocked_by_vid": {},
  158. "no_features": 0,
  159. "feature_candidates_yielded": 0,
  160. }
  161. logger.info(
  162. "[landing_candidate_pool] account=%d source=%s valid=%d/%d feature_videos=%d feature_rows=%d",
  163. self.account_id, source_label, len(valid),
  164. len(videos), len(features_by_vid), sum(len(v) for v in features_by_vid.values()),
  165. )
  166. state = _LandingSourceState(
  167. videos=valid,
  168. features_by_vid=features_by_vid,
  169. stats=stats,
  170. )
  171. self._source_state_by_label[source_label] = state
  172. logger.info(
  173. "[landing_candidate_pool] account=%d source=%s stats=%s",
  174. self.account_id, source_label, stats,
  175. )
  176. return state
  177. def build_landing_candidate_pool(
  178. account_id: int,
  179. max_landings: int = MAX_LANDING_ATTEMPTS_PER_AD,
  180. ) -> LandingCandidatePool:
  181. return LandingCandidatePool(account_id, max_landings=max_landings)
  182. def find_ads_needing_creatives(
  183. account_id: int,
  184. min_creatives: int = TARGET_CREATIVES_PER_AD,
  185. ) -> list[dict]:
  186. """扫描账户下"需要补创意"的广告(P0-B,2026-06-09)。
  187. 口径(2026-06-08 用户确认 = C):
  188. configured_status = AD_STATUS_NORMAL AND creative_count < min_creatives
  189. 实测发现:腾讯 /adgroups/get 不返回 creative_count 字段,
  190. 所以分两条路径取创意数:
  191. - 快路径:system_status = ADGROUP_STATUS_CREATIVE_EMPTY → creative_count = 0
  192. - 慢路径:其他状态 → 单独调 /dynamic_creatives/get 数总数(N+1,目前广告 ≤ 10 可接受)
  193. Args:
  194. account_id: 腾讯广告主账号 ID
  195. min_creatives: 默认读 config.TARGET_CREATIVES_PER_AD(测试=1,生产应回 15)
  196. — find 阈值 + 补量目标的同一变量,无矛盾
  197. Returns:
  198. [{adgroup_id, adgroup_name, system_status, creative_count}, ...]
  199. """
  200. # 注意:腾讯 filtering 对 configured_status IN 静默拒绝(实测 2026-06-09 加了 filtering 返回 0)
  201. # 改为不加 filtering 拉全部 + Python 内存过滤(单账户 ≤ 10 条广告,代价≈0)
  202. resp = _get("/adgroups/get", {
  203. "account_id": account_id, "page": 1, "page_size": 100,
  204. "fields": ["adgroup_id", "adgroup_name", "system_status", "configured_status"],
  205. })
  206. all_ads_raw = (resp.get("data") or {}).get("list") or []
  207. all_ads = [a for a in all_ads_raw if a.get("configured_status") == "AD_STATUS_NORMAL"]
  208. logger.info(
  209. "[find_ads_needing_creatives] account=%d 共 %d 条广告,%d 条 NORMAL",
  210. account_id, len(all_ads_raw), len(all_ads),
  211. )
  212. out = []
  213. for ad in all_ads:
  214. adgroup_id = ad["adgroup_id"]
  215. system_status = ad.get("system_status", "")
  216. adgroup_name = ad.get("adgroup_name", "")
  217. if system_status == "ADGROUP_STATUS_CREATIVE_EMPTY":
  218. creative_count = 0
  219. else:
  220. cresp = _get("/dynamic_creatives/get", {
  221. "account_id": account_id, "page": 1, "page_size": 100,
  222. "filtering": [{
  223. "field": "adgroup_id", "operator": "IN",
  224. "values": [str(adgroup_id)],
  225. }],
  226. "fields": ["dynamic_creative_id", "system_status"],
  227. })
  228. all_creatives = (cresp.get("data") or {}).get("list") or []
  229. # 2026-06-09:忽略 DENIED 状态(审核拒绝),让 find_ads 能重补
  230. # 其他状态(PENDING/ACTIVE/SUSPEND 等)都算"已挂"
  231. denied_count = sum(
  232. 1 for c in all_creatives
  233. if c.get("system_status") == "DYNAMIC_CREATIVE_STATUS_DENIED"
  234. )
  235. creative_count = len(all_creatives) - denied_count
  236. if denied_count:
  237. logger.info(
  238. "[find_ads_needing_creatives] adgroup=%d 总创意 %d 减去 %d 条 DENIED → 有效 %d",
  239. adgroup_id, len(all_creatives), denied_count, creative_count,
  240. )
  241. if creative_count < min_creatives:
  242. out.append({
  243. "adgroup_id": adgroup_id,
  244. "adgroup_name": adgroup_name,
  245. "system_status": system_status,
  246. "creative_count": creative_count,
  247. })
  248. logger.info(
  249. "[find_ads_needing_creatives] ✓ adgroup=%d name=%r creative_count=%d < %d",
  250. adgroup_id, adgroup_name, creative_count, min_creatives,
  251. )
  252. logger.info(
  253. "[find_ads_needing_creatives] account=%d 命中 %d 条需补创意",
  254. account_id, len(out),
  255. )
  256. return out
  257. def load_excluded_ad_ids_from_adjustment(
  258. date_str: Optional[str] = None,
  259. output_dir: str = "outputs/reports",
  260. ) -> set[int]:
  261. """读调控当日决策 CSV,提取被 pause 的 adgroup_id(P0-E 关联点过滤,2026-06-09)。
  262. 新建子系统启动时调用,排除调控当日已决策 pause 的广告,避免"调控刚关、新建又补创意"的冲突。
  263. Args:
  264. date_str: 形如 '20260609';None → 用昨天日期(调控 cron 02:00 UTC 跑完后)
  265. output_dir: 调控产物目录,相对当前工作目录
  266. Returns:
  267. 被 pause 的 adgroup_id 集合;文件不存在 / CSV 字段缺失时返回空集(降级,不阻塞)
  268. """
  269. import csv
  270. import glob
  271. import os
  272. from datetime import datetime, timedelta
  273. if date_str is None:
  274. date_str = (datetime.utcnow() - timedelta(days=1)).strftime("%Y%m%d")
  275. pattern = os.path.join(output_dir, f"llm_decisions_{date_str}*.csv")
  276. matches = sorted(glob.glob(pattern))
  277. if not matches:
  278. logger.warning(
  279. "[load_excluded_ad_ids] 未找到调控决策 CSV: %s,返回空排除集(不阻塞主循环)",
  280. pattern,
  281. )
  282. return set()
  283. latest = matches[-1]
  284. excluded: set[int] = set()
  285. with open(latest, newline="", encoding="utf-8") as f:
  286. reader = csv.DictReader(f)
  287. for row in reader:
  288. action = (row.get("action") or "").strip().lower()
  289. ad_id_raw = (row.get("ad_id") or row.get("adgroup_id") or "").strip()
  290. if action == "pause" and ad_id_raw.isdigit():
  291. excluded.add(int(ad_id_raw))
  292. logger.info(
  293. "[load_excluded_ad_ids] 从 %s 读出 %d 个 pause 广告(排除)",
  294. os.path.basename(latest), len(excluded),
  295. )
  296. return excluded
  297. def find_existing_creative_by_image(
  298. account_id: int, adgroup_id: int, material_image_id: str,
  299. ) -> Optional[int]:
  300. """查 adgroup 下是否已有创意挂了这个素材 image_id(幂等检查)。
  301. 判等键(2026-06-08 决策):**同 adgroup + 同 material_image_id**。
  302. - 不按 creative_name 判等:name = root_source_id,每次 xcx/save 都新,等于没做
  303. - 按 image_id 判等:同 image 在同 adgroup 下挂多条会被腾讯模型降权曝光
  304. Returns:
  305. 已有创意的 dynamic_creative_id;无则 None。
  306. """
  307. resp = _get("/dynamic_creatives/get", {
  308. "account_id": account_id, "page": 1, "page_size": 100,
  309. "filtering": [{
  310. "field": "adgroup_id", "operator": "IN", "values": [str(adgroup_id)],
  311. }],
  312. "fields": ["dynamic_creative_id", "creative_components"],
  313. })
  314. items = (resp.get("data") or {}).get("list") or []
  315. for c in items:
  316. images = (c.get("creative_components") or {}).get("image") or []
  317. for img in images:
  318. existing_id = ((img.get("value") or {}).get("image_id")) or ""
  319. if str(existing_id) == str(material_image_id):
  320. cid = int(c.get("dynamic_creative_id"))
  321. logger.info(
  322. "[idempotency] adgroup=%d image_id=%s 已挂创意 creative_id=%d,skip 新建",
  323. adgroup_id, material_image_id, cid,
  324. )
  325. return cid
  326. return None
  327. def get_account_brand(account_id: int) -> dict:
  328. """读取或初始化账户级 brand 资产。
  329. 返回 {"brand_name": str, "brand_image_id": str}。
  330. 跨账户 brand_image_id 不可复用,所以一定按 account_id 取。
  331. 如果 account_whitelist 还没有 brand_image_id,则按待投放配置的 brand_key
  332. 找统一品牌模板,上传模板 URL 到当前账户,并把新 image_id 写回 DB。
  333. """
  334. from db.connection import get_connection
  335. conn = get_connection()
  336. try:
  337. with conn.cursor() as cur:
  338. cur.execute(
  339. "SELECT brand_name, brand_image_id FROM account_whitelist WHERE account_id=%s",
  340. (account_id,),
  341. )
  342. row = cur.fetchone()
  343. if row and row.get("brand_name") and row.get("brand_image_id"):
  344. return {
  345. "brand_name": row["brand_name"],
  346. "brand_image_id": str(row["brand_image_id"]),
  347. }
  348. cur.execute(
  349. """
  350. SELECT b.brand_key, b.brand_name, b.brand_image_url
  351. FROM ad_creation_account_config c
  352. JOIN brand_asset_template b
  353. ON b.brand_key = c.brand_key
  354. AND b.enabled = TRUE
  355. WHERE c.account_id=%s
  356. AND c.enabled = TRUE
  357. """,
  358. (account_id,),
  359. )
  360. tpl = cur.fetchone()
  361. finally:
  362. conn.close()
  363. if not tpl or not tpl.get("brand_name") or not tpl.get("brand_image_url"):
  364. raise RuntimeError(
  365. f"account {account_id} 未配置可用品牌资产模板。"
  366. "请在 ad_creation_account_config.brand_key 关联 brand_asset_template"
  367. )
  368. brand_name = tpl["brand_name"]
  369. brand_image_url = tpl["brand_image_url"]
  370. logger.info(
  371. "[brand] account=%d 缺 brand_image_id,按模板 %s 上传品牌图",
  372. account_id, tpl.get("brand_key"),
  373. )
  374. brand_image_id = images_add(account_id, brand_image_url)
  375. conn = get_connection()
  376. try:
  377. with conn.cursor() as cur:
  378. cur.execute(
  379. """
  380. UPDATE account_whitelist
  381. SET brand_name=%s,
  382. brand_image_id=%s,
  383. updated_by=%s,
  384. updated_at=CURRENT_TIMESTAMP
  385. WHERE account_id=%s
  386. """,
  387. (brand_name, brand_image_id, "auto-brand-init", account_id),
  388. )
  389. conn.commit()
  390. finally:
  391. conn.close()
  392. logger.info(
  393. "[brand] account=%d 已初始化 brand_name=%s brand_image_id=%s",
  394. account_id, brand_name, brand_image_id,
  395. )
  396. return {
  397. "brand_name": brand_name,
  398. "brand_image_id": str(brand_image_id),
  399. }
  400. def build_creative_request_body(
  401. account_id: int,
  402. adgroup_id: int,
  403. landing: LandingVideo,
  404. material: Material,
  405. material_image_id: str,
  406. brand_name: str,
  407. brand_image_id: str,
  408. creative_name: str,
  409. jump_path: str,
  410. description_contents: Optional[list] = None,
  411. ) -> dict:
  412. """生成 /v3.0/dynamic_creatives/add 的请求 body(纯函数,无 I/O)。
  413. Args:
  414. material_image_id: 已上传到当前账户的素材图 image_id
  415. brand_name / brand_image_id: 账户级 brand 资产(已上传)
  416. creative_name: 由 xcx/save 返回的 root_source_id(归因锚点)
  417. jump_path: 由 xcx/save 返回的 page_url(小程序跳转路径)
  418. description_contents: 文案列表(可选);None 时自动 random.sample(用于审批表回显)
  419. """
  420. # 默认文案由配置控制;生产当前统一使用"打开看看"。
  421. if description_contents is None:
  422. description_count = min(CREATIVE_DESCRIPTION_COUNT_PER_AD, len(CREATIVE_DESCRIPTION_POOL))
  423. description_contents = CREATIVE_DESCRIPTION_POOL[:description_count]
  424. jump_spec = {
  425. "page_type": "PAGE_TYPE_WECHAT_MINI_PROGRAM",
  426. "page_spec": {
  427. "wechat_mini_program_spec": {
  428. "mini_program_id": MARKETING_CARRIER_GH_ID,
  429. "mini_program_path": jump_path,
  430. }
  431. },
  432. }
  433. return {
  434. "account_id": account_id,
  435. "adgroup_id": adgroup_id,
  436. "dynamic_creative_name": creative_name,
  437. "delivery_mode": "DELIVERY_MODE_COMPONENT",
  438. "dynamic_creative_type": "DYNAMIC_CREATIVE_TYPE_PROGRAM",
  439. "configured_status": "AD_STATUS_NORMAL",
  440. "creative_components": {
  441. "description": [{"value": {"content": d}} for d in description_contents],
  442. "image": [{"value": {"image_id": material_image_id}}],
  443. "brand": [{"value": {
  444. "brand_name": brand_name,
  445. "brand_image_id": brand_image_id,
  446. }}],
  447. "action_button": [{"value": {"button_text": "查看详情"}}],
  448. "jump_info": [{"value": jump_spec}],
  449. "main_jump_info": [{"value": jump_spec}],
  450. },
  451. }
  452. def _pick_landing_and_materials(account_id: int) -> tuple[LandingVideo, list[Material]]:
  453. """召回链:承接视频 → 多路素材召回 → 取第一个有素材命中的 landing 及其 top 素材。
  454. 出口:确保 landing.point_type+standard_element 都有值(否则多路召回会全 skip)。
  455. """
  456. videos = fetch_landing_videos_for_account(account_id, page_size=50)
  457. valid = [v for v in videos if _is_landing_candidate(v)]
  458. if not valid:
  459. raise RuntimeError(
  460. f"account={account_id} 无 pointType+standardElement 都有值的承接视频"
  461. )
  462. for v in valid:
  463. risk = check_video_risk(v.video_id)
  464. if not risk.passed:
  465. logger.warning(
  466. "[creative_creation] landing=%d 风险拦截:%s",
  467. v.video_id, risk.reason,
  468. )
  469. continue
  470. materials = recall_materials_for_video(v, final_top_n=5)
  471. if materials:
  472. return v, materials
  473. raise RuntimeError(
  474. f"account={account_id} 前 {len(valid)} 条承接视频都召回 0 素材"
  475. )
  476. def preview_for_account(account_id: int, adgroup_id: int) -> dict:
  477. """承接视频 → 召回素材 → top 1 → 上传素材图 → 注册落地计划 → 读 brand → 构造 body。
  478. **会真实调:**
  479. - 腾讯 /images/add(MD5 幂等)
  480. - piaoquantv xcx/save(每次新建一条计划)
  481. body 是真实可投放的(只差 POST /dynamic_creatives/add)。
  482. """
  483. landing, materials = _pick_landing_and_materials(account_id)
  484. top_material = materials[0]
  485. image_url = _pick_image_url(top_material)
  486. if not image_url:
  487. raise ValueError(
  488. f"素材 {top_material.material_id} 既无 cover 也无 imageList,无法构造 image 组件"
  489. )
  490. material_image_id = images_add(account_id, image_url)
  491. crowd_package = get_account_crowd_package(account_id)
  492. plan = create_landing_plan(crowd_package, landing)
  493. brand = get_account_brand(account_id)
  494. body = build_creative_request_body(
  495. account_id=account_id, adgroup_id=adgroup_id,
  496. landing=landing, material=top_material,
  497. material_image_id=material_image_id,
  498. brand_name=brand["brand_name"],
  499. brand_image_id=brand["brand_image_id"],
  500. creative_name=plan.root_source_id,
  501. jump_path=plan.page_url,
  502. )
  503. return {
  504. "landing": asdict(landing),
  505. "material": asdict(top_material),
  506. "material_image_id": material_image_id,
  507. "brand": brand,
  508. "landing_plan": asdict(plan),
  509. "body": body,
  510. }
  511. def create_creative_for_ad(
  512. account_id: int, adgroup_id: int,
  513. landing: LandingVideo, material: Material,
  514. skip_if_exists: bool = True,
  515. ) -> int:
  516. """编排:上传素材图 → 幂等检查 → 注册落地计划 → 读 brand → build body → POST。
  517. Args:
  518. skip_if_exists: True(默认) — 同 adgroup + 同 material_image_id 已有创意时直接返回已有 ID,
  519. 跳过 xcx/save 注册和腾讯 POST,节省审核额度 + 避免模型降权。
  520. False — 强制新建(用于 A/B 测试不同归因锚点的场景)。
  521. Returns:
  522. dynamic_creative_id(新建或已有)
  523. """
  524. image_url = _pick_image_url(material)
  525. if not image_url:
  526. raise ValueError(
  527. f"素材 {material.material_id} 既无 cover 也无 imageList,无法构造 image 组件"
  528. )
  529. material_image_id = images_add(account_id, image_url)
  530. if skip_if_exists:
  531. existing_cid = find_existing_creative_by_image(account_id, adgroup_id, material_image_id)
  532. if existing_cid:
  533. return existing_cid
  534. crowd_package = get_account_crowd_package(account_id)
  535. plan = create_landing_plan(crowd_package, landing)
  536. brand = get_account_brand(account_id)
  537. body = build_creative_request_body(
  538. account_id, adgroup_id, landing, material,
  539. material_image_id=material_image_id,
  540. brand_name=brand["brand_name"],
  541. brand_image_id=brand["brand_image_id"],
  542. creative_name=plan.root_source_id,
  543. jump_path=plan.page_url,
  544. )
  545. logger.info(
  546. "[creative_creation] POST /dynamic_creatives/add adgroup=%d name=%s image_id=%s plan_id=%d",
  547. adgroup_id, body["dynamic_creative_name"], material_image_id, plan.plan_id,
  548. )
  549. resp = _post("/dynamic_creatives/add", body)
  550. data = _check(resp, "creative_create")
  551. return data.get("dynamic_creative_id")
  552. def prepare_one_creative_for_ad(
  553. account_id: int,
  554. adgroup_id: int,
  555. excluded_material_ids: Optional[set] = None,
  556. excluded_landing_ids: Optional[set] = None,
  557. landing_candidates: Optional[LandingCandidatePool] = None,
  558. failed_landing_ids: Optional[set[int]] = None,
  559. max_landings: int = MAX_LANDING_ATTEMPTS_PER_AD,
  560. max_materials_per_landing: int = MAX_MATERIAL_PER_LANDING,
  561. ) -> Optional[dict]:
  562. """Phase 1 准备:召回 + 上传图 + xcx/save + build body → 返回 pending record。
  563. **不 POST 腾讯**。POST 行为留给 Phase 3(供"先审后挂"流程审批后才挂)。
  564. 跟 try_create_one_creative_with_fallback 的差异:
  565. - 不做 POST-based fallback(因为不 POST)
  566. - 信任黑名单 + 选 top 1 material(`EXCLUDED_COVER_URL_PATTERNS` 已经截掉尺寸不符的)
  567. - 如果 Phase 3 POST 失败(腾讯尺寸 reject 等),由 Phase 3 记 error,下轮主循环重试
  568. Args:
  569. excluded_material_ids: 同广告内已挂的 material_id 集合(2026-06-09 N=3 时去重必需)。
  570. 召回后过滤掉这些,避免同广告挂重复素材被腾讯模型降权曝光。
  571. excluded_landing_ids: 本轮/近期已使用的 landing_video_id 集合。
  572. 用于同人群包跨广告、跨轮 landing 排重。
  573. landing_candidates: 本轮复用的承接视频候选池。传入后不重复拉视频/查特征/风险。
  574. failed_landing_ids: 本广告本轮已尝试失败的 landing_video_id,避免 AI 拒审/无素材后重复尝试。
  575. Returns:
  576. pending record dict(飞书表格字段 + Phase 3 POST 用的完整 body + 元数据);
  577. 所有 landing 都召回 0 素材时返回 None。
  578. """
  579. from datetime import datetime, timezone
  580. excluded_material_ids = excluded_material_ids or set()
  581. excluded_landing_ids = excluded_landing_ids or set()
  582. failed_landing_ids = failed_landing_ids if failed_landing_ids is not None else set()
  583. crowd_package = get_account_crowd_package(account_id)
  584. material_strategy = load_account_material_strategy(account_id)
  585. video_crowd_package = map_crowd_package_for_video_recall(crowd_package)
  586. landing_candidates = landing_candidates or build_landing_candidate_pool(
  587. account_id,
  588. max_landings=max_landings,
  589. )
  590. if material_strategy.use_ai_generated and not material_strategy.ai_fallback_to_history:
  591. recent_material_ids = set()
  592. logger.info(
  593. "[prepare_one_creative] account=%d adgroup=%d material_source=%s fallback_history=%s; "
  594. "AI素材不回退历史,跳过历史素材排重库",
  595. account_id, adgroup_id, material_strategy.material_source,
  596. material_strategy.ai_fallback_to_history,
  597. )
  598. else:
  599. try:
  600. recent_material_ids = load_recent_used_material_ids(crowd_package)
  601. except Exception as e:
  602. logger.warning(
  603. "[prepare_one_creative] account=%d crowd=%r 读取素材使用历史失败,仅使用本轮排重:%s",
  604. account_id, crowd_package, e,
  605. )
  606. recent_material_ids = set()
  607. effective_excluded_material_ids = merge_used_material_ids(
  608. excluded_material_ids,
  609. recent_material_ids,
  610. )
  611. logger.info(
  612. "[prepare_one_creative] account=%d adgroup=%d crowd=%r video_crowd=%r "
  613. "material_source=%s fallback_history=%s material_dedupe run=%d recent=%d effective=%d",
  614. account_id, adgroup_id, crowd_package, video_crowd_package,
  615. material_strategy.material_source, material_strategy.ai_fallback_to_history,
  616. len(excluded_material_ids), len(recent_material_ids),
  617. len(effective_excluded_material_ids),
  618. )
  619. chosen_landing = None
  620. chosen_material = None
  621. chosen_risk: Optional[VideoRiskResult] = None
  622. chosen_landing_source = ""
  623. chosen_material_source = material_strategy.material_source
  624. chosen_ai_generated_material_id = None
  625. chosen_external_recalled_material_id = None
  626. source_stats_by_label: dict[str, dict] = {}
  627. for source_label, v, element_features in landing_candidates.iter_featured_landings():
  628. source_stats = source_stats_by_label.setdefault(source_label, {
  629. "pool_candidates": 0,
  630. "landing_dedupe": 0,
  631. "failed_landing_dedupe": 0,
  632. "ai_attempts": 0,
  633. "ai_failed": 0,
  634. "ai_empty": 0,
  635. "external_attempts": 0,
  636. "external_failed": 0,
  637. "external_empty": 0,
  638. "history_recall_empty": 0,
  639. "all_excluded": 0,
  640. "selected": 0,
  641. })
  642. source_stats["pool_candidates"] += 1
  643. if v.video_id in excluded_landing_ids:
  644. source_stats["landing_dedupe"] += 1
  645. logger.info(
  646. "[prepare_one_creative] landing=%d landing 排重命中,跳过",
  647. v.video_id,
  648. )
  649. continue
  650. if v.video_id in failed_landing_ids:
  651. source_stats["failed_landing_dedupe"] += 1
  652. logger.info(
  653. "[prepare_one_creative] landing=%d 本广告本轮已失败,跳过",
  654. v.video_id,
  655. )
  656. continue
  657. risk = landing_candidates.check_risk(source_label, v)
  658. if not risk.passed:
  659. continue
  660. source_stats = source_stats_by_label[source_label]
  661. materials = []
  662. candidate_material_source = material_strategy.material_source
  663. if material_strategy.use_external_recall:
  664. source_stats["external_attempts"] += 1
  665. try:
  666. processed = prepare_external_material_for_landing(
  667. account_id=account_id,
  668. adgroup_id=adgroup_id,
  669. crowd_package=crowd_package,
  670. landing=v,
  671. element_features=element_features,
  672. excluded_material_ids=effective_excluded_material_ids,
  673. )
  674. materials = [processed] if processed is not None else []
  675. except Exception as e:
  676. source_stats["external_failed"] += 1
  677. logger.exception(
  678. "[prepare_one_creative] landing=%d 外部素材处理失败:%s",
  679. v.video_id, e,
  680. )
  681. if not materials:
  682. source_stats["external_empty"] += 1
  683. failed_landing_ids.add(v.video_id)
  684. continue
  685. elif material_strategy.use_ai_generated:
  686. source_stats["ai_attempts"] += 1
  687. try:
  688. assets = get_or_generate_assets_for_landing(
  689. account_id=account_id,
  690. adgroup_id=adgroup_id,
  691. crowd_package=crowd_package,
  692. landing=v,
  693. )
  694. materials = [asset.to_material() for asset in assets]
  695. logger.info(
  696. "[prepare_one_creative] landing=%d AI生成素材候选=%d fallback_history=%s",
  697. v.video_id, len(materials), material_strategy.ai_fallback_to_history,
  698. )
  699. except Exception as e:
  700. source_stats["ai_failed"] += 1
  701. failed_landing_ids.add(v.video_id)
  702. logger.exception(
  703. "[prepare_one_creative] landing=%d AI生成素材失败:%s",
  704. v.video_id, e,
  705. )
  706. if not material_strategy.ai_fallback_to_history:
  707. continue
  708. if (
  709. material_strategy.use_ai_generated
  710. and not materials
  711. and not material_strategy.ai_fallback_to_history
  712. ):
  713. source_stats["ai_empty"] += 1
  714. failed_landing_ids.add(v.video_id)
  715. logger.info(
  716. "[prepare_one_creative] landing=%d AI无可用素材且不允许回退历史素材,跳过",
  717. v.video_id,
  718. )
  719. continue
  720. if (not materials) and (
  721. (
  722. not material_strategy.use_ai_generated
  723. and not material_strategy.use_external_recall
  724. )
  725. or (
  726. material_strategy.use_ai_generated
  727. and material_strategy.ai_fallback_to_history
  728. )
  729. ):
  730. if material_strategy.use_ai_generated:
  731. logger.info(
  732. "[prepare_one_creative] landing=%d AI无可用素材,按账户配置回退历史素材",
  733. v.video_id,
  734. )
  735. candidate_material_source = "history_fallback"
  736. materials = recall_materials_for_video(
  737. v,
  738. final_top_n=max_materials_per_landing,
  739. element_features=element_features,
  740. )
  741. if not materials:
  742. source_stats["history_recall_empty"] += 1
  743. failed_landing_ids.add(v.video_id)
  744. # material_id 去重(2026-06-09):跳过已用素材(账户层 set,跨广告也共享)
  745. fresh = [
  746. m for m in materials
  747. if m.material_id not in effective_excluded_material_ids
  748. ]
  749. if fresh:
  750. chosen_landing = v
  751. chosen_material = fresh[0]
  752. chosen_risk = risk
  753. chosen_landing_source = source_label
  754. chosen_material_source = candidate_material_source
  755. if chosen_material.material_id.startswith("ai:"):
  756. chosen_ai_generated_material_id = chosen_material.raw.get("ai_generated_material_id")
  757. if chosen_material.material_id.startswith("external:"):
  758. chosen_external_recalled_material_id = chosen_material.raw.get(
  759. "external_recalled_material_id"
  760. )
  761. source_stats["selected"] += 1
  762. logger.info(
  763. "[prepare_one_creative] 选中 landing=%d source=%s category=%r material_source=%s material=%s recall=%s/%s/%s cost=%s roi=%s ctr=%s imp=%s score=%s policy=%s",
  764. v.video_id, source_label, v.category,
  765. chosen_material_source,
  766. chosen_material.material_id,
  767. chosen_material.recall_element_dimension,
  768. chosen_material.recall_point_type,
  769. chosen_material.recall_standard_element,
  770. chosen_material.cost,
  771. chosen_material.roi,
  772. chosen_material.ctr,
  773. chosen_material.impressions,
  774. chosen_material.score,
  775. (
  776. "ai_generated"
  777. if chosen_material.material_id.startswith("ai:")
  778. else "score>=0.8,visit_uv_window_desc,ai_cleanup"
  779. if chosen_material.material_id.startswith("external:")
  780. else "score>=0.8,cost_desc"
  781. ),
  782. )
  783. break
  784. if materials:
  785. source_stats["all_excluded"] += 1
  786. failed_landing_ids.add(v.video_id)
  787. logger.info(
  788. "[prepare_one_creative] landing=%d 召回 %d 全在 excluded,试下一条",
  789. v.video_id, len(materials),
  790. )
  791. if chosen_landing and chosen_material:
  792. logger.info(
  793. "[prepare_one_creative] source_summary account=%d adgroup=%d source=%s stats=%s",
  794. account_id, adgroup_id, chosen_landing_source,
  795. source_stats_by_label.get(chosen_landing_source, {}),
  796. )
  797. else:
  798. logger.info(
  799. "[prepare_one_creative] account=%d adgroup=%d 未产出可用创意 stats=%s",
  800. account_id, adgroup_id, source_stats_by_label,
  801. )
  802. if not chosen_landing or not chosen_material:
  803. logger.error(
  804. "[prepare_one_creative] account=%d adgroup=%d material_source=%s fallback_history=%s "
  805. "穷尽 landing 后无可用素材(excluded=%d)",
  806. account_id, adgroup_id, material_strategy.material_source,
  807. material_strategy.ai_fallback_to_history, len(effective_excluded_material_ids),
  808. )
  809. return None
  810. image_url = _pick_image_url(chosen_material)
  811. if not image_url:
  812. logger.error(
  813. "[prepare_one_creative] material=%s 既无 cover 也无 imageList,放弃",
  814. chosen_material.material_id,
  815. )
  816. failed_landing_ids.add(chosen_landing.video_id)
  817. return None
  818. is_ai_generated_material = chosen_material.material_id.startswith("ai:")
  819. is_external_recalled_material = chosen_material.material_id.startswith("external:")
  820. is_deferred_generated_material = (
  821. is_ai_generated_material or is_external_recalled_material
  822. )
  823. if is_deferred_generated_material:
  824. # AI生成图与外部素材派生图先走人工审批,Phase 3 才上传腾讯。
  825. material_image_id = ""
  826. else:
  827. # 历史素材保持原有行为:Phase 1 上传腾讯图片(MD5 幂等)。
  828. material_image_id = images_add(account_id, image_url)
  829. # 注册落地计划(xcx/save)
  830. plan = create_landing_plan(crowd_package, chosen_landing)
  831. # 读账户 brand
  832. brand = get_account_brand(account_id)
  833. # 先确定文案,再传给 build_body — 这样 record 跟 body 文案一致。
  834. desc_count = min(CREATIVE_DESCRIPTION_COUNT_PER_AD, len(CREATIVE_DESCRIPTION_POOL))
  835. description_contents = CREATIVE_DESCRIPTION_POOL[:desc_count]
  836. # 构造完整 POST body(Phase 3 直接用)
  837. body = build_creative_request_body(
  838. account_id, adgroup_id, chosen_landing, chosen_material,
  839. material_image_id=material_image_id,
  840. brand_name=brand["brand_name"],
  841. brand_image_id=brand["brand_image_id"],
  842. creative_name=plan.root_source_id,
  843. jump_path=plan.page_url,
  844. description_contents=description_contents,
  845. )
  846. # 反查广告 metadata(飞书表格 B 组用)
  847. ad_info = _fetch_ad_metadata_for_approval(account_id, adgroup_id)
  848. today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
  849. rec = {
  850. # === 飞书表格字段(im_approval_creation 用)===
  851. "approval_date": today,
  852. "account_id": account_id,
  853. "audience_tier": crowd_package,
  854. "video_crowd_package": video_crowd_package,
  855. "adgroup_id": adgroup_id,
  856. "adgroup_name": ad_info.get("adgroup_name", ""),
  857. "bid_amount_yuan": ad_info.get("bid_amount_yuan", ""),
  858. "site_set": ad_info.get("site_set", ""),
  859. "age_range": ad_info.get("age_range", ""),
  860. "landing_video_id": chosen_landing.video_id,
  861. "landing_video_url": chosen_landing.video_url,
  862. "landing_title": chosen_landing.title,
  863. "landing_source": chosen_landing_source,
  864. "landing_category": chosen_landing.category,
  865. "material_source": chosen_material_source,
  866. "material_cover_url": chosen_material.cover,
  867. # 素材质量字段(2026-06-10 batchByText 升级 — 给 Task 25 飞书表展示用)
  868. "material_ctr": chosen_material.ctr,
  869. "material_cost": chosen_material.cost,
  870. "material_roi": chosen_material.roi,
  871. "material_impressions": chosen_material.impressions,
  872. "material_visit_uv_30d": chosen_material.visit_uv_30d,
  873. "material_quality_score": chosen_material.quality_score,
  874. "material_score": chosen_material.score,
  875. "material_selection_policy": (
  876. "ai_generated_manual_review"
  877. if is_ai_generated_material
  878. else "score>=0.8,visit_uv_window_desc,ai_cleanup_manual_review"
  879. if is_external_recalled_material
  880. else "score>=0.8,cost_desc"
  881. ),
  882. "material_recall_strategy": chosen_material.recall_strategy,
  883. "material_recall_query_text": chosen_material.recall_query_text,
  884. "material_recall_config_code": chosen_material.recall_config_code,
  885. "material_recall_element_dimension": chosen_material.recall_element_dimension,
  886. "material_recall_point_type": chosen_material.recall_point_type,
  887. "material_recall_standard_element": chosen_material.recall_standard_element,
  888. "material_recall_hit_queries": chosen_material.recall_hit_queries,
  889. "material_dedupe_recent_count": len(recent_material_ids),
  890. "material_dedupe_run_count": len(excluded_material_ids),
  891. "material_dedupe_effective_count": len(effective_excluded_material_ids),
  892. "landing_dedupe_run_count": len(excluded_landing_ids),
  893. "creative_name": plan.root_source_id,
  894. # === Phase 3 POST 用 ===
  895. "_request_body": body,
  896. # === 追溯元数据(写 summary JSON)===
  897. "_material_id": chosen_material.material_id,
  898. "_material_image_id": material_image_id,
  899. "_pending_image_url": image_url if is_deferred_generated_material else "",
  900. "_ai_generated_material_id": chosen_ai_generated_material_id,
  901. "_external_recalled_material_id": chosen_external_recalled_material_id,
  902. "_external_source_material_id": (
  903. chosen_material.raw.get("source_material_id")
  904. if is_external_recalled_material else ""
  905. ),
  906. "_external_source_image_url": (
  907. chosen_material.raw.get("source_image_url")
  908. if is_external_recalled_material else ""
  909. ),
  910. "_plan_id": plan.plan_id,
  911. "_experiment_id": chosen_landing.experiment_id,
  912. "_brand_image_id": brand["brand_image_id"],
  913. # 文案选择回显(飞书表格"创意文案"列要展示)
  914. "_description_contents": description_contents,
  915. }
  916. if chosen_risk is not None:
  917. rec.update(chosen_risk.to_record_fields())
  918. if chosen_ai_generated_material_id:
  919. try:
  920. update_generated_material_status(
  921. rec,
  922. "prepared",
  923. tencent_image_id=material_image_id,
  924. )
  925. except Exception as e:
  926. logger.warning(
  927. "[prepare_one_creative] AI素材状态更新失败 id=%s:%s",
  928. chosen_ai_generated_material_id, e,
  929. )
  930. if chosen_external_recalled_material_id:
  931. try:
  932. update_external_material_status(rec, "prepared")
  933. except Exception as e:
  934. logger.warning(
  935. "[prepare_one_creative] 外部素材状态更新失败 id=%s:%s",
  936. chosen_external_recalled_material_id, e,
  937. )
  938. return rec
  939. def _fetch_ad_metadata_for_approval(account_id: int, adgroup_id: int) -> dict:
  940. """反查广告,为飞书审批表组装 B 组(广告维度)字段。"""
  941. resp = _get("/adgroups/get", {
  942. "account_id": account_id, "page": 1, "page_size": 1,
  943. "filtering": [{
  944. "field": "adgroup_id", "operator": "IN", "values": [str(adgroup_id)],
  945. }],
  946. "fields": [
  947. "adgroup_id", "adgroup_name",
  948. "bid_amount", "site_set", "targeting",
  949. ],
  950. })
  951. items = (resp.get("data") or {}).get("list") or []
  952. if not items:
  953. return {}
  954. ad = items[0]
  955. bid_fen = ad.get("bid_amount")
  956. bid_yuan = f"{int(bid_fen) / 100:.2f}" if bid_fen is not None else ""
  957. site_set_cn_map = {
  958. "SITE_SET_WECHAT": "微信公众号",
  959. "SITE_SET_WECHAT_PLUGIN": "微信插件",
  960. "SITE_SET_SEARCH_SCENE": "搜索场景",
  961. "SITE_SET_MOMENTS": "朋友圈",
  962. "SITE_SET_MINI_GAME_WECHAT": "小游戏",
  963. "SITE_SET_MINI_PROGRAM_WECHAT": "小程序",
  964. }
  965. site_raw = ad.get("site_set") or []
  966. if isinstance(site_raw, str):
  967. site_str = site_set_cn_map.get(site_raw, site_raw)
  968. else:
  969. site_str = ",".join(site_set_cn_map.get(s, s) for s in site_raw)
  970. targeting = ad.get("targeting") or {}
  971. age_list = targeting.get("age") or []
  972. if age_list:
  973. age_str = ",".join(f"{a.get('min', '?')}-{a.get('max', '?')}" for a in age_list)
  974. else:
  975. age_str = "不限"
  976. return {
  977. "adgroup_name": ad.get("adgroup_name", ""),
  978. "bid_amount_yuan": bid_yuan,
  979. "site_set": site_str,
  980. "age_range": age_str,
  981. }
  982. # Task 28:永久业务错误码(重试无意义,同一 body 永远报同样错)
  983. # 实测/文档来源:
  984. # 1801159 — 图片尺寸/格式不符
  985. # 1801143 — 创意素材审核拒绝
  986. # 1800269 — 品牌字段缺失/不合规
  987. # 1801118 — 视频 / 图片资产 ID 无效
  988. # 1901634 — 唯一性 reject(同营销内容广告组已存在相同创意)
  989. # 1901589 — 相似性 reject
  990. # 33001 — 参数校验失败
  991. _PERMANENT_ERROR_CODES = ("1801159", "1801143", "1800269", "1801118", "1901634", "1901589", "33001")
  992. def post_creative_with_prepared_body(
  993. account_id: int,
  994. body: dict,
  995. skip_if_exists: bool = True,
  996. max_retries: int = 2,
  997. ) -> Optional[int]:
  998. """Phase 3 POST:用 Phase 1 准备好的 body 调腾讯 /dynamic_creatives/add。
  999. Task 28(2026-06-11):加重试机制,区分瞬时 / 永久错误。
  1000. - 永久业务错误(图尺寸 / 品牌缺失 / 唯一性 / 33001 等)→ 直接返回 None,不重试
  1001. - 瞬时错误(网络超时 / 5xx / QPS limit)→ 最多重试 max_retries 次,指数退避
  1002. Args:
  1003. account_id: 腾讯账户 ID(用于幂等检查)
  1004. body: Phase 1 prepare_one_creative_for_ad 返回的 _request_body
  1005. skip_if_exists: True(默认)POST 前做幂等检查,命中返回已有 cid
  1006. max_retries: 瞬时错误的最大重试次数(默认 2;首次 + 2 次重试 = 最坏 3 次总尝试)
  1007. Returns:
  1008. 成功 dynamic_creative_id;失败 None(记 error log)
  1009. """
  1010. import time
  1011. adgroup_id = body.get("adgroup_id")
  1012. image_comp = body.get("creative_components", {}).get("image") or []
  1013. material_image_id = ""
  1014. if image_comp:
  1015. material_image_id = (image_comp[0].get("value") or {}).get("image_id", "")
  1016. if skip_if_exists and material_image_id and adgroup_id:
  1017. existing_cid = find_existing_creative_by_image(
  1018. account_id, int(adgroup_id), str(material_image_id),
  1019. )
  1020. if existing_cid:
  1021. return existing_cid
  1022. for attempt in range(max_retries + 1): # 首次 + 重试
  1023. try:
  1024. logger.info(
  1025. "[post_creative] account=%d adgroup=%s name=%s image_id=%s attempt=%d/%d",
  1026. account_id, adgroup_id,
  1027. body.get("dynamic_creative_name", ""), material_image_id,
  1028. attempt + 1, max_retries + 1,
  1029. )
  1030. resp = _post("/dynamic_creatives/add", body)
  1031. data = _check(resp, "creative_create")
  1032. cid = data.get("dynamic_creative_id")
  1033. if cid:
  1034. logger.info("[post_creative] 成功 cid=%s", cid)
  1035. return cid
  1036. logger.error("[post_creative] 返回 data 缺 dynamic_creative_id: %s", data)
  1037. return None
  1038. except RuntimeError as e:
  1039. err = str(e)
  1040. # 永久错误 → 不重试,直接放弃(节省 quota,避免无意义打)
  1041. is_permanent = any(code in err for code in _PERMANENT_ERROR_CODES)
  1042. if is_permanent:
  1043. logger.error(
  1044. "[post_creative] 永久错误,不重试 account=%d adgroup=%s: %s",
  1045. account_id, adgroup_id, err[:200],
  1046. )
  1047. return None
  1048. # 瞬时错误:重试 quota 没用完 → backoff 后重试
  1049. if attempt < max_retries:
  1050. backoff_s = 5 * (2 ** attempt) # 5s, 10s
  1051. logger.warning(
  1052. "[post_creative] 瞬时错误 attempt=%d/%d,sleep %ds 后重试 account=%d adgroup=%s: %s",
  1053. attempt + 1, max_retries + 1, backoff_s,
  1054. account_id, adgroup_id, err[:150],
  1055. )
  1056. time.sleep(backoff_s)
  1057. continue
  1058. # 重试用完 → 放弃
  1059. logger.error(
  1060. "[post_creative] 重试 %d 次后仍失败 account=%d adgroup=%s: %s",
  1061. max_retries, account_id, adgroup_id, err[:200],
  1062. )
  1063. return None
  1064. return None
  1065. def try_create_one_creative_with_fallback(
  1066. account_id: int,
  1067. adgroup_id: int,
  1068. max_landings: int = MAX_LANDING_ATTEMPTS_PER_AD,
  1069. max_materials_per_landing: int = MAX_MATERIAL_PER_LANDING,
  1070. ) -> Optional[int]:
  1071. """对一条广告挂 1 条创意,带 try-fallback 鲁棒性(P0-A 核心 helper,2026-06-09)。
  1072. 召回的素材不一定都能挂(实测 code=1801159 尺寸不符,1530003 等),
  1073. 所以遍历 landing × material 尝试 POST,失败就试下一条,直到成功或穷尽。
  1074. Args:
  1075. account_id: 腾讯广告主账号 ID
  1076. adgroup_id: 目标广告 ID
  1077. max_landings: 最多尝试的 landing 数
  1078. max_materials_per_landing: 每条 landing 召回 top N 素材尝试
  1079. Returns:
  1080. 成功:dynamic_creative_id;穷尽:None(记 error log,主循环继续下一广告)
  1081. """
  1082. videos = fetch_landing_videos_for_account(account_id, page_size=max_landings * 2)
  1083. valid = [v for v in videos if _is_landing_candidate(v)][:max_landings]
  1084. logger.info(
  1085. "[try_create_one_creative] account=%d adgroup=%d 候选 landing=%d",
  1086. account_id, adgroup_id, len(valid),
  1087. )
  1088. attempts = []
  1089. for v in valid:
  1090. materials = recall_materials_for_video(v, final_top_n=max_materials_per_landing)
  1091. if not materials:
  1092. attempts.append(f" · landing={v.video_id} 召回 0 素材,跳过")
  1093. continue
  1094. for m in materials:
  1095. try:
  1096. cid = create_creative_for_ad(account_id, adgroup_id, v, m)
  1097. attempts.append(
  1098. f" · landing={v.video_id} material={m.material_id[:12]} → 成功 cid={cid}"
  1099. )
  1100. logger.info("[try_create_one_creative] 成功 cid=%s\n%s", cid, "\n".join(attempts))
  1101. return cid
  1102. except RuntimeError as e:
  1103. err = str(e)[:100]
  1104. attempts.append(f" · landing={v.video_id} material={m.material_id[:12]} → 失败 {err}")
  1105. continue
  1106. logger.error(
  1107. "[try_create_one_creative] account=%d adgroup=%d 穷尽所有 landing×material 仍失败:\n%s",
  1108. account_id, adgroup_id, "\n".join(attempts),
  1109. )
  1110. return None