recommend.py 58 KB

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