cal_account_read_rate_avg_daily.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. """
  2. @author: luojunhui
  3. cal each account && position reading rate
  4. """
  5. from tqdm import tqdm
  6. from pandas import DataFrame
  7. from argparse import ArgumentParser
  8. from datetime import datetime
  9. from applications import DeNetMysql, PQMySQL, longArticlesMySQL, bot, Functions
  10. from applications.const import updateAccountReadRateTaskConst
  11. const = updateAccountReadRateTaskConst()
  12. functions = Functions()
  13. read_rate_table = "long_articles_read_rate"
  14. def filter_outlier_data(group, key='show_view_count'):
  15. """
  16. :param group:
  17. :param key:
  18. :return:
  19. """
  20. mean = group[key].mean()
  21. std = group[key].std()
  22. # 过滤二倍标准差的数据
  23. filtered_group = group[(group[key] > mean - 2 * std) & (group[key] < mean + 2 * std)]
  24. # 过滤均值倍数大于5的数据
  25. new_mean = filtered_group[key].mean()
  26. # print("阅读均值", new_mean)
  27. filtered_group = filtered_group[filtered_group[key] < new_mean * 5]
  28. return filtered_group
  29. def get_account_fans_by_dt(db_client) -> dict:
  30. """
  31. 获取每个账号发粉丝,通过日期来区分
  32. :return:
  33. """
  34. sql = f"""
  35. SELECT
  36. t1.date_str,
  37. t1.fans_count,
  38. t2.gh_id
  39. FROM datastat_wx t1
  40. JOIN publish_account t2 ON t1.account_id = t2.id
  41. WHERE
  42. t2.channel = 5
  43. AND t2.status = 1
  44. AND t1.date_str >= '2024-07-01'
  45. ORDER BY t1.date_str;
  46. """
  47. result = db_client.select(sql)
  48. D = {}
  49. for line in result:
  50. dt = line[0]
  51. fans = line[1]
  52. gh_id = line[2]
  53. if D.get(gh_id):
  54. D[gh_id][dt] = fans
  55. else:
  56. D[gh_id] = {dt: fans}
  57. return D
  58. def get_publishing_accounts(db_client) -> list[dict]:
  59. """
  60. 获取每日正在发布的账号
  61. :return:
  62. """
  63. sql = f"""
  64. SELECT DISTINCT
  65. t3.`name`,
  66. t3.gh_id,
  67. t3.follower_count,
  68. t6.account_source_name,
  69. t6.mode_type,
  70. t6.account_type,
  71. t6.`status`
  72. FROM
  73. publish_plan t1
  74. JOIN publish_plan_account t2 ON t1.id = t2.plan_id
  75. JOIN publish_account t3 ON t2.account_id = t3.id
  76. LEFT JOIN publish_account_wx_type t4 on t3.id = t4.account_id
  77. LEFT JOIN wx_statistics_group_source_account t5 on t3.id = t5.account_id
  78. LEFT JOIN wx_statistics_group_source t6 on t5.group_source_name = t6.account_source_name
  79. WHERE
  80. t1.plan_status = 1
  81. AND t3.channel = 5
  82. AND t3.follower_count > 0
  83. GROUP BY t3.id;
  84. """
  85. account_list = db_client.select(sql)
  86. result_list = [
  87. {
  88. "account_name": i[0],
  89. "gh_id": i[1]
  90. } for i in account_list
  91. ]
  92. return result_list
  93. def get_account_articles_detail(db_client, gh_id_tuple) -> list[dict]:
  94. """
  95. get articles details
  96. :return:
  97. """
  98. sql = f"""
  99. SELECT
  100. ghId, accountName, ItemIndex, show_view_count, publish_timestamp
  101. FROM
  102. official_articles_v2
  103. WHERE
  104. ghId IN {gh_id_tuple} and Type = '{const.BULK_PUBLISH_TYPE}';
  105. """
  106. result = db_client.select(sql)
  107. response_list = [
  108. {
  109. "ghId": i[0],
  110. "accountName": i[1],
  111. "ItemIndex": i[2],
  112. "show_view_count": i[3],
  113. "publish_timestamp": i[4]
  114. }
  115. for i in result
  116. ]
  117. return response_list
  118. def cal_account_read_rate(gh_id_tuple) -> DataFrame:
  119. """
  120. 计算账号位置的阅读率
  121. :return:
  122. """
  123. pq_db = PQMySQL()
  124. de_db = DeNetMysql()
  125. response = []
  126. fans_dict_each_day = get_account_fans_by_dt(db_client=de_db)
  127. account_article_detail = get_account_articles_detail(
  128. db_client=pq_db,
  129. gh_id_tuple=gh_id_tuple
  130. )
  131. for line in account_article_detail:
  132. gh_id = line['ghId']
  133. dt = functions.timestamp_to_str(timestamp=line['publish_timestamp'], string_format='%Y-%m-%d')
  134. fans = fans_dict_each_day.get(gh_id, {}).get(dt, 0)
  135. line['fans'] = fans
  136. if fans > 1000:
  137. line['readRate'] = line['show_view_count'] / fans if fans else 0
  138. response.append(line)
  139. return DataFrame(response,
  140. columns=['ghId', 'accountName', 'ItemIndex', 'show_view_count', 'publish_timestamp', 'readRate'])
  141. def cal_avg_account_read_rate(df, gh_id, index, dt) -> dict:
  142. """
  143. 计算账号的阅读率均值
  144. :return:
  145. """
  146. max_time = functions.str_to_timestamp(date_string=dt)
  147. min_time = max_time - const.STATISTICS_PERIOD
  148. # 通过
  149. filterDataFrame = df[
  150. (df["ghId"] == gh_id)
  151. & (min_time <= df["publish_timestamp"])
  152. & (df["publish_timestamp"] <= max_time)
  153. & (df['ItemIndex'] == index)
  154. ]
  155. # 用二倍标准差过滤
  156. finalDF = filter_outlier_data(filterDataFrame)
  157. return {
  158. "read_rate_avg": finalDF['readRate'].mean(),
  159. "max_publish_time": finalDF['publish_timestamp'].max(),
  160. "min_publish_time": finalDF['publish_timestamp'].min(),
  161. "records": len(finalDF)
  162. }
  163. def check_each_position(db_client, gh_id, index, dt, avg_rate) -> dict:
  164. """
  165. 检验某个具体账号的具体文章的阅读率均值和前段日子的比较
  166. :param avg_rate: 当天计算出的阅读率均值
  167. :param db_client: 数据库连接
  168. :param gh_id: 账号 id
  169. :param index: 账号 index
  170. :param dt:
  171. :return:
  172. """
  173. dt = int(dt.replace("-", ""))
  174. select_sql = f"""
  175. SELECT account_name, read_rate_avg
  176. FROM {read_rate_table}
  177. WHERE gh_id = '{gh_id}' and position = {index} and dt_version < {dt}
  178. ORDER BY dt_version DESC limit 1;
  179. """
  180. result = db_client.select(select_sql)
  181. if result:
  182. account_name = result[0][0]
  183. previous_read_rate_avg = result[0][1]
  184. relative_value = (avg_rate - previous_read_rate_avg) / previous_read_rate_avg
  185. if -const.RELATIVE_VALUE_THRESHOLD <= relative_value <= const.RELATIVE_VALUE_THRESHOLD:
  186. return {}
  187. else:
  188. response = {
  189. "账号名称": account_name,
  190. "位置": index,
  191. "当天阅读率均值": Functions().float_to_percentage(avg_rate),
  192. "前一天阅读率均值": Functions().float_to_percentage(previous_read_rate_avg),
  193. "相对变化率": Functions().float_to_percentage(relative_value)
  194. }
  195. return response
  196. def update_single_day(dt, account_list, article_df, lam):
  197. """
  198. 更新单天数据
  199. :param article_df:
  200. :param lam:
  201. :param account_list:
  202. :param dt:
  203. :return:
  204. """
  205. error_list = []
  206. insert_error_list = []
  207. update_timestamp = functions.str_to_timestamp(date_string=dt)
  208. # 因为计算均值的时候是第二天,所以需要把时间前移一天
  209. avg_date = functions.timestamp_to_str(
  210. timestamp=update_timestamp - const.ONE_DAY_IN_SECONDS,
  211. string_format='%Y-%m-%d'
  212. )
  213. for account in tqdm(account_list):
  214. for index in const.ARTICLE_INDEX_LIST:
  215. read_rate_detail = cal_avg_account_read_rate(
  216. df=article_df,
  217. gh_id=account['gh_id'],
  218. index=index,
  219. dt=dt
  220. )
  221. read_rate_avg = read_rate_detail['read_rate_avg']
  222. max_publish_time = read_rate_detail['max_publish_time']
  223. min_publish_time = read_rate_detail['min_publish_time']
  224. articles_count = read_rate_detail['records']
  225. if articles_count:
  226. if index in {1, 2}:
  227. error_obj = check_each_position(
  228. db_client=lam,
  229. gh_id=account['gh_id'],
  230. index=index,
  231. dt=dt,
  232. avg_rate=read_rate_avg
  233. )
  234. if error_obj:
  235. error_list.append(error_obj)
  236. # continue
  237. try:
  238. if not read_rate_avg:
  239. continue
  240. insert_sql = f"""
  241. INSERT INTO {read_rate_table}
  242. (account_name, gh_id, position, read_rate_avg, remark, articles_count, earliest_publish_time, latest_publish_time, dt_version, is_delete)
  243. values
  244. (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
  245. """
  246. lam.update(
  247. sql=insert_sql,
  248. params=(
  249. account['account_name'],
  250. account['gh_id'],
  251. index,
  252. read_rate_avg,
  253. "从 {} 开始往前计算 31 天".format(dt),
  254. articles_count,
  255. functions.timestamp_to_str(timestamp=min_publish_time, string_format='%Y-%m-%d'),
  256. functions.timestamp_to_str(timestamp=max_publish_time, string_format='%Y-%m-%d'),
  257. avg_date.replace("-", ""),
  258. 0
  259. )
  260. )
  261. except Exception as e:
  262. insert_error_list.append(e)
  263. if insert_error_list:
  264. bot(
  265. title="更新阅读率均值,存在sql 插入失败",
  266. detail=insert_error_list
  267. )
  268. if error_list:
  269. bot(
  270. title="更新阅读率均值,头次出现异常值通知",
  271. detail={
  272. "时间": dt,
  273. "异常列表": error_list
  274. }
  275. )
  276. if not error_list and not insert_error_list:
  277. bot(
  278. title="阅读率均值表,更新成功",
  279. detail={
  280. "日期": dt
  281. }
  282. )
  283. def main() -> None:
  284. """
  285. main function
  286. :return:
  287. """
  288. parser = ArgumentParser()
  289. parser.add_argument("--run-date",
  290. help="Run only once for date in format of %Y-%m-%d. \
  291. If no specified, run as daily jobs.")
  292. args = parser.parse_args()
  293. if args.run_date:
  294. dt = args.run_date
  295. else:
  296. dt = datetime.today().strftime('%Y-%m-%d')
  297. lam = longArticlesMySQL()
  298. de = DeNetMysql()
  299. account_list = get_publishing_accounts(db_client=de)
  300. df = cal_account_read_rate(tuple([i['gh_id'] for i in account_list]))
  301. update_single_day(dt, account_list, df, lam)
  302. if __name__ == '__main__':
  303. main()