common.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/1/31
  4. """
  5. 公共方法,包含:生成log / 删除log / 下载方法 / 删除 weixinzhishu_chlsfiles / 过滤词库 / 保存视频信息至本地 txt / 翻译 / ffmpeg
  6. """
  7. from datetime import date, timedelta
  8. from loguru import logger
  9. import datetime
  10. import os
  11. import time
  12. import requests
  13. import ffmpeg
  14. import urllib3
  15. proxies = {"http": None, "https": None}
  16. class Common:
  17. # 统一获取当前时间 <class 'datetime.datetime'> 2022-04-14 20:13:51.244472
  18. now = datetime.datetime.now()
  19. # 昨天 <class 'str'> 2022-04-13
  20. yesterday = (date.today() + timedelta(days=-1)).strftime("%Y/%m/%d")
  21. # 今天 <class 'datetime.date'> 2022-04-14
  22. today = date.today()
  23. # 明天 <class 'str'> 2022-04-15
  24. tomorrow = (date.today() + timedelta(days=1)).strftime("%Y/%m/%d")
  25. # 使用 logger 模块生成日志
  26. @staticmethod
  27. def logger(log_type, crawler):
  28. """
  29. 使用 logger 模块生成日志
  30. """
  31. # 日志路径
  32. log_dir = f"./{crawler}/logs/"
  33. log_path = os.getcwd() + os.sep + log_dir
  34. if not os.path.isdir(log_path):
  35. os.makedirs(log_path)
  36. # 日志文件名
  37. log_name = time.strftime("%Y-%m-%d", time.localtime(time.time())) + f'-{crawler}-{log_type}.log'
  38. # 日志不打印到控制台
  39. logger.remove(handler_id=None)
  40. # rotation="500 MB",实现每 500MB 存储一个文件
  41. # rotation="12:00",实现每天 12:00 创建一个文件
  42. # rotation="1 week",每周创建一个文件
  43. # retention="10 days",每隔10天之后就会清理旧的日志
  44. # 初始化日志
  45. logger.add(log_dir + log_name, level="INFO", rotation='00:00')
  46. return logger
  47. # 清除日志,保留最近 10 个文件
  48. @classmethod
  49. def del_logs(cls, log_type, crawler):
  50. """
  51. 清除冗余日志文件
  52. :return: 保留最近 10 个日志
  53. """
  54. log_dir = f"./{crawler}/logs/"
  55. all_files = sorted(os.listdir(log_dir))
  56. all_logs = []
  57. for log in all_files:
  58. name = os.path.splitext(log)[-1]
  59. if name == ".log":
  60. all_logs.append(log)
  61. if len(all_logs) <= 10:
  62. pass
  63. else:
  64. for file in all_logs[:len(all_logs) - 10]:
  65. os.remove(log_dir + file)
  66. cls.logger(log_type, crawler).info("清除日志成功\n")
  67. # 删除 charles 缓存文件,只保留最近的两个文件
  68. @classmethod
  69. def del_charles_files(cls, log_type, crawler):
  70. # 目标文件夹下所有文件
  71. all_file = sorted(os.listdir(f"./{crawler}/{crawler}_chlsfiles/"))
  72. for file in all_file[0:-3]:
  73. os.remove(f"./{crawler}/{crawler}_chlsfiles/{file}")
  74. cls.logger(log_type, crawler).info("删除 charles 缓存文件成功\n")
  75. # 保存视频信息至 "./videos/{video_dict['video_title}/info.txt"
  76. @classmethod
  77. def save_video_info(cls, log_type, crawler, video_dict):
  78. with open(f"./{crawler}/videos/{video_dict['video_title']}/info.txt",
  79. "a", encoding="UTF-8") as f_a:
  80. f_a.write(str(video_dict['video_id']) + "\n" +
  81. str(video_dict['video_title']) + "\n" +
  82. str(video_dict['duration']) + "\n" +
  83. str(video_dict['play_cnt']) + "\n" +
  84. str(video_dict['comment_cnt']) + "\n" +
  85. str(video_dict['like_cnt']) + "\n" +
  86. str(video_dict['share_cnt']) + "\n" +
  87. f"{video_dict['video_width']}*{video_dict['video_height']}" + "\n" +
  88. str(video_dict['publish_time_stamp']) + "\n" +
  89. str(video_dict['user_name']) + "\n" +
  90. str(video_dict['avatar_url']) + "\n" +
  91. str(video_dict['video_url']) + "\n" +
  92. str(video_dict['cover_url']) + "\n" +
  93. str(video_dict['session']))
  94. Common.logger(log_type, crawler).info("==========视频信息已保存至info.txt==========")
  95. # 封装下载视频或封面的方法
  96. @classmethod
  97. def download_method(cls, log_type, crawler, text, title, url):
  98. """
  99. 下载封面:text == "cover" ; 下载视频:text == "video"
  100. 需要下载的视频标题:d_title
  101. 视频封面,或视频播放地址:d_url
  102. 下载保存路径:"./files/{d_title}/"
  103. """
  104. videos_dir = f"./{crawler}/videos/"
  105. if not os.path.exists(videos_dir):
  106. os.mkdir(videos_dir)
  107. # 首先创建一个保存该视频相关信息的文件夹
  108. video_dir = f"./{crawler}/videos/{title}/"
  109. if not os.path.exists(video_dir):
  110. os.mkdir(video_dir)
  111. # 下载视频
  112. if text == "video":
  113. # 需要下载的视频地址
  114. video_url = str(url).replace('http://', 'https://')
  115. # 视频名
  116. video_name = "video.mp4"
  117. # 下载视频
  118. urllib3.disable_warnings()
  119. response = requests.get(video_url, stream=True, proxies=proxies, verify=False)
  120. try:
  121. with open(video_dir + video_name, "wb") as f:
  122. for chunk in response.iter_content(chunk_size=10240):
  123. f.write(chunk)
  124. cls.logger(log_type, crawler).info("==========视频下载完成==========")
  125. except Exception as e:
  126. cls.logger(log_type, crawler).error(f"视频下载失败:{e}\n")
  127. elif text == "youtube_video":
  128. # 需要下载的视频地址
  129. video_url = url
  130. # 视频名
  131. video_name = "video.mp4"
  132. try:
  133. download_cmd = f'yt-dlp -f "bv[height=720][ext=mp4]+ba[ext=m4a]" --merge-output-format mp4 {video_url}-U -o {video_name}'
  134. # 'yt-dlp -f "bv[height=720][ext=mp4]+ba[ext=m4a]" --merge-output-format mp4 https://www.youtube.com/watch?v=Q4MtXQY0aHM-U -o video.mp4'
  135. Common.logger(log_type, crawler).info(f"download_cmd:{download_cmd}")
  136. os.system(download_cmd)
  137. move_cmd = f"mv {video_name} {video_dir}"
  138. os.system(move_cmd)
  139. cls.logger(log_type, crawler).info("==========视频下载完成==========")
  140. except Exception as e:
  141. Common.logger(log_type, crawler).error(f"视频下载失败:{e}\n")
  142. # 下载音频
  143. elif text == "audio":
  144. # 需要下载的视频地址
  145. audio_url = str(url).replace('http://', 'https://')
  146. # 音频名
  147. audio_name = "audio.mp4"
  148. # 下载视频
  149. urllib3.disable_warnings()
  150. response = requests.get(audio_url, stream=True, proxies=proxies, verify=False)
  151. try:
  152. with open(video_dir + audio_name, "wb") as f:
  153. for chunk in response.iter_content(chunk_size=10240):
  154. f.write(chunk)
  155. cls.logger(log_type, crawler).info("==========音频下载完成==========")
  156. except Exception as e:
  157. cls.logger(log_type, crawler).error(f"音频下载失败:{e}\n")
  158. # 下载封面
  159. elif text == "cover":
  160. # 需要下载的封面地址
  161. cover_url = str(url)
  162. # 封面名
  163. cover_name = "image.jpg"
  164. # 下载封面
  165. urllib3.disable_warnings()
  166. response = requests.get(cover_url, proxies=proxies, verify=False)
  167. try:
  168. with open(video_dir + cover_name, "wb") as f:
  169. f.write(response.content)
  170. cls.logger(log_type, crawler).info("==========封面下载完成==========")
  171. except Exception as e:
  172. cls.logger(log_type, crawler).error(f"封面下载失败:{e}\n")
  173. @classmethod
  174. def ffmpeg(cls, log_type, crawler, video_path):
  175. probe = ffmpeg.probe(video_path)
  176. video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
  177. if video_stream is None:
  178. Common.logger(log_type, crawler).info('No video Stream found!')
  179. return
  180. format1 = probe['format']
  181. size = int(int(format1['size']) / 1024 / 1024)
  182. width = int(video_stream['width'])
  183. height = int(video_stream['height'])
  184. duration = int(float(video_stream['duration']))
  185. ffmpeg_dict = {
  186. 'width': width,
  187. 'height': height,
  188. 'duration': duration,
  189. 'size': size
  190. }
  191. return ffmpeg_dict
  192. if __name__ == "__main__":
  193. pass