alg_recsys_rank_item_realtime_1h.py 8.0 KB

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