noumanjavaid commited on
Commit
422e5df
·
verified ·
1 Parent(s): b19a665

Create download.py

Browse files
Files changed (1) hide show
  1. download.py +96 -0
download.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import unicode_literals
2
+ import yt_dlp as youtube_dl
3
+ import os
4
+ import time
5
+ import os
6
+ import shutil
7
+
8
+ MAX_FILE_SIZE = 100 * 1024 * 1024 # 100 MB
9
+ FILE_TOO_LARGE_MESSAGE = "The audio file is too large for the current size and rate limits using Whisper. If you used a YouTube link, please try a shorter video clip. If you uploaded an audio file, try trimming or compressing the audio to under 100 MB."
10
+ max_retries = 3
11
+ delay = 2
12
+
13
+
14
+ class MyLogger(object):
15
+ def __init__(self, external_logger=lambda x: None):
16
+ self.external_logger = external_logger
17
+
18
+ def debug(self, msg):
19
+ print("[debug]: ", msg)
20
+ self.external_logger(msg)
21
+
22
+ def warning(self, msg):
23
+ print("[warning]: ", msg)
24
+
25
+ def error(self, msg):
26
+ print("[error]: ", msg)
27
+
28
+
29
+ def my_hook(d):
30
+ print("hook", d["status"])
31
+ if d["status"] == "finished":
32
+ print("Done downloading, now converting ...")
33
+
34
+
35
+ def get_ydl_opts(external_logger=lambda x: None):
36
+ return {
37
+ "format": "bestaudio/best",
38
+ "postprocessors": [
39
+ {
40
+ "key": "FFmpegExtractAudio",
41
+ "preferredcodec": "mp3",
42
+ "preferredquality": "192", # set the preferred bitrate to 192kbps
43
+ }
44
+ ],
45
+ "logger": MyLogger(external_logger),
46
+ "outtmpl": "./downloads/audio/%(title)s.%(ext)s", # Set the output filename directly
47
+ "progress_hooks": [my_hook],
48
+ }
49
+
50
+
51
+ def download_video_audio(url, external_logger=lambda x: None):
52
+ retries = 0
53
+ while retries < max_retries:
54
+ try:
55
+ ydl_opts = get_ydl_opts(external_logger)
56
+ with youtube_dl.YoutubeDL(ydl_opts) as ydl:
57
+ print("Going to download ", url)
58
+ info = ydl.extract_info(url, download=False)
59
+ filesize = info.get("filesize", 0)
60
+ if filesize > MAX_FILE_SIZE:
61
+ raise Exception(FILE_TOO_LARGE_MESSAGE)
62
+ filename = ydl.prepare_filename(info)
63
+ res = ydl.download([url])
64
+ print("youtube-dl result :", res)
65
+ mp3_filename = os.path.splitext(filename)[0] + '.mp3'
66
+ print('mp3 file name - ', mp3_filename)
67
+ return mp3_filename
68
+ except Exception as e:
69
+ retries += 1
70
+ print(
71
+ f"An error occurred during downloading (Attempt {retries}/{max_retries}):",
72
+ str(e),
73
+ )
74
+ if retries >= max_retries:
75
+ raise e
76
+ time.sleep(delay)
77
+
78
+
79
+
80
+ def delete_download(path):
81
+ try:
82
+ if os.path.isfile(path):
83
+ os.remove(path)
84
+ print(f"File {path} has been deleted.")
85
+ elif os.path.isdir(path):
86
+ shutil.rmtree(path)
87
+ print(f"Directory {path} and its contents have been deleted.")
88
+ else:
89
+ print(f"The path {path} is neither a file nor a directory.")
90
+ except PermissionError:
91
+ print(f"Permission denied: Unable to delete {path}.")
92
+ except FileNotFoundError:
93
+ print(f"File or directory not found: {path}")
94
+ except Exception as e:
95
+ print(f"An error occurred while trying to delete {path}: {str(e)}")
96
+