alg_recsys_rank_item_realtime_1h.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import sys
  4. root_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
  5. if root_dir not in sys.path:
  6. sys.path.append(root_dir)
  7. print("******** sys.path ********")
  8. print(sys.path)
  9. from multiprocessing import Process
  10. from odps import ODPS
  11. import threading
  12. from my_utils import RedisHelper, execute_sql_from_odps
  13. from my_config import set_config
  14. from log import Log
  15. import json
  16. from datetime import datetime, timedelta
  17. from queue import Queue
  18. from tqdm import tqdm
  19. import time
  20. config_, _ = set_config()
  21. log_ = Log()
  22. redis_helper = RedisHelper()
  23. REDIS_PREFIX = "item_rt_fea_1h_"
  24. EXPIRE_TIME = 24 * 3600
  25. TIME_LIMIT_TABLE = 40
  26. TIME_LIMIT_TASK = 60
  27. def worker(queue, executor):
  28. while True:
  29. row = queue.get()
  30. if row is None: # 结束信号
  31. queue.task_done()
  32. break
  33. executor(row)
  34. queue.task_done()
  35. def records_process_for_list(records, executor, max_size=50, num_workers=10):
  36. # 创建一个线程安全的队列
  37. queue = Queue(maxsize=max_size) # 可以调整 maxsize 以控制内存使用
  38. # 设置线程池大小
  39. num_workers = num_workers
  40. # 启动工作线程
  41. threads = []
  42. for _ in range(num_workers):
  43. t = threading.Thread(target=worker, args=(queue, executor))
  44. t.start()
  45. threads.append(t)
  46. # 读取数据并放入队列
  47. for row in tqdm(records):
  48. queue.put(row)
  49. # 发送结束信号
  50. for _ in range(num_workers):
  51. queue.put(None)
  52. # 等待所有任务完成
  53. queue.join()
  54. # 等待所有工作线程结束
  55. for t in threads:
  56. t.join()
  57. def process_and_store(row):
  58. table_key, json_str = row
  59. key = REDIS_PREFIX + str(table_key)
  60. expire_time = EXPIRE_TIME
  61. redis_helper.set_data_to_redis(key, json_str, expire_time)
  62. def check_data(project, table, partition) -> int:
  63. """检查数据是否准备好,输出数据条数"""
  64. odps = ODPS(
  65. access_id=config_.ODPS_CONFIG['ACCESSID'],
  66. secret_access_key=config_.ODPS_CONFIG['ACCESSKEY'],
  67. project=project,
  68. endpoint=config_.ODPS_CONFIG['ENDPOINT'],
  69. connect_timeout=3000,
  70. read_timeout=500000,
  71. pool_maxsize=1000,
  72. pool_connections=1000
  73. )
  74. try:
  75. t = odps.get_table(name=table)
  76. log_.info(f"检查分区是否存在-【 dt={partition} 】")
  77. check_res = t.exist_partition(partition_spec=f'dt={partition}')
  78. if check_res:
  79. sql = f'select * from {project}.{table} where dt = {partition}'
  80. log_.info(sql)
  81. with odps.execute_sql(sql=sql).open_reader() as reader:
  82. data_count = reader.count
  83. else:
  84. log_.info("表{}分区{}不存在".format(table, partition))
  85. data_count = 0
  86. except Exception as e:
  87. log_.error("table:{},partition:{} no data. return data_count=0,报错原因是:{}".format(table, partition, e))
  88. data_count = 0
  89. return data_count
  90. def get_sql(date, previous_date_str, project):
  91. sql = '''
  92. SELECT videoid
  93. ,CONCAT_WS(',',COLLECT_LIST(CONCAT(dt,":",view_uv))) AS view_uv_list_1h
  94. ,CONCAT_WS(',',COLLECT_LIST(CONCAT(dt,":",view_pv))) AS view_pv_list_1h
  95. ,CONCAT_WS(',',COLLECT_LIST(CONCAT(dt,":",play_uv))) AS play_uv_list_1h
  96. ,CONCAT_WS(',',COLLECT_LIST(CONCAT(dt,":",play_pv))) AS play_pv_list_1h
  97. ,CONCAT_WS(',',COLLECT_LIST(CONCAT(dt,":",share_uv))) AS share_uv_list_1h
  98. ,CONCAT_WS(',',COLLECT_LIST(CONCAT(dt,":",share_pv))) AS share_pv_list_1h
  99. ,CONCAT_WS(',',COLLECT_LIST(CONCAT(dt,":",return_uv))) AS return_uv_list_1h
  100. ,CONCAT_WS(',',COLLECT_LIST(CONCAT(dt,":",p_return_uv))) AS p_return_uv_list_1h
  101. FROM (
  102. SELECT videoid
  103. ,dt
  104. ,SUM(lastonehour_view) AS view_uv
  105. ,SUM(lastonehour_view_total) AS view_pv
  106. ,SUM(lastonehour_play) AS play_uv
  107. ,SUM(lastonehour_play_total) AS play_pv
  108. ,SUM(lastonehour_share) AS share_uv
  109. ,SUM(lastonehour_share_total) AS share_pv
  110. ,SUM(lastonehour_return) AS return_uv
  111. ,SUM(platform_return) AS p_return_uv
  112. FROM loghubods.video_each_hour_update_no_province_apptype
  113. WHERE dt <= '{}23'
  114. AND dt >= '{}00'
  115. GROUP BY videoid
  116. ,dt
  117. )
  118. GROUP BY videoid
  119. '''.format(date, previous_date_str)
  120. print("sql:" + sql)
  121. records = execute_sql_from_odps(project=project, sql=sql)
  122. video_list = []
  123. with records.open_reader() as reader:
  124. for record in reader:
  125. video_id = record['videoid']
  126. m = dict()
  127. try:
  128. m["view_uv_list_1h"] = record['view_uv_list_1h']
  129. except Exception as e:
  130. log_.error(e)
  131. try:
  132. m["view_pv_list_1h"] = record['view_pv_list_1h']
  133. except Exception as e:
  134. log_.error(e)
  135. try:
  136. m["play_uv_list_1h"] = record['play_uv_list_1h']
  137. except Exception as e:
  138. log_.error(e)
  139. try:
  140. m["play_pv_list_1h"] = record['play_pv_list_1h']
  141. except Exception as e:
  142. log_.error(e)
  143. try:
  144. m["share_uv_list_1h"] = record['share_uv_list_1h']
  145. except Exception as e:
  146. log_.error(e)
  147. try:
  148. m["share_pv_list_1h"] = record['share_pv_list_1h']
  149. except Exception as e:
  150. log_.error(e)
  151. try:
  152. m["return_uv_list_1h"] = record['return_uv_list_1h']
  153. except Exception as e:
  154. log_.error(e)
  155. try:
  156. m["p_return_uv_list_1h"] = record['p_return_uv_list_1h']
  157. except Exception as e:
  158. log_.error(e)
  159. json_str = json.dumps(m)
  160. video_list.append([video_id, json_str])
  161. return video_list
  162. def main():
  163. try:
  164. date = sys.argv[1]
  165. hour = sys.argv[2]
  166. except Exception as e:
  167. date = datetime.now().strftime('%Y%m%d')
  168. hour = datetime.now().hour
  169. log_.info("没有读取到参数,采用系统时间: {}".format(e))
  170. log_.info("使用时间参数-日期:{},小时:{}".format(date, str(hour)))
  171. if hour in []:
  172. log_.info(f"hour={hour}不执行,直接返回。")
  173. return
  174. # 1 判断上游数据表是否生产完成
  175. project = "loghubods"
  176. table = "video_each_hour_update_no_province_apptype"
  177. partition = str(date) + str(hour)
  178. run_flag = True
  179. begin_ts = int(time.time())
  180. table_data_cnt = 0
  181. while run_flag:
  182. if int(time.time()) - begin_ts >= 60 * TIME_LIMIT_TABLE:
  183. log_.info("等待上游数据超过40分钟了,认为失败退出:过了{}秒。".format(int(time.time()) - begin_ts))
  184. sys.exit(1)
  185. table_data_cnt = check_data(project, table, partition)
  186. if table_data_cnt == 0:
  187. log_.info("上游数据{}未就绪{}/{},等待...".format(table, date, hour))
  188. log_.info("等待2分钟")
  189. time.sleep(60 * 2)
  190. else:
  191. run_flag = False
  192. log_.info("上游数据就绪,count={},开始读取数据表".format(table_data_cnt))
  193. # 2 读取数据表 处理特征
  194. previous_date_str = (datetime.strptime(date, "%Y%m%d") - timedelta(days=1)).strftime("%Y%m%d")
  195. video_list = get_sql(date, previous_date_str, project)
  196. # 3 写入redis
  197. records_process_for_list(video_list, process_and_store, max_size=50, num_workers=8)
  198. redis_helper.set_data_to_redis(REDIS_PREFIX + "partition", partition, 24 * 3600)
  199. if __name__ == '__main__':
  200. log_.info("开始执行:" + datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  201. process = Process(target=main)
  202. process.start()
  203. # 等待子进程完成或超时
  204. timeout = 60 * TIME_LIMIT_TASK
  205. process.join(timeout=timeout) # 设置超时为3600秒(1小时)
  206. if process.is_alive():
  207. print("脚本执行时间超过1小时,执行失败,经过了{}秒。".format(timeout))
  208. process.terminate() # 终止子进程
  209. sys.exit(1) # 直接退出主进程并返回状态码999
  210. log_.info("完成执行:" + datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  211. # cd /root/zhangbo/rov-offline
  212. # python alg_recsys_rank_item_realtime_1h.py 20240702 14