1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- import yt_dlp
- from typing import NamedTuple, Optional
- ydl_opts = {
- 'format': 'bestaudio/best',
- 'postprocessors': [{
- 'key': 'FFmpegExtractAudio',
- 'preferredcodec': 'mp3',
- 'preferredquality': '128',
- }],
- }
- Url = str
- class Video(NamedTuple):
- link: Url
- id: str
- title: str
- is_live: Optional[bool] = None
- def get_info_yt_video(url) -> Video:
- """Checks yt video url and returns info about video
- [is_live, link, id, title]
- """
- ydl = yt_dlp.YoutubeDL({'outtmpl': '%(id)s.%(ext)s'})
- with ydl:
- try:
- result = ydl.extract_info(url, download=False)
- except yt_dlp.utils.DownloadError as err:
- print('Unsupported URL. Try another one')
- # TODO make good
- raise Exception(str(err))
- # We just want to extract the info
- if result:
- videos = dict(result)
- else:
- raise Exception('Video not found')
- if 'entries' in videos:
- # Can be a playlist or a list of videos
- info = videos['entries'][0]
- else:
- # Just a video
- info = videos
- try:
- is_live = info["is_live"]
- except KeyError:
- is_live = False
- return Video(
- is_live=is_live,
- link=url,
- id=info["id"],
- title=info["title"]
- )
- def get_mp3_from_yt(video: Video) -> None:
- """Just download audio from yt video and convert to mp3"""
- with yt_dlp.YoutubeDL(ydl_opts) as ydl:
- ydl.download([video.link])
|