This repository has been archived by the owner on Feb 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfrom_url.py
67 lines (52 loc) · 1.85 KB
/
from_url.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from typing import NamedTuple
from pathlib import Path
import urllib.request
from logger import log
class DownloadResult(NamedTuple):
data: bytes
content_type: str
FAKE_UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"
def download_file(url: str) -> DownloadResult:
req = urllib.request.Request(
url,
data=None,
headers={"User-Agent": FAKE_UA},
)
with urllib.request.urlopen(req) as response:
return DownloadResult(
data=response.read(),
content_type=response.headers["content-type"],
)
def pretty_size(num, suffix="B") -> str:
for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, "Yi", suffix)
def cache_file(url: str, destination: Path, overwrite: bool = False) -> None:
if destination.exists():
if overwrite:
log.info(f"Overwriting file at {destination}")
else:
log.info(f"Using cached file at {destination}")
return
result = download_file(url=url)
size = pretty_size(num=len(result.data))
log.info(f"Downloaded {size} from {url}")
with open(destination, "wb") as f:
f.write(result.data)
log.info(f"Stored audio at {destination}")
def download_vid_audio(
url: str,
destination_path: Path,
) -> None:
import yt_dlp
ydl_opts = {
"format": "bestaudio",
"postprocessors": [{"key": "FFmpegExtractAudio", "preferredcodec": "mp3"}],
"outtmpl": f"{destination_path}.%(ext)s",
}
log.info(f"Download video from {url}")
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download(url)
log.info(f"Saved audio from {url} to {destination_path}")