cal_account_read_rate_avg_daily.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. """
  2. @author: luojunhui
  3. cal each account && position reading rate
  4. """
  5. import json
  6. from tqdm import tqdm
  7. from pandas import DataFrame
  8. from argparse import ArgumentParser
  9. from datetime import datetime
  10. from pymysql.cursors import DictCursor
  11. from applications import bot, Functions, log
  12. from applications import create_feishu_columns_sheet
  13. from applications.db import DatabaseConnector
  14. from applications.const import UpdateAccountReadRateTaskConst
  15. from applications.utils import fetch_publishing_account_list
  16. from applications.utils import fetch_account_fans
  17. from config import apolloConfig, long_articles_config, piaoquan_crawler_config, denet_config
  18. const = UpdateAccountReadRateTaskConst()
  19. config = apolloConfig()
  20. unauthorized_account = json.loads(config.getConfigValue("unauthorized_gh_id_fans"))
  21. backup_account_fans = json.loads(config.getConfigValue("backup_account_fans"))
  22. functions = Functions()
  23. read_rate_table = "long_articles_read_rate"
  24. def filter_outlier_data(group, key='show_view_count'):
  25. """
  26. :param group:
  27. :param key:
  28. :return:
  29. """
  30. mean = group[key].mean()
  31. std = group[key].std()
  32. # 过滤二倍标准差的数据
  33. filtered_group = group[(group[key] > mean - 2 * std) & (group[key] < mean + 2 * std)]
  34. # 过滤均值倍数大于5的数据
  35. new_mean = filtered_group[key].mean()
  36. # print("阅读均值", new_mean)
  37. filtered_group = filtered_group[filtered_group[key] < new_mean * 5]
  38. return filtered_group
  39. def get_account_articles_detail(db_client, gh_id_tuple, min_publish_timestamp) -> list[dict]:
  40. """
  41. get articles details
  42. :return:
  43. """
  44. sql = f"""
  45. SELECT
  46. ghId, accountName, ItemIndex, show_view_count, publish_timestamp
  47. FROM
  48. official_articles_v2
  49. WHERE
  50. ghId IN {gh_id_tuple} and Type = '{const.BULK_PUBLISH_TYPE}' and publish_timestamp >= {min_publish_timestamp};
  51. """
  52. response_list = db_client.fetch(query=sql, cursor_type=DictCursor)
  53. return response_list
  54. def cal_account_read_rate(article_list, fans_dict) -> DataFrame:
  55. """
  56. 计算账号位置的阅读率
  57. :return:
  58. """
  59. response = []
  60. for line in article_list:
  61. gh_id = line['ghId']
  62. dt = functions.timestamp_to_str(timestamp=line['publish_timestamp'], string_format='%Y-%m-%d')
  63. fans = fans_dict.get(gh_id, {}).get(dt, const.DEFAULT_FANS)
  64. if not fans:
  65. fans = int(unauthorized_account.get(gh_id, const.DEFAULT_FANS))
  66. if not fans:
  67. fans = int(backup_account_fans.get(gh_id, const.DEFAULT_FANS))
  68. log(
  69. task='cal_read_rate_avg_task',
  70. function='cal_account_read_rate',
  71. message='未获取到粉丝,使用备份粉丝表',
  72. data=line
  73. )
  74. line['fans'] = fans
  75. if fans > const.MIN_FANS:
  76. line['readRate'] = line['show_view_count'] / fans if fans else 0
  77. response.append(line)
  78. return DataFrame(response, columns=['ghId', 'accountName', 'ItemIndex', 'show_view_count', 'publish_timestamp', 'readRate'])
  79. def cal_avg_account_read_rate(df, gh_id, index, dt) -> dict:
  80. """
  81. 计算账号的阅读率均值
  82. :return:
  83. """
  84. max_time = functions.str_to_timestamp(date_string=dt)
  85. min_time = max_time - const.STATISTICS_PERIOD
  86. # 通过
  87. filter_dataframe = df[
  88. (df["ghId"] == gh_id)
  89. & (min_time <= df["publish_timestamp"])
  90. & (df["publish_timestamp"] <= max_time)
  91. & (df['ItemIndex'] == index)
  92. ]
  93. # 用二倍标准差过滤
  94. final_dataframe = filter_outlier_data(filter_dataframe)
  95. return {
  96. "read_rate_avg": final_dataframe['readRate'].mean(),
  97. "max_publish_time": final_dataframe['publish_timestamp'].max(),
  98. "min_publish_time": final_dataframe['publish_timestamp'].min(),
  99. "records": len(final_dataframe)
  100. }
  101. def check_each_position(db_client, gh_id, index, dt, avg_rate) -> dict:
  102. """
  103. 检验某个具体账号的具体文章的阅读率均值和前段日子的比较
  104. :param avg_rate: 当天计算出的阅读率均值
  105. :param db_client: 数据库连接
  106. :param gh_id: 账号 id
  107. :param index: 账号 index
  108. :param dt:
  109. :return:
  110. """
  111. dt = int(dt.replace("-", ""))
  112. select_sql = f"""
  113. SELECT account_name, read_rate_avg
  114. FROM {read_rate_table}
  115. WHERE gh_id = '{gh_id}' and position = {index} and dt_version < {dt}
  116. ORDER BY dt_version DESC limit 1;
  117. """
  118. result = db_client.fetch(select_sql)
  119. if result:
  120. account_name = result[0][0]
  121. previous_read_rate_avg = result[0][1]
  122. relative_value = (avg_rate - previous_read_rate_avg) / previous_read_rate_avg
  123. if -const.RELATIVE_VALUE_THRESHOLD <= relative_value <= const.RELATIVE_VALUE_THRESHOLD:
  124. return {}
  125. else:
  126. response = {
  127. "account_name": account_name,
  128. "position": index,
  129. "read_rate_avg_yesterday": Functions().float_to_percentage(avg_rate),
  130. "read_rate_avg_the_day_before_yesterday": Functions().float_to_percentage(previous_read_rate_avg),
  131. "relative_change_rate": [
  132. {
  133. "text": Functions().float_to_percentage(relative_value),
  134. "color": "red" if relative_value < 0 else "green"
  135. }
  136. ]
  137. }
  138. return response
  139. def update_single_day(dt, account_list, article_df, lam):
  140. """
  141. 更新单天数据
  142. :param article_df:
  143. :param lam:
  144. :param account_list:
  145. :param dt:
  146. :return:
  147. """
  148. error_list = []
  149. insert_error_list = []
  150. update_timestamp = functions.str_to_timestamp(date_string=dt)
  151. # 因为计算均值的时候是第二天,所以需要把时间前移一天
  152. avg_date = functions.timestamp_to_str(
  153. timestamp=update_timestamp - const.ONE_DAY_IN_SECONDS,
  154. string_format='%Y-%m-%d'
  155. )
  156. # processed_account_set
  157. processed_account_set = set()
  158. for account in tqdm(account_list, desc=dt):
  159. for index in const.ARTICLE_INDEX_LIST:
  160. read_rate_detail = cal_avg_account_read_rate(
  161. df=article_df,
  162. gh_id=account['gh_id'],
  163. index=index,
  164. dt=dt
  165. )
  166. read_rate_avg = read_rate_detail['read_rate_avg']
  167. max_publish_time = read_rate_detail['max_publish_time']
  168. min_publish_time = read_rate_detail['min_publish_time']
  169. articles_count = read_rate_detail['records']
  170. if articles_count:
  171. processed_account_set.add(account['gh_id'])
  172. # check read rate in position 1 and 2
  173. if index in [1, 2]:
  174. error_obj = check_each_position(
  175. db_client=lam,
  176. gh_id=account['gh_id'],
  177. index=index,
  178. dt=dt,
  179. avg_rate=read_rate_avg
  180. )
  181. if error_obj:
  182. error_list.append(error_obj)
  183. # insert into database
  184. try:
  185. if not read_rate_avg:
  186. continue
  187. insert_sql = f"""
  188. INSERT INTO {read_rate_table}
  189. (account_name, gh_id, position, read_rate_avg, remark, articles_count, earliest_publish_time, latest_publish_time, dt_version, is_delete)
  190. values
  191. (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
  192. """
  193. lam.save(
  194. query=insert_sql,
  195. params=(
  196. account['account_name'],
  197. account['gh_id'],
  198. index,
  199. read_rate_avg,
  200. "从 {} 开始往前计算 31 天".format(dt),
  201. articles_count,
  202. functions.timestamp_to_str(timestamp=min_publish_time, string_format='%Y-%m-%d'),
  203. functions.timestamp_to_str(timestamp=max_publish_time, string_format='%Y-%m-%d'),
  204. avg_date.replace("-", ""),
  205. 0
  206. )
  207. )
  208. except Exception as e:
  209. print(e)
  210. insert_error_list.append(str(e))
  211. # bot sql error
  212. if insert_error_list:
  213. bot(
  214. title="更新阅读率均值,存在sql 插入失败",
  215. detail=insert_error_list
  216. )
  217. # bot outliers
  218. if error_list:
  219. columns = [
  220. create_feishu_columns_sheet(sheet_type="plain_text", sheet_name="account_name", display_name="账号名称"),
  221. create_feishu_columns_sheet(sheet_type="plain_text", sheet_name="position", display_name="文章位置"),
  222. create_feishu_columns_sheet(sheet_type="plain_text", sheet_name="read_rate_avg_yesterday",
  223. display_name="昨日阅读率均值"),
  224. create_feishu_columns_sheet(sheet_type="plain_text", sheet_name="read_rate_avg_the_day_before_yesterday",
  225. display_name="前天阅读率均值"),
  226. create_feishu_columns_sheet(sheet_type="options", sheet_name="relative_change_rate",
  227. display_name="相对变化率")
  228. ]
  229. bot(
  230. title="阅读率均值表异常信息, 总共处理{}个账号".format(len(processed_account_set)),
  231. detail={
  232. "columns": columns,
  233. "rows": error_list
  234. },
  235. table=True,
  236. mention=False
  237. )
  238. # if no error, send success info
  239. if not error_list and not insert_error_list:
  240. bot(
  241. title="阅读率均值表更新成功, 总共处理{}个账号".format(len(processed_account_set)),
  242. detail={
  243. "日期": dt
  244. },
  245. mention=False
  246. )
  247. def main() -> None:
  248. """
  249. main function
  250. :return:
  251. """
  252. parser = ArgumentParser()
  253. parser.add_argument("--run-date",
  254. help="Run only once for date in format of %Y-%m-%d. \
  255. If no specified, run as daily jobs.")
  256. args = parser.parse_args()
  257. if args.run_date:
  258. dt = args.run_date
  259. else:
  260. dt = datetime.today().strftime('%Y-%m-%d')
  261. # init stat period
  262. max_time = functions.str_to_timestamp(date_string=dt)
  263. min_time = max_time - const.STATISTICS_PERIOD
  264. min_stat_date = functions.timestamp_to_str(timestamp=min_time, string_format='%Y-%m-%d')
  265. # init database connector
  266. long_articles_db_client = DatabaseConnector(db_config=long_articles_config)
  267. long_articles_db_client.connect()
  268. piaoquan_crawler_db_client = DatabaseConnector(db_config=piaoquan_crawler_config)
  269. piaoquan_crawler_db_client.connect()
  270. denet_db_client = DatabaseConnector(db_config=denet_config)
  271. denet_db_client.connect()
  272. # get account list
  273. account_list = fetch_publishing_account_list(db_client=denet_db_client)
  274. # get fans dict
  275. fans_dict = fetch_account_fans(db_client=denet_db_client, start_date=min_stat_date)
  276. # get data frame from official_articles_v2
  277. gh_id_tuple = tuple([i['gh_id'] for i in account_list])
  278. article_list = get_account_articles_detail(db_client=piaoquan_crawler_db_client, gh_id_tuple=gh_id_tuple, min_publish_timestamp=min_time)
  279. # cal account read rate and make a dataframe
  280. read_rate_dataframe = cal_account_read_rate(article_list, fans_dict)
  281. # update each day's data
  282. update_single_day(dt, account_list, read_rate_dataframe, long_articles_db_client)
  283. if __name__ == '__main__':
  284. main()