Compare commits

..
1 Commits
5 changed files with 292 additions and 53 deletions

No files matched your search

+183 -31
View File
@@ -1,7 +1,11 @@
import os
import sys
import subprocess
import tempfile
import logging
import zipfile
import shutil
import re
class KaraokeFinalise:
@@ -9,7 +13,14 @@ class KaraokeFinalise:
self,
log_level=logging.DEBUG,
log_formatter=None,
dry_run=False,
force=False,
model_name="UVR_MDXNET_KARA_2",
instrumental_format="flac",
brand_prefix=None,
target_dir=None,
public_share_dir=None,
rclone_destination=None,
):
self.logger = logging.getLogger(__name__)
self.logger.setLevel(log_level)
@@ -24,7 +35,9 @@ class KaraokeFinalise:
self.log_handler.setFormatter(self.log_formatter)
self.logger.addHandler(self.log_handler)
self.logger.debug(f"KaraokeFinalise instantiating")
self.logger.debug(
f"KaraokeFinalise instantiating, dry_run: {dry_run}, model_name: {model_name}, force: {force}, brand_prefix: {brand_prefix}, target_dir: {target_dir}, public_share_dir: {public_share_dir}, rclone_destination: {rclone_destination}"
)
# Path to the Windows PyInstaller frozen bundled ffmpeg.exe, or the system-installed FFmpeg binary on Mac/Linux
ffmpeg_path = os.path.join(sys._MEIPASS, "ffmpeg.exe") if getattr(sys, "frozen", False) else "ffmpeg"
@@ -36,57 +49,196 @@ class KaraokeFinalise:
else:
self.ffmpeg_base_command += " -loglevel fatal"
self.dry_run = dry_run
self.force = force
self.model_name = model_name
self.instrumental_format = instrumental_format
self.brand_prefix = brand_prefix
self.target_dir = target_dir
self.public_share_dir = public_share_dir
self.rclone_destination = rclone_destination
def get_next_sequence_number(self):
"""
Calculate the next sequence number based on existing directories in the target_dir.
Assumes directories are named with the format: BRAND-XXXX Artist - Title
"""
max_num = 0
pattern = re.compile(rf"^{re.escape(self.brand_prefix)}-(\d{{4}})")
if not os.path.isdir(self.target_dir):
self.logger.error(f"Target directory does not exist: {self.target_dir}")
return None
for dir_name in os.listdir(self.target_dir):
match = pattern.match(dir_name)
if match:
num = int(match.group(1))
max_num = max(max_num, num)
self.logger.info(f"Next sequence number for brand {self.brand_prefix} calculated as: {max_num + 1}")
return max_num + 1
def process(self):
tracks = []
self.logger.info(f"Searching for files in current directory ending with (Karaoke).mov")
for karaoke_file in filter(lambda f: " (Karaoke).mov" in f, os.listdir(".")):
base_name = karaoke_file.replace(" (Karaoke).mov", "")
if self.dry_run:
self.logger.info("Dry run enabled. No actions will be performed.")
self.logger.info(f"Searching for files in current directory ending with (With Vocals).mov")
for with_vocals_file in filter(lambda f: " (With Vocals).mov" in f, os.listdir(".")):
base_name = with_vocals_file.replace(" (With Vocals).mov", "")
artist = base_name.split(" - ")[0]
title = base_name.split(" - ")[1]
with_vocals_file = f"{base_name} (With Vocals).mov"
# Input files which should already exist after karaoke-prep and manual production process
title_file = f"{base_name} (Title).mov"
instrumental_file = f"{base_name} (Instrumental {self.model_name}).mp3"
instrumental_file = f"{base_name} (Instrumental {self.model_name}).{self.instrumental_format}"
cdg_file = f"{base_name} (Karaoke).cdg"
mp3_file = f"{base_name} (Karaoke).mp3"
# Output files which will be created by this script
karaoke_mov_file = f"{base_name} (Karaoke).mov"
final_mp4_file = f"{base_name} (Final Karaoke).mp4"
final_zip_file = f"{base_name} (Final Karaoke).zip"
track = {
"artist": artist,
"title": title,
"video_with_vocals": with_vocals_file,
"video_with_instrumental": karaoke_file,
"final_video": final_mp4_file,
}
if os.path.isfile(karaoke_mov_file) and not self.force:
self.logger.error(
f"Karaoke MOV file with instrumental audio already exists: {karaoke_mov_file}. Use --force parameter to override."
)
return []
if os.path.isfile(title_file) and os.path.isfile(karaoke_file) and os.path.isfile(instrumental_file):
self.logger.info(f"All 3 input files found for {base_name}, beginning finalisation")
if os.path.isfile(final_mp4_file) and not self.force:
self.logger.error(f"Final MP4 file already exists: {final_mp4_file}. Use --force parameter to override.")
return []
self.logger.info(f"Output [With Vocals]: renaming synced video to: {with_vocals_file}")
os.rename(karaoke_file, with_vocals_file)
if not os.path.isfile(title_file):
self.logger.error(f"Title file not found: {title_file}")
return []
self.logger.info(f"Output [With Instrumental]: remuxing synced video with instrumental audio to: {karaoke_file}")
if not os.path.isfile(with_vocals_file):
self.logger.error(f"With Vocals file not found: {with_vocals_file}")
return []
ffmpeg_command = f'{self.ffmpeg_base_command} -an -i "{with_vocals_file}" -vn -i "{instrumental_file}" -c:v copy -c:a aac "{karaoke_file}"'
self.logger.debug(f"Running command: {ffmpeg_command}")
os.system(ffmpeg_command)
if not os.path.isfile(instrumental_file):
self.logger.error(f"Instrumental file not found: {instrumental_file}")
return []
self.logger.info(f"Output [Final Karaoke]: joining title video and instrumental video to produce: {final_mp4_file}")
if not os.path.isfile(cdg_file):
self.logger.error(f"CDG file not found: {cdg_file}")
return []
with tempfile.NamedTemporaryFile(mode="w+", delete=False, dir="/tmp", suffix=".txt") as tmp_file_list:
tmp_file_list.write(f"file '{os.path.abspath(title_file)}'\n")
tmp_file_list.write(f"file '{os.path.abspath(karaoke_file)}'\n")
if not os.path.isfile(mp3_file):
self.logger.error(f"MP3 file not found: {mp3_file}")
return []
ffmpeg_command = f'{self.ffmpeg_base_command} -f concat -safe 0 -i "{tmp_file_list.name}" -vf settb=AVTB,setpts=N/30/TB,fps=30 "{final_mp4_file}"'
self.logger.debug(f"Running command: {ffmpeg_command}")
os.system(ffmpeg_command)
self.logger.info(
f"All 5 input files (Title MOV, With Vocals MOV, Instrumental {self.instrumental_format}, CDG, MP3) found for {base_name}, beginning finalisation"
)
os.remove(tmp_file_list.name)
# Remux the synced video with the instrumental audio to produce an instrumental karaoke MOV file
self.logger.info(f"Output [With Instrumental]: remuxing synced video with instrumental audio to: {karaoke_mov_file}")
remux_ffmpeg_command = f'{self.ffmpeg_base_command} -an -i "{with_vocals_file}" -vn -i "{instrumental_file}" -c:v copy -c:a aac "{karaoke_mov_file}"'
if self.dry_run:
self.logger.info(f"DRY RUN: Would run command: {remux_ffmpeg_command}")
else:
self.logger.error(f"Unable to find all 3 required input files:\n {title_file}\n {karaoke_file}\n {instrumental_file}")
self.logger.info(f"Running command: {remux_ffmpeg_command}")
os.system(remux_ffmpeg_command)
tracks.append(track)
# Join the title video and the karaoke video and reencode with fixed 30 FPS to produce the final MP4
self.logger.info(f"Output [Final Karaoke]: joining title video and instrumental video to produce: {final_mp4_file}")
with tempfile.NamedTemporaryFile(mode="w+", delete=False, dir="/tmp", suffix=".txt") as tmp_file_list:
tmp_file_list.write(f"file '{os.path.abspath(title_file)}'\n")
tmp_file_list.write(f"file '{os.path.abspath(karaoke_mov_file)}'\n")
join_ffmpeg_command = f'{self.ffmpeg_base_command} -f concat -safe 0 -i "{tmp_file_list.name}" -vf settb=AVTB,setpts=N/30/TB,fps=30 "{final_mp4_file}"'
if self.dry_run:
self.logger.info(f"DRY RUN: Would run command: {join_ffmpeg_command}")
else:
self.logger.info(f"Running command: {join_ffmpeg_command}")
os.system(join_ffmpeg_command)
os.remove(tmp_file_list.name)
# Create the ZIP file containing the MP3 and CDG files
if self.dry_run:
self.logger.info(f"DRY RUN: Would create ZIP file: {final_zip_file}")
else:
self.logger.info(f"Creating ZIP file containing {mp3_file} and {cdg_file}")
with zipfile.ZipFile(final_zip_file, "w") as zipf:
zipf.write(mp3_file, os.path.basename(mp3_file))
zipf.write(cdg_file, os.path.basename(cdg_file))
self.logger.info(f"ZIP file created: {final_zip_file}")
# Create new folder in target folder and move all files to it
new_track_prefix = None
new_dir_path = None
if self.brand_prefix is not None and self.target_dir is not None:
next_num = self.get_next_sequence_number()
new_track_prefix = f"{self.brand_prefix}-{next_num:04d}"
new_dir_name = f"{new_track_prefix} {artist} - {title}"
new_dir_path = os.path.join(self.target_dir, new_dir_name)
if self.dry_run:
self.logger.info(f"DRY RUN: Would create new folder and move files to: {new_dir_path}")
else:
if not os.path.exists(new_dir_path):
os.makedirs(new_dir_path)
for file in os.listdir("."):
src_file = os.path.join(".", file)
dest_file = os.path.join(new_dir_path, file)
shutil.move(src_file, dest_file)
self.logger.info(f"Moved all files to: {new_dir_path}")
else:
self.logger.info("brand_prefix or target_dir not specified, skipping move")
# Copy files to public share directory with brand prefix
if self.public_share_dir is not None and new_track_prefix is not None and new_dir_path is not None:
self.logger.info(f"public_share_dir specified, will rename and copy final files to public share directory")
src_mp4_file = os.path.join(new_dir_path, final_mp4_file)
src_zip_file = os.path.join(new_dir_path, final_zip_file)
dest_mp4_file = os.path.join(self.public_share_dir, f"{new_track_prefix} {base_name} (Karaoke).mp4")
dest_zip_file = os.path.join(self.public_share_dir, f"{new_track_prefix} {base_name} (Karaoke).zip")
if self.dry_run:
self.logger.info(f"DRY RUN: Would copy {src_mp4_file} to {dest_mp4_file}")
self.logger.info(f"DRY RUN: Would copy {src_zip_file} to {dest_zip_file}")
else:
shutil.copy2(src_mp4_file, dest_mp4_file)
shutil.copy2(src_zip_file, dest_zip_file)
self.logger.info(f"Final files copied to public share directory: {dest_mp4_file}, {dest_zip_file}")
else:
self.logger.info(f"public_share_dir or new_track_prefix not specified, skipping copy to shared dir")
# Sync with various cloud destinations using rclone
if self.rclone_destination is not None and self.public_share_dir is not None:
rclone_cmd = ["rclone", "sync", "-v", self.public_share_dir, self.rclone_destination]
if self.dry_run:
self.logger.info(f"DRY RUN: Would sync {self.public_share_dir} to {self.rclone_destination} using rclone")
else:
self.logger.info(f"Running command: {rclone_cmd}")
subprocess.run(rclone_cmd)
else:
self.logger.info(f"rclone_destination or public_share_dir not specified, skipping sync")
# Add track to list of processed tracks now we've created all of the new output files
tracks.append(
{
"artist": artist,
"title": title,
"video_with_vocals": with_vocals_file,
"video_with_instrumental": karaoke_mov_file,
"final_video": final_mp4_file,
"final_zip": final_zip_file,
}
)
return tracks
+53 -16
View File
@@ -22,7 +22,8 @@ class KaraokePrep:
model_name_2="UVR-MDX-NET-Inst_HQ_3",
model_file_dir=os.path.join(tempfile.gettempdir(), "audio-separator-models"),
output_dir=".",
output_format="WAV",
lossless_output_format="FLAC",
lossy_output_format="MP3",
use_cuda=False,
use_coreml=False,
normalization_enabled=True,
@@ -56,7 +57,8 @@ 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.lossless_output_format = lossless_output_format.lower()
self.lossy_output_format = lossy_output_format.lower()
self.use_cuda = use_cuda
self.use_coreml = use_coreml
self.normalization_enabled = normalization_enabled
@@ -83,7 +85,7 @@ class KaraokePrep:
self.persistent_artist = None
self.logger.debug(f"KaraokePrep output_format: {self.output_format}")
self.logger.debug(f"KaraokePrep lossless_output_format: {self.lossless_output_format}")
if not os.path.exists(self.output_dir):
self.logger.debug(f"Overall output dir {self.output_dir} did not exist, creating")
@@ -234,9 +236,9 @@ class KaraokePrep:
comma_indices = [i for i, char in enumerate(line) if char == ","]
for index in comma_indices:
if abs(mid_point - index) < 20: # Roughly the length of two average words
if abs(mid_point - index) < 20 and len(line[: index + 1].strip()) <= 36:
self.logger.debug(
f"Found comma at index {index} which is within 20 characters of mid_point {mid_point}, accepting as split point"
f"Found comma at index {index} which is within 20 characters of mid_point {mid_point} and results in a suitable line length, accepting as split point"
)
return index + 1 # Include the comma in the first line
@@ -244,9 +246,10 @@ class KaraokePrep:
if " and " in line:
mid_point = len(line) // 2
and_indices = [m.start() for m in re.finditer(" and ", line)]
split_point = min(and_indices, key=lambda x: abs(x - mid_point))
self.logger.debug(f"Found 'and' at index {split_point} which is close to mid_point {mid_point}, accepting as split point")
return split_point + len(" and ") # Include 'and' in the first line
for index in sorted(and_indices, key=lambda x: abs(x - mid_point)):
if len(line[: index + len(" and ")].strip()) <= 36:
self.logger.debug(f"Found 'and' at index {index} which results in a suitable line length, accepting as split point")
return index + len(" and ")
# Split at the middle word
self.logger.debug(f"No comma or suitable 'and' found, using middle word as split point")
@@ -281,7 +284,7 @@ class KaraokePrep:
return processed_lines
def write_processed_lyrics(self, lyrics, processed_lyrics_file):
self.logger.debug(f"Writing processed lyrics to {processed_lyrics_file}")
self.logger.info(f"Writing processed lyrics to {processed_lyrics_file}")
with open(processed_lyrics_file, "w") as outfile:
all_processed = False
@@ -316,7 +319,7 @@ class KaraokePrep:
self.logger.debug(f"audio_file is valid file: {audio_file}")
self.logger.debug(
f"instantiating Separator with model_name: {model_name} instrumental_path: {instrumental_path} and output_format: {self.output_format}"
f"instantiating Separator with model_name: {model_name} instrumental_path: {instrumental_path} and lossless_output_format: {self.lossless_output_format}"
)
from audio_separator.separator import Separator
@@ -325,7 +328,7 @@ class KaraokePrep:
log_level=self.log_level,
log_formatter=self.log_formatter,
model_file_dir=self.model_file_dir,
output_format=self.output_format,
output_format=self.lossless_output_format,
primary_stem_path=instrumental_path,
secondary_stem_path=vocals_path,
)
@@ -491,7 +494,7 @@ class KaraokePrep:
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")
self.logger.info(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.")
@@ -519,32 +522,66 @@ 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}).{self.output_format}")
vocals_path = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name}).{self.output_format}")
instrumental_path = os.path.join(track_output_dir, f"{artist_title} (Instrumental {self.model_name}).{self.lossless_output_format}")
vocals_path = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name}).{self.lossless_output_format}")
instrumental_path_lossy = os.path.join(
track_output_dir, f"{artist_title} (Instrumental {self.model_name}).{self.lossy_output_format}"
)
vocals_path_lossy = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name}).{self.lossy_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}")
else:
self.separate_audio(processed_track["youtube_audio"], self.model_name, instrumental_path, vocals_path)
self.convert_to_lossy(instrumental_path, instrumental_path_lossy)
self.convert_to_lossy(vocals_path, vocals_path_lossy)
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}).{self.output_format}")
vocals_path_2 = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name_2}).{self.output_format}")
processed_track["instrumental_audio_lossy"] = instrumental_path_lossy
processed_track["vocals_audio_lossy"] = vocals_path_lossy
instrumental_path_2 = os.path.join(
track_output_dir, f"{artist_title} (Instrumental {self.model_name_2}).{self.lossless_output_format}"
)
vocals_path_2 = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name_2}).{self.lossless_output_format}")
instrumental_path_2_lossy = os.path.join(
track_output_dir, f"{artist_title} (Instrumental {self.model_name_2}).{self.lossy_output_format}"
)
vocals_path_2_lossy = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name_2}).{self.lossy_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}")
else:
self.separate_audio(processed_track["youtube_audio"], self.model_name_2, instrumental_path_2, vocals_path_2)
self.convert_to_lossy(instrumental_path_2, instrumental_path_2_lossy)
self.convert_to_lossy(vocals_path_2, vocals_path_2_lossy)
processed_track["instrumental_audio_2"] = instrumental_path_2
processed_track["vocals_audio_2"] = vocals_path_2
processed_track["instrumental_audio_2_lossy"] = instrumental_path_2_lossy
processed_track["vocals_audio_2_lossy"] = vocals_path_2_lossy
self.logger.info("Script finished, audio downloaded, lyrics fetched and audio separated!")
return processed_track
def convert_to_lossy(self, input_filename, output_filename):
if input_filename is None or not os.path.isfile(input_filename):
raise Exception(f"Error: Invalid input file provided for convert_to_lossy: {input_filename}")
self.logger.info(f"Converting {self.lossless_output_format} audio to lossy {self.lossy_output_format} format")
ffmpeg_extras = "-q:a 0" if self.lossy_output_format == "mp3" else ""
ffmpeg_command = f'{self.ffmpeg_base_command} -i "{input_filename}" {ffmpeg_extras} "{output_filename}"'
self.logger.debug(f"Running command: {ffmpeg_command}")
os.system(ffmpeg_command)
def is_playlist_url(self):
"""
Checks if the provided URL is a YouTube playlist URL.
+44 -1
View File
@@ -26,12 +26,48 @@ def main():
help="Optional: logging level, e.g. info, debug, warning (default: %(default)s). Example: --log_level=debug",
)
parser.add_argument(
"--dry_run",
action="store_true",
help="Optional: Enable dry run mode to print actions without executing them (default: disabled). Example: --dry_run",
)
parser.add_argument(
"--force",
action="store_true",
help="Optional: Force processing even if final output file exists (default: disabled). Example: --force",
)
parser.add_argument(
"--model_name",
default="UVR_MDXNET_KARA_2",
help="Optional: model name to be used for separation (default: %(default)s). Example: --model_name=UVR-MDX-NET-Inst_HQ_3",
)
parser.add_argument(
"--brand_prefix",
default=None,
help="Optional: Your brand prefix to calculate the next sequential number and move the resulting folder. Example: --brand_prefix=BRAND",
)
parser.add_argument(
"--target_dir",
default=None,
help="Optional: Target directory where the processed folder will be moved after finalisation. Example: --target_dir='/path/to/Tracks-Organized'",
)
parser.add_argument(
"--public_share_dir",
default=None,
help="Optional: Public share directory where final MP4 and ZIP files will be copied. Example: --public_share_dir='/path/to/Tracks-PublicShare'",
)
parser.add_argument(
"--rclone_destination",
default=None,
help="Optional: Rclone destination to sync your public_share_dir to after adding files to it. Example: --rclone_destination='googledrive:YourBrandNameFolder'",
)
args = parser.parse_args()
log_level = getattr(logging, args.log_level.upper())
@@ -42,7 +78,13 @@ def main():
kfinalise = KaraokeFinalise(
log_formatter=log_formatter,
log_level=log_level,
dry_run=args.dry_run,
force=args.force,
model_name=args.model_name,
brand_prefix=args.brand_prefix,
target_dir=args.target_dir,
public_share_dir=args.public_share_dir,
rclone_destination=args.rclone_destination,
)
tracks = kfinalise.process()
@@ -57,7 +99,8 @@ def main():
logger.info(f"Track: {track['artist']} - {track['title']}")
logger.info(f" Video With Vocals: {track['video_with_vocals']}")
logger.info(f" Video With Instrumental: {track['video_with_instrumental']}")
logger.info(f" Final Video with Title: {track['final_video']}")
logger.info(f" Final CDG+MP3 ZIP: {track['final_video']}")
logger.info(f" Final Video with Title: {track['final_zip']}")
if __name__ == "__main__":
+11 -4
View File
@@ -60,9 +60,15 @@ def main():
)
parser.add_argument(
"--output_format",
default="mp3",
help="Optional: output format for separated audio (default: mp3). Example: --output_format=flac",
"--lossless_output_format",
default="FLAC",
help="Optional: lossless output format for separated audio (default: FLAC). Example: --lossless_output_format=WAV",
)
parser.add_argument(
"--lossy_output_format",
default="MP3",
help="Optional: lossy output format for separated audio (default: MP3). Example: --lossy_output_format=OGG",
)
parser.add_argument(
@@ -166,7 +172,8 @@ def main():
model_name=args.model_name,
model_file_dir=args.model_file_dir,
output_dir=args.output_dir,
output_format=args.output_format,
lossless_output_format=args.lossless_output_format,
lossy_output_format=args.lossy_output_format,
use_cuda=args.use_cuda,
use_coreml=args.use_coreml,
normalization_enabled=args.normalize,
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-prep"
version = "0.9.1"
version = "0.9.2"
description = "Prepare for karaoke video creation, by downloading audio and lyrics for a specified song or playlist from youtube and separating audio stems. After syncing, finalise the video with a title screen!"
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"