run_category_model_v1.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. #! /usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # vim:fenc=utf-8
  4. #
  5. # Copyright © 2024 StrayWarrior <i@straywarrior.com>
  6. import sys
  7. import os
  8. sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))
  9. import time
  10. import json
  11. from datetime import datetime, timedelta
  12. import pandas as pd
  13. from argparse import ArgumentParser
  14. from long_articles.category_models import CategoryRegressionV1
  15. from long_articles.consts import reverse_category_name_map
  16. from common.database import MySQLManager
  17. from common import db_operation
  18. from common.logging import LOG
  19. from config.dev import Config
  20. NIGHT_ACCOUNTS = ('gh_12523d39d809','gh_df4a630c04db','gh_f67df16f4670','gh_ca44517edda9','gh_a66c1316fd5e','gh_4242c478bbba','gh_60b0c23fcc7c','gh_33b3470784fc','gh_ec1bcb283daf','gh_234ab9ff490d','gh_7715a626a4c6','gh_1bfe1d257728','gh_9db5e3ac2c93','gh_9d1ae5f9ceac','gh_7208b813f16d','gh_e56ddf195d91','gh_a43aecffe81b','gh_d4a7d2ce54fd','gh_c2b458818b09','gh_349a57ef1c44','gh_89bfe54ad90f','gh_b929ed680b62','gh_f8e8a931ff56','gh_916f4fad5ce0','gh_0d7c5f4c38a9','gh_bceef3f747c2','gh_706456719017','gh_fd51a5e33fc6','gh_5372093f5fb0','gh_957ff8e08e1b','gh_64fc629d3ec2','gh_c8b69797912a','gh_6909b38ad95f','gh_1e69a1b4dc1a','gh_0763523103e4','gh_9b83a9ad7da0','gh_82b416f27698','gh_a60647e98cd9','gh_3ce2fa1956ea','gh_44127c197525','gh_06834aba13a5','gh_c33809af68bc','gh_82cf39ef616e','gh_a342ef23c48e','gh_c9cc1471af7d','gh_291ec369f017','gh_810a439f320a','gh_00f942061a0d','gh_7662653b0e77','gh_d192d757b606','gh_391702d26b3b','gh_3e90f421c974','gh_30d189fe56c7','gh_7ebfbbf675ee','gh_3f84c2b9a1a2','gh_bccbe3681e22','gh_005fc1cb4b73','gh_21d120007b64','gh_3d5f24fd3311','gh_3621aaa6c4a0','gh_aee2dca32701','gh_c25c6040c4b2','gh_641019d44876','gh_95ba63e5cf18','gh_efd90dcf48ac','gh_5e1464b76ff6','gh_5765f834684c','gh_81bec2f4f577','gh_401396006e13','gh_7c33726c5147','gh_bbd8a52ba98b','gh_f74ca3104604'
  21. )
  22. def prepare_raw_data(dt_begin, dt_end):
  23. data_fields = ['dt', 'gh_id', 'account_name', 'title', 'similarity',
  24. 'view_count_rate', 'category', 'read_avg',
  25. 'read_avg_rate', 'first_pub_interval', '`index`']
  26. fields_str = ','.join(data_fields)
  27. db_manager = MySQLManager(Config().MYSQL_LONG_ARTICLES)
  28. night_accounts_condition = str(NIGHT_ACCOUNTS)
  29. sql = f"""
  30. SELECT {fields_str} FROM datastat_score WHERE dt BETWEEN {dt_begin} AND {dt_end}
  31. AND similarity > 0 AND category IS NOT NULL AND read_avg > 500
  32. AND read_avg_rate BETWEEN 0 AND 3
  33. AND `index` in (1, 2)
  34. AND (FROM_UNIXTIME(coalesce(publish_timestamp, 0), '%H') < '15'
  35. OR gh_id in {night_accounts_condition})
  36. """
  37. rows = db_manager.select(sql)
  38. df = pd.DataFrame(rows, columns=data_fields)
  39. df.rename(columns={'`index`': 'index'}, inplace=True)
  40. df = df.drop_duplicates(['dt', 'gh_id', 'title'])
  41. return df
  42. def clear_old_version(db_manager, dt):
  43. update_timestamp = int(time.time())
  44. sql = f"""
  45. UPDATE account_category
  46. SET status = 0, update_timestamp = {update_timestamp}
  47. WHERE dt < {dt} and status = 1
  48. """
  49. rows = db_manager.execute(sql)
  50. print(f"updated rows: {rows}")
  51. def get_last_version(db_manager, dt):
  52. sql = f"""
  53. SELECT gh_id, category_map
  54. FROM account_category
  55. WHERE dt = (SELECT max(dt) FROM account_category WHERE dt < {dt})
  56. """
  57. data = db_manager.select(sql)
  58. return data
  59. def compare_version(db_manager, dt_version, new_version, account_id_map):
  60. last_version = get_last_version(db_manager, dt_version)
  61. last_version = { entry[0]: json.loads(entry[1]) for entry in last_version }
  62. new_version = { entry['gh_id']: json.loads(entry['category_map']) for entry in new_version }
  63. # new record
  64. all_gh_ids = set(list(new_version.keys()) + list(last_version.keys()))
  65. for gh_id in all_gh_ids:
  66. account_name = account_id_map.get(gh_id, None)
  67. if gh_id not in last_version:
  68. print(f"new account {account_name}: {new_version[gh_id]}")
  69. elif gh_id not in new_version:
  70. print(f"old account {account_name}: {last_version[gh_id]}")
  71. else:
  72. new_cates = new_version[gh_id]
  73. old_cates = last_version[gh_id]
  74. for cate in new_cates:
  75. if cate not in old_cates:
  76. print(f"account {account_name} new cate: {cate} {new_cates[cate]}")
  77. for cate in old_cates:
  78. if cate not in new_cates:
  79. print(f"account {account_name} old cate: {cate} {old_cates[cate]}")
  80. def main():
  81. parser = ArgumentParser()
  82. parser.add_argument('-n', '--dry-run', action='store_true', help='do not update database')
  83. parser.add_argument('--run-at', help='dt, also for version')
  84. parser.add_argument('--print-matrix', action='store_true')
  85. parser.add_argument('--print-residual', action='store_true')
  86. args = parser.parse_args()
  87. run_date = datetime.today()
  88. if args.run_at:
  89. run_date = datetime.strptime(args.run_at, "%Y%m%d")
  90. begin_dt = 20240914
  91. end_dt = (run_date - timedelta(1)).strftime("%Y%m%d")
  92. dt_version = end_dt
  93. LOG.info(f"data range: {begin_dt} - {end_dt}")
  94. raw_df = prepare_raw_data(begin_dt, end_dt)
  95. cate_model = CategoryRegressionV1()
  96. df = cate_model.preprocess_data(raw_df)
  97. if args.dry_run and args.print_matrix:
  98. cate_model.build_and_print_matrix(df)
  99. return
  100. create_timestamp = int(time.time())
  101. update_timestamp = create_timestamp
  102. records_to_save = []
  103. param_to_category_map = reverse_category_name_map
  104. account_ids = df['gh_id'].unique()
  105. account_id_map = df[['account_name', 'gh_id']].drop_duplicates() \
  106. .set_index('gh_id')['account_name'].to_dict()
  107. account_negative_cates = {k: [] for k in account_ids}
  108. P_VALUE_THRESHOLD = 0.15
  109. for account_id in account_ids:
  110. sub_df = df[df['gh_id'] == account_id]
  111. account_name = account_id_map[account_id]
  112. sample_count = len(sub_df)
  113. if sample_count < 5:
  114. continue
  115. params, t_stats, p_values = cate_model.run_ols_linear_regression(
  116. sub_df, args.print_residual, P_VALUE_THRESHOLD)
  117. current_record = {}
  118. current_record['dt'] = dt_version
  119. current_record['gh_id'] = account_id
  120. current_record['category_map'] = {}
  121. param_names = cate_model.get_param_names()
  122. for name, param, p_value in zip(param_names, params, p_values):
  123. cate_name = param_to_category_map.get(name, None)
  124. # 用于排序的品类相关性
  125. if abs(param) > 0.1 and p_value < P_VALUE_THRESHOLD and cate_name is not None:
  126. scale_factor = min(0.1 / p_value, 1)
  127. print(f"{account_id} {account_name} {cate_name} {param:.3f} {p_value:.3f}")
  128. truncate_param = round(max(min(param, 0.25), -0.3) * scale_factor, 6)
  129. current_record['category_map'][cate_name] = truncate_param
  130. # 用于冷启文章分配的负向品类
  131. if param < -0.1 and cate_name is not None and p_value < P_VALUE_THRESHOLD:
  132. account_negative_cates[account_id].append(cate_name)
  133. # print((account_name, cate_name, param, p_value))
  134. if not current_record['category_map']:
  135. continue
  136. current_record['category_map'] = json.dumps(current_record['category_map'], ensure_ascii=False)
  137. current_record['status'] = 1
  138. current_record['create_timestamp'] = create_timestamp
  139. current_record['update_timestamp'] = update_timestamp
  140. records_to_save.append(current_record)
  141. db_manager = MySQLManager(Config().MYSQL_LONG_ARTICLES)
  142. if args.dry_run:
  143. compare_version(db_manager, dt_version, records_to_save, account_id_map)
  144. return
  145. db_manager.batch_insert('account_category', records_to_save)
  146. clear_old_version(db_manager, dt_version)
  147. # 过滤空账号
  148. for account_id in [*account_negative_cates.keys()]:
  149. if not account_negative_cates[account_id]:
  150. account_negative_cates.pop(account_id)
  151. # print(json.dumps(account_negative_cates, ensure_ascii=False, indent=2))
  152. if __name__ == '__main__':
  153. main()