recommend.py 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  1. import json
  2. import time
  3. import multiprocessing
  4. import traceback
  5. import hashlib
  6. from datetime import datetime, timedelta
  7. import config
  8. from log import Log
  9. from config import set_config
  10. from video_recall import PoolRecall
  11. from video_rank import video_rank, bottom_strategy, video_rank_by_w_h_rate, video_rank_with_old_video, bottom_strategy2
  12. from db_helper import RedisHelper
  13. import gevent
  14. from utils import FilterVideos, get_user_has30day_return
  15. import ast
  16. log_ = Log()
  17. config_ = set_config()
  18. def relevant_video_top_recommend(request_id, app_type, mid, uid, head_vid, videos, size):
  19. """
  20. 相关推荐强插 运营给定置顶相关性视频
  21. :param request_id: request_id
  22. :param app_type: 产品标识 type-int
  23. :param mid: mid
  24. :param uid: uid
  25. :param head_vid: 相关推荐头部视频id type-int
  26. :param videos: 当前相关推荐结果 type-list
  27. :param size: 返回视频个数 type-int
  28. :return: rank_result
  29. """
  30. # 获取头部视频对应的相关性视频
  31. key_name = '{}{}'.format(config_.RELEVANT_VIDEOS_WITH_OP_KEY_NAME, head_vid)
  32. redis_helper = RedisHelper()
  33. relevant_videos = redis_helper.get_data_from_redis(key_name=key_name)
  34. if relevant_videos is None:
  35. # 该视频没有指定的相关性视频
  36. return videos
  37. relevant_videos = json.loads(relevant_videos)
  38. # 按照指定顺序排序
  39. relevant_videos_sorted = sorted(relevant_videos, key=lambda x: x['order'], reverse=False)
  40. # 过滤
  41. relevant_video_ids = [int(item['recommend_vid']) for item in relevant_videos_sorted]
  42. filter_helper = FilterVideos(request_id=request_id, app_type=app_type, video_ids=relevant_video_ids, mid=mid, uid=uid)
  43. filtered_ids = filter_helper.filter_videos()
  44. if filtered_ids is None:
  45. return videos
  46. # 获取生效中的视频
  47. now = int(time.time())
  48. relevant_videos_in_effect = [
  49. {'videoId': int(item['recommend_vid']), 'pushFrom': config_.PUSH_FROM['relevant_video_op'],
  50. 'abCode': config_.AB_CODE['relevant_video_op']}
  51. for item in relevant_videos_sorted
  52. if item['start_time'] < now < item['finish_time'] and int(item['recommend_vid']) in filtered_ids
  53. ]
  54. if len(relevant_videos_in_effect) == 0:
  55. return videos
  56. # 与现有排序结果 进行合并重排
  57. # 获取现有排序结果中流量池视频 及其位置
  58. relevant_ids = [item['videoId'] for item in relevant_videos_in_effect]
  59. flow_pool_videos = []
  60. other_videos = []
  61. for i, item in enumerate(videos):
  62. if item.get('pushFrom', None) == config_.PUSH_FROM['flow_recall'] and item.get('videoId') not in relevant_ids:
  63. flow_pool_videos.append((i, item))
  64. elif item.get('videoId') not in relevant_ids:
  65. other_videos.append(item)
  66. else:
  67. continue
  68. # 重排,保持流量池视频位置不变
  69. rank_result = relevant_videos_in_effect + other_videos
  70. for i, item in flow_pool_videos:
  71. rank_result.insert(i, item)
  72. return rank_result[:size]
  73. def video_position_recommend(request_id, mid, uid, app_type, videos):
  74. # videos = video_recommend(mid=mid, uid=uid, size=size, app_type=app_type,
  75. # algo_type=algo_type, client_info=client_info)
  76. redis_helper = RedisHelper()
  77. pos1_vids = redis_helper.get_data_from_redis(config.BaseConfig.RECALL_POSITION1_KEY_NAME)
  78. pos2_vids = redis_helper.get_data_from_redis(config.BaseConfig.RECALL_POSITION2_KEY_NAME)
  79. if pos1_vids is not None:
  80. pos1_vids = ast.literal_eval(pos1_vids)
  81. if pos2_vids is not None:
  82. pos2_vids = ast.literal_eval(pos2_vids)
  83. pos1_vids = [] if pos1_vids is None else pos1_vids
  84. pos2_vids = [] if pos2_vids is None else pos2_vids
  85. pos1_vids = [int(i) for i in pos1_vids]
  86. pos2_vids = [int(i) for i in pos2_vids]
  87. filter_1 = FilterVideos(request_id=request_id, app_type=app_type, video_ids=pos1_vids, mid=mid, uid=uid)
  88. filter_2 = FilterVideos(request_id=request_id, app_type=app_type, video_ids=pos2_vids, mid=mid, uid=uid)
  89. t = [gevent.spawn(filter_1.filter_videos), gevent.spawn(filter_2.filter_videos)]
  90. gevent.joinall(t)
  91. filted_list = [i.get() for i in t]
  92. pos1_vids = filted_list[0]
  93. pos2_vids = filted_list[1]
  94. videos = positon_duplicate(pos1_vids, pos2_vids, videos)
  95. if pos1_vids is not None and len(pos1_vids) >0 :
  96. videos.insert(0, {'videoId': int(pos1_vids[0]), 'rovScore': 100,
  97. 'pushFrom': config_.PUSH_FROM['position_insert'], 'abCode': config_.AB_CODE['position_insert']})
  98. if pos2_vids is not None and len(pos2_vids) >0 :
  99. videos.insert(1, {'videoId': int(pos2_vids[0]), 'rovScore': 100,
  100. 'pushFrom': config_.PUSH_FROM['position_insert'], 'abCode': config_.AB_CODE['position_insert']})
  101. return videos[:10]
  102. def positon_duplicate(pos1_vids, pos2_vids, videos):
  103. s = set()
  104. if pos1_vids is not None and len(pos1_vids) >0:
  105. s.add(int(pos1_vids[0]))
  106. if pos2_vids is not None and len(pos2_vids) >0:
  107. s.add(int(pos2_vids[0]))
  108. l = []
  109. for item in videos:
  110. if item['videoId'] in s:
  111. continue
  112. else:
  113. l.append(item)
  114. return l
  115. def video_recommend(request_id, mid, uid, size, top_K, flow_pool_P, app_type, algo_type, client_info,
  116. expire_time=24*3600, ab_code=config_.AB_CODE['initial'], rule_key='', data_key='',
  117. no_op_flag=False, old_video_index=-1, video_id=None, params=None, rule_key_30day=None,
  118. shield_config=None):
  119. """
  120. 首页线上推荐逻辑
  121. :param request_id: request_id
  122. :param mid: mid type-string
  123. :param uid: uid type-string
  124. :param size: 请求视频数量 type-int
  125. :param top_K: 保证topK为召回池视频 type-int
  126. :param flow_pool_P: size-top_K视频为流量池视频的概率 type-float
  127. :param app_type: 产品标识 type-int
  128. :param algo_type: 算法类型 type-string
  129. :param client_info: 用户位置信息 {"country": "国家", "province": "省份", "city": "城市"}
  130. :param expire_time: 末位视频记录redis过期时间
  131. :param ab_code: AB实验code
  132. :param video_id: 相关推荐头部视频id
  133. :param params:
  134. :return:
  135. """
  136. result = {}
  137. # ####### 多进程召回
  138. start_recall = time.time()
  139. # log_.info('====== recall')
  140. '''
  141. cores = multiprocessing.cpu_count()
  142. pool = multiprocessing.Pool(processes=cores)
  143. pool_recall = PoolRecall(app_type=app_type, mid=mid, uid=uid, ab_code=ab_code)
  144. _, last_rov_recall_key, _ = pool_recall.get_video_last_idx()
  145. pool_list = [
  146. # rov召回池
  147. pool.apply_async(pool_recall.rov_pool_recall, (size,)),
  148. # 流量池
  149. pool.apply_async(pool_recall.flow_pool_recall, (size,))
  150. ]
  151. recall_result_list = [p.get() for p in pool_list]
  152. pool.close()
  153. pool.join()
  154. '''
  155. recall_result_list = []
  156. pool_recall = PoolRecall(request_id=request_id,
  157. app_type=app_type, mid=mid, uid=uid, ab_code=ab_code,
  158. client_info=client_info, rule_key=rule_key, data_key=data_key, no_op_flag=no_op_flag,
  159. params=params, rule_key_30day=rule_key_30day, shield_config=shield_config)
  160. # _, last_rov_recall_key, _ = pool_recall.get_video_last_idx()
  161. # # 小时级实验
  162. # if ab_code in [code for _, code in config_.AB_CODE['rank_by_h'].items()]:
  163. # t = [gevent.spawn(pool_recall.rule_recall_by_h, size, expire_time),
  164. # gevent.spawn(pool_recall.flow_pool_recall, size, config_.QUICK_FLOW_POOL_ID),
  165. # gevent.spawn(pool_recall.flow_pool_recall, size)]
  166. # # 小时级实验
  167. # elif ab_code in [code for _, code in config_.AB_CODE['rank_by_24h'].items()]:
  168. # t = [gevent.spawn(pool_recall.rov_pool_recall_by_h, size, expire_time),
  169. # gevent.spawn(pool_recall.flow_pool_recall, size, config_.QUICK_FLOW_POOL_ID),
  170. # gevent.spawn(pool_recall.flow_pool_recall, size)]
  171. # 地域分组实验
  172. # if ab_code in [code for _, code in config_.AB_CODE['region_rank_by_h'].items()]:
  173. if app_type in [config_.APP_TYPE['LAO_HAO_KAN_VIDEO'], config_.APP_TYPE['ZUI_JING_QI']]:
  174. t = [gevent.spawn(pool_recall.rov_pool_recall_with_region, size, expire_time)]
  175. else:
  176. t = [gevent.spawn(pool_recall.rov_pool_recall_with_region, size, expire_time),
  177. gevent.spawn(pool_recall.flow_pool_recall, size, config_.QUICK_FLOW_POOL_ID),
  178. gevent.spawn(pool_recall.flow_pool_recall, size)]
  179. # 最惊奇相关推荐实验
  180. # elif ab_code == config_.AB_CODE['top_video_relevant_appType_19']:
  181. # t = [gevent.spawn(pool_recall.relevant_recall_19, video_id, size, expire_time),
  182. # gevent.spawn(pool_recall.flow_pool_recall_18_19, size)]
  183. # 最惊奇完整影视实验
  184. # elif ab_code == config_.AB_CODE['whole_movies']:
  185. # t = [gevent.spawn(pool_recall.rov_pool_recall_19, size, expire_time)]
  186. # 最惊奇/老好看实验
  187. # elif app_type in [config_.APP_TYPE['LAO_HAO_KAN_VIDEO'], config_.APP_TYPE['ZUI_JING_QI']]:
  188. # t = [gevent.spawn(pool_recall.rov_pool_recall, size, expire_time),
  189. # gevent.spawn(pool_recall.flow_pool_recall_18_19, size)]
  190. # # 天级实验
  191. # elif ab_code in [code for _, code in config_.AB_CODE['rank_by_day'].items()]:
  192. # t = [gevent.spawn(pool_recall.rov_pool_recall_by_day, size, expire_time),
  193. # gevent.spawn(pool_recall.flow_pool_recall, size, config_.QUICK_FLOW_POOL_ID),
  194. # gevent.spawn(pool_recall.flow_pool_recall, size)]
  195. # 老视频实验
  196. # elif ab_code in [config_.AB_CODE['old_video']]:
  197. # t = [gevent.spawn(pool_recall.rov_pool_recall, size, expire_time),
  198. # gevent.spawn(pool_recall.flow_pool_recall, size),
  199. # gevent.spawn(pool_recall.old_videos_recall, size)]
  200. # else:
  201. # if app_type in [config_.APP_TYPE['LAO_HAO_KAN_VIDEO'], config_.APP_TYPE['ZUI_JING_QI']]:
  202. # t = [gevent.spawn(pool_recall.rov_pool_recall, size, expire_time)]
  203. # else:
  204. # t = [gevent.spawn(pool_recall.rov_pool_recall, size, expire_time),
  205. # gevent.spawn(pool_recall.flow_pool_recall, size, config_.QUICK_FLOW_POOL_ID),
  206. # gevent.spawn(pool_recall.flow_pool_recall, size)]
  207. gevent.joinall(t)
  208. recall_result_list = [i.get() for i in t]
  209. # end_recall = time.time()
  210. # log_.info({
  211. # 'logTimestamp': int(time.time() * 1000),
  212. # 'request_id': request_id,
  213. # 'mid': mid,
  214. # 'uid': uid,
  215. # 'operation': 'recall',
  216. # 'recall_result': recall_result_list,
  217. # 'executeTime': (time.time() - start_recall) * 1000
  218. # })
  219. result['recallResult'] = recall_result_list
  220. result['recallTime'] = (time.time() - start_recall) * 1000
  221. # ####### 排序
  222. start_rank = time.time()
  223. # log_.info('====== rank')
  224. if app_type in [config_.APP_TYPE['LAO_HAO_KAN_VIDEO'], config_.APP_TYPE['ZUI_JING_QI']]:
  225. if ab_code in [
  226. config_.AB_CODE['rov_rank_appType_18_19'],
  227. config_.AB_CODE['rov_rank_appType_19'],
  228. config_.AB_CODE['top_video_relevant_appType_19']
  229. ]:
  230. data = {
  231. 'rov_pool_recall': recall_result_list[0],
  232. 'flow_pool_recall': recall_result_list[1]
  233. }
  234. else:
  235. data = {
  236. 'rov_pool_recall': recall_result_list[0],
  237. 'flow_pool_recall': []
  238. }
  239. else:
  240. if recall_result_list[1]:
  241. redis_helper = RedisHelper()
  242. quick_flow_pool_P = redis_helper.get_data_from_redis(
  243. key_name=f"{config_.QUICK_FLOWPOOL_DISTRIBUTE_RATE_KEY_NAME_PREFIX}{config_.QUICK_FLOW_POOL_ID}"
  244. )
  245. if quick_flow_pool_P:
  246. flow_pool_P = quick_flow_pool_P
  247. data = {
  248. 'rov_pool_recall': recall_result_list[0],
  249. 'flow_pool_recall': recall_result_list[1]
  250. }
  251. else:
  252. data = {
  253. 'rov_pool_recall': recall_result_list[0],
  254. 'flow_pool_recall': recall_result_list[2]
  255. }
  256. rank_result = video_rank(data=data, size=size, top_K=top_K, flow_pool_P=float(flow_pool_P))
  257. # 老视频实验
  258. # if ab_code in [config_.AB_CODE['old_video']]:
  259. # rank_result = video_rank_with_old_video(rank_result=rank_result, old_video_recall=recall_result_list[2],
  260. # size=size, top_K=top_K, old_video_index=old_video_index)
  261. # end_rank = time.time()
  262. # log_.info({
  263. # 'logTimestamp': int(time.time() * 1000),
  264. # 'request_id': request_id,
  265. # 'mid': mid,
  266. # 'uid': uid,
  267. # 'operation': 'rank',
  268. # 'rank_result': rank_result,
  269. # 'executeTime': (time.time() - start_rank) * 1000
  270. # })
  271. result['rankResult'] = rank_result
  272. result['rankTime'] = (time.time() - start_rank) * 1000
  273. # if not rank_result:
  274. # # 兜底策略
  275. # # log_.info('====== bottom strategy')
  276. # start_bottom = time.time()
  277. # rank_result = bottom_strategy2(
  278. # size=size, app_type=app_type, mid=mid, uid=uid, ab_code=ab_code, client_info=client_info, params=params
  279. # )
  280. #
  281. # # if ab_code == config_.AB_CODE['region_rank_by_h'].get('abtest_130'):
  282. # # rank_result = bottom_strategy2(
  283. # # size=size, app_type=app_type, mid=mid, uid=uid, ab_code=ab_code, client_info=client_info, params=params
  284. # # )
  285. # # else:
  286. # # rank_result = bottom_strategy(
  287. # # request_id=request_id, size=size, app_type=app_type, ab_code=ab_code, params=params
  288. # # )
  289. #
  290. # # log_.info({
  291. # # 'logTimestamp': int(time.time() * 1000),
  292. # # 'request_id': request_id,
  293. # # 'mid': mid,
  294. # # 'uid': uid,
  295. # # 'operation': 'bottom',
  296. # # 'bottom_result': rank_result,
  297. # # 'executeTime': (time.time() - start_bottom) * 1000
  298. # # })
  299. # result['bottomResult'] = rank_result
  300. # result['bottomTime'] = (time.time() - start_bottom) * 1000
  301. #
  302. # result['rankResult'] = rank_result
  303. return result
  304. # return rank_result, last_rov_recall_key
  305. def ab_test_op(rank_result, ab_code_list, app_type, mid, uid, **kwargs):
  306. """
  307. 对排序后的结果 按照AB实验进行对应的分组操作
  308. :param rank_result: 排序后的结果
  309. :param ab_code_list: 此次请求参与的 ab实验组
  310. :param app_type: 产品标识
  311. :param mid: mid
  312. :param uid: uid
  313. :param kwargs: 其他参数
  314. :return:
  315. """
  316. # ####### 视频宽高比AB实验
  317. # 对内容精选进行 视频宽高比分发实验
  318. # if config_.AB_CODE['w_h_rate'] in ab_code_list and app_type in config_.AB_TEST.get('w_h_rate', []):
  319. # rank_result = video_rank_by_w_h_rate(videos=rank_result)
  320. # log_.info('app_type: {}, mid: {}, uid: {}, rank_by_w_h_rate_result: {}'.format(
  321. # app_type, mid, uid, rank_result))
  322. # 按position位置排序
  323. if config_.AB_CODE['position_insert'] in ab_code_list and app_type in config_.AB_TEST.get('position_insert', []):
  324. rank_result = video_position_recommend(mid, uid, app_type, rank_result)
  325. print('===========================')
  326. print(rank_result)
  327. log_.info('app_type: {}, mid: {}, uid: {}, rank_by_position_insert_result: {}'.format(
  328. app_type, mid, uid, rank_result))
  329. # 相关推荐强插
  330. # if config_.AB_CODE['relevant_video_op'] in ab_code_list \
  331. # and app_type in config_.AB_TEST.get('relevant_video_op', []):
  332. # head_vid = kwargs['head_vid']
  333. # size = kwargs['size']
  334. # rank_result = relevant_video_top_recommend(
  335. # app_type=app_type, mid=mid, uid=uid, head_vid=head_vid, videos=rank_result, size=size
  336. # )
  337. # log_.info('app_type: {}, mid: {}, uid: {}, head_vid: {}, rank_by_relevant_video_op_result: {}'.format(
  338. # app_type, mid, uid, head_vid, rank_result))
  339. return rank_result
  340. def update_redis_data(result, app_type, mid, top_K, expire_time=24*3600):
  341. """
  342. 根据最终的排序结果更新相关redis数据
  343. :param result: 排序结果
  344. :param app_type: 产品标识
  345. :param mid: mid
  346. :param top_K: 保证topK为召回池视频 type-int
  347. :param expire_time: 末位视频记录redis过期时间
  348. :return: None
  349. """
  350. # ####### redis数据刷新
  351. try:
  352. redis_helper = RedisHelper()
  353. # log_.info('====== update redis')
  354. if mid and mid != 'null':
  355. # mid为空时,不做预曝光和定位数据更新
  356. # 预曝光数据同步刷新到Redis, 过期时间为0.5h
  357. preview_key_name = f"{config_.PREVIEW_KEY_PREFIX}{app_type}:{mid}"
  358. preview_video_ids = [int(item['videoId']) for item in result]
  359. if preview_video_ids:
  360. # log_.error('key_name = {} \n values = {}'.format(preview_key_name, tuple(preview_video_ids)))
  361. redis_helper.add_data_with_set(key_name=preview_key_name, values=tuple(preview_video_ids), expire_time=30 * 60)
  362. # log_.info('preview redis update success!')
  363. # # 将此次获取的ROV召回池top_K末位视频id同步刷新到Redis中,方便下次快速定位到召回位置,过期时间为1天
  364. # rov_recall_video = [item['videoId'] for item in result[:top_K]
  365. # if item['pushFrom'] == config_.PUSH_FROM['rov_recall']]
  366. # if len(rov_recall_video) > 0:
  367. # if app_type == config_.APP_TYPE['APP']:
  368. # key_name = config_.UPDATE_ROV_KEY_NAME_APP
  369. # else:
  370. # key_name = config_.UPDATE_ROV_KEY_NAME
  371. # if not redis_helper.get_score_with_value(key_name=key_name, value=rov_recall_video[-1]):
  372. # redis_helper.set_data_to_redis(key_name=last_rov_recall_key, value=rov_recall_video[-1],
  373. # expire_time=expire_time)
  374. # log_.info('last video redis update success!')
  375. # 将此次获取的 地域分组小时级数据列表 中的视频id同步刷新到redis中,方便下次快速定位到召回位置
  376. rov_recall_h_video = [item['videoId'] for item in result[:top_K]
  377. if item['pushFrom'] == config_.PUSH_FROM['rov_recall_region_h']]
  378. if len(rov_recall_h_video) > 0:
  379. last_video_key = f'{config_.LAST_VIDEO_FROM_REGION_H_PREFIX}{app_type}:{mid}'
  380. redis_helper.set_data_to_redis(key_name=last_video_key, value=rov_recall_h_video[-1],
  381. expire_time=expire_time)
  382. # 将此次获取的 地域分组相对24h数据列表 中的视频id同步刷新到redis中,方便下次快速定位到召回位置
  383. rov_recall_24h_dup1_video = [item['videoId'] for item in result[:top_K]
  384. if item['pushFrom'] == config_.PUSH_FROM['rov_recall_region_24h']]
  385. if len(rov_recall_24h_dup1_video) > 0:
  386. last_video_key = f'{config_.LAST_VIDEO_FROM_REGION_DUP1_24H_PREFIX}{app_type}:{mid}'
  387. redis_helper.set_data_to_redis(key_name=last_video_key, value=rov_recall_24h_dup1_video[-1],
  388. expire_time=expire_time)
  389. # 将此次获取的 相对24h筛选数据列表 中的视频id同步刷新到redis中,方便下次快速定位到召回位置
  390. rov_recall_24h_dup2_video = [item['videoId'] for item in result[:top_K]
  391. if item['pushFrom'] == config_.PUSH_FROM['rov_recall_24h']]
  392. if len(rov_recall_24h_dup2_video) > 0:
  393. last_video_key = f'{config_.LAST_VIDEO_FROM_REGION_DUP2_24H_PREFIX}{app_type}:{mid}'
  394. redis_helper.set_data_to_redis(key_name=last_video_key, value=rov_recall_24h_dup2_video[-1],
  395. expire_time=expire_time)
  396. # 将此次获取的 相对24h筛选后剩余数据列表 中的视频id同步刷新到redis中,方便下次快速定位到召回位置
  397. rov_recall_24h_dup3_video = [item['videoId'] for item in result[:top_K]
  398. if item['pushFrom'] == config_.PUSH_FROM['rov_recall_24h_dup']]
  399. if len(rov_recall_24h_dup3_video) > 0:
  400. last_video_key = f'{config_.LAST_VIDEO_FROM_REGION_DUP3_24H_PREFIX}{app_type}:{mid}'
  401. redis_helper.set_data_to_redis(key_name=last_video_key, value=rov_recall_24h_dup3_video[-1],
  402. expire_time=expire_time)
  403. # 将此次获取的 相对48h筛选数据列表 中的视频id同步刷新到redis中,方便下次快速定位到召回位置
  404. rov_recall_48h_dup2_video = [item['videoId'] for item in result[:top_K]
  405. if item['pushFrom'] == config_.PUSH_FROM['rov_recall_48h']]
  406. if len(rov_recall_48h_dup2_video) > 0:
  407. last_video_key = f'{config_.LAST_VIDEO_FROM_REGION_DUP2_48H_PREFIX}{app_type}:{mid}'
  408. redis_helper.set_data_to_redis(key_name=last_video_key, value=rov_recall_48h_dup2_video[-1],
  409. expire_time=expire_time)
  410. # 将此次获取的 相对48h筛选后剩余数据列表 中的视频id同步刷新到redis中,方便下次快速定位到召回位置
  411. rov_recall_48h_dup3_video = [item['videoId'] for item in result[:top_K]
  412. if item['pushFrom'] == config_.PUSH_FROM['rov_recall_48h_dup']]
  413. if len(rov_recall_48h_dup3_video) > 0:
  414. last_video_key = f'{config_.LAST_VIDEO_FROM_REGION_DUP3_48H_PREFIX}{app_type}:{mid}'
  415. redis_helper.set_data_to_redis(key_name=last_video_key, value=rov_recall_48h_dup3_video[-1],
  416. expire_time=expire_time)
  417. # 将此次分发的流量池视频,对 本地分发数-1 进行记录
  418. if app_type not in [config_.APP_TYPE['LAO_HAO_KAN_VIDEO'], config_.APP_TYPE['ZUI_JING_QI']]:
  419. # 获取本地分发数-1策略开关
  420. switch = redis_helper.get_data_from_redis(key_name=config_.IN_FLOW_POOL_COUNT_SWITCH_KEY_NAME)
  421. if switch is not None:
  422. if int(switch) == 1:
  423. flow_recall_video = [item for item in result if item.get('flowPool', None) is not None]
  424. else:
  425. flow_recall_video = [item for item in result if
  426. item['pushFrom'] == config_.PUSH_FROM['flow_recall']]
  427. else:
  428. flow_recall_video = [item for item in result if item['pushFrom'] == config_.PUSH_FROM['flow_recall']]
  429. if flow_recall_video:
  430. update_local_distribute_count(flow_recall_video)
  431. # log_.info('update local distribute count success!')
  432. # 限流视频分发数记录
  433. if app_type == config_.APP_TYPE['APP']:
  434. # APP 不计入
  435. return
  436. limit_video_id_list = redis_helper.get_data_from_set(
  437. key_name=f"{config_.KEY_NAME_PREFIX_LIMIT_VIDEO_SET}{datetime.today().strftime('%Y%m%d')}"
  438. )
  439. if limit_video_id_list is not None:
  440. limit_video_id_list = [int(item) for item in limit_video_id_list]
  441. for item in result:
  442. video_id = item['videoId']
  443. if video_id in limit_video_id_list:
  444. key_name = f"{config_.KEY_NAME_PREFIX_LIMIT_VIDEO_DISTRIBUTE_COUNT}{video_id}"
  445. redis_helper.setnx_key(key_name=key_name, value=0, expire_time=24*2600)
  446. redis_helper.incr_key(key_name=key_name, amount=1, expire_time=24*3600)
  447. except Exception as e:
  448. log_.error("update redis data fail!")
  449. log_.error(traceback.format_exc())
  450. def update_local_distribute_count(videos):
  451. """
  452. 更新本地分发数
  453. :param videos: 视频列表 type-list [{'videoId':'', 'flowPool':'', 'distributeCount': '',
  454. 'rovScore': '', 'pushFrom': 'flow_pool', 'abCode': self.ab_code}, ....]
  455. :return:
  456. """
  457. try:
  458. redis_helper = RedisHelper()
  459. for item in videos:
  460. video_id, flow_pool = item['videoId'], item['flowPool']
  461. key_name = f"{config_.LOCAL_DISTRIBUTE_COUNT_PREFIX}{video_id}:{flow_pool}"
  462. # 本地记录的分发数 - 1
  463. redis_helper.decr_key(key_name=key_name, amount=1, expire_time=15 * 60)
  464. # 对该视频做分发数检查
  465. cur_count = redis_helper.get_data_from_redis(key_name=key_name)
  466. # 无记录
  467. if cur_count is None:
  468. continue
  469. # 本地分发数 cur_count <= 0,从所有的流量召回池移除,删除本地分发记录key
  470. if int(cur_count) <= 0:
  471. redis_helper.del_keys(key_name=key_name)
  472. for app_name in config_.APP_TYPE:
  473. app_type = config_.APP_TYPE.get(app_name)
  474. flow_pool_key_list = [
  475. f"{config_.FLOWPOOL_KEY_NAME_PREFIX}{app_type}",
  476. f"{config_.QUICK_FLOWPOOL_KEY_NAME_PREFIX}{app_type}:{config_.QUICK_FLOW_POOL_ID}"
  477. ]
  478. for key in flow_pool_key_list:
  479. redis_helper.remove_value_from_zset(key_name=key, value=f"{video_id}-{flow_pool}")
  480. video_flow_pool_key_list = [
  481. f"{config_.QUICK_FLOWPOOL_VIDEO_INFO_KEY_NAME_PREFIX}{app_type}:{config_.QUICK_FLOW_POOL_ID}:{video_id}",
  482. f"{config_.FLOWPOOL_VIDEO_INFO_KEY_NAME_PREFIX}{app_type}:{video_id}"
  483. ]
  484. for key in video_flow_pool_key_list:
  485. redis_helper.remove_value_from_set(key_name=key, values=(flow_pool, ))
  486. # if redis_helper.key_exists(key_name=key_name):
  487. # # 该视频本地有记录,本地记录的分发数 - 1
  488. # redis_helper.decr_key(key_name=key_name, amount=1, expire_time=5 * 60)
  489. # else:
  490. # # 该视频本地无记录,接口获取的分发数 - 1
  491. # redis_helper.incr_key(key_name=key_name, amount=int(item['distributeCount']) - 1, expire_time=5 * 60)
  492. except Exception as e:
  493. log_.error('update_local_distribute_count error...')
  494. log_.error(traceback.format_exc())
  495. def get_religion_class_with_mid(mid, religion_class_name):
  496. """
  497. 判断用户是否属于对应的宗教类型
  498. :param mid: mid type-string
  499. :param religion_class_name: 宗教类型, type-string, (catholicism-天主教, christianity-基督教)
  500. :return: religion_class_flag, type-int, (0-否,1-是), 默认: 0
  501. """
  502. religion_class_flag = 0
  503. now_date = datetime.today()
  504. redis_helper = RedisHelper()
  505. if mid:
  506. hash_mid = hashlib.md5(mid.encode('utf-8')).hexdigest()
  507. hash_tag = hash_mid[-1:]
  508. key_name_prefix = config_.KEY_NAME_PREFIX_RELIGION_USER.get(religion_class_name, None)
  509. if key_name_prefix is None:
  510. return religion_class_flag
  511. key_name = f"{key_name_prefix}{hash_tag}:{datetime.strftime(now_date, '%Y%m%d')}"
  512. if not redis_helper.key_exists(key_name=key_name):
  513. key_name = f"{key_name_prefix}{hash_tag}:{datetime.strftime(now_date - timedelta(days=1), '%Y%m%d')}"
  514. if redis_helper.data_exists_with_set(key_name=key_name, value=mid):
  515. religion_class_flag = 1
  516. return religion_class_flag
  517. def get_recommend_params(recommend_type, ab_exp_info, ab_info_data, mid, app_type, page_type=0):
  518. """
  519. 根据实验分组给定对应的推荐参数
  520. :param recommend_type: 首页推荐和相关推荐区分参数(0-首页推荐,1-相关推荐)
  521. :param ab_exp_info: AB实验组参数
  522. :param ab_info_data: app实验组参数
  523. :param mid: mid
  524. :param app_type: app_type, type-int
  525. :param page_type: 页面区分参数,默认:0(首页)
  526. :return:
  527. """
  528. top_K = config_.K
  529. flow_pool_P = config_.P
  530. # 不获取人工干预数据标记
  531. no_op_flag = True
  532. expire_time = 3600
  533. old_video_index = -1
  534. # 获取对应的默认配置
  535. ab_initial_config = config_.INITIAL_CONFIG.get(app_type, None)
  536. if ab_initial_config is None:
  537. ab_initial_config = config_.INITIAL_CONFIG.get('other')
  538. param = config_.AB_EXP_CODE[ab_initial_config]
  539. ab_code = param.get('ab_code')
  540. rule_key = param.get('rule_key')
  541. data_key = param.get('data_key')
  542. rule_key_30day = param.get('30day_rule_key')
  543. shield_config = config_.SHIELD_CONFIG
  544. # 默认使用 095 实验的配置
  545. # ab_code = config_.AB_EXP_CODE['095'].get('ab_code')
  546. # rule_key = config_.AB_EXP_CODE['095'].get('rule_key')
  547. # data_key = config_.AB_EXP_CODE['095'].get('data_key')
  548. # rule_key_30day = None
  549. # 获取用户近30天是否有回流
  550. # user_30day_return_result = get_user_has30day_return(mid=mid)
  551. # 获取实验配置
  552. if ab_exp_info:
  553. ab_exp_code_list = []
  554. config_value_dict = {}
  555. for _, item in ab_exp_info.items():
  556. if not item:
  557. continue
  558. for ab_item in item:
  559. ab_exp_code = ab_item.get('abExpCode', None)
  560. if not ab_exp_code:
  561. continue
  562. ab_exp_code_list.append(str(ab_exp_code))
  563. config_value_dict[str(ab_exp_code)] = ab_item.get('configValue', None)
  564. # 流量池视频分发概率实验
  565. if '211' in ab_exp_code_list:
  566. flow_pool_P = 0.4
  567. elif '221' in ab_exp_code_list:
  568. flow_pool_P = 0
  569. # if '136' in ab_exp_code_list:
  570. # # 无回流 - 消费人群
  571. # if user_30day_return_result == 0:
  572. # param = config_.AB_EXP_CODE.get('136')
  573. # ab_code = param.get('ab_code')
  574. # expire_time = 3600
  575. # rule_key = param.get('rule_key')
  576. # data_key = param.get('data_key')
  577. # no_op_flag = True
  578. # elif '137' in ab_exp_code_list:
  579. # # 有回流 - 分享人群
  580. # if user_30day_return_result == 1:
  581. # param = config_.AB_EXP_CODE.get('137')
  582. # ab_code = param.get('ab_code')
  583. # expire_time = 3600
  584. # rule_key = param.get('rule_key')
  585. # data_key = param.get('data_key')
  586. # no_op_flag = True
  587. # elif '161' in ab_exp_code_list:
  588. # # 无回流 - 消费人群
  589. # if user_30day_return_result == 0:
  590. # param = config_.AB_EXP_CODE.get('136')
  591. # ab_code = param.get('ab_code')
  592. # expire_time = 3600
  593. # rule_key = param.get('rule_key')
  594. # data_key = param.get('data_key')
  595. # no_op_flag = True
  596. # # 有回流 - 分享人群
  597. # else:
  598. # param = config_.AB_EXP_CODE.get('137')
  599. # ab_code = param.get('ab_code')
  600. # expire_time = 3600
  601. # rule_key = param.get('rule_key')
  602. # data_key = param.get('data_key')
  603. # no_op_flag = True
  604. # elif '162' in ab_exp_code_list:
  605. # # 有回流
  606. # if user_30day_return_result == 1:
  607. # param = config_.AB_EXP_CODE.get('162')
  608. # ab_code = param.get('ab_code')
  609. # expire_time = 3600
  610. # rule_key = param.get('rule_key')
  611. # data_key = param.get('data_key')
  612. # no_op_flag = True
  613. # 老好看视频 宗教人群实验
  614. if '228' in ab_exp_code_list:
  615. # 天主教
  616. religion_param = config_.AB_EXP_CODE['228']
  617. religion_class_name = religion_param.get('religion_class_name')
  618. religion_class_flag = get_religion_class_with_mid(mid=mid, religion_class_name=religion_class_name)
  619. if religion_class_flag == 1:
  620. ab_code = religion_param.get('ab_code')
  621. rule_key = religion_param.get('rule_key')
  622. data_key = religion_param.get('data_key')
  623. rule_key_30day = religion_param.get('30day_rule_key')
  624. elif '229' in ab_exp_code_list:
  625. # 基督教
  626. religion_param = config_.AB_EXP_CODE['229']
  627. religion_class_name = religion_param.get('religion_class_name')
  628. religion_class_flag = get_religion_class_with_mid(mid=mid, religion_class_name=religion_class_name)
  629. if religion_class_flag == 1:
  630. ab_code = religion_param.get('ab_code')
  631. rule_key = religion_param.get('rule_key')
  632. data_key = religion_param.get('data_key')
  633. rule_key_30day = religion_param.get('30day_rule_key')
  634. else:
  635. for code, param in config_.AB_EXP_CODE.items():
  636. if code in ab_exp_code_list:
  637. ab_code = param.get('ab_code')
  638. rule_key = param.get('rule_key')
  639. data_key = param.get('data_key')
  640. rule_key_30day = param.get('30day_rule_key')
  641. shield_config = param.get('shield_config', config_.SHIELD_CONFIG)
  642. break
  643. """
  644. # 推荐条数 10->4 实验
  645. # if config_.AB_EXP_CODE['rec_size_home'] in ab_exp_code_list:
  646. # config_value = config_value_dict.get(config_.AB_EXP_CODE['rec_size_home'], None)
  647. # if config_value:
  648. # config_value = eval(str(config_value))
  649. # else:
  650. # config_value = {}
  651. # log_.info(f'config_value: {config_value}, type: {type(config_value)}')
  652. # size = int(config_value.get('size', 4))
  653. # top_K = int(config_value.get('K', 3))
  654. # flow_pool_P = float(config_value.get('P', 0.3))
  655. # else:
  656. # size = size
  657. # top_K = config_.K
  658. # flow_pool_P = config_.P
  659. # 算法实验相对对照组
  660. # if config_.AB_EXP_CODE['ab_initial'] in ab_exp_code_list:
  661. # ab_code = config_.AB_CODE['ab_initial']
  662. # expire_time = 24 * 3600
  663. # rule_key = config_.RULE_KEY['initial']
  664. # no_op_flag = True
  665. # 小时级更新-规则1 实验
  666. # elif config_.AB_EXP_CODE['rule_rank1'] in ab_exp_code_list:
  667. # ab_code = config_.AB_CODE['rank_by_h'].get('rule_rank1')
  668. # expire_time = 3600
  669. # rule_key = config_.RULE_KEY['rule_rank1']
  670. # no_op_flag = True
  671. # elif config_.AB_EXP_CODE['rule_rank2'] in ab_exp_code_list:
  672. # ab_code = config_.AB_CODE['rank_by_h'].get('rule_rank2')
  673. # expire_time = 3600
  674. # rule_key = config_.RULE_KEY['rule_rank2']
  675. # elif config_.AB_EXP_CODE['rule_rank3'] in ab_exp_code_list:
  676. # ab_code = config_.AB_CODE['rank_by_h'].get('rule_rank3')
  677. # expire_time = 3600
  678. # rule_key = config_.RULE_KEY['rule_rank3']
  679. # no_op_flag = True
  680. # elif config_.AB_EXP_CODE['rule_rank4'] in ab_exp_code_list:
  681. # ab_code = config_.AB_CODE['rank_by_h'].get('rule_rank4')
  682. # expire_time = 3600
  683. # rule_key = config_.RULE_KEY['rule_rank4']
  684. # elif config_.AB_EXP_CODE['rule_rank5'] in ab_exp_code_list:
  685. # ab_code = config_.AB_CODE['rank_by_h'].get('rule_rank5')
  686. # expire_time = 3600
  687. # rule_key = config_.RULE_KEY['rule_rank5']
  688. # elif config_.AB_EXP_CODE['day_rule_rank1'] in ab_exp_code_list:
  689. # ab_code = config_.AB_CODE['rank_by_day'].get('day_rule_rank1')
  690. # expire_time = 24 * 3600
  691. # rule_key = config_.RULE_KEY_DAY['day_rule_rank1']
  692. # no_op_flag = True
  693. # if config_.AB_EXP_CODE['rule_rank6'] in ab_exp_code_list:
  694. # ab_code = config_.AB_CODE['rank_by_h'].get('rule_rank6')
  695. # expire_time = 3600
  696. # rule_key = config_.RULE_KEY['rule_rank6']
  697. # no_op_flag = True
  698. # elif config_.AB_EXP_CODE['day_rule_rank2'] in ab_exp_code_list:
  699. # ab_code = config_.AB_CODE['rank_by_day'].get('day_rule_rank2')
  700. # expire_time = 24 * 3600
  701. # rule_key = config_.RULE_KEY_DAY['day_rule_rank2']
  702. # no_op_flag = True
  703. # elif config_.AB_EXP_CODE['region_rule_rank1'] in ab_exp_code_list:
  704. # ab_code = config_.AB_CODE['region_rank_by_h'].get('region_rule_rank1')
  705. # expire_time = 3600
  706. # rule_key = config_.RULE_KEY_REGION['region_rule_rank1']
  707. # no_op_flag = True
  708. # elif config_.AB_EXP_CODE['24h_rule_rank1'] in ab_exp_code_list:
  709. # ab_code = config_.AB_CODE['rank_by_24h'].get('24h_rule_rank1')
  710. # expire_time = 3600
  711. # rule_key = config_.RULE_KEY_24H['24h_rule_rank1']
  712. # no_op_flag = True
  713. # elif config_.AB_EXP_CODE['24h_rule_rank2'] in ab_exp_code_list:
  714. # ab_code = config_.AB_CODE['rank_by_24h'].get('24h_rule_rank2')
  715. # expire_time = 3600
  716. # rule_key = config_.RULE_KEY_24H['24h_rule_rank2']
  717. # no_op_flag = True
  718. # elif config_.AB_EXP_CODE['region_rule_rank2'] in ab_exp_code_list:
  719. # ab_code = config_.AB_CODE['region_rank_by_h'].get('region_rule_rank2')
  720. # expire_time = 3600
  721. # rule_key = config_.RULE_KEY_REGION['region_rule_rank2']
  722. # no_op_flag = True
  723. # if config_.AB_EXP_CODE['region_rule_rank3'] in ab_exp_code_list or\
  724. # config_.AB_EXP_CODE['region_rule_rank3_appType_19'] in ab_exp_code_list or\
  725. # config_.AB_EXP_CODE['region_rule_rank3_appType_4'] in ab_exp_code_list or\
  726. # config_.AB_EXP_CODE['region_rule_rank3_appType_6'] in ab_exp_code_list or\
  727. # config_.AB_EXP_CODE['region_rule_rank3_appType_18'] in ab_exp_code_list:
  728. # ab_code = config_.AB_CODE['region_rank_by_h'].get('region_rule_rank3')
  729. # expire_time = 3600
  730. # rule_key = config_.RULE_KEY_REGION['region_rule_rank3'].get('rule_key')
  731. # data_key = config_.RULE_KEY_REGION['region_rule_rank3'].get('data_key')
  732. # no_op_flag = True
  733. # if config_.AB_EXP_CODE['region_rule_rank4'] in ab_exp_code_list or\
  734. if config_.AB_EXP_CODE['region_rule_rank4_appType_19'] in ab_exp_code_list or \
  735. config_.AB_EXP_CODE['region_rule_rank4_appType_4'] in ab_exp_code_list or\
  736. config_.AB_EXP_CODE['region_rule_rank4_appType_6'] in ab_exp_code_list or\
  737. config_.AB_EXP_CODE['region_rule_rank4_appType_18'] in ab_exp_code_list:
  738. ab_code = config_.AB_CODE['region_rank_by_h'].get('region_rule_rank4')
  739. expire_time = 3600
  740. rule_key = config_.RULE_KEY_REGION['region_rule_rank4'].get('rule_key')
  741. data_key = config_.RULE_KEY_REGION['region_rule_rank4'].get('data_key')
  742. no_op_flag = True
  743. # elif config_.AB_EXP_CODE['region_rule_rank4_appType_5_data1'] in ab_exp_code_list:
  744. # ab_code = config_.AB_CODE['region_rank_by_h'].get('region_rule_rank4')
  745. # expire_time = 3600
  746. # rule_key = config_.RULE_KEY_REGION['region_rule_rank4_appType_5_data1'].get('rule_key')
  747. # data_key = config_.RULE_KEY_REGION['region_rule_rank4_appType_5_data1'].get('data_key')
  748. # no_op_flag = True
  749. # elif config_.AB_EXP_CODE['region_rule_rank3_appType_5_data2'] in ab_exp_code_list:
  750. # ab_code = config_.AB_CODE['region_rank_by_h'].get('region_rule_rank3_appType_5_data2')
  751. # expire_time = 3600
  752. # rule_key = config_.RULE_KEY_REGION['region_rule_rank3_appType_5_data2'].get('rule_key')
  753. # data_key = config_.RULE_KEY_REGION['region_rule_rank3_appType_5_data2'].get('data_key')
  754. # no_op_flag = True
  755. elif config_.AB_EXP_CODE['region_rule_rank4_appType_5_data3'] in ab_exp_code_list:
  756. ab_code = config_.AB_CODE['region_rank_by_h'].get('region_rule_rank4_appType_5_data3')
  757. expire_time = 3600
  758. rule_key = config_.RULE_KEY_REGION['region_rule_rank4_appType_5_data3'].get('rule_key')
  759. data_key = config_.RULE_KEY_REGION['region_rule_rank4_appType_5_data3'].get('data_key')
  760. no_op_flag = True
  761. elif config_.AB_EXP_CODE['region_rule_rank4_appType_5_data4'] in ab_exp_code_list:
  762. ab_code = config_.AB_CODE['region_rank_by_h'].get('region_rule_rank4_appType_5_data4')
  763. expire_time = 3600
  764. rule_key = config_.RULE_KEY_REGION['region_rule_rank4_appType_5_data4'].get('rule_key')
  765. data_key = config_.RULE_KEY_REGION['region_rule_rank4_appType_5_data4'].get('data_key')
  766. no_op_flag = True
  767. elif config_.AB_EXP_CODE['region_rule_rank4_appType_0_data2'] in ab_exp_code_list:
  768. ab_code = config_.AB_CODE['region_rank_by_h'].get('region_rule_rank4_appType_0_data2')
  769. expire_time = 3600
  770. rule_key = config_.RULE_KEY_REGION['region_rule_rank4_appType_0_data2'].get('rule_key')
  771. data_key = config_.RULE_KEY_REGION['region_rule_rank4_appType_0_data2'].get('data_key')
  772. no_op_flag = True
  773. # elif config_.AB_EXP_CODE['region_rule_rank4_appType_19_data2'] in ab_exp_code_list:
  774. # ab_code = config_.AB_CODE['region_rank_by_h'].get('region_rule_rank4_appType_19_data2')
  775. # expire_time = 3600
  776. # rule_key = config_.RULE_KEY_REGION['region_rule_rank4_appType_19_data2'].get('rule_key')
  777. # data_key = config_.RULE_KEY_REGION['region_rule_rank4_appType_19_data2'].get('data_key')
  778. # no_op_flag = True
  779. # elif config_.AB_EXP_CODE['region_rule_rank4_appType_19_data3'] in ab_exp_code_list:
  780. # ab_code = config_.AB_CODE['region_rank_by_h'].get('region_rule_rank4_appType_19_data3')
  781. # expire_time = 3600
  782. # rule_key = config_.RULE_KEY_REGION['region_rule_rank4_appType_19_data3'].get('rule_key')
  783. # data_key = config_.RULE_KEY_REGION['region_rule_rank4_appType_19_data3'].get('data_key')
  784. # no_op_flag = True
  785. elif config_.AB_EXP_CODE['region_rule_rank5_appType_0_data1'] in ab_exp_code_list:
  786. ab_code = config_.AB_CODE['region_rank_by_h'].get('region_rule_rank5_appType_0_data1')
  787. expire_time = 3600
  788. rule_key = config_.RULE_KEY_REGION['region_rule_rank5_appType_0_data1'].get('rule_key')
  789. data_key = config_.RULE_KEY_REGION['region_rule_rank5_appType_0_data1'].get('data_key')
  790. no_op_flag = True
  791. elif config_.AB_EXP_CODE['region_rule_rank4_appType_4_data2'] in ab_exp_code_list:
  792. ab_code = config_.AB_CODE['region_rank_by_h'].get('region_rule_rank4_appType_4_data2')
  793. expire_time = 3600
  794. rule_key = config_.RULE_KEY_REGION['region_rule_rank4_appType_4_data2'].get('rule_key')
  795. data_key = config_.RULE_KEY_REGION['region_rule_rank4_appType_4_data2'].get('data_key')
  796. no_op_flag = True
  797. elif config_.AB_EXP_CODE['region_rule_rank4_appType_4_data3'] in ab_exp_code_list:
  798. ab_code = config_.AB_CODE['region_rank_by_h'].get('region_rule_rank4_appType_4_data3')
  799. expire_time = 3600
  800. rule_key = config_.RULE_KEY_REGION['region_rule_rank4_appType_4_data3'].get('rule_key')
  801. data_key = config_.RULE_KEY_REGION['region_rule_rank4_appType_4_data3'].get('data_key')
  802. no_op_flag = True
  803. elif config_.AB_EXP_CODE['region_rule_rank4_appType_6_data2'] in ab_exp_code_list:
  804. ab_code = config_.AB_CODE['region_rank_by_h'].get('region_rule_rank4_appType_6_data2')
  805. expire_time = 3600
  806. rule_key = config_.RULE_KEY_REGION['region_rule_rank4_appType_6_data2'].get('rule_key')
  807. data_key = config_.RULE_KEY_REGION['region_rule_rank4_appType_6_data2'].get('data_key')
  808. no_op_flag = True
  809. elif config_.AB_EXP_CODE['region_rule_rank4_appType_6_data3'] in ab_exp_code_list:
  810. ab_code = config_.AB_CODE['region_rank_by_h'].get('region_rule_rank4_appType_6_data3')
  811. expire_time = 3600
  812. rule_key = config_.RULE_KEY_REGION['region_rule_rank4_appType_6_data3'].get('rule_key')
  813. data_key = config_.RULE_KEY_REGION['region_rule_rank4_appType_6_data3'].get('data_key')
  814. no_op_flag = True
  815. # elif config_.AB_EXP_CODE['region_rule_rank4_appType_18_data2'] in ab_exp_code_list:
  816. # ab_code = config_.AB_CODE['region_rank_by_h'].get('region_rule_rank4_appType_18_data2')
  817. # expire_time = 3600
  818. # rule_key = config_.RULE_KEY_REGION['region_rule_rank4_appType_18_data2'].get('rule_key')
  819. # data_key = config_.RULE_KEY_REGION['region_rule_rank4_appType_18_data2'].get('data_key')
  820. # no_op_flag = True
  821. # elif config_.AB_EXP_CODE['region_rule_rank6_appType_0_data1'] in ab_exp_code_list:
  822. # ab_code = config_.AB_CODE['region_rank_by_h'].get('region_rule_rank6_appType_0_data1')
  823. # expire_time = 3600
  824. # rule_key = config_.RULE_KEY_REGION['region_rule_rank6_appType_0_data1'].get('rule_key')
  825. # data_key = config_.RULE_KEY_REGION['region_rule_rank6_appType_0_data1'].get('data_key')
  826. # no_op_flag = True
  827. else:
  828. ab_code = config_.AB_CODE['initial']
  829. expire_time = 24 * 3600
  830. rule_key = config_.RULE_KEY_REGION['initial'].get('rule_key')
  831. data_key = config_.RULE_KEY_REGION['initial'].get('data_key')
  832. # # 老好看视频 / 票圈最惊奇 首页/相关推荐逻辑更新实验
  833. # if config_.AB_EXP_CODE['rov_rank_appType_18_19'] in ab_exp_code_list:
  834. # ab_code = config_.AB_CODE['rov_rank_appType_18_19']
  835. # expire_time = 3600
  836. # flow_pool_P = config_.P_18_19
  837. # no_op_flag = True
  838. #
  839. # elif config_.AB_EXP_CODE['rov_rank_appType_19'] in ab_exp_code_list:
  840. # ab_code = config_.AB_CODE['rov_rank_appType_19']
  841. # expire_time = 3600
  842. # top_K = 0
  843. # flow_pool_P = config_.P_18_19
  844. # no_op_flag = True
  845. #
  846. # elif config_.AB_EXP_CODE['top_video_relevant_appType_19'] in ab_exp_code_list and page_type == 2:
  847. # ab_code = config_.AB_CODE['top_video_relevant_appType_19']
  848. # expire_time = 3600
  849. # top_K = 1
  850. # flow_pool_P = config_.P_18_19
  851. # no_op_flag = True
  852. #
  853. # # 票圈最惊奇完整影视资源实验
  854. # elif config_.AB_EXP_CODE['whole_movies'] in ab_exp_code_list:
  855. # ab_code = config_.AB_CODE['whole_movies']
  856. # expire_time = 24 * 3600
  857. # no_op_flag = True
  858. # 老视频实验
  859. # if config_.AB_EXP_CODE['old_video'] in ab_exp_code_list:
  860. # ab_code = config_.AB_CODE['old_video']
  861. # no_op_flag = True
  862. # old_video_index = 2
  863. # else:
  864. # old_video_index = -1
  865. """
  866. # APP实验组
  867. if ab_info_data:
  868. ab_info_app = {}
  869. for page_code, item in json.loads(ab_info_data).items():
  870. if not item:
  871. continue
  872. ab_info_code = item.get('eventId', None)
  873. if ab_info_code:
  874. ab_info_app[page_code] = ab_info_code
  875. # print(f"======{ab_info_app}")
  876. # 首页推荐
  877. if recommend_type == 0:
  878. app_ab_code = ab_info_app.get('10003', None)
  879. for code, param in config_.APP_AB_CODE['10003'].items():
  880. if code == app_ab_code:
  881. ab_code = param.get('ab_code')
  882. rule_key = param.get('rule_key')
  883. data_key = param.get('data_key')
  884. break
  885. # # 相关推荐
  886. # elif recommend_type == 1:
  887. # if config_.APP_AB_CODE['10037'] == ab_info_app.get('10037', None):
  888. # ab_code = config_.AB_CODE['region_rank_by_h'].get('region_rule_rank4')
  889. # expire_time = 3600
  890. # rule_key = 'rule3'
  891. # data_key = 'data1'
  892. # no_op_flag = True
  893. return top_K, flow_pool_P, ab_code, rule_key, data_key, expire_time, no_op_flag, old_video_index, rule_key_30day, shield_config
  894. def video_homepage_recommend(request_id, mid, uid, size, app_type, algo_type,
  895. client_info, ab_exp_info, params, ab_info_data, version_audit_status):
  896. """
  897. 首页线上推荐逻辑
  898. :param request_id: request_id
  899. :param mid: mid type-string
  900. :param uid: uid type-string
  901. :param size: 请求视频数量 type-int
  902. :param app_type: 产品标识 type-int
  903. :param algo_type: 算法类型 type-string
  904. :param client_info: 用户位置信息 {"country": "国家", "province": "省份", "city": "城市"}
  905. :param ab_exp_info: ab实验分组参数 [{"expItemId":1, "configValue":{"size":4, "K":3, ...}}, ...]
  906. :param params:
  907. :param ab_info_data: app实验分组参数
  908. :param version_audit_status: 小程序版本审核参数:1-审核中,2-审核通过
  909. :return:
  910. """
  911. # 对 vlog 切换10%的流量做实验
  912. # 对mid进行哈希
  913. # hash_mid = hashlib.md5(mid.encode('utf-8')).hexdigest()
  914. # if app_type in config_.AB_TEST['rank_by_h'] and hash_mid[-1:] in ['8', '0', 'a', 'b']:
  915. # # 简单召回 - 排序 - 兜底
  916. # rank_result, last_rov_recall_key = video_recommend(mid=mid, uid=uid, size=size, app_type=app_type,
  917. # algo_type=algo_type, client_info=client_info,
  918. # expire_time=3600,
  919. # ab_code=config_.AB_CODE['rank_by_h'])
  920. # # ab-test
  921. # result = ab_test_op(rank_result=rank_result,
  922. # ab_code_list=[config_.AB_CODE['position_insert']],
  923. # app_type=app_type, mid=mid, uid=uid)
  924. # # redis数据刷新
  925. # update_redis_data(result=result, app_type=app_type, mid=mid, last_rov_recall_key=last_rov_recall_key,
  926. # expire_time=3600)
  927. # if app_type == config_.APP_TYPE['APP']:
  928. # # 票圈视频APP
  929. # top_K = config_.K
  930. # flow_pool_P = config_.P
  931. # # 简单召回 - 排序 - 兜底
  932. # rank_result, last_rov_recall_key = video_recommend(request_id=request_id,
  933. # mid=mid, uid=uid, app_type=app_type,
  934. # size=size, top_K=top_K, flow_pool_P=flow_pool_P,
  935. # algo_type=algo_type, client_info=client_info,
  936. # expire_time=12 * 3600, params=params)
  937. # # ab-test
  938. # # result = ab_test_op(rank_result=rank_result,
  939. # # ab_code_list=[config_.AB_CODE['position_insert']],
  940. # # app_type=app_type, mid=mid, uid=uid)
  941. # # redis数据刷新
  942. # update_redis_data(result=rank_result, app_type=app_type, mid=mid, last_rov_recall_key=last_rov_recall_key,
  943. # top_K=top_K, expire_time=12 * 3600)
  944. #
  945. # else:
  946. recommend_result = {}
  947. param_st = time.time()
  948. # 特殊mid 和 小程序审核版本推荐处理
  949. if mid in get_special_mid_list() or version_audit_status == 1:
  950. rank_result = special_mid_recommend(request_id=request_id, mid=mid, uid=uid, app_type=app_type, size=size)
  951. recommend_result['videos'] = rank_result
  952. return recommend_result
  953. # 普通mid推荐处理
  954. top_K, flow_pool_P, ab_code, rule_key, data_key, expire_time, \
  955. no_op_flag, old_video_index, rule_key_30day, shield_config = \
  956. get_recommend_params(recommend_type=0, ab_exp_info=ab_exp_info, ab_info_data=ab_info_data, mid=mid,
  957. app_type=app_type)
  958. # log_.info({
  959. # 'logTimestamp': int(time.time() * 1000),
  960. # 'request_id': request_id,
  961. # 'app_type': app_type,
  962. # 'mid': mid,
  963. # 'uid': uid,
  964. # 'operation': 'get_recommend_params',
  965. # 'executeTime': (time.time() - param_st) * 1000
  966. # })
  967. recommend_result['getRecommendParamsTime'] = (time.time() - param_st) * 1000
  968. # 简单召回 - 排序 - 兜底
  969. get_result_st = time.time()
  970. result = video_recommend(request_id=request_id,
  971. mid=mid, uid=uid, app_type=app_type,
  972. size=size, top_K=top_K, flow_pool_P=flow_pool_P,
  973. algo_type=algo_type, client_info=client_info,
  974. ab_code=ab_code, expire_time=expire_time,
  975. rule_key=rule_key, data_key=data_key,
  976. no_op_flag=no_op_flag, old_video_index=old_video_index,
  977. params=params, rule_key_30day=rule_key_30day, shield_config=shield_config)
  978. # log_.info({
  979. # 'logTimestamp': int(time.time() * 1000),
  980. # 'request_id': request_id,
  981. # 'app_type': app_type,
  982. # 'mid': mid,
  983. # 'uid': uid,
  984. # 'operation': 'get_recommend_result',
  985. # 'executeTime': (time.time() - get_result_st) * 1000
  986. # })
  987. recommend_result['recommendOperation'] = result
  988. rank_result = result.get('rankResult')
  989. recommend_result['videos'] = rank_result
  990. recommend_result['getRecommendResultTime'] = (time.time() - get_result_st) * 1000
  991. # ab-test
  992. # result = ab_test_op(rank_result=rank_result,
  993. # ab_code_list=[config_.AB_CODE['position_insert']],
  994. # app_type=app_type, mid=mid, uid=uid)
  995. # redis数据刷新
  996. update_redis_st = time.time()
  997. update_redis_data(result=rank_result, app_type=app_type, mid=mid, top_K=top_K)
  998. # log_.info({
  999. # 'logTimestamp': int(time.time() * 1000),
  1000. # 'request_id': request_id,
  1001. # 'app_type': app_type,
  1002. # 'mid': mid,
  1003. # 'uid': uid,
  1004. # 'operation': 'update_redis_data',
  1005. # 'executeTime': (time.time() - update_redis_st) * 1000
  1006. # })
  1007. recommend_result['updateRedisDataTime'] = (time.time() - update_redis_st) * 1000
  1008. return recommend_result
  1009. # return rank_result
  1010. def video_relevant_recommend(request_id, video_id, mid, uid, size, app_type, ab_exp_info, client_info,
  1011. page_type, params, ab_info_data, version_audit_status):
  1012. """
  1013. 相关推荐逻辑
  1014. :param request_id: request_id
  1015. :param video_id: 相关推荐的头部视频id
  1016. :param mid: mid type-string
  1017. :param uid: uid type-string
  1018. :param size: 请求视频数量 type-int
  1019. :param app_type: 产品标识 type-int
  1020. :param ab_exp_info: ab实验分组参数 [{"expItemId":1, "configValue":{"size":4, "K":3, ...}}, ...]
  1021. :param client_info: 地域参数
  1022. :param page_type: 页面区分参数 1:详情页;2:分享页
  1023. :param params:
  1024. :param ab_info_data: app实验分组参数
  1025. :param version_audit_status: 小程序版本审核参数:1-审核中,2-审核通过
  1026. :return: videos type-list
  1027. """
  1028. recommend_result = {}
  1029. param_st = time.time()
  1030. # 特殊mid 和 小程序审核版本推荐处理
  1031. if mid in get_special_mid_list() or version_audit_status == 1:
  1032. rank_result = special_mid_recommend(request_id=request_id, mid=mid, uid=uid, app_type=app_type, size=size)
  1033. recommend_result['videos'] = rank_result
  1034. return recommend_result
  1035. # return rank_result
  1036. # 普通mid推荐处理
  1037. top_K, flow_pool_P, ab_code, rule_key, data_key, expire_time, \
  1038. no_op_flag, old_video_index, rule_key_30day, shield_config = \
  1039. get_recommend_params(recommend_type=1, ab_exp_info=ab_exp_info, ab_info_data=ab_info_data, page_type=page_type,
  1040. mid=mid, app_type=app_type)
  1041. # log_.info({
  1042. # 'logTimestamp': int(time.time() * 1000),
  1043. # 'request_id': request_id,
  1044. # 'app_type': app_type,
  1045. # 'mid': mid,
  1046. # 'uid': uid,
  1047. # 'operation': 'get_recommend_params',
  1048. # 'executeTime': (time.time() - param_st) * 1000
  1049. # })
  1050. recommend_result['getRecommendParamsTime'] = (time.time() - param_st) * 1000
  1051. # 简单召回 - 排序 - 兜底
  1052. get_result_st = time.time()
  1053. result = video_recommend(request_id=request_id,
  1054. mid=mid, uid=uid, app_type=app_type,
  1055. size=size, top_K=top_K, flow_pool_P=flow_pool_P,
  1056. algo_type='', client_info=client_info,
  1057. ab_code=ab_code, expire_time=expire_time,
  1058. rule_key=rule_key, data_key=data_key, no_op_flag=no_op_flag,
  1059. old_video_index=old_video_index, video_id=video_id,
  1060. params=params, rule_key_30day=rule_key_30day, shield_config=shield_config)
  1061. # log_.info({
  1062. # 'logTimestamp': int(time.time() * 1000),
  1063. # 'request_id': request_id,
  1064. # 'app_type': app_type,
  1065. # 'mid': mid,
  1066. # 'uid': uid,
  1067. # 'operation': 'get_recommend_result',
  1068. # 'executeTime': (time.time() - get_result_st) * 1000
  1069. # })
  1070. recommend_result['recommendOperation'] = result
  1071. rank_result = result.get('rankResult')
  1072. recommend_result['videos'] = rank_result
  1073. recommend_result['getRecommendResultTime'] = (time.time() - get_result_st) * 1000
  1074. # ab-test
  1075. # result = ab_test_op(rank_result=rank_result,
  1076. # ab_code_list=[config_.AB_CODE['position_insert'], config_.AB_CODE['relevant_video_op']],
  1077. # app_type=app_type, mid=mid, uid=uid, head_vid=video_id, size=size)
  1078. # redis数据刷新
  1079. update_redis_st = time.time()
  1080. update_redis_data(result=rank_result, app_type=app_type, mid=mid, top_K=top_K)
  1081. # log_.info({
  1082. # 'logTimestamp': int(time.time() * 1000),
  1083. # 'request_id': request_id,
  1084. # 'app_type': app_type,
  1085. # 'mid': mid,
  1086. # 'uid': uid,
  1087. # 'operation': 'update_redis_data',
  1088. # 'executeTime': (time.time() - update_redis_st) * 1000
  1089. # })
  1090. recommend_result['updateRedisDataTime'] = (time.time() - update_redis_st) * 1000
  1091. return recommend_result
  1092. # return rank_result
  1093. def special_mid_recommend(request_id, mid, uid, app_type, size,
  1094. ab_code=config_.AB_CODE['special_mid'],
  1095. push_from=config_.PUSH_FROM['special_mid'],
  1096. expire_time=24*3600):
  1097. redis_helper = RedisHelper()
  1098. # 特殊mid推荐指定视频列表
  1099. pool_recall = PoolRecall(request_id=request_id, app_type=app_type,
  1100. mid=mid, uid=uid, ab_code=ab_code)
  1101. # 获取相关redis key
  1102. special_key_name, redis_date = pool_recall.get_pool_redis_key(pool_type='special')
  1103. # 用户上一次在rov召回池对应的位置
  1104. last_special_recall_key = f'{config_.LAST_VIDEO_FROM_SPECIAL_POOL_PREFIX}{app_type}:{mid}:{redis_date}'
  1105. value = redis_helper.get_data_from_redis(last_special_recall_key)
  1106. if value:
  1107. idx = redis_helper.get_index_with_data(special_key_name, value)
  1108. if not idx:
  1109. idx = 0
  1110. else:
  1111. idx += 1
  1112. else:
  1113. idx = 0
  1114. recall_result = []
  1115. # 每次获取的视频数
  1116. get_size = size * 5
  1117. # 记录获取频次
  1118. freq = 0
  1119. while len(recall_result) < size:
  1120. freq += 1
  1121. if freq > config_.MAX_FREQ_FROM_ROV_POOL:
  1122. break
  1123. # 获取数据
  1124. data = redis_helper.get_data_zset_with_index(key_name=special_key_name,
  1125. start=idx, end=idx + get_size - 1,
  1126. with_scores=True)
  1127. if not data:
  1128. break
  1129. # 获取视频id,并转换类型为int,并存储为key-value{videoId: score}
  1130. # 添加视频源参数 pushFrom, abCode
  1131. temp_result = [{'videoId': int(value[0]), 'rovScore': value[1],
  1132. 'pushFrom': push_from, 'abCode': ab_code}
  1133. for value in data]
  1134. recall_result.extend(temp_result)
  1135. idx += get_size
  1136. # 将此次获取的末位视频id同步刷新到Redis中,方便下次快速定位到召回位置,过期时间为1天
  1137. if mid and recall_result:
  1138. # mid为空时,不做记录
  1139. redis_helper.set_data_to_redis(key_name=last_special_recall_key,
  1140. value=recall_result[:size][-1]['videoId'],
  1141. expire_time=expire_time)
  1142. return recall_result[:size]
  1143. def get_special_mid_list():
  1144. redis_helper = RedisHelper()
  1145. special_mid_list = redis_helper.get_data_from_set(key_name=config_.KEY_NAME_SPECIAL_MID)
  1146. if special_mid_list:
  1147. return special_mid_list
  1148. else:
  1149. return []
  1150. if __name__ == '__main__':
  1151. videos = [
  1152. {"videoId": 10136461, "rovScore": 99.971, "pushFrom": "recall_pool", "abCode": 10000},
  1153. {"videoId": 10239014, "rovScore": 99.97, "pushFrom": "recall_pool", "abCode": 10000},
  1154. {"videoId": 9851154, "rovScore": 99.969, "pushFrom": "recall_pool", "abCode": 10000},
  1155. {"videoId": 10104347, "rovScore": 99.968, "pushFrom": "recall_pool", "abCode": 10000},
  1156. {"videoId": 10141507, "rovScore": 99.967, "pushFrom": "recall_pool", "abCode": 10000},
  1157. {"videoId": 10292817, "flowPool": "2#6#2#1641780979606", "rovScore": 53.926690610816486,
  1158. "pushFrom": "flow_pool", "abCode": 10000},
  1159. {"videoId": 10224932, "flowPool": "2#5#1#1641800279644", "rovScore": 53.47890460059617, "pushFrom": "flow_pool",
  1160. "abCode": 10000},
  1161. {"videoId": 9943255, "rovScore": 99.966, "pushFrom": "recall_pool", "abCode": 10000},
  1162. {"videoId": 10282970, "flowPool": "2#5#1#1641784814103", "rovScore": 52.682815076325575,
  1163. "pushFrom": "flow_pool", "abCode": 10000},
  1164. {"videoId": 10282205, "rovScore": 99.965, "pushFrom": "recall_pool", "abCode": 10000}
  1165. ]
  1166. res = relevant_video_top_recommend(app_type=4, mid='', uid=1111, head_vid=123, videos=videos, size=10)
  1167. print(res)