utils.py 22 KB

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