material_recall.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. """创意素材召回接口适配层(vector 服务)。
  2. 业务模型(用户 2026-06-08 确认):
  3. 对一个承接视频(LandingVideo)执行 3 种策略召回素材,合并去重,按 score 取 top N。
  4. 接口:POST https://api-internal.piaoquantv.com/videoVector/recallTest/matchByText
  5. 鉴权:不需要(内部 API)
  6. 本质(用户 2026-06-08 确认):**多路召回 → 排序 → 去重**
  7. 实测确认素材库的 4 个有效 configCode(VIDEO_TITLE 和 ALL 对 MATERIAL 模态返回 0):
  8. - VIDEO_TOPIC (选题向量)
  9. - VIDEO_KEYPOINT (关键点向量)
  10. - VIDEO_INSPIRATION(灵感点向量)
  11. - VIDEO_PURPOSE (目的点向量)
  12. 策略:对一个承接视频,选合适的 queryText,**串行调 4 个 configCode**,合并按 materialId 去重(取 max score),按 score 降序返回 top N。
  13. queryText 选择优先级(选第一个非空且非占位符 "-"):
  14. 1. standard_element(标准化元素,实测效果最好)
  15. 2. demand_content_topic(选题,如果非 "-")
  16. 3. title(承接视频标题,兜底)
  17. """
  18. import logging
  19. import os
  20. from concurrent.futures import ThreadPoolExecutor, as_completed
  21. from dataclasses import dataclass, field
  22. from typing import Iterable, List, Optional
  23. import httpx
  24. from tools.video_recall import LandingVideo
  25. logger = logging.getLogger(__name__)
  26. VECTOR_BASE = os.getenv(
  27. "VECTOR_BASE_URL",
  28. "https://api-internal.piaoquantv.com/videoVector",
  29. )
  30. VECTOR_MATCH_BY_TEXT = f"{VECTOR_BASE}/recallTest/matchByText"
  31. VECTOR_BATCH_BY_TEXT = f"{VECTOR_BASE}/recallTest/batchByText"
  32. VECTOR_ALL_CONFIG_CODES = f"{VECTOR_BASE}/videoSearch/getAllConfigCodes"
  33. def fetch_all_config_codes() -> dict[str, str]:
  34. """动态获取 vector 服务支持的全部 configCode → 中文名。
  35. 返回 {configCode: 中文名}。
  36. 召回前先调一次,避免硬编码列表过时。
  37. """
  38. resp = httpx.get(VECTOR_ALL_CONFIG_CODES, timeout=15)
  39. resp.raise_for_status()
  40. data = resp.json()
  41. if data.get("code") not in (0, 200):
  42. raise RuntimeError(
  43. f"getAllConfigCodes 失败:code={data.get('code')} msg={data.get('msg')}"
  44. )
  45. return data.get("data") or {}
  46. # 字段维度策略(2026-06-08 用户最终确认)
  47. # - 维度 1 选题: queryText=demand_content_topic, configCode=VIDEO_TOPIC
  48. # - 维度 2 标准化元素: queryText=standard_element, configCode 按 point_type **唯一对应**:
  49. # - "灵感点" → INSPIRATION_SUBSTANCE
  50. # - "关键点" → KEYPOINT_SUBSTANCE
  51. # - "目的点" → PURPOSE_SUBSTANCE
  52. # - 其他/空 → 跳过(没办法确定走哪一路,no-guessing)
  53. # - 维度 3 标题: 不做(VIDEO_TITLE 对 MATERIAL 实测返回 0)
  54. POINT_TYPE_TO_SUBSTANCE = {
  55. "灵感点": "INSPIRATION_SUBSTANCE",
  56. "关键点": "KEYPOINT_SUBSTANCE",
  57. "目的点": "PURPOSE_SUBSTANCE",
  58. }
  59. POINT_TYPE_TO_VIDEO_CONFIG = {
  60. "灵感点": "VIDEO_INSPIRATION",
  61. "关键点": "VIDEO_KEYPOINT",
  62. "目的点": "VIDEO_PURPOSE",
  63. }
  64. SUBSTANCE_TO_VIDEO_CONFIG = {
  65. "INSPIRATION_SUBSTANCE": "VIDEO_INSPIRATION",
  66. "KEYPOINT_SUBSTANCE": "VIDEO_KEYPOINT",
  67. "PURPOSE_SUBSTANCE": "VIDEO_PURPOSE",
  68. }
  69. ODPS_FEATURE_TO_CONFIG = {
  70. ("解构选题", ""): "VIDEO_TOPIC",
  71. ("实质", "灵感点"): "INSPIRATION_SUBSTANCE",
  72. ("实质", "关键点"): "KEYPOINT_SUBSTANCE",
  73. ("实质", "目的点"): "PURPOSE_SUBSTANCE",
  74. }
  75. # fallback(动态接口失败时用)
  76. MATERIAL_EFFECTIVE_CONFIG_CODES = ["VIDEO_TOPIC"] + list(POINT_TYPE_TO_SUBSTANCE.values())
  77. # 占位符值视为无效(piaoquantv 数据里 demandContentTopic 大量为 "-")
  78. PLACEHOLDER_VALUES = {"", "-", None}
  79. # 单 configCode 召回 top N(合并前)
  80. DEFAULT_PER_CC_TOP_N = 100
  81. # 最终合并去重后返回 top N
  82. DEFAULT_FINAL_TOP_N = 20
  83. # Cover URL 黑名单 — 已知尺寸/比例不符合腾讯创意要求的来源
  84. # (2026-06-09 用户决策:踩坑驱动渐进收紧,踩到新模式再加)
  85. # - "auto_reply_cards_cover" :自动回复卡片业务的 cover,实测 reject code 1801159
  86. EXCLUDED_COVER_URL_PATTERNS = (
  87. "auto_reply_cards_cover",
  88. )
  89. @dataclass
  90. class RecallQuery:
  91. """One ODPS-derived material recall query."""
  92. query_text: str
  93. config_code: str
  94. element_dimension: str
  95. point_type: str
  96. standard_element: str
  97. contribution_score: float = 0.0
  98. dt: str = ""
  99. @property
  100. def strategy_name(self) -> str:
  101. if self.element_dimension == "解构选题":
  102. return "解构选题"
  103. return f"{self.element_dimension}-{self.point_type}"
  104. def to_hit(self) -> dict:
  105. return {
  106. "strategy": self.strategy_name,
  107. "element_dimension": self.element_dimension,
  108. "point_type": self.point_type,
  109. "standard_element": self.standard_element,
  110. "query_text": self.query_text,
  111. "config_code": self.config_code,
  112. "contribution_score": self.contribution_score,
  113. "dt": self.dt,
  114. }
  115. @dataclass
  116. class Material:
  117. """召回的创意素材。
  118. 2026-06-10 升级:从 batchByText 接口接收质量数据(cost/ctr/cvr/roi/impressions 等)。
  119. """
  120. material_id: str # 素材原始 ID
  121. score: float # 服务端综合分(wCtr=1 配置下 ≈ qualityScore,与 CTR 强相关)
  122. title: str = ""
  123. cover: str = ""
  124. video_url: str = ""
  125. # 投放质量数据(来自 materialDetail.quality)— 2026-06-10 升级新增
  126. cost: Optional[float] = None # 累计成本(元)
  127. ctr: Optional[float] = None # 点击率
  128. cvr: Optional[float] = None # 转化率
  129. roi: Optional[float] = None # ROI(收入/成本)
  130. impressions: Optional[int] = None # 累计曝光
  131. quality_score: Optional[float] = None # 服务端 qualityScore
  132. visit_uv_30d: Optional[int] = None # 外部素材配置窗口内访问UV之和(列名兼容历史)
  133. recall_strategy: str = ""
  134. recall_query_text: str = ""
  135. recall_config_code: str = ""
  136. recall_element_dimension: str = ""
  137. recall_point_type: str = ""
  138. recall_standard_element: str = ""
  139. recall_hit_queries: List[dict] = field(default_factory=list)
  140. # 原始 item dict(以备后用)
  141. raw: dict = field(default_factory=dict, repr=False)
  142. def _call_match_by_text(
  143. query_text: str,
  144. config_code: str,
  145. material_top_n: int = DEFAULT_PER_CC_TOP_N,
  146. source_labels: Optional[List[str]] = None,
  147. timeout: int = 30,
  148. ) -> List[dict]:
  149. """单次调 matchByText,只要 MATERIAL 模态,返回原始 items 列表。"""
  150. body = {
  151. "queryText": query_text,
  152. "configCode": config_code,
  153. "modalities": ["MATERIAL"],
  154. "videoTopN": 0,
  155. "articleTopN": 0,
  156. "materialTopN": material_top_n,
  157. "topN": material_top_n,
  158. "displayK": material_top_n,
  159. }
  160. if source_labels:
  161. body["sourceLabels"] = source_labels
  162. logger.info(
  163. "[material_recall] matchByText q=%r configCode=%s topN=%d",
  164. query_text[:40], config_code, material_top_n,
  165. )
  166. resp = httpx.post(
  167. VECTOR_MATCH_BY_TEXT,
  168. json=body,
  169. headers={"content-type": "application/json", "accept": "application/json"},
  170. timeout=timeout,
  171. )
  172. resp.raise_for_status()
  173. data = resp.json()
  174. code = data.get("code")
  175. # CommonResponse 可能用 0 或 200 表示成功;以 data 字段为准
  176. if code not in (0, 200, "0", "200"):
  177. raise RuntimeError(
  178. f"vector matchByText 失败:code={code} msg={data.get('msg') or data.get('message')}"
  179. )
  180. payload = data.get("data") or {}
  181. items = payload.get("items") or []
  182. # 只留 MATERIAL 模态(防御性 — 万一返回混入)
  183. return [it for it in items if it.get("modality") == "MATERIAL"]
  184. def _pick_query_text(landing: LandingVideo) -> Optional[str]:
  185. """按优先级选 queryText:standard_element > demand_content_topic > title。
  186. 占位符 "-" / 空串视为无效。"""
  187. for cand in (landing.standard_element, landing.demand_content_topic, landing.title):
  188. if cand and cand not in PLACEHOLDER_VALUES:
  189. return cand
  190. return None
  191. def _pick_query_text_for_batch(landing: LandingVideo) -> Optional[str]:
  192. """选 queryText:standard_element > demand_content_topic > title。(保留兼容)"""
  193. for cand in (landing.standard_element, landing.demand_content_topic, landing.title):
  194. if cand and cand not in PLACEHOLDER_VALUES:
  195. return cand
  196. return None
  197. def _pick_query_strategies_for_batch(landing: LandingVideo) -> List[tuple]:
  198. """返回 (queryText, configCode, strategy_name) 策略候选(2026-06-10 用户最终确认)。
  199. 只用 2 个维度:
  200. 维度 1 - 标准化元素:queryText=standard_element, configCode 按 point_type 唯一对应
  201. - "灵感点" → INSPIRATION_SUBSTANCE
  202. - "关键点" → KEYPOINT_SUBSTANCE
  203. - "目的点" → PURPOSE_SUBSTANCE
  204. 维度 2 - 选题:queryText=demand_content_topic, configCode=VIDEO_TOPIC
  205. prepare 阶段:维度 1 失败 → 试维度 2 → 仍失败 → 换 landing。
  206. """
  207. strategies = []
  208. seen = set()
  209. for feature in landing.raw.get("element_features") or []:
  210. if not isinstance(feature, dict):
  211. continue
  212. standard_element = (feature.get("standard_element") or "").strip()
  213. point_type = (feature.get("point_type") or "").strip()
  214. if standard_element in PLACEHOLDER_VALUES:
  215. continue
  216. cc = POINT_TYPE_TO_SUBSTANCE.get(point_type)
  217. if not cc:
  218. continue
  219. key = (standard_element, cc)
  220. if key in seen:
  221. continue
  222. seen.add(key)
  223. strategies.append((standard_element, cc, f"标准化元素-{point_type}"))
  224. # 维度 1: 标准化元素(优先)
  225. if landing.standard_element and landing.standard_element not in PLACEHOLDER_VALUES:
  226. cc = POINT_TYPE_TO_SUBSTANCE.get(landing.point_type)
  227. if cc and (landing.standard_element, cc) not in seen:
  228. strategies.append((landing.standard_element, cc, f"标准化元素-{landing.point_type}"))
  229. # 维度 2: 选题
  230. if landing.demand_content_topic and landing.demand_content_topic not in PLACEHOLDER_VALUES:
  231. strategies.append((landing.demand_content_topic, "VIDEO_TOPIC", "选题"))
  232. return strategies
  233. def _fallback_config_codes_for_strategy(config_code: str, landing: LandingVideo) -> List[str]:
  234. """batchByText 无结果时给 matchByText 的兼容 configCode。
  235. 2026-06-30 实测:batchByText 对 MATERIAL 返回 0 时,旧 matchByText 仍可在
  236. VIDEO_KEYPOINT/VIDEO_INSPIRATION 等历史向量字段命中素材。
  237. """
  238. out = [config_code]
  239. video_cc = SUBSTANCE_TO_VIDEO_CONFIG.get(config_code) or POINT_TYPE_TO_VIDEO_CONFIG.get(landing.point_type)
  240. if video_cc and video_cc not in out:
  241. out.append(video_cc)
  242. if config_code != "VIDEO_TOPIC" and "VIDEO_TOPIC" not in out:
  243. out.append("VIDEO_TOPIC")
  244. return out
  245. def _call_batch_by_text(
  246. query_text: str,
  247. config_codes: List[str],
  248. display_k: int,
  249. days: int,
  250. sim_threshold: float,
  251. alpha: float,
  252. w_ctr: float, w_cvr: float, w_roi: float,
  253. w_open_rate: float, w_fission_rate: float,
  254. deconstruct_boost: float,
  255. source_labels: List[str],
  256. modalities: List[str] = None,
  257. timeout: int = 30,
  258. ) -> List[dict]:
  259. """调用 batchByText 接口(2026-06-10 升级).
  260. 服务端单次 embedding + 多 configCode 并行 ANN + 跨模态过滤 + ranking 加权 + 去重。
  261. """
  262. body = {
  263. "queryText": query_text,
  264. "configCodes": config_codes,
  265. "displayK": display_k,
  266. "modalities": modalities or ["MATERIAL"],
  267. "sourceLabels": source_labels,
  268. "days": days,
  269. "ranking": {
  270. "simThreshold": sim_threshold,
  271. "alpha": alpha,
  272. "wCtr": w_ctr, "wCvr": w_cvr, "wRoi": w_roi,
  273. "wOpenRate": w_open_rate, "wFissionRate": w_fission_rate,
  274. "deconstructBoost": deconstruct_boost,
  275. },
  276. }
  277. logger.info(
  278. "[material_recall] batchByText q=%r configCodes=%d displayK=%d simT=%.2f wCtr=%.2f",
  279. query_text[:40], len(config_codes), display_k, sim_threshold, w_ctr,
  280. )
  281. resp = httpx.post(
  282. VECTOR_BATCH_BY_TEXT,
  283. json=body,
  284. headers={"content-type": "application/json", "accept": "application/json"},
  285. timeout=timeout,
  286. )
  287. resp.raise_for_status()
  288. data = resp.json()
  289. if data.get("code") not in (0, 200, "0", "200"):
  290. raise RuntimeError(
  291. f"batchByText 失败:code={data.get('code')} msg={data.get('msg') or data.get('message')}"
  292. )
  293. payload = data.get("data") or {}
  294. return payload.get("items") or []
  295. def _as_float(value, default: float = 0.0) -> float:
  296. try:
  297. if value is None:
  298. return default
  299. return float(value)
  300. except (TypeError, ValueError):
  301. return default
  302. def _as_int(value, default: int = 0) -> int:
  303. try:
  304. if value is None:
  305. return default
  306. return int(float(value))
  307. except (TypeError, ValueError):
  308. return default
  309. def _items_to_materials(
  310. items: List[dict],
  311. sim_threshold: float,
  312. *,
  313. apply_cover_blacklist: bool = True,
  314. ) -> tuple:
  315. """把召回 items 过滤 + 转 Material。
  316. 过滤条件:
  317. - modality=MATERIAL(防御性)
  318. - cover URL 不在黑名单
  319. - score >= sim_threshold
  320. CTR / impressions 只作为审批展示和兜底排序参考,不再作为硬筛。
  321. 返回 (materials, stats)。
  322. """
  323. out: List[Material] = []
  324. stats = {
  325. "blacklist": 0,
  326. "low_score": 0,
  327. "low_imp": 0,
  328. "low_ctr": 0,
  329. }
  330. for it in items:
  331. if it.get("modality") != "MATERIAL":
  332. continue
  333. mid = it.get("materialId") or (str(it["id"]) if it.get("id") is not None else None)
  334. if not mid:
  335. continue
  336. cover = it.get("cover") or ""
  337. if apply_cover_blacklist and any(
  338. pattern in cover for pattern in EXCLUDED_COVER_URL_PATTERNS
  339. ):
  340. stats["blacklist"] += 1
  341. continue
  342. score = _as_float(it.get("score"))
  343. if score < sim_threshold:
  344. stats["low_score"] += 1
  345. continue
  346. md = it.get("materialDetail") or {}
  347. q = md.get("quality") or {}
  348. out.append(Material(
  349. material_id=str(mid),
  350. score=score,
  351. title=it.get("title") or "",
  352. cover=cover,
  353. video_url=it.get("videoUrl") or "",
  354. cost=_as_float(q.get("cost")) if q.get("cost") is not None else None,
  355. ctr=_as_float(q.get("ctr")) if q.get("ctr") is not None else None,
  356. cvr=_as_float(q.get("cvr")) if q.get("cvr") is not None else None,
  357. roi=_as_float(q.get("roi")) if q.get("roi") is not None else None,
  358. impressions=_as_int(q.get("impressions")) if q.get("impressions") is not None else None,
  359. quality_score=_as_float(q.get("qualityScore")) if q.get("qualityScore") is not None else None,
  360. raw=it,
  361. ))
  362. return out, stats
  363. def _sort_materials_by_policy(materials: List[Material]) -> List[Material]:
  364. """生产排序策略:先相关性准入,再按历史消耗倒序。"""
  365. return sorted(
  366. materials,
  367. key=lambda m: (
  368. m.cost is not None,
  369. m.cost or 0,
  370. m.roi or 0,
  371. m.impressions or 0,
  372. m.ctr or 0,
  373. m.quality_score or 0,
  374. m.score or 0,
  375. ),
  376. reverse=True,
  377. )
  378. def _material_rank(material: Material) -> tuple:
  379. return (
  380. material.cost is not None,
  381. material.cost or 0,
  382. material.roi or 0,
  383. material.impressions or 0,
  384. material.ctr or 0,
  385. material.quality_score or 0,
  386. material.score or 0,
  387. )
  388. def _feature_attr(feature, name: str, default=""):
  389. if isinstance(feature, dict):
  390. return feature.get(name, default)
  391. return getattr(feature, name, default)
  392. def _build_recall_queries_from_features(
  393. element_features: Iterable,
  394. query_limit: int,
  395. ) -> List[RecallQuery]:
  396. """Build recall queries from ODPS features.
  397. Supported dimensions:
  398. - 解构选题 -> VIDEO_TOPIC
  399. - 实质 + 灵感点/关键点/目的点 -> *_SUBSTANCE
  400. """
  401. queries: List[RecallQuery] = []
  402. seen = set()
  403. raw_features = list(element_features or [])
  404. sorted_features = sorted(
  405. raw_features,
  406. key=lambda f: (
  407. 0 if str(_feature_attr(f, "element_dimension") or "") == "解构选题" else 1,
  408. -float(_feature_attr(f, "contribution_score", 0) or 0),
  409. ),
  410. )
  411. for feature in sorted_features:
  412. element_dimension = str(_feature_attr(feature, "element_dimension") or "").strip()
  413. point_type = str(_feature_attr(feature, "point_type") or "").strip()
  414. standard_element = str(_feature_attr(feature, "standard_element") or "").strip()
  415. if standard_element in PLACEHOLDER_VALUES:
  416. continue
  417. config_code = ODPS_FEATURE_TO_CONFIG.get((element_dimension, point_type))
  418. if not config_code and element_dimension == "解构选题":
  419. config_code = ODPS_FEATURE_TO_CONFIG.get(("解构选题", ""))
  420. if not config_code:
  421. continue
  422. key = (standard_element, config_code)
  423. if key in seen:
  424. continue
  425. seen.add(key)
  426. queries.append(RecallQuery(
  427. query_text=standard_element,
  428. config_code=config_code,
  429. element_dimension=element_dimension,
  430. point_type=point_type,
  431. standard_element=standard_element,
  432. contribution_score=float(_feature_attr(feature, "contribution_score", 0) or 0),
  433. dt=str(_feature_attr(feature, "dt") or ""),
  434. ))
  435. if len(queries) >= query_limit:
  436. break
  437. return queries
  438. def _call_batch_for_recall_query(
  439. query: RecallQuery,
  440. *,
  441. display_k: int,
  442. days: int,
  443. sim_threshold: float,
  444. alpha: float,
  445. w_ctr: float,
  446. w_cvr: float,
  447. w_roi: float,
  448. w_open_rate: float,
  449. w_fission_rate: float,
  450. deconstruct_boost: float,
  451. source_labels: List[str],
  452. ) -> tuple[RecallQuery, List[dict]]:
  453. items = _call_batch_by_text(
  454. query_text=query.query_text,
  455. config_codes=[query.config_code],
  456. display_k=display_k,
  457. days=days,
  458. sim_threshold=sim_threshold,
  459. alpha=alpha,
  460. w_ctr=w_ctr,
  461. w_cvr=w_cvr,
  462. w_roi=w_roi,
  463. w_open_rate=w_open_rate,
  464. w_fission_rate=w_fission_rate,
  465. deconstruct_boost=deconstruct_boost,
  466. source_labels=source_labels,
  467. modalities=["MATERIAL"],
  468. )
  469. return query, items
  470. def _merge_materials_by_policy(query_materials: List[tuple[RecallQuery, List[Material]]]) -> List[Material]:
  471. by_mid: dict[str, Material] = {}
  472. for query, materials in query_materials:
  473. hit = query.to_hit()
  474. for material in materials:
  475. material.recall_hit_queries = [hit]
  476. material.recall_strategy = query.strategy_name
  477. material.recall_query_text = query.query_text
  478. material.recall_config_code = query.config_code
  479. material.recall_element_dimension = query.element_dimension
  480. material.recall_point_type = query.point_type
  481. material.recall_standard_element = query.standard_element
  482. existing = by_mid.get(material.material_id)
  483. if existing is None:
  484. by_mid[material.material_id] = material
  485. continue
  486. merged_hits = existing.recall_hit_queries + [
  487. h for h in material.recall_hit_queries
  488. if h not in existing.recall_hit_queries
  489. ]
  490. if _material_rank(material) > _material_rank(existing):
  491. material.recall_hit_queries = merged_hits
  492. by_mid[material.material_id] = material
  493. else:
  494. existing.recall_hit_queries = merged_hits
  495. return _sort_materials_by_policy(list(by_mid.values()))
  496. def recall_materials_for_video(
  497. landing: LandingVideo,
  498. final_top_n: Optional[int] = DEFAULT_FINAL_TOP_N,
  499. source_labels: Optional[List[str]] = None,
  500. element_features: Optional[Iterable] = None,
  501. apply_cover_blacklist: bool = True,
  502. ) -> List[Material]:
  503. """素材召回:用 ODPS 多维特征并行召回并合并排序。
  504. 流程:
  505. 1. 从 ODPS features 生成 query:解构选题 + 实质三点。
  506. 2. 多 query 并行调用 batchByText。
  507. 3. 汇总、material_id 去重、score>=阈值、按 cost 倒序。
  508. 当前硬筛只保留相似度阈值;曝光/CTR 进入审批表但不拦截。
  509. """
  510. from config import (
  511. RECALL_ALPHA, RECALL_DAYS, RECALL_DECONSTRUCT_BOOST,
  512. RECALL_DISPLAY_K, RECALL_PARALLEL_MAX_WORKERS, RECALL_QUERY_LIMIT_PER_VIDEO,
  513. RECALL_SIM_THRESHOLD, RECALL_SOURCE_LABELS,
  514. RECALL_W_CTR, RECALL_W_CVR, RECALL_W_FISSION_RATE,
  515. RECALL_W_OPEN_RATE, RECALL_W_ROI,
  516. )
  517. if element_features is None:
  518. element_features = landing.raw.get("element_features") or []
  519. queries = _build_recall_queries_from_features(
  520. element_features,
  521. query_limit=max(1, RECALL_QUERY_LIMIT_PER_VIDEO),
  522. )
  523. if not queries:
  524. logger.warning(
  525. "[material_recall] landing video_id=%d 无 ODPS 可用召回特征,返回空",
  526. landing.video_id,
  527. )
  528. return []
  529. logger.info(
  530. "[material_recall] landing video_id=%d 走 %d 个 ODPS 策略:%s",
  531. landing.video_id, len(queries),
  532. "; ".join(f"{q.strategy_name}:{q.query_text}->{q.config_code}" for q in queries),
  533. )
  534. query_materials: List[tuple[RecallQuery, List[Material]]] = []
  535. labels = source_labels or RECALL_SOURCE_LABELS
  536. max_workers = max(1, min(RECALL_PARALLEL_MAX_WORKERS, len(queries)))
  537. with ThreadPoolExecutor(max_workers=max_workers) as executor:
  538. futures = [
  539. executor.submit(
  540. _call_batch_for_recall_query,
  541. query,
  542. display_k=RECALL_DISPLAY_K,
  543. days=RECALL_DAYS,
  544. sim_threshold=RECALL_SIM_THRESHOLD,
  545. alpha=RECALL_ALPHA,
  546. w_ctr=RECALL_W_CTR,
  547. w_cvr=RECALL_W_CVR,
  548. w_roi=RECALL_W_ROI,
  549. w_open_rate=RECALL_W_OPEN_RATE,
  550. w_fission_rate=RECALL_W_FISSION_RATE,
  551. deconstruct_boost=RECALL_DECONSTRUCT_BOOST,
  552. source_labels=labels,
  553. )
  554. for query in queries
  555. ]
  556. for future in as_completed(futures):
  557. try:
  558. query, items = future.result()
  559. except Exception as e:
  560. logger.error("[material_recall] 并行 batchByText 失败:%s", e)
  561. continue
  562. mats, stats = _items_to_materials(
  563. items,
  564. RECALL_SIM_THRESHOLD,
  565. apply_cover_blacklist=apply_cover_blacklist,
  566. )
  567. query_materials.append((query, mats))
  568. logger.info(
  569. "[material_recall] 策略=%s q=%r configCode=%s 返回 %d 条,⊘ 黑名单 %d,⊘ score<%.2f %d → 保留 %d",
  570. query.strategy_name, query.query_text[:30], query.config_code,
  571. len(items), stats["blacklist"], RECALL_SIM_THRESHOLD,
  572. stats["low_score"], len(mats),
  573. )
  574. merged = _merge_materials_by_policy(query_materials)
  575. logger.info(
  576. "[material_recall] landing video_id=%d 多维召回合并后保留 %d 条(cost desc)",
  577. landing.video_id, len(merged),
  578. )
  579. if merged:
  580. return merged if final_top_n is None else merged[:final_top_n]
  581. for query in queries:
  582. # batchByText 当前可能对 MATERIAL 返回 0;降级到历史 matchByText 路径。
  583. for fallback_cc in _fallback_config_codes_for_strategy(query.config_code, landing):
  584. try:
  585. fallback_items = _call_match_by_text(
  586. query_text=query.query_text,
  587. config_code=fallback_cc,
  588. material_top_n=RECALL_DISPLAY_K,
  589. source_labels=labels,
  590. )
  591. except Exception as e:
  592. logger.error(
  593. "[material_recall] fallback matchByText %s 失败,试下一个:%s",
  594. fallback_cc, e,
  595. )
  596. continue
  597. fmats, fstats = _items_to_materials(
  598. fallback_items,
  599. RECALL_SIM_THRESHOLD,
  600. apply_cover_blacklist=apply_cover_blacklist,
  601. )
  602. fquery = RecallQuery(
  603. query_text=query.query_text,
  604. config_code=fallback_cc,
  605. element_dimension=query.element_dimension,
  606. point_type=query.point_type,
  607. standard_element=query.standard_element,
  608. contribution_score=query.contribution_score,
  609. dt=query.dt,
  610. )
  611. fmats = _merge_materials_by_policy([(fquery, fmats)])
  612. logger.info(
  613. "[material_recall] fallback=%s 返回 %d 条,⊘ 黑名单 %d,⊘ score<%.2f %d → 保留 %d(cost desc)",
  614. fallback_cc, len(fallback_items), fstats["blacklist"],
  615. RECALL_SIM_THRESHOLD, fstats["low_score"],
  616. len(fmats),
  617. )
  618. if fmats:
  619. return fmats if final_top_n is None else fmats[:final_top_n]
  620. logger.info(
  621. "[material_recall] landing video_id=%d 所有 %d ODPS 策略全失败,返回空(上层换 landing)",
  622. landing.video_id, len(queries),
  623. )
  624. return []