download.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import yt_dlp
  2. from typing import NamedTuple, Optional
  3. ydl_opts = {
  4. 'format': 'bestaudio/best',
  5. 'postprocessors': [{
  6. 'key': 'FFmpegExtractAudio',
  7. 'preferredcodec': 'mp3',
  8. 'preferredquality': '128',
  9. }],
  10. }
  11. Url = str
  12. class Video(NamedTuple):
  13. link: Url
  14. id: str
  15. title: str
  16. is_live: Optional[bool] = None
  17. def get_info_yt_video(url) -> Video:
  18. """Checks yt video url and returns info about video
  19. [is_live, link, id, title]
  20. """
  21. ydl = yt_dlp.YoutubeDL({'outtmpl': '%(id)s.%(ext)s'})
  22. with ydl:
  23. try:
  24. result = ydl.extract_info(url, download=False)
  25. except yt_dlp.utils.DownloadError:
  26. print('Unsupported URL. Try another one')
  27. exit()
  28. # We just want to extract the info
  29. if result:
  30. videos = dict(result)
  31. else:
  32. raise Exception('Video not found')
  33. if 'entries' in videos:
  34. # Can be a playlist or a list of videos
  35. info = videos['entries'][0]
  36. else:
  37. # Just a video
  38. info = videos
  39. try:
  40. is_live = info["is_live"]
  41. except KeyError:
  42. is_live = False
  43. return Video(
  44. is_live=is_live,
  45. link=url,
  46. id=info["id"],
  47. title=info["title"]
  48. )
  49. def get_mp3_from_yt(video: Video) -> None:
  50. """Just download audio from yt video and convert to mp3"""
  51. with yt_dlp.YoutubeDL(ydl_opts) as ydl:
  52. ydl.download([video.link])