generator.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. import os
  2. import time
  3. from pod2gen import Podcast, Episode, Media, Person
  4. from mutagen import mp4, mp3
  5. from datetime import timedelta, datetime as dt
  6. from dateutil.tz import UTC
  7. def get_mp3_metadata(file_path: str, filename: str) -> (timedelta, str):
  8. """Extract MP3 metadata from a file.
  9. Args:
  10. file_path (str): Path to the MP3 file.
  11. filename (str): Name of the MP3 file.
  12. Returns:
  13. tuple: Timedelta and description of the MP3 file.
  14. """
  15. try:
  16. mp3_file = mp3.MP3(file_path)
  17. track_seconds = round(mp3_file.info.length)
  18. time_split = time.strftime("%H:%M:%S", time.gmtime(track_seconds)).split(":")
  19. duration = timedelta(
  20. hours=int(time_split[0]),
  21. minutes=int(time_split[1]),
  22. seconds=int(time_split[2]),
  23. )
  24. description = mp3_file.tags.get("COMM::'eng'", [filename.replace("_", " ")])[0].text[0]
  25. except Exception as e:
  26. print(f"Error processing file {file_path}: {e}")
  27. duration = timedelta(0)
  28. description = filename.replace("_", " ")
  29. return duration, description
  30. def get_mp4_metadata(file_path: str, filename: str) -> (timedelta, str):
  31. """Extract MP4 metadata from a file.
  32. Args:
  33. file_path (_type_): File path to the MP4 file.
  34. str (_type_): Name of the MP4 file.
  35. Returns:
  36. _type_: Timedelta and description of the MP4 file.
  37. """
  38. track_seconds = round(mp4.MP4(file_path).info.length)
  39. time_split = time.strftime("%H:%M:%S", time.gmtime(track_seconds)).split(":")
  40. try:
  41. description = mp4.MP4(file_path).tags["\xa9cmt"][0]
  42. except KeyError:
  43. description = filename.replace("_", " ")
  44. return (
  45. timedelta(
  46. hours=int(time_split[0]),
  47. minutes=int(time_split[1]),
  48. seconds=int(time_split[2]),
  49. ),
  50. description,
  51. )
  52. def add_episodes_from_folder(folder_path: str, season:int) -> None:
  53. """Loop over all files in a folder and add them to the Podcast.
  54. Args:
  55. folder_path (str): Folder to loop over.
  56. season (int): Season number for for the podcast
  57. """
  58. file_list = os.listdir(folder_path)
  59. list_of_episodes = sorted([x for x in file_list if "mp3" in x], key=lambda x: int(x.split()[1].split('.')[0]))
  60. # file_list.pop(0)
  61. for file in list_of_episodes:
  62. filename = file[:-4]
  63. ep_details = filename.split(" ")
  64. file_size = os.stat(f"./{folder_path}/{file}").st_size
  65. file_length, description = get_mp3_metadata(f"./{folder_path}/{file}", filename)
  66. p.add_episode(
  67. Episode(
  68. title=f"{folder_path} - {filename}",
  69. media=Media(
  70. f"https://kithub.k-world.me.uk/Karl/GTPStories/raw/master/{folder_path}/{file}",
  71. size=file_size,
  72. type="mp3",
  73. ),
  74. summary=description,
  75. season=season,
  76. episode_number=int(ep_details[1][-0]),
  77. image=f'https://kithub.k-world.me.uk/Karl/GTPStories/raw/master/{folder_path}/{folder_path}_wide.png',
  78. publication_date=dt.fromtimestamp(
  79. os.stat(f"./{folder_path}/{file}").st_ctime, tz=UTC
  80. ),
  81. )
  82. )
  83. owner = Person("Example", "email@example.com")
  84. # Create the Podcast
  85. p = Podcast(
  86. name="GPT Stories",
  87. description="GPT Stories in audio form",
  88. website="http://kithub.k-world.me.uk/Karl/GTPStories",
  89. explicit=True,
  90. )
  91. p.image = "https://kithub.k-world.me.uk/Karl/GTPStories/raw/master/logo.png"
  92. p.owner = owner
  93. p.locked = True
  94. p.withhold_from_itunes = True
  95. add_episodes_from_folder("Reboot", 1)
  96. add_episodes_from_folder("Pathfinders", 2)
  97. # add_episodes_from_folder("Season 3")
  98. # Generate the RSS feed
  99. p.rss_file("feed.xml", minimize=True)