creative_material_usage.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. """Creative material usage reservation for duplicate control.
  2. Usage is written when a pending creative is prepared, before Tencent POST.
  3. Review/task tables remain responsible for submitted Tencent creatives.
  4. """
  5. from __future__ import annotations
  6. import json
  7. import logging
  8. import os
  9. from typing import Iterable
  10. logger = logging.getLogger(__name__)
  11. CREATIVE_MATERIAL_DEDUPE_LOOKBACK_DAYS = int(
  12. os.getenv("CREATIVE_MATERIAL_DEDUPE_LOOKBACK_DAYS", "7")
  13. )
  14. CREATIVE_LANDING_DEDUPE_LOOKBACK_DAYS = int(
  15. os.getenv("CREATIVE_LANDING_DEDUPE_LOOKBACK_DAYS", "7")
  16. )
  17. CREATION_RECOVERY_LOOKBACK_HOURS = int(
  18. os.getenv("CREATION_RECOVERY_LOOKBACK_HOURS", "24")
  19. )
  20. CREATE_USAGE_TABLE_SQL = """
  21. CREATE TABLE IF NOT EXISTS creative_material_usage (
  22. id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '自增主键',
  23. account_id BIGINT NOT NULL COMMENT '腾讯广告账户ID',
  24. adgroup_id BIGINT DEFAULT NULL COMMENT '广告ID',
  25. crowd_package VARCHAR(200) NOT NULL COMMENT '投放人群包名称',
  26. landing_video_id BIGINT DEFAULT NULL COMMENT '承接视频ID,用于同人群包近期排重',
  27. material_id VARCHAR(100) NOT NULL COMMENT '内部素材ID',
  28. material_image_id VARCHAR(100) DEFAULT NULL COMMENT '腾讯图片ID',
  29. dynamic_creative_id BIGINT DEFAULT NULL COMMENT '腾讯动态创意ID',
  30. status VARCHAR(50) NOT NULL DEFAULT 'prepared' COMMENT 'prepared/submitted/failed',
  31. source VARCHAR(50) DEFAULT NULL COMMENT 'primary/hot',
  32. raw_record MEDIUMTEXT DEFAULT NULL COMMENT '准备记录JSON',
  33. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  34. updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  35. KEY idx_crowd_material_created (crowd_package, material_id, created_at),
  36. KEY idx_crowd_landing_created (crowd_package, landing_video_id, created_at),
  37. KEY idx_crowd_account_ad_material (crowd_package, account_id, adgroup_id, material_id),
  38. KEY idx_account_created (account_id, created_at),
  39. KEY idx_status_created (status, created_at)
  40. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='创意素材使用历史/占位'
  41. """
  42. def ensure_usage_table() -> None:
  43. from db.connection import get_connection
  44. conn = get_connection()
  45. try:
  46. with conn.cursor() as cur:
  47. cur.execute(CREATE_USAGE_TABLE_SQL)
  48. cur.execute("SHOW INDEX FROM creative_material_usage WHERE Key_name = 'idx_crowd_landing_created'")
  49. if not cur.fetchall():
  50. cur.execute(
  51. """
  52. ALTER TABLE creative_material_usage
  53. ADD INDEX idx_crowd_landing_created (crowd_package, landing_video_id, created_at)
  54. """
  55. )
  56. conn.commit()
  57. finally:
  58. conn.close()
  59. def load_recent_used_material_ids(
  60. crowd_package: str,
  61. lookback_days: int = CREATIVE_MATERIAL_DEDUPE_LOOKBACK_DAYS,
  62. ) -> set[str]:
  63. """Load recent material reservations for the same crowd package."""
  64. if not crowd_package:
  65. return set()
  66. ensure_usage_table()
  67. from db.connection import get_connection
  68. conn = get_connection()
  69. try:
  70. with conn.cursor() as cur:
  71. cur.execute(
  72. """
  73. SELECT DISTINCT material_id
  74. FROM (
  75. SELECT material_id
  76. FROM creative_material_usage
  77. WHERE crowd_package=%s
  78. AND material_id IS NOT NULL
  79. AND material_id <> ''
  80. AND status IN ('posted_ok', 'rejected')
  81. AND created_at >= DATE_SUB(NOW(), INTERVAL %s DAY)
  82. UNION
  83. SELECT material_id
  84. FROM creative_creation_task
  85. WHERE material_id IS NOT NULL
  86. AND material_id <> ''
  87. AND review_status IN ('approved', 'rejected')
  88. AND submitted_at >= DATE_SUB(NOW(), INTERVAL %s DAY)
  89. AND JSON_UNQUOTE(JSON_EXTRACT(raw_record, '$.audience_tier'))=%s
  90. ) t
  91. """,
  92. (crowd_package, int(lookback_days), int(lookback_days), crowd_package),
  93. )
  94. rows = cur.fetchall() or []
  95. finally:
  96. conn.close()
  97. return {str(row["material_id"]) for row in rows if row.get("material_id")}
  98. def load_recent_used_landing_video_ids(
  99. crowd_package: str,
  100. lookback_days: int = CREATIVE_LANDING_DEDUPE_LOOKBACK_DAYS,
  101. ) -> set[int]:
  102. """Load recent landing-video reservations for the same crowd package."""
  103. if not crowd_package:
  104. return set()
  105. ensure_usage_table()
  106. from db.connection import get_connection
  107. conn = get_connection()
  108. try:
  109. with conn.cursor() as cur:
  110. cur.execute(
  111. """
  112. SELECT DISTINCT landing_video_id
  113. FROM (
  114. SELECT landing_video_id
  115. FROM creative_material_usage
  116. WHERE crowd_package=%s
  117. AND landing_video_id IS NOT NULL
  118. AND landing_video_id > 0
  119. AND status IN ('posted_ok', 'submitted')
  120. AND created_at >= DATE_SUB(NOW(), INTERVAL %s DAY)
  121. UNION
  122. SELECT landing_video_id
  123. FROM creative_creation_task
  124. WHERE landing_video_id IS NOT NULL
  125. AND landing_video_id > 0
  126. AND submitted_at >= DATE_SUB(NOW(), INTERVAL %s DAY)
  127. AND JSON_UNQUOTE(JSON_EXTRACT(raw_record, '$.audience_tier'))=%s
  128. ) t
  129. """,
  130. (crowd_package, int(lookback_days), int(lookback_days), crowd_package),
  131. )
  132. rows = cur.fetchall() or []
  133. finally:
  134. conn.close()
  135. out: set[int] = set()
  136. for row in rows:
  137. try:
  138. out.add(int(row["landing_video_id"]))
  139. except (TypeError, ValueError):
  140. continue
  141. return out
  142. def _material_source_from_record(material_id: object, raw_record: object) -> str:
  143. material_id_text = str(material_id or "").strip()
  144. if material_id_text.startswith("external:"):
  145. return "external_recall"
  146. if material_id_text.startswith("ai:"):
  147. return "ai_generated"
  148. if raw_record:
  149. try:
  150. data = json.loads(str(raw_record))
  151. source = str(data.get("material_source") or "").strip()
  152. raw_material_id = str(data.get("_material_id") or "").strip()
  153. if source == "external_recall" or raw_material_id.startswith("external:"):
  154. return "external_recall"
  155. if source == "ai_generated" or raw_material_id.startswith("ai:"):
  156. return "ai_generated"
  157. except Exception:
  158. pass
  159. return "history"
  160. def load_recent_landing_usage_counts(
  161. crowd_package: str,
  162. lookback_days: int = CREATIVE_LANDING_DEDUPE_LOOKBACK_DAYS,
  163. ) -> dict[str, dict[int, int]]:
  164. """Load recent landing-video usage counts split by material source.
  165. The `source` column in creative_material_usage means primary/hot video source,
  166. so material source must be derived from material_id/raw_record.
  167. """
  168. counts: dict[str, dict[int, int]] = {
  169. "history": {},
  170. "ai_generated": {},
  171. "external_recall": {},
  172. }
  173. if not crowd_package:
  174. return counts
  175. ensure_usage_table()
  176. from db.connection import get_connection
  177. conn = get_connection()
  178. try:
  179. with conn.cursor() as cur:
  180. cur.execute(
  181. """
  182. SELECT account_id, adgroup_id, landing_video_id, material_id, raw_record
  183. FROM creative_material_usage
  184. WHERE crowd_package=%s
  185. AND landing_video_id IS NOT NULL
  186. AND landing_video_id > 0
  187. AND status IN ('posted_ok', 'submitted')
  188. AND created_at >= DATE_SUB(NOW(), INTERVAL %s DAY)
  189. """,
  190. (crowd_package, int(lookback_days)),
  191. )
  192. usage_rows = cur.fetchall() or []
  193. cur.execute(
  194. """
  195. SELECT account_id, adgroup_id, landing_video_id, material_id, raw_record
  196. FROM creative_creation_task
  197. WHERE landing_video_id IS NOT NULL
  198. AND landing_video_id > 0
  199. AND submitted_at >= DATE_SUB(NOW(), INTERVAL %s DAY)
  200. AND JSON_UNQUOTE(JSON_EXTRACT(raw_record, '$.audience_tier'))=%s
  201. """,
  202. (int(lookback_days), crowd_package),
  203. )
  204. task_rows = cur.fetchall() or []
  205. finally:
  206. conn.close()
  207. seen: set[tuple[str, int, int, int, str]] = set()
  208. for row in list(usage_rows) + list(task_rows):
  209. try:
  210. landing_video_id = int(row["landing_video_id"])
  211. account_id = int(row.get("account_id") or 0)
  212. adgroup_id = int(row.get("adgroup_id") or 0)
  213. except (TypeError, ValueError):
  214. continue
  215. material_id = str(row.get("material_id") or "")
  216. source = _material_source_from_record(material_id, row.get("raw_record"))
  217. key = (source, account_id, adgroup_id, landing_video_id, material_id)
  218. if key in seen:
  219. continue
  220. seen.add(key)
  221. counts.setdefault(source, {})
  222. counts[source][landing_video_id] = counts[source].get(landing_video_id, 0) + 1
  223. return counts
  224. def load_recoverable_prepared_records(
  225. *,
  226. account_id: int,
  227. adgroup_id: int,
  228. crowd_package: str,
  229. material_source: str,
  230. limit: int,
  231. lookback_hours: int = CREATION_RECOVERY_LOOKBACK_HOURS,
  232. ) -> list[dict]:
  233. """Load unsubmitted prepared records after an interrupted Phase 1 run."""
  234. if limit <= 0 or not crowd_package:
  235. return []
  236. ensure_usage_table()
  237. from db.connection import get_connection
  238. conn = get_connection()
  239. try:
  240. with conn.cursor() as cur:
  241. cur.execute(
  242. """
  243. SELECT raw_record
  244. FROM creative_material_usage
  245. WHERE account_id=%s
  246. AND adgroup_id <=> %s
  247. AND crowd_package=%s
  248. AND status='prepared'
  249. AND dynamic_creative_id IS NULL
  250. AND raw_record IS NOT NULL
  251. AND raw_record <> ''
  252. AND created_at >= DATE_SUB(NOW(), INTERVAL %s HOUR)
  253. ORDER BY id ASC
  254. LIMIT %s
  255. """,
  256. (
  257. int(account_id),
  258. int(adgroup_id) if adgroup_id else None,
  259. crowd_package,
  260. int(lookback_hours),
  261. max(int(limit) * 3, int(limit)),
  262. ),
  263. )
  264. rows = cur.fetchall() or []
  265. finally:
  266. conn.close()
  267. out: list[dict] = []
  268. seen_materials: set[str] = set()
  269. for row in rows:
  270. try:
  271. record = json.loads(str(row.get("raw_record") or ""))
  272. except Exception:
  273. continue
  274. material_id = str(record.get("_material_id") or "").strip()
  275. if not material_id or material_id in seen_materials:
  276. continue
  277. if _material_source_from_record(material_id, row.get("raw_record")) != material_source:
  278. continue
  279. if not record.get("_request_body"):
  280. continue
  281. seen_materials.add(material_id)
  282. out.append(record)
  283. if len(out) >= limit:
  284. break
  285. return out
  286. def record_prepared_material_usage(record: dict, status: str = "prepared") -> None:
  287. """Reserve a material once Phase 1 has produced a pending creative."""
  288. material_id = str(record.get("_material_id") or "").strip()
  289. crowd_package = str(record.get("audience_tier") or "").strip()
  290. if not material_id or not crowd_package:
  291. return
  292. ensure_usage_table()
  293. from db.connection import get_connection
  294. raw_record = json.dumps(record, ensure_ascii=False, default=str)
  295. conn = get_connection()
  296. try:
  297. with conn.cursor() as cur:
  298. cur.execute(
  299. """
  300. INSERT INTO creative_material_usage
  301. (account_id, adgroup_id, crowd_package, landing_video_id,
  302. material_id, material_image_id, dynamic_creative_id,
  303. status, source, raw_record)
  304. VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
  305. """,
  306. (
  307. int(record["account_id"]),
  308. int(record.get("adgroup_id") or 0) or None,
  309. crowd_package,
  310. record.get("landing_video_id"),
  311. material_id,
  312. str(record.get("_material_image_id") or ""),
  313. record.get("dynamic_creative_id"),
  314. status,
  315. record.get("landing_source"),
  316. raw_record,
  317. ),
  318. )
  319. conn.commit()
  320. finally:
  321. conn.close()
  322. def update_material_usage_status(
  323. record: dict,
  324. status: str,
  325. dynamic_creative_id: int | str | None = None,
  326. error: str = "",
  327. ) -> None:
  328. """Update the latest usage reservation for this crowd_package + material_id."""
  329. material_id = str(record.get("_material_id") or "").strip()
  330. crowd_package = str(record.get("audience_tier") or "").strip()
  331. if not material_id or not crowd_package:
  332. return
  333. ensure_usage_table()
  334. from db.connection import get_connection
  335. normalized_status = {
  336. "reject": "rejected",
  337. "approve": "approved",
  338. "hold": "no_result",
  339. "skip": "no_result",
  340. }.get(status, status)
  341. raw_record = json.dumps(record, ensure_ascii=False, default=str)
  342. conn = get_connection()
  343. try:
  344. with conn.cursor() as cur:
  345. cur.execute(
  346. """
  347. UPDATE creative_material_usage
  348. SET status=%s,
  349. dynamic_creative_id=COALESCE(%s, dynamic_creative_id),
  350. raw_record=%s,
  351. updated_at=CURRENT_TIMESTAMP
  352. WHERE crowd_package=%s
  353. AND material_id=%s
  354. AND account_id=%s
  355. AND adgroup_id <=> %s
  356. ORDER BY id DESC
  357. LIMIT 1
  358. """,
  359. (
  360. normalized_status,
  361. int(dynamic_creative_id) if dynamic_creative_id else None,
  362. raw_record if not error else json.dumps(
  363. {**record, "usage_error": error[:2000]},
  364. ensure_ascii=False,
  365. default=str,
  366. ),
  367. crowd_package,
  368. material_id,
  369. int(record["account_id"]),
  370. int(record.get("adgroup_id") or 0) or None,
  371. ),
  372. )
  373. conn.commit()
  374. finally:
  375. conn.close()
  376. def merge_used_material_ids(*sets: Iterable[str]) -> set[str]:
  377. out: set[str] = set()
  378. for values in sets:
  379. out.update(str(v) for v in values if str(v))
  380. return out