creative_creation.py 43 KB

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