account_position_info.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. import asyncio
  2. import traceback
  3. import numpy as np
  4. from collections import defaultdict
  5. from typing import Dict, List
  6. from pandas import DataFrame
  7. from scipy import stats
  8. from tqdm.asyncio import tqdm
  9. from datetime import datetime, timedelta
  10. class AccountPositionInfoConst:
  11. # 阅读率统计周期(秒)
  12. STATISTICS_PERIOD = 31 * 24 * 60 * 60
  13. # 一天的秒数
  14. ONE_DAY_IN_SECONDS = 60 * 60 * 24
  15. # 相对变化率阈值
  16. RELATIVE_VALUE_THRESHOLD = 0.1
  17. # 发文类型
  18. UNLIMITED_PUBLISH_TYPE = 10002
  19. BULK_PUBLISH_TYPE = 9
  20. # 文章位置
  21. ARTICLE_INDEX_LIST = [1, 2, 3, 4, 5, 6, 7, 8]
  22. # 默认粉丝
  23. DEFAULT_FANS = 0
  24. # 最低粉丝量
  25. MIN_FANS = 1000
  26. ARTICLES_DAILY = 1
  27. TOULIU = 2
  28. # 默认点赞
  29. DEFAULT_LIKE = 0
  30. # 状态
  31. USING_STATUS = 1
  32. NOT_USING_STATUS = 0
  33. # 服务号
  34. GROUP_ACCOUNT_SET = {
  35. "gh_9cf3b7ff486b",
  36. "gh_ecb21c0453af",
  37. "gh_45beb952dc74",
  38. # "gh_84e744b16b3a",
  39. "gh_b3ffc1ca3a04",
  40. "gh_b8baac4296cb",
  41. "gh_efaf7da157f5",
  42. # "gh_5855bed97938",
  43. "gh_b32125c73861",
  44. "gh_761976bb98a6",
  45. "gh_5e543853d8f0",
  46. # "gh_61a72b720de3",
  47. }
  48. # 违禁账号
  49. FORBIDDEN_GH_IDS = {
  50. "gh_4c058673c07e",
  51. "gh_de9f9ebc976b",
  52. "gh_7b4a5f86d68c",
  53. "gh_f902cea89e48",
  54. "gh_789a40fe7935",
  55. "gh_cd041ed721e6",
  56. "gh_62d7f423f382",
  57. "gh_043223059726",
  58. "gh_6cfd1132df94",
  59. "gh_7f5075624a50",
  60. "gh_d4dffc34ac39",
  61. "gh_c69776baf2cd",
  62. "gh_9877c8541764",
  63. "gh_ac43e43b253b",
  64. "gh_93e00e187787",
  65. "gh_080bb43aa0dc",
  66. "gh_b1c71a0e7a85",
  67. "gh_d5f935d0d1f2",
  68. }
  69. # 投流账号
  70. TOULIU_ACCOUNTS = {
  71. "小阳看天下",
  72. "趣味生活方式",
  73. "趣味生活漫时光",
  74. "史趣探秘",
  75. "暖心一隅",
  76. "趣味生活漫谈",
  77. "历史长河流淌",
  78. "美好意义时光",
  79. "银发生活畅谈",
  80. "美好时光阅读汇",
  81. "时光趣味生活",
  82. }
  83. class AccountPositionReadRateAvg(AccountPositionInfoConst):
  84. """计算账号每个位置评价阅读率"""
  85. def __init__(self, pool, log_client, trace_id):
  86. self.pool = pool
  87. self.log_client = log_client
  88. self.trace_id = trace_id
  89. # 生成统计周期
  90. def generate_stat_duration(self, end_date: str) -> str:
  91. end_date_dt = datetime.strptime(end_date, "%Y-%m-%d")
  92. start_date_dt = end_date_dt - timedelta(seconds=self.STATISTICS_PERIOD)
  93. return start_date_dt.strftime("%Y-%m-%d")
  94. # 获取发文账号
  95. async def get_publishing_accounts(self):
  96. query = """
  97. select distinct
  98. t3.name as account_name,
  99. t3.gh_id as gh_id,
  100. group_concat(distinct t4.remark) as account_remark,
  101. t6.account_source_name as account_source,
  102. t6.mode_type as mode_type,
  103. t6.account_type as account_type,
  104. t6.`status` as status
  105. from
  106. publish_plan t1
  107. join publish_plan_account t2 on t1.id = t2.plan_id
  108. join publish_account t3 on t2.account_id = t3.id
  109. left join publish_account_remark t4 on t3.id = t4.publish_account_id
  110. left join wx_statistics_group_source_account t5 on t3.id = t5.account_id
  111. left join wx_statistics_group_source t6 on t5.group_source_name = t6.account_source_name
  112. where t1.plan_status = 1 and t1.content_modal = 3 and t3.channel = 5
  113. group by t3.id;
  114. """
  115. account_list = await self.pool.async_fetch(query, db_name="aigc")
  116. return [i for i in account_list if "自动回复" not in str(i["account_remark"])]
  117. # 获取统计周期内,每个账号的粉丝量
  118. async def get_fans_for_each_date(self, start_date: str):
  119. # 获取订阅号粉丝量
  120. query = """
  121. SELECT t1.date_str as dt,
  122. CASE
  123. WHEN t1.fans_count IS NULL OR t1.fans_count = 0 THEN t2.follower_count
  124. ELSE t1.fans_count
  125. END AS fans,
  126. t2.gh_id as gh_id
  127. FROM datastat_wx t1 JOIN publish_account t2 ON t1.account_id = t2.id
  128. WHERE t2.channel = 5 AND t2.status = 1 AND t1.date_str >= %s;
  129. """
  130. task1 = self.pool.async_fetch(query=query, db_name="aigc", params=(start_date,))
  131. if self.GROUP_ACCOUNT_SET:
  132. gh_ids = tuple(self.GROUP_ACCOUNT_SET)
  133. placeholders = ",".join(["%s"] * len(gh_ids))
  134. query_group = f"""
  135. SELECT gh_id, publish_date AS dt, CAST(SUM(sent_count) / 8 AS SIGNED) AS fans
  136. FROM long_articles_group_send_result
  137. WHERE publish_date >= %s AND gh_id IN ({placeholders})
  138. GROUP BY publish_date, gh_id;
  139. """
  140. params_group = (start_date, *gh_ids)
  141. task2 = self.pool.async_fetch(query=query_group, params=params_group)
  142. else:
  143. # 没有 group 账号,返回空列表
  144. task2 = asyncio.sleep(0, result=[])
  145. account_with_fans, group_account_with_fans = await asyncio.gather(task1, task2)
  146. # 合并粉丝数据
  147. account_dt_fans_mapper: Dict[str, Dict[str, int]] = defaultdict(dict)
  148. # 订阅号
  149. for item in account_with_fans or []:
  150. gh_id = item["gh_id"]
  151. dt = item["dt"]
  152. fans = int(item.get("fans") or 0)
  153. account_dt_fans_mapper[gh_id][dt] = fans
  154. # 服务号(覆盖相同 gh_id + dt)
  155. for item in group_account_with_fans or []:
  156. gh_id = item["gh_id"]
  157. dt = item["dt"]
  158. fans = int(item.get("fans") or 0)
  159. account_dt_fans_mapper[gh_id][dt] = fans
  160. return account_dt_fans_mapper
  161. # 从数据库获取账号群发文章 && 群发数据
  162. async def get_single_account_published_articles(
  163. self, gh_id: str, start_timestamp: int
  164. ):
  165. query = """
  166. SELECT
  167. ghId as gh_id, accountName as account_name,
  168. ItemIndex as position,
  169. CAST(AVG(show_view_count) AS SIGNED) as read_count,
  170. FROM_UNIXTIME(publish_timestamp, '%%Y-%%m-%%d') AS pub_dt
  171. FROM
  172. official_articles_v2
  173. WHERE
  174. ghId = %s and Type = %s and publish_timestamp >= %s
  175. GROUP BY ghId, accountName, ItemIndex, pub_dt;
  176. """
  177. return await self.pool.async_fetch(
  178. query=query,
  179. db_name="piaoquan_crawler",
  180. params=(gh_id, self.BULK_PUBLISH_TYPE, start_timestamp),
  181. )
  182. # 计算单个账号的每篇文章的阅读率
  183. async def cal_read_rate_for_single_account(
  184. self,
  185. publish_details: List[Dict],
  186. gh_id: str,
  187. fans_mapper: Dict[str, Dict[str, int]],
  188. ) -> DataFrame | None:
  189. if not publish_details:
  190. return None
  191. article_list_with_fans = []
  192. for article in publish_details:
  193. fans = fans_mapper.get(gh_id, {}).get(article["pub_dt"], self.DEFAULT_FANS)
  194. if not fans:
  195. print(
  196. f"账号 {article['account_name']} 在 {article['pub_dt']} 没有粉丝数据"
  197. )
  198. continue
  199. article["fans"] = fans
  200. if fans > self.MIN_FANS:
  201. article["read_rate"] = article["read_count"] / fans if fans else 0
  202. article_list_with_fans.append(article)
  203. # 转化为 DataFrame 方便后续处理
  204. return DataFrame(
  205. article_list_with_fans,
  206. columns=[
  207. "gh_id",
  208. "account_name",
  209. "position",
  210. "read_count",
  211. "pub_dt",
  212. "fans",
  213. "read_rate",
  214. ],
  215. )
  216. # 更新账号阅读率均值并且更新数据库
  217. async def update_read_rate_avg_for_each_account(
  218. self,
  219. account: dict,
  220. start_date: str,
  221. end_dt: str,
  222. df: DataFrame,
  223. fans_dict: Dict[str, int],
  224. ):
  225. avg_date = (datetime.strptime(end_dt, "%Y-%m-%d") - timedelta(days=1)).strftime(
  226. "%Y-%m-%d"
  227. )
  228. insert_error_list = []
  229. for index in self.ARTICLE_INDEX_LIST:
  230. # 过滤
  231. filter_df = df[
  232. (df["position"] == index)
  233. & (df["pub_dt"] < end_dt)
  234. & (df["pub_dt"] >= start_date)
  235. ]
  236. read_average = filter_df["read_count"].mean()
  237. read_std = filter_df["read_count"].std()
  238. output_df = filter_df[
  239. (filter_df["read_count"] > read_average - 2 * read_std)
  240. & (filter_df["read_count"] < read_average + 2 * read_std)
  241. ]
  242. records = len(output_df)
  243. if records:
  244. # todo: 需要检查波动
  245. # if index <= 2:
  246. # print("position need to be checked")
  247. # insert
  248. try:
  249. insert_query = """
  250. INSERT INTO long_articles_read_rate
  251. (account_name, gh_id, position, read_rate_avg, remark, articles_count, earliest_publish_time, latest_publish_time, dt_version, is_delete, fans)
  252. VALUES
  253. (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
  254. """
  255. await self.pool.async_save(
  256. query=insert_query,
  257. params=(
  258. account["account_name"],
  259. account["gh_id"],
  260. index,
  261. output_df["read_rate"].mean(),
  262. "从 {} 开始往前计算 31 天".format(start_date),
  263. records,
  264. output_df["pub_dt"].min(),
  265. output_df["pub_dt"].max(),
  266. avg_date.replace("-", ""),
  267. 0,
  268. fans_dict.get(avg_date, 0),
  269. ),
  270. )
  271. except Exception as e:
  272. insert_error_list.append(str(e))
  273. # 入口函数
  274. async def deal(self, end_date: str | None):
  275. if not end_date:
  276. end_date = datetime.now().strftime("%Y-%m-%d")
  277. start_dt = self.generate_stat_duration(end_date)
  278. fans_mapper = await self.get_fans_for_each_date(start_date=start_dt)
  279. accounts = await self.get_publishing_accounts()
  280. for account in tqdm(accounts, desc="计算单个账号阅读率均值"):
  281. if account["gh_id"] in self.FORBIDDEN_GH_IDS:
  282. continue
  283. published_articles = await self.get_single_account_published_articles(
  284. gh_id=account["gh_id"],
  285. start_timestamp=int(
  286. datetime.strptime(start_dt, "%Y-%m-%d").timestamp()
  287. ),
  288. )
  289. article_dataframe = await self.cal_read_rate_for_single_account(
  290. publish_details=published_articles,
  291. gh_id=account["gh_id"],
  292. fans_mapper=fans_mapper,
  293. )
  294. if article_dataframe is None:
  295. continue
  296. if article_dataframe.empty:
  297. continue
  298. await self.update_read_rate_avg_for_each_account(
  299. account=account,
  300. start_date=start_dt,
  301. end_dt=end_date,
  302. df=article_dataframe,
  303. fans_dict=fans_mapper.get(account["gh_id"], {}),
  304. )
  305. class AccountPositionReadAvg(AccountPositionReadRateAvg):
  306. # 计算阅读均值置信区间上限
  307. async def cal_read_avg_ci_upper(self, gh_id: str, index: int):
  308. fetch_query = f"""
  309. select read_avg, update_time
  310. from account_avg_info_v3
  311. where gh_id = %s and position = %s
  312. order by update_time desc limit 30;
  313. """
  314. fetch_response_list = await self.pool.async_fetch(
  315. query=fetch_query, db_name="piaoquan_crawler", params=(gh_id, index)
  316. )
  317. read_avg_list = [i["read_avg"] for i in fetch_response_list]
  318. n = len(read_avg_list)
  319. mean = np.mean(read_avg_list)
  320. std = np.std(read_avg_list, ddof=1)
  321. se = std / np.sqrt(n)
  322. t = stats.t.ppf(0.975, df=n - 1)
  323. upper_t = mean + t * se
  324. return upper_t
  325. # 获取账号的阅读率均值信息
  326. async def get_accounts_read_avg(self, dt):
  327. query = """
  328. select gh_id, position, fans, read_rate_avg, fans * read_rate_avg as read_avg
  329. from long_articles_read_rate
  330. where dt_version = %s
  331. """
  332. fetch_result = await self.pool.async_fetch(query=query, params=(dt.replace("-", ""),))
  333. response = {}
  334. for item in fetch_result:
  335. key = f"{item['gh_id']}_{item['position']}"
  336. response[key] = {
  337. "read_rate_avg": item["read_rate_avg"],
  338. "read_avg": item["read_avg"],
  339. "fans": item["fans"],
  340. }
  341. return response
  342. # 计算阅读均值置信区间上限
  343. async def cal_read_avg_detail(
  344. self, account: Dict, dt: str, account_with_read_rate_avg: Dict
  345. ):
  346. for index in self.ARTICLE_INDEX_LIST:
  347. key = f"{account['gh_id']}_{index}"
  348. print(key)
  349. if account_with_read_rate_avg.get(key) is None:
  350. continue
  351. read_avg = account_with_read_rate_avg[key]["read_avg"]
  352. # 计算阅读均值置信区间上限
  353. read_avg_ci_upper = await self.cal_read_avg_ci_upper(
  354. gh_id=account["gh_id"], index=index
  355. )
  356. await self.process_each_record(
  357. account=account,
  358. index=index,
  359. fans=account_with_read_rate_avg[key]["fans"],
  360. read_rate_avg=account_with_read_rate_avg[key]["read_rate_avg"],
  361. read_avg=read_avg,
  362. read_avg_ci_upper=read_avg_ci_upper,
  363. dt=dt,
  364. )
  365. async def process_each_record(
  366. self, account, index, fans, read_rate_avg, read_avg, read_avg_ci_upper, dt
  367. ):
  368. gh_id = account["gh_id"]
  369. account_name = account["account_name"]
  370. business_type = (
  371. self.TOULIU if account_name in self.TOULIU_ACCOUNTS else self.ARTICLES_DAILY
  372. )
  373. # insert into database
  374. insert_sql = f"""
  375. insert into account_avg_info_v3
  376. (gh_id, position, update_time, account_name, fans, read_avg, like_avg, status, account_type,
  377. account_mode, account_source, account_status, business_type, read_rate_avg, read_avg_ci_upper)
  378. values
  379. (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
  380. """
  381. try:
  382. await self.pool.async_save(
  383. query=insert_sql,
  384. db_name="piaoquan_crawler",
  385. params=(
  386. gh_id,
  387. index,
  388. dt,
  389. account["account_name"],
  390. fans,
  391. read_avg,
  392. self.DEFAULT_LIKE,
  393. self.USING_STATUS,
  394. account["account_type"],
  395. account["mode_type"],
  396. account["account_source"],
  397. account["status"],
  398. business_type,
  399. read_rate_avg,
  400. read_avg_ci_upper,
  401. ),
  402. )
  403. except Exception as e:
  404. print(e)
  405. update_sql = f"""
  406. update account_avg_info_v3
  407. set fans = %s, read_avg = %s, read_rate_avg = %s, read_avg_ci_upper = %s
  408. where gh_id = %s and position = %s and update_time = %s
  409. """
  410. try:
  411. await self.pool.async_save(
  412. query=update_sql,
  413. db_name="piaoquan_crawler",
  414. params=(
  415. fans,
  416. read_avg,
  417. read_rate_avg,
  418. read_avg_ci_upper,
  419. account["gh_id"],
  420. index,
  421. dt,
  422. ),
  423. )
  424. except Exception as e:
  425. print(e)
  426. # 修改前一天的状态为 0
  427. update_status_sql = f"""
  428. UPDATE account_avg_info_v3
  429. SET status = %s
  430. WHERE update_time != %s AND gh_id = %s AND position = %s;
  431. """
  432. await self.pool.async_save(
  433. query=update_status_sql,
  434. db_name="piaoquan_crawler",
  435. params=(self.NOT_USING_STATUS, dt, gh_id, index),
  436. )
  437. async def deal(self, end_date: str | None):
  438. if not end_date:
  439. end_date = datetime.now().strftime("%Y-%m-%d")
  440. dt = (datetime.strptime(end_date, "%Y-%m-%d") - timedelta(days=1)).strftime(
  441. "%Y-%m-%d"
  442. )
  443. account_with_read_rate_avg = await self.get_accounts_read_avg(dt)
  444. accounts = await self.get_publishing_accounts()
  445. for account in tqdm(accounts, desc="计算单个账号的阅读均值"):
  446. if account["gh_id"] in self.FORBIDDEN_GH_IDS:
  447. continue
  448. try:
  449. await self.cal_read_avg_detail(
  450. account=account,
  451. dt=dt,
  452. account_with_read_rate_avg=account_with_read_rate_avg,
  453. )
  454. except Exception as e:
  455. print(f"计算账号 {account['account_name']} 阅读均值失败 : {e}")
  456. print(traceback.format_exc())
  457. class AccountPositonOpenRateAvg(AccountPositionReadRateAvg):
  458. pass