Compare commits

...
7 Commits
8 changed files with 376 additions and 64 deletions

No files matched your search

+76 -16
View File
@@ -17,6 +17,7 @@ This was created to make it easier for me to prepare the source audio, lyrics an
- Internet First: Completes operations which require internet first, in case user is preparing last-minute before a period of being offline!
- Flexible Input: provide just a YouTube URL, just an artist and title, or both.
- Playlist Processing: Capable of processing an entire YouTube playlist, extracting audio and lyrics for each track.
- Easy Finalisation: After manually performing your sync (e.g. using [MidiCo](https://www.midicokaraoke.com)), run `karaoke-finalise` to remux and add your title screen!
## Installation 🛠️
@@ -24,6 +25,26 @@ You can install Karaoke Prep using pip:
`pip install karaoke-prep`
If you aren't sure what `pip` is or how to use the command line, here are some YouTube tutorials which will probably help:
- Install Python on Windows: https://www.youtube.com/watch?v=YKSpANU8jPE
- Command Line basics Windows: https://www.youtube.com/watch?v=MBBWVgE0ewk
- Install Python on Mac: https://www.youtube.com/watch?v=3-sPfR4JEQ8
- Command Line basics Mac: https://www.youtube.com/watch?v=FfT8OfMpARM
## Karaoke production guide using karaoke-prep and MidiCo
- Run `karaoke-prep <Artist> <Title>` to fetch and prep the files above
- Wait for it to output at least the WAV file and lyrics (you can leave it running in the background while you sync)
- Open the WAV file in MidiCo: `(YouTube xxxxxxxxxxx).wav`
- Copy/paste the lyrics into MidiCo: `(Lyrics Processed).txt`
- Perform the lyrics sync (here's a [video](https://www.youtube.com/watch?v=63-Fk3mfZ7Q) showing me doing it) in MidiCo
- Render the video to 4k using the MidiCo "Export Movie" feature, saving it as `Artist - Title (Karaoke).mov` in the same folder
- Run `karaoke-finalise` to remux the instrumental audio and join the title clip to the start
- Upload the resulting `Artist - Title (Final Karaoke).mp4` video to YouTube!
Here's my [tutorial video with verbal explanation](https://www.youtube.com/watch?v=ZsROHgqAVHs) of the whole process, and here's a [normal speed demo](https://www.youtube.com/watch?v=63-Fk3mfZ7Q) of me doing it (8 minutes total for a single track).
## Usage 🚀
@@ -61,13 +82,12 @@ options:
```
### Only YouTube URL
### ⭐ YouTube URL with Artist and Title
This will process the video at the given URL, *guessing the artist and title from the YouTube title*.
⚠️ Be aware the downloaded lyrics may be incorrect if the video title doesn't match the standard "Artist - Title" format.
For the most consistent results, provide a specific YouTube URL along with the artist and title like so:
```
karaoke-prep "https://www.youtube.com/watch?v=YOUR_VIDEO_ID"
karaoke-prep "https://www.youtube.com/watch?v=YOUR_VIDEO_ID" "The Fray" "Never Say Never"
```
### Artist and Title Only
@@ -78,12 +98,13 @@ If you don't have a specific YouTube URL, just provide the artist and title. Kar
karaoke-prep "The Fray" "Never Say Never"
```
### ⭐ YouTube URL with Artist and Title
### Only YouTube URL
For more precise control (and most consistent results), provide the YouTube URL along with the artist and title to avoid any guesswork.
This will process the video at the given URL, *guessing the artist and title from the YouTube title*.
⚠️ Be aware the downloaded lyrics may be incorrect if the video title doesn't match the standard "Artist - Title" format.
```
karaoke-prep "https://www.youtube.com/watch?v=YOUR_VIDEO_ID" "The Fray" "Never Say Never"
karaoke-prep "https://www.youtube.com/watch?v=YOUR_VIDEO_ID"
```
### YouTube Playlist URL
@@ -95,16 +116,55 @@ To process a playlist, just provide the playlist URL. The script will process ev
karaoke-prep "https://www.youtube.com/playlist?list=YOUR_PLAYLIST_ID"
```
By default, you'll end up with files in the current folder, neatly organised into folders for each track and files named consistently e.g.
## Files produced by karaoke-prep and what to do with them
After running `karaoke-prep` you should have the following 11 files, grouped into folder(s) for each track:
- `Artist - Title (YouTube xxxxxxxxxxx).webm`
- Original unmodified video, fetched from YouTube in the highest quality available
- You probably don't need this unless you're creating a custom request
- `Artist - Title (YouTube xxxxxxxxxxx).png`
- A still image taken from 30 seconds into the video, in case that's useful for a custom background
- You probably don't need this unless you're creating a custom request
- `Artist - Title (YouTube xxxxxxxxxxx).wav`
- Unmodified audio from the YouTube video, converted to WAV format for compatibility
- You should open this in MidiCo to begin syncing lyrics to make your karaoke video.
- `Artist - Title (Lyrics).txt`
- Unmodified lyrics fetched from genius.com based on the artist/title provided
- Depending on the song, may have lines which are too long for one karaoke screen
- `Artist - Title (Lyrics Processed).txt`
- Lyrics from genius, split into lines no longer than 40 characters
- You should open this and copy/paste the text into the MidiCo lyrics editor
- `Artist - Title (Vocals UVR-MDX-NET-Inst_HQ_3).mp3`
- Vocal track from the audio, separated using the UVR Inst_HQ_3 model.
- You probably don't need this unless you're trying to tweak the backing track
- `Artist - Title (Vocals UVR_MDXNET_KARA_2).mp3`
- Vocal track from the audio, separated using the UVR KARA_2 model.
- You probably don't need this unless you're trying to tweak the backing track
- `Artist - Title (Instrumental UVR-MDX-NET-Inst_HQ_3).mp3`
- Instrumental track from the audio, separated using the UVR Inst_HQ_3 model.
- This is typically a safe bet for the instrumental track but will not include any backing vocals.
- `Artist - Title (Instrumental UVR_MDXNET_KARA_2).mp3`
- Instrumental track from the audio, separated using the UVR KARA_2 model.
- This is the default choice for the finalisation step below as it usually does a good job of keeping backing vocals. However for some songs it includes far too much or is kinda glitchy, so you should check it before finalising and make a judgement call about using this vs. the Inst_HQ_3 one.
- `Artist - Title (Title).png`
- Title screen static image; if you specify your own background image, font, color etc. this should give you a convenient way to add a title screen to the start of your video.
- `Artist - Title (Title).mov`
- 5 second video clip version of the title screen image, ready to be joined by the finalisation step.
## Finalisation 🎥
After completing your manual sync process and rendering your `Artist - Title (Karaoke).mov` file (still using the original audio!) into the same folder, you can now run `karaoke-finalise`.
This will output some additional files:
- `Artist - Title (Karaoke).mov`
- Karaoke video without title screen, remuxed to use the instrumental audio
- `Artist - Title (With Vocals).mov`
- Karaoke video without title screen, using the original audio (useful for practicing!)
- `Artist - Title (Final Karaoke).mp4`
- Final karaoke video with 5 second title screen intro, instrumental audio and converted to MP4 for compatibility and reduced file size. Upload this to YouTube!
```
├── Artist - Title (Instrumental UVR-MDX-NET-Inst_HQ_3).flac
├── Artist - Title (Instrumental UVR_MDXNET_KARA_2).flac
├── Artist - Title (Lyrics).txt
├── Artist - Title (Vocals UVR-MDX-NET-Inst_HQ_3).flac
├── Artist - Title (Vocals UVR_MDXNET_KARA_2).flac
└── Artist - Title (YouTube CNUgemJBLTw).wav
```
## Requirements 📋
+1
View File
@@ -0,0 +1 @@
from .karaoke_finalise import KaraokeFinalise
+89
View File
@@ -0,0 +1,89 @@
import os
import subprocess
import tempfile
import logging
class KaraokeFinalise:
def __init__(
self,
log_level=logging.DEBUG,
log_formatter=None,
model_name="UVR_MDXNET_KARA_2",
):
self.logger = logging.getLogger(__name__)
self.logger.setLevel(log_level)
self.log_level = log_level
self.log_formatter = log_formatter
self.log_handler = logging.StreamHandler()
if self.log_formatter is None:
self.log_formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(module)s - %(message)s")
self.log_handler.setFormatter(self.log_formatter)
self.logger.addHandler(self.log_handler)
self.logger.debug(f"KaraokeFinalise instantiating")
self.ffmpeg_base_command = "ffmpeg -hide_banner -nostats"
if self.log_level == logging.DEBUG:
self.ffmpeg_base_command += " -loglevel verbose"
else:
self.ffmpeg_base_command += " -loglevel fatal"
self.model_name = model_name
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", "")
artist = base_name.split(" - ")[0]
title = base_name.split(" - ")[1]
with_vocals_file = f"{base_name} (With Vocals).mov"
title_file = f"{base_name} (Title).mov"
instrumental_file = f"{base_name} (Instrumental {self.model_name}).mp3"
final_mp4_file = f"{base_name} (Final Karaoke).mp4"
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(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")
self.logger.info(f"Output [With Vocals]: renaming synced video to: {with_vocals_file}")
os.rename(karaoke_file, with_vocals_file)
self.logger.info(f"Output [With Instrumental]: remuxing synced video with instrumental audio to: {karaoke_file}")
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)
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_file)}'\n")
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)
os.remove(tmp_file_list.name)
else:
self.logger.error(f"Unable to find all 3 required input files:\n {title_file}\n {karaoke_file}\n {instrumental_file}")
tracks.append(track)
return tracks
+133 -41
View File
@@ -4,7 +4,7 @@ import glob
import yt_dlp
import logging
import lyricsgenius
import subprocess
import tempfile
from PIL import Image, ImageDraw, ImageFont
@@ -18,7 +18,7 @@ class KaraokePrep:
log_formatter=None,
model_name="UVR_MDXNET_KARA_2",
model_name_2="UVR-MDX-NET-Inst_HQ_3",
model_file_dir="/tmp/audio-separator-models/",
model_file_dir=os.path.join(tempfile.gettempdir(), "audio-separator-models"),
output_dir=".",
output_format="WAV",
use_cuda=False,
@@ -61,6 +61,13 @@ class KaraokePrep:
self.denoise_enabled = denoise_enabled
self.create_track_subfolders = create_track_subfolders
self.ffmpeg_base_command = "ffmpeg -hide_banner -nostats"
if self.log_level == logging.DEBUG:
self.ffmpeg_base_command += " -loglevel verbose"
else:
self.ffmpeg_base_command += " -loglevel fatal"
self.title_format = {
"background_color": intro_background_color,
"background_image": intro_background_image,
@@ -71,7 +78,7 @@ class KaraokePrep:
}
self.persistent_artist = None
self.logger.debug(f"KaraokePrep output_format: {self.output_format}")
if not os.path.exists(self.output_dir):
@@ -138,6 +145,7 @@ class KaraokePrep:
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 = {
"quiet": "True",
"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",
@@ -151,18 +159,22 @@ class KaraokePrep:
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}"')
self.logger.info(f"Extracting still image from position 30s YouTube video")
ffmpeg_command = f'{self.ffmpeg_base_command} -i "{input_filename}" -ss 00:00:30 -vframes 1 "{output_filename}"'
self.logger.debug(f"Running command: {ffmpeg_command}")
os.system(ffmpeg_command)
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}"')
self.logger.info(f"Converting input video to audio WAV file")
ffmpeg_command = f'{self.ffmpeg_base_command} -i "{input_filename}" "{output_filename}"'
self.logger.debug(f"Running command: {ffmpeg_command}")
os.system(ffmpeg_command)
return output_filename
def write_lyrics_from_genius(self, artist, title, filename):
genius = lyricsgenius.Genius(os.environ["GENIUS_API_TOKEN"])
genius = lyricsgenius.Genius(access_token=os.environ["GENIUS_API_TOKEN"], verbose=False, remove_section_headers=True)
song = genius.search_song(title, artist)
if song:
lyrics = self.clean_genius_lyrics(song.lyrics)
@@ -171,6 +183,7 @@ class KaraokePrep:
f.write(lyrics)
self.logger.info("Lyrics for %s by %s fetched successfully", title, artist)
return lyrics.split("\n")
else:
self.logger.warning("Could not find lyrics for %s by %s", title, artist)
@@ -180,6 +193,10 @@ class KaraokePrep:
lyrics = re.sub(
r".*?Lyrics([A-Z])", r"\1", lyrics
) # Remove the song name and word "Lyrics" if this has a non-newline char at the start
lyrics = re.sub(r"^[0-9]* Contributors.*Lyrics", "", lyrics) # Remove this example: 27 ContributorsSex Bomb Lyrics
lyrics = re.sub(
r"See.*Live.*Get tickets as low as \$[0-9]+", "", lyrics
) # Remove this example: See Tom Jones LiveGet tickets as low as $71
lyrics = re.sub(r"[0-9]+Embed$", "", lyrics) # Remove the word "Embed" at end of line with preceding numbers if found
lyrics = re.sub(r"(\S)Embed$", r"\1", lyrics) # Remove the word "Embed" if it has been tacked onto a word at the end of a line
lyrics = re.sub(r"^Embed$", r"", lyrics) # Remove the word "Embed" if it has been tacked onto a word at the end of a line
@@ -187,6 +204,87 @@ class KaraokePrep:
# add any additional cleaning rules here
return lyrics
def find_best_split_point(self, line):
"""
Find the best split point in a line based on the specified criteria.
"""
self.logger.debug(f"Finding best_split_point for line: {line}")
words = line.split()
mid_word_index = len(words) // 2
# Check for a comma within one or two words of the middle word
if "," in line:
mid_point = len(" ".join(words[:mid_word_index]))
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
self.logger.debug(
f"Found comma at index {index} which is within 20 characters of mid_point {mid_point}, accepting as split point"
)
return index + 1 # Include the comma in the first line
# Check for 'and'
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
# Split at the middle word
self.logger.debug(f"No comma or suitable 'and' found, using middle word as split point")
return len(" ".join(words[:mid_word_index]))
def process_line(self, line):
"""
Process a single line to ensure it's within the maximum length,
and handle parentheses.
"""
processed_lines = []
while len(line) > 36:
# Check if the line contains parentheses
if "(" in line and ")" in line:
start_paren = line.find("(")
end_paren = line.find(")") + 1
if end_paren < len(line) and line[end_paren] == ",":
end_paren += 1
if start_paren > 0:
processed_lines.append(line[:start_paren].strip())
processed_lines.append(line[start_paren:end_paren].strip())
line = line[end_paren:].strip()
else:
split_point = self.find_best_split_point(line)
processed_lines.append(line[:split_point].strip())
line = line[split_point:].strip()
if line: # Add the remaining part if not empty
processed_lines.append(line)
return processed_lines
def write_processed_lyrics(self, lyrics, processed_lyrics_file):
self.logger.debug(f"Writing processed lyrics to {processed_lyrics_file}")
with open(processed_lyrics_file, "w") as outfile:
all_processed = False
while not all_processed:
all_processed = True
new_lyrics = []
for line in lyrics:
line = line.strip()
processed = self.process_line(line)
new_lyrics.extend(processed)
if any(len(l) > 36 for l in processed):
all_processed = False
lyrics = new_lyrics
# Write the processed lyrics to file
for line in lyrics:
outfile.write(line + "\n")
def sanitize_filename(self, filename):
"""Replace or remove characters that are unsafe for filenames."""
# Replace problematic characters with underscores
@@ -266,15 +364,16 @@ class KaraokePrep:
text_y = vertical_offset
return (text_x, text_y), text_height
def create_intro_video(self, artist, title, format, output_image_filepath, output_video_filepath):
def create_title_video(self, artist, title, format, output_image_filepath, output_video_filepath):
duration = 5 # Duration in seconds
resolution = (3840, 2160) # 4K resolution
# Load or create background image
if format["background_image"] and os.path.exists(format["background_image"]):
self.logger.debug(f"Title screen background image file found: {format['background_image']}")
self.logger.info(f"Using title screen background image file: {format['background_image']}")
background = Image.open(format["background_image"])
else:
self.logger.info(f"Using title screen background color: {format['background_color']}")
background = Image.new("RGB", resolution, color=self.hex_to_rgb(format["background_color"]))
# Resize background to match resolution
@@ -298,10 +397,12 @@ class KaraokePrep:
artist_font, _ = self.calculate_text_size_and_position(
draw, artist, format["artist_font"], initial_font_size, resolution, artist_padding
)
# Calculate vertical positions with consistent gap
title_text_position, title_height = self.calculate_text_position(draw, title, title_font, resolution, top_padding)
artist_text_position, _ = self.calculate_text_position(draw, artist, artist_font, resolution, title_text_position[1] + title_height + fixed_gap)
artist_text_position, _ = self.calculate_text_position(
draw, artist, artist_font, resolution, title_text_position[1] + title_height + fixed_gap
)
draw.text(title_text_position, title, fill=format["title_color"], font=title_font)
draw.text(artist_text_position, artist, fill=format["artist_color"], font=artist_font)
@@ -310,25 +411,12 @@ class KaraokePrep:
background.save(output_image_filepath)
# Use ffmpeg to create video
ffmpeg_command = [
"ffmpeg",
"-y",
"-loop",
"1",
"-i",
output_image_filepath,
"-c:v",
"libx264",
"-t",
str(duration),
"-pix_fmt",
"yuv420p",
"-vf",
f"scale={resolution[0]}:{resolution[1]}",
output_video_filepath,
]
ffmpeg_command = f'{self.ffmpeg_base_command} -y -loop 1 -framerate 30 -i "{output_image_filepath}" -f lavfi -i anullsrc '
ffmpeg_command += f'-c:v libx264 -r 30 -t {duration} -pix_fmt yuv420p -vf scale={resolution[0]}:{resolution[1]} -c:a aac -shortest "{output_video_filepath}"'
subprocess.run(ffmpeg_command)
self.logger.info("Generating title video...")
self.logger.debug(f"Running command: {ffmpeg_command}")
os.system(ffmpeg_command)
def hex_to_rgb(self, hex_color):
"""Convert hex color to RGB tuple."""
@@ -343,7 +431,7 @@ class KaraokePrep:
artist = self.artist
title = self.title
self.logger.info(f"Downloading inputs for track: {title} by {artist}")
self.logger.info(f"Preparing output path for track: {title} by {artist}")
track_output_dir, artist_title = self.setup_output_paths(artist, title)
processed_track = {
"track_output_dir": track_output_dir,
@@ -351,9 +439,22 @@ class KaraokePrep:
"title": title,
}
self.logger.info(f"Creating title video...")
processed_track["title_image"] = os.path.join(track_output_dir, f"{artist_title} (Title).png")
processed_track["title_video"] = os.path.join(track_output_dir, f"{artist_title} (Title).mov")
self.create_intro_video(artist, title, self.title_format, processed_track["title_image"], processed_track["title_video"])
self.create_title_video(artist, title, self.title_format, processed_track["title_image"], processed_track["title_video"])
lyrics_file = os.path.join(track_output_dir, f"{artist_title} (Lyrics).txt")
processed_lyrics_file = os.path.join(track_output_dir, f"{artist_title} (Lyrics Processed).txt")
if os.path.exists(lyrics_file):
self.logger.debug(f"Lyrics file already exists, skipping fetch: {lyrics_file}")
else:
self.logger.info("Fetching lyrics from Genius...")
lyrics = self.write_lyrics_from_genius(artist, title, lyrics_file)
self.write_processed_lyrics(lyrics, processed_lyrics_file)
processed_track["lyrics"] = lyrics_file
processed_track["processed_lyrics"] = processed_lyrics_file
yt_webm_filename_pattern = os.path.join(track_output_dir, f"{artist_title} (YouTube *.webm")
yt_webm_glob = glob.glob(yt_webm_filename_pattern)
@@ -399,15 +500,6 @@ class KaraokePrep:
else:
self.logger.warning(f"Skipping {title} by {artist} due to missing YouTube ID.")
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}")
else:
self.logger.info("Fetching lyrics from Genius...")
self.write_lyrics_from_genius(artist, title, lyrics_file)
processed_track["lyrics"] = lyrics_file
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}")
+4 -3
View File
@@ -1,7 +1,7 @@
[tool.poetry]
name = "karaoke-prep"
version = "0.4.9"
description = "Prepare for karaoke video creation, by downloading audio and lyrics for a specified song or youtube playlist and separatung audio stems."
version = "0.7.0"
description = "Prepare for karaoke video creation, by downloading audio and lyrics for a specified song or youtube playlist and separatung audio stems, then finalise the video with a title screen after manual syncing!"
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"
readme = "README.md"
@@ -24,7 +24,8 @@ pillow = "^10.1.0"
black = "^23"
[tool.poetry.scripts]
karaoke-prep = 'karaoke_prep.utils.cli:main'
karaoke-prep = 'utils.prep_cli:main'
karaoke-finalise = 'utils.finalise_cli:main'
[tool.black]
line-length = 140
File renamed without changes.
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env python
import argparse
import logging
import pkg_resources
from karaoke_finalise import KaraokeFinalise
def main():
logger = logging.getLogger(__name__)
log_handler = logging.StreamHandler()
log_formatter = logging.Formatter(fmt="%(asctime)s.%(msecs)03d - %(levelname)s - %(module)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log_handler.setFormatter(log_formatter)
logger.addHandler(log_handler)
parser = argparse.ArgumentParser(
description="Render, remux and join intermediate files to create final karaoke video, as the third stage after using karaoke-prep. Processes all (Karaoke).mov files in current directory.",
formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=54),
)
package_version = pkg_resources.get_distribution("karaoke-prep").version
parser.add_argument("-v", "--version", action="version", version=f"%(prog)s {package_version}")
parser.add_argument(
"--log_level",
default="info",
help="Optional: logging level, e.g. info, debug, warning (default: %(default)s). Example: --log_level=debug",
)
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",
)
args = parser.parse_args()
log_level = getattr(logging, args.log_level.upper())
logger.setLevel(log_level)
logger.info(f"KaraokeFinalise beginning with model_name: {args.model_name}")
kfinalise = KaraokeFinalise(
log_formatter=log_formatter,
log_level=log_level,
model_name=args.model_name,
)
tracks = kfinalise.process()
if len(tracks) == 0:
logger.error(f"No tracks found to process.")
return
logger.info(f"Karaoke finalisation processing complete! Output files:")
for track in tracks:
logger.info(f"")
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']}")
if __name__ == "__main__":
main()
@@ -2,6 +2,8 @@
import argparse
import logging
import pkg_resources
import tempfile
import os
from karaoke_prep import KaraokePrep
@@ -43,9 +45,11 @@ def main():
help="Optional: model name to be used for separation (default: %(default)s). Example: --model_name=UVR-MDX-NET-Inst_HQ_3",
)
# Use tempfile to get the platform-independent temp directory
default_model_dir = os.path.join(tempfile.gettempdir(), "audio-separator-models")
parser.add_argument(
"--model_file_dir",
default="/tmp/audio-separator-models/",
default=default_model_dir,
help="Optional: model files directory (default: %(default)s). Example: --model_file_dir=/app/models",
)
@@ -57,8 +61,8 @@ def main():
parser.add_argument(
"--output_format",
default="MP3",
help="Optional: output format for separated audio (default: MP3). Example: --output_format=FLAC",
default="mp3",
help="Optional: output format for separated audio (default: mp3). Example: --output_format=flac",
)
parser.add_argument(
@@ -95,7 +99,7 @@ def main():
parser.add_argument(
"--intro_background_color",
default="black",
default="#000000",
help="Optional: Background color for intro video (default: black). Example: --intro_background_color=#123456",
)
@@ -186,6 +190,7 @@ def main():
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" Processed Lyrics: {track['processed_lyrics']}")
logger.info(f" Instrumental: {track['instrumental_audio']}")
logger.info(f" Vocals: {track['vocals_audio']}")