video_processing.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. import logging
  2. import time
  3. import requests
  4. import hashlib
  5. import ffmpeg
  6. import os
  7. import oss2
  8. from model.sql_models import DB
  9. from config import using_config as db_config
  10. def change_format(video_url, file_md5=None):
  11. now_time = int(time.time() * 1000)
  12. input_file = '/tmp/{}.mp4'.format(now_time)
  13. output_file = '/tmp/{}.mp4'.format(now_time + 1)
  14. rsp = requests.get(video_url)
  15. with open(input_file, 'wb') as f:
  16. f.write(rsp.content)
  17. # 获取视频---matedata-title
  18. video_info_input = ffmpeg.probe(input_file)['format']
  19. video_title = ''
  20. try:
  21. if 'zx' in video_info_input['tags']['title']:
  22. video_title = video_info_input['tags']['title']
  23. except:
  24. pass
  25. if video_title[:2] == 'zx':
  26. # 如果有这一类数据,数据库比对matedata,获取download_path,等其他信息
  27. db_qc = DB(config=db_config.quchen_text)
  28. sql = '''
  29. select download_path ,video_meta_data ,size,video_length ,byte_rate ,
  30. width ,height ,type
  31. from video_info
  32. where video_meta_data='{}'
  33. '''.format(video_title)
  34. cursor = db_qc.session.execute(sql)
  35. lines = []
  36. for line in cursor.fetchall():
  37. lines.append(line)
  38. if len(lines) > 0:
  39. logging.info(video_url + ' 视频已经存在')
  40. cloud_filepath, metadata_title, video_size, duration, bit_rate, width, height, format = lines[0]
  41. return cloud_filepath, metadata_title, video_size, duration, bit_rate, width, height, format
  42. if not file_md5:
  43. file_md5 = hashlib.md5(rsp.content).hexdigest()
  44. logging.info(file_md5) # ac3ee699961c58ef80a78c2434efe0d0
  45. metadata_title = 'zx_' + file_md5
  46. ffmpeg.input(input_file).output(output_file, preset='slower', vcodec='h264',
  47. metadata='title=' + metadata_title).overwrite_output().run()
  48. video_info = ffmpeg.probe(output_file)['format']
  49. duration = video_info['duration']
  50. video_size = int(video_info['size'])
  51. bit_rate = (video_size / (float(duration) / 8))
  52. probe = ffmpeg.probe(input_file)
  53. format = probe['format']
  54. duration = format['duration']
  55. video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
  56. width = int(video_stream['width'])
  57. height = int(video_stream['height'])
  58. logging.info('视频时长:{} 视频大小:{} 视频比特率:{} 视频宽:{} 视频长:{}'.format(duration, video_size, bit_rate, width, height))
  59. cloud_filepath = 'video/{}.mp4'.format(metadata_title)
  60. video_format = video_url.split('.')[-1]
  61. format = 'mp4' if len(video_format) > 4 else video_format
  62. # 上传视频
  63. update_to_aliyun(local_filepath=output_file, cloud_filepath=cloud_filepath)
  64. # 删除视频,上传视频
  65. os.remove(input_file)
  66. os.remove(output_file)
  67. return cloud_filepath, metadata_title, video_size, duration, bit_rate, width, height, format
  68. def update_to_aliyun(local_filepath, cloud_filepath):
  69. logging.info('准备上传视频')
  70. oss_config = db_config.oss_config
  71. access_key_id = os.getenv('OSS_TEST_ACCESS_KEY_ID', oss_config['OSS_TEST_ACCESS_KEY_ID'])
  72. access_key_secret = os.getenv('OSS_TEST_ACCESS_KEY_SECRET', oss_config['OSS_TEST_ACCESS_KEY_SECRET'])
  73. bucket_name = os.getenv('OSS_TEST_BUCKET', oss_config['OSS_TEST_BUCKET'])
  74. endpoint = os.getenv('OSS_TEST_ENDPOINT', oss_config['OSS_TEST_ENDPOINT'])
  75. # 创建Bucket对象,所有Object相关的接口都可以通过Bucket对象来进行
  76. bucket = oss2.Bucket(oss2.Auth(access_key_id, access_key_secret), endpoint, bucket_name)
  77. # 查询文件是否已经在云上
  78. name_set = set()
  79. for i, object_info in enumerate(oss2.ObjectIterator(bucket)):
  80. name_set.add(object_info.key)
  81. if cloud_filepath not in name_set:
  82. logging.info('上传视频' + cloud_filepath)
  83. # 数据不存在于云上,则进行数据存储
  84. # 进行数据存储
  85. bucket.put_object_from_file(cloud_filepath, local_filepath)
  86. if __name__ == '__main__':
  87. # import threading
  88. #
  89. # for i in range(100):
  90. # x_thread = threading.Thread(target=change_format, args=(
  91. # 'http://wxsnsdy.wxs.qq.com/131/20210/snssvpdownload/SH/reserved/ads_svp_video__0b53qybncaaciaadpfl53jqbrbqe2gdafuka.f110002.mp4?dis_k=2982f4fc3f191cb6199045ca072ed033&dis_t=1618995038&m=beb8a2fd5980bb6fb4f9cef486546338',))
  92. # x_thread.start()
  93. import logging
  94. from logging import handlers
  95. logging.basicConfig(
  96. handlers=[
  97. logging.handlers.RotatingFileHandler('video_process.log',
  98. maxBytes=10 * 1024 * 1024,
  99. backupCount=5,
  100. encoding='utf-8')
  101. , logging.StreamHandler() # 供输出使用
  102. ],
  103. level=logging.INFO,
  104. format="%(asctime)s - %(levelname)s %(filename)s %(funcName)s %(lineno)s - %(message)s"
  105. )
  106. # change_format(
  107. # 'https://zx-media-database.oss-cn-hangzhou.aliyuncs.com/video/zx_beb8a2fd5980bb6fb4f9cef486546338.mp4',
  108. # file_md5='beb8a2fd5980bb6fb4f9cef486546338')
  109. change_format(
  110. 'http://wxsnsdy.wxs.qq.com/131/20210/snssvpdownload/SH/reserved/ads_svp_video__0b53qybncaaciaadpfl53jqbrbqe2gdafuka.f110002.mp4?dis_k=2982f4fc3f191cb6199045ca072ed033&dis_t=1618995038&m=beb8a2fd5980bb6fb4f9cef486546338')