mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-02 01:48:08 +09:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
242c1e03ac | ||
|
|
ade7c40af7 | ||
|
|
162faa9189 |
No files matched your search
@@ -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
@@ -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
@@ -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 |
File renamed without changes.
File renamed without changes.
@@ -42,6 +42,7 @@ class KaraokeFinalise:
|
||||
discord_webhook_url=None,
|
||||
non_interactive=False,
|
||||
email_template_file=None,
|
||||
cdg_styles=None,
|
||||
):
|
||||
self.logger = logging.getLogger(__name__)
|
||||
self.logger.setLevel(log_level)
|
||||
@@ -124,6 +125,8 @@ class KaraokeFinalise:
|
||||
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...")
|
||||
|
||||
@@ -467,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}")
|
||||
@@ -606,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...")
|
||||
|
||||
@@ -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
|
||||
@@ -119,6 +120,12 @@ def main():
|
||||
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())
|
||||
@@ -126,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,
|
||||
@@ -143,6 +166,7 @@ def main():
|
||||
rclone_destination=args.rclone_destination,
|
||||
discord_webhook_url=args.discord_webhook_url,
|
||||
email_template_file=args.email_template_file,
|
||||
cdg_styles=cdg_styles,
|
||||
)
|
||||
|
||||
if args.test_email_template:
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-prep"
|
||||
version = "0.30.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"
|
||||
|
||||
Reference in new issue
Block a user