Compare commits

..
7 Commits
4 changed files with 130 additions and 43 deletions

No files matched your search

+1 -1
View File
@@ -52,7 +52,7 @@ options:
--use_coreml Optional: use Apple Silicon GPU with CoreML for separation (default: False). Example: --use_coreml=true
--denoise DENOISE Optional: enable or disable denoising during separation (default: True). Example: --denoise=False
--normalize NORMALIZE Optional: enable or disable normalization during separation (default: True). Example: --normalize=False
--create_track_subfolders Optional: create subfolders in the output folder for each track (default: False). Example: --create_track_subfolders=true
--no_track_subfolders Optional:do NOT create a named subfolder for each track. Example: --no_track_subfolders
```
Example:
+103 -29
View File
@@ -22,6 +22,7 @@ class KaraokePrep:
model_name_2="UVR-MDX-NET-Inst_HQ_3",
model_file_dir="/tmp/audio-separator-models/",
output_dir=".",
output_format="WAV",
use_cuda=False,
use_coreml=False,
normalization_enabled=True,
@@ -50,12 +51,15 @@ class KaraokePrep:
self.model_name_2 = model_name_2
self.model_file_dir = model_file_dir
self.output_dir = output_dir
self.output_format = output_format
self.use_cuda = use_cuda
self.use_coreml = use_coreml
self.normalization_enabled = normalization_enabled
self.denoise_enabled = denoise_enabled
self.create_track_subfolders = create_track_subfolders
self.logger.debug(f"KaraokePrep output_format: {self.output_format}")
if not os.path.exists(self.output_dir):
self.logger.debug(f"Overall output dir {self.output_dir} did not exist, creating")
os.makedirs(self.output_dir)
@@ -63,7 +67,49 @@ class KaraokePrep:
self.logger.debug(f"Overall output dir {self.output_dir} already exists")
if artist is None or title is None:
raise Exception("Error: You must provide an artist and title.")
self.logger.warn(f"Artist or Title nor specified manually, guessing from YouTube metadata...")
self.extract_metadata_from_url()
def extract_metadata_from_url(self):
"""
Extracts metadata from the YouTube URL.
"""
if self.url:
with yt_dlp.YoutubeDL({"quiet": True}) as ydl:
info = ydl.extract_info(self.url, download=False)
self.artist, self.title = self.parse_metadata(info)
if self.artist and self.title:
self.logger.info(f"Extracted artist: {self.artist}, title: {self.title}")
else:
self.logger.error("Failed to extract artist and title from the YouTube URL.")
def parse_metadata(self, info):
"""
Parses the metadata to extract artist and title.
:param info: The metadata information extracted from yt_dlp.
:return: A tuple containing the artist and title.
"""
# Default values if parsing fails
artist = ""
title = ""
# Example: "Artist - Title"
if "title" in info and "-" in info["title"]:
artist, title = info["title"].split("-", 1)
artist = artist.strip()
title = title.strip()
elif "uploader" in info:
# Fallback to uploader as artist if title parsing fails
artist = info["uploader"]
if "title" in info:
title = info["title"].strip()
# If unable to parse, log an appropriate message
if not artist or not title:
self.logger.warning("Could not parse artist and title from the video metadata.")
return artist, title
def get_youtube_id_for_top_search_result(self, query):
ydl_opts = {"quiet": "True", "format": "bestaudio", "noplaylist": "True", "extract_flat": True}
@@ -77,22 +123,31 @@ class KaraokePrep:
self.logger.warning(f"No YouTube results found for query: {query}")
return None
def download_audio(self, youtube_id, filename):
def download_video(self, youtube_id, output_filename_no_extension):
self.logger.debug(f"Downloading YouTube video {youtube_id} to filename {output_filename_no_extension} + (as yet) unknown extension")
ydl_opts = {
"format": "ba",
"postprocessors": [
{
"key": "FFmpegExtractAudio",
"preferredcodec": "wav",
"preferredquality": "192",
}
],
"outtmpl": f"{filename}",
"format": "bv*+ba/b", # if a combined video + audio format is better than the best video-only format use the combined format
"outtmpl": f"{output_filename_no_extension}",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",
}
with yt_dlp.YoutubeDL(ydl_opts) as youtube_dl_instance:
youtube_dl_instance.download([f"https://www.youtube.com/watch?v={youtube_id}"])
self.logger.warn(f"Download finished, assuming hard-coded webm extension (!) and returning this filename")
# TODO: Replace hard-coded webm extension with the actual extension of the downloaded file using yt-dlp hooks / event callback
return output_filename_no_extension + ".webm"
def extract_still_image_from_video(self, input_filename, output_filename_no_extension):
output_filename = output_filename_no_extension + ".png"
self.logger.debug(f"Extracting still image from position 30s YouTube video to {output_filename}")
os.system(f'ffmpeg -i "{input_filename}" -ss 00:00:30 -vframes 1 "{output_filename}"')
return output_filename
def convert_to_wav(self, input_filename, output_filename_no_extension):
output_filename = output_filename_no_extension + ".wav"
self.logger.debug(f"Converting {input_filename} to WAV file {output_filename}")
os.system(f'ffmpeg -i "{input_filename}" "{output_filename}"')
return output_filename
def write_lyrics_from_genius(self, artist, title, filename):
genius = lyricsgenius.Genius(os.environ["GENIUS_API_TOKEN"])
@@ -135,14 +190,16 @@ class KaraokePrep:
self.logger.debug(f"audio_file is valid file: {audio_file}")
self.logger.debug(f"instantiating Separator with model_name: {model_name} and instrumental_path: {instrumental_path}")
self.logger.debug(
f"instantiating Separator with model_name: {model_name} instrumental_path: {instrumental_path} and output_format: {self.output_format}"
)
separator = Separator(
audio_file,
log_level=self.log_level,
log_formatter=self.log_formatter,
model_name=model_name,
model_file_dir=self.model_file_dir,
output_format="FLAC",
output_format=self.output_format,
primary_stem_path=instrumental_path,
secondary_stem_path=vocals_path,
)
@@ -176,13 +233,25 @@ class KaraokePrep:
"title": title,
}
yt_filename_pattern = os.path.join(track_output_dir, f"{artist_title} (YouTube *.wav")
youtube_audio_files = glob.glob(yt_filename_pattern)
youtube_audio_file = None
yt_webm_filename_pattern = os.path.join(track_output_dir, f"{artist_title} (YouTube *.webm")
yt_webm_glob = glob.glob(yt_webm_filename_pattern)
if youtube_audio_files:
youtube_audio_file = youtube_audio_files[0]
self.logger.debug(f"Youtube audio already exists, skipping download: {youtube_audio_file}")
yt_png_filename_pattern = os.path.join(track_output_dir, f"{artist_title} (YouTube *.png")
yt_png_glob = glob.glob(yt_png_filename_pattern)
yt_wav_filename_pattern = os.path.join(track_output_dir, f"{artist_title} (YouTube *.wav")
yt_wav_glob = glob.glob(yt_wav_filename_pattern)
processed_track["youtube_video"] = None
processed_track["youtube_still_image"] = None
processed_track["youtube_audio"] = None
if yt_webm_glob and yt_png_glob and yt_wav_glob:
processed_track["youtube_video"] = yt_webm_glob[0]
processed_track["youtube_still_image"] = yt_png_glob[0]
processed_track["youtube_audio"] = yt_wav_glob[0]
self.logger.debug(f"YouTube output files already exist, skipping download: {processed_track['youtube_video']} + .wav + .png")
else:
if self.url is None:
self.logger.warn(f"No URL specified - the top result from YouTube will be used.")
@@ -193,16 +262,21 @@ class KaraokePrep:
self.logger.info("Parsing YouTube video ID from URL...")
youtube_id = self.url.split("watch?v=")[1]
if youtube_id:
youtube_audio_file = os.path.join(track_output_dir, f"{artist_title} (YouTube {youtube_id})")
output_filename_no_extension = os.path.join(track_output_dir, f"{artist_title} (YouTube {youtube_id})")
self.logger.info("Downloading original audio from YouTube to filename {original_audio_filename}")
self.download_audio(youtube_id, youtube_audio_file)
youtube_audio_file = youtube_audio_file + ".wav"
self.logger.info("Downloading original video from YouTube...")
processed_track["youtube_video"] = self.download_video(youtube_id, output_filename_no_extension)
self.logger.info("Extracting still image from downloaded video...")
processed_track["youtube_still_image"] = self.extract_still_image_from_video(
processed_track["youtube_video"], output_filename_no_extension
)
self.logger.info("Converting downloaded video to WAV for audio processing...")
processed_track["youtube_audio"] = self.convert_to_wav(processed_track["youtube_video"], output_filename_no_extension)
else:
self.logger.warning(f"Skipping {title} by {artist} due to missing YouTube ID.")
processed_track["youtube_audio"] = youtube_audio_file
lyrics_file = os.path.join(track_output_dir, f"{artist_title} (Lyrics).txt")
if os.path.exists(lyrics_file):
self.logger.debug(f"Lyrics file already exists, skipping fetch: {lyrics_file}")
@@ -214,8 +288,8 @@ class KaraokePrep:
self.logger.info(f"Separating audio twice for track: {title} by {artist}")
instrumental_path = os.path.join(track_output_dir, f"{artist_title} (Instrumental {self.model_name}).flac")
vocals_path = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name}).flac")
instrumental_path = os.path.join(track_output_dir, f"{artist_title} (Instrumental {self.model_name}).{self.output_format}")
vocals_path = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name}).{self.output_format}")
if os.path.isfile(instrumental_path) and os.path.isfile(vocals_path):
self.logger.debug(f"Separated audio files already exist in output paths, skipping separation: {instrumental_path}")
@@ -225,8 +299,8 @@ class KaraokePrep:
processed_track["instrumental_audio"] = instrumental_path
processed_track["vocals_audio"] = vocals_path
instrumental_path_2 = os.path.join(track_output_dir, f"{artist_title} (Instrumental {self.model_name_2}).flac")
vocals_path_2 = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name_2}).flac")
instrumental_path_2 = os.path.join(track_output_dir, f"{artist_title} (Instrumental {self.model_name_2}).{self.output_format}")
vocals_path_2 = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name_2}).{self.output_format}")
if os.path.isfile(instrumental_path_2) and os.path.isfile(vocals_path_2):
self.logger.debug(f"Separated audio files already exist in output paths, skipping separation: {instrumental_path_2}")
+24 -11
View File
@@ -17,9 +17,9 @@ def main():
formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=50),
)
parser.add_argument("artist", nargs="?", help="Artist name for the song to prep.", default=argparse.SUPPRESS)
parser.add_argument("title", nargs="?", help="Title of the song to prep.", default=argparse.SUPPRESS)
parser.add_argument("url", nargs="?", help="YouTube URL of the song to prep.", default=None)
parser.add_argument("artist", nargs="?", help="Artist name for the song to prep.", default=None)
parser.add_argument("title", nargs="?", help="Title of the song to prep.", default=None)
package_version = pkg_resources.get_distribution("karaoke-prep").version
parser.add_argument("-v", "--version", action="version", version=f"%(prog)s {package_version}")
@@ -44,8 +44,14 @@ def main():
parser.add_argument(
"--output_dir",
default="karaoke",
help="Optional: directory to write output files (default: <current dir>/karaoke). Example: --output_dir=/app/karaoke",
default=".",
help="Optional: directory to write output files (default: <current dir>). Example: --output_dir=/app/karaoke",
)
parser.add_argument(
"--output_format",
default="MP3",
help="Optional: output format for separated audio (default: MP3). Example: --output_format=FLAC",
)
parser.add_argument(
@@ -75,9 +81,9 @@ def main():
)
parser.add_argument(
"--create_track_subfolders",
action="store_true",
help="Optional: create subfolders in the output folder for each track (default: %(default)s). Example: --create_track_subfolders=true",
"--no_track_subfolders",
action="store_false",
help="Optional: do NOT create a named subfolder for each track. Example: --no_track_subfolders",
)
args = parser.parse_args()
@@ -86,10 +92,14 @@ def main():
logger.setLevel(log_level)
if not hasattr(args, "artist") or not hasattr(args, "title"):
parser.print_help()
exit(1)
if not args.url:
parser.print_help()
exit(1)
else:
# Proceed with only URL
logger.info("Artist and title will be guessed from the provided URL.")
logger.info(f"KaraokePrep beginning with artist: {args.artist} and title: {args.title} and url: {args.url}")
logger.info(f"KaraokePrep beginning with url: {args.url} artist: {args.artist} and title: {args.title}")
kprep = KaraokePrep(
artist=args.artist,
@@ -100,11 +110,12 @@ def main():
model_name=args.model_name,
model_file_dir=args.model_file_dir,
output_dir=args.output_dir,
output_format=args.output_format,
use_cuda=args.use_cuda,
use_coreml=args.use_coreml,
normalization_enabled=args.normalize,
denoise_enabled=args.denoise,
create_track_subfolders=args.create_track_subfolders,
create_track_subfolders=args.no_track_subfolders,
)
track = kprep.prep()
@@ -113,7 +124,9 @@ def main():
logger.info(f"")
logger.info(f"Track: {track['artist']} - {track['title']}")
logger.info(f" YouTube Video: {track['youtube_video']}")
logger.info(f" YouTube Audio: {track['youtube_audio']}")
logger.info(f" YouTube Still Image: {track['youtube_still_image']}")
logger.info(f" Lyrics: {track['lyrics']}")
logger.info(f" Instrumental: {track['instrumental_audio']}")
logger.info(f" Vocals: {track['vocals_audio']}")
+2 -2
View File
@@ -1,7 +1,7 @@
[tool.poetry]
name = "karaoke-prep"
version = "0.1.3"
description = "Prepare for karaoke video creation, by downloading audio and lyrics for a specified song."
version = "0.3.0"
description = "Prepare for karaoke video creation, by downloading audio and lyrics for a specified song or youtube playlist and separatung audio stems."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"
readme = "README.md"