ad_threshold_auto_update.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. import datetime
  2. import traceback
  3. import numpy as np
  4. from threading import Timer
  5. import pandas as pd
  6. from utils import RedisHelper, data_check, get_feature_data, send_msg_to_feishu
  7. from config import set_config
  8. from log import Log
  9. config_, _ = set_config()
  10. log_ = Log()
  11. redis_helper = RedisHelper()
  12. features = [
  13. 'apptype',
  14. 'adcode',
  15. 'visit_uv_today',
  16. 'visit_uv_yesterday',
  17. 'b'
  18. ]
  19. def get_threshold_record_new(ad_abtest_abcode_config, feature_df, threshold_record):
  20. """根据活跃人数变化计算新的阈值参数"""
  21. robot_msg_record = []
  22. threshold_record_new = threshold_record.copy()
  23. for app_type, config_params in ad_abtest_abcode_config.items():
  24. # 获取对应端的数据, 更新阈值参数
  25. # log_.info(f"app_type = {app_type}")
  26. temp_df = feature_df[feature_df['apptype'] == app_type]
  27. ab_test_id = config_params.get('ab_test_id')
  28. ab_test_config = config_params.get('ab_test_config')
  29. up_threshold_update = config_params.get('up_threshold_update')
  30. down_threshold_update = config_params.get('down_threshold_update')
  31. for config_name, ab_code_list in ab_test_config.items():
  32. ad_abtest_tag = f"{ab_test_id}-{config_name}"
  33. # log_.info(f"ad_abtest_tag = {ad_abtest_tag}")
  34. if len(ab_code_list) > 0:
  35. b_mean = temp_df[temp_df['adcode'].isin(ab_code_list)]['b'].mean()
  36. if b_mean < 0:
  37. # 阈值按梯度调高
  38. gradient = up_threshold_update[config_name].get('gradient')
  39. update_range = up_threshold_update[config_name].get('update_range')
  40. b_i = (b_mean * -1) // gradient + 1
  41. threshold_param_new = float(threshold_record.get(ad_abtest_tag)) + update_range * b_i
  42. elif b_mean > 0.1:
  43. # 阈值按梯度调低
  44. gradient = down_threshold_update[config_name].get('gradient')
  45. update_range = down_threshold_update[config_name].get('update_range')
  46. b_i = (b_mean - 0.1) // gradient + 1
  47. threshold_param_new = float(threshold_record.get(ad_abtest_tag)) - update_range * b_i
  48. else:
  49. continue
  50. if threshold_param_new > 0:
  51. threshold_record_new[ad_abtest_tag] = threshold_param_new
  52. robot_msg_record.append({'appType': app_type, 'abtestTag': ad_abtest_tag,
  53. 'gradient': round(gradient, 4), 'range': round(update_range, 4),
  54. 'i': int(b_i),
  55. 'paramOld': round(float(threshold_record.get(ad_abtest_tag)), 4),
  56. 'paramNew': round(threshold_param_new, 4)})
  57. return threshold_record_new, robot_msg_record
  58. def update_threshold(threshold_record_old, threshold_record_new):
  59. """更新阈值"""
  60. ad_mid_group_list = [group for class_key, group_list in config_.AD_MID_GROUP.items()
  61. for group in group_list]
  62. ad_mid_group_list.append("mean_group")
  63. ad_mid_group_list = list(set(ad_mid_group_list))
  64. for ad_abtest_tag, threshold_param_new in threshold_record_new.items():
  65. threshold_param_old = threshold_record_old.get(ad_abtest_tag)
  66. log_.info(f"ad_abtest_tag = {ad_abtest_tag}, "
  67. f"threshold_param_old = {threshold_param_old}, threshold_param_new = {threshold_param_new}")
  68. tag_list = ad_abtest_tag.split('-')
  69. for group_key in ad_mid_group_list:
  70. # 获取对应的阈值
  71. key_name = f"{config_.KEY_NAME_PREFIX_AD_THRESHOLD}{tag_list[0]}:{tag_list[1]}:{group_key}"
  72. threshold_old = redis_helper.get_data_from_redis(key_name=key_name)
  73. if threshold_old is None:
  74. continue
  75. # 计算新的阈值
  76. threshold_new = float(threshold_old) / threshold_param_old * threshold_param_new
  77. log_.info(f"ad_abtest_tag = {ad_abtest_tag}, group_key = {group_key}, "
  78. f"threshold_old = {threshold_old}, threshold_new = {threshold_new}")
  79. # 更新redis
  80. redis_helper.set_data_to_redis(key_name=key_name, value=threshold_new)
  81. def update_ad_abtest_threshold(project, table, dt, ad_abtest_abcode_config):
  82. # 获取当前阈值参数值
  83. threshold_record = redis_helper.get_data_from_redis(key_name=config_.KEY_NAME_PREFIX_AD_THRESHOLD_RECORD)
  84. threshold_record = eval(threshold_record)
  85. log_.info(f"threshold_record = {threshold_record}")
  86. # 获取uv数据
  87. feature_df = get_feature_data(project=project, table=table, features=features, dt=dt)
  88. feature_df['apptype'] = feature_df['apptype'].astype(int)
  89. feature_df['b'] = feature_df['b'].astype(float)
  90. # 根据活跃人数变化计算新的阈值参数
  91. threshold_record_new, robot_msg_record = get_threshold_record_new(
  92. ad_abtest_abcode_config=ad_abtest_abcode_config, feature_df=feature_df, threshold_record=threshold_record)
  93. log_.info(f"threshold_record_new = {threshold_record_new}")
  94. # 更新阈值
  95. update_threshold(threshold_record_old=threshold_record, threshold_record_new=threshold_record_new)
  96. # 更新阈值参数
  97. redis_helper.set_data_to_redis(key_name=config_.KEY_NAME_PREFIX_AD_THRESHOLD_RECORD,
  98. value=str(threshold_record_new))
  99. return robot_msg_record
  100. def timer_check():
  101. try:
  102. ad_abtest_abcode_config = config_.AD_ABTEST_ABCODE_CONFIG
  103. project = config_.AD_THRESHOLD_AUTO_UPDATE_DATA.get('project')
  104. table = config_.AD_THRESHOLD_AUTO_UPDATE_DATA.get('table')
  105. now_date = datetime.datetime.today()
  106. now_min = datetime.datetime.now().minute
  107. log_.info(f"now_date: {datetime.datetime.strftime(now_date, '%Y%m%d%H')}")
  108. dt = datetime.datetime.strftime(now_date - datetime.timedelta(hours=1), '%Y%m%d%H')
  109. # 查看当前更新的数据是否已准备好
  110. data_count = data_check(project=project, table=table, dt=dt)
  111. if data_count > 0:
  112. log_.info(f"data count = {data_count}")
  113. # 数据准备好,进行更新
  114. robot_msg_record = update_ad_abtest_threshold(
  115. project=project, table=table, dt=dt, ad_abtest_abcode_config=ad_abtest_abcode_config)
  116. if len(robot_msg_record) > 0:
  117. robot_msg_record_text = "\n".join([str(item) for item in robot_msg_record])
  118. msg = f"threshold_param_update: \n{robot_msg_record_text.replace(', ', ', ')}\n"
  119. else:
  120. msg = "无需更新!\n"
  121. send_msg_to_feishu(
  122. webhook=config_.FEISHU_ROBOT['ad_threshold_auto_update_robot'].get('webhook'),
  123. key_word=config_.FEISHU_ROBOT['ad_threshold_auto_update_robot'].get('key_word'),
  124. msg_text=f"rov-offline{config_.ENV_TEXT} - 阈值更新完成!\n{msg}"
  125. )
  126. log_.info(f"threshold update end!")
  127. elif now_min > 30:
  128. log_.info('threshold update data is None!')
  129. send_msg_to_feishu(
  130. webhook=config_.FEISHU_ROBOT['ad_threshold_auto_update_robot'].get('webhook'),
  131. key_word=config_.FEISHU_ROBOT['ad_threshold_auto_update_robot'].get('key_word'),
  132. msg_text=f"rov-offline{config_.ENV_TEXT} - 阈值更新相关数据未准备好!\n"
  133. )
  134. else:
  135. # 数据没准备好,1分钟后重新检查
  136. Timer(60, timer_check).start()
  137. except Exception as e:
  138. log_.error(f"阈值更新失败, exception: {e}, traceback: {traceback.format_exc()}")
  139. send_msg_to_feishu(
  140. webhook=config_.FEISHU_ROBOT['ad_threshold_auto_update_robot'].get('webhook'),
  141. key_word=config_.FEISHU_ROBOT['ad_threshold_auto_update_robot'].get('key_word'),
  142. msg_text=f"rov-offline{config_.ENV_TEXT} - 阈值更新失败\n"
  143. f"exception: {e}\n"
  144. f"traceback: {traceback.format_exc()}"
  145. )
  146. if __name__ == '__main__':
  147. timer_check()