generator.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import os
  2. import time
  3. from pod2gen import Podcast, Episode, Media, Person
  4. from mutagen import mp4
  5. from datetime import timedelta, datetime as dt
  6. from dateutil.tz import UTC
  7. def get_mp4_metadata(file_path:str, filename:str) -> (timedelta, str):
  8. """Extract MP4 metadata from a file.
  9. Args:
  10. file_path (_type_): File path to the MP4 file.
  11. str (_type_): Name of the MP4 file.
  12. Returns:
  13. _type_: Timedelta and description of the MP4 file.
  14. """
  15. track_seconds = round(mp4.MP4(file_path).info.length)
  16. time_split = time.strftime("%H:%M:%S", time.gmtime(track_seconds)).split(":")
  17. try:
  18. description = mp4.MP4(file_path).tags["\xa9cmt"][0]
  19. except KeyError:
  20. description = filename.replace("_", " ")
  21. return (
  22. timedelta(
  23. hours=int(time_split[0]),
  24. minutes=int(time_split[1]),
  25. seconds=int(time_split[2]),
  26. ),
  27. description,
  28. )
  29. def add_episodes_from_folder(folder_path:str) -> None:
  30. """Loop over all files in a folder and add them to the Podcast.
  31. Args:
  32. folder_path (str): Folder to loop over.
  33. """
  34. file_list = os.listdir(folder_path)
  35. list_of_episodes = [x for x in file_list if "m4b" in x]
  36. # file_list.pop(0)
  37. for file in list_of_episodes:
  38. filename = file[:-4]
  39. ep_details = filename.split(" ")
  40. file_size = os.stat(f"./{folder_path}/{file}").st_size
  41. file_length, description = get_mp4_metadata(f"./{folder_path}/{file}", filename)
  42. p.add_episode(
  43. Episode(
  44. title=mp4.MP4(f"./{folder_path}/{file}").tags["\xa9nam"][0],
  45. media=Media(
  46. f"https://kithub.k-world.me.uk/Karl/KFMPod/raw/master/{folder_path}/{file}",
  47. size=file_size,
  48. type="mp3",
  49. ),
  50. summary=description,
  51. season=[int(i) for i in folder_path.split() if i.isdigit()][0],
  52. episode_number=int(ep_details[1][-0]),
  53. publication_date=dt.fromtimestamp(
  54. os.stat(f"./{folder_path}/{file}").st_ctime, tz=UTC
  55. ),
  56. )
  57. )
  58. owner = Person("Example", "email@example.com")
  59. # Create the Podcast
  60. p = Podcast(
  61. name="Kurupt FM Podcast",
  62. description="Kurupt FM Podcast",
  63. website="https://kithub.k-world.me.uk/Karl/KFMPod",
  64. explicit=False,
  65. )
  66. p.image = "https://kithub.k-world.me.uk/Karl/KFMPod/raw/master/Season%201/Ep.%201%ea%9e%89%20Music%20[B08DFKGFP8].jpg"
  67. p.owner = owner
  68. p.locked = True
  69. p.withhold_from_itunes = True
  70. add_episodes_from_folder("Season 1")
  71. add_episodes_from_folder("Season 2")
  72. add_episodes_from_folder("Season 3")
  73. # Generate the RSS feed
  74. p.rss_file("feed.xml", minimize=True)