utils.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. # coding:utf-8
  2. import pickle
  3. import os
  4. import requests
  5. import json
  6. import traceback
  7. import pandas as pd
  8. from odps import ODPS
  9. from config import set_config
  10. from db_helper import HologresHelper, MysqlHelper, RedisHelper
  11. from log import Log
  12. config_, env = set_config()
  13. log_ = Log()
  14. def execute_sql_from_odps(project, sql, connect_timeout=3000, read_timeout=500000,
  15. pool_maxsize=1000, pool_connections=1000):
  16. odps = ODPS(
  17. access_id=config_.ODPS_CONFIG['ACCESSID'],
  18. secret_access_key=config_.ODPS_CONFIG['ACCESSKEY'],
  19. project=project,
  20. endpoint=config_.ODPS_CONFIG['ENDPOINT'],
  21. connect_timeout=connect_timeout,
  22. read_timeout=read_timeout,
  23. pool_maxsize=pool_maxsize,
  24. pool_connections=pool_connections
  25. )
  26. records = odps.execute_sql(sql=sql)
  27. return records
  28. def get_data_from_odps(date, project, table, connect_timeout=3000, read_timeout=500000,
  29. pool_maxsize=1000, pool_connections=1000):
  30. """
  31. 从odps获取数据
  32. :param date: 日期 type-string '%Y%m%d'
  33. :param project: type-string
  34. :param table: 表名 type-string
  35. :param connect_timeout: 连接超时设置
  36. :param read_timeout: 读取超时设置
  37. :param pool_maxsize:
  38. :param pool_connections:
  39. :return: records
  40. """
  41. odps = ODPS(
  42. access_id=config_.ODPS_CONFIG['ACCESSID'],
  43. secret_access_key=config_.ODPS_CONFIG['ACCESSKEY'],
  44. project=project,
  45. endpoint=config_.ODPS_CONFIG['ENDPOINT'],
  46. connect_timeout=connect_timeout,
  47. read_timeout=read_timeout,
  48. pool_maxsize=pool_maxsize,
  49. pool_connections=pool_connections
  50. )
  51. records = odps.read_table(name=table, partition='dt=%s' % date)
  52. return records
  53. def check_table_partition_exits(date, project, table, connect_timeout=3000, read_timeout=500000,
  54. pool_maxsize=1000, pool_connections=1000):
  55. """
  56. 判断表中是否存在这个分区
  57. :param date: 日期 type-string '%Y%m%d'
  58. :param project: type-string
  59. :param table: 表名 type-string
  60. :param connect_timeout: 连接超时设置
  61. :param read_timeout: 读取超时设置
  62. :param pool_maxsize:
  63. :param pool_connections:
  64. :return: records
  65. """
  66. odps = ODPS(
  67. access_id=config_.ODPS_CONFIG['ACCESSID'],
  68. secret_access_key=config_.ODPS_CONFIG['ACCESSKEY'],
  69. project=project,
  70. endpoint=config_.ODPS_CONFIG['ENDPOINT'],
  71. connect_timeout=connect_timeout,
  72. read_timeout=read_timeout,
  73. pool_maxsize=pool_maxsize,
  74. pool_connections=pool_connections
  75. )
  76. t = odps.get_table(name=table)
  77. return t.exist_partition(partition_spec=f'dt={date}')
  78. def write_to_pickle(data, filename, filepath=config_.DATA_DIR_PATH):
  79. """
  80. 将数据写入pickle文件中
  81. :param data: 数据
  82. :param filename: 写入的文件名
  83. :param filepath: 文件存放路径,默认为config_.DATA_DIR_PATH
  84. :return: None
  85. """
  86. if not os.path.exists(filepath):
  87. os.makedirs(filepath)
  88. file = os.path.join(filepath, filename)
  89. with open(file, 'wb') as wf:
  90. pickle.dump(data, wf)
  91. def read_from_pickle(filename, filepath=config_.DATA_DIR_PATH):
  92. """
  93. 从pickle文件读取数据
  94. :param filename: 文件名
  95. :param filepath: 文件存放路径,默认为config_.DATA_DIR_PATH
  96. :return: data
  97. """
  98. file = os.path.join(filepath, filename)
  99. if not os.path.exists(file):
  100. return None
  101. with open(file, 'rb') as rf:
  102. data = pickle.load(rf)
  103. return data
  104. def send_msg_to_feishu(webhook, key_word, msg_text):
  105. """发送消息到飞书"""
  106. headers = {'Content-Type': 'application/json'}
  107. payload_message = {
  108. "msg_type": "text",
  109. "content": {
  110. "text": '{}: {}'.format(key_word, msg_text)
  111. }
  112. }
  113. response = requests.request('POST', url=webhook, headers=headers, data=json.dumps(payload_message))
  114. print(response.text)
  115. def request_post(request_url, request_data=None, **kwargs):
  116. """
  117. post 请求 HTTP接口
  118. :param request_url: 接口URL
  119. :param request_data: 请求参数
  120. :return: res_data json格式
  121. """
  122. try:
  123. response = requests.post(url=request_url, json=request_data, **kwargs)
  124. if response.status_code == 200:
  125. res_data = json.loads(response.text)
  126. return res_data
  127. else:
  128. log_.info(f"response.status_code: {response.status_code}")
  129. return None
  130. except Exception as e:
  131. log_.error('url: {}, exception: {}, traceback: {}'.format(request_url, e, traceback.format_exc()))
  132. send_msg_to_feishu(
  133. webhook=config_.FEISHU_ROBOT['server_robot'].get('webhook'),
  134. key_word=config_.FEISHU_ROBOT['server_robot'].get('key_word'),
  135. msg_text='rov-offline{} - 接口请求失败:{}, exception: {}'.format(config_.ENV_TEXT, request_url, e)
  136. )
  137. return None
  138. def data_normalization(data):
  139. """
  140. 对结果做归一化处理(Min-Max Normalization),将分数控制在[0, 100]
  141. :param data: type-list
  142. :return: normal_data, type-list 归一化后的数据
  143. """
  144. x_max = max(data)
  145. x_min = min(data)
  146. normal_data = [(x-x_min)/(x_max-x_min)*100 for x in data]
  147. return normal_data
  148. def filter_video_status(video_ids):
  149. """
  150. 对视频状态进行过滤
  151. :param video_ids: 视频id列表 type-list
  152. :return: filtered_videos
  153. """
  154. i = 0
  155. while i < 3:
  156. try:
  157. mysql_helper = MysqlHelper(mysql_info=config_.FILTER_MYSQL_INFO)
  158. video_status_sql = "SELECT t1.id AS 'video_id', " \
  159. "t1.transcode_status AS 'transcoding_status', " \
  160. "t2.audit_status AS 'audit_status', " \
  161. "t2.video_status AS 'open_status', " \
  162. "t2.recommend_status AS 'applet_rec_status', " \
  163. "t2.app_recommend_status AS 'app_rec_status', " \
  164. "t3.charge AS 'payment_status', " \
  165. "case when t4.max_validate_count is null then 0 else t4.max_validate_count end AS 'encryption_status' " \
  166. "FROM longvideo.wx_video t1 " \
  167. "LEFT JOIN longvideo.wx_video_status t2 ON t1.id= t2.video_id " \
  168. "LEFT JOIN longvideo.wx_video_detail t3 ON t1.id= t3.video_id " \
  169. "LEFT JOIN longvideo.wx_video_pwd t4 ON t1.id= t4.video_id"
  170. if len(video_ids) == 1:
  171. sql = "SELECT video_id " \
  172. "FROM ({}) " \
  173. "WHERE audit_status = 5 " \
  174. "AND applet_rec_status IN (1, -6) " \
  175. "AND open_status = 1 " \
  176. "AND payment_status = 0 " \
  177. "AND encryption_status != 5 " \
  178. "AND transcoding_status = 3 " \
  179. "AND video_id IN ({});".format(video_status_sql, video_ids[0])
  180. data = mysql_helper.get_data(sql=sql)
  181. else:
  182. data = []
  183. for i in range(len(video_ids) // 200 + 1):
  184. sql = "SELECT video_id " \
  185. "FROM ({}) " \
  186. "WHERE audit_status = 5 " \
  187. "AND applet_rec_status IN (1, -6) " \
  188. "AND open_status = 1 " \
  189. "AND payment_status = 0 " \
  190. "AND encryption_status != 5 " \
  191. "AND transcoding_status = 3 " \
  192. "AND video_id IN {};".format(video_status_sql, tuple(video_ids[i*200:(i+1)*200]))
  193. select_res = mysql_helper.get_data(sql=sql)
  194. if select_res is not None:
  195. data += select_res
  196. filtered_videos = [int(temp[0]) for temp in data]
  197. return filtered_videos
  198. except Exception as e:
  199. log_.error(f"过滤失败, exception: {e}, traceback: {traceback.format_exc()}")
  200. send_msg_to_feishu(
  201. webhook=config_.FEISHU_ROBOT['server_robot'].get('webhook'),
  202. key_word=config_.FEISHU_ROBOT['server_robot'].get('key_word'),
  203. msg_text=f"rov-offline{config_.ENV_TEXT} - 过滤失败\n"
  204. f"retry count: {i}\n"
  205. f"exception: {e}\n"
  206. f"traceback: {traceback.format_exc()}"
  207. )
  208. i += 1
  209. if i == 1:
  210. return video_ids
  211. def filter_video_status_with_applet_rec(video_ids, applet_rec_status):
  212. """
  213. 对视频状态进行过滤
  214. :param video_ids: 视频id列表 type-list
  215. :param applet_rec_status: 小程序推荐状态 -6:待推荐 1:普通推荐
  216. :return: filtered_videos
  217. """
  218. i = 0
  219. while i < 3:
  220. try:
  221. mysql_helper = MysqlHelper(mysql_info=config_.FILTER_MYSQL_INFO)
  222. video_status_sql = "SELECT t1.id AS 'video_id', " \
  223. "t1.transcode_status AS 'transcoding_status', " \
  224. "t2.audit_status AS 'audit_status', " \
  225. "t2.video_status AS 'open_status', " \
  226. "t2.recommend_status AS 'applet_rec_status', " \
  227. "t2.app_recommend_status AS 'app_rec_status', " \
  228. "t3.charge AS 'payment_status', " \
  229. "case when t4.max_validate_count is null then 0 else t4.max_validate_count end AS 'encryption_status' " \
  230. "FROM longvideo.wx_video t1 " \
  231. "LEFT JOIN longvideo.wx_video_status t2 ON t1.id= t2.video_id " \
  232. "LEFT JOIN longvideo.wx_video_detail t3 ON t1.id= t3.video_id " \
  233. "LEFT JOIN longvideo.wx_video_pwd t4 ON t1.id= t4.video_id"
  234. if len(video_ids) == 1:
  235. sql = "SELECT video_id " \
  236. "FROM ({}) " \
  237. "WHERE audit_status = 5 " \
  238. "AND applet_rec_status = {} " \
  239. "AND open_status = 1 " \
  240. "AND payment_status = 0 " \
  241. "AND encryption_status != 5 " \
  242. "AND transcoding_status = 3 " \
  243. "AND video_id IN ({});".format(video_status_sql, applet_rec_status, video_ids[0])
  244. data = mysql_helper.get_data(sql=sql)
  245. else:
  246. data = []
  247. for i in range(len(video_ids) // 200 + 1):
  248. sql = "SELECT video_id " \
  249. "FROM ({}) " \
  250. "WHERE audit_status = 5 " \
  251. "AND applet_rec_status = {} " \
  252. "AND open_status = 1 " \
  253. "AND payment_status = 0 " \
  254. "AND encryption_status != 5 " \
  255. "AND transcoding_status = 3 " \
  256. "AND video_id IN {};".format(video_status_sql, applet_rec_status,
  257. tuple(video_ids[i*200:(i+1)*200]))
  258. select_res = mysql_helper.get_data(sql=sql)
  259. if select_res is not None:
  260. data += select_res
  261. filtered_videos = [int(temp[0]) for temp in data]
  262. return filtered_videos
  263. except Exception as e:
  264. log_.error(f"过滤失败, exception: {e}, traceback: {traceback.format_exc()}")
  265. send_msg_to_feishu(
  266. webhook=config_.FEISHU_ROBOT['server_robot'].get('webhook'),
  267. key_word=config_.FEISHU_ROBOT['server_robot'].get('key_word'),
  268. msg_text=f"rov-offline{config_.ENV_TEXT} - 过滤失败\n"
  269. f"retry count: {i}\n"
  270. f"exception: {e}\n"
  271. f"traceback: {traceback.format_exc()}"
  272. )
  273. i += 1
  274. if i == 1:
  275. return video_ids
  276. def filter_video_status_app(video_ids):
  277. """
  278. 对视频状态进行过滤 - app
  279. :param video_ids: 视频id列表 type-list
  280. :return: filtered_videos
  281. """
  282. i = 0
  283. while i < 3:
  284. try:
  285. mysql_helper = MysqlHelper(mysql_info=config_.FILTER_MYSQL_INFO)
  286. video_status_sql = "SELECT t1.id AS 'video_id', " \
  287. "t1.transcode_status AS 'transcoding_status', " \
  288. "t2.app_audit_status AS 'app_audit_status', " \
  289. "t2.original_status AS 'open_status', " \
  290. "t2.recommend_status AS 'applet_rec_status', " \
  291. "t2.app_recommend_status AS 'app_rec_status', " \
  292. "t3.charge AS 'payment_status', " \
  293. "case when t4.max_validate_count is null then 0 else t4.max_validate_count end AS 'encryption_status' " \
  294. "FROM longvideo.wx_video t1 " \
  295. "LEFT JOIN longvideo.wx_video_status t2 ON t1.id= t2.video_id " \
  296. "LEFT JOIN longvideo.wx_video_detail t3 ON t1.id= t3.video_id " \
  297. "LEFT JOIN longvideo.wx_video_pwd t4 ON t1.id= t4.video_id"
  298. if len(video_ids) == 1:
  299. sql = "SELECT video_id " \
  300. "FROM ({}) " \
  301. "WHERE app_audit_status = 5 " \
  302. "AND app_rec_status IN (1, -6, 10) " \
  303. "AND open_status = 1 " \
  304. "AND payment_status = 0 " \
  305. "AND encryption_status != 5 " \
  306. "AND transcoding_status = 3 " \
  307. "AND video_id IN ({});".format(video_status_sql, video_ids[0])
  308. data = mysql_helper.get_data(sql=sql)
  309. else:
  310. data = []
  311. for i in range(len(video_ids) // 200 + 1):
  312. sql = "SELECT video_id " \
  313. "FROM ({}) " \
  314. "WHERE app_audit_status = 5 " \
  315. "AND app_rec_status IN (1, -6, 10) " \
  316. "AND open_status = 1 " \
  317. "AND payment_status = 0 " \
  318. "AND encryption_status != 5 " \
  319. "AND transcoding_status = 3 " \
  320. "AND video_id IN {};".format(video_status_sql, tuple(video_ids[i*200:(i+1)*200]))
  321. select_res = mysql_helper.get_data(sql=sql)
  322. if select_res is not None:
  323. data += select_res
  324. filtered_videos = [int(temp[0]) for temp in data]
  325. return filtered_videos
  326. except Exception as e:
  327. log_.error(f"过滤失败, exception: {e}, traceback: {traceback.format_exc()}")
  328. send_msg_to_feishu(
  329. webhook=config_.FEISHU_ROBOT['server_robot'].get('webhook'),
  330. key_word=config_.FEISHU_ROBOT['server_robot'].get('key_word'),
  331. msg_text=f"rov-offline{config_.ENV_TEXT} - 过滤失败\n"
  332. f"retry count: {i}\n"
  333. f"exception: {e}\n"
  334. f"traceback: {traceback.format_exc()}"
  335. )
  336. i += 1
  337. if i == 1:
  338. return video_ids
  339. def filter_shield_video(video_ids, shield_key_name_list):
  340. """
  341. 过滤屏蔽视频视频
  342. :param video_ids: 需过滤的视频列表 type-list
  343. :param shield_key_name_list: 过滤视频 redis-key
  344. :return: filtered_videos 过滤后的列表 type-list
  345. """
  346. if len(video_ids) == 0:
  347. return video_ids
  348. # 根据Redis缓存中的数据过滤
  349. redis_helper = RedisHelper()
  350. for shield_key_name in shield_key_name_list:
  351. shield_videos_list = redis_helper.get_data_from_set(key_name=shield_key_name)
  352. if not shield_videos_list:
  353. continue
  354. shield_videos = [int(video) for video in shield_videos_list]
  355. video_ids = [int(video_id) for video_id in video_ids if int(video_id) not in shield_videos]
  356. return video_ids
  357. def update_video_w_h_rate(video_ids, key_name):
  358. """
  359. 获取横屏视频的宽高比,并存入redis中 (width/height>1)
  360. :param video_ids: videoId列表 type-list
  361. :param key_name: redis key
  362. :return: None
  363. """
  364. # 获取数据
  365. if len(video_ids) == 1:
  366. sql = "SELECT id, width, height, rotate FROM longvideo.wx_video WHERE id = {};".format(video_ids[0])
  367. else:
  368. sql = "SELECT id, width, height, rotate FROM longvideo.wx_video WHERE id IN {};".format(tuple(video_ids))
  369. mysql_helper = MysqlHelper(mysql_info=config_.MYSQL_INFO)
  370. data = mysql_helper.get_data(sql=sql)
  371. # 更新到redis
  372. info_data = {}
  373. for video_id, width, height, rotate in data:
  374. if int(width) == 0 or int(height) == 0:
  375. continue
  376. # rotate 字段值为 90或270时,width和height的值相反
  377. if int(rotate) in (90, 270):
  378. w_h_rate = int(height) / int(width)
  379. else:
  380. w_h_rate = int(width) / int(height)
  381. if w_h_rate > 1:
  382. info_data[int(video_id)] = w_h_rate
  383. redis_helper = RedisHelper()
  384. # 删除旧数据
  385. redis_helper.del_keys(key_name=key_name)
  386. # 写入新数据
  387. if len(info_data) > 0:
  388. redis_helper.add_data_with_zset(key_name=key_name, data=info_data)
  389. def data_check(project, table, dt):
  390. """检查数据是否准备好"""
  391. odps = ODPS(
  392. access_id=config_.ODPS_CONFIG['ACCESSID'],
  393. secret_access_key=config_.ODPS_CONFIG['ACCESSKEY'],
  394. project=project,
  395. endpoint=config_.ODPS_CONFIG['ENDPOINT'],
  396. connect_timeout=3000,
  397. read_timeout=500000,
  398. pool_maxsize=1000,
  399. pool_connections=1000
  400. )
  401. try:
  402. check_res = check_table_partition_exits(date=dt, project=project, table=table)
  403. if check_res:
  404. sql = f'select * from {project}.{table} where dt = {dt}'
  405. with odps.execute_sql(sql=sql).open_reader() as reader:
  406. data_count = reader.count
  407. else:
  408. data_count = 0
  409. except Exception as e:
  410. data_count = 0
  411. return data_count
  412. def get_feature_data(project, table, features, dt):
  413. """获取特征数据"""
  414. records = get_data_from_odps(date=dt, project=project, table=table)
  415. feature_data = []
  416. for record in records:
  417. item = {}
  418. for feature_name in features:
  419. item[feature_name] = record[feature_name]
  420. feature_data.append(item)
  421. feature_df = pd.DataFrame(feature_data)
  422. return feature_df
  423. if __name__ == '__main__':
  424. # data_test = [9.20273281e+03, 7.00795065e+03, 5.54813112e+03, 9.97402494e-01, 9.96402495e-01, 9.96402494e-01]
  425. # data_normalization(data_test)
  426. # request_post(request_url=config_.NOTIFY_BACKEND_UPDATE_ROV_SCORE_URL, request_data={'videos': []})
  427. # video_ids = [110, 112, 113, 115, 116, 117, 8289883]
  428. # update_video_w_h_rate(video_ids=video_ids, key_name='')
  429. project = config_.PROJECT_24H_APP_TYPE
  430. table = config_.TABLE_24H_APP_TYPE
  431. dt = '2022080115'
  432. check_res = check_table_partition_exits(date=dt, project=project, table=table)
  433. print(check_res)