creative_creation.py 50 KB

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