Compare commits

..
13 Commits
18 changed files with 2289 additions and 991 deletions

No files matched your search

+1
View File
@@ -6,6 +6,7 @@
audio/
lyrics/
karaoke/
tests/outputs
# Byte-compiled / optimized / DLL files
+5 -2
View File
@@ -1591,6 +1591,9 @@ class KaraokeComposer:
)
y += int(bigfont.size)
# Add vertical gap between title and artist using configured value
y += self.config.title_artist_gap
# Draw song artist
for image in render_lines(
get_wrapped_text(
@@ -1650,7 +1653,7 @@ class KaraokeComposer:
# Queue background image packets (and apply transition)
transition = Image.open(
package_dir / "transitions" / "cdgtitlescreenwipepatternnomad.png"
package_dir / "transitions" / f"{self.config.title_screen_transition}.png"
)
for coord in self._gradient_to_tile_positions(transition):
self.writer.queue_packets(packets.get(coord, []))
@@ -1775,7 +1778,7 @@ class KaraokeComposer:
# Queue background image packets (and apply transition)
transition = Image.open(
package_dir / "transitions" / "cdgtitlescreenwipepatternnomad.png"
package_dir / "transitions" / f"{self.config.title_screen_transition}.png"
)
for coord in self._gradient_to_tile_positions(transition):
self.writer.queue_packets(packets.get(coord, []))
+18 -9
View File
@@ -8,10 +8,14 @@ from PIL import ImageColor
# NOTE RGBColor is specifically an RGB 3-tuple (red, green, blue).
RGBColor: TypeAlias = tuple[int, int, int]
def to_rgbcolor(val: Any) -> RGBColor:
if isinstance(val, str):
return ImageColor.getrgb(val)[:3]
raise TypeError("color value not convertible to RGBColor")
def to_rgbcolor_or_none(val: Any) -> RGBColor | None:
if val is None or val == "":
return None
@@ -76,10 +80,10 @@ class SettingsInstrumental:
@define
class SettingsSinger:
active_fill: RGBColor = field(converter=to_rgbcolor, default="#33f")
active_stroke: RGBColor = field(converter=to_rgbcolor, default="#004")
inactive_fill: RGBColor = field(converter=to_rgbcolor, default="#ddf")
inactive_stroke: RGBColor = field(converter=to_rgbcolor, default="#009")
active_fill: RGBColor = field(converter=to_rgbcolor, default="#000")
active_stroke: RGBColor = field(converter=to_rgbcolor, default="#000")
inactive_fill: RGBColor = field(converter=to_rgbcolor, default="#000")
inactive_stroke: RGBColor = field(converter=to_rgbcolor, default="#000")
@define
@@ -118,14 +122,19 @@ class Settings:
singers: list[SettingsSinger] = field(factory=list)
lyrics: list[SettingsLyric] = field(factory=list)
title_color: RGBColor = field(converter=to_rgbcolor, default="#ffffff")
artist_color: RGBColor = field(converter=to_rgbcolor, default="#ffdf6b")
artist_color: RGBColor = field(converter=to_rgbcolor, default="#ffffff")
title_screen_transition: str = "centertexttoplogobottomtext"
title_artist_gap: int = 30
__all__ = [
"RGBColor",
"LyricClearMode", "TextAlign", "TextPlacement", "StrokeType",
"SettingsInstrumental", "SettingsSinger", "SettingsLyric",
"LyricClearMode",
"TextAlign",
"TextPlacement",
"StrokeType",
"SettingsInstrumental",
"SettingsSinger",
"SettingsLyric",
"Settings",
]
Binary file not shown.
Binary file not shown.
+192 -103
View File
@@ -7,55 +7,17 @@ import argparse
from pathlib import Path
from cdgmaker.composer import KaraokeComposer
import sys
from PIL import ImageFont, Image
from PIL import ImageFont
from cdgmaker.render import get_wrapped_text
import itertools
# Constants for TOML configuration
CLEAR_MODE = "eager"
BACKGROUND_COLOR = "#111427"
BORDER_COLOR = "#111427"
FONT_SIZE = 18
STROKE_WIDTH = 0
STROKE_STYLE = "octagon"
ACTIVE_FILL = "#7070F7"
ACTIVE_STROKE = "#000000"
INACTIVE_FILL = "#ff7acc"
INACTIVE_STROKE = "#000000"
import os
import json
# Keep only the truly constant values that aren't style-related
CDG_VISIBLE_WIDTH = 280
TITLE_COLOR = "#ffffff"
ARTIST_COLOR = "#ffdf6b"
FONT = "/Users/andrew/AvenirNext-Bold.ttf"
TITLE_SCREEN_BACKGROUND = "/Users/andrew/cdg-title-screen-background-nomad-simple.png"
# Instead, create a logger specific to this module
# Create a logger specific to this module
logger = logging.getLogger(__name__)
# Add new constants for default values
DEFAULT_ROW = 4 # Increased from 1 to move text lower
DEFAULT_LINE_TILE_HEIGHT = 3
DEFAULT_LINES_PER_PAGE = 4
# Add new constants for instrumentals
INSTRUMENTAL_GAP_THRESHOLD = 1500 # 15 seconds in centiseconds
DEFAULT_INSTRUMENTAL_TEXT = "INSTRUMENTAL"
# Add these constants near the top of the file, with the other constants
INSTRUMENTAL_BACKGROUND = "/Users/andrew/cdg-instrumental-background-nomad-notes.png"
INSTRUMENTAL_TRANSITION = "cdginstrumentalwipepatternnomad"
INSTRUMENTAL_FONT_COLOR = "#ffdf6b"
# Add this constant near the top of the file with other constants
LEAD_IN_THRESHOLD = 300 # 3 seconds in centiseconds
LEAD_IN_OFFSET = 200 # 2 seconds in centiseconds
# Modify these constants near the top of the file
LEAD_IN_SYMBOLS = ["/>", ">", ">", ">"]
LEAD_IN_DURATION = 30 # 300 ms in centiseconds
LEAD_IN_TOTAL = 200 # 2 seconds in centiseconds
def parse_lrc(lrc_file):
with open(lrc_file, "r", encoding="utf-8") as f:
@@ -81,27 +43,35 @@ def parse_lrc(lrc_file):
return lyrics
def detect_instrumentals(lyrics_data):
def detect_instrumentals(
lyrics_data,
line_tile_height,
instrumental_font_color,
instrumental_background,
instrumental_transition,
instrumental_gap_threshold,
instrumental_text,
):
instrumentals = []
for i in range(len(lyrics_data) - 1):
current_end = lyrics_data[i]["timestamp"]
next_start = lyrics_data[i + 1]["timestamp"]
gap = next_start - current_end
if gap >= INSTRUMENTAL_GAP_THRESHOLD:
if gap >= instrumental_gap_threshold:
instrumental_start = current_end + 200 # Add 2 seconds (200 centiseconds) delay
instrumental_duration = (gap - 200) // 100 # Convert to seconds
instrumentals.append(
{
"sync": instrumental_start,
"wait": True,
"text": f"{DEFAULT_INSTRUMENTAL_TEXT}\n{instrumental_duration} seconds\n",
"text": f"{instrumental_text}\n{instrumental_duration} seconds\n",
"text_align": "center",
"text_placement": "bottom middle",
"line_tile_height": DEFAULT_LINE_TILE_HEIGHT,
"fill": INSTRUMENTAL_FONT_COLOR,
"line_tile_height": line_tile_height,
"fill": instrumental_font_color,
"stroke": "",
"image": INSTRUMENTAL_BACKGROUND,
"transition": INSTRUMENTAL_TRANSITION,
"image": instrumental_background,
"transition": instrumental_transition,
}
)
logger.info(
@@ -112,7 +82,86 @@ def detect_instrumentals(lyrics_data):
return instrumentals
def generate_toml(lrc_file, audio_file, title, artist, output_file, row, line_tile_height, lines_per_page, title_color, artist_color):
def generate_toml(
lrc_file,
audio_file,
title,
artist,
output_file,
cdg_styles,
):
"""
Generate a TOML configuration file for CDG creation.
Args:
cdg_styles (dict): Must contain all style-related parameters:
- title_color
- artist_color
- background_color
- border_color
- font_path
- font_size
- stroke_width
- stroke_style
- active_fill
- active_stroke
- inactive_fill
- inactive_stroke
- title_screen_background
- instrumental_background
- instrumental_transition
- instrumental_font_color
- title_screen_transition
- row
- line_tile_height
- lines_per_page
- clear_mode
- sync_offset
- instrumental_gap_threshold
- instrumental_text
- lead_in_threshold
- lead_in_symbols
- lead_in_duration
- lead_in_total
- title_artist_gap
"""
# Validate required style parameters
required_styles = {
"title_color",
"artist_color",
"background_color",
"border_color",
"font_path",
"font_size",
"stroke_width",
"stroke_style",
"active_fill",
"active_stroke",
"inactive_fill",
"inactive_stroke",
"title_screen_background",
"instrumental_background",
"instrumental_transition",
"instrumental_font_color",
"title_screen_transition",
"row",
"line_tile_height",
"lines_per_page",
"clear_mode",
"sync_offset",
"instrumental_gap_threshold",
"instrumental_text",
"lead_in_threshold",
"lead_in_symbols",
"lead_in_duration",
"lead_in_total",
"title_artist_gap",
}
missing_styles = required_styles - set(cdg_styles.keys())
if missing_styles:
raise ValueError(f"Missing required style parameters: {', '.join(missing_styles)}")
try:
lyrics_data = parse_lrc(lrc_file)
except ValueError as e:
@@ -129,11 +178,11 @@ def generate_toml(lrc_file, audio_file, title, artist, output_file, row, line_ti
for i, lyric in enumerate(lyrics_data):
logger.debug(f"Processing lyric {i}: timestamp {lyric['timestamp']}, text '{lyric['text']}'")
if i == 0 or lyric["timestamp"] - lyrics_data[i - 1]["timestamp"] >= LEAD_IN_THRESHOLD:
lead_in_start = lyric["timestamp"] - LEAD_IN_TOTAL
if i == 0 or lyric["timestamp"] - lyrics_data[i - 1]["timestamp"] >= cdg_styles["lead_in_threshold"]:
lead_in_start = lyric["timestamp"] - cdg_styles["lead_in_total"]
logger.debug(f"Adding lead-in before lyric {i} at timestamp {lead_in_start}")
for j, symbol in enumerate(LEAD_IN_SYMBOLS):
sync_time = lead_in_start + j * LEAD_IN_DURATION
for j, symbol in enumerate(cdg_styles["lead_in_symbols"]):
sync_time = lead_in_start + j * cdg_styles["lead_in_duration"]
sync_times.append(sync_time)
formatted_lyrics.append(symbol)
logger.debug(f" Added lead-in symbol {j+1}: '{symbol}' at {sync_time}")
@@ -142,52 +191,68 @@ def generate_toml(lrc_file, audio_file, title, artist, output_file, row, line_ti
formatted_lyrics.append(lyric["text"])
logger.debug(f"Added lyric: '{lyric['text']}' at {lyric['timestamp']}")
instrumentals = detect_instrumentals(lyrics_data)
formatted_lyrics = format_lyrics(formatted_lyrics, instrumentals, sync_times)
instrumentals = detect_instrumentals(
lyrics_data,
line_tile_height=cdg_styles["line_tile_height"],
instrumental_font_color=cdg_styles["instrumental_font_color"],
instrumental_background=cdg_styles["instrumental_background"],
instrumental_transition=cdg_styles["instrumental_transition"],
instrumental_gap_threshold=cdg_styles["instrumental_gap_threshold"],
instrumental_text=cdg_styles["instrumental_text"],
)
formatted_lyrics = format_lyrics(
formatted_lyrics, instrumentals, sync_times, font_path=cdg_styles["font_path"], font_size=cdg_styles["font_size"]
)
toml_data = {
"title": title,
"artist": artist,
"file": audio_file,
"outname": Path(lrc_file).stem,
"clear_mode": CLEAR_MODE,
"sync_offset": 0,
"background": BACKGROUND_COLOR,
"border": BORDER_COLOR,
"font": FONT,
"font_size": FONT_SIZE,
"stroke_width": STROKE_WIDTH,
"stroke_style": STROKE_STYLE,
"clear_mode": cdg_styles["clear_mode"],
"sync_offset": cdg_styles["sync_offset"],
"background": cdg_styles["background_color"],
"border": cdg_styles["border_color"],
"font": cdg_styles["font_path"],
"font_size": cdg_styles["font_size"],
"stroke_width": cdg_styles["stroke_width"],
"stroke_style": cdg_styles["stroke_style"],
"singers": [
{"active_fill": ACTIVE_FILL, "active_stroke": ACTIVE_STROKE, "inactive_fill": INACTIVE_FILL, "inactive_stroke": INACTIVE_STROKE}
{
"active_fill": cdg_styles["active_fill"],
"active_stroke": cdg_styles["active_stroke"],
"inactive_fill": cdg_styles["inactive_fill"],
"inactive_stroke": cdg_styles["inactive_stroke"],
}
],
"lyrics": [
{
"singer": 1,
"sync": sync_times,
"row": row,
"line_tile_height": line_tile_height,
"lines_per_page": lines_per_page,
"row": cdg_styles["row"],
"line_tile_height": cdg_styles["line_tile_height"],
"lines_per_page": cdg_styles["lines_per_page"],
"text": formatted_lyrics,
}
],
"title_color": title_color,
"artist_color": artist_color,
"title_screen_background": TITLE_SCREEN_BACKGROUND,
"title_color": cdg_styles["title_color"],
"artist_color": cdg_styles["artist_color"],
"title_screen_background": cdg_styles["title_screen_background"],
"title_screen_transition": cdg_styles["title_screen_transition"],
"instrumentals": instrumentals,
}
with open(output_file, "w", encoding="utf-8") as f:
toml.dump(toml_data, f)
logger.info(f"TOML file generated: {output_file}")
def get_font():
def get_font(font_path=None, font_size=18):
try:
return ImageFont.truetype(FONT, FONT_SIZE)
return ImageFont.truetype(font_path, font_size) if font_path else ImageFont.load_default()
except IOError:
logger.warning(f"Font file {FONT} not found. Using default font.")
logger.warning(f"Font file {font_path} not found. Using default font.")
return ImageFont.load_default()
@@ -220,9 +285,9 @@ def wrap_text(text, max_width, font):
return lines
def format_lyrics(lyrics_data, instrumentals, sync_times):
def format_lyrics(lyrics_data, instrumentals, sync_times, font_path=None, font_size=18):
formatted_lyrics = []
font = get_font()
font = get_font(font_path, font_size)
logger.debug(f"Using font: {font}")
current_line = ""
@@ -292,27 +357,46 @@ def generate_cdg(
audio_file,
title,
artist,
row=DEFAULT_ROW,
line_tile_height=DEFAULT_LINE_TILE_HEIGHT,
lines_per_page=DEFAULT_LINES_PER_PAGE,
title_color=TITLE_COLOR,
artist_color=ARTIST_COLOR,
cdg_styles,
):
"""
Generate a CDG file from an LRC file and audio file.
This function can be called from other Python code to generate CDG files.
Args:
lrc_file (str): Path to the LRC file
audio_file (str): Path to the audio file
title (str): Title of the song
artist (str): Artist of the song
cdg_styles (dict): Dictionary containing all style and layout parameters
"""
# Check if font_path is just a filename and look for it in the package's fonts directory
if cdg_styles["font_path"] and not os.path.isabs(cdg_styles["font_path"]) and not os.path.exists(cdg_styles["font_path"]):
package_font_path = os.path.join(os.path.dirname(__file__), "fonts", cdg_styles["font_path"])
if os.path.exists(package_font_path):
cdg_styles["font_path"] = package_font_path
logger.debug(f"Found font in package fonts directory: {cdg_styles['font_path']}")
else:
logger.warning(f"Font file {cdg_styles['font_path']} not found in package fonts directory, will use default font")
cdg_styles["font_path"] = None
# Set up logging for this function if it hasn't been configured
if not logger.handlers:
handler = logging.StreamHandler()
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO) # Set to INFO by default, can be changed
logger.setLevel(logging.INFO)
toml_file = f"{Path(lrc_file).stem}.toml"
generate_toml(lrc_file, audio_file, title, artist, toml_file, row, line_tile_height, lines_per_page, title_color, artist_color)
generate_toml(
lrc_file,
audio_file,
title,
artist,
toml_file,
cdg_styles,
)
try:
kc = KaraokeComposer.from_file(toml_file)
@@ -327,7 +411,6 @@ def cli_main():
"""
Command-line interface entry point for the lrc2cdg tool.
"""
# Set up logging for CLI use
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
parser = argparse.ArgumentParser(description="Convert LRC file to CDG")
@@ -335,25 +418,31 @@ def cli_main():
parser.add_argument("audio_file", help="Path to the audio file")
parser.add_argument("--title", required=True, help="Title of the song")
parser.add_argument("--artist", required=True, help="Artist of the song")
parser.add_argument("--row", type=int, default=DEFAULT_ROW, help="Starting row for lyrics (0-17)")
parser.add_argument("--line-tile-height", type=int, default=DEFAULT_LINE_TILE_HEIGHT, help="Height of each line in tile rows")
parser.add_argument("--lines-per-page", type=int, default=DEFAULT_LINES_PER_PAGE, help="Number of lines per page")
parser.add_argument("--title-color", default=TITLE_COLOR, help="Color of the title text on the intro screen")
parser.add_argument("--artist-color", default=ARTIST_COLOR, help="Color of the artist text on the intro screen")
parser.add_argument("--cdg-styles-json", required=True, help="Path to JSON file containing CDG style configuration")
args = parser.parse_args()
generate_cdg(
args.lrc_file,
args.audio_file,
args.title,
args.artist,
args.row,
args.line_tile_height,
args.lines_per_page,
args.title_color,
args.artist_color,
)
try:
with open(args.cdg_styles_json, "r") as f:
cdg_styles = json.loads(f.read())
except FileNotFoundError:
logger.error(f"Style configuration file not found: {args.cdg_styles_json}")
sys.exit(1)
except json.JSONDecodeError as e:
logger.error(f"Invalid JSON in style configuration file: {e}")
sys.exit(1)
try:
generate_cdg(
args.lrc_file,
args.audio_file,
args.title,
args.artist,
cdg_styles,
)
except ValueError as e:
logger.error(f"Invalid style configuration: {e}")
sys.exit(1)
if __name__ == "__main__":
Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

+123 -31
View File
@@ -17,6 +17,9 @@ from googleapiclient.http import MediaFileUpload
import subprocess
import time
from cdgmaker.lrc_to_cdg import generate_cdg
from google.oauth2.credentials import Credentials
import base64
from email.mime.text import MIMEText
class KaraokeFinalise:
@@ -38,6 +41,8 @@ class KaraokeFinalise:
rclone_destination=None,
discord_webhook_url=None,
non_interactive=False,
email_template_file=None,
cdg_styles=None,
):
self.logger = logging.getLogger(__name__)
self.logger.setLevel(log_level)
@@ -117,6 +122,11 @@ class KaraokeFinalise:
self.new_brand_code_dir_path = None
self.brand_code_dir_sharing_link = None
self.email_template_file = email_template_file
self.gmail_service = None
self.cdg_styles = cdg_styles
def check_input_files_exist(self, base_name, with_vocals_file, instrumental_audio_file):
self.logger.info(f"Checking required input files exist...")
@@ -265,11 +275,11 @@ class KaraokeFinalise:
def authenticate_youtube(self):
"""Authenticate and return a YouTube service object."""
credentials = None
pickle_file = "/tmp/karaoke-finalise-token.pickle"
youtube_token_file = "/tmp/karaoke-finalise-youtube-token.pickle"
# Token file stores the user's access and refresh tokens.
if os.path.exists(pickle_file):
with open(pickle_file, "rb") as token:
# Token file stores the user's access and refresh tokens for YouTube.
if os.path.exists(youtube_token_file):
with open(youtube_token_file, "rb") as token:
credentials = pickle.load(token)
# If there are no valid credentials, let the user log in.
@@ -283,7 +293,7 @@ class KaraokeFinalise:
credentials = flow.run_local_server(port=0) # This will open a browser for authentication
# Save the credentials for the next run
with open(pickle_file, "wb") as token:
with open(youtube_token_file, "wb") as token:
pickle.dump(credentials, token)
return build("youtube", "v3", credentials=credentials)
@@ -460,19 +470,26 @@ class KaraokeFinalise:
def choose_instrumental_audio_file(self, base_name):
self.logger.info(f"Choosing instrumental audio file to use as karaoke audio...")
search_string = " (Instrumental "
search_string = " (Instrumental"
self.logger.info(f"Searching for files in current directory containing {search_string}")
all_instrumental_files = [f for f in os.listdir(".") if search_string in f]
flac_files = set(f.rsplit(".", 1)[0] for f in all_instrumental_files if f.endswith(".flac"))
mp3_files = set(f.rsplit(".", 1)[0] for f in all_instrumental_files if f.endswith(".mp3"))
wav_files = set(f.rsplit(".", 1)[0] for f in all_instrumental_files if f.endswith(".wav"))
self.logger.debug(f"FLAC files found: {flac_files}")
self.logger.debug(f"MP3 files found: {mp3_files}")
self.logger.debug(f"WAV files found: {wav_files}")
# Filter out MP3 files if their FLAC counterpart exists
# Filter out MP3 files if their FLAC or WAV counterpart exists
# Filter out WAV files if their FLAC counterpart exists
filtered_files = [
f for f in all_instrumental_files if f.endswith(".flac") or (f.endswith(".mp3") and f.rsplit(".", 1)[0] not in flac_files)
f
for f in all_instrumental_files
if f.endswith(".flac")
or (f.endswith(".wav") and f.rsplit(".", 1)[0] not in flac_files)
or (f.endswith(".mp3") and f.rsplit(".", 1)[0] not in flac_files and f.rsplit(".", 1)[0] not in wav_files)
]
self.logger.debug(f"Filtered instrumental files: {filtered_files}")
@@ -599,36 +616,45 @@ class KaraokeFinalise:
else:
self.logger.info(f"Generating CDG and MP3 files")
generate_cdg(input_files["karaoke_lrc"], input_files["instrumental_audio"], title, artist)
if self.cdg_styles is None:
raise ValueError("CDG styles configuration is required when enable_cdg is True")
# Look for the generated ZIP file
expected_zip = f"{artist} - {title} (Karaoke).zip"
generate_cdg(
input_files["karaoke_lrc"],
input_files["instrumental_audio"],
title,
artist,
self.cdg_styles,
)
self.logger.info(f"Searching for CDG ZIP file. Expected: {expected_zip}")
# Look for the generated ZIP file
expected_zip = f"{artist} - {title} (Karaoke).zip"
if os.path.isfile(expected_zip):
self.logger.info(f"Found expected CDG ZIP file: {expected_zip}")
os.rename(expected_zip, output_files["final_karaoke_cdg_zip"])
self.logger.info(f"Renamed CDG ZIP file from {expected_zip} to {output_files['final_karaoke_cdg_zip']}")
self.logger.info(f"Searching for CDG ZIP file. Expected: {expected_zip}")
if not os.path.isfile(output_files["final_karaoke_cdg_zip"]):
self.logger.error(f"Failed to find any CDG ZIP file. Listing directory contents:")
for file in os.listdir():
self.logger.error(f" - {file}")
raise Exception(f"Failed to create CDG ZIP file: {output_files['final_karaoke_cdg_zip']}")
if os.path.isfile(expected_zip):
self.logger.info(f"Found expected CDG ZIP file: {expected_zip}")
os.rename(expected_zip, output_files["final_karaoke_cdg_zip"])
self.logger.info(f"Renamed CDG ZIP file from {expected_zip} to {output_files['final_karaoke_cdg_zip']}")
self.logger.info(f"CDG ZIP file created: {output_files['final_karaoke_cdg_zip']}")
if not os.path.isfile(output_files["final_karaoke_cdg_zip"]):
self.logger.error(f"Failed to find any CDG ZIP file. Listing directory contents:")
for file in os.listdir():
self.logger.error(f" - {file}")
raise Exception(f"Failed to create CDG ZIP file: {output_files['final_karaoke_cdg_zip']}")
# Extract the CDG ZIP file
self.logger.info(f"Extracting CDG ZIP file: {output_files['final_karaoke_cdg_zip']}")
with zipfile.ZipFile(output_files["final_karaoke_cdg_zip"], "r") as zip_ref:
zip_ref.extractall()
self.logger.info(f"CDG ZIP file created: {output_files['final_karaoke_cdg_zip']}")
if os.path.isfile(output_files["karaoke_mp3"]):
self.logger.info(f"Found extracted MP3 file: {output_files['karaoke_mp3']}")
else:
self.logger.error("Failed to find extracted MP3 file")
raise Exception("Failed to extract MP3 file from CDG ZIP")
# Extract the CDG ZIP file
self.logger.info(f"Extracting CDG ZIP file: {output_files['final_karaoke_cdg_zip']}")
with zipfile.ZipFile(output_files["final_karaoke_cdg_zip"], "r") as zip_ref:
zip_ref.extractall()
if os.path.isfile(output_files["karaoke_mp3"]):
self.logger.info(f"Found extracted MP3 file: {output_files['karaoke_mp3']}")
else:
self.logger.error("Failed to find extracted MP3 file")
raise Exception("Failed to extract MP3 file from CDG ZIP")
def create_txt_zip_file(self, input_files, output_files):
self.logger.info(f"Creating TXT ZIP file...")
@@ -817,6 +843,69 @@ class KaraokeFinalise:
self.generate_organised_folder_sharing_link()
def authenticate_gmail(self):
"""Authenticate and return a Gmail service object."""
creds = None
gmail_token_file = "/tmp/karaoke-finalise-gmail-token.pickle"
if os.path.exists(gmail_token_file):
with open(gmail_token_file, "rb") as token:
creds = pickle.load(token)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
self.youtube_client_secrets_file, ["https://www.googleapis.com/auth/gmail.compose"]
)
creds = flow.run_local_server(port=0)
with open(gmail_token_file, "wb") as token:
pickle.dump(creds, token)
return build("gmail", "v1", credentials=creds)
def draft_completion_email(self, artist, title, youtube_url, dropbox_url):
if not self.email_template_file:
self.logger.info("Email template file not provided, skipping email draft creation.")
return
with open(self.email_template_file, "r") as f:
template = f.read()
email_body = template.format(youtube_url=youtube_url, dropbox_url=dropbox_url)
subject = f"{self.brand_code}: {artist} - {title}"
if self.dry_run:
self.logger.info(f"DRY RUN: Would create email draft with subject: {subject}")
self.logger.info(f"DRY RUN: Email body:\n{email_body}")
else:
if not self.gmail_service:
self.gmail_service = self.authenticate_gmail()
message = MIMEText(email_body)
message["subject"] = subject
raw_message = base64.urlsafe_b64encode(message.as_bytes()).decode("utf-8")
draft = self.gmail_service.users().drafts().create(userId="me", body={"message": {"raw": raw_message}}).execute()
self.logger.info(f"Email draft created with ID: {draft['id']}")
def test_email_template(self):
if not self.email_template_file:
self.logger.error("Email template file not provided. Use --email_template_file to specify the file path.")
return
fake_artist = "Test Artist"
fake_title = "Test Song"
fake_youtube_url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
fake_dropbox_url = "https://www.dropbox.com/sh/fake/folder/link"
fake_brand_code = "TEST-0001"
self.brand_code = fake_brand_code
self.draft_completion_email(fake_artist, fake_title, fake_youtube_url, fake_dropbox_url)
self.logger.info("Email template test complete. Check your Gmail drafts for the test email.")
def process(self):
if self.dry_run:
self.logger.warning("Dry run enabled. No actions will be performed.")
@@ -862,4 +951,7 @@ class KaraokeFinalise:
if self.enable_txt:
result["final_karaoke_txt_zip"] = output_files["final_karaoke_txt_zip"]
if self.email_template_file:
self.draft_completion_email(artist, title, result["youtube_url"], result["brand_code_dir_sharing_link"])
return result
+464 -223
View File
@@ -11,6 +11,7 @@ import yt_dlp.YoutubeDL as ydl
from PIL import Image, ImageDraw, ImageFont
from lyrics_transcriber import LyricsTranscriber
from karaoke_lyrics_processor import KaraokeLyricsProcessor
from pydub import AudioSegment
class KaraokePrep:
@@ -23,47 +24,48 @@ class KaraokePrep:
dry_run=False,
log_level=logging.DEBUG,
log_formatter=None,
model_names=["UVR_MDXNET_KARA_2.onnx", "model_mel_band_roformer_ep_3005_sdr_11.4360.ckpt"],
clean_instrumental_model="model_bs_roformer_ep_317_sdr_12.9755.ckpt",
backing_vocals_models=["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"],
other_stems_models=["htdemucs_6s.yaml"],
model_file_dir=os.path.join(tempfile.gettempdir(), "audio-separator-models"),
output_dir=".",
existing_instrumental=None,
lossless_output_format="FLAC",
lossy_output_format="MP3",
use_cuda=False,
use_coreml=False,
normalization_enabled=True,
denoise_enabled=True,
create_track_subfolders=False,
lyrics_artist=None,
lyrics_title=None,
skip_lyrics=False,
output_png=True,
output_jpg=True,
render_bounding_boxes=False,
existing_title_image=None,
intro_video_duration=5,
intro_background_color="#000000",
intro_background_image=None,
intro_font="Montserrat-Bold.ttf",
intro_artist_color="#ffffff",
intro_title_color="#ff7acc",
existing_instrumental=None,
existing_title_image=None,
intro_title_color="#ffdf6b",
intro_extra_text=None,
intro_extra_text_color="#ffffff",
intro_extra_text_region=None,
intro_title_region=None,
intro_artist_region=None,
existing_end_image=None,
end_video_duration=5,
end_background_color="#000000",
end_background_image=None,
end_font="Montserrat-Bold.ttf",
end_extra_text_color="#ffffff",
end_artist_color="#ffffff",
end_title_color="#ff7acc",
existing_end_image=None,
title_video_duration=5,
end_video_duration=5,
title_initial_font_size=500,
title_top_padding=950,
title_title_padding=400,
title_artist_padding=700,
title_fixed_gap=150,
end_initial_font_size=500,
end_top_padding=950,
end_title_padding=400,
end_artist_padding=700,
end_extra_text_padding=300,
end_fixed_gap=150,
end_title_color="#ffdf6b",
end_extra_text="THANK YOU FOR SINGING!",
lyrics_artist=None,
lyrics_title=None,
skip_lyrics=False,
end_extra_text_color="#ffffff",
end_extra_text_region=None,
end_title_region=None,
end_artist_region=None,
):
self.logger = logging.getLogger(__name__)
self.logger.setLevel(log_level)
@@ -89,11 +91,12 @@ class KaraokePrep:
self.artist = artist
self.title = title
self.filename_pattern = filename_pattern
self.model_names = model_names
self.clean_instrumental_model = clean_instrumental_model
self.backing_vocals_models = backing_vocals_models
self.other_stems_models = other_stems_models
self.model_file_dir = model_file_dir
self.output_dir = output_dir
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
@@ -101,23 +104,14 @@ class KaraokePrep:
self.create_track_subfolders = create_track_subfolders
self.existing_instrumental = existing_instrumental
self.existing_title_image = existing_title_image
self.title_video_duration = title_video_duration
self.end_video_duration = end_video_duration
self.title_initial_font_size = title_initial_font_size
self.title_top_padding = title_top_padding
self.title_title_padding = title_title_padding
self.title_artist_padding = title_artist_padding
self.title_fixed_gap = title_fixed_gap
self.end_initial_font_size = end_initial_font_size
self.end_top_padding = end_top_padding
self.end_title_padding = end_title_padding
self.end_artist_padding = end_artist_padding
self.end_extra_text_padding = end_extra_text_padding
self.end_fixed_gap = end_fixed_gap
self.end_extra_text = end_extra_text
self.lyrics_artist = lyrics_artist
self.lyrics_title = lyrics_title
self.skip_lyrics = skip_lyrics
self.render_bounding_boxes = render_bounding_boxes
self.output_png = output_png
self.output_jpg = output_jpg
self.intro_video_duration = intro_video_duration
self.end_video_duration = end_video_duration
# 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"
@@ -135,17 +129,32 @@ class KaraokePrep:
"font": intro_font,
"artist_color": intro_artist_color,
"title_color": intro_title_color,
"extra_text": intro_extra_text,
"extra_text_color": intro_extra_text_color,
"extra_text_region": self.parse_region(intro_extra_text_region) or (370, 1200, 3100, 480),
"title_region": self.parse_region(intro_title_region) or (370, 200, 3100, 480),
"artist_region": self.parse_region(intro_artist_region) or (370, 700, 3100, 480),
}
self.logger.debug(f"Initialized title_format with extra_text: {self.title_format['extra_text']}")
self.logger.debug(f"Initialized title_format with extra_text_region: {self.title_format['extra_text_region']}")
self.end_format = {
"background_color": end_background_color,
"background_image": end_background_image,
"font": end_font,
"extra_text_color": end_extra_text_color,
"artist_color": end_artist_color,
"title_color": end_title_color,
"extra_text": end_extra_text,
"extra_text_color": end_extra_text_color,
"extra_text_region": self.parse_region(end_extra_text_region) or (370, 300, 3100, 400),
"title_region": self.parse_region(end_title_region) or (370, 800, 3100, 400),
"artist_region": self.parse_region(end_artist_region) or (370, 1300, 3100, 400),
}
self.logger.debug(f"Initialized end_format with extra_text: {self.end_format['extra_text']}")
self.logger.debug(f"Initialized end_format with extra_text_region: {self.end_format['extra_text_region']}")
self.existing_end_image = existing_end_image
self.extracted_info = None
@@ -159,6 +168,15 @@ class KaraokePrep:
else:
self.logger.debug(f"Overall output dir {self.output_dir} already exists")
@staticmethod
def parse_region(region_str):
if region_str:
try:
return tuple(map(int, region_str.split(",")))
except ValueError:
raise ValueError(f"Invalid region format: {region_str}. Expected format: 'x,y,width,height'")
return None
def extract_info_for_online_media(self, input_url=None, input_artist=None, input_title=None):
self.logger.info(f"Extracting info for input_url: {input_url} input_artist: {input_artist} input_title: {input_title}")
if input_url is not None:
@@ -288,6 +306,10 @@ class KaraokePrep:
return output_filename
def write_lyrics_from_genius(self, artist, title, filename):
if self._file_exists(filename):
with open(filename, "r") as f:
return f.read().split("\n")
genius = lyricsgenius.Genius(access_token=os.environ["GENIUS_API_TOKEN"], verbose=False, remove_section_headers=True)
song = genius.search_song(title, artist)
if song:
@@ -428,6 +450,9 @@ class KaraokePrep:
self.logger.info(f"MidiCo LRC output file: {transcriber_outputs['midico_lrc_filepath']}")
def write_processed_lyrics(self, lyrics_file, processed_lyrics_file):
if self._file_exists(processed_lyrics_file):
return processed_lyrics_file
self.logger.info(f"Processing lyrics from {lyrics_file} and writing to {processed_lyrics_file}")
if not self.dry_run:
@@ -530,35 +555,91 @@ class KaraokePrep:
return track_output_dir, artist_title
def calculate_text_size_and_position(self, draw, text, font_path, start_size, resolution, padding):
font_size = start_size
def calculate_text_size_to_fit(self, draw, text, font_path, region):
font_size = 500 # Start with a large font size
font = ImageFont.truetype(font_path, size=font_size) if os.path.exists(font_path) else ImageFont.load_default()
# Initial position for calculating the text bounding box
temp_position = (padding, padding)
bbox = draw.textbbox(temp_position, text, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
def get_text_size(text, font):
return draw.textbbox((0, 0), text, font=font)[2:]
while text_width + 2 * padding > resolution[0] or text_height + 2 * padding > resolution[1]:
text_width, text_height = get_text_size(text, font)
while text_width > region[2] or text_height > region[3]:
font_size -= 10
if font_size <= 0:
raise ValueError("Cannot fit text within screen bounds.")
if font_size <= 150:
# Split the text into two lines
words = text.split()
mid = len(words) // 2
line1 = " ".join(words[:mid])
line2 = " ".join(words[mid:])
# Reset font size for two-line layout
font_size = 500
font = ImageFont.truetype(font_path, size=font_size) if os.path.exists(font_path) else ImageFont.load_default()
while True:
text_width1, text_height1 = get_text_size(line1, font)
text_width2, text_height2 = get_text_size(line2, font)
total_height = text_height1 + text_height2
if max(text_width1, text_width2) <= region[2] and total_height <= region[3]:
return font, (line1, line2)
font_size -= 10
if font_size <= 0:
raise ValueError("Cannot fit text within the defined region.")
font = ImageFont.truetype(font_path, size=font_size) if os.path.exists(font_path) else ImageFont.load_default()
font = ImageFont.truetype(font_path, size=font_size) if os.path.exists(font_path) else ImageFont.load_default()
bbox = draw.textbbox(temp_position, text, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
text_width, text_height = get_text_size(text, font)
text_position = ((resolution[0] - text_width) // 2, (resolution[1] - text_height) // 2)
return font, text_position
return font, text
def calculate_text_position(self, draw, text, font, resolution, vertical_offset):
bbox = draw.textbbox((0, 0), text, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
text_x = (resolution[0] - text_width) // 2
text_y = vertical_offset
return (text_x, text_y), text_height
def _render_text_in_region(self, draw, text, font_path, region, color, font=None):
"""Helper method to render text within a specified region."""
self.logger.debug(f"Rendering text: '{text}' in region: {region} with color: {color}")
if text is None:
self.logger.debug("Text is None, skipping rendering")
return region
if font is None:
font, text_lines = self.calculate_text_size_to_fit(draw, text, font_path, region)
else:
text_lines = text
self.logger.debug(f"Using text_lines: {text_lines}")
x, y, width, height = region
if isinstance(text_lines, tuple): # Two lines
line1, line2 = text_lines
bbox1 = draw.textbbox((0, 0), line1, font=font)
bbox2 = draw.textbbox((0, 0), line2, font=font)
total_height = bbox1[3] + bbox2[3]
y_offset = (height - total_height) // 2
# Draw first line
draw.text((x + (width - bbox1[2]) // 2, y + y_offset), line1, fill=color, font=font)
# Draw second line
draw.text((x + (width - bbox2[2]) // 2, y + y_offset + bbox1[3]), line2, fill=color, font=font)
else:
# Single line
bbox = draw.textbbox((0, 0), text_lines, font=font)
position = (
x + (width - bbox[2]) // 2,
y + (height - bbox[3]) // 2,
)
draw.text(position, text_lines, fill=color, font=font)
return region
def _draw_bounding_box(self, draw, region, color):
"""Helper method to draw a bounding box around a region."""
x, y, width, height = region
draw.rectangle([x, y, x + width, y + height], outline=color, width=2)
def create_video(
self,
@@ -569,147 +650,160 @@ class KaraokePrep:
output_image_filepath_noext,
output_video_filepath,
existing_image=None,
extra_text_color=None,
title_color=None,
artist_color=None,
duration=5,
initial_font_size=500,
top_padding=950,
title_padding=400,
artist_padding=700,
extra_text_padding=600,
fixed_gap=150,
render_bounding_boxes=False,
output_png=True,
output_jpg=True,
):
"""Create a video with title, artist, and optional extra text."""
self.logger.debug(f"Creating video with extra_text: '{extra_text}'")
self.logger.debug(f"Format settings: {format}")
resolution = (3840, 2160) # 4K resolution
self.logger.info(f"Creating video with format: {format}")
self.logger.info(f"extra_text: {extra_text}, artist_text: {artist_text}, title_text: {title_text}")
self.logger.info(
f"top_padding: {top_padding}, title_padding: {title_padding}, artist_padding: {artist_padding}, extra_text_padding: {extra_text_padding}"
)
if existing_image:
self.logger.info(f"Using existing image file: {existing_image}")
existing_extension = os.path.splitext(existing_image)[1]
return self._handle_existing_image(existing_image, output_image_filepath_noext, output_video_filepath, duration)
if existing_extension == ".png":
self.logger.info(f"Copying existing PNG image file: {existing_image}")
shutil.copy2(existing_image, output_image_filepath_noext + existing_extension)
else:
self.logger.info(f"Converting existing image to PNG")
existing_image_obj = Image.open(existing_image)
existing_image_obj.save(output_image_filepath_noext + ".png")
# Create or load background
background = self._create_background(format, resolution)
draw = ImageDraw.Draw(background)
if existing_extension != ".jpg":
self.logger.info(f"Converting existing image to JPG")
existing_image_obj = Image.open(existing_image)
if existing_image_obj.mode == "RGBA":
existing_image_obj = existing_image_obj.convert("RGB") # Convert RGBA to RGB
existing_image_obj.save(output_image_filepath_noext + ".jpg", quality=95)
else:
# Load or create background image
if format["background_image"] and os.path.exists(format["background_image"]):
self.logger.info(f"Using background image file: {format['background_image']}")
background = Image.open(format["background_image"])
else:
self.logger.info(f"Using background color: {format['background_color']}")
background = Image.new("RGB", resolution, color=self.hex_to_rgb(format["background_color"]))
# Resize background to match resolution
background = background.resize(resolution)
draw = ImageDraw.Draw(background)
# Accessing the font file from the package resources
if format["font"] is not None:
self.logger.info(f"Using font: {format['font']}")
with pkg_resources.path("karaoke_prep.resources", format["font"]) as font_path:
# Calculate positions and sizes for title, artist, and extra text
title_font, _ = self.calculate_text_size_and_position(
draw, title_text, str(font_path), initial_font_size, resolution, title_padding
# Render all text elements
self._render_all_text(
draw,
str(font_path),
title_text,
artist_text,
format,
render_bounding_boxes,
)
artist_font, _ = self.calculate_text_size_and_position(
draw, artist_text, str(font_path), initial_font_size, resolution, artist_padding
)
if extra_text:
self.logger.info(f"Calculating extra text font size and position for: {extra_text}")
extra_text_font, _ = self.calculate_text_size_and_position(
draw, extra_text, str(font_path), initial_font_size, resolution, extra_text_padding
)
else:
self.logger.info("No font specified, skipping text rendering")
# Calculate vertical positions with consistent gap
current_y = top_padding
if extra_text:
self.logger.info(f"Calculating extra text position for: {extra_text}")
extra_text_position, extra_text_height = self.calculate_text_position(
draw, extra_text, extra_text_font, resolution, current_y
)
draw.text(extra_text_position, extra_text, fill=extra_text_color, font=extra_text_font)
current_y += extra_text_height + fixed_gap
# Save images and create video
self._save_output_files(
background, output_image_filepath_noext, output_video_filepath, output_png, output_jpg, duration, resolution
)
title_text_position, title_height = self.calculate_text_position(draw, title_text, title_font, resolution, current_y)
draw.text(title_text_position, title_text, fill=title_color, font=title_font)
current_y += title_height + fixed_gap
def _handle_existing_image(self, existing_image, output_image_filepath_noext, output_video_filepath, duration):
"""Handle case where an existing image is provided."""
self.logger.info(f"Using existing image file: {existing_image}")
existing_extension = os.path.splitext(existing_image)[1]
artist_text_position, _ = self.calculate_text_position(draw, artist_text, artist_font, resolution, current_y)
draw.text(artist_text_position, artist_text, fill=artist_color, font=artist_font)
if existing_extension == ".png":
self.logger.info(f"Copying existing PNG image file: {existing_image}")
shutil.copy2(existing_image, output_image_filepath_noext + existing_extension)
else:
self.logger.info(f"Converting existing image to PNG")
existing_image_obj = Image.open(existing_image)
existing_image_obj.save(output_image_filepath_noext + ".png")
# Save static background image
if existing_extension != ".jpg":
self.logger.info(f"Converting existing image to JPG")
existing_image_obj = Image.open(existing_image)
if existing_image_obj.mode == "RGBA":
existing_image_obj = existing_image_obj.convert("RGB")
existing_image_obj.save(output_image_filepath_noext + ".jpg", quality=95)
if duration > 0:
self._create_video_from_image(output_image_filepath_noext + ".png", output_video_filepath, duration)
def _create_background(self, format, resolution):
"""Create or load the background image."""
if format["background_image"] and os.path.exists(format["background_image"]):
self.logger.info(f"Using background image file: {format['background_image']}")
background = Image.open(format["background_image"])
else:
self.logger.info(f"Using background color: {format['background_color']}")
background = Image.new("RGB", resolution, color=self.hex_to_rgb(format["background_color"]))
return background.resize(resolution)
def _render_all_text(self, draw, font_path, title_text, artist_text, format, render_bounding_boxes):
"""Render all text elements on the image."""
# Render title
region = self._render_text_in_region(draw, title_text.upper(), font_path, format["title_region"], format["title_color"])
if render_bounding_boxes:
self._draw_bounding_box(draw, region, format["title_color"])
# Render artist
region = self._render_text_in_region(draw, artist_text.upper(), font_path, format["artist_region"], format["artist_color"])
if render_bounding_boxes:
self._draw_bounding_box(draw, region, format["artist_color"])
# Render extra text if provided
if format["extra_text"]:
region = self._render_text_in_region(
draw, format["extra_text"], font_path, format["extra_text_region"], format["extra_text_color"]
)
if render_bounding_boxes:
self._draw_bounding_box(draw, region, format["extra_text_color"])
def _save_output_files(
self, background, output_image_filepath_noext, output_video_filepath, output_png, output_jpg, duration, resolution
):
"""Save the output image files and create video if needed."""
# Save static background image
if output_png:
background.save(f"{output_image_filepath_noext}.png")
# Save static background image as JPG for smaller filesize to upload as YouTube thumbnail
if output_jpg:
# Save static background image as JPG for smaller filesize
background_rgb = background.convert("RGB")
background_rgb.save(f"{output_image_filepath_noext}.jpg", quality=95)
# Use ffmpeg to create video
ffmpeg_command = f'{self.ffmpeg_base_command} -y -loop 1 -framerate 30 -i "{output_image_filepath_noext}.png" -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}"'
if duration > 0:
self._create_video_from_image(f"{output_image_filepath_noext}.png", output_video_filepath, duration, resolution)
def _create_video_from_image(self, image_path, video_path, duration, resolution=(3840, 2160)):
"""Create a video from a static image."""
ffmpeg_command = (
f'{self.ffmpeg_base_command} -y -loop 1 -framerate 30 -i "{image_path}" '
f"-f lavfi -i anullsrc -c:v libx264 -r 30 -t {duration} -pix_fmt yuv420p "
f'-vf scale={resolution[0]}:{resolution[1]} -c:a aac -shortest "{video_path}"'
)
self.logger.info("Generating video...")
self.logger.debug(f"Running command: {ffmpeg_command}")
os.system(ffmpeg_command)
def create_end_video(self, artist, title, format, output_image_filepath_noext, output_video_filepath):
extra_text = self.end_extra_text
title_text = title.upper()
artist_text = artist.upper()
self.create_video(
extra_text=extra_text,
title_text=title_text,
artist_text=artist_text,
format=format,
output_image_filepath_noext=output_image_filepath_noext,
output_video_filepath=output_video_filepath,
existing_image=self.existing_end_image,
extra_text_color=format["extra_text_color"],
title_color=format["title_color"],
artist_color=format["artist_color"],
duration=self.end_video_duration,
initial_font_size=self.end_initial_font_size,
top_padding=self.end_top_padding,
title_padding=self.end_title_padding,
artist_padding=self.end_artist_padding,
extra_text_padding=self.end_extra_text_padding,
fixed_gap=self.end_fixed_gap,
)
def create_title_video(self, artist, title, format, output_image_filepath_noext, output_video_filepath):
title_text = title.upper()
artist_text = artist.upper()
self.create_video(
extra_text=None,
title_text=title_text,
artist_text=artist_text,
extra_text=format["extra_text"],
format=format,
output_image_filepath_noext=output_image_filepath_noext,
output_video_filepath=output_video_filepath,
existing_image=self.existing_title_image,
title_color=format["title_color"],
artist_color=format["artist_color"],
duration=self.title_video_duration,
initial_font_size=self.title_initial_font_size,
top_padding=self.title_top_padding,
title_padding=self.title_title_padding,
artist_padding=self.title_artist_padding,
fixed_gap=self.title_fixed_gap,
duration=self.intro_video_duration,
render_bounding_boxes=self.render_bounding_boxes,
output_png=self.output_png,
output_jpg=self.output_jpg,
)
def create_end_video(self, artist, title, format, output_image_filepath_noext, output_video_filepath):
title_text = title.upper()
artist_text = artist.upper()
self.create_video(
title_text=title_text,
artist_text=artist_text,
extra_text=format["extra_text"],
format=format,
output_image_filepath_noext=output_image_filepath_noext,
output_video_filepath=output_video_filepath,
existing_image=self.existing_end_image,
duration=self.end_video_duration,
render_bounding_boxes=self.render_bounding_boxes,
output_png=self.output_png,
output_jpg=self.output_jpg,
)
def hex_to_rgb(self, hex_color):
@@ -717,11 +811,202 @@ class KaraokePrep:
hex_color = hex_color.lstrip("#")
return tuple(int(hex_color[i : i + 2], 16) for i in (0, 2, 4))
def process_audio_separation(self, audio_file, artist_title, track_output_dir):
from audio_separator.separator import Separator
self.logger.info(f"Starting audio separation process for {artist_title}")
separator = Separator(
log_level=self.log_level,
log_formatter=self.log_formatter,
model_file_dir=self.model_file_dir,
output_format=self.lossless_output_format,
)
stems_dir = self._create_stems_directory(track_output_dir)
result = {"clean_instrumental": {}, "other_stems": {}, "backing_vocals": {}, "combined_instrumentals": {}}
result["clean_instrumental"] = self._separate_clean_instrumental(separator, audio_file, artist_title, track_output_dir, stems_dir)
result["other_stems"] = self._separate_other_stems(separator, audio_file, artist_title, stems_dir)
result["backing_vocals"] = self._separate_backing_vocals(separator, result["clean_instrumental"]["vocals"], artist_title, stems_dir)
result["combined_instrumentals"] = self._generate_combined_instrumentals(
result["clean_instrumental"]["instrumental"], result["backing_vocals"], artist_title, track_output_dir
)
self._normalize_audio_files(result, artist_title, track_output_dir)
self.logger.info("Audio separation, combination, and normalization process completed")
return result
def _create_stems_directory(self, track_output_dir):
stems_dir = os.path.join(track_output_dir, "stems")
os.makedirs(stems_dir, exist_ok=True)
self.logger.info(f"Created stems directory: {stems_dir}")
return stems_dir
def _separate_clean_instrumental(self, separator, audio_file, artist_title, track_output_dir, stems_dir):
self.logger.info(f"Separating using clean instrumental model: {self.clean_instrumental_model}")
instrumental_path = os.path.join(
track_output_dir, f"{artist_title} (Instrumental {self.clean_instrumental_model}).{self.lossless_output_format}"
)
vocals_path = os.path.join(stems_dir, f"{artist_title} (Vocals {self.clean_instrumental_model}).{self.lossless_output_format}")
result = {}
if not self._file_exists(instrumental_path) or not self._file_exists(vocals_path):
separator.load_model(model_filename=self.clean_instrumental_model)
clean_output_files = separator.separate(audio_file)
for file in clean_output_files:
if "(Vocals)" in file and not self._file_exists(vocals_path):
os.rename(file, vocals_path)
result["vocals"] = vocals_path
elif "(Instrumental)" in file and not self._file_exists(instrumental_path):
os.rename(file, instrumental_path)
result["instrumental"] = instrumental_path
else:
result["vocals"] = vocals_path
result["instrumental"] = instrumental_path
return result
def _separate_other_stems(self, separator, audio_file, artist_title, stems_dir):
self.logger.info(f"Separating using other stems models: {self.other_stems_models}")
result = {}
for model in self.other_stems_models:
self.logger.info(f"Processing with model: {model}")
result[model] = {}
# Check if any stem files for this model already exist
existing_stems = glob.glob(os.path.join(stems_dir, f"{artist_title} (*{model}).{self.lossless_output_format}"))
if existing_stems:
self.logger.info(f"Found existing stem files for model {model}, skipping separation")
for stem_file in existing_stems:
stem_name = os.path.basename(stem_file).split("(")[1].split(")")[0].strip()
result[model][stem_name] = stem_file
else:
separator.load_model(model_filename=model)
other_stems_output = separator.separate(audio_file)
for file in other_stems_output:
file_name = os.path.basename(file)
stem_name = file_name[file_name.rfind("_(") + 2 : file_name.rfind(")_")]
new_filename = f"{artist_title} ({stem_name} {model}).{self.lossless_output_format}"
other_stem_path = os.path.join(stems_dir, new_filename)
if not self._file_exists(other_stem_path):
os.rename(file, other_stem_path)
result[model][stem_name] = other_stem_path
return result
def _separate_backing_vocals(self, separator, vocals_path, artist_title, stems_dir):
self.logger.info(f"Separating clean vocals using backing vocals models: {self.backing_vocals_models}")
result = {}
for model in self.backing_vocals_models:
self.logger.info(f"Processing with model: {model}")
result[model] = {}
lead_vocals_path = os.path.join(stems_dir, f"{artist_title} (Lead Vocals {model}).{self.lossless_output_format}")
backing_vocals_path = os.path.join(stems_dir, f"{artist_title} (Backing Vocals {model}).{self.lossless_output_format}")
if not self._file_exists(lead_vocals_path) or not self._file_exists(backing_vocals_path):
separator.load_model(model_filename=model)
backing_vocals_output = separator.separate(vocals_path)
for file in backing_vocals_output:
if "(Vocals)" in file and not self._file_exists(lead_vocals_path):
os.rename(file, lead_vocals_path)
result[model]["lead_vocals"] = lead_vocals_path
elif "(Instrumental)" in file and not self._file_exists(backing_vocals_path):
os.rename(file, backing_vocals_path)
result[model]["backing_vocals"] = backing_vocals_path
else:
result[model]["lead_vocals"] = lead_vocals_path
result[model]["backing_vocals"] = backing_vocals_path
return result
def _generate_combined_instrumentals(self, instrumental_path, backing_vocals_result, artist_title, track_output_dir):
self.logger.info("Generating combined instrumental tracks with backing vocals")
result = {}
for model, paths in backing_vocals_result.items():
backing_vocals_path = paths["backing_vocals"]
combined_path = os.path.join(track_output_dir, f"{artist_title} (Instrumental +BV {model}).{self.lossless_output_format}")
if not self._file_exists(combined_path):
ffmpeg_command = (
f'{self.ffmpeg_base_command} -i "{instrumental_path}" -i "{backing_vocals_path}" '
f'-filter_complex "[0:a][1:a]amix=inputs=2:duration=longest:weights=1 1" '
f'-c:a {self.lossless_output_format.lower()} "{combined_path}"'
)
self.logger.debug(f"Running command: {ffmpeg_command}")
os.system(ffmpeg_command)
result[model] = combined_path
return result
def _normalize_audio_files(self, separation_result, artist_title, track_output_dir):
self.logger.info("Normalizing clean instrumental and combined instrumentals")
files_to_normalize = [
("clean_instrumental", separation_result["clean_instrumental"]["instrumental"]),
] + [("combined_instrumentals", path) for path in separation_result["combined_instrumentals"].values()]
for key, file_path in files_to_normalize:
if self._file_exists(file_path):
try:
self._normalize_audio(file_path, file_path) # Normalize in-place
# Verify the normalized file
if os.path.getsize(file_path) > 0:
self.logger.info(f"Successfully normalized: {file_path}")
else:
raise Exception("Normalized file is empty")
except Exception as e:
self.logger.error(f"Error during normalization of {file_path}: {e}")
self.logger.warning(f"Normalization failed for {file_path}. Original file remains unchanged.")
else:
self.logger.warning(f"File not found for normalization: {file_path}")
self.logger.info("Audio normalization process completed")
def _normalize_audio(self, input_path, output_path, target_level=0.0):
self.logger.info(f"Normalizing audio file: {input_path}")
# Load audio file
audio = AudioSegment.from_file(input_path, format=self.lossless_output_format.lower())
# Calculate the peak amplitude
peak_amplitude = float(audio.max_dBFS)
# Calculate the necessary gain
gain_db = target_level - peak_amplitude
# Apply gain
normalized_audio = audio.apply_gain(gain_db)
# Ensure the audio is not completely silent
if normalized_audio.rms == 0:
self.logger.warning(f"Normalized audio is silent for {input_path}. Using original audio.")
normalized_audio = audio
# Export normalized audio, overwriting the original file
normalized_audio.export(output_path, format=self.lossless_output_format.lower())
self.logger.info(f"Normalized audio saved, replacing: {output_path}")
self.logger.debug(f"Original peak: {peak_amplitude} dB, Applied gain: {gain_db} dB")
def _file_exists(self, file_path):
"""Check if a file exists and log the result."""
exists = os.path.isfile(file_path)
if exists:
self.logger.info(f"File already exists, skipping creation: {file_path}")
return exists
def prep_single_track(self):
self.logger.info(f"Preparing single track: {self.artist} - {self.title}")
if self.input_media is not None and os.path.isfile(self.input_media):
self.extractor = "Local"
self.extractor = "Original"
else:
# Parses metadata in self.extracted_info to set vars: self.url, self.extractor, self.media_id, self.artist, self.title
self.parse_single_track_metadata(input_artist=self.artist, input_title=self.title)
@@ -825,9 +1110,7 @@ class KaraokePrep:
processed_track["title_image_jpg"] = f"{output_image_filepath_noext}.jpg"
processed_track["title_video"] = os.path.join(track_output_dir, f"{artist_title} (Title).mov")
if os.path.exists(processed_track["title_video"]):
self.logger.debug(f"Title video already exists, skipping render: {processed_track['title_video']}")
else:
if not self._file_exists(processed_track["title_video"]):
self.logger.info(f"Creating title video...")
self.create_title_video(self.artist, self.title, self.title_format, output_image_filepath_noext, processed_track["title_video"])
@@ -836,9 +1119,7 @@ class KaraokePrep:
processed_track["end_image_jpg"] = f"{output_image_filepath_noext}.jpg"
processed_track["end_video"] = os.path.join(track_output_dir, f"{artist_title} (End).mov")
if os.path.exists(processed_track["end_video"]):
self.logger.debug(f"End screen video already exists, skipping render: {processed_track['end_video']}")
else:
if not self._file_exists(processed_track["end_video"]):
self.logger.info(f"Creating end screen video...")
self.create_end_video(self.artist, self.title, self.end_format, output_image_filepath_noext, processed_track["end_video"])
@@ -847,65 +1128,25 @@ class KaraokePrep:
existing_instrumental_extension = os.path.splitext(self.existing_instrumental)[1]
instrumental_path = os.path.join(track_output_dir, f"{artist_title} (Instrumental Custom){existing_instrumental_extension}")
instrumental_path_lossy = os.path.join(track_output_dir, f"{artist_title} (Instrumental Custom).{self.lossy_output_format}")
shutil.copy2(self.existing_instrumental, instrumental_path)
self.convert_to_lossy(instrumental_path, instrumental_path_lossy)
if not self._file_exists(instrumental_path):
shutil.copy2(self.existing_instrumental, instrumental_path)
processed_track["separated_audio"]["Custom"] = {
"instrumental": instrumental_path,
"instrumental_lossy": instrumental_path_lossy,
"vocals": None,
"vocals_lossy": None,
}
else:
self.logger.info(f"Separating audio for track: {self.title} by {self.artist} using models: {', '.join(self.model_names)}")
for model_name in self.model_names:
processed_track[f"separated_audio"][model_name] = {}
instrumental_path = os.path.join(
track_output_dir, f"{artist_title} (Instrumental {model_name}).{self.lossless_output_format}"
)
vocals_path = os.path.join(track_output_dir, f"{artist_title} (Vocals {model_name}).{self.lossless_output_format}")
instrumental_path_lossy = os.path.join(
track_output_dir, f"{artist_title} (Instrumental {model_name}).{self.lossy_output_format}"
)
vocals_path_lossy = os.path.join(track_output_dir, f"{artist_title} (Vocals {model_name}).{self.lossy_output_format}")
if not (os.path.isfile(instrumental_path) and os.path.isfile(vocals_path)):
self.separate_audio(
audio_file=processed_track["input_audio_wav"],
model_name=model_name,
track_output_dir=track_output_dir,
artist_title=artist_title,
instrumental_path=instrumental_path,
vocals_path=vocals_path,
)
if os.path.isfile(instrumental_path):
self.convert_to_lossy(instrumental_path, instrumental_path_lossy)
if os.path.isfile(vocals_path):
self.convert_to_lossy(vocals_path, vocals_path_lossy)
processed_track[f"separated_audio"][model_name]["instrumental"] = instrumental_path
processed_track[f"separated_audio"][model_name]["vocals"] = vocals_path
processed_track[f"separated_audio"][model_name]["instrumental_lossy"] = instrumental_path_lossy
processed_track[f"separated_audio"][model_name]["vocals_lossy"] = vocals_path_lossy
self.logger.info(f"Separating audio for track: {self.title} by {self.artist}")
separation_results = self.process_audio_separation(
audio_file=processed_track["input_audio_wav"], artist_title=artist_title, track_output_dir=track_output_dir
)
processed_track["separated_audio"] = separation_results
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 process_playlist(self):
if self.artist is None or self.title is None:
raise Exception("Error: Artist and Title are required for processing a local file.")
Binary file not shown.
+47 -6
View File
@@ -4,6 +4,7 @@ import logging
import pkg_resources
import os
import sys
import json
from karaoke_prep.karaoke_finalise import KaraokeFinalise
@@ -16,7 +17,7 @@ def main():
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),
formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=62),
)
package_version = pkg_resources.get_distribution("karaoke-prep").version
@@ -107,6 +108,24 @@ def main():
help="Optional: Discord webhook URL to send notifications to. Example: --discord_webhook_url='https://discord.com/api/webhooks/1234567890/TOKEN/messages",
)
parser.add_argument(
"--email_template_file",
default=None,
help="Optional: File path to email template for drafting completion email. Example: --email_template_file='/path/to/email_template.txt'",
)
parser.add_argument(
"--test_email_template",
action="store_true",
help="Optional: Test the email template functionality with fake data. Example: --test_email_template",
)
parser.add_argument(
"--cdg_styles_json",
default=None,
help="Optional: Path to JSON file containing CDG style configuration. Required if --enable_cdg is used. Example: --cdg_styles_json='/path/to/cdg_styles.json'",
)
args = parser.parse_args()
log_level = getattr(logging, args.log_level.upper())
@@ -114,6 +133,22 @@ def main():
logger.info(f"KaraokeFinalise CLI beginning initialisation...")
# Load CDG styles if CDG generation is enabled
cdg_styles = None
if args.enable_cdg:
if not args.cdg_styles_json:
logger.error("CDG styles JSON file path (--cdg_styles_json) is required when --enable_cdg is used")
sys.exit(1)
try:
with open(args.cdg_styles_json, "r") as f:
cdg_styles = json.loads(f.read())
except FileNotFoundError:
logger.error(f"CDG styles configuration file not found: {args.cdg_styles_json}")
sys.exit(1)
except json.JSONDecodeError as e:
logger.error(f"Invalid JSON in CDG styles configuration file: {e}")
sys.exit(1)
kfinalise = KaraokeFinalise(
log_formatter=log_formatter,
log_level=log_level,
@@ -130,13 +165,19 @@ def main():
youtube_description_file=args.youtube_description_file,
rclone_destination=args.rclone_destination,
discord_webhook_url=args.discord_webhook_url,
email_template_file=args.email_template_file,
cdg_styles=cdg_styles,
)
try:
track = kfinalise.process()
except Exception as e:
logger.error(f"An error occurred during finalisation, see stack trace below: {str(e)}")
raise e
if args.test_email_template:
logger.info("Testing email template functionality...")
kfinalise.test_email_template()
else:
try:
track = kfinalise.process()
except Exception as e:
logger.error(f"An error occurred during finalisation, see stack trace below: {str(e)}")
raise e
logger.info(f"Karaoke finalisation processing complete! Output files:")
logger.info(f"")
+124 -106
View File
@@ -56,17 +56,23 @@ def main():
)
parser.add_argument(
"--model_names",
"--clean_instrumental_model",
default="model_bs_roformer_ep_317_sdr_12.9755.ckpt",
help="Optional: Model for clean instrumental separation (default: %(default)s).",
)
parser.add_argument(
"--backing_vocals_models",
nargs="+",
default=[
"UVR_MDXNET_KARA_2.onnx",
"mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt",
"2_HP-UVR.pth",
"model_bs_roformer_ep_317_sdr_12.9755.yaml",
"MDX23C-8KFFT-InstVoc_HQ_2.ckpt",
"htdemucs_6s.yaml",
],
help="Optional: list of model names to be used for separation (default: %(default)s). Example: --model_names UVR_MDXNET_KARA_2.onnx UVR-MDX-NET-Inst_HQ_4.onnx",
default=["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"],
help="Optional: List of models for backing vocals separation (default: %(default)s).",
)
parser.add_argument(
"--other_stems_models",
nargs="+",
default=["htdemucs_6s.yaml"],
help="Optional: List of models for other stems separation (default: %(default)s).",
)
default_model_dir_unix = "/tmp/audio-separator-models/"
@@ -94,12 +100,6 @@ def main():
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(
"--use_cuda",
action="store_true",
@@ -218,10 +218,10 @@ def main():
)
parser.add_argument(
"--title_video_duration",
"--intro_video_duration",
type=int,
default=5,
help="Optional: duration of the title video in seconds (default: 5). Example: --title_video_duration=10",
help="Optional: duration of the title video in seconds (default: 5). Example: --intro_video_duration=10",
)
parser.add_argument(
@@ -231,73 +231,6 @@ def main():
help="Optional: duration of the end video in seconds (default: 5). Example: --end_video_duration=10",
)
parser.add_argument(
"--title_initial_font_size",
type=int,
default=500,
help="Optional: Initial font size for title video (default: 500). Example: --title_initial_font_size=600",
)
parser.add_argument(
"--title_top_padding",
type=int,
default=950,
help="Optional: Top padding for title video (default: 950). Example: --title_top_padding=1000",
)
parser.add_argument(
"--title_title_padding",
type=int,
default=400,
help="Optional: Title padding for title video (default: 400). Example: --title_title_padding=450",
)
parser.add_argument(
"--title_artist_padding",
type=int,
default=700,
help="Optional: Artist padding for title video (default: 700). Example: --title_artist_padding=750",
)
parser.add_argument(
"--title_fixed_gap",
type=int,
default=150,
help="Optional: Fixed gap for title video (default: 150). Example: --title_fixed_gap=200",
)
parser.add_argument(
"--end_initial_font_size",
type=int,
default=500,
help="Optional: Initial font size for end video (default: 500). Example: --end_initial_font_size=600",
)
parser.add_argument(
"--end_top_padding",
type=int,
default=950,
help="Optional: Top padding for end video (default: 950). Example: --end_top_padding=1000",
)
parser.add_argument(
"--end_title_padding",
type=int,
default=400,
help="Optional: Title padding for end video (default: 400). Example: --end_title_padding=450",
)
parser.add_argument(
"--end_artist_padding",
type=int,
default=700,
help="Optional: Artist padding for end video (default: 700). Example: --end_artist_padding=750",
)
parser.add_argument(
"--end_extra_text_padding",
type=int,
default=300,
help="Optional: Extra text padding for end video (default: 600). Example: --end_extra_text_padding=650",
)
parser.add_argument(
"--end_fixed_gap",
type=int,
default=150,
help="Optional: Fixed gap for end video (default: 150). Example: --end_fixed_gap=200",
)
parser.add_argument(
"--lyrics_artist",
help="Optional: Override the artist name used for lyrics search. Example: --lyrics_artist='The Beatles'",
@@ -314,6 +247,67 @@ def main():
help="Optional: Skip fetching and processing lyrics. Example: --skip_lyrics",
)
parser.add_argument(
"--render_bounding_boxes",
action="store_true",
help="Optional: render bounding boxes around text regions for debugging (default: %(default)s). Example: --render_bounding_boxes",
)
parser.add_argument(
"--output_png",
type=lambda x: (str(x).lower() == "true"),
default=True,
help="Optional: output PNG format for title and end images (default: %(default)s). Example: --output_png=False",
)
parser.add_argument(
"--output_jpg",
type=lambda x: (str(x).lower() == "true"),
default=True,
help="Optional: output JPG format for title and end images (default: %(default)s). Example: --output_jpg=False",
)
parser.add_argument(
"--intro_extra_text",
help="Optional: Extra text to display on the intro video. Example: --intro_extra_text='GET READY TO SING!'",
)
parser.add_argument(
"--intro_extra_text_color",
default="#ffffff",
help="Optional: Font color for intro video extra text (default: #ffffff). Example: --intro_extra_text_color=#123456",
)
parser.add_argument(
"--intro_extra_text_region",
help="Optional: Region for extra text in intro video (x, y, width, height; default: 370,1950,3100,480). Example: --intro_extra_text_region=370,1950,3100,480",
)
parser.add_argument(
"--end_extra_text_region",
help="Optional: Region for extra text in end video (x, y, width, height; default: 370,1950,3100,480). Example: --end_extra_text_region=370,1950,3100,480",
)
parser.add_argument(
"--intro_title_region",
help="Optional: Region for title text in intro video (x, y, width, height; default: 370,470,3100,480). Example: --intro_title_region=370,470,3100,480",
)
parser.add_argument(
"--intro_artist_region",
help="Optional: Region for artist text in intro video (x, y, width, height; default: 370,1210,3100,480). Example: --intro_artist_region=370,1210,3100,480",
)
parser.add_argument(
"--end_title_region",
help="Optional: Region for title text in end video (x, y, width, height; default: 370,470,3100,480). Example: --end_title_region=370,470,3100,480",
)
parser.add_argument(
"--end_artist_region",
help="Optional: Region for artist text in end video (x, y, width, height; default: 370,1210,3100,480). Example: --end_artist_region=370,1210,3100,480",
)
args = parser.parse_args()
input_media, artist, title, filename_pattern = None, None, None, None
@@ -361,7 +355,9 @@ def main():
logger.setLevel(log_level)
if args.existing_instrumental:
args.model_names = ["Custom"]
args.clean_instrumental_model = None
args.backing_vocals_models = []
args.other_stems_models = []
logger.info(f"KaraokePrep beginning with input_media: {input_media} artist: {artist} and title: {title}")
@@ -373,11 +369,12 @@ def main():
dry_run=args.dry_run,
log_formatter=log_formatter,
log_level=log_level,
model_names=args.model_names,
clean_instrumental_model=args.clean_instrumental_model,
backing_vocals_models=args.backing_vocals_models,
other_stems_models=args.other_stems_models,
model_file_dir=args.model_file_dir,
output_dir=args.output_dir,
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,
@@ -386,34 +383,34 @@ def main():
existing_instrumental=args.existing_instrumental,
existing_title_image=args.existing_title_image,
existing_end_image=args.existing_end_image,
title_video_duration=args.title_video_duration,
intro_video_duration=args.intro_video_duration,
intro_background_color=args.intro_background_color,
intro_background_image=args.intro_background_image,
intro_font=args.intro_font,
intro_artist_color=args.intro_artist_color,
intro_title_color=args.intro_title_color,
title_initial_font_size=args.title_initial_font_size,
title_top_padding=args.title_top_padding,
title_title_padding=args.title_title_padding,
title_artist_padding=args.title_artist_padding,
title_fixed_gap=args.title_fixed_gap,
intro_title_region=args.intro_title_region,
intro_artist_region=args.intro_artist_region,
end_video_duration=args.end_video_duration,
end_extra_text=args.end_extra_text,
end_background_color=args.end_background_color,
end_background_image=args.end_background_image,
end_font=args.end_font,
end_extra_text_color=args.end_extra_text_color,
end_artist_color=args.end_artist_color,
end_title_color=args.end_title_color,
end_initial_font_size=args.end_initial_font_size,
end_top_padding=args.end_top_padding,
end_title_padding=args.end_title_padding,
end_artist_padding=args.end_artist_padding,
end_extra_text_padding=args.end_extra_text_padding,
end_fixed_gap=args.end_fixed_gap,
end_title_region=args.end_title_region,
end_artist_region=args.end_artist_region,
lyrics_artist=args.lyrics_artist,
lyrics_title=args.lyrics_title,
skip_lyrics=args.skip_lyrics,
render_bounding_boxes=args.render_bounding_boxes,
output_png=args.output_png,
output_jpg=args.output_jpg,
intro_extra_text=args.intro_extra_text,
intro_extra_text_color=args.intro_extra_text_color,
intro_extra_text_region=args.intro_extra_text_region,
end_extra_text=args.end_extra_text,
end_extra_text_region=args.end_extra_text_region,
)
tracks = kprep.process()
@@ -429,11 +426,32 @@ def main():
logger.info(f" Lyrics: {track['lyrics']}")
logger.info(f" Processed Lyrics: {track['processed_lyrics']}")
for model_name in args.model_names:
logger.info(f" Instrumental: {track['separated_audio'][model_name]['instrumental']}")
logger.info(f" Instrumental (Lossy): {track['separated_audio'][model_name]['instrumental_lossy']}")
logger.info(f" Vocals: {track['separated_audio'][model_name]['vocals']}")
logger.info(f" Vocals (Lossy): {track['separated_audio'][model_name]['vocals_lossy']}")
logger.info(f" Separated Audio:")
# Clean Instrumental
logger.info(f" Clean Instrumental Model:")
for stem_type, file_path in track["separated_audio"]["clean_instrumental"].items():
logger.info(f" {stem_type.capitalize()}: {file_path}")
# Other Stems
logger.info(f" Other Stems Models:")
for model, stems in track["separated_audio"]["other_stems"].items():
logger.info(f" Model: {model}")
for stem_type, file_path in stems.items():
logger.info(f" {stem_type.capitalize()}: {file_path}")
# Backing Vocals
logger.info(f" Backing Vocals Models:")
for model, stems in track["separated_audio"]["backing_vocals"].items():
logger.info(f" Model: {model}")
for stem_type, file_path in stems.items():
logger.info(f" {stem_type.capitalize()}: {file_path}")
# Combined Instrumentals
logger.info(f" Combined Instrumentals:")
for model, file_path in track["separated_audio"]["combined_instrumentals"].items():
logger.info(f" Model: {model}")
logger.info(f" Combined Instrumental: {file_path}")
if __name__ == "__main__":
Generated
+448 -508
View File
File diff suppressed because it is too large. Load diff
+2 -3
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-prep"
version = "0.27.2"
version = "0.30.3"
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"
@@ -24,14 +24,13 @@ google-api-python-client = "*"
google-auth = "*"
google-auth-oauthlib = "*"
google-auth-httplib2 = "*"
pyperclip = ">=1.8"
thefuzz = ">=0.22"
numpy = "^1"
audio-separator = { version = ">=0.21.0", extras = ["cpu"] }
lyrics-converter = ">=0.2.1"
lyrics-transcriber = ">=0.18"
kbputils = "^0.0.16"
karaoke-lyrics-processor = ">=0.4.0"
karaoke-lyrics-processor = ">=0.4.1"
attrs = ">=24.2.0"
cattrs = ">=24.1.2"
toml = ">=0.10"
+714
View File
@@ -0,0 +1,714 @@
[
["This Is Me Smiling", "Prettier"],
["Ленинград", "Алкаш"],
["Cher", "Apples Don't Fall Far From The Tree"],
["The Hush Sound", "Don't Wake Me Up"],
["ABBA", "I Am The City"],
["ABBA", "Under Attack"],
["The Hush Sound", "A Dark Congregation"],
["The Hush Sound", "As You Cry"],
["The Hush Sound", "Boys Are Too Refined"],
["The Hush Sound", "Break the Sky"],
["The Hush Sound", "Carry Me Home"],
["The Hush Sound", "City Traffic Puzzle"],
["The Hush Sound", "Crawling Towards The Sun"],
["The Hush Sound", "Echo"],
["The Hush Sound", "Eileen"],
["The Hush Sound", "Honey"],
["The Hush Sound", "Hospital Bed Crawl"],
["The Hush Sound", "Hourglass"],
["The Hush Sound", "Hurricane"],
["The Hush Sound", "Intro"],
["The Hush Sound", "Lions Roar"],
["The Hush Sound", "Love You Much Better"],
["The Hush Sound", "Magnolia"],
["The Hush Sound", "Medicine Man"],
["The Hush Sound", "Molasses"],
["The Hush Sound", "Momentum"],
["The Hush Sound", "My Apologies"],
["The Hush Sound", "Not Your Concern"],
["The Hush Sound", "Out Through The Curtain"],
["The Hush Sound", "Sweet Tangerine"],
["The Hush Sound", "That's Okay"],
["The Hush Sound", "The Artist"],
["The Hush Sound", "The Market"],
["The Hush Sound", "Tides Change"],
["The Hush Sound", "Unsafe Safe"],
["The Hush Sound", "We Intertwined"],
["The Hush Sound", "Weeping Willow"],
["The Hush Sound", "Where We Went Wrong"],
["The Hush Sound", "Wine Red"],
["The Hush Sound", "You Are The Moon"],
["The Hush Sound", "Lighthouse"],
["Allie X", "GLAM!"],
["Lemaitre", "Rocket Girl (feat. Betty Who)"],
["Just Jack", "253"],
["Just Jack", "All Night Cinema"],
["Just Jack", "Astronaut"],
["Just Jack", "Blood"],
["Just Jack", "Disco Friends"],
["Just Jack", "Doctor Doctor"],
["Just Jack", "Embers"],
["Just Jack", "Glory Days"],
["Just Jack", "Goth In The Disco"],
["Just Jack", "Hold On"],
["Just Jack", "I Talk Too Much"],
["Just Jack", "Life Stories"],
["Just Jack", "Lo And Behold"],
["Just Jack", "Lost"],
["Just Jack", "Mourning Morning"],
["Just Jack", "No Time"],
["Just Jack", "So Wrong"],
["Just Jack", "Spectacular Failures"],
["Just Jack", "Starz in Their Eyes"],
["Just Jack", "Symphony of Sirens"],
["Just Jack", "The Day I Died"],
["Just Jack", "Writers Block"],
[
"Los Campesinos!",
"This Is How You Spell \"HAHAHA, We Destroyed the Hopes and Dreams of a Generation of Faux-Romantics\""
],
["Los Campesinos!", "2007, The Year Punk Broke (My Heart)"],
["Los Campesinos!", "And We Exhale and Roll Our Eyes in Unison"],
["Los Campesinos!", "Broken Heartbeats Sounds Like Breakbeats"],
["Los Campesinos!", "Death to Los Campesinos!"],
["Los Campesinos!", "Don't Tell Me to Do the Math(s)"],
["Los Campesinos!", "Drop It Doe Eyes"],
["Los Campesinos!", "Knee Deep At ATP"],
["Los Campesinos!", "My Year In Lists"],
["Los Campesinos!", "Sweet Dreams, Sweet Cheeks"],
["Los Campesinos!", "We Are All Accelerated Readers"],
["Los Campesinos!", "You! Me! Dancing!"],
["Mew", "156"],
["Mew", "Am I Wry? No"],
["Mew", "Behind the Drapes"],
["Mew", "Comforting Sounds"],
["Mew", "Eight Flew Over, One was Destroyed"],
["Mew", "Her Voice is Beyond Her Years"],
["Mew", "She Came Home for Christmas"],
["Mew", "She Spider"],
["Mew", "Snow Brigade"],
["Mew", "Symmetry"],
["of Montreal", "Gronlandic Edit"],
["Idlewild", "(I Am) What I Am Not"],
["Idlewild", "A Modern Way of Letting Go"],
["Idlewild", "Actually It's Darkness"],
["Idlewild", "American English"],
["Idlewild", "Century After Century"],
["Idlewild", "I Don't Have The Map"],
["Idlewild", "I Never Wanted"],
["Idlewild", "Idea Track"],
["Idlewild", "In Remote Part , Scottish Fiction"],
["Idlewild", "Let Me Sleep (Next To The Mirror)"],
["Idlewild", "Listen To What You've Got"],
["Idlewild", "Little Discourage"],
["Idlewild", "Live in a Hiding Place"],
["Idlewild", "Mistake Pageant"],
["Idlewild", "Out of Routine"],
["Idlewild", "Quiet Crown"],
["Idlewild", "Roseability"],
["Idlewild", "Rusty"],
["Idlewild", "Stay the Same"],
["Idlewild", "Tell Me Ten Words"],
["Idlewild", "The Bronze Medal"],
["Idlewild", "These Wooden Ideas"],
["Idlewild", "You Held the World in Your Arms"],
["Los Campesinos!", "A Heat Rash in the Shape of the Show Me State"],
["Los Campesinos!", "All Your Kayfabe Friends"],
["Los Campesinos!", "Coda A Burn Scar in the Shape of the Sooner State"],
["Los Campesinos!", "Documented Minor Emotional Breakdown #1"],
["Los Campesinos!", "Heart Swells:100-1"],
["Los Campesinos!", "Heart Swells / Pacific Daylight Time"],
["Los Campesinos!", "I Just Sighed, I Just Signed, Just So You Know"],
["Los Campesinos!", "I Warned You, Do Not Make an Enemy of Me"],
["Los Campesinos!", "In Medias Res"],
[
"Los Campesinos!",
"It's Never That Easy Though, Is It (Song For The Other Kurt)"
],
["Los Campesinos!", "Miserabilia"],
["Los Campesinos!", "Plan A"],
["Los Campesinos!", "Romance is Boring"],
["Los Campesinos!", "Straight in at 101"],
["Los Campesinos!", "The End Of The Asterisk"],
["Los Campesinos!", "The Sea is a Good Place to Think of the Future"],
["Los Campesinos!", "There Are Listed Buildings"],
["Los Campesinos!", "This is a Flag, There is No Wind"],
["Los Campesinos!", "Ways To Make It Through The Wall"],
["Los Campesinos!", "We Are Beautiful, We Are Doomed"],
["Los Campesinos!", "We've Got Your Back"],
["Los Campesinos!", "Who Fell Asleep In"],
["Los Campesinos!", "You'll Need Those Fingers For Crossing"],
["Miracles of Modern Science", "Bossa Supernova"],
["Miracles of Modern Science", "Eating Me Alive"],
["Miracles of Modern Science", "Friend Of The Animals"],
["Miracles of Modern Science", "I Found Space"],
["Miracles of Modern Science", "Luminol"],
["Miracles of Modern Science", "MOMS AWAY!"],
["Miracles of Modern Science", "Quantum Of Solace"],
["Miracles of Modern Science", "Secret Track"],
["Miracles of Modern Science", "Space Chopper"],
["Miracles of Modern Science", "Strangerous"],
["Miracles of Modern Science", "Tensity"],
["Miracles of Modern Science", "The Moon & Australia"],
["Nia Archives", "(Over)Thinking"],
["Nia Archives", "18 & Over"],
["Nia Archives", "Crossroads"],
["Nia Archives", "Don't Kid Urself"],
["Nia Archives", "Gud Gudbyez"],
["Nia Archives", "Headz Gone West"],
["Nia Archives", "Luv Like"],
["Nia Archives", "Part Of Me"],
["Nia Archives", "Sober Feels"],
["This Is Me Smiling", "A Better Way to Fall in Love"],
["This Is Me Smiling", "Alive in the Chase"],
["This Is Me Smiling", "Ephemera"],
["This Is Me Smiling", "Feelin' the Time Pass By"],
["This Is Me Smiling", "For When You Don't Hear It Right"],
["This Is Me Smiling", "Goodbye to Each New Day"],
["This Is Me Smiling", "Matter to Matter"],
["This Is Me Smiling", "Mixin' Up Adjectives"],
["This Is Me Smiling", "Say What You're Gonna Say"],
["This Is Me Smiling", "So Excited to Sleep"],
["This Is Me Smiling", "Up in All Directions"],
["Bug Hunter", "Dear McCracken"],
["Ken Ashcorp", "Burgz"],
["Ken Ashcorp", "Absolute Territory"],
["Ken Ashcorp", "I'm Your Slave"],
["Mew", "A Dark Design"],
["Mew", "An Envoy To The Open Fields"],
["Mew", "Apocalypso"],
["Mew", "Chinaberry Tree"],
["Mew", "Fox Cub"],
["Mew", "Louise Louisa"],
["Mew", "Saviours Of Jazz Ballet"],
["Mew", "Special"],
["Mew", "The Seething Rain Weeps For You"],
["Mew", "The Zookeeper's Boy"],
["Mew", "White Lips Kissed"],
["Mew", "Why Are You Looking Grave"],
["Get Cape. Wear Cape. Fly", "An Oak Tree"],
["Get Cape. Wear Cape. Fly", "Call Me Ishmael"],
["Get Cape. Wear Cape. Fly", "Get Cape. Wear Cape. Fly"],
["Get Cape. Wear Cape. Fly", "Glasshouses"],
["Get Cape. Wear Cape. Fly", "I-Spy"],
[
"Get Cape. Wear Cape. Fly",
"If I Had £1 For Every Stale Song Title I'd Be 30 Short Of Getting Out Of This Mess"
],
["Get Cape. Wear Cape. Fly", "Once More With Feeling"],
[
"Get Cape. Wear Cape. Fly",
"The Chronicles Of A Bohemian Teenager (Part Two)"
],
[
"Get Cape. Wear Cape. Fly",
"The Chronicles Of A Bohemian Teenager (Part One)"
],
["Get Cape. Wear Cape. Fly", "The Lighthousekeeper"],
["Get Cape. Wear Cape. Fly", "War Of The Worlds"],
["Get Cape. Wear Cape. Fly", "Whitewash Is Brainwash"],
["Hi I'm Case", "Smoke Damage (Youtube version)"],
["Ken Ashcorp", "Wear"],
["Hi I'm Case", "Smoke Damage (Spotify version)"],
["Neil Diamond", "The Look Of Love"],
["Amy Winehouse", "Valerie (Short Version)"],
["Anastacia", "I'm Outta Love (Short Version)"],
["Calum Scott", "Dancing On My Own (Short Version)"],
["Ed Sheeran", "Shivers (Short Version)"],
["Eminem", "Without Me (Short Version)"],
["Gnarls Barkley", "Crazy (Short Version)"],
["Jess Glynne", "Hold My Hand (Short Version)"],
["Kenny Loggins", "Footloose (Short Version)"],
["Kings Of Leon", "Sex on Fire (Short Version)"],
["Lady Gaga", "Born This Way (Short Version)"],
["Miley Cyrus", "Jolene (Short Version)"],
["Miley Cyrus", "Wrecking Ball (Short Version)"],
["Robbie Williams", "Angels (Short Version)"],
["Shakira", "Whenever, Wherever (Short Version)"],
["Shania Twain", "Man! I Feel Like A Woman (Short Version)"],
["Shirley Bassey", "Big Spender (Short Version)"],
["The Killers", "Mr. Brightside (Short Version)"],
["The Pussycat Dolls", "Sway (Short Version)"],
["Twenty One Pilots", "Stressed Out (Short Version)"],
["Wheatus", "Teenage Dirtbag (Short Version)"],
["Christina Stürmer", "Nie Genug"],
["James Brown", "It's a Man's World (Short Version)"],
["Jerry Lee Lewis", "Great Balls Of Fire (Short Version)"],
["Melanie Martinez", "Toxic (Short Version)"],
["Melissa Etheridge", "Bring Me Some Water (Short Version)"],
["Queen", "Crazy Little Thing Called Love (Short Version)"],
["Tina Turner", "Proud Mary (Short Version)"],
["Tina Turner", "The Best (Short Version)"],
["Tom Jones", "Help Yourself (Short Version)"],
["Tom Jones", "Sex Bomb (Short Version)"],
["Andreas Gabalier", "Hulapalu (Short Version)"],
["Christina Stürmer", "Nie Genug (Short Version)"],
["Die Draufgänger", "Cordula Grün (Short Version)"],
["Jimi Jamison", "I'm Always Here (Short Version)"],
["Jürgen Drews", "Ein Bett im Kornfeld"],
["Jürgen Drews", "Ein Bett im Kornfeld (Short Version)"],
["STS", "Kalt Und Kälter (Short Version)"],
["STS", "Kalt Und Kälter"],
["Udo Jürgens", "Aber bitte mit Sahne"],
["Udo Jürgens", "Aber bitte mit Sahne (Short Version)"],
["Bryan Adams", "Summer of '69 (Short Version)"],
["Dylan Emmet", "Lose This"],
["Loosey LaDuca", "Let Loose"],
["Against Me", "People Who Died"],
["Eleven Hundred Springs", "Thunderbird Will Do Just Fine"],
["Etherwood", "Begin By Letting Go"],
["Foy Vance", "She Burns"],
["Frightened Rabbit", "Late March Death March"],
["George Barnett", "Stone Cold Classic"],
["Get Cape. Wear Cape. Fly", "Better Things (ft. Kate Nash)"],
["Get Cape. Wear Cape. Fly", "Could've Seen It All"],
["Get Cape. Wear Cape. Fly", "Find The Time"],
["Get Cape. Wear Cape. Fly", "I Could Build You A Tower"],
["Get Cape. Wear Cape. Fly", "Keep Singing Out"],
["Get Cape. Wear Cape. Fly", "Let The Journey Begin"],
["Get Cape. Wear Cape. Fly", "Moving Forward"],
["Get Cape. Wear Cape. Fly", "Postcards From Catalunya"],
[
"Get Cape. Wear Cape. Fly",
"The Children Are (The Consumers Of) The Future"
],
["Get Cape. Wear Cape. Fly", "This Could Be All"],
["Get Cape. Wear Cape. Fly", "Waiting For The Monster To Drown"],
["Get Cape. Wear Cape. Fly", "Window Of Your Mind"],
["Get Cape. Wear Cape. Fly", "Young And Lovestruck"],
["K-Os", "The Rain"],
["Nothing But Thieves", "Pop The Balloon"],
["Robbie Basho", "Blue Crystal Fire"],
["Smino", "Lee and Lovie"],
["The Skints", "Murderer"],
["Xan Griffin", "Capricorn (ft. WOLFE)"],
["Pulp", "Cocaine Socialism"],
["Random Hand", "Play Some Ska"],
["Sexyy Red, Nicki Minaj & Tay Keith", "Pound Town 2"],
["Tori Amos", "Liquid Diamonds"],
["Frightened Rabbit", "Music Now"],
["Frightened Rabbit", "Housing (out)"],
["Frightened Rabbit", "The Modern Leper"],
["Frightened Rabbit", "A Lick Of Paint"],
["Frightened Rabbit", "The Greys"],
["Frightened Rabbit", "Head Rolls Off"],
["Frightened Rabbit", "Backyard Skulls"],
["Frightened Rabbit", "The Wreck"],
["Frightened Rabbit", "My Backwards Walk"],
["Frightened Rabbit", "Be Less Rude"],
["Frightened Rabbit", "Die Like A Rich Boy"],
["Frightened Rabbit", "State Hospital"],
["Frightened Rabbit", "Skip the Youth"],
["Frightened Rabbit", "Yes, I Would"],
["Frightened Rabbit", "Floating in the Forth"],
["Frightened Rabbit", "Nitrous Gas"],
["Frightened Rabbit", "Break"],
["Frightened Rabbit", "Things"],
["Frightened Rabbit", "Nothing Like You"],
["Frightened Rabbit", "Good Arms vs Bad Arms"],
["Frightened Rabbit", "Foot Shooter"],
["Frightened Rabbit", "The Twist"],
["Frightened Rabbit", "The Loneliness and the Scream"],
["Frightened Rabbit", "Swim Until You Can't See Land"],
["Frightened Rabbit", "An Otherwise Disappointing Life"],
["Frightened Rabbit", "Holy"],
["Frightened Rabbit", "Behave!"],
["Frightened Rabbit", "Old Old Fashioned"],
["Frightened Rabbit", "Yawns"],
["Frightened Rabbit", "I Feel Better"],
["Frightened Rabbit", "Woke Up Hurting"],
["Frightened Rabbit", "Dead Now"],
["Frightened Rabbit", "Poke"],
["Frightened Rabbit", "400 Bones"],
["Frightened Rabbit", "Little Drum"],
["Frightened Rabbit", "Fast Blood"],
["Frightened Rabbit", "Square 9"],
["Frightened Rabbit", "I Wish I Was Sober"],
["Frightened Rabbit", "The Oil Slick"],
["Frightened Rabbit", "Still Want To Be Here"],
["Frightened Rabbit", "Blood Under The Bridge"],
["Frightened Rabbit", "Death Dream"],
["Frightened Rabbit", "Wait 'Til The Morning"],
["Frightened Rabbit", "Not Miserable"],
["Frightened Rabbit", "Snake"],
["Frightened Rabbit", "Acts of Man"],
["Frightened Rabbit", "Living in Colour"],
["Frightened Rabbit", "Housing (in)"],
["Frightened Rabbit", "The Wrestle"],
["Frightened Rabbit", "Go Go Girls"],
["Frightened Rabbit", "December's Traditions"],
["Frightened Rabbit", "Lump Street"],
["Frightened Rabbit", "Keep Yourself Warm"],
["Frightened Rabbit", "The Woodpile"],
["Frightened Rabbit", "Get Out"],
["Judas Priest", "Living Bad Dreams"],
["The Spits", "Bring Me Down"],
["Voltaire", "Feathery Wings"],
["City and Colour", "The Death of Me"],
["Was (Not Was)", "Out Come the Freaks"],
["Bon Jovi", "Hallelujah"],
["Marilyn Dagenais", "Je serai là"],
["Marilyn Dagenais", "J't'écrirai pas"],
["A Lost People", "Big Booty Bitches"],
["Annika Norlin", "Failure"],
["Ascension", "Monsters"],
["Bonnie Prince Billy and Tortoise", "Pancho"],
["Brandi Carlile", "Raise Hell"],
["Britt Daniel", "Let the Distance Bring Us Together"],
["Cyn", "Drinks"],
["Dan Wriggins", "All Used Up"],
["Davey Dynamite & Absent", "Solidarity Forever"],
["Elliott Smith", "Strung Out Again"],
["Emperor X", "Sad React"],
["Girls", "Hellhole Ratrace"],
["Hercules & Love Affair", "Iris"],
["Iris DeMent", "Easy's Gettin' Harder Every Day"],
["Iris DeMent", "Let the Mystery Be"],
["Iris DeMent", "Wasteland of the Free"],
["Joanna Newsom", "Inflammatory Writ"],
["Jukebox The Ghost", "Jumpstarted"],
["Kevin Devine", "Splittin’ Up Christmas"],
["Kirin J Callinan", "Life Is Life"],
["MJ Lenderman", "TLC Cagematch"],
["Molly Hatchet", "Sailor"],
["Necro", "Pussy Is My Weakness"],
["Nevermore", "The Heart Collector"],
["New Found Glory", "Sincerely Me"],
["New Radicals", "I Hope I Didn't Just Give Away The Ending"],
["No Doubt", "Six Feet Under"],
["Petey", "Dont Tell The Boys"],
["Randy Newman", "A Wedding in Cherokee County"],
["Reverend Horton Heat", "Wiggle Stick"],
["Rough Cutt", "Dreamin' Again"],
["Steve Earle", "Christmas in Washington"],
["The Buttertones", "Baby Doll"],
["The Buttertones", "Eros"],
["Whiskey Myers", "Broken Window Serenade"],
["Yoko Kanno", "Whats it For"],
["Mac McCaughan & Annie Hayden", "Down We Go"],
["The Buttertones", "You and Your Knife"],
["The Doubleclicks", "Really Big Chickens"],
["Tony All", "At The Party"],
["Tony All", "Guitar Case"],
["Velvet Pony", "LESBIAN PONIES WITH WEAPONS"],
["Waxahatchee", "Noccalula"],
["David Bowie", "I Know It’s Gonna Happen Someday"],
["Mary Heather Hickman", "Treasure"],
["Ray Price", "The Wind Beneath My Wings"],
["The Avett Brothers", "Ain't No Man"],
["Dropout Kings", "Scratch & Claw"],
["Gogol Bordello", "Not a Crime"],
["Sparks", "Girl from Germany"],
["Sparks", "Under the Table with Her"],
["Streetlight Manifesto", "One Foot on the Gas, One Foot in the Grave"],
["The Doors", "Not to touch the earth"],
["Weird Al Yankovic", "Money for Nothing Beverly Hillbillies"],
["Adam Sandler", "Mr. Bake-O"],
["Eydie Gormé", "The Gentleman is a Dope"],
["Eydie Gormé", "What Did I Have That I Don't Have"],
["Rickie Lee Jones", "The Ballad Of The Sad Young Men"],
["Eddie Cochran", "Three Stars"],
["Lil Durk", "Broadway Girls"],
["Luude", "Down Under"],
[
"Taylor Swift",
"We Are Never Ever Getting Back Together (Taylor's Version)"
],
["The Fray", "Never Say Never"],
["The Ghost Club", "See Below"],
["General Levy", "Incredible (50% Volume Vocals)"],
["General Levy", "Incredible"],
["Marilyn Dagenais", "Chanson pour Papa"],
["Royal Navy", "Heart of Oak"],
["Tiamat", "Cain"],
["Marilyn Dagenais", "You Make Me Sing"],
["Young and Restless", "B Girls"],
["Bug Hunter", "Pinecones"],
["Streetlight Manifesto", "With Any Sort of Certainty"],
["Marvin Gaye", "God is Love"],
["Ben&Ben", "Maybe the Night"],
["Blink 182", "Fell In Love"],
["Blink 182", "Turpentine"],
["Bryson Tiller", "Right My Wrongs"],
["Chris Stapleton", "Joy of My Life"],
["Marilyn Dagenais", "L'hiver"],
["Metric", "Who Would You Be For Me"],
["Rex Orange County", "Happiness"],
["Sheff G", "Weight on Me"],
["Taylor Swift", "I Knew You Were Trouble (Taylor's Version)"],
["Taylor Swift", "You Belong With Me (Taylor's Version)"],
["The 1975", "Robbers"],
["Unknown", "Before the Screen Reads Fin"],
["ACDC", "Gone Shootin'"],
["Ozzy Osbourne", "You're No Different"],
["Alice Cooper", "He's Back (The Man Behind The Mask)"],
["Echo and The Bunnymen", "New Direction"],
["Iggy Pop", "Tell Me a Story"],
["Left Boy", "Security Check"],
["The Lemonheads", "If I Could Talk I’d Tell You"],
["They Might Be Giants", "Dinner Bell"],
["XTC", "Scissor Man"],
["XTC", "The Smartest Monkeys"],
["Marilyn Dagenais", "Un peu de lumière"],
["Bad Lip Reading", "Black Umbrella"],
["Bruno Mars", "The Lazy Song (Non-Lazy Parody)"],
["Marilyn Dagenais", "Si je t'aime"],
["Jerry Lee Lewis", "Meat Man"],
["Shovels & Rope", "Birmingham"],
["Wolfe Tones", "Rock On Rockall"],
["James Rado", "Where Do I Go? (From Hair)"],
["Andrea Bocelli", "Gloria in Excelsis Deo"],
["ABBA", "The Day Before You Came"],
["Fleet Foxes", "He Doesn’t Know Why"],
["The Drifters", "Up On The Roof"],
["The Seekers", "California Dreamin'"],
["Fleet Foxes", "Silver Dagger"],
["She Wants Revenge", "Broken Promises For Broken Hearts"],
["Ken Ashcorp", "On The Rocks"],
["Z-Ro", "Mo City Don Freestyle"],
["The Time", "Cool"],
["Urban Cookie Collective", "The Key, The Secret"],
["Melissa Etheridge", "Meet Me In The Back"],
["Garfunkel And Oates", "I Get to Do It With You"],
["A Fine Frenzy", "Come On, Come Out"],
["A Fine Frenzy", "Rangers"],
["Ken Ashcorp", "PVP"],
["A Fine Frenzy", "Almost Lover"],
["A Fine Frenzy", "You Picked Me"],
["Peach PRC", "God Is A Freak"],
["Righteous Brothers", "See That Girl"],
["Blue Eyed Blondes", "Maneater"],
["piri & tommy", "on & on"],
["Sudley ft. piri", "fumble"],
["A Fine Frenzy", "Ashes And Wine"],
["A Fine Frenzy", "The Minnow & The Trout"],
["Tame Impala", "The Boat I Row"],
["Spinal Tap", "Rainy Day Sun"],
["Röyksopp", "Running To The Sea"],
["Röyksopp", "Oh, Lover"],
["Röyksopp", "Monument"],
["Röyksopp", "Only This Moment"],
["Röyksopp", "The Girl And The Robot"],
["Röyksopp", "49 Percent"],
["Maisi & piri", "head"],
["Django Django", "Default"],
["Django Django", "Hail Bop"],
["piri & tommy", "silver lining"],
["Daniel O'Donnell", "Galway Bay"],
["Daniel O'Donnell", "I'll Take You Home Again Kathleen"],
["Daniel O'Donnell", "Mountains of Mourne"],
[
"Daniel O'Donnell",
"Medley: It's a Long Way to Tipperary / Pack up Your Troubles / If You're Irish, Come into the Parlour"
],
["Jackson Singleton", "Disguise"],
["Ken Ashcorp", "Dare You To Love Me"],
["A Fine Frenzy", "Borrowed Time"],
["A Fine Frenzy", "Last Of Days"],
["A Fine Frenzy", "Hope For The Hopeless"],
["A Fine Frenzy", "Liar, Liar"],
["A Fine Frenzy", "Lifesize"],
["A Fine Frenzy", "Near To You"],
["A Fine Frenzy", "Think Of You"],
["A Fine Frenzy", "Whisper"],
["piri & tommy", "settle"],
["piri & tommy", "soft spot"],
["piri & tommy", "sunlight"],
["piri & tommy", "beachin"],
["piri & tommy", "player 2"],
["piri & tommy", "can we"],
["piri & tommy", "easy"],
["piri & tommy", "say it"],
["piri & tommy", "slowly but surely"],
["piri & tommy", "words"],
["piri & tommy", "nice 2 me"],
["Tony Bennett & k.d.lang", "What A Wonderful World"],
["Ying Yang Twins", "Georgia Dome"],
[
"Daniel O'Donnell",
"Medley: Galway Bay, The Mountains Of Mourne, I'll Take You Home Again Kathleen"
],
["The Beatles", "In My Life"],
["Truck Stop", "Komm her du bist mein Cowboy"],
["Linda Feller", "Du gabst ihr deinen Namen"],
["Victoria OB", "Yeshua"],
["Matthew Morrison", "Somewhere Over the Rainbow"],
["fun.", "Benson Hedges"],
["fun.", "All the Pretty Girls"],
["fun.", "At Least I'm Not as Sad (As I Used to Be)"],
["fun.", "I Wanna Be the One"],
["fun.", "Walking the Dog"],
["fun.", "Light a Roman Candle with Me"],
["fun.", "Barlights"],
["fun.", "Take Your Time (Coming Home)"],
["Tom Astor", "Sturm Und Drang"],
["Titellied der gleichnamigen Fernsehserie 1962", "Bonanza"],
["Linda Feller", "Billy Bob's Texas"],
["ABBA", "Dancing Queen"],
["Ken Ashcorp", "Touch Fluffy Tail"],
["Mavi Phoenix", "Pretty Life (Whsprs Cover)"],
["Jimi Hendrix", "Remember"],
["Smash Mouth", "All Star"],
["Smash Mouth", "All Star (with Shrek)"],
["The Silent Comedy", "Enemies Multiply"],
["ABBA", "Ring Ring"],
["ABBA", "Another Town, Another Train"],
["ABBA", "Disillusion"],
["ABBA", "People Need Love"],
["Frank Sinatra", "New York, New York"],
["ABBA", "I Saw It In The Mirror"],
["ABBA", "Nina, Pretty Ballerina"],
["ABBA", "Love Isn’t Easy (But It Sure Is Hard Enough)"],
["ABBA", "Me And Bobby And Bobby’s Brother"],
["ABBA", "He Is Your Brother"],
["ABBA", "She’s My Kind Of Girl"],
["ABBA", "I Am Just A Girl"],
["ABBA", "Rock ’N Roll Band"],
["ABBA", "Ring Ring (Bara Du Slog En Signal) (Swedish Version)"],
["ABBA", "Åh, Vilka Tider"],
["ABBA", "Merry‐Go‐Round"],
["ABBA", "Santa Rosa"],
["ABBA", "Ring Ring (Spanish Version)"],
["ABBA", "Wer Im Wartesaal Der Liebe Steht"],
["ABBA", "Ring Ring (German Version)"],
["Fleet Foxes", "Montezuma"],
["Harald Juhnke", "Berlin, Berlin"],
["Shoshana Bean", "Strange Thunder"],
["Michael Callen", "Crazy World"],
["Michael Callen", "Wish I Had A Dime"],
["The Blasters", "One Bad Stud"],
["Michael Callen", "The Healing Power Of Love"],
["Meat Loaf", "Braver Than We Are"],
["Harald Juhnke", "Berlin, Berlin (Lisa, Milan)"],
["Friday", "The Ballad Of Skinny Linguine"],
["Emery", "The Ponytail Parades"],
["Black Sabbath", "Buried Alive"],
["Aloha from space", "Storm Troopin'"],
["NerdOut", "Bounty"],
["Charles Strouse and Lee Adams", "Han's Your Man"],
["Juliane Werding", "Man muß Das Leben Eben Nehmen, Wie Das Leben Eben Ist"],
["Aurelio Voltaire", "Butterfly"],
["Blind Guardian", "Violent Shadows"],
["Jonny Hill & Linda Feller", "Zusammenstehn (Duet)"],
["Tori Amos", "Big Wheel"],
["Chairlift", "Bruises"],
["Jonny Hill & Linda Feller", "London"],
["Life Languages", "The Mover Song"],
["Life Languages", "The Responder Song"],
["Life Languages", "The Contemplator Song"],
["Life Languages", "The Doer Song"],
["Life Languages", "The Shaper Song"],
["Life Languages", "The Influencer Song"],
["Life Languages", "The Producer Song"],
["The Amazing Devil", "That Unwanted Animal"],
["Bobby Capo", "Locamente Enamorado"],
["Dagmar", "Lass mich damit bloß in Ruhe"],
["Los Campesinos!", "You! Me! Dancing! (Daytrotter Session)"],
["Joe P", "Leaves"],
["ABBA", "Waterloo"],
["ABBA", "Sitting In The Palmtree"],
["ABBA", "King Kong Song"],
["ABBA", "Hasta Mañana"],
["ABBA", "My Mama Said"],
["ABBA", "Dance (While The Music Still Goes On)"],
["ABBA", "Honey, Honey"],
["Thomas Borchert", "I Know Those Eyes / This Man Is Dead (Duet)"],
[
"Thomas Borchert",
"I Know Those Eyes / This Man Is Dead (Duet With Female Vocals)"
],
["SHE WANTS REVENGE", "Rachael"],
["Matt Redmond", "Unbroken Praise"],
["Ian McConnell", "Level 429"],
["ABBA", "Watch Out"],
["ABBA", "What About Livingstone"],
["Ten Years After", "Outside My Window"],
["ABBA", "Gonna Sing You My Lovesong"],
["ABBA", "Suzy-Hang-Around"],
["ABBA", "Waterloo (Swedish Version)"],
["ABBA", "Honey, Honey (Swedish Version)"],
["ABBA", "Waterloo (German Version)"],
["ABBA", "Hasta Mañana (Spanish Version)"],
["ABBA", "Waterloo (French Version)"],
["ABBA", "Mamma Mia"],
["ABBA", "Hey, Hey Helen"],
["ABBA", "Tropical Loveland"],
["ABBA", "S.O.S."],
["ABBA", "Man In The Middle"],
["ABBA", "Bang-A-Boomerang"],
["ABBA", "I Do, I Do, I Do, I Do, I Do"],
["ABBA", "Rock Me"],
["ABBA", "I’ve Been Waiting For You"],
["ABBA", "So Long"],
["ABBA", "Crazy World"],
["ABBA", "Medley (1978 Mix)"],
["ABBA", "Mamma Mia (Spanish Version)"],
["Marina and The Diamonds", "Froot"],
["Maxton Waller", "On My Way (Marching Band)"],
["100 gecs", "mememe"],
["Stuck Out Here", "Embarrass You"],
["DCSane", "Heart's Whiskey"],
["Release", "Devil's Handshake"],
["Kelly Clarkson", "Since U Been Gone (Pitch -3: E major)"],
["Justin Townes Earle", "Rogers Park"],
["Armin van Buuren ft. Teddy Swims", "Easy To Love"],
["Willie Nelson", "One More Song to Write"],
["Will Varley", "Seize The Night"],
["Passenger", "However It Comes, Wherever It Goes"],
["Ricky Braddy", "Anyone (Acoustic Cover of Demi Lovato)"],
["Bryan Adams", "Help Me Make It Through The Night"],
["Ivan Rivers", "Mid-Riff"],
["Kane Brown", "American Bad Dream"],
["Mother Mother", "Ghosting"],
["Charlie Terrell", "Libby Anna"],
["Taylor Swift", "Fortnight (feat. Post Malone)"],
["The Gaslight Anthem", "National Anthem"],
["The Lonely Island", "Semicolon (feat. Solange)"],
["Lucky Daye", "Algorithm"],
["The Black Eyed Peas", "They Don't Want Music"],
["Tiger Really", "Fundamentally Unlovable"],
["Da Ali G Show", "Jarvis Cocker"],
["Colin Hay", "Send Somebody (Stripped Mix)"],
["Ernie Taylor", "I Ain't Leavin' Yet"],
["Smashing Pumpkins", "Here Is No Why"],
["Drake", "Virginia Beach"],
["Maverick City Music", "I Thank God"],
["Ax and the Hatchetmen", "Drive-in Movie"],
["Faith No More", "Das Schutzenfest"],
["Miguel", "Use Me"],
["Ivan Rivers", "Sad Around Me"],
["Young The Giant", "Both Sides Now"],
["Jimmy Buffett", "Bob Robert's Society Band"],
["buildspace, MAYV", "the end"],
["Frank Turner", "A Wave Across A Bay"],
["Angel Olsen", "Eyes Without A Face"],
["Deven May", "The Sensitive Song (from Cops)"],
["The Mountain Goats", "Night Light"],
["Steppenwolf", "Born To Be Wild"],
["Bobby Solo", "O sole mio"],
["HCA West", "Driving Quality"],
["Engelbert Humperdinck", "Marry Me"],
["Mark Knopfler", "Are We in Trouble Now"],
["Danny Pynes", "One Night in Spain"],
["The Butterfly Effect", "I’m Not Okay"],
["The Sonic Bridges", "Sweet Evelyn"],
["Carrie and Jake", "Wedding Medley"],
["Gregory Porter", "Insanity (feat. Lalah Hathaway)"],
["Linda Feller", "Ich weiss genau, was ich will"],
["Mikey Chuck Rivers", "She's Cryin' (I'm Drunk Again)"],
["Gregory Porter", "Insanity (feat. Lalah Hathaway) (Duet)"],
["Country Rose", "Spaß Am Leben"],
["Tom Astor", "Du bist da (wenn's drum geht)"],
["Linda Feller", "Wenn überhaupt, dann nur Country"],
["Alabama", "The Fans"],
["Ghost Brothers", "What Kind Of Man Am I"],
["The Stand", "Baby, Can You Dig Your Man"],
["Nu Shooz", "I Can't Wait"],
["Freddie Jackson", "All I'll Ever Ask (feat. Najee)"],
["Linda Feller", "Du bist das Salz in meiner Suppe"],
["Claudia Jung, Tom Astor", "Wer Liebe Sucht"],
["The Smashing Pumpkins", "Tales of a Scorched Earth"],
["The Smashing Pumpkins", "Thru the Eyes of Ruby"],
["Tom Astor", "Geistertruck"]
]
+151
View File
@@ -0,0 +1,151 @@
import os
import json
import logging
from karaoke_prep.karaoke_prep import KaraokePrep
# Set up logging
logger = logging.getLogger(__name__)
log_handler = logging.StreamHandler()
log_formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
log_handler.setFormatter(log_formatter)
logger.addHandler(log_handler)
logger.setLevel(logging.DEBUG)
# Define the artist/title combinations
def total_length(tuple):
artist, title = tuple
return len(artist) + len(title)
with open("data/artist-titles.json", "r", encoding="utf-8") as f:
all_combinations = json.load(f)
# Sort by length and get shortest and longest 20
sorted_combinations = sorted(all_combinations, key=total_length)
artist_title_combinations = sorted_combinations[:10] + sorted_combinations[-10:]
# Define the format dictionary with expanded configurations
formats = [
{
"name": "vocalstar",
"intro_background_image": "/Users/andrew/AB Dropbox/Andrew Beveridge/MediaUnsynced/Karaoke/Tracks-NonPublished/VocalStar/Resources/vocal-star-title-background-black.4k.png",
"end_background_image": "/Users/andrew/AB Dropbox/Andrew Beveridge/MediaUnsynced/Karaoke/Tracks-NonPublished/VocalStar/Resources/vocal-star-end-card-black.4k.png",
"font": "Zurich_Cn_BT_Bold.ttf",
"artist_color": "#FCDF01",
"title_color": "#FCDF01",
"intro_title_region": "370,470,3100,480",
"intro_artist_region": "370,1210,3100,480",
"intro_extra_text": "GET READY TO SING!",
"intro_extra_text_color": "#FFFFFF",
"intro_extra_text_region": "370,1800,3100,280",
"end_title_region": "370,670,3100,480",
"end_artist_region": "370,1410,3100,480",
"end_extra_text": "THANK YOU FOR SINGING!",
"end_extra_text_color": "#FFFFFF",
"end_extra_text_region": "370,1800,3100,280",
},
{
"name": "nomadkaraoke",
"intro_background_image": "/Users/andrew/AB Dropbox/Andrew Beveridge/MediaUnsynced/Karaoke/NomadBranding/karaoke-title-screen-background-nomad-4k.png",
"end_background_color": "#000000", # Using solid color for end screen
"font": "AvenirNext-Bold.ttf",
"artist_color": "#FFFFFF",
"title_color": "#ffdf6b",
"intro_title_region": "370,950,3100,350",
"intro_artist_region": "370,1350,3100,450",
"intro_extra_text": None, # No extra text on intro
"end_title_region": "370,800,3100,350",
"end_artist_region": "370,1200,3100,450",
"end_extra_text": "Follow us @NomadKaraoke",
"end_extra_text_color": "#ffdf6b",
"end_extra_text_region": "370,1700,3100,280",
},
{
"name": "minimal",
"intro_background_color": "#000033",
"end_background_color": "#000033",
"font": "Montserrat-Bold.ttf",
"artist_color": "#FFFFFF",
"title_color": "#ffdf6b",
"intro_title_region": "370,800,3100,400",
"intro_artist_region": "370,1300,3100,400",
"intro_extra_text": None, # No extra text on either screen
"end_title_region": "370,800,3100,400",
"end_artist_region": "370,1300,3100,400",
"end_extra_text": None,
},
]
# Define other parameters
base_output_dir = "outputs"
os.makedirs(base_output_dir, exist_ok=True)
# Process each format
for format in formats:
# Create format-specific output directory
format_output_dir = os.path.join(base_output_dir, format["name"])
os.makedirs(format_output_dir, exist_ok=True)
# Instantiate KaraokePrep for this format
kprep = KaraokePrep(
log_level=logging.INFO,
log_formatter=log_formatter,
output_dir=format_output_dir,
intro_background_image=format.get("intro_background_image"),
intro_background_color=format.get("intro_background_color", "#000000"),
end_background_image=format.get("end_background_image"),
end_background_color=format.get("end_background_color", "#000000"),
intro_font=format["font"],
end_font=format["font"],
intro_artist_color=format["artist_color"],
intro_title_color=format["title_color"],
end_artist_color=format["artist_color"],
end_title_color=format["title_color"],
intro_title_region=format.get("intro_title_region"),
intro_artist_region=format.get("intro_artist_region"),
intro_extra_text=format.get("intro_extra_text"),
intro_extra_text_color=format.get("intro_extra_text_color"),
intro_extra_text_region=format.get("intro_extra_text_region"),
end_title_region=format.get("end_title_region"),
end_artist_region=format.get("end_artist_region"),
end_extra_text=format.get("end_extra_text"),
end_extra_text_color=format.get("end_extra_text_color"),
end_extra_text_region=format.get("end_extra_text_region"),
intro_video_duration=0,
end_video_duration=0,
render_bounding_boxes=True,
output_jpg=False,
output_png=True,
)
# Run the create_title_video and create_end_video functions for each combination
for artist, title in artist_title_combinations:
sanitized_artist = kprep.sanitize_filename(artist)
sanitized_title = kprep.sanitize_filename(title)
# Generate title video
title_image_filepath_noext = os.path.join(format_output_dir, f"{sanitized_artist}_{sanitized_title}_title")
title_video_filepath = os.path.join(format_output_dir, f"{sanitized_artist}_{sanitized_title}_title.mov")
kprep.create_title_video(
artist=artist,
title=title,
format=kprep.title_format,
output_image_filepath_noext=title_image_filepath_noext,
output_video_filepath=title_video_filepath,
)
logger.info(f"Created title video for {artist} - {title} using {format['name']} format")
# Generate end video
end_image_filepath_noext = os.path.join(format_output_dir, f"{sanitized_artist}_{sanitized_title}_end")
end_video_filepath = os.path.join(format_output_dir, f"{sanitized_artist}_{sanitized_title}_end.mov")
kprep.create_end_video(
artist=artist,
title=title,
format=kprep.end_format,
output_image_filepath_noext=end_image_filepath_noext,
output_video_filepath=end_video_filepath,
)
logger.info(f"Created end video for {artist} - {title} using {format['name']} format")