cal_account_read_rate_avg_daily.py 12 KB

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