creative_material_usage.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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("ai:"):
  145. return "ai_generated"
  146. if raw_record:
  147. try:
  148. data = json.loads(str(raw_record))
  149. source = str(data.get("material_source") or "").strip()
  150. raw_material_id = str(data.get("_material_id") or "").strip()
  151. if source == "ai_generated" or raw_material_id.startswith("ai:"):
  152. return "ai_generated"
  153. except Exception:
  154. pass
  155. return "history"
  156. def load_recent_landing_usage_counts(
  157. crowd_package: str,
  158. lookback_days: int = CREATIVE_LANDING_DEDUPE_LOOKBACK_DAYS,
  159. ) -> dict[str, dict[int, int]]:
  160. """Load recent landing-video usage counts split by material source.
  161. The `source` column in creative_material_usage means primary/hot video source,
  162. so material source must be derived from material_id/raw_record.
  163. """
  164. counts: dict[str, dict[int, int]] = {
  165. "history": {},
  166. "ai_generated": {},
  167. }
  168. if not crowd_package:
  169. return counts
  170. ensure_usage_table()
  171. from db.connection import get_connection
  172. conn = get_connection()
  173. try:
  174. with conn.cursor() as cur:
  175. cur.execute(
  176. """
  177. SELECT account_id, adgroup_id, landing_video_id, material_id, raw_record
  178. FROM creative_material_usage
  179. WHERE crowd_package=%s
  180. AND landing_video_id IS NOT NULL
  181. AND landing_video_id > 0
  182. AND status IN ('posted_ok', 'submitted')
  183. AND created_at >= DATE_SUB(NOW(), INTERVAL %s DAY)
  184. """,
  185. (crowd_package, int(lookback_days)),
  186. )
  187. usage_rows = cur.fetchall() or []
  188. cur.execute(
  189. """
  190. SELECT account_id, adgroup_id, landing_video_id, material_id, raw_record
  191. FROM creative_creation_task
  192. WHERE landing_video_id IS NOT NULL
  193. AND landing_video_id > 0
  194. AND submitted_at >= DATE_SUB(NOW(), INTERVAL %s DAY)
  195. AND JSON_UNQUOTE(JSON_EXTRACT(raw_record, '$.audience_tier'))=%s
  196. """,
  197. (int(lookback_days), crowd_package),
  198. )
  199. task_rows = cur.fetchall() or []
  200. finally:
  201. conn.close()
  202. seen: set[tuple[str, int, int, int, str]] = set()
  203. for row in list(usage_rows) + list(task_rows):
  204. try:
  205. landing_video_id = int(row["landing_video_id"])
  206. account_id = int(row.get("account_id") or 0)
  207. adgroup_id = int(row.get("adgroup_id") or 0)
  208. except (TypeError, ValueError):
  209. continue
  210. material_id = str(row.get("material_id") or "")
  211. source = _material_source_from_record(material_id, row.get("raw_record"))
  212. key = (source, account_id, adgroup_id, landing_video_id, material_id)
  213. if key in seen:
  214. continue
  215. seen.add(key)
  216. counts.setdefault(source, {})
  217. counts[source][landing_video_id] = counts[source].get(landing_video_id, 0) + 1
  218. return counts
  219. def load_recoverable_prepared_records(
  220. *,
  221. account_id: int,
  222. adgroup_id: int,
  223. crowd_package: str,
  224. material_source: str,
  225. limit: int,
  226. lookback_hours: int = CREATION_RECOVERY_LOOKBACK_HOURS,
  227. ) -> list[dict]:
  228. """Load unsubmitted prepared records after an interrupted Phase 1 run."""
  229. if limit <= 0 or not crowd_package:
  230. return []
  231. ensure_usage_table()
  232. from db.connection import get_connection
  233. conn = get_connection()
  234. try:
  235. with conn.cursor() as cur:
  236. cur.execute(
  237. """
  238. SELECT raw_record
  239. FROM creative_material_usage
  240. WHERE account_id=%s
  241. AND adgroup_id <=> %s
  242. AND crowd_package=%s
  243. AND status='prepared'
  244. AND dynamic_creative_id IS NULL
  245. AND raw_record IS NOT NULL
  246. AND raw_record <> ''
  247. AND created_at >= DATE_SUB(NOW(), INTERVAL %s HOUR)
  248. ORDER BY id ASC
  249. LIMIT %s
  250. """,
  251. (
  252. int(account_id),
  253. int(adgroup_id) if adgroup_id else None,
  254. crowd_package,
  255. int(lookback_hours),
  256. max(int(limit) * 3, int(limit)),
  257. ),
  258. )
  259. rows = cur.fetchall() or []
  260. finally:
  261. conn.close()
  262. out: list[dict] = []
  263. seen_materials: set[str] = set()
  264. for row in rows:
  265. try:
  266. record = json.loads(str(row.get("raw_record") or ""))
  267. except Exception:
  268. continue
  269. material_id = str(record.get("_material_id") or "").strip()
  270. if not material_id or material_id in seen_materials:
  271. continue
  272. if _material_source_from_record(material_id, row.get("raw_record")) != material_source:
  273. continue
  274. if not record.get("_request_body"):
  275. continue
  276. seen_materials.add(material_id)
  277. out.append(record)
  278. if len(out) >= limit:
  279. break
  280. return out
  281. def record_prepared_material_usage(record: dict, status: str = "prepared") -> None:
  282. """Reserve a material once Phase 1 has produced a pending creative."""
  283. material_id = str(record.get("_material_id") or "").strip()
  284. crowd_package = str(record.get("audience_tier") or "").strip()
  285. if not material_id or not crowd_package:
  286. return
  287. ensure_usage_table()
  288. from db.connection import get_connection
  289. raw_record = json.dumps(record, ensure_ascii=False, default=str)
  290. conn = get_connection()
  291. try:
  292. with conn.cursor() as cur:
  293. cur.execute(
  294. """
  295. INSERT INTO creative_material_usage
  296. (account_id, adgroup_id, crowd_package, landing_video_id,
  297. material_id, material_image_id, dynamic_creative_id,
  298. status, source, raw_record)
  299. VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
  300. """,
  301. (
  302. int(record["account_id"]),
  303. int(record.get("adgroup_id") or 0) or None,
  304. crowd_package,
  305. record.get("landing_video_id"),
  306. material_id,
  307. str(record.get("_material_image_id") or ""),
  308. record.get("dynamic_creative_id"),
  309. status,
  310. record.get("landing_source"),
  311. raw_record,
  312. ),
  313. )
  314. conn.commit()
  315. finally:
  316. conn.close()
  317. def update_material_usage_status(
  318. record: dict,
  319. status: str,
  320. dynamic_creative_id: int | str | None = None,
  321. error: str = "",
  322. ) -> None:
  323. """Update the latest usage reservation for this crowd_package + material_id."""
  324. material_id = str(record.get("_material_id") or "").strip()
  325. crowd_package = str(record.get("audience_tier") or "").strip()
  326. if not material_id or not crowd_package:
  327. return
  328. ensure_usage_table()
  329. from db.connection import get_connection
  330. normalized_status = {
  331. "reject": "rejected",
  332. "approve": "approved",
  333. "hold": "no_result",
  334. "skip": "no_result",
  335. }.get(status, status)
  336. raw_record = json.dumps(record, ensure_ascii=False, default=str)
  337. conn = get_connection()
  338. try:
  339. with conn.cursor() as cur:
  340. cur.execute(
  341. """
  342. UPDATE creative_material_usage
  343. SET status=%s,
  344. dynamic_creative_id=COALESCE(%s, dynamic_creative_id),
  345. raw_record=%s,
  346. updated_at=CURRENT_TIMESTAMP
  347. WHERE crowd_package=%s
  348. AND material_id=%s
  349. AND account_id=%s
  350. AND adgroup_id <=> %s
  351. ORDER BY id DESC
  352. LIMIT 1
  353. """,
  354. (
  355. normalized_status,
  356. int(dynamic_creative_id) if dynamic_creative_id else None,
  357. raw_record if not error else json.dumps(
  358. {**record, "usage_error": error[:2000]},
  359. ensure_ascii=False,
  360. default=str,
  361. ),
  362. crowd_package,
  363. material_id,
  364. int(record["account_id"]),
  365. int(record.get("adgroup_id") or 0) or None,
  366. ),
  367. )
  368. conn.commit()
  369. finally:
  370. conn.close()
  371. def merge_used_material_ids(*sets: Iterable[str]) -> set[str]:
  372. out: set[str] = set()
  373. for values in sets:
  374. out.update(str(v) for v in values if str(v))
  375. return out