common.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. from hashlib import md5
  10. import datetime
  11. import os
  12. import time
  13. import requests
  14. import ffmpeg
  15. import urllib3
  16. import subprocess
  17. proxies = {"http": None, "https": None}
  18. class Common:
  19. # 统一获取当前时间 <class 'datetime.datetime'> 2022-04-14 20:13:51.244472
  20. now = datetime.datetime.now()
  21. # 昨天 <class 'str'> 2022-04-13
  22. yesterday = (date.today() + timedelta(days=-1)).strftime("%Y/%m/%d")
  23. # 今天 <class 'datetime.date'> 2022-04-14
  24. today = date.today()
  25. # 明天 <class 'str'> 2022-04-15
  26. tomorrow = (date.today() + timedelta(days=1)).strftime("%Y/%m/%d")
  27. # 使用 logger 模块生成日志
  28. @staticmethod
  29. def logger(log_type, crawler):
  30. """
  31. 使用 logger 模块生成日志
  32. """
  33. # 日志路径
  34. log_dir = f"./{crawler}/logs/"
  35. log_path = os.getcwd() + os.sep + log_dir
  36. if not os.path.isdir(log_path):
  37. os.makedirs(log_path)
  38. # 日志文件名
  39. # log_name = time.strftime("%Y-%m-%d", time.localtime(time.time())) + f'-{crawler}-{log_type}.log'
  40. log_name = f'{date.today()}-{crawler}-{log_type}.log'
  41. # 日志不打印到控制台
  42. logger.remove(handler_id=None)
  43. # rotation="500 MB",实现每 500MB 存储一个文件
  44. # rotation="12:00",实现每天 12:00 创建一个文件
  45. # rotation="1 week",每周创建一个文件
  46. # retention="10 days",每隔10天之后就会清理旧的日志
  47. # 初始化日志
  48. logger.add(f"{log_dir}{log_name}", level="INFO", rotation='00:00')
  49. return logger
  50. # 清除日志,保留最近 10 个文件
  51. @classmethod
  52. def del_logs(cls, log_type, crawler):
  53. """
  54. 清除冗余日志文件
  55. :return: 保留最近 10 个日志
  56. """
  57. log_dir = f"./{crawler}/logs/"
  58. all_files = sorted(os.listdir(log_dir))
  59. all_logs = []
  60. for log in all_files:
  61. name = os.path.splitext(log)[-1]
  62. if name == ".log":
  63. all_logs.append(log)
  64. if len(all_logs) <= 30:
  65. pass
  66. else:
  67. for file in all_logs[:len(all_logs) - 30]:
  68. os.remove(log_dir + file)
  69. cls.logger(log_type, crawler).info("清除日志成功\n")
  70. # 删除 charles 缓存文件,只保留最近的两个文件
  71. @classmethod
  72. def del_charles_files(cls, log_type, crawler):
  73. # 目标文件夹下所有文件
  74. all_file = sorted(os.listdir(f"./{crawler}/{crawler}_chlsfiles/"))
  75. for file in all_file[0:-3]:
  76. os.remove(f"./{crawler}/{crawler}_chlsfiles/{file}")
  77. cls.logger(log_type, crawler).info("删除 charles 缓存文件成功\n")
  78. # 保存视频信息至 "./videos/{video_dict['video_title}/info.txt"
  79. @classmethod
  80. def save_video_info(cls, log_type, crawler, video_dict):
  81. md_title = md5(video_dict['video_title'].encode('utf8')).hexdigest()
  82. save_dict = {
  83. "video_title": "video_title",
  84. "video_id": "video_id",
  85. "duration": 0,
  86. "play_cnt": 0,
  87. "comment_cnt": 0,
  88. "like_cnt": 0,
  89. "share_cnt": 0,
  90. "video_width": 1920,
  91. "video_height": 1080,
  92. "publish_time_stamp": 946656000, # 2000-01-01 00:00:00
  93. "user_name": "crawler",
  94. "avatar_url": "http://weapppiccdn.yishihui.com/resources/images/pic_normal.png",
  95. "video_url": "video_url",
  96. "cover_url": "cover_url",
  97. "session": f"session-{int(time.time())}",
  98. }
  99. for video_key, video_value in video_dict.items():
  100. for save_key, save_value in save_dict.items():
  101. if save_key == video_key:
  102. save_dict[save_key] = video_value
  103. with open(f"./{crawler}/videos/{md_title}/info.txt", "w", encoding="UTF-8") as f_w:
  104. f_w.write(str(video_dict['video_id']) + "\n" +
  105. str(video_dict['video_title']) + "\n" +
  106. str(video_dict['duration']) + "\n" +
  107. str(video_dict['play_cnt']) + "\n" +
  108. str(video_dict['comment_cnt']) + "\n" +
  109. str(video_dict['like_cnt']) + "\n" +
  110. str(video_dict['share_cnt']) + "\n" +
  111. f"{video_dict['video_width']}*{video_dict['video_height']}" + "\n" +
  112. str(video_dict['publish_time_stamp']) + "\n" +
  113. str(video_dict['user_name']) + "\n" +
  114. str(video_dict['avatar_url']) + "\n" +
  115. str(video_dict['video_url']) + "\n" +
  116. str(video_dict['cover_url']) + "\n" +
  117. str(video_dict['session']))
  118. Common.logger(log_type, crawler).info("==========视频信息已保存至info.txt==========")
  119. # 封装下载视频或封面的方法
  120. @classmethod
  121. def download_method(cls, log_type, crawler, text, title, url):
  122. """
  123. 下载封面:text == "cover" ; 下载视频:text == "video"
  124. 需要下载的视频标题:d_title
  125. 视频封面,或视频播放地址:d_url
  126. 下载保存路径:"./files/{d_title}/"
  127. """
  128. videos_dir = f"./{crawler}/videos/"
  129. if not os.path.exists(videos_dir):
  130. os.mkdir(videos_dir)
  131. # 首先创建一个保存该视频相关信息的文件夹
  132. md_title = md5(title.encode('utf8')).hexdigest()
  133. video_path = f"./{crawler}/videos/{md_title}/"
  134. if not os.path.exists(video_path):
  135. os.mkdir(video_path)
  136. # 下载视频
  137. if text == "video":
  138. # 需要下载的视频地址
  139. video_url = str(url).replace('http://', 'https://')
  140. # 视频名
  141. video_name = "video.mp4"
  142. for i in range(3):
  143. try:
  144. # 下载视频,最多重试三次
  145. urllib3.disable_warnings()
  146. # response = requests.get(video_url, stream=True, proxies=cls.tunnel_proxies(), verify=False)
  147. response = requests.get(video_url, stream=True, proxies=proxies, verify=False)
  148. with open(video_path + video_name, "wb") as f:
  149. for chunk in response.iter_content(chunk_size=10240):
  150. f.write(chunk)
  151. cls.logger(log_type, crawler).info("==========视频下载完成==========")
  152. break
  153. except Exception as e:
  154. cls.logger(log_type, crawler).error(f"视频下载失败:{e}\n")
  155. time.sleep(1)
  156. # 下载音频
  157. elif text == "audio":
  158. # 需要下载的视频地址
  159. audio_url = str(url).replace('http://', 'https://')
  160. # 音频名
  161. audio_name = "audio.mp4"
  162. # 下载视频
  163. urllib3.disable_warnings()
  164. # response = requests.get(audio_url, stream=True, proxies=cls.tunnel_proxies(), verify=False)
  165. response = requests.get(audio_url, stream=True, proxies=proxies, verify=False)
  166. try:
  167. with open(video_path + audio_name, "wb") as f:
  168. for chunk in response.iter_content(chunk_size=10240):
  169. f.write(chunk)
  170. cls.logger(log_type, crawler).info("==========音频下载完成==========")
  171. except Exception as e:
  172. cls.logger(log_type, crawler).error(f"音频下载失败:{e}\n")
  173. # 下载封面
  174. elif text == "cover":
  175. # 需要下载的封面地址
  176. cover_url = str(url)
  177. # 封面名
  178. cover_name = "image.jpg"
  179. # 下载封面
  180. urllib3.disable_warnings()
  181. # response = requests.get(cover_url, proxies=cls.tunnel_proxies(), verify=False)
  182. response = requests.get(cover_url, verify=False)
  183. try:
  184. with open(video_path + cover_name, "wb") as f:
  185. f.write(response.content)
  186. cls.logger(log_type, crawler).info("==========封面下载完成==========")
  187. except Exception as e:
  188. cls.logger(log_type, crawler).error(f"封面下载失败:{e}\n")
  189. # youtube 视频下载
  190. elif text == "youtube_video":
  191. # 需要下载的视频地址
  192. video_url = url
  193. # 视频名
  194. video_name = "video.mp4"
  195. try:
  196. download_cmd = f'yt-dlp -f "bv[height<=720][ext=mp4]+ba[ext=m4a]" --merge-output-format mp4 "{video_url}-U" -o {video_path}{video_name}'
  197. Common.logger(log_type, crawler).info(f"download_cmd:{download_cmd}")
  198. os.system(download_cmd)
  199. # move_cmd = f"mv {video_name} {video_path}"
  200. # os.system(move_cmd)
  201. cls.logger(log_type, crawler).info("==========视频下载完成==========")
  202. except Exception as e:
  203. Common.logger(log_type, crawler).error(f"视频下载失败:{e}\n")
  204. # 西瓜视频 / 音频下载
  205. elif text == "xigua_video":
  206. # 需要下载的视频地址
  207. video_url = str(url).replace('http://', 'https://')
  208. # 视频名
  209. video_name = "video1.mp4"
  210. # 下载视频
  211. urllib3.disable_warnings()
  212. # response = requests.get(video_url, stream=True, proxies=cls.tunnel_proxies(), verify=False)
  213. response = requests.get(video_url, stream=True, proxies=proxies, verify=False)
  214. try:
  215. with open(video_path + video_name, "wb") as f:
  216. for chunk in response.iter_content(chunk_size=10240):
  217. f.write(chunk)
  218. cls.logger(log_type, crawler).info("==========视频下载完成==========")
  219. except Exception as e:
  220. cls.logger(log_type, crawler).error(f"视频下载失败:{e}\n")
  221. elif text == "xigua_audio":
  222. # 需要下载的视频地址
  223. audio_url = str(url).replace('http://', 'https://')
  224. # 音频名
  225. audio_name = "audio1.mp4"
  226. # 下载视频
  227. urllib3.disable_warnings()
  228. # response = requests.get(audio_url, stream=True, proxies=cls.tunnel_proxies(), verify=False)
  229. response = requests.get(audio_url, stream=True, proxies=proxies, verify=False)
  230. try:
  231. with open(video_path + audio_name, "wb") as f:
  232. for chunk in response.iter_content(chunk_size=10240):
  233. f.write(chunk)
  234. cls.logger(log_type, crawler).info("==========音频下载完成==========")
  235. except Exception as e:
  236. cls.logger(log_type, crawler).error(f"音频下载失败:{e}\n")
  237. @classmethod
  238. def ffmpeg(cls, log_type, crawler, video_path):
  239. # Common.logger(log_type, crawler).info(f"video_path:{video_path}")
  240. video_title = video_path.replace(f"./{crawler}/videos/", "").replace("/video.mp4", "")
  241. # Common.logger(log_type, crawler).info(f"video_title:{video_title}")
  242. md_title = md5(video_title.encode('utf8')).hexdigest()
  243. video_path = f"./{crawler}/videos/{md_title}/video.mp4"
  244. # Common.logger(log_type, crawler).info(f"{video_path}")
  245. if os.path.getsize(video_path) == 0:
  246. Common.logger(log_type, crawler).info(f'video_size:{os.path.getsize(video_path)}')
  247. return
  248. probe = ffmpeg.probe(video_path)
  249. video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
  250. if video_stream is None:
  251. Common.logger(log_type, crawler).info('No video Stream found!')
  252. return
  253. format1 = probe['format']
  254. size = int(int(format1['size']) / 1024 / 1024)
  255. width = int(video_stream['width'])
  256. height = int(video_stream['height'])
  257. duration = int(float(video_stream['duration']))
  258. ffmpeg_dict = {
  259. 'width': width,
  260. 'height': height,
  261. 'duration': duration,
  262. 'size': size
  263. }
  264. return ffmpeg_dict
  265. # 合并音视频
  266. @classmethod
  267. def video_compose(cls, log_type, crawler, video_dir):
  268. video_title = video_dir.replace(f"./{crawler}/videos/", "")
  269. md_title = md5(video_title.encode('utf8')).hexdigest()
  270. video_dir = f"./{crawler}/videos/{md_title}"
  271. try:
  272. video_path = f'{video_dir}/video1.mp4'
  273. audio_path = f'{video_dir}/audio1.mp4'
  274. out_path = f'{video_dir}/video.mp4'
  275. cmd = f'ffmpeg -i {video_path} -i {audio_path} -c:v copy -c:a aac -strict experimental -map 0:v:0 -map 1:a:0 {out_path}'
  276. # print(cmd)
  277. subprocess.call(cmd, shell=True)
  278. for file in os.listdir(video_dir):
  279. if file.split('.mp4')[0] == 'video1' or file.split('.mp4')[0] == 'audio1':
  280. os.remove(f'{video_dir}/{file}')
  281. Common.logger(log_type, crawler).info('合成成功\n')
  282. except Exception as e:
  283. Common.logger(log_type, crawler).error(f'video_compose异常:{e}\n')
  284. # 快代理
  285. @classmethod
  286. def tunnel_proxies(cls):
  287. # 隧道域名:端口号
  288. tunnel = "q796.kdltps.com:15818"
  289. # 用户名密码方式
  290. username = "t17772369458618"
  291. password = "5zqcjkmy"
  292. tunnel_proxies = {
  293. "http": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": username, "pwd": password, "proxy": tunnel},
  294. "https": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": username, "pwd": password, "proxy": tunnel}
  295. }
  296. # 白名单方式(需提前设置白名单)
  297. # proxies = {
  298. # "http": "http://%(proxy)s/" % {"proxy": tunnel},
  299. # "https": "http://%(proxy)s/" % {"proxy": tunnel}
  300. # }
  301. # 要访问的目标网页
  302. # target_url = "https://www.kuaishou.com/profile/3xk9tkk6kkwkf7g"
  303. # target_url = "https://dev.kdlapi.com/testproxy"
  304. # # 使用隧道域名发送请求
  305. # response = requests.get(target_url, proxies=proxies)
  306. # print(response.text)
  307. return tunnel_proxies
  308. if __name__ == "__main__":
  309. Common.tunnel_proxies()
  310. pass