download.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 as err:
  26. print('Unsupported URL. Try another one')
  27. # TODO make good
  28. raise Exception(str(err))
  29. # We just want to extract the info
  30. if result:
  31. videos = dict(result)
  32. else:
  33. raise Exception('Video not found')
  34. if 'entries' in videos:
  35. # Can be a playlist or a list of videos
  36. info = videos['entries'][0]
  37. else:
  38. # Just a video
  39. info = videos
  40. try:
  41. is_live = info["is_live"]
  42. except KeyError:
  43. is_live = False
  44. return Video(
  45. is_live=is_live,
  46. link=url,
  47. id=info["id"],
  48. title=info["title"]
  49. )
  50. def get_mp3_from_yt(video: Video) -> None:
  51. """Just download audio from yt video and convert to mp3"""
  52. with yt_dlp.YoutubeDL(ydl_opts) as ydl:
  53. ydl.download([video.link])