cal_account_read_rate_avg_daily.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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_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, 0)
  64. if not fans:
  65. fans = int(unauthorized_account.get(gh_id, 0))
  66. if not fans:
  67. fans = int(backup_account_fans.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.fetch(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. # processed_account_set
  151. processed_account_set = set()
  152. for account in tqdm(account_list, desc=dt):
  153. for index in const.ARTICLE_INDEX_LIST:
  154. read_rate_detail = cal_avg_account_read_rate(
  155. df=article_df,
  156. gh_id=account['gh_id'],
  157. index=index,
  158. dt=dt
  159. )
  160. read_rate_avg = read_rate_detail['read_rate_avg']
  161. max_publish_time = read_rate_detail['max_publish_time']
  162. min_publish_time = read_rate_detail['min_publish_time']
  163. articles_count = read_rate_detail['records']
  164. if articles_count:
  165. processed_account_set.add(account['gh_id'])
  166. # check read rate in position 1 and 2
  167. if index in [1, 2]:
  168. error_obj = check_each_position(
  169. db_client=lam,
  170. gh_id=account['gh_id'],
  171. index=index,
  172. dt=dt,
  173. avg_rate=read_rate_avg
  174. )
  175. if error_obj:
  176. error_list.append(error_obj)
  177. # insert into database
  178. try:
  179. if not read_rate_avg:
  180. continue
  181. insert_sql = f"""
  182. INSERT INTO {read_rate_table}
  183. (account_name, gh_id, position, read_rate_avg, remark, articles_count, earliest_publish_time, latest_publish_time, dt_version, is_delete)
  184. values
  185. (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
  186. """
  187. lam.save(
  188. query=insert_sql,
  189. params=(
  190. account['account_name'],
  191. account['gh_id'],
  192. index,
  193. read_rate_avg,
  194. "从 {} 开始往前计算 31 天".format(dt),
  195. articles_count,
  196. functions.timestamp_to_str(timestamp=min_publish_time, string_format='%Y-%m-%d'),
  197. functions.timestamp_to_str(timestamp=max_publish_time, string_format='%Y-%m-%d'),
  198. avg_date.replace("-", ""),
  199. 0
  200. )
  201. )
  202. except Exception as e:
  203. print(e)
  204. insert_error_list.append(str(e))
  205. # bot sql error
  206. if insert_error_list:
  207. bot(
  208. title="更新阅读率均值,存在sql 插入失败",
  209. detail=insert_error_list
  210. )
  211. # bot outliers
  212. if error_list:
  213. columns = [
  214. create_feishu_columns_sheet(sheet_type="plain_text", sheet_name="account_name", display_name="账号名称"),
  215. create_feishu_columns_sheet(sheet_type="plain_text", sheet_name="position", display_name="文章位置"),
  216. create_feishu_columns_sheet(sheet_type="plain_text", sheet_name="read_rate_avg_yesterday",
  217. display_name="昨日阅读率均值"),
  218. create_feishu_columns_sheet(sheet_type="plain_text", sheet_name="read_rate_avg_the_day_before_yesterday",
  219. display_name="前天阅读率均值"),
  220. create_feishu_columns_sheet(sheet_type="options", sheet_name="relative_change_rate",
  221. display_name="相对变化率")
  222. ]
  223. bot(
  224. title="阅读率均值表异常信息, 总共处理{}个账号".format(len(processed_account_set)),
  225. detail={
  226. "columns": columns,
  227. "rows": error_list
  228. },
  229. table=True,
  230. mention=False
  231. )
  232. # if no error, send success info
  233. if not error_list and not insert_error_list:
  234. bot(
  235. title="阅读率均值表更新成功, 总共处理{}个账号".format(len(processed_account_set)),
  236. detail={
  237. "日期": dt
  238. },
  239. mention=False
  240. )
  241. def main() -> None:
  242. """
  243. main function
  244. :return:
  245. """
  246. parser = ArgumentParser()
  247. parser.add_argument("--run-date",
  248. help="Run only once for date in format of %Y-%m-%d. \
  249. If no specified, run as daily jobs.")
  250. args = parser.parse_args()
  251. if args.run_date:
  252. dt = args.run_date
  253. else:
  254. dt = datetime.today().strftime('%Y-%m-%d')
  255. # init stat period
  256. max_time = functions.str_to_timestamp(date_string=dt)
  257. min_time = max_time - const.STATISTICS_PERIOD
  258. min_stat_date = functions.timestamp_to_str(timestamp=min_time, string_format='%Y-%m-%d')
  259. # init database connector
  260. long_articles_db_client = DatabaseConnector(db_config=long_articles_config)
  261. long_articles_db_client.connect()
  262. piaoquan_crawler_db_client = DatabaseConnector(db_config=piaoquan_crawler_config)
  263. piaoquan_crawler_db_client.connect()
  264. denet_db_client = DatabaseConnector(db_config=denet_config)
  265. denet_db_client.connect()
  266. # get account list
  267. account_list = fetch_publishing_account_list(db_client=denet_db_client)
  268. # get fans dict
  269. fans_dict = fetch_account_fans(db_client=denet_db_client, start_date=min_stat_date)
  270. # get data frame from official_articles_v2
  271. gh_id_tuple = tuple([i['gh_id'] for i in account_list])
  272. article_list = get_account_articles_detail(db_client=piaoquan_crawler_db_client, gh_id_tuple=gh_id_tuple, min_publish_timestamp=min_time)
  273. # cal account read rate and make a dataframe
  274. read_rate_dataframe = cal_account_read_rate(article_list, fans_dict)
  275. # update each day's data
  276. update_single_day(dt, account_list, read_rate_dataframe, long_articles_db_client)
  277. if __name__ == '__main__':
  278. main()