alg_growth_3rd_gh_reply_video_v1.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. # -*- coding: utf-8 -*-
  2. import pandas as pd
  3. import traceback
  4. import odps
  5. from odps import ODPS
  6. import json
  7. import time
  8. from pymysql.cursors import DictCursor
  9. from datetime import datetime, timedelta
  10. from db_helper import MysqlHelper
  11. from my_utils import check_table_partition_exits_v2, get_dataframe_from_odps, \
  12. get_odps_df_of_max_partition, get_odps_instance, get_odps_df_of_recent_partitions
  13. from my_utils import request_post, send_msg_to_feishu
  14. from my_config import set_config
  15. import numpy as np
  16. from log import Log
  17. import os
  18. from argparse import ArgumentParser
  19. from constants import AutoReplyAccountType
  20. from alg_growth_common import check_unsafe_video, filter_unsafe_video
  21. CONFIG, _ = set_config()
  22. LOGGER = Log()
  23. BASE_GROUP_NAME = '3rd-party-base'
  24. EXPLORE1_GROUP_NAME = '3rd-party-explore1'
  25. EXPLORE2_GROUP_NAME = '3rd-party-explore2'
  26. # GH_IDS will be updated by get_and_update_gh_ids
  27. GH_IDS = ('default',)
  28. pd.set_option('display.max_rows', None)
  29. CDN_IMG_OPERATOR = "?x-oss-process=image/resize,m_fill,w_600,h_480,limit_0/format,jpg/watermark,image_eXNoL3BpYy93YXRlcm1hcmtlci9pY29uX3BsYXlfd2hpdGUucG5nP3gtb3NzLXByb2Nlc3M9aW1hZ2UvcmVzaXplLHdfMTQ0,g_center"
  30. ODS_PROJECT = "loghubods"
  31. EXPLORE_POOL_TABLE = 'alg_growth_video_return_stats_history'
  32. GH_REPLY_STATS_TABLE = 'alg_growth_3rd_gh_reply_video_stats'
  33. ODPS_RANK_RESULT_TABLE = 'alg_3rd_gh_autoreply_video_rank_data'
  34. GH_DETAIL = 'gh_detail'
  35. RDS_RANK_RESULT_TABLE = 'alg_gh_autoreply_video_rank_data'
  36. STATS_PERIOD_DAYS = 5
  37. SEND_N = 1
  38. def get_and_update_gh_ids(run_dt):
  39. db = MysqlHelper(CONFIG.MYSQL_GROWTH_INFO)
  40. gh_type = AutoReplyAccountType.EXTERNAL_GZH.value
  41. sqlstr = f"""
  42. SELECT gh_id, gh_name, category1, category2, channel,
  43. video_ids, strategy_status
  44. FROM {GH_DETAIL}
  45. WHERE is_delete = 0 AND `type` = {gh_type}
  46. """
  47. account_data = db.get_data(sqlstr, DictCursor)
  48. account_df = pd.DataFrame(account_data)
  49. # default单独处理
  50. if 'default' not in account_df['gh_id'].values:
  51. new_row = pd.DataFrame({'gh_id': ['default'], 'gh_name': ['默认'], 'type': [2], 'category1': ['泛生活']},
  52. index=[0])
  53. account_df = pd.concat([account_df, new_row], ignore_index=True)
  54. account_df = account_df.drop_duplicates(subset=['gh_id'])
  55. global GH_IDS
  56. GH_IDS = tuple(account_df['gh_id'])
  57. return account_df
  58. def check_data_partition(project, table, data_dt, data_hr=None):
  59. """检查数据是否准备好"""
  60. try:
  61. partition_spec = {'dt': data_dt}
  62. if data_hr:
  63. partition_spec['hour'] = data_hr
  64. part_exist, data_count = check_table_partition_exits_v2(
  65. project, table, partition_spec)
  66. except Exception as e:
  67. data_count = 0
  68. return data_count
  69. def get_last_strategy_result(project, rank_table, dt_version, key):
  70. strategy_df = get_odps_df_of_max_partition(
  71. project, rank_table, {'ctime': dt_version}
  72. ).to_pandas()
  73. dt_version = strategy_df.iloc[0]['dt_version']
  74. sub_df = strategy_df.query(f'strategy_key == "{key}"')
  75. sub_df = sub_df[['gh_id', 'video_id', 'strategy_key', 'sort']].drop_duplicates()
  76. return sub_df, dt_version
  77. def process_reply_stats(project, table, period, run_dt):
  78. # 获取多天即转统计数据用于聚合
  79. df = get_odps_df_of_recent_partitions(project, table, period, {'dt': run_dt})
  80. df = df.to_pandas()
  81. df['video_id'] = df['video_id'].astype('int64')
  82. df = df[['gh_id', 'video_id', 'send_count', 'first_visit_uv', 'day0_return']]
  83. # 获取统计数据时统一去除不安全视频
  84. df = filter_unsafe_video(df)
  85. # 账号内聚合
  86. df = df.groupby(['video_id', 'gh_id']).agg({
  87. 'send_count': 'sum',
  88. 'first_visit_uv': 'sum',
  89. 'day0_return': 'sum'
  90. }).reset_index()
  91. # 聚合所有数据作为default
  92. default_stats_df = df.groupby('video_id').agg({
  93. 'send_count': 'sum',
  94. 'first_visit_uv': 'sum',
  95. 'day0_return': 'sum'
  96. }).reset_index()
  97. default_stats_df['gh_id'] = 'default'
  98. merged_df = pd.concat([df, default_stats_df]).reset_index(drop=True)
  99. merged_df['score'] = merged_df['day0_return'] / (merged_df['first_visit_uv'] + 100)
  100. return merged_df
  101. def rank_for_layer1(run_dt, run_hour, project, table, gh):
  102. # TODO: 加审核&退场
  103. df = get_odps_df_of_max_partition(project, table, {'dt': run_dt})
  104. df = df.to_pandas()
  105. df = filter_unsafe_video(df)
  106. # 确保重跑时可获得一致结果
  107. dt_version = f'{run_dt}{run_hour}'
  108. np.random.seed(int(dt_version) + 1)
  109. # TODO: 修改权重计算策略
  110. df['score'] = 1.0
  111. # 按照 category1 分类后进行加权随机抽样
  112. sampled_df = df.groupby('category1').apply(
  113. lambda x: x.sample(n=SEND_N, weights=x['score'], replace=False)).reset_index(drop=True)
  114. sampled_df['sort'] = sampled_df.groupby('category1')['score'].rank(method='first', ascending=False).astype(int)
  115. # 按得分排序
  116. sampled_df = sampled_df.sort_values(by=['category1', 'score'], ascending=[True, False]).reset_index(drop=True)
  117. sampled_df['strategy_key'] = EXPLORE1_GROUP_NAME
  118. sampled_df['dt_version'] = dt_version
  119. extend_df = sampled_df.merge(gh, on='category1')
  120. result_df = extend_df[['strategy_key', 'dt_version', 'gh_id', 'sort', 'video_id', 'score']]
  121. return result_df
  122. def rank_for_layer2(run_dt, run_hour, project, stats_table, rank_table):
  123. stats_df = process_reply_stats(project, stats_table, STATS_PERIOD_DAYS, run_dt)
  124. # 确保重跑时可获得一致结果
  125. dt_version = f'{run_dt}{run_hour}'
  126. np.random.seed(int(dt_version) + 1)
  127. # TODO: 计算账号间相关性
  128. ## 账号两两组合,取有RoVn数值视频的交集,单个账号内的RoVn(平滑后)组成向量
  129. ## 求向量相关系数或cosine相似度
  130. ## 单个视频的RoVn加权求和
  131. # 当前实现基础版本:只在账号内求二级探索排序分
  132. sampled_dfs = []
  133. # 处理default逻辑(default-explore2)
  134. default_stats_df = stats_df.query('gh_id == "default"')
  135. sampled_df = default_stats_df.sample(n=SEND_N, weights=default_stats_df['score'])
  136. sampled_df['sort'] = range(1, len(sampled_df) + 1)
  137. sampled_dfs.append(sampled_df)
  138. # 基础过滤for账号
  139. df = stats_df.query('send_count > 200 and score > 0')
  140. # fallback to base if necessary
  141. base_strategy_df, _ = get_last_strategy_result(
  142. project, rank_table, dt_version, BASE_GROUP_NAME)
  143. for gh_id in GH_IDS:
  144. if gh_id == 'default':
  145. continue
  146. sub_df = df.query(f'gh_id == "{gh_id}"')
  147. if len(sub_df) < SEND_N:
  148. LOGGER.warning(
  149. "gh_id[{}] rows[{}] not enough for layer2, fallback to base"
  150. .format(gh_id, len(sub_df)))
  151. sub_df = base_strategy_df.query(f'gh_id == "{gh_id}"').copy()
  152. sub_df['score'] = sub_df['sort']
  153. sampled_df = sub_df.sample(n=SEND_N, weights=sub_df['score'])
  154. sampled_df['sort'] = range(1, len(sampled_df) + 1)
  155. sampled_dfs.append(sampled_df)
  156. extend_df = pd.concat(sampled_dfs)
  157. extend_df['strategy_key'] = EXPLORE2_GROUP_NAME
  158. extend_df['dt_version'] = dt_version
  159. result_df = extend_df[['strategy_key', 'dt_version', 'gh_id', 'sort', 'video_id', 'score']]
  160. return result_df
  161. def rank_for_base(run_dt, run_hour, project, stats_table, rank_table, stg_key):
  162. stats_df = process_reply_stats(project, stats_table, STATS_PERIOD_DAYS, run_dt)
  163. # TODO: support to set base manually
  164. dt_version = f'{run_dt}{run_hour}'
  165. # 获取当前base信息, 策略表dt_version(ctime partition)采用当前时间
  166. base_strategy_df, _ = get_last_strategy_result(
  167. project, rank_table, dt_version, stg_key)
  168. default_stats_df = stats_df.query('gh_id == "default"')
  169. # 在账号内排序,决定该账号(包括default)的base利用内容
  170. # 排序过程中,确保当前base策略参与排序,因此先关联再过滤
  171. non_default_ids = list(filter(lambda x: x != 'default', GH_IDS))
  172. gh_ids_str = ','.join(f'"{x}"' for x in non_default_ids)
  173. stats_df = stats_df.query(f'gh_id in ({gh_ids_str})')
  174. stats_with_strategy_df = stats_df \
  175. .merge(
  176. base_strategy_df,
  177. on=['gh_id', 'video_id'],
  178. how='outer') \
  179. .query('strategy_key.notna() or (send_count > 500 and score > 0.05)') \
  180. .fillna({'score': 0.0})
  181. # 合并default和分账号数据
  182. grouped_stats_df = pd.concat([default_stats_df, stats_with_strategy_df]).reset_index()
  183. def set_top_n(group, n=2):
  184. group_sorted = group.sort_values(by='score', ascending=False)
  185. top_n = group_sorted.head(n)
  186. top_n['sort'] = range(1, len(top_n) + 1)
  187. return top_n
  188. ranked_df = grouped_stats_df.groupby('gh_id').apply(set_top_n, SEND_N)
  189. ranked_df = ranked_df.reset_index(drop=True)
  190. ranked_df['strategy_key'] = stg_key
  191. ranked_df['dt_version'] = dt_version
  192. ranked_df = ranked_df[['strategy_key', 'dt_version', 'gh_id', 'sort', 'video_id', 'score']]
  193. return ranked_df
  194. def check_result_data(df):
  195. check_unsafe_video(df)
  196. for gh_id in GH_IDS:
  197. for key in (EXPLORE1_GROUP_NAME, EXPLORE2_GROUP_NAME, BASE_GROUP_NAME):
  198. sub_df = df.query(f'gh_id == "{gh_id}" and strategy_key == "{key}"')
  199. n_records = len(sub_df)
  200. if n_records != SEND_N:
  201. raise Exception(f"Unexpected record count: {gh_id},{key},{n_records}")
  202. def postprocess_override_by_config(df, gh_df, dt_version):
  203. override_config = gh_df.query('strategy_status == 0').to_dict(orient='records')
  204. override_data = {
  205. 'strategy_key': [],
  206. 'gh_id': [],
  207. 'sort': [],
  208. 'video_id': []
  209. }
  210. for row in override_config:
  211. gh_id = row['gh_id']
  212. try:
  213. video_ids = json.loads(row['video_ids'])
  214. if not isinstance(video_ids, list):
  215. raise Exception("video_ids is not list")
  216. video_ids = video_ids[:SEND_N]
  217. except Exception as e:
  218. LOGGER.error(f"json parse error: {e}. content: {row['video_ids']}")
  219. continue
  220. for idx, video_id in enumerate(video_ids):
  221. for key in (BASE_GROUP_NAME, EXPLORE1_GROUP_NAME, EXPLORE2_GROUP_NAME):
  222. df = df.drop(df.query(
  223. f'gh_id == "{gh_id}" and strategy_key == "{key}" and sort == {idx + 1}'
  224. ).index)
  225. override_data['strategy_key'].append(key)
  226. override_data['gh_id'].append(gh_id)
  227. override_data['sort'].append(idx + 1)
  228. override_data['video_id'].append(video_id)
  229. n_records = len(override_data['strategy_key'])
  230. override_data['dt_version'] = [dt_version] * n_records
  231. override_data['score'] = [0.0] * n_records
  232. df_to_append = pd.DataFrame(override_data)
  233. df = pd.concat([df, df_to_append], ignore_index=True)
  234. # 强制更换不安全视频
  235. idx = df[df['video_id'] == 14403867].index
  236. df.loc[idx, 'video_id'] = 20463342
  237. return df
  238. def build_and_transfer_base_mode(gh_df, run_dt, run_hour, dt_version, dry_run):
  239. layer1_rank = rank_for_layer1(run_dt, run_hour, ODS_PROJECT, EXPLORE_POOL_TABLE, gh_df)
  240. layer2_rank = rank_for_layer2(run_dt, run_hour, ODS_PROJECT, GH_REPLY_STATS_TABLE, ODPS_RANK_RESULT_TABLE)
  241. base_rank = rank_for_base(run_dt, run_hour, ODS_PROJECT, GH_REPLY_STATS_TABLE, ODPS_RANK_RESULT_TABLE,BASE_GROUP_NAME)
  242. final_rank_df = pd.concat([layer1_rank, layer2_rank, base_rank]).reset_index(drop=True)
  243. final_rank_df = postprocess_override_by_config(final_rank_df, gh_df, dt_version)
  244. check_result_data(final_rank_df)
  245. final_df = join_video_info(final_rank_df)
  246. # reverse sending order
  247. final_df['sort'] = SEND_N + 1 - final_df['sort']
  248. if dry_run:
  249. print("==== ALL DATA ====")
  250. print(final_df[['strategy_key', 'gh_id', 'sort', 'video_id', 'score', 'title']]
  251. .sort_values(by=['strategy_key', 'gh_id', 'sort']))
  252. last_odps_df = get_odps_df_of_max_partition(
  253. ODS_PROJECT, ODPS_RANK_RESULT_TABLE, {'ctime': dt_version}
  254. ).to_pandas()
  255. merged_df = last_odps_df.merge(
  256. final_df, on=['strategy_key', 'gh_id', 'sort'], how='outer')
  257. delta_df = merged_df.query('title_x != title_y')
  258. delta_df = delta_df[['strategy_key', 'gh_id', 'sort',
  259. 'title_x', 'score_x', 'title_y', 'score_y']]
  260. delta_df.to_csv('tmp_delta_data.csv')
  261. return
  262. # save to ODPS
  263. odps_instance = get_odps_instance(ODS_PROJECT)
  264. t = odps_instance.get_table(ODPS_RANK_RESULT_TABLE)
  265. part_spec_dict = {'dt': run_dt, 'hour': run_hour, 'ctime': dt_version}
  266. part_spec = ','.join(['{}={}'.format(k, part_spec_dict[k]) for k in part_spec_dict.keys()])
  267. with t.open_writer(partition=part_spec, create_partition=True, overwrite=True) as writer:
  268. writer.write(list(final_df.itertuples(index=False)))
  269. # sync to MySQL
  270. data_to_insert = [tuple(row) for row in final_df.itertuples(index=False)]
  271. data_columns = list(final_df.columns)
  272. max_time_to_delete = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  273. mysql = MysqlHelper(CONFIG.MYSQL_GROWTH_INFO)
  274. mysql.batch_insert(RDS_RANK_RESULT_TABLE, data_to_insert, data_columns)
  275. # remove old data of same version
  276. for key in final_df['strategy_key'].unique():
  277. sql = f"""
  278. update {RDS_RANK_RESULT_TABLE}
  279. set is_delete = 1
  280. where
  281. dt_version = '{dt_version}'
  282. and strategy_key = '{key}'
  283. and create_time < '{max_time_to_delete}'
  284. and is_delete = 0
  285. """
  286. rows = mysql.execute(sql)
  287. def build_and_transfer_delta_mode(account_df, dt_version, dry_run):
  288. # 获取最新策略信息, 策略表dt_version(ctime partition)采用当前时间
  289. last_strategy, last_dt_version = get_last_strategy_result(
  290. ODS_PROJECT, ODPS_RANK_RESULT_TABLE, dt_version, BASE_GROUP_NAME)
  291. account_map = { x['gh_id']: x for x in account_df.to_dict(orient='records') }
  292. all_accounts = account_df['gh_id'].unique()
  293. accounts_in_strategy = last_strategy['gh_id'].unique()
  294. delta_accounts = [x for x in set(all_accounts) - set(accounts_in_strategy)]
  295. if len(delta_accounts) > 0:
  296. LOGGER.info('Found {} new accounts: {}'.format(
  297. len(delta_accounts), ','.join(delta_accounts)))
  298. else:
  299. LOGGER.info('Found 0 new account, do nothing.')
  300. return
  301. default_video = {
  302. '泛生活': [20463342],
  303. '泛历史': [13586800],
  304. }
  305. # 新增账号,不存在历史,可直接忽略strategy_status字段
  306. # TODO: set default by history stats
  307. groups = (BASE_GROUP_NAME, EXPLORE1_GROUP_NAME, EXPLORE2_GROUP_NAME)
  308. rows = []
  309. for gh_id in delta_accounts:
  310. account_info = account_map[gh_id]
  311. configured_videos = account_info['video_ids']
  312. if configured_videos:
  313. LOGGER.info(f'{gh_id} has configured video IDs: {configured_videos}')
  314. video_ids = [int(x) for x in configured_videos.split(',')]
  315. else:
  316. video_ids = default_video[account_info['category1']]
  317. for group_key in groups:
  318. for idx in range(SEND_N):
  319. row = {
  320. 'strategy_key': group_key,
  321. 'gh_id': gh_id,
  322. 'sort': idx + 1,
  323. 'video_id': video_ids[idx],
  324. 'dt_version': last_dt_version,
  325. 'score': 0.0
  326. }
  327. rows.append(row)
  328. df = pd.DataFrame(rows)
  329. final_df = join_video_info(df)
  330. if dry_run:
  331. print(final_df)
  332. return
  333. # 增量记录更新至MySQL
  334. data_to_insert = [tuple(row) for row in final_df.itertuples(index=False)]
  335. data_columns = list(final_df.columns)
  336. mysql = MysqlHelper(CONFIG.MYSQL_GROWTH_INFO)
  337. mysql.batch_insert(RDS_RANK_RESULT_TABLE, data_to_insert, data_columns)
  338. # 全量记录写回ODPS
  339. last_odps_df = get_odps_df_of_max_partition(
  340. ODS_PROJECT, ODPS_RANK_RESULT_TABLE, {'ctime': dt_version}
  341. ).to_pandas()
  342. updated_odps_df = pd.concat([final_df, last_odps_df], ignore_index=True)
  343. odps_instance = get_odps_instance(ODS_PROJECT)
  344. t = odps_instance.get_table(ODPS_RANK_RESULT_TABLE)
  345. target_dt = last_dt_version[0:8]
  346. target_hour = last_dt_version[8:10]
  347. part_spec_dict = {'dt': target_dt, 'hour': target_hour, 'ctime': last_dt_version}
  348. part_spec = ','.join(['{}={}'.format(k, part_spec_dict[k]) for k in part_spec_dict.keys()])
  349. with t.open_writer(partition=part_spec, create_partition=True, overwrite=True) as writer:
  350. writer.write(list(updated_odps_df.itertuples(index=False)))
  351. def join_video_info(df):
  352. db = MysqlHelper(CONFIG.MYSQL_INFO)
  353. video_ids = df['video_id'].unique().tolist()
  354. video_ids_str = ','.join([str(x) for x in video_ids])
  355. sql = f"""
  356. SELECT id as video_id, title, cover_img_path FROM wx_video
  357. WHERE id in ({video_ids_str})
  358. """
  359. rows = db.get_data(sql, DictCursor)
  360. video_df = pd.DataFrame(rows)
  361. video_df['cover_url'] = video_df['cover_img_path'] + CDN_IMG_OPERATOR
  362. final_df = df.merge(video_df, on='video_id')
  363. # odps_instance = get_odps_instance(ODS_PROJECT)
  364. # odps_df = odps.DataFrame(df)
  365. # video_df = get_dataframe_from_odps('videoods', 'wx_video')
  366. # video_df['cover_url'] = video_df['cover_img_path'] + CDN_IMG_OPERATOR
  367. # video_df = video_df['id', 'title', 'cover_url']
  368. # final_df = odps_df.join(video_df, on=('video_id', 'id'))
  369. # final_df = final_df.to_pandas()
  370. final_df = final_df[['strategy_key', 'dt_version', 'gh_id', 'sort', 'video_id', 'title', 'cover_url', 'score']]
  371. return final_df
  372. def build_and_transfer_data(run_dt, run_hour, **kwargs):
  373. dt_version = f'{run_dt}{run_hour}'
  374. dry_run = kwargs.get('dry_run', False)
  375. mode = kwargs.get('mode')
  376. gh_df = get_and_update_gh_ids(run_dt)
  377. if mode == 'delta':
  378. return build_and_transfer_delta_mode(gh_df, dt_version, dry_run)
  379. else:
  380. return build_and_transfer_base_mode(gh_df, run_dt, run_hour, dt_version, dry_run)
  381. def main():
  382. LOGGER.info("%s 开始执行" % os.path.basename(__file__))
  383. LOGGER.info(f"environment: {CONFIG.ENV_TEXT}")
  384. argparser = ArgumentParser()
  385. argparser.add_argument('-n', '--dry-run', action='store_true')
  386. argparser.add_argument('--run-at',help='assume to run at date and hour, yyyyMMddHH')
  387. argparser.add_argument('--mode', default='base', choices=['base', 'delta'], help='run mode')
  388. args = argparser.parse_args()
  389. run_date = datetime.today()
  390. if args.run_at:
  391. run_date = datetime.strptime(args.run_at, "%Y%m%d%H")
  392. LOGGER.info(f"Assume to run at {run_date.strftime('%Y-%m-%d %H:00')}")
  393. try:
  394. now_date = datetime.today()
  395. LOGGER.info(f"开始执行: {datetime.strftime(now_date, '%Y-%m-%d %H:%M')}")
  396. last_date = run_date - timedelta(1)
  397. last_dt = last_date.strftime("%Y%m%d")
  398. # 查看当前天级更新的数据是否已准备好
  399. # 当前上游统计表为天级更新,但字段设计为兼容小时级
  400. while True:
  401. h_data_count = check_data_partition(ODS_PROJECT, GH_REPLY_STATS_TABLE, last_dt, '00')
  402. if h_data_count > 0:
  403. LOGGER.info('上游数据表查询数据条数={},开始计算'.format(h_data_count))
  404. run_dt = run_date.strftime("%Y%m%d")
  405. run_hour = run_date.strftime("%H")
  406. LOGGER.info(f'run_dt: {run_dt}, run_hour: {run_hour}')
  407. build_and_transfer_data(run_dt, run_hour, dry_run=args.dry_run, mode=args.mode)
  408. LOGGER.info('数据更新完成')
  409. return
  410. else:
  411. LOGGER.info("上游数据未就绪,等待60s")
  412. time.sleep(60)
  413. except Exception as e:
  414. LOGGER.error(f"数据更新失败, exception: {e}, traceback: {traceback.format_exc()}")
  415. if CONFIG.ENV_TEXT == '开发环境' or args.dry_run:
  416. return
  417. send_msg_to_feishu(
  418. webhook=CONFIG.FEISHU_ROBOT['growth_task_robot'].get('webhook'),
  419. key_word=CONFIG.FEISHU_ROBOT['growth_task_robot'].get('key_word'),
  420. msg_text=f"rov-offline{CONFIG.ENV_TEXT} - 数据更新失败\n"
  421. f"exception: {e}\n"
  422. f"traceback: {traceback.format_exc()}"
  423. )
  424. if __name__ == '__main__':
  425. main()