You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

131 lines
5.3KB

  1. # -*- coding: utf-8 -*-
  2. import datetime
  3. import time
  4. import json
  5. from aliyunsdkcore.client import AcsClient
  6. from aliyunsdkvod.request.v20170321 import GetPlayInfoRequest
  7. from loguru import logger
  8. from vodsdk.AliyunVodUploader import AliyunVodUploader
  9. from vodsdk.UploadVideoRequest import UploadVideoRequest
  10. '''
  11. 视频上传使用vod
  12. 1. 阿里云VOD文档地址:https://help.aliyun.com/product/29932.html?spm=5176.8413026.J_3895079540.5.1b4a1029mXvncc
  13. 2. 阿里云对象存储OSS SDK示例地址:https://help.aliyun.com/document_detail/64148.html?spm=a2c4g.64148.0.0.5ae54150jUecEU
  14. 4. 安装SDK:
  15. python -m pip install aliyun-python-sdk-core -i https://pypi.tuna.tsinghua.edu.cn/simple
  16. python -m pip install aliyun-python-sdk-live -i https://pypi.tuna.tsinghua.edu.cn/simple
  17. python -m pip install aliyun-python-sdk-core-v3 -i https://pypi.tuna.tsinghua.edu.cn/simple
  18. python -m pip install aliyun-python-sdk-vod -i https://pypi.tuna.tsinghua.edu.cn/simple
  19. python -m pip install alibabacloud_vod20170321 -i https://pypi.tuna.tsinghua.edu.cn/simple
  20. python -m pip install oss2 -i https://pypi.tuna.tsinghua.edu.cn/simple
  21. 5. 视频域名地址:https://vod.play.t-aaron.com/
  22. '''
  23. class AliyunVodSdk:
  24. def __init__(self, requestId):
  25. self.__client = None
  26. self.__access_key = 'LTAI5tMiefafZ6br4zmrQWv9'
  27. self.__access_secret = 'JgzQjSCkwZ7lefZO6egOArw38YH1Tk'
  28. self.__regionId = "cn-shanghai"
  29. self.__cateId = '1000468340'
  30. self.__requestId = requestId
  31. def init_vod_client(self):
  32. return AcsClient(self.__access_key, self.__access_secret, self.__regionId, auto_retry=True, max_retry_time=3, timeout=30)
  33. '''
  34. 根据videoId获取视频地址
  35. '''
  36. def get_play_info(self, videoId):
  37. logger.info("开始获取视频地址,videoId:{}", videoId)
  38. start = time.time()
  39. while True:
  40. try:
  41. clt = self.init_vod_client()
  42. request = GetPlayInfoRequest.GetPlayInfoRequest()
  43. request.set_accept_format('JSON')
  44. request.set_VideoId(videoId)
  45. request.set_AuthTimeout(3600 * 5)
  46. response = json.loads(clt.do_action_with_exception(request))
  47. play_url = response["PlayInfoList"]["PlayInfo"][0]["PlayURL"]
  48. logger.info("获取视频地址成功,视频地址: {}", play_url)
  49. return play_url
  50. except Exception as e:
  51. logger.error("获取视频地址失败,5秒后重试, requestId: {}")
  52. time.sleep(5)
  53. current_time = time.time()
  54. if "HTTP Status: 403" not in str(e):
  55. logger.exception("获取视频地址失败: {}", e)
  56. raise e
  57. if "HTTP Status: 403" in str(e) and ("UploadFail" in str(e) or "TranscodeFail" in str(e)):
  58. logger.exception("获取视频地址失败: {}", e)
  59. raise e
  60. diff_time = current_time - start
  61. if diff_time > 60 * 60 * 5:
  62. logger.exception("获取视频地址失败超时异常: {},超时时间:{}", str(e), diff_time)
  63. raise e
  64. def upload_local_video(self, filePath, file_title, storageLocation=None):
  65. logger.info("开始执行vod视频上传, filePath: {}", filePath)
  66. uploader = AliyunVodUploader(self.__access_key, self.__access_secret, self.__requestId)
  67. uploadVideoRequest = UploadVideoRequest(filePath, file_title)
  68. uploadVideoRequest.setCateId(self.__cateId)
  69. if storageLocation:
  70. uploadVideoRequest.setStorageLocation(storageLocation)
  71. MAX_RETRIES = 3
  72. retry_count = 0
  73. while True:
  74. try:
  75. result = uploader.uploadLocalVideo(uploadVideoRequest)
  76. logger.info("vod视频上传成功, videoId:{}", result.get("VideoId"))
  77. return result.get("VideoId")
  78. except Exception as e:
  79. retry_count += 1
  80. time.sleep(1)
  81. logger.error("vod视频上传失败,重试次数:{}", retry_count)
  82. if retry_count >= MAX_RETRIES:
  83. logger.exception("vod视频上传重试失败: {}", str(e))
  84. raise e
  85. YY_MM_DD_HH_MM_SS = "%Y-%m-%d %H:%M:%S"
  86. YMDHMSF = "%Y%m%d%H%M%S%f"
  87. def generate_timestamp():
  88. """根据当前时间获取时间戳,返回整数"""
  89. return int(time.time())
  90. def now_date_to_str(fmt=None):
  91. if fmt is None:
  92. fmt = YY_MM_DD_HH_MM_SS
  93. return datetime.datetime.now().strftime(fmt)
  94. if __name__ == "__main__":
  95. # 本地原视频命名
  96. random_time = now_date_to_str(YMDHMSF)
  97. # # 如果是离线视频,将 _on_or_ 替换为 _off_or_
  98. # orFilePath = "%s%s%s%s%s" % ('本地路径', random_time, "_on_or_", 'requestId', ".mp4")
  99. # # 本地AI识别后的视频命名
  100. # # 如果是离线视频,将 _on_ai_ 替换为 _off_ai_
  101. # aiFilePath = "%s%s%s%s%s" % ('本地路径', random_time, "_on_ai_", 'requestId', ".mp4")
  102. # filePath = "%s%s%s%s%s" % ('D:\\shipin\\', random_time, "_on_ai_", '11111111', ".mp4")
  103. filePath = 'D:\\shipin\\111.mp4'
  104. codClinet = AliyunVodSdk("1111111")
  105. result = codClinet.upload_local_video(filePath, 'aiOnLineVideo')
  106. print(result)
  107. url = codClinet.get_play_info(result)
  108. print(url)