region_rule_rank_h_v2.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  1. # -*- coding: utf-8 -*-
  2. # @ModuleName: region_rule_rank_h
  3. # @Author: Liqian
  4. # @Time: 2022/5/5 15:54
  5. # @Software: PyCharm
  6. import multiprocessing
  7. import os
  8. import sys
  9. import time
  10. import traceback
  11. import gevent
  12. import datetime
  13. import pandas as pd
  14. import math
  15. from functools import reduce
  16. from odps import ODPS
  17. from threading import Timer, Thread
  18. from utils import MysqlHelper, RedisHelper, get_data_from_odps, filter_video_status, filter_shield_video, \
  19. check_table_partition_exits, filter_video_status_app, send_msg_to_feishu, filter_political_videos
  20. from config import set_config
  21. from log import Log
  22. from check_video_limit_distribute import update_limit_video_score
  23. # os.environ['NUMEXPR_MAX_THREADS'] = '16'
  24. config_, _ = set_config()
  25. log_ = Log()
  26. region_code = config_.REGION_CODE
  27. features = [
  28. 'apptype',
  29. 'code',
  30. 'videoid',
  31. 'lastonehour_preview', # 过去1小时预曝光人数 - 区分地域
  32. 'lastonehour_view', # 过去1小时曝光人数 - 区分地域
  33. 'lastonehour_play', # 过去1小时播放人数 - 区分地域
  34. 'lastonehour_share', # 过去1小时分享人数 - 区分地域
  35. 'lastonehour_return', # 过去1小时分享,过去1小时回流人数 - 区分地域
  36. 'lastonehour_preview_total', # 过去1小时预曝光次数 - 区分地域
  37. 'lastonehour_view_total', # 过去1小时曝光次数 - 区分地域
  38. 'lastonehour_play_total', # 过去1小时播放次数 - 区分地域
  39. 'lastonehour_share_total', # 过去1小时分享次数 - 区分地域
  40. 'platform_return',
  41. 'lastonehour_show', # 不区分地域
  42. 'lastonehour_show_region', # 地域分组
  43. 'lasttwohour_share', # h-2小时分享人数
  44. 'lasttwohour_return_now', # h-2分享,过去1小时回流人数
  45. 'lasttwohour_return', # h-2分享,h-2回流人数
  46. 'lastthreehour_share', # h-3小时分享人数
  47. 'lastthreehour_return_now', # h-3分享,过去1小时回流人数
  48. 'lastthreehour_return', # h-3分享,h-3回流人数
  49. 'lastonehour_return_new', # 过去1小时分享,过去1小时回流人数(回流统计为对应地域分享带回的回流,分享限制地域,回流不限制地域)
  50. 'lasttwohour_return_now_new', # h-2分享,过去1小时回流人数(回流统计为对应地域分享带回的回流,分享限制地域,回流不限制地域)
  51. 'lasttwohour_return_new', # h-2分享,h-2回流人数(回流统计为对应地域分享带回的回流,分享限制地域,回流不限制地域)
  52. 'lastthreehour_return_now_new', # h-3分享,过去1小时回流人数(回流统计为对应地域分享带回的回流,分享限制地域,回流不限制地域)
  53. 'lastthreehour_return_new', # h-3分享,h-3回流人数(回流统计为对应地域分享带回的回流,分享限制地域,回流不限制地域)
  54. 'platform_return_new', # 平台分发回流(回流统计为对应地域分享带回的回流,分享限制地域,回流不限制地域)
  55. 'lastonehour_allreturn',
  56. 'lastonehour_allreturn_sharecnt'
  57. ]
  58. def get_region_code(region):
  59. """获取省份对应的code"""
  60. mysql_helper = MysqlHelper(mysql_info=config_.MYSQL_INFO)
  61. sql = f"SELECT ad_code FROM region_adcode WHERE parent_id = 0 AND region LIKE '{region}%';"
  62. ad_code = mysql_helper.get_data(sql=sql)
  63. return ad_code[0][0]
  64. def h_data_check(project, table, now_date):
  65. """检查数据是否准备好"""
  66. odps = ODPS(
  67. access_id=config_.ODPS_CONFIG['ACCESSID'],
  68. secret_access_key=config_.ODPS_CONFIG['ACCESSKEY'],
  69. project=project,
  70. endpoint=config_.ODPS_CONFIG['ENDPOINT'],
  71. connect_timeout=3000,
  72. read_timeout=500000,
  73. pool_maxsize=1000,
  74. pool_connections=1000
  75. )
  76. try:
  77. dt = datetime.datetime.strftime(now_date, '%Y%m%d%H')
  78. # 测试 张博
  79. check_res = check_table_partition_exits(date=dt, project=project, table=table)
  80. if check_res:
  81. sql = f'select * from {project}.{table} where dt = "{dt}"'
  82. print("zhangbo-sql-是否有数据")
  83. print(sql)
  84. with odps.execute_sql(sql=sql).open_reader() as reader:
  85. data_count = reader.count
  86. else:
  87. data_count = 0
  88. except Exception as e:
  89. data_count = 0
  90. return data_count
  91. def get_rov_redis_key(now_date):
  92. """获取rov模型结果存放key"""
  93. redis_helper = RedisHelper()
  94. now_dt = datetime.datetime.strftime(now_date, '%Y%m%d')
  95. key_name = f'{config_.RECALL_KEY_NAME_PREFIX}{now_dt}'
  96. if not redis_helper.key_exists(key_name=key_name):
  97. pre_dt = datetime.datetime.strftime(now_date - datetime.timedelta(days=1), '%Y%m%d')
  98. key_name = f'{config_.RECALL_KEY_NAME_PREFIX}{pre_dt}'
  99. return key_name
  100. def get_day_30day_videos(now_date, data_key, rule_key):
  101. """获取天级更新相对30天的视频id"""
  102. redis_helper = RedisHelper()
  103. day_30day_recall_key_prefix = config_.RECALL_KEY_NAME_PREFIX_30DAY
  104. now_dt = datetime.datetime.strftime(now_date, '%Y%m%d')
  105. day_30day_recall_key_name = f"{day_30day_recall_key_prefix}{data_key}:{rule_key}:{now_dt}"
  106. if not redis_helper.key_exists(key_name=day_30day_recall_key_name):
  107. redis_dt = datetime.datetime.strftime((now_date - datetime.timedelta(days=1)), '%Y%m%d')
  108. day_30day_recall_key_name = f"{day_30day_recall_key_prefix}{data_key}:{rule_key}:{redis_dt}"
  109. data = redis_helper.get_all_data_from_zset(key_name=day_30day_recall_key_name, with_scores=True)
  110. if data is None:
  111. return None
  112. video_ids = [int(video_id) for video_id, _ in data]
  113. return video_ids
  114. def get_feature_data(project, table, now_date):
  115. """获取特征数据"""
  116. dt = datetime.datetime.strftime(now_date, '%Y%m%d%H')
  117. # 张博 测试
  118. records = get_data_from_odps(date=dt, project=project, table=table)
  119. feature_data = []
  120. for record in records:
  121. item = {}
  122. for feature_name in features:
  123. item[feature_name] = record[feature_name]
  124. feature_data.append(item)
  125. feature_df = pd.DataFrame(feature_data)
  126. return feature_df
  127. def cal_score_initial_20240223(df, param):
  128. """
  129. 计算score
  130. :param df: 特征数据
  131. :param param: 规则参数
  132. :return:
  133. """
  134. log_.info("进入了cal_score_initial_20240223")
  135. df = df.fillna(0)
  136. df['share_rate'] = df['lastonehour_share'] / (df['lastonehour_play'] + 1000)
  137. df['back_rate'] = df['lastonehour_return'] / (df['lastonehour_share'] + 10)
  138. df['back_rate_new'] = (df['lastonehour_return'] + 1) / (df['lastonehour_share'] + 10)
  139. df['back_rate_all'] = df['lastonehour_allreturn'] / (df['lastonehour_allreturn_sharecnt'] + 10)
  140. df['log_back'] = (df['lastonehour_return'] + 1).apply(math.log)
  141. df['log_back_all'] = (df['lastonehour_allreturn'] + 1).apply(math.log)
  142. if param.get('view_type', None) == 'video-show':
  143. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_show'] + 1000)
  144. elif param.get('view_type', None) == 'video-show-region':
  145. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_show_region'] + 1000)
  146. else:
  147. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_preview'] + 1000)
  148. df['K2'] = df['ctr'].apply(lambda x: 0.6 if x > 0.6 else x)
  149. df['platform_return_rate'] = df['platform_return'] / df['lastonehour_return']
  150. df['score'] = df['share_rate'] * (
  151. df['back_rate_new'] + 0.01 * df['back_rate_all']
  152. ) * (
  153. df['log_back'] + 0.01 * df['log_back_all']
  154. ) * df['K2']
  155. df = df.sort_values(by=['score'], ascending=False)
  156. return df
  157. def cal_score_initial(df, param):
  158. """
  159. 计算score
  160. :param df: 特征数据
  161. :param param: 规则参数
  162. :return:
  163. """
  164. # score计算公式: sharerate*backrate*logback*ctr
  165. # sharerate = lastonehour_share/(lastonehour_play+1000)
  166. # backrate = lastonehour_return/(lastonehour_share+10)
  167. # ctr = lastonehour_play/(lastonehour_preview+1000), 对ctr限最大值:K2 = 0.6 if ctr > 0.6 else ctr
  168. # score = sharerate * backrate * LOG(lastonehour_return+1) * K2
  169. df = df.fillna(0)
  170. df['share_rate'] = df['lastonehour_share'] / (df['lastonehour_play'] + 1000)
  171. df['back_rate'] = df['lastonehour_return'] / (df['lastonehour_share'] + 10)
  172. df['log_back'] = (df['lastonehour_return'] + 1).apply(math.log)
  173. if param.get('view_type', None) == 'video-show':
  174. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_show'] + 1000)
  175. elif param.get('view_type', None) == 'video-show-region':
  176. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_show_region'] + 1000)
  177. else:
  178. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_preview'] + 1000)
  179. df['K2'] = df['ctr'].apply(lambda x: 0.6 if x > 0.6 else x)
  180. df['platform_return_rate'] = df['platform_return'] / df['lastonehour_return']
  181. df['score1'] = df['share_rate'] * df['back_rate'] * df['log_back'] * df['K2']
  182. click_score_rate = param.get('click_score_rate', None)
  183. back_score_rate = param.get('click_score_rate', None)
  184. if click_score_rate is not None:
  185. df['score'] = (1 - click_score_rate) * df['score1'] + click_score_rate * df['K2']
  186. elif back_score_rate is not None:
  187. df['score'] = (1 - back_score_rate) * df['score1'] + back_score_rate * df['back_rate']
  188. else:
  189. df['score'] = df['score1']
  190. df = df.sort_values(by=['score'], ascending=False)
  191. return df
  192. def cal_score_add_return(df, param):
  193. # score计算公式: sharerate*(backrate*logback + backrate2*logback_now2 + backrate3*logback_now3)*ctr
  194. # sharerate = lastonehour_share/(lastonehour_play+1000)
  195. # backrate = lastonehour_return/(lastonehour_share+10)
  196. # backrate2 = lasttwohour_return_now/(lasttwohour_share+10)
  197. # backrate3 = lastthreehour_return_now/(lastthreehour_share+10)
  198. # ctr = lastonehour_play/(lastonehour_preview+1000), 对ctr限最大值:K2 = 0.6 if ctr > 0.6 else ctr
  199. # score = k2 * sharerate * (backrate * LOG(lastonehour_return+1) + backrate_2 * LOG(lasttwohour_return_now+1) + backrate_3 * LOG(lastthreehour_return_now+1))
  200. df = df.fillna(0)
  201. df['share_rate'] = df['lastonehour_share'] / (df['lastonehour_play'] + 1000)
  202. df['back_rate'] = df['lastonehour_return'] / (df['lastonehour_share'] + 10)
  203. df['log_back'] = (df['lastonehour_return'] + 1).apply(math.log)
  204. df['back_rate2'] = df['lasttwohour_return_now'] / (df['lasttwohour_share'] + 10)
  205. df['log_back2'] = (df['lasttwohour_return_now'] + 1).apply(math.log)
  206. df['back_rate3'] = df['lastthreehour_return_now'] / (df['lastthreehour_share'] + 10)
  207. df['log_back3'] = (df['lastthreehour_return_now'] + 1).apply(math.log)
  208. if param.get('view_type', None) == 'video-show':
  209. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_show'] + 1000)
  210. elif param.get('view_type', None) == 'video-show-region':
  211. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_show_region'] + 1000)
  212. else:
  213. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_preview'] + 1000)
  214. df['K2'] = df['ctr'].apply(lambda x: 0.6 if x > 0.6 else x)
  215. df['platform_return_rate'] = df['platform_return'] / df['lastonehour_return']
  216. df['score'] = df['K2'] * df['share_rate'] * (
  217. df['back_rate'] * df['log_back'] +
  218. df['back_rate2'] * df['log_back2'] +
  219. df['back_rate3'] * df['log_back3']
  220. )
  221. df = df.sort_values(by=['score'], ascending=False)
  222. return df
  223. def cal_score_multiply_return_retention(df, param):
  224. # score计算公式: k2 * sharerate * backrate * LOG(lastonehour_return+1) * 前两小时回流留存
  225. # sharerate = lastonehour_share/(lastonehour_play+1000)
  226. # backrate = lastonehour_return/(lastonehour_share+10)
  227. # ctr = lastonehour_play/(lastonehour_preview+1000), 对ctr限最大值:K2 = 0.6 if ctr > 0.6 else ctr
  228. # 前两小时回流留存 return_retention_initial = (lasttwohour_return_now + lastthreehour_return_now)/(lasttwohour_return + lastthreehour_return + 1)
  229. # return_retention = 0.5 if return_retention_initial == 0 else return_retention_initial
  230. # score = k2 * sharerate * backrate * LOG(lastonehour_return+1) * return_retention
  231. df = df.fillna(0)
  232. df['share_rate'] = df['lastonehour_share'] / (df['lastonehour_play'] + 1000)
  233. df['back_rate'] = df['lastonehour_return'] / (df['lastonehour_share'] + 10)
  234. df['log_back'] = (df['lastonehour_return'] + 1).apply(math.log)
  235. if param.get('view_type', None) == 'video-show':
  236. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_show'] + 1000)
  237. elif param.get('view_type', None) == 'video-show-region':
  238. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_show_region'] + 1000)
  239. else:
  240. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_preview'] + 1000)
  241. df['K2'] = df['ctr'].apply(lambda x: 0.6 if x > 0.6 else x)
  242. df['return_retention_initial'] = (df['lasttwohour_return_now'] + df['lastthreehour_return_now']) / \
  243. (df['lasttwohour_return'] + df['lastthreehour_return'] + 1)
  244. df['return_retention'] = df['return_retention_initial'].apply(lambda x: 0.5 if x == 0 else x)
  245. df['platform_return_rate'] = df['platform_return'] / df['lastonehour_return']
  246. df['score'] = df['K2'] * df['share_rate'] * df['back_rate'] * df['log_back'] * df['return_retention']
  247. df = df.sort_values(by=['score'], ascending=False)
  248. return df
  249. def cal_score_update_backrate(df, param):
  250. # score计算公式: k2 * sharerate * (backrate + backrate * backrate_2 * backrate_3) * LOG(lastonehour_return+1)
  251. # sharerate = lastonehour_share/(lastonehour_play+1000)
  252. # backrate = lastonehour_return/(lastonehour_share+10)
  253. # backrate2 = lasttwohour_return_now/(lasttwohour_share+10)
  254. # backrate3 = lastthreehour_return_now/(lastthreehour_share+10)
  255. # ctr = lastonehour_play/(lastonehour_preview+1000), 对ctr限最大值:K2 = 0.6 if ctr > 0.6 else ctr
  256. # backrate1_3_initial = backrate * backrate_2 * backrate_3
  257. # backrate1_3 = 0.02 if backrate1_3_initial == 0 else backrate1_3_initial
  258. # score = k2 * sharerate * (backrate + backrate1_3) * LOG(lastonehour_return+1)
  259. df = df.fillna(0)
  260. df['share_rate'] = df['lastonehour_share'] / (df['lastonehour_play'] + 1000)
  261. df['back_rate'] = df['lastonehour_return'] / (df['lastonehour_share'] + 10)
  262. df['back_rate2'] = df['lasttwohour_return_now'] / (df['lasttwohour_share'] + 10)
  263. df['back_rate3'] = df['lastthreehour_return_now'] / (df['lastthreehour_share'] + 10)
  264. df['log_back'] = (df['lastonehour_return'] + 1).apply(math.log)
  265. if param.get('view_type', None) == 'video-show':
  266. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_show'] + 1000)
  267. elif param.get('view_type', None) == 'video-show-region':
  268. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_show_region'] + 1000)
  269. else:
  270. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_preview'] + 1000)
  271. df['K2'] = df['ctr'].apply(lambda x: 0.6 if x > 0.6 else x)
  272. df['backrate1_3_initial'] = df['back_rate'] * df['back_rate2'] * df['back_rate3']
  273. df['backrate1_3'] = df['backrate1_3_initial'].apply(lambda x: 0.02 if x == 0 else x)
  274. df['platform_return_rate'] = df['platform_return'] / df['lastonehour_return']
  275. df['score'] = df['K2'] * df['share_rate'] * (df['back_rate'] + df['backrate1_3']) * df['log_back']
  276. df = df.sort_values(by=['score'], ascending=False)
  277. return df
  278. def cal_score_with_new_return(df, param):
  279. # 回流数据使用 分享限制地域,回流不限制地域 统计数据
  280. # score计算公式: sharerate*backrate*logback*ctr
  281. # sharerate = lastonehour_share/(lastonehour_play+1000)
  282. # backrate = lastonehour_return_new/(lastonehour_share+10)
  283. # ctr = lastonehour_play/(lastonehour_preview+1000), 对ctr限最大值:K2 = 0.6 if ctr > 0.6 else ctr
  284. # score = sharerate * backrate * LOG(lastonehour_return_new+1) * K2
  285. df = df.fillna(0)
  286. df['share_rate'] = df['lastonehour_share'] / (df['lastonehour_play'] + 1000)
  287. df['back_rate'] = df['lastonehour_return_new'] / (df['lastonehour_share'] + 10)
  288. df['log_back'] = (df['lastonehour_return_new'] + 1).apply(math.log)
  289. if param.get('view_type', None) == 'video-show':
  290. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_show'] + 1000)
  291. elif param.get('view_type', None) == 'video-show-region':
  292. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_show_region'] + 1000)
  293. else:
  294. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_preview'] + 1000)
  295. df['K2'] = df['ctr'].apply(lambda x: 0.6 if x > 0.6 else x)
  296. df['platform_return_rate'] = df['platform_return_new'] / df['lastonehour_return_new']
  297. df['score'] = df['share_rate'] * df['back_rate'] * df['log_back'] * df['K2']
  298. df = df.sort_values(by=['score'], ascending=False)
  299. return df
  300. def cal_score_multiply_return_retention_with_new_return(df, param):
  301. # 回流数据使用 分享限制地域,回流不限制地域 统计数据
  302. # score计算公式: k2 * sharerate * backrate * LOG(lastonehour_return_new+1) * 前两小时回流留存
  303. # sharerate = lastonehour_share/(lastonehour_play+1000)
  304. # backrate = lastonehour_return_new/(lastonehour_share+10)
  305. # ctr = lastonehour_play/(lastonehour_preview+1000), 对ctr限最大值:K2 = 0.6 if ctr > 0.6 else ctr
  306. # 前两小时回流留存 return_retention_initial = (lasttwohour_return_now_new + lastthreehour_return_now_new)/(lasttwohour_return_new + lastthreehour_return_new + 1)
  307. # return_retention = 0.5 if return_retention_initial == 0 else return_retention_initial
  308. # score = k2 * sharerate * backrate * LOG(lastonehour_return_new+1) * return_retention
  309. df = df.fillna(0)
  310. df['share_rate'] = df['lastonehour_share'] / (df['lastonehour_play'] + 1000)
  311. df['back_rate'] = df['lastonehour_return_new'] / (df['lastonehour_share'] + 10)
  312. df['log_back'] = (df['lastonehour_return_new'] + 1).apply(math.log)
  313. if param.get('view_type', None) == 'video-show':
  314. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_show'] + 1000)
  315. elif param.get('view_type', None) == 'video-show-region':
  316. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_show_region'] + 1000)
  317. else:
  318. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_preview'] + 1000)
  319. df['K2'] = df['ctr'].apply(lambda x: 0.6 if x > 0.6 else x)
  320. df['return_retention_initial'] = (df['lasttwohour_return_now_new'] + df['lastthreehour_return_now_new']) / \
  321. (df['lasttwohour_return_new'] + df['lastthreehour_return_new'] + 1)
  322. df['return_retention'] = df['return_retention_initial'].apply(lambda x: 0.5 if x == 0 else x)
  323. df['platform_return_rate'] = df['platform_return_new'] / df['lastonehour_return_new']
  324. df['score'] = df['K2'] * df['share_rate'] * df['back_rate'] * df['log_back'] * df['return_retention']
  325. df = df.sort_values(by=['score'], ascending=False)
  326. return df
  327. def cal_score_with_back_view0(df, param):
  328. # score = sharerate*backrate*log(return+1)*CTR,
  329. # sharerate=(lastonehour_share+1)/(lastonehour_play+1000)
  330. # backrate=(lastonehour_return+1)/(lastonehour_share+10)
  331. # CTR=(lastonehour_play+1)/(lastonehour_view+100), ctr不进行校正
  332. df = df.fillna(0)
  333. df['share_rate'] = (df['lastonehour_share'] + 1) / (df['lastonehour_play'] + 1000)
  334. df['back_rate'] = (df['lastonehour_return'] + 1) / (df['lastonehour_share'] + 10)
  335. df['log_back'] = (df['lastonehour_return'] + 1).apply(math.log)
  336. df['ctr'] = (df['lastonehour_play'] + 1) / (df['lastonehour_view'] + 100)
  337. df['platform_return_rate'] = df['platform_return'] / df['lastonehour_return']
  338. df['score'] = df['share_rate'] * df['back_rate'] * df['log_back'] * df['ctr']
  339. df = df.sort_values(by=['score'], ascending=False)
  340. return df
  341. def cal_score_with_back_view1(df, param):
  342. # score = back_play_rate*log(return+1)*CTR,
  343. # back_play_rate=(lastonehour_return+1)/(lastonehour_play+1000)
  344. # CTR=(lastonehour_play+1)/(lastonehour_view+100), ctr不进行校正
  345. df = df.fillna(0)
  346. df['back_play_rate'] = (df['lastonehour_return'] + 1) / (df['lastonehour_play'] + 1000)
  347. df['log_back'] = (df['lastonehour_return'] + 1).apply(math.log)
  348. df['ctr'] = (df['lastonehour_play'] + 1) / (df['lastonehour_view'] + 100)
  349. df['platform_return_rate'] = df['platform_return'] / df['lastonehour_return']
  350. df['score'] = df['back_play_rate'] * df['log_back'] * df['ctr']
  351. df = df.sort_values(by=['score'], ascending=False)
  352. return df
  353. def cal_score_with_back_rate_exponential_weighting1(df, param):
  354. """
  355. 计算score
  356. :param df: 特征数据
  357. :param param: 规则参数
  358. :return:
  359. """
  360. # score计算公式: score = sharerate * backrate ^ 2 * LOG(lastonehour_return + 1) * K2
  361. # sharerate = lastonehour_share / (lastonehour_play + 1000)
  362. # backrate = lastonehour_return / (lastonehour_share + 10)
  363. # ctr = lastonehour_play / (lastonehour_show + 1000), 对ctr限最大值:K2 = 0.6 if ctr > 0.6 else ctr
  364. df = df.fillna(0)
  365. df['share_rate'] = df['lastonehour_share'] / (df['lastonehour_play'] + 1000)
  366. df['back_rate'] = df['lastonehour_return'] / (df['lastonehour_share'] + 10)
  367. df['log_back'] = (df['lastonehour_return'] + 1).apply(math.log)
  368. if param.get('view_type', None) == 'video-show':
  369. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_show'] + 1000)
  370. elif param.get('view_type', None) == 'video-show-region':
  371. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_show_region'] + 1000)
  372. else:
  373. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_preview'] + 1000)
  374. df['K2'] = df['ctr'].apply(lambda x: 0.6 if x > 0.6 else x)
  375. df['platform_return_rate'] = df['platform_return'] / df['lastonehour_return']
  376. df['score'] = df['share_rate'] * df['back_rate'] ** 2 * df['log_back'] * df['K2']
  377. df = df.sort_values(by=['score'], ascending=False)
  378. return df
  379. def cal_score_with_back_rate_exponential_weighting2(df, param):
  380. """
  381. 计算score
  382. :param df: 特征数据
  383. :param param: 规则参数
  384. :return:
  385. """
  386. # score计算公式: score = sharerate ^ 0.5 * backrate ^ 2 * LOG(lastonehour_return + 1) * K2 ^ 0.5
  387. # sharerate = lastonehour_share / (lastonehour_play + 1000)
  388. # backrate = lastonehour_return / (lastonehour_share + 10)
  389. # ctr = lastonehour_play / (lastonehour_show + 1000), 对ctr限最大值:K2 = 0.6 if ctr > 0.6 else ctr
  390. df = df.fillna(0)
  391. df['share_rate'] = df['lastonehour_share'] / (df['lastonehour_play'] + 1000)
  392. df['back_rate'] = df['lastonehour_return'] / (df['lastonehour_share'] + 10)
  393. df['log_back'] = (df['lastonehour_return'] + 1).apply(math.log)
  394. if param.get('view_type', None) == 'video-show':
  395. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_show'] + 1000)
  396. elif param.get('view_type', None) == 'video-show-region':
  397. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_show_region'] + 1000)
  398. else:
  399. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_preview'] + 1000)
  400. df['K2'] = df['ctr'].apply(lambda x: 0.6 if x > 0.6 else x)
  401. df['platform_return_rate'] = df['platform_return'] / df['lastonehour_return']
  402. df['score'] = df['share_rate'] ** 0.5 * df['back_rate'] ** 2 * df['log_back'] * df['K2'] ** 0.5
  403. df = df.sort_values(by=['score'], ascending=False)
  404. return df
  405. def cal_score_with_back_rate_by_rank_weighting(df, param):
  406. """
  407. add by sunmingze 20231123
  408. 计算score
  409. :param df: 特征数据
  410. :param param: 规则参数
  411. :return:
  412. """
  413. # score计算公式: score = 1 / sharerate(rank)^0.5 + 5 / backrate(rank)^0.5 + 10 / LOG(lastonehour_return +1)(rank) ^0.5
  414. # + 1 / K2(rank)^0.5
  415. # sharerate = lastonehour_share / (lastonehour_play + 1000)
  416. # backrate = lastonehour_return / (lastonehour_share + 10)
  417. # ctr = lastonehour_play / (lastonehour_show + 1000), 对ctr限最大值:K2 = 0.6 if ctr > 0.6 else ctr
  418. df = df.fillna(0)
  419. df['share_rate'] = df['lastonehour_share'] / (df['lastonehour_play'] + 1000)
  420. df['back_rate'] = df['lastonehour_return'] / (df['lastonehour_share'] + 10)
  421. df['log_back'] = (df['lastonehour_return'] + 1).apply(math.log)
  422. if param.get('view_type', None) == 'video-show':
  423. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_show'] + 1000)
  424. elif param.get('view_type', None) == 'video-show-region':
  425. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_show_region'] + 1000)
  426. else:
  427. df['ctr'] = df['lastonehour_play'] / (df['lastonehour_preview'] + 1000)
  428. df['K2'] = df['ctr'].apply(lambda x: 0.6 if x > 0.6 else x)
  429. df['platform_return_rate'] = df['platform_return'] / df['lastonehour_return']
  430. # 分别的得到sharerate、backrate、K值、return人数的序关系
  431. df['rank_by_sharerate'] = df['share_rate'].rank(ascending=0, method='dense')
  432. df['rank_by_backrate'] = df['back_rate'].rank(ascending=0, method='dense')
  433. df['rank_by_K2'] = df['K2'].rank(ascending=0, method='dense')
  434. df['rank_by_logback'] = df['log_back'].rank(ascending=0, method='dense')
  435. # 计算基于序的加法关系函数
  436. df['score'] = 1/(df['rank_by_sharerate'] + 10) + 5/(df['rank_by_backrate'] + 10)
  437. df['score'] = df['score'] + 5/(df['rank_by_logback'] + 10) + 1/(df['rank_by_K2'] + 10)
  438. df = df.sort_values(by=['score'], ascending=False)
  439. return df
  440. def cal_score(df, param):
  441. if param.get('return_data', None) == 'share_region_return':
  442. if param.get('score_func', None) == 'multiply_return_retention':
  443. df = cal_score_multiply_return_retention_with_new_return(df=df, param=param)
  444. else:
  445. df = cal_score_with_new_return(df=df, param=param)
  446. else:
  447. if param.get('score_func', None) == 'add_backrate*log(return+1)':
  448. df = cal_score_add_return(df=df, param=param)
  449. elif param.get('score_func', None) == 'multiply_return_retention':
  450. df = cal_score_multiply_return_retention(df=df, param=param)
  451. elif param.get('score_func', None) == 'update_backrate':
  452. df = cal_score_update_backrate(df=df, param=param)
  453. elif param.get('score_func', None) == 'back_view0':
  454. df = cal_score_with_back_view0(df=df, param=param)
  455. elif param.get('score_func', None) == 'back_view1':
  456. df = cal_score_with_back_view1(df=df, param=param)
  457. elif param.get('score_func', None) == 'back_rate_exponential_weighting1':
  458. df = cal_score_with_back_rate_exponential_weighting1(df=df, param=param)
  459. elif param.get('score_func', None) == 'back_rate_exponential_weighting2':
  460. df = cal_score_with_back_rate_exponential_weighting2(df=df, param=param)
  461. elif param.get('score_func', None) == 'back_rate_rank_weighting':
  462. df = cal_score_with_back_rate_by_rank_weighting(df=df, param=param)
  463. elif param.get('score_func', None) == '20240223':
  464. df = cal_score_initial_20240223(df=df, param=param)
  465. else:
  466. df = cal_score_initial(df=df, param=param)
  467. return df
  468. def add_func1(initial_df, pre_h_df):
  469. """当前小时级数据与前几个小时数据合并"""
  470. score_list = initial_df['score'].to_list()
  471. if len(score_list) > 0:
  472. min_score = min(score_list)
  473. else:
  474. min_score = 0
  475. pre_h_df = pre_h_df[pre_h_df['score'] > min_score]
  476. df = pd.concat([initial_df, pre_h_df], ignore_index=True)
  477. # videoid去重,保留分值高
  478. df['videoid'] = df['videoid'].astype(int)
  479. df = df.sort_values(by=['score'], ascending=False)
  480. df = df.drop_duplicates(subset=['videoid'], keep="first")
  481. return df
  482. def add_func2(initial_df, pre_h_df):
  483. """当前小时级数据与前几个小时数据合并: 当前小时存在的视频以当前小时为准,否则以高分为主"""
  484. score_list = initial_df['score'].to_list()
  485. if len(score_list) > 0:
  486. min_score = min(score_list)
  487. else:
  488. min_score = 0
  489. initial_video_id_list = initial_df['videoid'].to_list()
  490. pre_h_df = pre_h_df[pre_h_df['score'] > min_score]
  491. pre_h_df = pre_h_df[~pre_h_df['videoid'].isin(initial_video_id_list)]
  492. df = pd.concat([initial_df, pre_h_df], ignore_index=True)
  493. # videoid去重,保留分值高
  494. df['videoid'] = df['videoid'].astype(int)
  495. df = df.sort_values(by=['score'], ascending=False)
  496. df = df.drop_duplicates(subset=['videoid'], keep="first")
  497. return df
  498. def add_videos(initial_df, now_date, rule_key, region, data_key, hour_count, top, add_func):
  499. """
  500. 地域小时级数据列表中增加前6h优质视频
  501. :param initial_df: 地域小时级筛选结果
  502. :param now_date:
  503. :param data_key:
  504. :param region:
  505. :param rule_key:
  506. :param hour_count: 前几个小时, type-int
  507. :param top: type-int
  508. :return: df
  509. """
  510. redis_helper = RedisHelper()
  511. pre_h_data = []
  512. for i in range(1, hour_count+1):
  513. pre_date = now_date - datetime.timedelta(hours=i)
  514. pre_h = pre_date.hour
  515. pre_h_recall_key_name = f"{config_.RECALL_KEY_NAME_PREFIX_REGION_BY_H}{region}:{data_key}:{rule_key}:" \
  516. f"{datetime.datetime.strftime(pre_date, '%Y%m%d')}:{pre_h}"
  517. pre_h_top_data = redis_helper.get_data_zset_with_index(key_name=pre_h_recall_key_name,
  518. start=0, end=top-1,
  519. desc=True, with_scores=True)
  520. if pre_h_top_data is None:
  521. continue
  522. pre_h_data.extend(pre_h_top_data)
  523. pre_h_df = pd.DataFrame(data=pre_h_data, columns=['videoid', 'score'])
  524. if add_func == 'func2':
  525. df = add_func2(initial_df=initial_df, pre_h_df=pre_h_df)
  526. else:
  527. df = add_func1(initial_df=initial_df, pre_h_df=pre_h_df)
  528. return df
  529. def video_rank(df, now_date, now_h, rule_key, param, region, data_key, rule_rank_h_flag,
  530. add_videos_with_pre_h=False, hour_count=0):
  531. """
  532. 获取符合进入召回源条件的视频,与每日更新的rov模型结果视频列表进行合并
  533. :param df:
  534. :param now_date:
  535. :param now_h:
  536. :param rule_key: 小时级数据进入条件
  537. :param param: 小时级数据进入条件参数
  538. :param region: 所属地域
  539. :return:
  540. """
  541. redis_helper = RedisHelper()
  542. # 获取符合进入召回源条件的视频,进入条件:小时级回流>=20 && score>=0.005
  543. return_count = param.get('return_count', 1)
  544. score_value = param.get('score_rule', 0)
  545. platform_return_rate = param.get('platform_return_rate', 0)
  546. # h_recall_df = df[(df['lastonehour_return'] >= return_count) & (df['score'] >= score_value)
  547. # & (df['platform_return_rate'] >= platform_return_rate)]
  548. h_recall_df = df[
  549. (df['lastonehour_return'] >= return_count) &
  550. (df['score'] >= score_value) &
  551. (df['platform_return_rate'] >= platform_return_rate)
  552. ]
  553. if "lastonehour_allreturn" in param.keys():
  554. h_recall_df = df[
  555. (df['lastonehour_allreturn'] > 0)
  556. ]
  557. # try:
  558. # if "return_countv2" in param.keys() and "platform_return_ratev2" in param.keys():
  559. # return_countv2 = param["return_countv2"]
  560. # platform_return_ratev2 = param["platform_return_ratev2"]
  561. # h_recall_df = h_recall_df[
  562. # df['platform_return_rate'] >= platform_return_ratev2 |
  563. # (df['platform_return_rate'] < platform_return_ratev2 & df['lastonehour_return'] > return_countv2)
  564. # ]
  565. # except Exception as e:
  566. # log_.error("return_countv2 is wrong with{}".format(e))
  567. # videoid重复时,保留分值高
  568. h_recall_df = h_recall_df.sort_values(by=['score'], ascending=False)
  569. h_recall_df = h_recall_df.drop_duplicates(subset=['videoid'], keep='first')
  570. h_recall_df['videoid'] = h_recall_df['videoid'].astype(int)
  571. log_.info(f"各种规则过滤后,一共有多少个视频 = {len(h_recall_df)}")
  572. # 增加打捞的优质视频
  573. if add_videos_with_pre_h is True:
  574. add_func = param.get('add_func', None)
  575. h_recall_df = add_videos(initial_df=h_recall_df, now_date=now_date, rule_key=rule_key,
  576. region=region, data_key=data_key, hour_count=hour_count, top=10, add_func=add_func)
  577. log_.info(f"打捞优质视频完成")
  578. h_recall_videos = h_recall_df['videoid'].to_list()
  579. log_.info(f"各种规则增加后,一共有多少个视频 = {len(h_recall_videos)}")
  580. # 视频状态过滤
  581. if data_key in ['data7', ]:
  582. filtered_videos = filter_video_status_app(h_recall_videos)
  583. else:
  584. filtered_videos = filter_video_status(h_recall_videos)
  585. # 屏蔽视频过滤
  586. shield_config = param.get('shield_config', config_.SHIELD_CONFIG)
  587. shield_key_name_list = shield_config.get(region, None)
  588. if shield_key_name_list is not None:
  589. filtered_videos = filter_shield_video(video_ids=filtered_videos, shield_key_name_list=shield_key_name_list)
  590. # 涉政视频过滤
  591. political_filter = param.get('political_filter', None)
  592. if political_filter is True:
  593. filtered_videos = filter_political_videos(video_ids=filtered_videos)
  594. log_.info(f"视频状态-涉政等-过滤后,一共有多少个视频 = {len(filtered_videos)}")
  595. # 写入对应的redis
  596. h_video_ids = []
  597. by_30day_rule_key = param.get('30day_rule_key', None)
  598. if by_30day_rule_key is not None:
  599. # 与相对30天列表去重
  600. h_video_ids = get_day_30day_videos(now_date=now_date, data_key=data_key, rule_key=by_30day_rule_key)
  601. # log_.info(f"h_video_ids count = {len(h_video_ids)}")
  602. if h_video_ids is not None:
  603. filtered_videos = [video_id for video_id in filtered_videos if int(video_id) not in h_video_ids]
  604. # log_.info(f"filtered_videos count = {len(filtered_videos)}")
  605. h_recall_result = {}
  606. for video_id in filtered_videos:
  607. score = h_recall_df[h_recall_df['videoid'] == video_id]['score']
  608. # print(score)
  609. h_recall_result[int(video_id)] = float(score)
  610. h_video_ids.append(int(video_id))
  611. h_recall_key_name = \
  612. f"{config_.RECALL_KEY_NAME_PREFIX_REGION_BY_H}{region}:{data_key}:{rule_key}:" \
  613. f"{datetime.datetime.strftime(now_date, '%Y%m%d')}:{now_h}"
  614. log_.info("打印地域1小时的某个地域{},redis key:{}".format(region, h_recall_key_name))
  615. if len(h_recall_result) > 0:
  616. log_.info(f"开始写入头部数据:count = {len(h_recall_result)}, key = {h_recall_key_name}")
  617. redis_helper.add_data_with_zset(key_name=h_recall_key_name, data=h_recall_result, expire_time=2 * 24 * 3600)
  618. # 限流视频score调整
  619. update_limit_video_score(initial_videos=h_recall_result, key_name=h_recall_key_name)
  620. # 清空线上过滤应用列表
  621. # redis_helper.del_keys(key_name=f"{config_.REGION_H_VIDEO_FILER}{region}.{app_type}.{data_key}.{rule_key}")
  622. def merge_df(df_left, df_right):
  623. """
  624. df按照videoid, code 合并,对应特征求和
  625. :param df_left:
  626. :param df_right:
  627. :return:
  628. """
  629. df_merged = pd.merge(df_left, df_right, on=['videoid', 'code'], how='outer', suffixes=['_x', '_y'])
  630. df_merged.fillna(0, inplace=True)
  631. feature_list = ['videoid', 'code']
  632. for feature in features:
  633. if feature in ['apptype', 'videoid', 'code']:
  634. continue
  635. df_merged[feature] = df_merged[f'{feature}_x'] + df_merged[f'{feature}_y']
  636. feature_list.append(feature)
  637. return df_merged[feature_list]
  638. def merge_df_with_score(df_left, df_right):
  639. """
  640. df 按照[videoid, code]合并,平台回流人数、回流人数、分数 分别求和
  641. :param df_left:
  642. :param df_right:
  643. :return:
  644. """
  645. df_merged = pd.merge(df_left, df_right, on=['videoid', 'code'], how='outer', suffixes=['_x', '_y'])
  646. df_merged.fillna(0, inplace=True)
  647. feature_list = ['videoid', 'code', 'lastonehour_return', 'platform_return', 'score']
  648. for feature in feature_list[2:]:
  649. df_merged[feature] = df_merged[f'{feature}_x'] + df_merged[f'{feature}_y']
  650. return df_merged[feature_list]
  651. def process_with_region(region, df_merged, data_key, rule_key, rule_param, now_date, now_h,
  652. rule_rank_h_flag, add_videos_with_pre_h, hour_count):
  653. log_.info(f"多协程的region = {region} 开始执行")
  654. region_df = df_merged[df_merged['code'] == region]
  655. log_.info(f'该区域region = {region}, 下有多少数据量 = {len(region_df)}')
  656. score_df = cal_score(df=region_df, param=rule_param)
  657. video_rank(df=score_df, now_date=now_date, now_h=now_h, rule_key=rule_key, param=rule_param,
  658. region=region, data_key=data_key, rule_rank_h_flag=rule_rank_h_flag,
  659. add_videos_with_pre_h=add_videos_with_pre_h, hour_count=hour_count)
  660. log_.info(f"多协程的region = {region} 完成执行")
  661. def process_with_region2(region, df_merged, data_key, rule_key, rule_param, now_date, now_h,
  662. rule_rank_h_flag, add_videos_with_pre_h, hour_count):
  663. log_.info(f"region = {region} start...")
  664. region_score_df = df_merged[df_merged['code'] == region]
  665. log_.info(f'region = {region}, region_score_df count = {len(region_score_df)}')
  666. video_rank(df=region_score_df, now_date=now_date, now_h=now_h, region=region,
  667. rule_key=rule_key, param=rule_param, data_key=data_key, rule_rank_h_flag=rule_rank_h_flag,
  668. add_videos_with_pre_h=add_videos_with_pre_h, hour_count=hour_count)
  669. log_.info(f"region = {region} end!")
  670. def process_with_app_type(app_type, params, region_code_list, feature_df, now_date, now_h, rule_rank_h_flag):
  671. log_.info(f"app_type = {app_type} start...")
  672. data_params_item = params.get('data_params')
  673. rule_params_item = params.get('rule_params')
  674. task_list = []
  675. for param in params.get('params_list'):
  676. data_key = param.get('data')
  677. data_param = data_params_item.get(data_key)
  678. log_.info(f"data_key = {data_key}, data_param = {data_param}")
  679. df_list = [feature_df[feature_df['apptype'] == apptype] for apptype in data_param]
  680. df_merged = reduce(merge_df, df_list)
  681. rule_key = param.get('rule')
  682. rule_param = rule_params_item.get(rule_key)
  683. log_.info(f"rule_key = {rule_key}, rule_param = {rule_param}")
  684. task_list.extend(
  685. [
  686. gevent.spawn(process_with_region, region, df_merged, app_type, data_key, rule_key, rule_param,
  687. now_date, now_h, rule_rank_h_flag)
  688. for region in region_code_list
  689. ]
  690. )
  691. gevent.joinall(task_list)
  692. log_.info(f"app_type = {app_type} end!")
  693. def copy_data_for_city(region, city_code, data_key, rule_key, now_date, now_h, shield_config):
  694. """copy 对应数据到城市对应redis,并做相应屏蔽视频过滤"""
  695. log_.info(f"city_code = {city_code} start ...")
  696. redis_helper = RedisHelper()
  697. key_prefix_list = [
  698. config_.RECALL_KEY_NAME_PREFIX_REGION_BY_H, # 地域小时
  699. ]
  700. for key_prefix in key_prefix_list:
  701. region_key = f"{key_prefix}{region}:{data_key}:{rule_key}:{datetime.datetime.strftime(now_date, '%Y%m%d')}:{now_h}"
  702. city_key = f"{key_prefix}{city_code}:{data_key}:{rule_key}:{datetime.datetime.strftime(now_date, '%Y%m%d')}:{now_h}"
  703. if not redis_helper.key_exists(key_name=region_key):
  704. continue
  705. region_data = redis_helper.get_all_data_from_zset(key_name=region_key, with_scores=True)
  706. if not region_data:
  707. continue
  708. # 屏蔽视频过滤
  709. region_video_ids = [int(video_id) for video_id, _ in region_data]
  710. shield_key_name_list = shield_config.get(city_code, None)
  711. # shield_key_name_list = config_.SHIELD_CONFIG.get(city_code, None)
  712. if shield_key_name_list is not None:
  713. filtered_video_ids = filter_shield_video(video_ids=region_video_ids,
  714. shield_key_name_list=shield_key_name_list)
  715. else:
  716. filtered_video_ids = region_video_ids
  717. city_data = {}
  718. for video_id, score in region_data:
  719. if int(video_id) in filtered_video_ids:
  720. city_data[int(video_id)] = score
  721. if len(city_data) > 0:
  722. redis_helper.add_data_with_zset(key_name=city_key, data=city_data, expire_time=2 * 24 * 3600)
  723. log_.info(f"city_code = {city_code} end!")
  724. def process_with_param(param, data_params_item, rule_params_item, region_code_list, feature_df, now_date, now_h, rule_rank_h_flag):
  725. log_.info(f"param = {param} start...")
  726. data_key = param.get('data')
  727. data_param = data_params_item.get(data_key)
  728. rule_key = param.get('rule')
  729. rule_param = rule_params_item.get(rule_key)
  730. merge_func = rule_param.get('merge_func', None)
  731. log_.info("数据采用:{},统计采用{}.".format(data_key, rule_key))
  732. log_.info("具体的规则是:{}.".format(rule_param))
  733. # 是否在地域小时级数据中增加打捞的优质视频
  734. add_videos_with_pre_h = rule_param.get('add_videos_with_pre_h', False)
  735. hour_count = rule_param.get('hour_count', 0)
  736. if merge_func == 2:
  737. score_df_list = []
  738. for apptype, weight in data_param.items():
  739. df = feature_df[feature_df['apptype'] == apptype]
  740. # 计算score
  741. score_df = cal_score(df=df, param=rule_param)
  742. score_df['score'] = score_df['score'] * weight
  743. score_df_list.append(score_df)
  744. # 分数合并
  745. df_merged = reduce(merge_df_with_score, score_df_list)
  746. # 更新平台回流比
  747. df_merged['platform_return_rate'] = df_merged['platform_return'] / df_merged['lastonehour_return']
  748. task_list = [
  749. gevent.spawn(process_with_region2,
  750. region, df_merged, data_key, rule_key, rule_param, now_date, now_h, rule_rank_h_flag,
  751. add_videos_with_pre_h, hour_count)
  752. for region in region_code_list
  753. ]
  754. else:
  755. df_list = [feature_df[feature_df['apptype'] == apptype] for apptype in data_param]
  756. df_merged = reduce(merge_df, df_list)
  757. task_list = [
  758. gevent.spawn(process_with_region,
  759. region, df_merged, data_key, rule_key, rule_param, now_date, now_h, rule_rank_h_flag,
  760. add_videos_with_pre_h, hour_count)
  761. for region in region_code_list
  762. ]
  763. gevent.joinall(task_list)
  764. # 特殊城市视频数据准备
  765. # 屏蔽视频过滤
  766. shield_config = rule_param.get('shield_config', config_.SHIELD_CONFIG)
  767. for region, city_list in config_.REGION_CITY_MAPPING.items():
  768. t = [
  769. gevent.spawn(
  770. copy_data_for_city,
  771. region, city_code, data_key, rule_key, now_date, now_h, shield_config
  772. )
  773. for city_code in city_list
  774. ]
  775. gevent.joinall(t)
  776. log_.info(f"param = {param} end!")
  777. def rank_by_h(project, table, now_date, now_h, rule_params, region_code_list, rule_rank_h_flag):
  778. # 获取特征数据
  779. feature_df = get_feature_data(project=project, table=table, now_date=now_date)
  780. feature_df['apptype'] = feature_df['apptype'].astype(int)
  781. data_params_item = rule_params.get('data_params')
  782. rule_params_item = rule_params.get('rule_params')
  783. params_list = rule_params.get('params_list')
  784. pool = multiprocessing.Pool(processes=len(params_list))
  785. for param in params_list:
  786. pool.apply_async(
  787. func=process_with_param,
  788. args=(param, data_params_item, rule_params_item, region_code_list, feature_df, now_date, now_h, rule_rank_h_flag)
  789. )
  790. pool.close()
  791. pool.join()
  792. # pool = multiprocessing.Pool(processes=len(config_.APP_TYPE))
  793. # for app_type, params in rule_params.items():
  794. # pool.apply_async(func=process_with_app_type,
  795. # args=(app_type, params, region_code_list, feature_df, now_date, now_h, rule_rank_h_flag))
  796. # pool.close()
  797. # pool.join()
  798. """
  799. for app_type, params in rule_params.items():
  800. log_.info(f"app_type = {app_type} start...")
  801. data_params_item = params.get('data_params')
  802. rule_params_item = params.get('rule_params')
  803. for param in params.get('params_list'):
  804. log_.info(f"param = {param} start...")
  805. data_key = param.get('data')
  806. data_param = data_params_item.get(data_key)
  807. log_.info(f"data_key = {data_key}, data_param = {data_param}")
  808. df_list = [feature_df[feature_df['apptype'] == apptype] for apptype in data_param]
  809. df_merged = reduce(merge_df, df_list)
  810. rule_key = param.get('rule')
  811. rule_param = rule_params_item.get(rule_key)
  812. log_.info(f"rule_key = {rule_key}, rule_param = {rule_param}")
  813. task_list = []
  814. for region in region_code_list:
  815. t = Thread(target=process_with_region,
  816. args=(region, df_merged, app_type, data_key, rule_key, rule_param, now_date, now_h)
  817. )
  818. t.start()
  819. task_list.append(t)
  820. for t in task_list:
  821. t.join()
  822. log_.info(f"param = {param} end!")
  823. log_.info(f"app_type = {app_type} end!")
  824. """
  825. # for app_type, params in rule_params.items():
  826. # log_.info(f"app_type = {app_type}")
  827. # for data_key, data_param in params['data_params'].items():
  828. # log_.info(f"data_key = {data_key}, data_param = {data_param}")
  829. # df_list = [feature_df[feature_df['apptype'] == apptype] for apptype in data_param]
  830. # df_merged = reduce(merge_df, df_list)
  831. # for rule_key, rule_param in params['rule_params'].items():
  832. # log_.info(f"rule_key = {rule_key}, rule_param = {rule_param}")
  833. # task_list = [
  834. # gevent.spawn(process_with_region, region, df_merged, app_type, data_key, rule_key, rule_param, now_date, now_h)
  835. # for region in region_code_list
  836. # ]
  837. # gevent.joinall(task_list)
  838. # rank
  839. # for key, value in rule_params.items():
  840. # log_.info(f"rule = {key}, param = {value}")
  841. # for region in region_code_list:
  842. # log_.info(f"region = {region}")
  843. # # 计算score
  844. # region_df = feature_df[feature_df['code'] == region]
  845. # log_.info(f'region_df count = {len(region_df)}')
  846. # score_df = cal_score(df=region_df, param=value)
  847. # video_rank(df=score_df, now_date=now_date, now_h=now_h, rule_key=key, param=value, region=region)
  848. # # to-csv
  849. # score_filename = f"score_{region}_{key}_{datetime.datetime.strftime(now_date, '%Y%m%d%H')}.csv"
  850. # score_df.to_csv(f'./data/{score_filename}')
  851. # # to-logs
  852. # log_.info({"date": datetime.datetime.strftime(now_date, '%Y%m%d%H'),
  853. # "region_code": region,
  854. # "redis_key_prefix": config_.RECALL_KEY_NAME_PREFIX_REGION_BY_H,
  855. # "rule_key": key,
  856. # # "score_df": score_df[['videoid', 'score']]
  857. # }
  858. # )
  859. def h_bottom_process(param, rule_params_item, region_code_list, key_prefix, redis_dt, redis_h,
  860. now_date, now_h, rule_rank_h_flag):
  861. redis_helper = RedisHelper()
  862. data_key = param.get('data')
  863. rule_key = param.get('rule')
  864. rule_param = rule_params_item.get(rule_key)
  865. log_.info(f"data_key = {data_key}, rule_key = {rule_key}, rule_param = {rule_param}")
  866. h_rule_key = rule_param.get('h_rule_key', None)
  867. region_24h_rule_key = rule_param.get('region_24h_rule_key', 'rule1')
  868. by_24h_rule_key = rule_param.get('24h_rule_key', None)
  869. by_48h_rule_key = rule_param.get('48h_rule_key', None)
  870. # 涉政视频过滤
  871. political_filter = param.get('political_filter', None)
  872. # 屏蔽视频过滤
  873. shield_config = param.get('shield_config', config_.SHIELD_CONFIG)
  874. dup_remove = param.get('dup_remove', True)
  875. for region in region_code_list:
  876. log_.info(f"region = {region}")
  877. key_name = f"{key_prefix}{region}:{data_key}:{rule_key}:{redis_dt}:{redis_h}"
  878. initial_data = redis_helper.get_all_data_from_zset(key_name=key_name, with_scores=True)
  879. if initial_data is None:
  880. initial_data = []
  881. final_data = dict()
  882. h_video_ids = []
  883. for video_id, score in initial_data:
  884. final_data[video_id] = score
  885. h_video_ids.append(int(video_id))
  886. # 存入对应的redis
  887. final_key_name = \
  888. f"{key_prefix}{region}:{data_key}:{rule_key}:{datetime.datetime.strftime(now_date, '%Y%m%d')}:{now_h}"
  889. if len(final_data) > 0:
  890. redis_helper.add_data_with_zset(key_name=final_key_name, data=final_data, expire_time=2 * 24 * 3600)
  891. # 特殊城市视频数据准备
  892. for region, city_list in config_.REGION_CITY_MAPPING.items():
  893. t = [
  894. gevent.spawn(
  895. copy_data_for_city,
  896. region, city_code, data_key, rule_key, now_date, now_h, shield_config
  897. )
  898. for city_code in city_list
  899. ]
  900. gevent.joinall(t)
  901. def h_rank_bottom(now_date, now_h, rule_params, region_code_list, rule_rank_h_flag):
  902. """未按时更新数据,用上一小时结果作为当前小时的数据"""
  903. # 获取rov模型结果
  904. # redis_helper = RedisHelper()
  905. if now_h == 0:
  906. redis_dt = datetime.datetime.strftime(now_date - datetime.timedelta(days=1), '%Y%m%d')
  907. redis_h = 23
  908. else:
  909. redis_dt = datetime.datetime.strftime(now_date, '%Y%m%d')
  910. redis_h = now_h - 1
  911. # 以上一小时的地域分组数据作为当前小时的数据
  912. key_prefix = config_.RECALL_KEY_NAME_PREFIX_REGION_BY_H
  913. rule_params_item = rule_params.get('rule_params')
  914. params_list = rule_params.get('params_list')
  915. pool = multiprocessing.Pool(processes=len(params_list))
  916. for param in params_list:
  917. pool.apply_async(
  918. func=h_bottom_process,
  919. args=(param, rule_params_item, region_code_list, key_prefix, redis_dt, redis_h, now_date, now_h, rule_rank_h_flag)
  920. )
  921. pool.close()
  922. pool.join()
  923. # for param in rule_params.get('params_list'):
  924. # data_key = param.get('data')
  925. # rule_key = param.get('rule')
  926. # rule_param = rule_params_item.get(rule_key)
  927. # log_.info(f"data_key = {data_key}, rule_key = {rule_key}, rule_param = {rule_param}")
  928. # region_24h_rule_key = rule_param.get('region_24h_rule_key', 'rule1')
  929. # by_24h_rule_key = rule_param.get('24h_rule_key', None)
  930. # by_48h_rule_key = rule_param.get('48h_rule_key', None)
  931. # # 涉政视频过滤
  932. # political_filter = param.get('political_filter', None)
  933. # # 屏蔽视频过滤
  934. # shield_config = param.get('shield_config', config_.SHIELD_CONFIG)
  935. # for region in region_code_list:
  936. # log_.info(f"region = {region}")
  937. # key_name = f"{key_prefix}{region}:{data_key}:{rule_key}:{redis_dt}:{redis_h}"
  938. # initial_data = redis_helper.get_all_data_from_zset(key_name=key_name, with_scores=True)
  939. # if initial_data is None:
  940. # initial_data = []
  941. # final_data = dict()
  942. # h_video_ids = []
  943. # for video_id, score in initial_data:
  944. # final_data[video_id] = score
  945. # h_video_ids.append(int(video_id))
  946. # # 存入对应的redis
  947. # final_key_name = \
  948. # f"{key_prefix}{region}:{data_key}:{rule_key}:{datetime.datetime.strftime(now_date, '%Y%m%d')}:{now_h}"
  949. # if len(final_data) > 0:
  950. # redis_helper.add_data_with_zset(key_name=final_key_name, data=final_data, expire_time=2 * 24 * 3600)
  951. # # 与其他召回视频池去重,存入对应的redis
  952. # dup_to_redis(h_video_ids=h_video_ids, now_date=now_date, now_h=now_h, rule_key=rule_key,
  953. # region_24h_rule_key=region_24h_rule_key, region=region,
  954. # data_key=data_key, by_24h_rule_key=by_24h_rule_key,
  955. # by_48h_rule_key=by_48h_rule_key, rule_rank_h_flag=rule_rank_h_flag,
  956. # political_filter=political_filter, shield_config=shield_config)
  957. # # 特殊城市视频数据准备
  958. # for region, city_list in config_.REGION_CITY_MAPPING.items():
  959. # t = [
  960. # gevent.spawn(
  961. # copy_data_for_city,
  962. # region, city_code, data_key, rule_key, now_date, now_h, shield_config
  963. # )
  964. # for city_code in city_list
  965. # ]
  966. # gevent.joinall(t)
  967. def h_timer_check():
  968. try:
  969. rule_rank_h_flag = sys.argv[1]
  970. if rule_rank_h_flag == '48h':
  971. rule_params = config_.RULE_PARAMS_REGION_APP_TYPE_48H
  972. else:
  973. rule_params = config_.RULE_PARAMS_REGION_APP_TYPE
  974. project = config_.PROJECT_REGION_APP_TYPE
  975. table = config_.TABLE_REGION_APP_TYPE
  976. region_code_list = [code for region, code in region_code.items()]
  977. now_date = datetime.datetime.today()
  978. log_.info(f"开始执行: {datetime.datetime.strftime(now_date, '%Y%m%d%H')}")
  979. now_h = datetime.datetime.now().hour
  980. now_min = datetime.datetime.now().minute
  981. redis_helper = RedisHelper()
  982. if now_h == 0:
  983. log_.info("当前时间{}小时,使用bottom的data,开始。".format(now_h))
  984. h_rank_bottom(now_date=now_date, now_h=now_h, rule_params=rule_params, region_code_list=region_code_list,
  985. rule_rank_h_flag=rule_rank_h_flag)
  986. log_.info(f"region_h_data end!")
  987. redis_helper.set_data_to_redis(
  988. key_name=f"{config_.REGION_H_DATA_STATUS}:{datetime.datetime.strftime(now_date, '%Y%m%d%H')}",
  989. value='1', expire_time=2 * 3600
  990. )
  991. log_.info(f"region_h_data status update to '1' finished!")
  992. return
  993. # 查看当前小时更新的数据是否已准备好
  994. h_data_count = h_data_check(project=project, table=table, now_date=now_date)
  995. if h_data_count > 0:
  996. log_.info('上游数据表查询数据条数 h_data_count = {},开始计算。'.format(h_data_count))
  997. # 数据准备好,进行更新
  998. rank_by_h(now_date=now_date, now_h=now_h, rule_params=rule_params,
  999. project=project, table=table, region_code_list=region_code_list, rule_rank_h_flag=rule_rank_h_flag)
  1000. log_.info(f"region_h_data end!")
  1001. redis_helper.set_data_to_redis(
  1002. key_name=f"{config_.REGION_H_DATA_STATUS}:{datetime.datetime.strftime(now_date, '%Y%m%d%H')}",
  1003. value='1', expire_time=2 * 3600
  1004. )
  1005. log_.info(f"region_h_data status update to '1' finished!")
  1006. elif now_min > 40:
  1007. log_.info('h_recall data is None, use bottom data!')
  1008. h_rank_bottom(now_date=now_date, now_h=now_h, rule_params=rule_params, region_code_list=region_code_list,
  1009. rule_rank_h_flag=rule_rank_h_flag)
  1010. log_.info(f"region_h_data end!")
  1011. redis_helper.set_data_to_redis(
  1012. key_name=f"{config_.REGION_H_DATA_STATUS}:{datetime.datetime.strftime(now_date, '%Y%m%d%H')}",
  1013. value='1', expire_time=2 * 3600
  1014. )
  1015. log_.info(f"region_h_data status update to '1' finished!")
  1016. else:
  1017. # 数据没准备好,1分钟后重新检查
  1018. log_.info("上游数据未就绪,等待...")
  1019. Timer(60, h_timer_check).start()
  1020. except Exception as e:
  1021. log_.error(f"地域分组小时级数据更新失败, exception: {e}, traceback: {traceback.format_exc()}")
  1022. send_msg_to_feishu(
  1023. webhook=config_.FEISHU_ROBOT['server_robot'].get('webhook'),
  1024. key_word=config_.FEISHU_ROBOT['server_robot'].get('key_word'),
  1025. msg_text=f"rov-offline{config_.ENV_TEXT} - 地域分组小时级数据更新失败\n"
  1026. f"exception: {e}\n"
  1027. f"traceback: {traceback.format_exc()}"
  1028. )
  1029. if __name__ == '__main__':
  1030. log_.info(f"region-rule-rank-h-v2 start...")
  1031. h_timer_check()