KFMPod/generator.py

86 lines
2.7 KiB
Python
Raw Permalink Normal View History

2023-12-06 10:24:26 +00:00
import os
import time
from pod2gen import Podcast, Episode, Media, Person
2023-12-06 10:46:59 +00:00
from mutagen import mp4
2023-12-06 10:24:26 +00:00
from datetime import timedelta, datetime as dt
from dateutil.tz import UTC
2023-12-06 10:46:59 +00:00
def get_mp4_metadata(file_path:str, filename:str) -> (timedelta, str):
"""Extract MP4 metadata from a file.
Args:
file_path (_type_): File path to the MP4 file.
str (_type_): Name of the MP4 file.
Returns:
_type_: Timedelta and description of the MP4 file.
"""
2023-12-06 10:24:26 +00:00
track_seconds = round(mp4.MP4(file_path).info.length)
time_split = time.strftime("%H:%M:%S", time.gmtime(track_seconds)).split(":")
try:
2023-12-06 10:46:59 +00:00
description = mp4.MP4(file_path).tags["\xa9cmt"][0]
2023-12-06 10:24:26 +00:00
except KeyError:
2023-12-06 10:46:59 +00:00
description = filename.replace("_", " ")
2023-12-06 10:24:26 +00:00
return (
timedelta(
hours=int(time_split[0]),
minutes=int(time_split[1]),
seconds=int(time_split[2]),
),
description,
)
2023-12-06 10:46:59 +00:00
def add_episodes_from_folder(folder_path:str) -> None:
"""Loop over all files in a folder and add them to the Podcast.
Args:
folder_path (str): Folder to loop over.
"""
2023-12-06 10:24:26 +00:00
file_list = os.listdir(folder_path)
2023-12-06 10:46:59 +00:00
list_of_episodes = [x for x in file_list if "m4b" in x]
2023-12-06 10:24:26 +00:00
# file_list.pop(0)
for file in list_of_episodes:
filename = file[:-4]
ep_details = filename.split(" ")
file_size = os.stat(f"./{folder_path}/{file}").st_size
2023-12-06 10:46:59 +00:00
file_length, description = get_mp4_metadata(f"./{folder_path}/{file}", filename)
p.add_episode(
Episode(
title=mp4.MP4(f"./{folder_path}/{file}").tags["\xa9nam"][0],
media=Media(
f"https://kithub.k-world.me.uk/Karl/KFMPod/raw/master/{folder_path}/{file}",
size=file_size,
type="mp3",
),
summary=description,
season=[int(i) for i in folder_path.split() if i.isdigit()][0],
episode_number=int(ep_details[1][-0]),
publication_date=dt.fromtimestamp(
os.stat(f"./{folder_path}/{file}").st_ctime, tz=UTC
),
2023-12-06 10:24:26 +00:00
)
2023-12-06 10:46:59 +00:00
)
2023-12-06 10:24:26 +00:00
owner = Person("Example", "email@example.com")
# Create the Podcast
p = Podcast(
name="Kurupt FM Podcast",
description="Kurupt FM Podcast",
website="https://kithub.k-world.me.uk/Karl/KFMPod",
explicit=False,
)
2023-12-06 10:38:29 +00:00
p.image = "https://kithub.k-world.me.uk/Karl/KFMPod/raw/master/Season%201/Ep.%201%ea%9e%89%20Music%20[B08DFKGFP8].jpg"
2023-12-06 10:24:26 +00:00
p.owner = owner
p.locked = True
p.withhold_from_itunes = True
add_episodes_from_folder("Season 1")
add_episodes_from_folder("Season 2")
add_episodes_from_folder("Season 3")
# Generate the RSS feed
p.rss_file("feed.xml", minimize=True)