cal_account_read_rate_avg_daily.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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
  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_detail = json.loads(config.getConfigValue("backup_account_detail"))
  22. functions = Functions()
  23. read_rate_table = "long_articles_read_rate_dev"
  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, 0)
  64. if not fans:
  65. fans = int(unauthorized_account.get(gh_id, 0))
  66. if not fans:
  67. fans = int(backup_account_detail.get(gh_id, 0))
  68. line['fans'] = fans
  69. if fans > 1000:
  70. line['readRate'] = line['show_view_count'] / fans if fans else 0
  71. response.append(line)
  72. return DataFrame(response, columns=['ghId', 'accountName', 'ItemIndex', 'show_view_count', 'publish_timestamp', 'readRate'])
  73. def cal_avg_account_read_rate(df, gh_id, index, dt) -> dict:
  74. """
  75. 计算账号的阅读率均值
  76. :return:
  77. """
  78. max_time = functions.str_to_timestamp(date_string=dt)
  79. min_time = max_time - const.STATISTICS_PERIOD
  80. # 通过
  81. filter_dataframe = df[
  82. (df["ghId"] == gh_id)
  83. & (min_time <= df["publish_timestamp"])
  84. & (df["publish_timestamp"] <= max_time)
  85. & (df['ItemIndex'] == index)
  86. ]
  87. # 用二倍标准差过滤
  88. final_dataframe = filter_outlier_data(filter_dataframe)
  89. return {
  90. "read_rate_avg": final_dataframe['readRate'].mean(),
  91. "max_publish_time": final_dataframe['publish_timestamp'].max(),
  92. "min_publish_time": final_dataframe['publish_timestamp'].min(),
  93. "records": len(final_dataframe)
  94. }
  95. def check_each_position(db_client, gh_id, index, dt, avg_rate) -> dict:
  96. """
  97. 检验某个具体账号的具体文章的阅读率均值和前段日子的比较
  98. :param avg_rate: 当天计算出的阅读率均值
  99. :param db_client: 数据库连接
  100. :param gh_id: 账号 id
  101. :param index: 账号 index
  102. :param dt:
  103. :return:
  104. """
  105. dt = int(dt.replace("-", ""))
  106. select_sql = f"""
  107. SELECT account_name, read_rate_avg
  108. FROM {read_rate_table}
  109. WHERE gh_id = '{gh_id}' and position = {index} and dt_version < {dt}
  110. ORDER BY dt_version DESC limit 1;
  111. """
  112. result = db_client.select(select_sql)
  113. if result:
  114. account_name = result[0][0]
  115. previous_read_rate_avg = result[0][1]
  116. relative_value = (avg_rate - previous_read_rate_avg) / previous_read_rate_avg
  117. if -const.RELATIVE_VALUE_THRESHOLD <= relative_value <= const.RELATIVE_VALUE_THRESHOLD:
  118. return {}
  119. else:
  120. response = {
  121. "account_name": account_name,
  122. "position": index,
  123. "read_rate_avg_yesterday": Functions().float_to_percentage(avg_rate),
  124. "read_rate_avg_the_day_before_yesterday": Functions().float_to_percentage(previous_read_rate_avg),
  125. "relative_change_rate": [
  126. {
  127. "text": Functions().float_to_percentage(relative_value),
  128. "color": "red" if relative_value < 0 else "green"
  129. }
  130. ]
  131. }
  132. return response
  133. def update_single_day(dt, account_list, article_df, lam):
  134. """
  135. 更新单天数据
  136. :param article_df:
  137. :param lam:
  138. :param account_list:
  139. :param dt:
  140. :return:
  141. """
  142. error_list = []
  143. insert_error_list = []
  144. update_timestamp = functions.str_to_timestamp(date_string=dt)
  145. # 因为计算均值的时候是第二天,所以需要把时间前移一天
  146. avg_date = functions.timestamp_to_str(
  147. timestamp=update_timestamp - const.ONE_DAY_IN_SECONDS,
  148. string_format='%Y-%m-%d'
  149. )
  150. process_account_cnt = 0
  151. for account in tqdm(account_list, desc=dt):
  152. for index in const.ARTICLE_INDEX_LIST:
  153. read_rate_detail = cal_avg_account_read_rate(
  154. df=article_df,
  155. gh_id=account['gh_id'],
  156. index=index,
  157. dt=dt
  158. )
  159. read_rate_avg = read_rate_detail['read_rate_avg']
  160. max_publish_time = read_rate_detail['max_publish_time']
  161. min_publish_time = read_rate_detail['min_publish_time']
  162. articles_count = read_rate_detail['records']
  163. if articles_count:
  164. process_account_cnt += 1
  165. if index in {1, 2}:
  166. error_obj = check_each_position(
  167. db_client=lam,
  168. gh_id=account['gh_id'],
  169. index=index,
  170. dt=dt,
  171. avg_rate=read_rate_avg
  172. )
  173. if error_obj:
  174. error_list.append(error_obj)
  175. try:
  176. if not read_rate_avg:
  177. continue
  178. insert_sql = f"""
  179. INSERT INTO {read_rate_table}
  180. (account_name, gh_id, position, read_rate_avg, remark, articles_count, earliest_publish_time, latest_publish_time, dt_version, is_delete)
  181. values
  182. (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
  183. """
  184. lam.update(
  185. sql=insert_sql,
  186. params=(
  187. account['account_name'],
  188. account['gh_id'],
  189. index,
  190. read_rate_avg,
  191. "从 {} 开始往前计算 31 天".format(dt),
  192. articles_count,
  193. functions.timestamp_to_str(timestamp=min_publish_time, string_format='%Y-%m-%d'),
  194. functions.timestamp_to_str(timestamp=max_publish_time, string_format='%Y-%m-%d'),
  195. avg_date.replace("-", ""),
  196. 0
  197. )
  198. )
  199. except Exception as e:
  200. insert_error_list.append(str(e))
  201. print(process_account_cnt)
  202. # if insert_error_list:
  203. # bot(
  204. # title="更新阅读率均值,存在sql 插入失败",
  205. # detail=insert_error_list
  206. # )
  207. #
  208. # if error_list:
  209. # columns = [
  210. # create_feishu_columns_sheet(sheet_type="plain_text", sheet_name="account_name", display_name="账号名称"),
  211. # create_feishu_columns_sheet(sheet_type="plain_text", sheet_name="position", display_name="文章位置"),
  212. # create_feishu_columns_sheet(sheet_type="plain_text", sheet_name="read_rate_avg_yesterday",
  213. # display_name="昨日阅读率均值"),
  214. # create_feishu_columns_sheet(sheet_type="plain_text", sheet_name="read_rate_avg_the_day_before_yesterday",
  215. # display_name="前天阅读率均值"),
  216. # create_feishu_columns_sheet(sheet_type="options", sheet_name="relative_change_rate",
  217. # display_name="相对变化率")
  218. # ]
  219. # bot(
  220. # title="更新阅读率均值,头次出现异常值通知",
  221. # detail={
  222. # "columns": columns,
  223. # "rows": error_list
  224. # },
  225. # table=True,
  226. # mention=False
  227. # )
  228. #
  229. # if not error_list and not insert_error_list:
  230. # bot(
  231. # title="阅读率均值表,更新成功",
  232. # detail={
  233. # "日期": dt
  234. # }
  235. # )
  236. def main() -> None:
  237. """
  238. main function
  239. :return:
  240. """
  241. parser = ArgumentParser()
  242. parser.add_argument("--run-date",
  243. help="Run only once for date in format of %Y-%m-%d. \
  244. If no specified, run as daily jobs.")
  245. args = parser.parse_args()
  246. if args.run_date:
  247. dt = args.run_date
  248. else:
  249. dt = datetime.today().strftime('%Y-%m-%d')
  250. # init stat period
  251. max_time = functions.str_to_timestamp(date_string=dt)
  252. min_time = max_time - const.STATISTICS_PERIOD
  253. min_stat_date = functions.timestamp_to_str(timestamp=min_time, string_format='%Y-%m-%d')
  254. # init database connector
  255. long_articles_db_client = DatabaseConnector(db_config=long_articles_config)
  256. long_articles_db_client.connect()
  257. piaoquan_crawler_db_client = DatabaseConnector(db_config=piaoquan_crawler_config)
  258. piaoquan_crawler_db_client.connect()
  259. denet_db_client = DatabaseConnector(db_config=denet_config)
  260. denet_db_client.connect()
  261. # get account list
  262. account_list = fetch_publishing_account_list(db_client=denet_db_client)
  263. # get fans dict
  264. fans_dict = fetch_account_fans(db_client=denet_db_client, start_date=min_stat_date)
  265. # get data frame from official_articles_v2
  266. gh_id_tuple = tuple([i['gh_id'] for i in account_list])
  267. article_list = get_account_articles_detail(db_client=piaoquan_crawler_db_client, gh_id_tuple=gh_id_tuple, min_publish_timestamp=min_time)
  268. # cal account read rate and make a dataframe
  269. read_rate_dataframe = cal_account_read_rate(article_list, fans_dict)
  270. # update each day's data
  271. update_single_day(dt, account_list, read_rate_dataframe, long_articles_db_client)
  272. if __name__ == '__main__':
  273. main()