ad_threshold_auto_update.py 6.8 KB

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