cal_account_read_rate_avg_daily.py 11 KB

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