creative_creation.py 47 KB

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