alg_growth_3rd_gh_reply_video_v1.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. # -*- coding: utf-8 -*-
  2. import pandas as pd
  3. import traceback
  4. import odps
  5. from odps import ODPS
  6. from threading import Timer
  7. from datetime import datetime, timedelta
  8. from db_helper import MysqlHelper
  9. from my_utils import check_table_partition_exits_v2, get_dataframe_from_odps, \
  10. get_odps_df_of_max_partition, get_odps_instance, get_odps_df_of_recent_partitions
  11. from my_utils import request_post, send_msg_to_feishu
  12. from my_config import set_config
  13. import numpy as np
  14. from log import Log
  15. import os
  16. from argparse import ArgumentParser
  17. CONFIG, _ = set_config()
  18. LOGGER = Log()
  19. BASE_GROUP_NAME = '3rd-party-base'
  20. EXPLORE1_GROUP_NAME = '3rd-party-explore1'
  21. EXPLORE2_GROUP_NAME = '3rd-party-explore2'
  22. # TODO: fetch gh_id from external data source
  23. GH_IDS = (
  24. 'gh_2863155cedcb',
  25. 'gh_c1acd6bac0f8',
  26. 'gh_da993c5f7f64',
  27. 'gh_495d71abbda2',
  28. 'gh_e2318164f869',
  29. 'gh_fc4ec610756e',
  30. 'gh_2450ad774945',
  31. 'gh_175925e40318',
  32. 'gh_994adaf7a539',
  33. 'gh_250c51d5ce69',
  34. 'gh_37adcd637351',
  35. 'gh_a36405f4e5d3',
  36. 'gh_ee5b4b07ed8b',
  37. 'gh_11debb2c8392',
  38. 'gh_d645c1ef7fb0',
  39. 'gh_1899b728af86',
  40. 'gh_059a27ea86b2',
  41. 'gh_6454c103be14',
  42. 'gh_63745bad4f21',
  43. 'gh_8a29eebc2012',
  44. 'gh_57bc9846c86a',
  45. 'gh_570967881eae',
  46. 'gh_197a0d8caa31',
  47. 'gh_93af434e3f47',
  48. 'gh_184f2d765f55',
  49. 'gh_8157d8fd284e',
  50. 'gh_8e1d1f19d44f',
  51. 'gh_1da8f62f4a0d',
  52. 'gh_fd4df7c45bb9',
  53. 'gh_dcfcf74b0846',
  54. 'gh_3afc3a8b8a3d',
  55. 'gh_ef699270bf64',
  56. 'gh_ba870f8b178b',
  57. 'gh_58cdb2f1f0d0',
  58. 'gh_3dce33de6994',
  59. 'gh_543e6d7e15f3',
  60. 'gh_0d55fee6b78d',
  61. 'gh_1c11651e0df4',
  62. 'gh_7f4741dd5fea',
  63. 'gh_33e9e4cbed84',
  64. 'gh_23fa67ebb016',
  65. 'gh_33c26df4eab0',
  66. 'gh_01c93b07605f',
  67. 'gh_c655e3c8a121',
  68. 'gh_83adb78f4ede',
  69. 'gh_0cc7c6d712eb',
  70. 'gh_1b8bfb5c4ffd',
  71. 'gh_e4fb77b1023b',
  72. 'gh_f994f5d9a4b6',
  73. 'gh_e0ca8ba4ed91',
  74. 'gh_b2b4d5aa6b49',
  75. 'gh_53759f90b0c5',
  76. 'gh_d219a0cc8a35',
  77. 'gh_930b5ef5a185',
  78. 'gh_22cad14dc4ec',
  79. 'gh_8734c02f2983',
  80. 'gh_8d68e68f2d08',
  81. 'gh_c603033bf881',
  82. 'gh_55ac4e447179',
  83. 'gh_8b5c838ac19a',
  84. 'gh_aed71f26e7e6',
  85. 'gh_330ef0db846d',
  86. 'gh_87eca527c626',
  87. 'gh_7a14b4c15090',
  88. 'gh_b74693fed783',
  89. 'gh_e1594e6db64b',
  90. 'gh_d32daba8ccf8',
  91. 'gh_23e084923def',
  92. 'gh_148aa4a776ce',
  93. 'gh_0df4d6b647ea',
  94. 'gh_041d1c819c30',
  95. 'gh_7e33fbba4398',
  96. 'gh_354ab82cf9b3',
  97. 'gh_b1f1d7a1f351',
  98. 'gh_793647539ef5',
  99. 'gh_1ff0c29f8408',
  100. 'gh_ecef1c08bcf4',
  101. 'gh_22f53f6a2b5d',
  102. 'gh_34820675d0fc',
  103. 'gh_4175a8f745f6',
  104. 'gh_81145598368a',
  105. 'gh_5f0bb5822e10',
  106. 'gh_65d8db4e97ca',
  107. 'gh_a09594d52fda',
  108. 'gh_4411cf1e5f4e',
  109. 'gh_9ee5f5e8425f',
  110. 'gh_df24adad2521',
  111. 'gh_30b472377707',
  112. 'gh_bb6775b47656',
  113. 'gh_69808935bba0',
  114. 'gh_fb77872bf907',
  115. 'gh_830c4aa1b262',
  116. 'gh_b5393e35caa4',
  117. 'gh_fa7dceae7c9d',
  118. 'gh_449fb0c2d817',
  119. 'gh_d6e75ad9094f',
  120. 'gh_1cbb453a800e',
  121. 'gh_1b243f162cbd',
  122. 'gh_50db6881c86e',
  123. 'gh_9d94775e8137',
  124. 'gh_d37101fb9b98',
  125. 'gh_ed86d05703eb',
  126. 'gh_ac4072121e24',
  127. 'gh_620af8e24fb9',
  128. 'gh_ee4783ded544',
  129. 'gh_d2bb5f1b9498',
  130. 'gh_5044de6e1597',
  131. 'gh_d94de77a8d08',
  132. 'gh_98624814f69a',
  133. 'gh_4c38b9d4474a',
  134. 'gh_f2a6c90c56cb',
  135. 'gh_26f1353fda5a',
  136. 'gh_143743361496',
  137. 'gh_126c99b39cea',
  138. 'gh_53e6e0a1b1bd',
  139. 'gh_859aafbcda3d',
  140. 'gh_cfce2617bd82',
  141. 'gh_db8ea2bc6687',
  142. 'gh_c4708b8cfe39',
  143. 'gh_57d2388bd01d',
  144. 'gh_5fffe35cc12a',
  145. 'gh_45980a6448f3',
  146. 'gh_f5120c12ee23',
  147. 'gh_bf79e3645d7a',
  148. 'gh_6c6d81dd642d',
  149. 'gh_57ee6a6ef204',
  150. 'gh_45be25d1c06b',
  151. 'gh_3ee85ba7c3ae',
  152. 'gh_7c89d5a3e745',
  153. 'gh_c46be9ea4eef',
  154. 'gh_cedc3c4eb48b',
  155. 'gh_8a91fa7f32aa',
  156. 'gh_5207b355776f',
  157. 'gh_6c7f73de400b',
  158. 'gh_d2f3805f8fa3',
  159. 'gh_7dd47f8aca4e',
  160. 'gh_967f9abb9ccd',
  161. 'gh_f46c6c9b53fa',
  162. 'gh_086abf2a536b',
  163. 'gh_6e11282216f3',
  164. 'gh_f5332b8dfb63',
  165. 'gh_f78610e292ba',
  166. 'gh_06699758fa4b',
  167. 'gh_92323d0bea11',
  168. 'gh_517aed4e8197',
  169. 'gh_c80462b5a330',
  170. 'gh_1b1c3ced734e',
  171. 'gh_dd54e30b03ad',
  172. 'gh_cadd0ea4fab3',
  173. 'gh_ef07a709127e',
  174. 'gh_ab6ca922e605',
  175. 'gh_8b69b67ea723',
  176. 'gh_363c54315788',
  177. 'gh_a363987c60bf',
  178. 'gh_86ca35774fcf',
  179. 'gh_518694803ae7',
  180. 'gh_f98d5f17e9ea',
  181. 'gh_5e0cd3f7b457',
  182. 'gh_9e0d149e2c0a',
  183. 'gh_7e77b09bb4f5',
  184. 'gh_261bbd99a906',
  185. 'gh_2dc8e3a7b6c9',
  186. 'gh_1ec8dae66c97',
  187. 'gh_7f062810b4e7',
  188. 'gh_3c112c0c9c8b',
  189. 'gh_01cd19465b39',
  190. 'gh_8cc8ae6eb9a5',
  191. 'gh_210f7ce6f418',
  192. 'gh_04804a94e325',
  193. 'gh_4685665647f0',
  194. 'gh_d7fa96aeb839',
  195. 'gh_210cb680d83d',
  196. 'gh_862b00a394e3',
  197. 'gh_3cf7b310906a',
  198. 'gh_669555ebea28',
  199. 'gh_aaac62205137',
  200. 'gh_0a03f8fa63ba',
  201. 'gh_b8b2d4184832',
  202. 'gh_819a632d4bb1',
  203. 'gh_db09b87a0fc9',
  204. 'gh_b673c01e7bd8',
  205. 'gh_6da61a15044a',
  206. 'gh_2f1fab4efaef',
  207. 'gh_da22f64152d5',
  208. 'gh_ff9fe99f2097',
  209. 'gh_33731afddbdb',
  210. 'gh_4d2f75c3c3fe',
  211. 'gh_40ff43c50773',
  212. 'gh_56b65b7d4520',
  213. 'gh_ff16c412ab97',
  214. 'gh_8bf689ae15cc',
  215. 'gh_650b17dbba8f',
  216. 'gh_b63b9dde3f4b',
  217. 'gh_36e74017026e',
  218. 'gh_a8851bfa953b',
  219. 'gh_ec5beb465640',
  220. 'gh_133c36b99b14',
  221. 'gh_b144210318e5',
  222. 'gh_3bffce62dbb4',
  223. 'gh_2fbff340c683',
  224. 'gh_3ceae370dcf5',
  225. 'gh_530b634707b0',
  226. 'gh_b7cdece20099',
  227. 'gh_9e0c7a370aaf',
  228. 'gh_96412c0393e3',
  229. 'gh_c8060587e6d1',
  230. 'gh_0d3c97cc30cc',
  231. 'gh_491189a534f2',
  232. 'gh_fe9620386c2c',
  233. 'gh_9d50b7067f07',
  234. 'gh_e1331141406a',
  235. 'gh_d6db13fcf14d',
  236. 'gh_5522900b6a67',
  237. 'gh_a7c21403c493',
  238. 'gh_eeec7c2e28a5',
  239. 'gh_c783350a9660',
  240. )
  241. TARGET_GH_IDS = (
  242. 'gh_250c51d5ce69',
  243. 'gh_8a29eebc2012',
  244. 'gh_ff16c412ab97',
  245. 'gh_1014734791e0',
  246. 'gh_570967881eae',
  247. 'gh_a7c21403c493',
  248. 'gh_7f062810b4e7',
  249. 'gh_c8060587e6d1',
  250. 'gh_1da8f62f4a0d',
  251. 'gh_56b65b7d4520',
  252. 'gh_eeec7c2e28a5',
  253. 'gh_7c89d5a3e745',
  254. 'gh_ee5b4b07ed8b',
  255. 'gh_0d3c97cc30cc',
  256. 'gh_c783350a9660',
  257. )
  258. CDN_IMG_OPERATOR = "?x-oss-process=image/resize,m_fill,w_600,h_480,limit_0/format,jpg/watermark,image_eXNoL3BpYy93YXRlcm1hcmtlci9pY29uX3BsYXlfd2hpdGUucG5nP3gtb3NzLXByb2Nlc3M9aW1hZ2UvcmVzaXplLHdfMTQ0,g_center"
  259. ODS_PROJECT = "loghubods"
  260. EXPLORE_POOL_TABLE = 'alg_growth_video_return_stats_history'
  261. GH_REPLY_STATS_TABLE = 'alg_growth_3rd_gh_reply_video_stats'
  262. # ODPS_RANK_RESULT_TABLE = 'alg_gh_autoreply_video_rank_data'
  263. ODPS_3RD_RANK_RESULT_TABLE = 'alg_3rd_gh_autoreply_video_rank_data'
  264. RDS_RANK_RESULT_TABLE = 'alg_gh_autoreply_video_rank_data'
  265. STATS_PERIOD_DAYS = 5
  266. SEND_N = 1
  267. def check_data_partition(project, table, data_dt, data_hr=None):
  268. """检查数据是否准备好"""
  269. try:
  270. partition_spec = {'dt': data_dt}
  271. if data_hr:
  272. partition_spec['hour'] = data_hr
  273. part_exist, data_count = check_table_partition_exits_v2(
  274. project, table, partition_spec)
  275. except Exception as e:
  276. data_count = 0
  277. return data_count
  278. def get_last_strategy_result(project, rank_table, dt_version, key):
  279. strategy_df = get_odps_df_of_max_partition(
  280. project, rank_table, {'ctime': dt_version}
  281. ).to_pandas()
  282. sub_df = strategy_df.query(f'strategy_key == "{key}"')
  283. sub_df = sub_df[['gh_id', 'video_id', 'strategy_key', 'sort']].drop_duplicates()
  284. return sub_df
  285. def process_reply_stats(project, table, period, run_dt):
  286. # 获取多天即转统计数据用于聚合
  287. df = get_odps_df_of_recent_partitions(project, table, period, {'dt': run_dt})
  288. df = df.to_pandas()
  289. df['video_id'] = df['video_id'].astype('int64')
  290. df = df[['gh_id', 'video_id', 'send_count', 'first_visit_uv', 'day0_return']]
  291. # 账号内聚合
  292. df = df.groupby(['video_id', 'gh_id']).agg({
  293. 'send_count': 'sum',
  294. 'first_visit_uv': 'sum',
  295. 'day0_return': 'sum'
  296. }).reset_index()
  297. # 聚合所有数据作为default
  298. default_stats_df = df.groupby('video_id').agg({
  299. 'send_count': 'sum',
  300. 'first_visit_uv': 'sum',
  301. 'day0_return': 'sum'
  302. }).reset_index()
  303. default_stats_df['gh_id'] = 'default'
  304. merged_df = pd.concat([df, default_stats_df]).reset_index(drop=True)
  305. merged_df['score'] = merged_df['day0_return'] / (merged_df['send_count'] + 500)
  306. return merged_df
  307. def rank_for_layer1(run_dt, run_hour, project, table):
  308. # TODO: 加审核&退场
  309. df = get_odps_df_of_max_partition(project, table, {'dt': run_dt})
  310. df = df.to_pandas()
  311. # 确保重跑时可获得一致结果
  312. dt_version = f'{run_dt}{run_hour}'
  313. np.random.seed(int(dt_version) + 1)
  314. # TODO: 修改权重计算策略
  315. df['score'] = df['ros']
  316. sampled_df = df.sample(n=SEND_N, weights=df['score'])
  317. sampled_df['sort'] = range(1, len(sampled_df) + 1)
  318. sampled_df['strategy_key'] = EXPLORE1_GROUP_NAME
  319. sampled_df['dt_version'] = dt_version
  320. gh_name_df = pd.DataFrame({'gh_id': GH_IDS + ('default',)})
  321. sampled_df['_tmpkey'] = 1
  322. gh_name_df['_tmpkey'] = 1
  323. extend_df = sampled_df.merge(gh_name_df, on='_tmpkey').drop('_tmpkey', axis=1)
  324. result_df = extend_df[['strategy_key', 'dt_version', 'gh_id', 'sort', 'video_id', 'score']]
  325. return result_df
  326. def rank_for_layer2(run_dt, run_hour, project, stats_table, rank_table):
  327. stats_df = process_reply_stats(project, stats_table, STATS_PERIOD_DAYS, run_dt)
  328. # 确保重跑时可获得一致结果
  329. dt_version = f'{run_dt}{run_hour}'
  330. np.random.seed(int(dt_version) + 1)
  331. # TODO: 计算账号间相关性
  332. ## 账号两两组合,取有RoVn数值视频的交集,单个账号内的RoVn(平滑后)组成向量
  333. ## 求向量相关系数或cosine相似度
  334. ## 单个视频的RoVn加权求和
  335. # 当前实现基础版本:只在账号内求二级探索排序分
  336. sampled_dfs = []
  337. # 处理default逻辑(default-explore2)
  338. default_stats_df = stats_df.query('gh_id == "default"')
  339. sampled_df = default_stats_df.sample(n=SEND_N, weights=default_stats_df['score'])
  340. sampled_df['sort'] = range(1, len(sampled_df) + 1)
  341. sampled_dfs.append(sampled_df)
  342. # 基础过滤for账号
  343. df = stats_df.query('day0_return > 100')
  344. # fallback to base if necessary
  345. base_strategy_df = get_last_strategy_result(
  346. project, rank_table, dt_version, BASE_GROUP_NAME)
  347. for gh_id in GH_IDS:
  348. sub_df = df.query(f'gh_id == "{gh_id}"')
  349. if len(sub_df) < SEND_N:
  350. LOGGER.warning(
  351. "gh_id[{}] rows[{}] not enough for layer2, fallback to base"
  352. .format(gh_id, len(sub_df)))
  353. sub_df = base_strategy_df.query(f'gh_id == "{gh_id}"')
  354. sub_df['score'] = sub_df['sort']
  355. sampled_df = sub_df.sample(n=SEND_N, weights=sub_df['score'])
  356. sampled_df['sort'] = range(1, len(sampled_df) + 1)
  357. sampled_dfs.append(sampled_df)
  358. extend_df = pd.concat(sampled_dfs)
  359. extend_df['strategy_key'] = EXPLORE2_GROUP_NAME
  360. extend_df['dt_version'] = dt_version
  361. result_df = extend_df[['strategy_key', 'dt_version', 'gh_id', 'sort', 'video_id', 'score']]
  362. return result_df
  363. def rank_for_base(run_dt, run_hour, project, stats_table, rank_table, stg_key):
  364. stats_df = process_reply_stats(project, stats_table, STATS_PERIOD_DAYS, run_dt)
  365. # TODO: support to set base manually
  366. dt_version = f'{run_dt}{run_hour}'
  367. # 获取当前base信息, 策略表dt_version(ctime partition)采用当前时间
  368. base_strategy_df = get_last_strategy_result(
  369. project, rank_table, dt_version, stg_key)
  370. default_stats_df = stats_df.query('gh_id == "default"')
  371. # 在账号内排序,决定该账号(包括default)的base利用内容
  372. # 排序过程中,确保当前base策略参与排序,因此先关联再过滤
  373. gh_ids_str = ','.join(f'"{x}"' for x in GH_IDS)
  374. stats_df = stats_df.query(f'gh_id in ({gh_ids_str})')
  375. stats_with_strategy_df = stats_df \
  376. .merge(
  377. base_strategy_df,
  378. on=['gh_id', 'video_id'],
  379. how='left') \
  380. .query('strategy_key.notna() or score > 0.1')
  381. # 合并default和分账号数据
  382. grouped_stats_df = pd.concat([default_stats_df, stats_with_strategy_df]).reset_index()
  383. def set_top_n(group, n=2):
  384. group_sorted = group.sort_values(by='score', ascending=False)
  385. top_n = group_sorted.head(n)
  386. top_n['sort'] = range(1, len(top_n) + 1)
  387. return top_n
  388. ranked_df = grouped_stats_df.groupby('gh_id').apply(set_top_n, SEND_N)
  389. ranked_df = ranked_df.reset_index(drop=True)
  390. # ranked_df['sort'] = grouped_stats_df.groupby('gh_id')['score'].rank(ascending=False)
  391. ranked_df['strategy_key'] = stg_key
  392. ranked_df['dt_version'] = dt_version
  393. ranked_df = ranked_df[['strategy_key', 'dt_version', 'gh_id', 'sort', 'video_id', 'score']]
  394. return ranked_df
  395. def check_result_data(df):
  396. for gh_id in GH_IDS + ('default',):
  397. for key in (EXPLORE1_GROUP_NAME, EXPLORE2_GROUP_NAME, BASE_GROUP_NAME):
  398. sub_df = df.query(f'gh_id == "{gh_id}" and strategy_key == "{key}"')
  399. if len(sub_df) != SEND_N:
  400. raise Exception(f"Result not enough for gh_id[{gh_id}]")
  401. def rank_for_base_designate(run_dt, run_hour, stg_key):
  402. dt_version = f'{run_dt}{run_hour}'
  403. ranked_df = pd.DataFrame() # 初始化一个空的 DataFrame
  404. for gh_id in GH_IDS + ('default',):
  405. if gh_id in TARGET_GH_IDS:
  406. temp_df = pd.DataFrame({
  407. 'strategy_key': [stg_key],
  408. 'dt_version': [dt_version],
  409. 'gh_id': [gh_id],
  410. 'sort': [1],
  411. 'video_id': [13586800],
  412. 'score': [0.5]
  413. })
  414. else:
  415. temp_df = pd.DataFrame({
  416. 'strategy_key': [stg_key],
  417. 'dt_version': [dt_version],
  418. 'gh_id': [gh_id],
  419. 'sort': [1],
  420. 'video_id': [20463342],
  421. 'score': [0.5]
  422. })
  423. ranked_df = pd.concat([ranked_df, temp_df], ignore_index=True)
  424. return ranked_df
  425. def build_and_transfer_data(run_dt, run_hour, project, **kwargs):
  426. dt_version = f'{run_dt}{run_hour}'
  427. dry_run = kwargs.get('dry_run', False)
  428. # layer1_rank = rank_for_layer1(run_dt, run_hour, ODS_PROJECT, EXPLORE_POOL_TABLE)
  429. # layer2_rank = rank_for_layer2(run_dt, run_hour, ODS_PROJECT, GH_REPLY_STATS_TABLE, ODPS_3RD_RANK_RESULT_TABLE)
  430. # base_rank = rank_for_base(run_dt, run_hour, ODS_PROJECT, GH_REPLY_STATS_TABLE, ODPS_3RD_RANK_RESULT_TABLE,BASE_GROUP_NAME)
  431. layer1_rank = rank_for_base_designate(run_dt, run_hour, EXPLORE1_GROUP_NAME)
  432. layer2_rank = rank_for_base_designate(run_dt, run_hour, EXPLORE2_GROUP_NAME)
  433. base_rank = rank_for_base_designate(run_dt, run_hour, BASE_GROUP_NAME)
  434. final_rank_df = pd.concat([layer1_rank, layer2_rank, base_rank]).reset_index(drop=True)
  435. check_result_data(final_rank_df)
  436. odps_instance = get_odps_instance(project)
  437. odps_ranked_df = odps.DataFrame(final_rank_df)
  438. video_df = get_dataframe_from_odps('videoods', 'wx_video')
  439. video_df['cover_url'] = video_df['cover_img_path'] + CDN_IMG_OPERATOR
  440. video_df = video_df['id', 'title', 'cover_url']
  441. final_df = odps_ranked_df.join(video_df, on=('video_id', 'id'))
  442. final_df = final_df.to_pandas()
  443. final_df = final_df[['strategy_key', 'dt_version', 'gh_id', 'sort', 'video_id', 'title', 'cover_url', 'score']]
  444. # reverse sending order
  445. final_df['sort'] = SEND_N + 1 - final_df['sort']
  446. if dry_run:
  447. print(final_df[['strategy_key', 'gh_id', 'sort', 'video_id', 'score', 'title']])
  448. return
  449. # save to ODPS
  450. t = odps_instance.get_table(ODPS_3RD_RANK_RESULT_TABLE)
  451. part_spec_dict = {'dt': run_dt, 'hour': run_hour, 'ctime': dt_version}
  452. part_spec = ','.join(['{}={}'.format(k, part_spec_dict[k]) for k in part_spec_dict.keys()])
  453. with t.open_writer(partition=part_spec, create_partition=True, overwrite=True) as writer:
  454. writer.write(list(final_df.itertuples(index=False)))
  455. # sync to MySQL
  456. data_to_insert = [tuple(row) for row in final_df.itertuples(index=False)]
  457. data_columns = list(final_df.columns)
  458. mysql = MysqlHelper(CONFIG.MYSQL_CRAWLER_INFO)
  459. mysql.batch_insert(RDS_RANK_RESULT_TABLE, data_to_insert, data_columns)
  460. def main_loop():
  461. argparser = ArgumentParser()
  462. argparser.add_argument('-n', '--dry-run', action='store_true')
  463. args = argparser.parse_args()
  464. try:
  465. now_date = datetime.today()
  466. LOGGER.info(f"开始执行: {datetime.strftime(now_date, '%Y-%m-%d %H:%M')}")
  467. now_hour = now_date.strftime("%H")
  468. last_date = now_date - timedelta(1)
  469. last_dt = last_date.strftime("%Y%m%d")
  470. # 查看当前天级更新的数据是否已准备好
  471. # 当前上游统计表为天级更新,但字段设计为兼容小时级
  472. h_data_count = check_data_partition(ODS_PROJECT, GH_REPLY_STATS_TABLE, last_dt, '00')
  473. if h_data_count > 0:
  474. LOGGER.info('上游数据表查询数据条数={},开始计算'.format(h_data_count))
  475. run_dt = now_date.strftime("%Y%m%d")
  476. LOGGER.info(f'run_dt: {run_dt}, run_hour: {now_hour}')
  477. build_and_transfer_data(run_dt, now_hour, ODS_PROJECT,
  478. dry_run=args.dry_run)
  479. LOGGER.info('数据更新完成')
  480. else:
  481. LOGGER.info("上游数据未就绪,等待60s")
  482. Timer(60, main_loop).start()
  483. return
  484. except Exception as e:
  485. LOGGER.error(f"数据更新失败, exception: {e}, traceback: {traceback.format_exc()}")
  486. if CONFIG.ENV_TEXT == '开发环境':
  487. return
  488. send_msg_to_feishu(
  489. webhook=CONFIG.FEISHU_ROBOT['server_robot'].get('webhook'),
  490. key_word=CONFIG.FEISHU_ROBOT['server_robot'].get('key_word'),
  491. msg_text=f"rov-offline{CONFIG.ENV_TEXT} - 数据更新失败\n"
  492. f"exception: {e}\n"
  493. f"traceback: {traceback.format_exc()}"
  494. )
  495. if __name__ == '__main__':
  496. LOGGER.info("%s 开始执行" % os.path.basename(__file__))
  497. LOGGER.info(f"environment: {CONFIG.ENV_TEXT}")
  498. main_loop()