utils.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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 request_get(request_url):
  139. """
  140. get 请求 HTTP接口
  141. :param request_url: 接口URL
  142. :return: res_data json格式
  143. """
  144. try:
  145. response = requests.get(url=request_url)
  146. if response.status_code == 200:
  147. res_data = json.loads(response.text)
  148. return res_data
  149. else:
  150. log_.info(f"response.status_code: {response.status_code}")
  151. return None
  152. except Exception as e:
  153. log_.error('url: {}, exception: {}, traceback: {}'.format(request_url, e, traceback.format_exc()))
  154. send_msg_to_feishu(
  155. webhook=config_.FEISHU_ROBOT['server_robot'].get('webhook'),
  156. key_word=config_.FEISHU_ROBOT['server_robot'].get('key_word'),
  157. msg_text='rov-offline{} - 接口请求失败:{}, exception: {}'.format(config_.ENV_TEXT, request_url, e)
  158. )
  159. return None
  160. def data_normalization(data):
  161. """
  162. 对结果做归一化处理(Min-Max Normalization),将分数控制在[0, 100]
  163. :param data: type-list
  164. :return: normal_data, type-list 归一化后的数据
  165. """
  166. x_max = max(data)
  167. x_min = min(data)
  168. normal_data = [(x-x_min)/(x_max-x_min)*100 for x in data]
  169. return normal_data
  170. def filter_video_status(video_ids):
  171. """
  172. 对视频状态进行过滤
  173. :param video_ids: 视频id列表 type-list
  174. :return: filtered_videos
  175. """
  176. i = 0
  177. while i < 3:
  178. try:
  179. mysql_helper = MysqlHelper(mysql_info=config_.FILTER_MYSQL_INFO)
  180. video_status_sql = "SELECT t1.id AS 'video_id', " \
  181. "t1.transcode_status AS 'transcoding_status', " \
  182. "t2.audit_status AS 'audit_status', " \
  183. "t2.video_status AS 'open_status', " \
  184. "t2.recommend_status AS 'applet_rec_status', " \
  185. "t2.app_recommend_status AS 'app_rec_status', " \
  186. "t3.charge AS 'payment_status', " \
  187. "case when t4.max_validate_count is null then 0 else t4.max_validate_count end AS 'encryption_status' " \
  188. "FROM longvideo.wx_video t1 " \
  189. "LEFT JOIN longvideo.wx_video_status t2 ON t1.id= t2.video_id " \
  190. "LEFT JOIN longvideo.wx_video_detail t3 ON t1.id= t3.video_id " \
  191. "LEFT JOIN longvideo.wx_video_pwd t4 ON t1.id= t4.video_id"
  192. if len(video_ids) == 1:
  193. sql = "SELECT video_id " \
  194. "FROM ({}) " \
  195. "WHERE audit_status = 5 " \
  196. "AND applet_rec_status IN (1, -6) " \
  197. "AND open_status = 1 " \
  198. "AND payment_status = 0 " \
  199. "AND encryption_status != 5 " \
  200. "AND transcoding_status = 3 " \
  201. "AND video_id IN ({});".format(video_status_sql, video_ids[0])
  202. data = mysql_helper.get_data(sql=sql)
  203. else:
  204. data = []
  205. for i in range(len(video_ids) // 200 + 1):
  206. sql = "SELECT video_id " \
  207. "FROM ({}) " \
  208. "WHERE audit_status = 5 " \
  209. "AND applet_rec_status IN (1, -6) " \
  210. "AND open_status = 1 " \
  211. "AND payment_status = 0 " \
  212. "AND encryption_status != 5 " \
  213. "AND transcoding_status = 3 " \
  214. "AND video_id IN {};".format(video_status_sql, tuple(video_ids[i*200:(i+1)*200]))
  215. select_res = mysql_helper.get_data(sql=sql)
  216. if select_res is not None:
  217. data += select_res
  218. filtered_videos = [int(temp[0]) for temp in data]
  219. return filtered_videos
  220. except Exception as e:
  221. log_.error(f"过滤失败, exception: {e}, traceback: {traceback.format_exc()}")
  222. send_msg_to_feishu(
  223. webhook=config_.FEISHU_ROBOT['server_robot'].get('webhook'),
  224. key_word=config_.FEISHU_ROBOT['server_robot'].get('key_word'),
  225. msg_text=f"rov-offline{config_.ENV_TEXT} - 过滤失败\n"
  226. f"retry count: {i}\n"
  227. f"exception: {e}\n"
  228. f"traceback: {traceback.format_exc()}"
  229. )
  230. i += 1
  231. if i == 1:
  232. return video_ids
  233. def filter_video_status_with_applet_rec(video_ids, applet_rec_status):
  234. """
  235. 对视频状态进行过滤
  236. :param video_ids: 视频id列表 type-list
  237. :param applet_rec_status: 小程序推荐状态 -6:待推荐 1:普通推荐
  238. :return: filtered_videos
  239. """
  240. i = 0
  241. while i < 3:
  242. try:
  243. mysql_helper = MysqlHelper(mysql_info=config_.FILTER_MYSQL_INFO)
  244. video_status_sql = "SELECT t1.id AS 'video_id', " \
  245. "t1.transcode_status AS 'transcoding_status', " \
  246. "t2.audit_status AS 'audit_status', " \
  247. "t2.video_status AS 'open_status', " \
  248. "t2.recommend_status AS 'applet_rec_status', " \
  249. "t2.app_recommend_status AS 'app_rec_status', " \
  250. "t3.charge AS 'payment_status', " \
  251. "case when t4.max_validate_count is null then 0 else t4.max_validate_count end AS 'encryption_status' " \
  252. "FROM longvideo.wx_video t1 " \
  253. "LEFT JOIN longvideo.wx_video_status t2 ON t1.id= t2.video_id " \
  254. "LEFT JOIN longvideo.wx_video_detail t3 ON t1.id= t3.video_id " \
  255. "LEFT JOIN longvideo.wx_video_pwd t4 ON t1.id= t4.video_id"
  256. if len(video_ids) == 1:
  257. sql = "SELECT video_id " \
  258. "FROM ({}) " \
  259. "WHERE audit_status = 5 " \
  260. "AND applet_rec_status = {} " \
  261. "AND open_status = 1 " \
  262. "AND payment_status = 0 " \
  263. "AND encryption_status != 5 " \
  264. "AND transcoding_status = 3 " \
  265. "AND video_id IN ({});".format(video_status_sql, applet_rec_status, video_ids[0])
  266. data = mysql_helper.get_data(sql=sql)
  267. else:
  268. data = []
  269. for i in range(len(video_ids) // 200 + 1):
  270. sql = "SELECT video_id " \
  271. "FROM ({}) " \
  272. "WHERE audit_status = 5 " \
  273. "AND applet_rec_status = {} " \
  274. "AND open_status = 1 " \
  275. "AND payment_status = 0 " \
  276. "AND encryption_status != 5 " \
  277. "AND transcoding_status = 3 " \
  278. "AND video_id IN {};".format(video_status_sql, applet_rec_status,
  279. tuple(video_ids[i*200:(i+1)*200]))
  280. select_res = mysql_helper.get_data(sql=sql)
  281. if select_res is not None:
  282. data += select_res
  283. filtered_videos = [int(temp[0]) for temp in data]
  284. return filtered_videos
  285. except Exception as e:
  286. log_.error(f"过滤失败, exception: {e}, traceback: {traceback.format_exc()}")
  287. send_msg_to_feishu(
  288. webhook=config_.FEISHU_ROBOT['server_robot'].get('webhook'),
  289. key_word=config_.FEISHU_ROBOT['server_robot'].get('key_word'),
  290. msg_text=f"rov-offline{config_.ENV_TEXT} - 过滤失败\n"
  291. f"retry count: {i}\n"
  292. f"exception: {e}\n"
  293. f"traceback: {traceback.format_exc()}"
  294. )
  295. i += 1
  296. if i == 1:
  297. return video_ids
  298. def filter_video_status_app(video_ids):
  299. """
  300. 对视频状态进行过滤 - app
  301. :param video_ids: 视频id列表 type-list
  302. :return: filtered_videos
  303. """
  304. i = 0
  305. while i < 3:
  306. try:
  307. mysql_helper = MysqlHelper(mysql_info=config_.FILTER_MYSQL_INFO)
  308. video_status_sql = "SELECT t1.id AS 'video_id', " \
  309. "t1.transcode_status AS 'transcoding_status', " \
  310. "t2.app_audit_status AS 'app_audit_status', " \
  311. "t2.original_status AS 'open_status', " \
  312. "t2.recommend_status AS 'applet_rec_status', " \
  313. "t2.app_recommend_status AS 'app_rec_status', " \
  314. "t3.charge AS 'payment_status', " \
  315. "case when t4.max_validate_count is null then 0 else t4.max_validate_count end AS 'encryption_status' " \
  316. "FROM longvideo.wx_video t1 " \
  317. "LEFT JOIN longvideo.wx_video_status t2 ON t1.id= t2.video_id " \
  318. "LEFT JOIN longvideo.wx_video_detail t3 ON t1.id= t3.video_id " \
  319. "LEFT JOIN longvideo.wx_video_pwd t4 ON t1.id= t4.video_id"
  320. if len(video_ids) == 1:
  321. sql = "SELECT video_id " \
  322. "FROM ({}) " \
  323. "WHERE app_audit_status = 5 " \
  324. "AND app_rec_status IN (1, -6, 10) " \
  325. "AND open_status = 1 " \
  326. "AND payment_status = 0 " \
  327. "AND encryption_status != 5 " \
  328. "AND transcoding_status = 3 " \
  329. "AND video_id IN ({});".format(video_status_sql, video_ids[0])
  330. data = mysql_helper.get_data(sql=sql)
  331. else:
  332. data = []
  333. for i in range(len(video_ids) // 200 + 1):
  334. sql = "SELECT video_id " \
  335. "FROM ({}) " \
  336. "WHERE app_audit_status = 5 " \
  337. "AND app_rec_status IN (1, -6, 10) " \
  338. "AND open_status = 1 " \
  339. "AND payment_status = 0 " \
  340. "AND encryption_status != 5 " \
  341. "AND transcoding_status = 3 " \
  342. "AND video_id IN {};".format(video_status_sql, tuple(video_ids[i*200:(i+1)*200]))
  343. select_res = mysql_helper.get_data(sql=sql)
  344. if select_res is not None:
  345. data += select_res
  346. filtered_videos = [int(temp[0]) for temp in data]
  347. return filtered_videos
  348. except Exception as e:
  349. log_.error(f"过滤失败, exception: {e}, traceback: {traceback.format_exc()}")
  350. send_msg_to_feishu(
  351. webhook=config_.FEISHU_ROBOT['server_robot'].get('webhook'),
  352. key_word=config_.FEISHU_ROBOT['server_robot'].get('key_word'),
  353. msg_text=f"rov-offline{config_.ENV_TEXT} - 过滤失败\n"
  354. f"retry count: {i}\n"
  355. f"exception: {e}\n"
  356. f"traceback: {traceback.format_exc()}"
  357. )
  358. i += 1
  359. if i == 1:
  360. return video_ids
  361. def filter_shield_video(video_ids, shield_key_name_list):
  362. """
  363. 过滤屏蔽视频视频
  364. :param video_ids: 需过滤的视频列表 type-list
  365. :param shield_key_name_list: 过滤视频 redis-key
  366. :return: filtered_videos 过滤后的列表 type-list
  367. """
  368. if len(video_ids) == 0:
  369. return video_ids
  370. # 根据Redis缓存中的数据过滤
  371. redis_helper = RedisHelper()
  372. for shield_key_name in shield_key_name_list:
  373. shield_videos_list = redis_helper.get_data_from_set(key_name=shield_key_name)
  374. if not shield_videos_list:
  375. continue
  376. shield_videos = [int(video) for video in shield_videos_list]
  377. video_ids = [int(video_id) for video_id in video_ids if int(video_id) not in shield_videos]
  378. return video_ids
  379. def filter_political_videos(video_ids):
  380. """
  381. 过滤涉政视频
  382. :param video_ids: 需过滤的视频列表 type-list
  383. :return: filtered_video_ids 过滤后的列表 type-list
  384. """
  385. if len(video_ids) == 0:
  386. return video_ids
  387. # 根据Redis缓存中的数据过滤
  388. redis_helper = RedisHelper()
  389. political_key_name = config_.POLITICAL_VIDEOS_KEY_NAME
  390. political_videos_list = redis_helper.get_data_from_set(key_name=political_key_name)
  391. if not political_videos_list:
  392. return video_ids
  393. political_videos = [int(video) for video in political_videos_list]
  394. filtered_video_ids = [int(video_id) for video_id in video_ids if int(video_id) not in political_videos]
  395. return filtered_video_ids
  396. def update_video_w_h_rate(video_ids, key_name):
  397. """
  398. 获取横屏视频的宽高比,并存入redis中 (width/height>1)
  399. :param video_ids: videoId列表 type-list
  400. :param key_name: redis key
  401. :return: None
  402. """
  403. # 获取数据
  404. if len(video_ids) == 1:
  405. sql = "SELECT id, width, height, rotate FROM longvideo.wx_video WHERE id = {};".format(video_ids[0])
  406. else:
  407. sql = "SELECT id, width, height, rotate FROM longvideo.wx_video WHERE id IN {};".format(tuple(video_ids))
  408. mysql_helper = MysqlHelper(mysql_info=config_.MYSQL_INFO)
  409. data = mysql_helper.get_data(sql=sql)
  410. # 更新到redis
  411. info_data = {}
  412. for video_id, width, height, rotate in data:
  413. if int(width) == 0 or int(height) == 0:
  414. continue
  415. # rotate 字段值为 90或270时,width和height的值相反
  416. if int(rotate) in (90, 270):
  417. w_h_rate = int(height) / int(width)
  418. else:
  419. w_h_rate = int(width) / int(height)
  420. if w_h_rate > 1:
  421. info_data[int(video_id)] = w_h_rate
  422. redis_helper = RedisHelper()
  423. # 删除旧数据
  424. redis_helper.del_keys(key_name=key_name)
  425. # 写入新数据
  426. if len(info_data) > 0:
  427. redis_helper.add_data_with_zset(key_name=key_name, data=info_data)
  428. def data_check(project, table, dt):
  429. """检查数据是否准备好"""
  430. odps = ODPS(
  431. access_id=config_.ODPS_CONFIG['ACCESSID'],
  432. secret_access_key=config_.ODPS_CONFIG['ACCESSKEY'],
  433. project=project,
  434. endpoint=config_.ODPS_CONFIG['ENDPOINT'],
  435. connect_timeout=3000,
  436. read_timeout=500000,
  437. pool_maxsize=1000,
  438. pool_connections=1000
  439. )
  440. try:
  441. check_res = check_table_partition_exits(date=dt, project=project, table=table)
  442. if check_res:
  443. sql = f'select * from {project}.{table} where dt = {dt}'
  444. with odps.execute_sql(sql=sql).open_reader() as reader:
  445. data_count = reader.count
  446. else:
  447. data_count = 0
  448. except Exception as e:
  449. data_count = 0
  450. return data_count
  451. def get_feature_data(project, table, features, dt):
  452. """获取特征数据"""
  453. records = get_data_from_odps(date=dt, project=project, table=table)
  454. feature_data = []
  455. for record in records:
  456. item = {}
  457. for feature_name in features:
  458. item[feature_name] = record[feature_name]
  459. feature_data.append(item)
  460. feature_df = pd.DataFrame(feature_data)
  461. return feature_df
  462. if __name__ == '__main__':
  463. # data_test = [9.20273281e+03, 7.00795065e+03, 5.54813112e+03, 9.97402494e-01, 9.96402495e-01, 9.96402494e-01]
  464. # data_normalization(data_test)
  465. # request_post(request_url=config_.NOTIFY_BACKEND_UPDATE_ROV_SCORE_URL, request_data={'videos': []})
  466. # video_ids = [110, 112, 113, 115, 116, 117, 8289883]
  467. # update_video_w_h_rate(video_ids=video_ids, key_name='')
  468. project = config_.PROJECT_24H_APP_TYPE
  469. table = config_.TABLE_24H_APP_TYPE
  470. dt = '2022080115'
  471. check_res = check_table_partition_exits(date=dt, project=project, table=table)
  472. print(check_res)