material_recall.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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. recall_strategy: str = ""
  133. recall_query_text: str = ""
  134. recall_config_code: str = ""
  135. recall_element_dimension: str = ""
  136. recall_point_type: str = ""
  137. recall_standard_element: str = ""
  138. recall_hit_queries: List[dict] = field(default_factory=list)
  139. # 原始 item dict(以备后用)
  140. raw: dict = field(default_factory=dict, repr=False)
  141. def _call_match_by_text(
  142. query_text: str,
  143. config_code: str,
  144. material_top_n: int = DEFAULT_PER_CC_TOP_N,
  145. source_labels: Optional[List[str]] = None,
  146. timeout: int = 30,
  147. ) -> List[dict]:
  148. """单次调 matchByText,只要 MATERIAL 模态,返回原始 items 列表。"""
  149. body = {
  150. "queryText": query_text,
  151. "configCode": config_code,
  152. "modalities": ["MATERIAL"],
  153. "videoTopN": 0,
  154. "articleTopN": 0,
  155. "materialTopN": material_top_n,
  156. "topN": material_top_n,
  157. "displayK": material_top_n,
  158. }
  159. if source_labels:
  160. body["sourceLabels"] = source_labels
  161. logger.info(
  162. "[material_recall] matchByText q=%r configCode=%s topN=%d",
  163. query_text[:40], config_code, material_top_n,
  164. )
  165. resp = httpx.post(
  166. VECTOR_MATCH_BY_TEXT,
  167. json=body,
  168. headers={"content-type": "application/json", "accept": "application/json"},
  169. timeout=timeout,
  170. )
  171. resp.raise_for_status()
  172. data = resp.json()
  173. code = data.get("code")
  174. # CommonResponse 可能用 0 或 200 表示成功;以 data 字段为准
  175. if code not in (0, 200, "0", "200"):
  176. raise RuntimeError(
  177. f"vector matchByText 失败:code={code} msg={data.get('msg') or data.get('message')}"
  178. )
  179. payload = data.get("data") or {}
  180. items = payload.get("items") or []
  181. # 只留 MATERIAL 模态(防御性 — 万一返回混入)
  182. return [it for it in items if it.get("modality") == "MATERIAL"]
  183. def _pick_query_text(landing: LandingVideo) -> Optional[str]:
  184. """按优先级选 queryText:standard_element > demand_content_topic > title。
  185. 占位符 "-" / 空串视为无效。"""
  186. for cand in (landing.standard_element, landing.demand_content_topic, landing.title):
  187. if cand and cand not in PLACEHOLDER_VALUES:
  188. return cand
  189. return None
  190. def _pick_query_text_for_batch(landing: LandingVideo) -> Optional[str]:
  191. """选 queryText:standard_element > demand_content_topic > title。(保留兼容)"""
  192. for cand in (landing.standard_element, landing.demand_content_topic, landing.title):
  193. if cand and cand not in PLACEHOLDER_VALUES:
  194. return cand
  195. return None
  196. def _pick_query_strategies_for_batch(landing: LandingVideo) -> List[tuple]:
  197. """返回 (queryText, configCode, strategy_name) 策略候选(2026-06-10 用户最终确认)。
  198. 只用 2 个维度:
  199. 维度 1 - 标准化元素:queryText=standard_element, configCode 按 point_type 唯一对应
  200. - "灵感点" → INSPIRATION_SUBSTANCE
  201. - "关键点" → KEYPOINT_SUBSTANCE
  202. - "目的点" → PURPOSE_SUBSTANCE
  203. 维度 2 - 选题:queryText=demand_content_topic, configCode=VIDEO_TOPIC
  204. prepare 阶段:维度 1 失败 → 试维度 2 → 仍失败 → 换 landing。
  205. """
  206. strategies = []
  207. seen = set()
  208. for feature in landing.raw.get("element_features") or []:
  209. if not isinstance(feature, dict):
  210. continue
  211. standard_element = (feature.get("standard_element") or "").strip()
  212. point_type = (feature.get("point_type") or "").strip()
  213. if standard_element in PLACEHOLDER_VALUES:
  214. continue
  215. cc = POINT_TYPE_TO_SUBSTANCE.get(point_type)
  216. if not cc:
  217. continue
  218. key = (standard_element, cc)
  219. if key in seen:
  220. continue
  221. seen.add(key)
  222. strategies.append((standard_element, cc, f"标准化元素-{point_type}"))
  223. # 维度 1: 标准化元素(优先)
  224. if landing.standard_element and landing.standard_element not in PLACEHOLDER_VALUES:
  225. cc = POINT_TYPE_TO_SUBSTANCE.get(landing.point_type)
  226. if cc and (landing.standard_element, cc) not in seen:
  227. strategies.append((landing.standard_element, cc, f"标准化元素-{landing.point_type}"))
  228. # 维度 2: 选题
  229. if landing.demand_content_topic and landing.demand_content_topic not in PLACEHOLDER_VALUES:
  230. strategies.append((landing.demand_content_topic, "VIDEO_TOPIC", "选题"))
  231. return strategies
  232. def _fallback_config_codes_for_strategy(config_code: str, landing: LandingVideo) -> List[str]:
  233. """batchByText 无结果时给 matchByText 的兼容 configCode。
  234. 2026-06-30 实测:batchByText 对 MATERIAL 返回 0 时,旧 matchByText 仍可在
  235. VIDEO_KEYPOINT/VIDEO_INSPIRATION 等历史向量字段命中素材。
  236. """
  237. out = [config_code]
  238. video_cc = SUBSTANCE_TO_VIDEO_CONFIG.get(config_code) or POINT_TYPE_TO_VIDEO_CONFIG.get(landing.point_type)
  239. if video_cc and video_cc not in out:
  240. out.append(video_cc)
  241. if config_code != "VIDEO_TOPIC" and "VIDEO_TOPIC" not in out:
  242. out.append("VIDEO_TOPIC")
  243. return out
  244. def _call_batch_by_text(
  245. query_text: str,
  246. config_codes: List[str],
  247. display_k: int,
  248. days: int,
  249. sim_threshold: float,
  250. alpha: float,
  251. w_ctr: float, w_cvr: float, w_roi: float,
  252. w_open_rate: float, w_fission_rate: float,
  253. deconstruct_boost: float,
  254. source_labels: List[str],
  255. modalities: List[str] = None,
  256. timeout: int = 30,
  257. ) -> List[dict]:
  258. """调用 batchByText 接口(2026-06-10 升级).
  259. 服务端单次 embedding + 多 configCode 并行 ANN + 跨模态过滤 + ranking 加权 + 去重。
  260. """
  261. body = {
  262. "queryText": query_text,
  263. "configCodes": config_codes,
  264. "displayK": display_k,
  265. "modalities": modalities or ["MATERIAL"],
  266. "sourceLabels": source_labels,
  267. "days": days,
  268. "ranking": {
  269. "simThreshold": sim_threshold,
  270. "alpha": alpha,
  271. "wCtr": w_ctr, "wCvr": w_cvr, "wRoi": w_roi,
  272. "wOpenRate": w_open_rate, "wFissionRate": w_fission_rate,
  273. "deconstructBoost": deconstruct_boost,
  274. },
  275. }
  276. logger.info(
  277. "[material_recall] batchByText q=%r configCodes=%d displayK=%d simT=%.2f wCtr=%.2f",
  278. query_text[:40], len(config_codes), display_k, sim_threshold, w_ctr,
  279. )
  280. resp = httpx.post(
  281. VECTOR_BATCH_BY_TEXT,
  282. json=body,
  283. headers={"content-type": "application/json", "accept": "application/json"},
  284. timeout=timeout,
  285. )
  286. resp.raise_for_status()
  287. data = resp.json()
  288. if data.get("code") not in (0, 200, "0", "200"):
  289. raise RuntimeError(
  290. f"batchByText 失败:code={data.get('code')} msg={data.get('msg') or data.get('message')}"
  291. )
  292. payload = data.get("data") or {}
  293. return payload.get("items") or []
  294. def _as_float(value, default: float = 0.0) -> float:
  295. try:
  296. if value is None:
  297. return default
  298. return float(value)
  299. except (TypeError, ValueError):
  300. return default
  301. def _as_int(value, default: int = 0) -> int:
  302. try:
  303. if value is None:
  304. return default
  305. return int(float(value))
  306. except (TypeError, ValueError):
  307. return default
  308. def _items_to_materials(items: List[dict], sim_threshold: float) -> tuple:
  309. """把召回 items 过滤 + 转 Material。
  310. 过滤条件:
  311. - modality=MATERIAL(防御性)
  312. - cover URL 不在黑名单
  313. - score >= sim_threshold
  314. CTR / impressions 只作为审批展示和兜底排序参考,不再作为硬筛。
  315. 返回 (materials, stats)。
  316. """
  317. out: List[Material] = []
  318. stats = {
  319. "blacklist": 0,
  320. "low_score": 0,
  321. "low_imp": 0,
  322. "low_ctr": 0,
  323. }
  324. for it in items:
  325. if it.get("modality") != "MATERIAL":
  326. continue
  327. mid = it.get("materialId") or (str(it["id"]) if it.get("id") is not None else None)
  328. if not mid:
  329. continue
  330. cover = it.get("cover") or ""
  331. if any(p in cover for p in EXCLUDED_COVER_URL_PATTERNS):
  332. stats["blacklist"] += 1
  333. continue
  334. score = _as_float(it.get("score"))
  335. if score < sim_threshold:
  336. stats["low_score"] += 1
  337. continue
  338. md = it.get("materialDetail") or {}
  339. q = md.get("quality") or {}
  340. out.append(Material(
  341. material_id=str(mid),
  342. score=score,
  343. title=it.get("title") or "",
  344. cover=cover,
  345. video_url=it.get("videoUrl") or "",
  346. cost=_as_float(q.get("cost")) if q.get("cost") is not None else None,
  347. ctr=_as_float(q.get("ctr")) if q.get("ctr") is not None else None,
  348. cvr=_as_float(q.get("cvr")) if q.get("cvr") is not None else None,
  349. roi=_as_float(q.get("roi")) if q.get("roi") is not None else None,
  350. impressions=_as_int(q.get("impressions")) if q.get("impressions") is not None else None,
  351. quality_score=_as_float(q.get("qualityScore")) if q.get("qualityScore") is not None else None,
  352. raw=it,
  353. ))
  354. return out, stats
  355. def _sort_materials_by_policy(materials: List[Material]) -> List[Material]:
  356. """生产排序策略:先相关性准入,再按历史消耗倒序。"""
  357. return sorted(
  358. materials,
  359. key=lambda m: (
  360. m.cost is not None,
  361. m.cost or 0,
  362. m.roi or 0,
  363. m.impressions or 0,
  364. m.ctr or 0,
  365. m.quality_score or 0,
  366. m.score or 0,
  367. ),
  368. reverse=True,
  369. )
  370. def _material_rank(material: Material) -> tuple:
  371. return (
  372. material.cost is not None,
  373. material.cost or 0,
  374. material.roi or 0,
  375. material.impressions or 0,
  376. material.ctr or 0,
  377. material.quality_score or 0,
  378. material.score or 0,
  379. )
  380. def _feature_attr(feature, name: str, default=""):
  381. if isinstance(feature, dict):
  382. return feature.get(name, default)
  383. return getattr(feature, name, default)
  384. def _build_recall_queries_from_features(
  385. element_features: Iterable,
  386. query_limit: int,
  387. ) -> List[RecallQuery]:
  388. """Build recall queries from ODPS features.
  389. Supported dimensions:
  390. - 解构选题 -> VIDEO_TOPIC
  391. - 实质 + 灵感点/关键点/目的点 -> *_SUBSTANCE
  392. """
  393. queries: List[RecallQuery] = []
  394. seen = set()
  395. raw_features = list(element_features or [])
  396. sorted_features = sorted(
  397. raw_features,
  398. key=lambda f: (
  399. 0 if str(_feature_attr(f, "element_dimension") or "") == "解构选题" else 1,
  400. -float(_feature_attr(f, "contribution_score", 0) or 0),
  401. ),
  402. )
  403. for feature in sorted_features:
  404. element_dimension = str(_feature_attr(feature, "element_dimension") or "").strip()
  405. point_type = str(_feature_attr(feature, "point_type") or "").strip()
  406. standard_element = str(_feature_attr(feature, "standard_element") or "").strip()
  407. if standard_element in PLACEHOLDER_VALUES:
  408. continue
  409. config_code = ODPS_FEATURE_TO_CONFIG.get((element_dimension, point_type))
  410. if not config_code and element_dimension == "解构选题":
  411. config_code = ODPS_FEATURE_TO_CONFIG.get(("解构选题", ""))
  412. if not config_code:
  413. continue
  414. key = (standard_element, config_code)
  415. if key in seen:
  416. continue
  417. seen.add(key)
  418. queries.append(RecallQuery(
  419. query_text=standard_element,
  420. config_code=config_code,
  421. element_dimension=element_dimension,
  422. point_type=point_type,
  423. standard_element=standard_element,
  424. contribution_score=float(_feature_attr(feature, "contribution_score", 0) or 0),
  425. dt=str(_feature_attr(feature, "dt") or ""),
  426. ))
  427. if len(queries) >= query_limit:
  428. break
  429. return queries
  430. def _call_batch_for_recall_query(
  431. query: RecallQuery,
  432. *,
  433. display_k: int,
  434. days: int,
  435. sim_threshold: float,
  436. alpha: float,
  437. w_ctr: float,
  438. w_cvr: float,
  439. w_roi: float,
  440. w_open_rate: float,
  441. w_fission_rate: float,
  442. deconstruct_boost: float,
  443. source_labels: List[str],
  444. ) -> tuple[RecallQuery, List[dict]]:
  445. items = _call_batch_by_text(
  446. query_text=query.query_text,
  447. config_codes=[query.config_code],
  448. display_k=display_k,
  449. days=days,
  450. sim_threshold=sim_threshold,
  451. alpha=alpha,
  452. w_ctr=w_ctr,
  453. w_cvr=w_cvr,
  454. w_roi=w_roi,
  455. w_open_rate=w_open_rate,
  456. w_fission_rate=w_fission_rate,
  457. deconstruct_boost=deconstruct_boost,
  458. source_labels=source_labels,
  459. modalities=["MATERIAL"],
  460. )
  461. return query, items
  462. def _merge_materials_by_policy(query_materials: List[tuple[RecallQuery, List[Material]]]) -> List[Material]:
  463. by_mid: dict[str, Material] = {}
  464. for query, materials in query_materials:
  465. hit = query.to_hit()
  466. for material in materials:
  467. material.recall_hit_queries = [hit]
  468. material.recall_strategy = query.strategy_name
  469. material.recall_query_text = query.query_text
  470. material.recall_config_code = query.config_code
  471. material.recall_element_dimension = query.element_dimension
  472. material.recall_point_type = query.point_type
  473. material.recall_standard_element = query.standard_element
  474. existing = by_mid.get(material.material_id)
  475. if existing is None:
  476. by_mid[material.material_id] = material
  477. continue
  478. merged_hits = existing.recall_hit_queries + [
  479. h for h in material.recall_hit_queries
  480. if h not in existing.recall_hit_queries
  481. ]
  482. if _material_rank(material) > _material_rank(existing):
  483. material.recall_hit_queries = merged_hits
  484. by_mid[material.material_id] = material
  485. else:
  486. existing.recall_hit_queries = merged_hits
  487. return _sort_materials_by_policy(list(by_mid.values()))
  488. def recall_materials_for_video(
  489. landing: LandingVideo,
  490. final_top_n: int = DEFAULT_FINAL_TOP_N,
  491. source_labels: Optional[List[str]] = None,
  492. element_features: Optional[Iterable] = None,
  493. ) -> List[Material]:
  494. """素材召回:用 ODPS 多维特征并行召回并合并排序。
  495. 流程:
  496. 1. 从 ODPS features 生成 query:解构选题 + 实质三点。
  497. 2. 多 query 并行调用 batchByText。
  498. 3. 汇总、material_id 去重、score>=阈值、按 cost 倒序。
  499. 当前硬筛只保留相似度阈值;曝光/CTR 进入审批表但不拦截。
  500. """
  501. from config import (
  502. RECALL_ALPHA, RECALL_DAYS, RECALL_DECONSTRUCT_BOOST,
  503. RECALL_DISPLAY_K, RECALL_PARALLEL_MAX_WORKERS, RECALL_QUERY_LIMIT_PER_VIDEO,
  504. RECALL_SIM_THRESHOLD, RECALL_SOURCE_LABELS,
  505. RECALL_W_CTR, RECALL_W_CVR, RECALL_W_FISSION_RATE,
  506. RECALL_W_OPEN_RATE, RECALL_W_ROI,
  507. )
  508. if element_features is None:
  509. element_features = landing.raw.get("element_features") or []
  510. queries = _build_recall_queries_from_features(
  511. element_features,
  512. query_limit=max(1, RECALL_QUERY_LIMIT_PER_VIDEO),
  513. )
  514. if not queries:
  515. logger.warning(
  516. "[material_recall] landing video_id=%d 无 ODPS 可用召回特征,返回空",
  517. landing.video_id,
  518. )
  519. return []
  520. logger.info(
  521. "[material_recall] landing video_id=%d 走 %d 个 ODPS 策略:%s",
  522. landing.video_id, len(queries),
  523. "; ".join(f"{q.strategy_name}:{q.query_text}->{q.config_code}" for q in queries),
  524. )
  525. query_materials: List[tuple[RecallQuery, List[Material]]] = []
  526. labels = source_labels or RECALL_SOURCE_LABELS
  527. max_workers = max(1, min(RECALL_PARALLEL_MAX_WORKERS, len(queries)))
  528. with ThreadPoolExecutor(max_workers=max_workers) as executor:
  529. futures = [
  530. executor.submit(
  531. _call_batch_for_recall_query,
  532. query,
  533. display_k=RECALL_DISPLAY_K,
  534. days=RECALL_DAYS,
  535. sim_threshold=RECALL_SIM_THRESHOLD,
  536. alpha=RECALL_ALPHA,
  537. w_ctr=RECALL_W_CTR,
  538. w_cvr=RECALL_W_CVR,
  539. w_roi=RECALL_W_ROI,
  540. w_open_rate=RECALL_W_OPEN_RATE,
  541. w_fission_rate=RECALL_W_FISSION_RATE,
  542. deconstruct_boost=RECALL_DECONSTRUCT_BOOST,
  543. source_labels=labels,
  544. )
  545. for query in queries
  546. ]
  547. for future in as_completed(futures):
  548. try:
  549. query, items = future.result()
  550. except Exception as e:
  551. logger.error("[material_recall] 并行 batchByText 失败:%s", e)
  552. continue
  553. mats, stats = _items_to_materials(items, RECALL_SIM_THRESHOLD)
  554. query_materials.append((query, mats))
  555. logger.info(
  556. "[material_recall] 策略=%s q=%r configCode=%s 返回 %d 条,⊘ 黑名单 %d,⊘ score<%.2f %d → 保留 %d",
  557. query.strategy_name, query.query_text[:30], query.config_code,
  558. len(items), stats["blacklist"], RECALL_SIM_THRESHOLD,
  559. stats["low_score"], len(mats),
  560. )
  561. merged = _merge_materials_by_policy(query_materials)
  562. logger.info(
  563. "[material_recall] landing video_id=%d 多维召回合并后保留 %d 条(cost desc)",
  564. landing.video_id, len(merged),
  565. )
  566. if merged:
  567. return merged[:final_top_n]
  568. for query in queries:
  569. # batchByText 当前可能对 MATERIAL 返回 0;降级到历史 matchByText 路径。
  570. for fallback_cc in _fallback_config_codes_for_strategy(query.config_code, landing):
  571. try:
  572. fallback_items = _call_match_by_text(
  573. query_text=query.query_text,
  574. config_code=fallback_cc,
  575. material_top_n=RECALL_DISPLAY_K,
  576. source_labels=labels,
  577. )
  578. except Exception as e:
  579. logger.error(
  580. "[material_recall] fallback matchByText %s 失败,试下一个:%s",
  581. fallback_cc, e,
  582. )
  583. continue
  584. fmats, fstats = _items_to_materials(fallback_items, RECALL_SIM_THRESHOLD)
  585. fquery = RecallQuery(
  586. query_text=query.query_text,
  587. config_code=fallback_cc,
  588. element_dimension=query.element_dimension,
  589. point_type=query.point_type,
  590. standard_element=query.standard_element,
  591. contribution_score=query.contribution_score,
  592. dt=query.dt,
  593. )
  594. fmats = _merge_materials_by_policy([(fquery, fmats)])
  595. logger.info(
  596. "[material_recall] fallback=%s 返回 %d 条,⊘ 黑名单 %d,⊘ score<%.2f %d → 保留 %d(cost desc)",
  597. fallback_cc, len(fallback_items), fstats["blacklist"],
  598. RECALL_SIM_THRESHOLD, fstats["low_score"],
  599. len(fmats),
  600. )
  601. if fmats:
  602. return fmats[:final_top_n]
  603. logger.info(
  604. "[material_recall] landing video_id=%d 所有 %d ODPS 策略全失败,返回空(上层换 landing)",
  605. landing.video_id, len(queries),
  606. )
  607. return []