recommend.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. import time
  2. import multiprocessing
  3. import traceback
  4. from datetime import datetime
  5. from log import Log
  6. from config import set_config
  7. from video_recall import PoolRecall
  8. from video_rank import video_rank, bottom_strategy
  9. from db_helper import RedisHelper
  10. log_ = Log()
  11. config_ = set_config()
  12. def video_recommend(mid, uid, size, app_type, algo_type):
  13. """
  14. 首页线上推荐逻辑
  15. :param mid: mid type-string
  16. :param uid: uid type-string
  17. :param size: 请求视频数量 type-int
  18. :param app_type: 产品标识 type-int
  19. :param algo_type: 算法类型 type-string
  20. :return:
  21. """
  22. ab_code = config_.AB_CODE
  23. # ####### 多进程召回
  24. start_recall = time.time()
  25. log_.info('====== recall')
  26. cores = multiprocessing.cpu_count()
  27. pool = multiprocessing.Pool(processes=cores)
  28. pool_recall = PoolRecall(app_type=app_type, mid=mid, uid=uid, ab_code=ab_code)
  29. _, last_rov_recall_key, _ = pool_recall.get_video_last_idx()
  30. pool_list = [
  31. # rov召回池
  32. pool.apply_async(pool_recall.rov_pool_recall, (size,)),
  33. # 流量池
  34. pool.apply_async(pool_recall.flow_pool_recall, (size,))
  35. ]
  36. recall_result_list = [p.get() for p in pool_list]
  37. pool.close()
  38. pool.join()
  39. end_recall = time.time()
  40. log_.info('mid: {}, uid: {}, recall: {}, execute time = {}ms'.format(
  41. mid, uid, recall_result_list, (end_recall - start_recall) * 1000))
  42. # ####### 排序
  43. start_rank = time.time()
  44. log_.info('====== rank')
  45. data = {
  46. 'rov_pool_recall': recall_result_list[0],
  47. 'flow_pool_recall': recall_result_list[1]
  48. }
  49. rank_result = video_rank(data=data, size=size)
  50. end_rank = time.time()
  51. log_.info('mid: {}, uid: {}, rank_result: {}, execute time = {}ms'.format(
  52. mid, uid, rank_result, (end_rank - start_rank) * 1000))
  53. if not rank_result:
  54. # 兜底策略
  55. log_.info('====== bottom strategy')
  56. start_bottom = time.time()
  57. rank_result = bottom_strategy(size=size, app_type=app_type, ab_code=ab_code)
  58. end_bottom = time.time()
  59. log_.info('mid: {}, uid: {}, bottom strategy result: {}, execute time = {}ms'.format(
  60. mid, uid, rank_result, (end_bottom - start_bottom) * 1000))
  61. # ####### redis数据刷新
  62. log_.info('====== update redis')
  63. # 预曝光数据同步刷新到Redis, 过期时间为0.5h
  64. redis_helper = RedisHelper()
  65. preview_key_name = config_.PREVIEW_KEY_PREFIX + '{}.{}'.format(app_type, mid)
  66. preview_video_ids = [item['videoId'] for item in rank_result]
  67. if preview_video_ids:
  68. redis_helper.add_data_with_set(key_name=preview_key_name, values=tuple(preview_video_ids), expire_time=30*60)
  69. log_.info('preview redis update success!')
  70. # 将此次获取的ROV召回池config_.K末位视频id同步刷新到Redis中,方便下次快速定位到召回位置,过期时间为1天
  71. rov_recall_video = [item['videoId'] for item in rank_result if item['pushFrom'] == 'recall_pool']
  72. if 0 < len(rov_recall_video) <= config_.K:
  73. redis_helper.set_data_to_redis(key_name=last_rov_recall_key, value=rov_recall_video[-1])
  74. elif len(rov_recall_video) > config_.K:
  75. redis_helper.set_data_to_redis(key_name=last_rov_recall_key, value=rov_recall_video[config_.K - 1])
  76. log_.info('last video redis update success!')
  77. # 将此次分发的流量池视频,对 本地分发数-1 进行记录
  78. flow_recall_video = [item for item in rank_result if item['pushFrom'] == 'flow_pool']
  79. if flow_recall_video:
  80. update_local_distribute_count(flow_recall_video)
  81. log_.info('update local distribute count success!')
  82. return rank_result
  83. def update_local_distribute_count(videos):
  84. """
  85. 更新本地分发数
  86. :param videos: 视频列表 type-list [{'videoId':'', 'flowPool':'', 'distributeCount': '',
  87. 'rovScore': '', 'pushFrom': 'flow_pool', 'abCode': self.ab_code}, ....]
  88. :return:
  89. """
  90. try:
  91. redis_h = datetime.now().hour
  92. if datetime.now().minute >= 30:
  93. redis_h += 0.5
  94. key_name = config_.LOCAL_DISTRIBUTE_COUNT_PREFIX + str(redis_h)
  95. print(key_name)
  96. redis_helper = RedisHelper()
  97. update_data = {}
  98. for item in videos:
  99. video = '{}-{}'.format(item['videoId'], item['flowPool'])
  100. current_count = redis_helper.get_score_with_value(key_name=key_name, value=video)
  101. if current_count is not None:
  102. # 该视频本地有记录,本地记录的分发数 - 1
  103. new_count = current_count - 1
  104. else:
  105. # 该视频本地无记录,接口获取的分发数 - 1
  106. new_count = int(item['distributeCount']) - 1
  107. update_data[video] = new_count
  108. log_.info('now update video local distribute count: {}, key: {}'.format(update_data, key_name))
  109. # 更新redis中的数据
  110. redis_helper.add_data_with_zset(key_name=key_name, data=update_data, expire_time=0.5*3600)
  111. except Exception as e:
  112. log_.error(traceback.format_exc())
  113. if __name__ == '__main__':
  114. videos = [{'videoId': '12345', 'flowPool': '133#442#2', 'distributeCount': 10}]
  115. update_local_distribute_count(videos)