Compare commits

..
34 Commits
Author SHA1 Message Date
Andrew Beveridge 42647a7c36 Updated to latest lyrics-transcriber, updated dependencies, added graceful exit and other improvements 2025-02-19 00:55:43 -05:00
Andrew Beveridge cbc6470d3d Updated to latest lyrics-transcriber 2025-02-09 01:00:22 -05:00
Andrew Beveridge 0adc69ed75 Added audacity open and subtitle offset features 2025-02-09 00:52:51 -05:00
Andrew Beveridge b17440fd21 Removed lrc to cdg standalone functionality, now fully integrated with lyrics_transcriber CDGGenerator class 2025-02-07 00:05:14 -05:00
Andrew Beveridge 08b8abf27d Added lrc-to-cdg CLI with consistent styles JSON handling 2025-02-06 11:22:57 -05:00
Andrew Beveridge 1b62b396cb Removed cdgmaker code, migrated to using directly from python-lyrics-transcriber package 2025-02-05 23:27:43 -05:00
Andrew Beveridge f249a841e1 Fixed artist/title filename sanitization in auto mode 2025-02-05 02:18:02 -05:00
Andrew Beveridge 0f8eb3f6d4 Added strip to inputs from csv to fix bug 2025-02-03 00:55:57 -05:00
Andrew Beveridge 586763ae5f Updated bulk CLI 2025-02-03 00:47:01 -05:00
Andrew Beveridge 6092a67ef4 Updated to use latest lyrics transcriber. Added full auto and bulk processing modes. Added ability to pass in existing lyrics input file. 2025-02-02 22:35:16 -05:00
Andrew Beveridge 951b64eaf5 Bumped deps 2025-02-01 00:07:37 -05:00
Andrew Beveridge 78f7412d2d Fixed file rename, updated lyrics transcriber 2025-01-28 15:50:43 -05:00
Andrew Beveridge ef54ba9dc5 Lock poetry 2025-01-28 14:56:10 -05:00
Andrew Beveridge 481a57e0e1 Downgrade torch for now 2025-01-28 14:55:38 -05:00
Andrew Beveridge af5db142ef Move output files from transcriber to parent dir 2025-01-28 14:10:30 -05:00
Andrew Beveridge 54a48cef39 Bumped version for release 2025-01-28 01:00:33 -05:00
Andrew Beveridge 1663f229a3 Improved error handling with invalid inputs 2025-01-28 00:27:00 -05:00
Andrew Beveridge 87ed4799e5 Fixed parameters for integration with LyricsTranscriber 2025-01-27 23:47:04 -05:00
Andrew Beveridge a7a96f2f4b Added non-interactive mode to finalise 2025-01-22 17:37:33 -05:00
Andrew Beveridge 07ee85b304 Made work with MKV input 2025-01-20 00:16:43 -05:00
Andrew Beveridge 595fbbc4e2 Fixed filepaths to copy after moving org dir 2025-01-17 10:40:41 -05:00
Andrew Beveridge dfdbd92269 Added --keep-brand-code param 2025-01-17 01:13:09 -05:00
Andrew Beveridge 78f8880922 Added more output files to CLI output, copy youtube URL and folder sharing link to clipboard automatically 2025-01-15 11:48:24 -05:00
Andrew Beveridge 17be398a0f Reordered remuxing to leave no unnecessarily large files whilst retaining pure PCM audio in all output MP4 files 2025-01-14 21:27:40 -05:00
Andrew Beveridge ee9958bfe9 Improved text rendering size calculation to make text fill more of the region bounding box areas 2024-12-28 04:08:56 -05:00
Andrew Beveridge fc5eabb588 Added gradients, text transforms, and better font size calculation 2024-12-28 03:34:31 -05:00
Andrew Beveridge 4883a93603 Added support for configurable gradients and text transforms 2024-12-28 03:09:00 -05:00
Andrew Beveridge 5d8b697c61 Made styles configurable by JSON config file with combined config for prep and CDG in finalise, etc. 2024-12-28 02:30:09 -05:00
Andrew Beveridge 94ea24bfea Moved lyrics processing into LyricsTranscriber, added MKV output file with lossless audio, used that for upload to YouTube to improve audio quality 2024-12-27 16:00:12 -05:00
Andrew Beveridge 42fc646954 Fixed broken return in separation, transcriber dependency 2024-12-27 01:55:16 -05:00
Andrew Beveridge bd6db70bcf Updated dependencies, modified prep to use latest version of transcriber and rely on lyrics outputs from that rather than duplicating genius fetch logic etc. 2024-12-27 01:29:52 -05:00
Andrew Beveridge 242c1e03ac Improved cdg maker to have configurable styles 2024-12-26 00:03:50 -05:00
Andrew Beveridge ade7c40af7 Updated to check for fonts in the fonts dir 2024-12-25 00:31:03 -05:00
Andrew Beveridge 162faa9189 Updated cdg generation to use parameters 2024-12-25 00:05:24 -05:00
38 changed files with 4482 additions and 5807 deletions

No files matched your search

+2
View File
@@ -1,6 +1,8 @@
# Andrew env
.DS_Store
.vscode
*.csv
*.mp3
# Andrew functional adds
audio/
View File
Whitespace-only changes.
-262
View File
@@ -1,262 +0,0 @@
from collections.abc import Sequence
from enum import Enum
from typing import BinaryIO, NamedTuple, TypeAlias
from .utils import *
_RGBColor: TypeAlias = tuple[int, int, int]
CDG_COMMAND = 0x09
# TODO Find out how to store proper parity bytes
CDG_PARITY = 0xa5
CDG_MASK = 0x3f
CDG_SCREEN_WIDTH = 300
CDG_SCREEN_HEIGHT = 216
CDG_VISIBLE_WIDTH = 280
CDG_VISIBLE_HEIGHT = 192
CDG_VISIBLE_X = 6
CDG_VISIBLE_Y = 12
CDG_TILE_WIDTH = 6
CDG_TILE_HEIGHT = 12
CDG_FPS = 300
class CDGInstruction(Enum):
NO_INSTRUCTION = 0x00
MEMORY_PRESET = 0x01
BORDER_PRESET = 0x02
TILE_BLOCK = 0x06
SCROLL_PRESET = 0x14
SCROLL_COPY = 0x18
DEFINE_TRANSPARENT = 0x1c
LOAD_COLOR_TABLE_LO = 0x1e
LOAD_COLOR_TABLE_HI = 0x1f
TILE_BLOCK_XOR = 0x26
class CDGScrollCommand(Enum):
NO_SCROLL = 0
SCROLL_RIGHT = 1
SCROLL_DOWN = 1
SCROLL_AHEAD = 1
SCROLL_LEFT = 2
SCROLL_UP = 2
SCROLL_BACK = 2
class CDGPacket(NamedTuple):
command: bool
instruction: CDGInstruction
data: bytes
class CDGWriter:
def __init__(self):
self.packets: list[CDGPacket] = []
def queue_packet(self, packet: CDGPacket):
self.packets.append(packet)
def queue_packets(self, packets: Sequence[CDGPacket]):
for packet in packets:
self.queue_packet(packet)
@property
def packets_queued(self) -> int:
return len(self.packets)
def write_packets(self, stream: BinaryIO):
for packet in self.packets:
self.write_packet(stream, packet)
def write_packet(self, stream: BinaryIO, packet: CDGPacket):
stream.write((CDG_COMMAND if packet.command else 0x00).to_bytes())
stream.write(packet.instruction.value.to_bytes())
stream.write(CDG_PARITY.to_bytes() * 2)
stream.write(packet.data)
stream.write(CDG_PARITY.to_bytes() * 4)
def no_instruction() -> CDGPacket:
return CDGPacket(
command=False,
instruction=CDGInstruction.NO_INSTRUCTION,
data=b"\x00" * 16,
)
def memory_preset(color: int, repeat: int = 0) -> CDGPacket:
return CDGPacket(
command=True,
instruction=CDGInstruction.MEMORY_PRESET,
data=bytes(pad(
[
color & 0xf,
repeat & 0xf,
],
16,
padvalue=0,
)),
)
def border_preset(color: int) -> CDGPacket:
return CDGPacket(
command=True,
instruction=CDGInstruction.BORDER_PRESET,
data=bytes(pad(
[
color & 0xf,
],
16,
padvalue=0,
)),
)
def tile_block(
color0: int,
color1: int,
row: int,
column: int,
tile: Sequence[int],
) -> CDGPacket:
assert len(tile) == 12, "tile must have 12 rows"
return CDGPacket(
command=True,
instruction=CDGInstruction.TILE_BLOCK,
data=bytes([
color0 & 0xf,
color1 & 0xf,
row & 0x1f,
column & 0x3f,
*[t & 0x3f for t in tile],
]),
)
def scroll_preset(
color: int = 0,
hcmd: CDGScrollCommand = CDGScrollCommand.NO_SCROLL,
hoffset: int = 0,
vcmd: CDGScrollCommand = CDGScrollCommand.NO_SCROLL,
voffset: int = 0,
) -> CDGPacket:
return CDGPacket(
command=True,
instruction=CDGInstruction.SCROLL_PRESET,
data=bytes(pad(
[
color & 0xf,
(hcmd.value << 4) | (hoffset & 0x7),
(vcmd.value << 4) | (voffset & 0xf),
],
16,
padvalue=0,
)),
)
def scroll_copy(
color: int = 0,
hcmd: CDGScrollCommand = CDGScrollCommand.NO_SCROLL,
hoffset: int = 0,
vcmd: CDGScrollCommand = CDGScrollCommand.NO_SCROLL,
voffset: int = 0,
) -> CDGPacket:
return CDGPacket(
command=True,
instruction=CDGInstruction.SCROLL_COPY,
data=bytes(pad(
[
color & 0xf,
(hcmd.value << 4) | (hoffset & 0x7),
(vcmd.value << 4) | (voffset & 0xf),
],
16,
padvalue=0,
)),
)
def define_transparent(levels: Sequence[int]) -> CDGPacket:
assert len(levels) == 16, "must load 16 transparency levels"
return CDGPacket(
command=True,
instruction=CDGInstruction.DEFINE_TRANSPARENT,
data=bytes([level & CDG_MASK for level in levels]),
)
def load_color_table_lo(colors: Sequence[_RGBColor]) -> CDGPacket:
assert len(colors) == 8, "must load 8 colors into low table"
return CDGPacket(
command=True,
instruction=CDGInstruction.LOAD_COLOR_TABLE_LO,
data=b"".join(map(_rgb_to_bytes, colors)),
)
def load_color_table_hi(colors: Sequence[_RGBColor]) -> CDGPacket:
assert len(colors) == 8, "must load 8 colors into high table"
return CDGPacket(
command=True,
instruction=CDGInstruction.LOAD_COLOR_TABLE_HI,
data=b"".join(map(_rgb_to_bytes, colors)),
)
def tile_block_xor(
color0: int,
color1: int,
row: int,
column: int,
tile: Sequence[int],
) -> CDGPacket:
assert len(tile) == 12, "tile must have 12 rows"
return CDGPacket(
command=True,
instruction=CDGInstruction.TILE_BLOCK_XOR,
data=bytes([
color0 & 0xf,
color1 & 0xf,
row & 0x1f,
column & 0x3f,
*[t & 0x3f for t in tile],
]),
)
def memory_preset_repeat(color: int) -> list[CDGPacket]:
return [
memory_preset(color, repeat)
for repeat in range(16)
]
def load_color_table(colors: Sequence[_RGBColor]) -> list[CDGPacket]:
assert len(colors) == 16, "must load 16 colors into table"
return [
load_color_table_lo(colors[:8]),
load_color_table_hi(colors[8:]),
]
def _rgb_to_bytes(rgb: _RGBColor) -> bytes:
r, g, b = rgb
hi = ((r & 0xf0) >> 2) | ((g & 0xc0) >> 6)
lo = (g & 0x30) | ((b & 0xf0) >> 4)
return bytes([hi, lo])
__all__ = [
"CDG_COMMAND", "CDG_PARITY", "CDG_MASK",
"CDG_SCREEN_WIDTH", "CDG_SCREEN_HEIGHT",
"CDG_VISIBLE_WIDTH", "CDG_VISIBLE_HEIGHT",
"CDG_VISIBLE_X", "CDG_VISIBLE_Y",
"CDG_TILE_WIDTH", "CDG_TILE_HEIGHT",
"CDG_FPS",
"CDGInstruction", "CDGScrollCommand", "CDGPacket",
"CDGWriter",
"no_instruction", "memory_preset", "border_preset", "tile_block",
"scroll_preset", "scroll_copy", "define_transparent",
"load_color_table_lo", "load_color_table_hi", "tile_block_xor",
"memory_preset_repeat", "load_color_table",
]
-1907
View File
File diff suppressed because it is too large. Load diff
-131
View File
@@ -1,131 +0,0 @@
from enum import StrEnum
from pathlib import Path
from typing import Any, TypeAlias
from attrs import define, field
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
if isinstance(val, str):
return ImageColor.getrgb(val)[:3]
raise TypeError("color value not convertible to RGBColor or None")
class LyricClearMode(StrEnum):
PAGE = "page"
LINE_EAGER = "eager"
LINE_DELAYED = "delayed"
class TextAlign(StrEnum):
LEFT = "left"
CENTER = "center"
RIGHT = "right"
class TextPlacement(StrEnum):
TOP_LEFT = "top left"
TOP_MIDDLE = "top middle"
TOP_RIGHT = "top right"
MIDDLE_LEFT = "middle left"
MIDDLE = "middle"
MIDDLE_RIGHT = "middle right"
BOTTOM_LEFT = "bottom left"
BOTTOM_MIDDLE = "bottom middle"
BOTTOM_RIGHT = "bottom right"
class StrokeType(StrEnum):
CIRCLE = "circle"
SQUARE = "square"
OCTAGON = "octagon"
@define
class SettingsInstrumental:
sync: int
line_tile_height: int
wait: bool = True
text: str = "INSTRUMENTAL"
text_align: TextAlign = TextAlign.CENTER
text_placement: TextPlacement = TextPlacement.MIDDLE
fill: RGBColor = field(converter=to_rgbcolor, default="#bbb")
stroke: RGBColor | None = field(
converter=to_rgbcolor_or_none,
default=None,
)
background: RGBColor | None = field(
converter=to_rgbcolor_or_none,
default=None,
)
image: Path | None = None
transition: str | None = None
x: int = 0
y: int = 0
@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")
@define
class SettingsLyric:
sync: list[int]
text: str
line_tile_height: int
lines_per_page: int
singer: int = 1
row: int = 1
@define
class Settings:
title: str
artist: str
file: Path
font: Path
title_screen_background: Path
outname: str = "output"
clear_mode: LyricClearMode = LyricClearMode.LINE_DELAYED
sync_offset: int = 0
highlight_bandwidth: int = 1
draw_bandwidth: int = 1
background: RGBColor = field(converter=to_rgbcolor, default="black")
border: RGBColor | None = field(
converter=to_rgbcolor_or_none,
default="black",
)
font_size: int = 18
stroke_width: int = 0
stroke_type: StrokeType = StrokeType.OCTAGON
instrumentals: list[SettingsInstrumental] = field(factory=list)
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")
__all__ = [
"RGBColor",
"LyricClearMode", "TextAlign", "TextPlacement", "StrokeType",
"SettingsInstrumental", "SettingsSinger", "SettingsLyric",
"Settings",
]
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

-360
View File
@@ -1,360 +0,0 @@
#!/usr/bin/env python3
import logging
import re
import toml
import argparse
from pathlib import Path
from cdgmaker.composer import KaraokeComposer
import sys
from PIL import ImageFont, Image
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"
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
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:
content = f.read()
# Extract timestamps and lyrics
pattern = r"\[(\d{2}):(\d{2})\.(\d{3})\](\d+:)?(/?.*)"
matches = re.findall(pattern, content)
if not matches:
raise ValueError(f"No valid lyrics found in the LRC file: {lrc_file}")
lyrics = []
for match in matches:
minutes, seconds, milliseconds = map(int, match[:3])
timestamp = (minutes * 60 + seconds) * 100 + int(milliseconds / 10) # Convert to centiseconds
text = match[4].strip().upper()
if text: # Only add non-empty lyrics
lyrics.append({"timestamp": timestamp, "text": text})
# logger.debug(f"Parsed lyric: {timestamp} - {text}")
logger.info(f"Found {len(lyrics)} lyric lines")
return lyrics
def detect_instrumentals(lyrics_data):
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:
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_align": "center",
"text_placement": "bottom middle",
"line_tile_height": DEFAULT_LINE_TILE_HEIGHT,
"fill": INSTRUMENTAL_FONT_COLOR,
"stroke": "",
"image": INSTRUMENTAL_BACKGROUND,
"transition": INSTRUMENTAL_TRANSITION,
}
)
logger.info(
f"Detected instrumental: Gap of {gap} cs, starting at {instrumental_start} cs, duration {instrumental_duration} seconds"
)
logger.info(f"Total instrumentals detected: {len(instrumentals)}")
return instrumentals
def generate_toml(lrc_file, audio_file, title, artist, output_file, row, line_tile_height, lines_per_page, title_color, artist_color):
try:
lyrics_data = parse_lrc(lrc_file)
except ValueError as e:
logger.error(f"Error parsing LRC file: {e}")
return
if not lyrics_data:
logger.error(f"No lyrics data found in the LRC file: {lrc_file}")
return
sync_times = []
formatted_lyrics = []
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
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
sync_times.append(sync_time)
formatted_lyrics.append(symbol)
logger.debug(f" Added lead-in symbol {j+1}: '{symbol}' at {sync_time}")
sync_times.append(lyric["timestamp"])
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)
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,
"singers": [
{"active_fill": ACTIVE_FILL, "active_stroke": ACTIVE_STROKE, "inactive_fill": INACTIVE_FILL, "inactive_stroke": INACTIVE_STROKE}
],
"lyrics": [
{
"singer": 1,
"sync": sync_times,
"row": row,
"line_tile_height": line_tile_height,
"lines_per_page": lines_per_page,
"text": formatted_lyrics,
}
],
"title_color": title_color,
"artist_color": artist_color,
"title_screen_background": TITLE_SCREEN_BACKGROUND,
"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():
try:
return ImageFont.truetype(FONT, FONT_SIZE)
except IOError:
logger.warning(f"Font file {FONT} not found. Using default font.")
return ImageFont.load_default()
def get_text_width(text, font):
return font.getmask(text).getbbox()[2]
def wrap_text(text, max_width, font):
words = text.split()
lines = []
current_line = []
current_width = 0
for word in words:
word_width = get_text_width(word, font)
if current_width + word_width <= max_width:
current_line.append(word)
current_width += word_width + get_text_width(" ", font)
else:
if current_line:
lines.append(" ".join(current_line))
logger.debug(f"Wrapped line: {' '.join(current_line)}")
current_line = [word]
current_width = word_width
if current_line:
lines.append(" ".join(current_line))
logger.debug(f"Wrapped line: {' '.join(current_line)}")
return lines
def format_lyrics(lyrics_data, instrumentals, sync_times):
formatted_lyrics = []
font = get_font()
logger.debug(f"Using font: {font}")
current_line = ""
lines_on_page = 0
page_number = 1
for i, text in enumerate(lyrics_data):
logger.debug(f"Processing text {i}: '{text}' (sync time: {sync_times[i]})")
if text.startswith("/"):
if current_line:
wrapped_lines = get_wrapped_text(current_line.strip(), font, CDG_VISIBLE_WIDTH).split("\n")
for wrapped_line in wrapped_lines:
formatted_lyrics.append(wrapped_line)
lines_on_page += 1
logger.debug(f"Added wrapped line: '{wrapped_line}'. Lines on page: {lines_on_page}")
if lines_on_page == 4:
lines_on_page = 0
page_number += 1
logger.debug(f"Page full. New page number: {page_number}")
current_line = ""
text = text[1:]
current_line += text + " "
logger.debug(f"Current line: '{current_line}'")
is_last_before_instrumental = any(
inst["sync"] > sync_times[i] and (i == len(sync_times) - 1 or sync_times[i + 1] > inst["sync"]) for inst in instrumentals
)
if is_last_before_instrumental or i == len(lyrics_data) - 1:
if current_line:
wrapped_lines = get_wrapped_text(current_line.strip(), font, CDG_VISIBLE_WIDTH).split("\n")
for wrapped_line in wrapped_lines:
formatted_lyrics.append(wrapped_line)
lines_on_page += 1
logger.debug(f"Added wrapped line at end of section: '{wrapped_line}'. Lines on page: {lines_on_page}")
if lines_on_page == 4:
lines_on_page = 0
page_number += 1
logger.debug(f"Page full. New page number: {page_number}")
current_line = ""
if is_last_before_instrumental:
blank_lines_needed = 4 - lines_on_page
if blank_lines_needed < 4:
formatted_lyrics.extend(["~"] * blank_lines_needed)
logger.debug(f"Added {blank_lines_needed} empty lines before instrumental. Lines on page was {lines_on_page}")
lines_on_page = 0
page_number += 1
logger.debug(f"Reset lines_on_page to 0. New page number: {page_number}")
final_lyrics = []
for line in formatted_lyrics:
final_lyrics.append(line)
if line.endswith(("!", "?", ".")) and not line == "~":
final_lyrics.append("~")
logger.debug("Added empty line after punctuation")
result = "\n".join(final_lyrics)
logger.debug(f"Final formatted lyrics:\n{result}")
return result
def generate_cdg(
lrc_file,
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,
):
"""
Generate a CDG file from an LRC file and audio file.
This function can be called from other Python code to generate CDG files.
"""
# 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
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)
try:
kc = KaraokeComposer.from_file(toml_file)
kc.compose()
logger.info("CDG file generated successfully")
except Exception as e:
logger.error(f"Error composing CDG: {e}")
raise
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")
parser.add_argument("lrc_file", help="Path to the LRC file")
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")
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,
)
if __name__ == "__main__":
cli_main()
-507
View File
@@ -1,507 +0,0 @@
from collections.abc import Collection
import itertools as it
import operator
from PIL import Image, ImageChops
from .cdg import *
from .render import *
from .utils import *
FILL = 0
STROKE = 1
HIGHLIGHT = 2
def image_section_to_tile_data(
image: Image.Image,
colors: Collection[int],
xy: tuple[int, int] = (0, 0),
) -> list[int]:
"""
Convert a section of an image to a list of CDG tile data bytes.
The 6x12 section of the image with `xy` at the top left corner is
converted to a list of CDG tile data bytes. If a pixel's color index
is in `colors`, it is converted to color 1; otherwise, it is
converted to color 0. Pixels outside of the image are considered to
have a color index of 0.
Parameters
----------
image : `PIL.Image.Image`
Image to convert to tile data bytes.
colors : collection of int
Color indices to convert as color 1.
xy : tuple of (int, int), default (0, 0)
Top left corner of image section to convert.
Returns
-------
list of int
Tile data bytes.
"""
x, y = xy
tile_data: list[int] = []
for image_y in range(y, y + CDG_TILE_HEIGHT):
# If image Y is out of bounds
if not (0 <= image_y < image.height):
# Every pixel in this row is considered 0
tile_data.append(CDG_MASK if 0 in colors else 0)
continue
tile_line = 0
for image_x in range(x, x + CDG_TILE_WIDTH):
if 0 <= image_x < image.width:
pixel = image.getpixel((image_x, image_y))
else:
# If image X is out of bounds, pixel is 0
pixel = 0
# Shift in one bit, which is "on" if the pixel is in the
# collection of colors and "off" otherwise
tile_line = (tile_line << 1) | (pixel in colors)
tile_data.append(tile_line)
return tile_data
def line_image_to_packets(
image: Image.Image,
xy: tuple[int, int],
fill: int = FILL,
stroke: int = STROKE,
background: int = 0,
erase: bool = False,
) -> list[CDGPacket]:
"""
Convert a karaoke line image to CDG packets.
Parameters
----------
image : `PIL.Image.Image`
Image to convert.
xy : tuple of (int, int)
Position of top left corner of image on-screen.
fill : int, default 0
Color index of text fill.
stroke : int, default 1
Color index of text stroke.
background : int, default 0
Color index of background.
erase : bool, default False
If true, render the CDG packets to erase this karaoke line; if
false, render the CDG packets to draw this karaoke line.
Returns
-------
list of `CDGPacket`
CDG packets to draw this karaoke line image.
"""
x, y = xy
width = ceildiv(
# Width includes the blank space to the left of the first tile
(x % CDG_TILE_WIDTH) + image.width,
CDG_TILE_WIDTH,
)
height = ceildiv(
# Height includes the blank space above the first tile
(y % CDG_TILE_HEIGHT) + image.height,
CDG_TILE_HEIGHT,
)
packets: list[CDGPacket] = []
# NOTE We iterate top-to-bottom, then left-to-right, so the effect
# is sweeping across the columns from left to right.
for tile_x, tile_y in it.product(range(width), range(height)):
image_x = tile_x * CDG_TILE_WIDTH - (x % CDG_TILE_WIDTH)
image_y = tile_y * CDG_TILE_HEIGHT - (y % CDG_TILE_HEIGHT)
row = y // CDG_TILE_HEIGHT + tile_y
column = x // CDG_TILE_WIDTH + tile_x
# Skip if row or column is out of bounds
if not (
0 <= row < CDG_SCREEN_HEIGHT // CDG_TILE_HEIGHT
and 0 <= column < CDG_SCREEN_WIDTH // CDG_TILE_WIDTH
):
continue
if erase:
# Draw blank tiles over non-blank parts of the image
tile_data = image_section_to_tile_data(
image,
colors=[RENDERED_BLANK],
xy=(image_x, image_y),
)
if any(t != CDG_MASK for t in tile_data):
packets.append(tile_block(
color0=background, color1=background,
row=row, column=column,
tile=[0 for _ in range(CDG_TILE_HEIGHT)],
))
else:
# Draw stroke
tile_data = image_section_to_tile_data(
image,
colors=[RENDERED_STROKE],
xy=(image_x, image_y),
)
drew_stroke = False
if any(tile_data):
drew_stroke = True
packets.append(tile_block(
color0=background, color1=stroke,
row=row, column=column,
tile=tile_data,
))
# Draw text
tile_data = image_section_to_tile_data(
image,
colors=[RENDERED_FILL],
xy=(image_x, image_y),
)
if any(tile_data):
packet_func = tile_block
color0 = background
color1 = fill
if drew_stroke:
packet_func = tile_block_xor
color0 = 0
color1 = fill ^ background
packets.append(packet_func(
color0=color0, color1=color1,
row=row, column=column,
tile=tile_data,
))
return packets
def line_mask_to_packets(
image: Image.Image,
xy: tuple[int, int],
edges: tuple[int, int],
highlight: int = HIGHLIGHT,
) -> list[CDGPacket]:
"""
Convert a section of a karaoke mask image to CDG packets.
The section is assumed to take up only one column of tiles.
Parameters
----------
image : `PIL.Image.Image`
Image to convert.
xy : tuple of (int, int)
Position of top left corner of image on-screen.
edges : tuple of (int, int)
X positions of left and right edges of section.
highlight : int, default 2
Number with necessary bits on for highlight. This is XORed with
the color index for pixels with highlight.
Returns
-------
list of `CDGPacket`
CDG packets to draw this section of this karaoke line mask.
"""
x, y = xy
left_edge, right_edge = edges
# Create section mask
section_mask = Image.new("P", image.size, 0)
# Draw rectangle with color 255 with edges as boundaries
# NOTE The color index must be 255 for ImageChops.multiply to
# preserve the color indices.
section_mask.paste(255, (left_edge - x, 0, right_edge - x, image.height))
# Mask out section of image
section = ImageChops.multiply(image, section_mask)
height = ceildiv(
# Height includes the blank space above the first tile
(y % CDG_TILE_HEIGHT) + image.height,
CDG_TILE_HEIGHT,
)
packets: list[CDGPacket] = []
tile_x = (left_edge // CDG_TILE_WIDTH) - (x // CDG_TILE_WIDTH)
# For all tiles in this column
for tile_y in range(height):
image_x = tile_x * CDG_TILE_WIDTH - (x % CDG_TILE_WIDTH)
image_y = tile_y * CDG_TILE_HEIGHT - (y % CDG_TILE_HEIGHT)
row = y // CDG_TILE_HEIGHT + tile_y
column = x // CDG_TILE_WIDTH + tile_x
# Skip if row or column is out of bounds
if not (
0 <= row < CDG_SCREEN_HEIGHT // CDG_TILE_HEIGHT
and 0 <= column < CDG_SCREEN_WIDTH // CDG_TILE_WIDTH
):
continue
# Draw mask section as highlight
tile_data = image_section_to_tile_data(
section,
colors=[RENDERED_MASK],
xy=(image_x, image_y),
)
if any(tile_data):
packets.append(tile_block_xor(
color0=0, color1=highlight,
row=row, column=column,
tile=tile_data,
))
return packets
def image_to_packets(
image: Image.Image,
xy: tuple[int, int] = (0, 0),
background: Image.Image | None = None,
) -> dict[tuple[int, int], list[CDGPacket]]:
"""
Convert an image to CDG packets.
Parameters
----------
image : `PIL.Image.Image`
Image to convert.
xy : tuple of (int, int), default (0, 0)
Position to draw image on screen.
Returns
-------
dict of {tuple of (int, int): list of CDGPacket}
Tile positions, and CDG packets to draw at those positions.
"""
# Image must be in palette mode
assert image.mode == "P"
# Image must have correct number of colors
# HACK Assuming the palette is in RGB, there should be one palette
# entry per band (R, G, B). I don't know of a better way to count
# palette entries.
# REVIEW Is there a better way to count palette entries?
palette_mode, palette_data = image.palette.getdata()
assert palette_mode == "RGB"
assert len(palette_data) // 3 <= 16
# Same things apply to the background image, if any
if background is not None:
assert background.mode == "P"
bg_palette_mode, bg_palette_data = background.palette.getdata()
assert bg_palette_mode == "RGB"
assert len(bg_palette_data) // 3 <= 16
x, y = xy
width = ceildiv(
# Width includes the blank space to the left of the first tile
(x % CDG_TILE_WIDTH) + image.width,
CDG_TILE_WIDTH,
)
height = ceildiv(
# Height includes the blank space above the first tile
(y % CDG_TILE_HEIGHT) + image.height,
CDG_TILE_HEIGHT,
)
packets: dict[tuple[int, int], list[CDGPacket]] = {}
for tile_y, tile_x in it.product(range(height), range(width)):
image_x = tile_x * CDG_TILE_WIDTH - (x % CDG_TILE_WIDTH)
image_y = tile_y * CDG_TILE_HEIGHT - (y % CDG_TILE_HEIGHT)
row = y // CDG_TILE_HEIGHT + tile_y
column = x // CDG_TILE_WIDTH + tile_x
# Skip if row or column is out of bounds
if not (
0 <= row < CDG_SCREEN_HEIGHT // CDG_TILE_HEIGHT
and 0 <= column < CDG_SCREEN_WIDTH // CDG_TILE_WIDTH
):
continue
tile = image.crop((
image_x, image_y,
image_x + CDG_TILE_WIDTH, image_y + CDG_TILE_HEIGHT,
))
background_tile = None
if background is not None:
background_tile = background.crop((
image_x, image_y,
image_x + CDG_TILE_WIDTH, image_y + CDG_TILE_HEIGHT,
))
packets[(row, column)] = tile_to_packets(
tile, row, column,
background_tile=background_tile,
)
return packets
# REVIEW How can I change this function to draw an image over already
# existing pixels on the screen? For example, sometimes it would be more
# efficient to XOR over existing pixels than to draw a new tile.
def tile_to_packets(
tile: Image.Image,
row: int,
column: int,
background_tile: Image.Image | None = None,
) -> list[CDGPacket]:
"""
Convert a tile to CDG packets.
The tile is assumed to be a 6x12 image in `P` mode.
Parameters
----------
tile : `PIL.Image.Image`
Tile to convert.
row : int
Row to draw tile on screen.
column : int
Column to draw tile on screen.
Returns
-------
list of CDGPacket
CDG packets to draw this tile.
"""
# If the background tile has the same pixels as the tile we want to
# draw, don't draw this tile
if (
background_tile is not None
and list(tile.getdata()) == list(background_tile.getdata())
):
return []
# Sort colors in descending order by frequency
colors: list[int] = list(map(
operator.itemgetter(1),
sorted(tile.getcolors(), reverse=True),
))
if len(colors) == 1:
# HACK If the only color is 0 (and we're not drawing over a
# background tile), we don't draw this tile. This is not always
# desirable, but it's fine for our purposes.
if background_tile is None and not colors[0]:
return []
return [
tile_block(
color0=0, color1=colors[0],
row=row, column=column,
tile=[CDG_MASK] * CDG_TILE_HEIGHT,
),
]
if len(colors) == 2:
return [
tile_block(
color0=colors[1], color1=colors[0],
row=row, column=column,
tile=image_section_to_tile_data(tile, [colors[0]]),
),
]
if len(colors) == 3:
return [
tile_block(
color0=colors[1], color1=colors[0],
row=row, column=column,
tile=image_section_to_tile_data(tile, [colors[0]]),
),
tile_block_xor(
color0=0, color1=colors[1] ^ colors[2],
row=row, column=column,
tile=image_section_to_tile_data(tile, [colors[2]]),
),
]
colors_or = 0x00
colors_xor = 0x00
colors_and = 0xff
for color in colors:
colors_or |= color
colors_xor ^= color
colors_and &= color
and_bits = colors_and.bit_count()
or_bits = colors_or.bit_count()
used_bits = or_bits - and_bits
if len(colors) == 4 and used_bits > 2 and colors_xor != 0:
return [
tile_block(
color0=colors[0], color1=colors[1],
row=row, column=column,
tile=image_section_to_tile_data(
tile, [colors[1], colors[2], colors[3]],
),
),
tile_block_xor(
color0=0, color1=colors[1] ^ colors[2],
row=row, column=column,
tile=image_section_to_tile_data(
tile, [colors[2]],
),
),
tile_block_xor(
color0=0, color1=colors[1] ^ colors[3],
row=row, column=column,
tile=image_section_to_tile_data(
tile, [colors[3]],
),
),
]
if len(colors) > 4 or colors_xor != 0:
tile_packets: list[CDGPacket] = []
packet_func = tile_block
for i in range(4):
if not colors_or & (1 << i):
continue
if colors_and & (1 << i):
continue
color0 = 0
color1 = 1 << i
if packet_func == tile_block and colors_and:
color0 |= colors_and
color1 |= colors_and
tile_packets.append(packet_func(
color0=color0, color1=color1,
row=row, column=column,
tile=image_section_to_tile_data(
tile,
[color for color in range(16) if color & (1 << i)],
),
))
packet_func = tile_block_xor
return tile_packets
assert colors[2] ^ colors[0] == colors[1] ^ colors[3]
return [
tile_block(
color0=colors[1], color1=colors[0],
row=row, column=column,
tile=image_section_to_tile_data(
tile, [colors[0], colors[2]],
),
),
tile_block_xor(
color0=0, color1=colors[2] ^ colors[0],
row=row, column=column,
tile=image_section_to_tile_data(
tile, [colors[2], colors[3]],
),
),
]
__all__ = [
"image_section_to_tile_data", "line_image_to_packets",
"line_mask_to_packets", "image_to_packets", "tile_to_packets",
]
-346
View File
@@ -1,346 +0,0 @@
from collections.abc import Sequence
import itertools as it
from PIL import Image, ImageChops, ImageDraw, ImageFont
from .config import *
import logging
logger = logging.getLogger(__name__)
RENDERED_BLANK = 0
RENDERED_MASK = 1
RENDERED_FILL = 1
RENDERED_STROKE = 2
def get_wrapped_text(
text: str,
font: ImageFont.FreeTypeFont,
width: int,
) -> str:
"""
Add newlines to text such that it fits within the specified width
using the specified font.
Existing newlines are preserved.
Parameters
----------
text : str
Text to add newlines to.
font : `PIL.ImageFont.FreeTypeFont`
Font in which text will be rendered.
width : int
Maximum width of text lines in pixels.
Returns
-------
str
Text with inserted newlines.
"""
lines: list[str] = []
for text_line in text.split("\n"):
words: list[str] = []
for word in text_line.split():
if font.getlength(" ".join(words + [word])) > width:
lines.append(" ".join(words))
words.clear()
words.append(word)
lines.append(" ".join(words))
words.clear()
return "\n".join(lines)
def render_text(
text: str,
font: ImageFont.FreeTypeFont,
fill: int = RENDERED_FILL,
stroke_fill: int = RENDERED_STROKE,
stroke_width: int = 0,
stroke_type: StrokeType = StrokeType.OCTAGON,
) -> Image.Image:
"""
Render one text line as a `PIL.Image.Image` in `P` mode.
There may be horizontal padding on both sides of the image. However,
for the same text prefix or suffix, the padding on that side will be
the same.
Parameters
----------
text : str
Text line to render.
font : `PIL.ImageFont.FreeTypeFont`
Font to render text with.
config : `config.Settings`
Config settings.
fill : int, default 1
Color index of the text fill.
stroke_fill : int, default 2
Color index of the text stroke.
stroke_width : int, default 0
Width of the text stroke.
stroke_type : `StrokeType`, default `StrokeType.OCTAGON`
Stroke type.
Returns
-------
`PIL.Image.Image`
Image with rendered text.
"""
# Get relevant dimensions for font
_, _, text_width, _ = font.getbbox(text)
ascent, descent = font.getmetrics()
(_, _), (offset_x, _) = font.font.getsize(text)
image_width = text_width - offset_x
image_height = ascent + descent
# Add space on left/right for stroke
image_width += 2 * stroke_width
# Add space on top/bottom for stroke
image_height += 2 * stroke_width
# HACK I don't know exactly why, but sometimes a few pixels are cut
# off on the sides, so we add some horizontal padding here. (This is
# cropped by another function, so it's okay.)
padding_x = font.size * 4
image_width += padding_x
offset_x -= padding_x // 2
image = Image.new("P", (image_width, image_height), 0)
draw = ImageDraw.Draw(image)
# Turn off antialiasing
draw.fontmode = "1"
draw_x = stroke_width - offset_x
draw_y = stroke_width
# If we are to draw a text stroke
if stroke_width and stroke_fill is not None:
# NOTE PIL allows text to be drawn with a stroke, but this
# stroke is anti-aliased, and you can't turn off the anti-
# aliasing on it. So instead, we're simulating a stroke by
# drawing the text multiple times at various offsets.
stroke_coords = list(it.product(
range(-stroke_width, stroke_width + 1), repeat=2,
))
match stroke_type:
case StrokeType.CIRCLE:
stroke_coords = [
(x, y)
for x, y in stroke_coords
if x**2 + y**2 <= stroke_width ** 2
]
case StrokeType.SQUARE:
pass
case StrokeType.OCTAGON:
stroke_coords = [
(x, y)
for x, y in stroke_coords
if (abs(x) + abs(y)) * 2 <= stroke_width * 3
]
# Create image for text stroke
stroke_image = Image.new("P", image.size, 0)
stroke_draw = ImageDraw.Draw(stroke_image)
# Turn off antialiasing
stroke_draw.fontmode = "1"
# Render text stroke
stroke_draw.text((draw_x, draw_y), text, stroke_fill, font)
# Create mask for text stroke
stroke_mask = stroke_image.point(lambda v: v and 255, mode="1")
# Draw text stroke at various offsets
for x, y in stroke_coords:
image.paste(stroke_image, (x, y), mask=stroke_mask)
# NOTE Drawing the stroke once and pasting it multiple times is
# faster than drawing the stroke multiple times.
# Draw text fill
draw.text((draw_x, draw_y), text, fill, font)
return image
def render_lines_and_masks(
lines: Sequence[Sequence[str]],
font: ImageFont.FreeTypeFont,
stroke_width: int = 0,
stroke_type: StrokeType = StrokeType.OCTAGON,
render_masks: bool = True,
) -> tuple[list[Image.Image], list[list[Image.Image]]]:
"""
Render set of karaoke lines as `PIL.Image.Image`s, and masks for
each syllable as lists of `PIL.Image.Image`s.
The line images will be cropped as much as possible on the left,
right, and bottom sides. The top side of all line images will be
cropped by the largest amount that does not shrink any of their
bounding boxes.
Parameters
----------
lines : list of list of str
Lines as lists of syllables.
font : `PIL.ImageFont.FreeTypeFont`
Font to render text with.
stroke_width : int, default 0
WIdth of the text stroke.
stroke_type : `StrokeType`, default `StrokeType.OCTAGON`
Stroke type.
render_masks : bool, default True
If true, render masks for each line.
Returns
-------
list of `PIL.Image.Image`
Images with rendered lines.
list of list of `PIL.Image.Image`
Images with rendered masks for each syllable for each line.
"""
logger.debug("rendering line images")
# Render line images
uncropped_line_images = [
render_text(
text="".join(line),
font=font,
fill=RENDERED_FILL,
stroke_fill=RENDERED_STROKE,
stroke_width=stroke_width,
stroke_type=stroke_type,
)
for line in lines
]
# Calculate how much the tops of the lines can be cropped
top_crop = min(
(
bbox[1]
for image in uncropped_line_images
if (bbox := image.getbbox()) is not None
),
default=0,
)
logger.debug(
f"line images will be cropped by {top_crop} pixel(s) on the top"
)
# Crop line images
line_images: list[Image.Image] = []
bboxes: list[Sequence[int]] = []
logger.debug("cropping line images")
for image in uncropped_line_images:
bbox = image.getbbox()
if bbox is None:
# Create empty bounding box if image is empty
bbox = (0, 0, 0, 0)
else:
# Crop top of bounding box is image is not empty
bbox = list(bbox)
bbox[1] = top_crop
bboxes.append(bbox)
line_images.append(image.crop(bbox))
if not render_masks:
logger.debug("not rendering masks")
return line_images, []
# Render mask images
line_masks: list[list[Image.Image]] = []
logger.debug("rendering/cropping masks")
for line, bbox in zip(lines, bboxes):
# HACK For whatever reason, the presence or absence of certain
# characters of text can cause the rendered text to be 1 pixel
# off. We fix this by adding the entire rest of the text after
# each rendered part of it, so this mysterious offset is at
# least consistent.
extra_text = "".join(line)
# NOTE We will prefix the extra text with way more spaces than
# necessary, so it doesn't show up in the mask images.
text_padding = " " * bbox[2]
# REVIEW More testing is needed. Which characters does this
# happen for? Why does this even happen?
# Using Old Sans Black, this happens with at least "t" and "!".
# Get masks of the line's text from the start up to each
# syllable
# e.g. ["Don't ", "walk ", "a", "way"] ->
# ["Don't ", "Don't walk ", "Don't walk a", "Don't walk away"]
full_line_masks = [
render_text(
text="".join(line[:i+1]) + text_padding + extra_text,
font=font,
fill=RENDERED_MASK,
stroke_fill=RENDERED_MASK,
stroke_width=stroke_width,
stroke_type=stroke_type,
).crop(bbox)
for i in range(len(line))
]
line_mask: list[Image.Image] = []
# If this line has any syllables
if full_line_masks:
# Start with the first syllable's mask...
line_mask = [full_line_masks[0]] + [
# ...then get the pixel-by-pixel difference between each
# pair of full-line masks
ImageChops.difference(prev_mask, next_mask)
for prev_mask, next_mask in it.pairwise(full_line_masks)
]
# NOTE This will isolate the pixels that make up this syllable,
# by basically "cancelling out" the previous syllables of the
# line.
line_masks.append(line_mask)
return line_images, line_masks
def render_lines(
lines: Sequence[Sequence[str]],
font: ImageFont.FreeTypeFont,
stroke_width: int = 0,
stroke_type: StrokeType = StrokeType.OCTAGON,
) -> list[Image.Image]:
"""
Render set of karaoke lines as `PIL.Image.Image`s.
The line images will be cropped as much as possible on the left,
right, and bottom sides. The top side of all line images will be
cropped by the largest amount that does not shrink any of their
bounding boxes.
Parameters
----------
lines : list of list of str
Lines as lists of syllables.
font : `PIL.ImageFont.FreeTypeFont`
Font to render text with.
stroke_width : int, default 0
WIdth of the text stroke.
stroke_type : `StrokeType`, default `StrokeType.OCTAGON`
Stroke type.
Returns
-------
list of `PIL.Image.Image`
Images with rendered lines.
"""
images, _ = render_lines_and_masks(
lines,
font=font,
stroke_width=stroke_width,
stroke_type=stroke_type,
render_masks=False,
)
return images
__all__ = [
"RENDERED_BLANK", "RENDERED_MASK", "RENDERED_FILL",
"RENDERED_STROKE",
"get_wrapped_text", "render_text", "render_lines_and_masks",
"render_lines",
]
Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.2 KiB

-132
View File
@@ -1,132 +0,0 @@
from collections.abc import Iterable, Iterator, Sequence
import itertools as it
import operator
from typing import Any, TypeVar, overload
_T = TypeVar("_T")
@overload
def ceildiv(a: int, b: int) -> int: ...
@overload
def ceildiv(a: float, b: float) -> float: ...
def ceildiv(a, b):
"""
Return the ceiling of `a / b`.
Parameters
----------
a : int or float
Dividend.
b : int or float
Divisor.
Returns
-------
int or float
The ceiling of the quotient of `a` and `b`.
"""
return -(a // -b)
def distribute(
sequence: Sequence[_T],
start: float = 0,
stop: float = 1,
) -> Iterator[tuple[float, _T]]:
"""
Enumerate the sequence evenly over the interval (`start`, `stop`).
Based on https://stackoverflow.com/a/59594546 .
Parameters
----------
sequence : array-like
Sequence to enumerate.
start : float, default 0
Start of interval (exclusive).
stop : float, default 1
End of interval (exclusive).
Yields
------
position : float
Position of sequence item in interval.
item
Sequence item.
Examples
--------
>>> list(distribute("abc"))
[(0.25, 'a'), (0.5, 'b'), (0.75, 'c')]
>>> list(distribute("abc", 1, 4))
[(1.75, 'a'), (2.5, 'b'), (3.25, 'c')]
"""
m = len(sequence) + 1
for i, v in enumerate(sequence, 1):
yield start + (stop - start) * i / m, v
def intersperse(*sequences: Sequence[_T]) -> Iterator[_T]:
"""
Evenly intersperse the sequences.
Based on https://stackoverflow.com/a/59594546 .
Parameters
----------
*sequences
Sequences to intersperse.
Yields
------
item
Sequence item.
Examples
--------
>>> list(intersperse(range(10), "abc"))
[0, 1, 'a', 2, 3, 4, 'b', 5, 6, 7, 'c', 8, 9]
>>> list(intersperse("XY", range(10), "abc"))
[0, 1, 'a', 2, 'X', 3, 4, 'b', 5, 6, 'Y', 7, 'c', 8, 9]
>>> "".join(intersperse("hlwl", "eood", "l r!"))
'hello world!'
"""
distributions = map(distribute, sequences)
for _, v in sorted(it.chain(*distributions), key=operator.itemgetter(0)):
yield v
def pad(
iterable: Iterable[_T],
size: int,
padvalue: Any = None,
) -> Iterable[_T]:
"""
Pad an iterable to a specified size.
If the iterable is longer than the specified size, it is truncated.
If it is shorter, `padvalue` is appended until the specified size is
reached.
Parameters
----------
iterable : iterable
Iterable to pad.
size : int
Size to pad iterable to.
padvalue : any, default None
Value to pad iterable with.
Returns
-------
iterable
Padded iterable.
"""
return it.islice(it.chain(iterable, it.repeat(padvalue)), size)
__all__ = [
"ceildiv", "distribute", "intersperse", "pad",
]
+290 -122
View File
@@ -16,10 +16,10 @@ from google.auth.transport.requests import Request
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
from lyrics_transcriber.output.cdg import CDGGenerator
class KaraokeFinalise:
@@ -40,8 +40,10 @@ class KaraokeFinalise:
youtube_description_file=None,
rclone_destination=None,
discord_webhook_url=None,
non_interactive=False,
email_template_file=None,
cdg_styles=None,
keep_brand_code=False,
non_interactive=False,
):
self.logger = logging.getLogger(__name__)
self.logger.setLevel(log_level)
@@ -102,15 +104,18 @@ class KaraokeFinalise:
"end_jpg": " (End).jpg",
"with_vocals_mov": " (With Vocals).mov",
"with_vocals_mp4": " (With Vocals).mp4",
"with_vocals_mkv": " (With Vocals).mkv",
"karaoke_lrc": " (Karaoke).lrc",
"karaoke_cdg": " (Karaoke).cdg",
"karaoke_txt": " (Karaoke).txt",
"karaoke_mp4": " (Karaoke).mp4",
"karaoke_cdg": " (Karaoke).cdg",
"karaoke_mp3": " (Karaoke).mp3",
"karaoke_mov": " (Karaoke).mov",
"final_karaoke_mp4": " (Final Karaoke).mp4",
"final_karaoke_lossless_mp4": " (Final Karaoke Lossless 4k).mp4",
"final_karaoke_lossless_mkv": " (Final Karaoke Lossless 4k).mkv",
"final_karaoke_lossy_mp4": " (Final Karaoke Lossy 4k).mp4",
"final_karaoke_lossy_720p_mp4": " (Final Karaoke Lossy 720p).mp4",
"final_karaoke_cdg_zip": " (Final Karaoke CDG).zip",
"final_karaoke_txt_zip": " (Final Karaoke TXT).zip",
"final_karaoke_720p_mp4": " (Final Karaoke 720p).mp4",
}
self.youtube_url_prefix = "https://www.youtube.com/watch?v="
@@ -124,6 +129,20 @@ class KaraokeFinalise:
self.email_template_file = email_template_file
self.gmail_service = None
self.cdg_styles = cdg_styles
# Determine best available AAC codec
self.aac_codec = self.detect_best_aac_codec()
self.keep_brand_code = keep_brand_code
# MP4 output flags for better compatibility and streaming
self.mp4_flags = "-pix_fmt yuv420p -movflags +faststart+frag_keyframe+empty_moov"
# Update ffmpeg base command to include -y if non-interactive
if self.non_interactive:
self.ffmpeg_base_command += " -y"
def check_input_files_exist(self, base_name, with_vocals_file, instrumental_audio_file):
self.logger.info(f"Checking required input files exist...")
@@ -159,11 +178,14 @@ class KaraokeFinalise:
def prepare_output_filenames(self, base_name):
output_files = {
"karaoke_mov": f"{base_name}{self.suffixes['karaoke_mov']}",
"karaoke_mp4": f"{base_name}{self.suffixes['karaoke_mp4']}",
"karaoke_mp3": f"{base_name}{self.suffixes['karaoke_mp3']}",
"karaoke_cdg": f"{base_name}{self.suffixes['karaoke_cdg']}",
"with_vocals_mp4": f"{base_name}{self.suffixes['with_vocals_mp4']}",
"final_karaoke_mp4": f"{base_name}{self.suffixes['final_karaoke_mp4']}",
"final_karaoke_720p_mp4": f"{base_name}{self.suffixes['final_karaoke_720p_mp4']}",
"final_karaoke_lossless_mp4": f"{base_name}{self.suffixes['final_karaoke_lossless_mp4']}",
"final_karaoke_lossless_mkv": f"{base_name}{self.suffixes['final_karaoke_lossless_mkv']}",
"final_karaoke_lossy_mp4": f"{base_name}{self.suffixes['final_karaoke_lossy_mp4']}",
"final_karaoke_lossy_720p_mp4": f"{base_name}{self.suffixes['final_karaoke_lossy_720p_mp4']}",
}
if self.enable_cdg:
@@ -176,13 +198,17 @@ class KaraokeFinalise:
return output_files
def prompt_user_confirmation_or_raise_exception(self, prompt_message, exit_message, allow_empty=False):
if self.non_interactive:
self.logger.info(f"Non-interactive mode, automatically confirming: {prompt_message}")
return True
if not self.prompt_user_bool(prompt_message, allow_empty=allow_empty):
self.logger.error(exit_message)
raise Exception(exit_message)
def prompt_user_bool(self, prompt_message, allow_empty=False):
if self.non_interactive:
self.logger.warning(f"Non-interactive mode, responding True for prompt: {prompt_message}")
self.logger.info(f"Non-interactive mode, automatically answering yes to: {prompt_message}")
return True
options_string = "[y]/n" if allow_empty else "y/[n]"
@@ -346,10 +372,10 @@ class KaraokeFinalise:
return truncated_title
def upload_final_mp4_to_youtube_with_title_thumbnail(self, artist, title, input_files, output_files):
self.logger.info(f"Uploading final MP4 to YouTube with title thumbnail...")
self.logger.info(f"Uploading final MKV to YouTube with title thumbnail...")
if self.dry_run:
self.logger.info(
f'DRY RUN: Would upload {output_files["final_karaoke_mp4"]} to YouTube with thumbnail {input_files["title_jpg"]} using client secrets file: {self.youtube_client_secrets_file}'
f'DRY RUN: Would upload {output_files["final_karaoke_lossless_mkv"]} to YouTube with thumbnail {input_files["title_jpg"]} using client secrets file: {self.youtube_client_secrets_file}'
)
else:
youtube_title = f"{artist} - {title} (Karaoke)"
@@ -384,11 +410,11 @@ class KaraokeFinalise:
"status": {"privacyStatus": "public"},
}
# Use MediaFileUpload to handle the video file
media_file = MediaFileUpload(output_files["final_karaoke_mp4"], mimetype="video/mp4", resumable=True)
# Use MediaFileUpload to handle the video file - using the MKV with FLAC audio
media_file = MediaFileUpload(output_files["final_karaoke_lossless_mkv"], mimetype="video/x-matroska", resumable=True)
# Call the API's videos.insert method to create and upload the video.
self.logger.info(f"Uploading final MP4 to YouTube...")
self.logger.info(f"Uploading final MKV to YouTube...")
request = youtube.videos().insert(part="snippet,status", body=body, media_body=media_file)
response = request.execute()
@@ -432,23 +458,37 @@ class KaraokeFinalise:
self.logger.info("Message posted to Discord")
def find_with_vocals_file(self):
self.logger.info("Finding input file in current directory ending (With Vocals).mov or (With Vocals).mp4")
self.logger.info("Finding input file ending in (With Vocals).mov/.mp4/.mkv or (Karaoke).mov/.mp4/.mkv")
with_vocals_files = [f for f in os.listdir(".") if self.suffixes["with_vocals_mov"] in f]
# Define all possible suffixes for with vocals files
with_vocals_suffixes = [
self.suffixes["with_vocals_mov"],
self.suffixes["with_vocals_mp4"],
self.suffixes["with_vocals_mkv"],
]
if not with_vocals_files:
self.logger.info(f"No with vocals MOV file found, looking for with vocals MP4 file instead")
# First try to find a properly named with vocals file in any supported format
with_vocals_files = [f for f in os.listdir(".") if any(f.endswith(suffix) for suffix in with_vocals_suffixes)]
with_vocals_files = [f for f in os.listdir(".") if self.suffixes["with_vocals_mp4"] in f]
if with_vocals_files:
self.logger.info(f"Found with vocals MP4 file: {with_vocals_files[0]}")
return with_vocals_files[0]
if with_vocals_files:
self.logger.info(f"Found with vocals file: {with_vocals_files[0]}")
return with_vocals_files[0]
if not with_vocals_files:
karaoke_files = [f for f in os.listdir(".") if self.suffixes["karaoke_mov"] in f]
if karaoke_files:
for file in karaoke_files:
new_file = file.replace(self.suffixes["karaoke_mov"], self.suffixes["with_vocals_mov"])
# If no with vocals file found, look for potentially misnamed karaoke files
karaoke_suffixes = [" (Karaoke).mov", " (Karaoke).mp4", " (Karaoke).mkv"]
karaoke_files = [f for f in os.listdir(".") if any(f.endswith(suffix) for suffix in karaoke_suffixes)]
if karaoke_files:
for file in karaoke_files:
# Get the current extension
current_ext = os.path.splitext(file)[1].lower() # Convert to lowercase
base_without_suffix = file.replace(f" (Karaoke){current_ext}", "")
# Map file extension to suffix dictionary key
ext_to_suffix = {".mov": "with_vocals_mov", ".mp4": "with_vocals_mp4", ".mkv": "with_vocals_mkv"}
if current_ext in ext_to_suffix:
new_file = f"{base_without_suffix}{self.suffixes[ext_to_suffix[current_ext]]}"
self.prompt_user_confirmation_or_raise_exception(
f"Found '{file}' but no '(With Vocals)', rename to {new_file} for vocal input?",
@@ -459,27 +499,34 @@ class KaraokeFinalise:
os.rename(file, new_file)
self.logger.info(f"Renamed '{file}' to '{new_file}'")
return new_file
else:
raise Exception("No suitable files found for processing.")
else:
return with_vocals_files[0] # Assuming only one such file is expected
else:
self.logger.warning(f"Unsupported file extension: {current_ext}")
raise Exception("No suitable files found for processing.")
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}")
@@ -490,6 +537,11 @@ class KaraokeFinalise:
if len(filtered_files) == 1:
return filtered_files[0]
# In non-interactive mode, always choose the first option
if self.non_interactive:
self.logger.info(f"Non-interactive mode, automatically choosing first instrumental file: {filtered_files[0]}")
return filtered_files[0]
# Sort the remaining instrumental options alphabetically
filtered_files.sort(reverse=True)
@@ -515,7 +567,18 @@ class KaraokeFinalise:
def get_names_from_withvocals(self, with_vocals_file):
self.logger.info(f"Getting artist and title from {with_vocals_file}")
base_name = with_vocals_file.replace(self.suffixes["with_vocals_mov"], "").replace(self.suffixes["with_vocals_mp4"], "")
# Remove both possible suffixes and their extensions
base_name = with_vocals_file
for suffix_key in ["with_vocals_mov", "with_vocals_mp4", "with_vocals_mkv"]:
suffix = self.suffixes[suffix_key]
if suffix in base_name:
base_name = base_name.replace(suffix, "")
break
# If we didn't find a match above, try removing just the extension
if base_name == with_vocals_file:
base_name = os.path.splitext(base_name)[0]
artist, title = base_name.split(" - ", 1)
return base_name, artist, title
@@ -527,27 +590,98 @@ class KaraokeFinalise:
self.logger.info(f"Running command: {command}")
os.system(command)
def remux_with_instrumental(self, with_vocals_file, instrumental_audio, output_file):
"""Remux the video with instrumental audio to create karaoke version"""
# fmt: off
ffmpeg_command = (
f'{self.ffmpeg_base_command} -an -i "{with_vocals_file}" '
f'-vn -i "{instrumental_audio}" -c:v copy -c:a pcm_s16le "{output_file}"'
)
# fmt: on
self.execute_command(ffmpeg_command, "Remuxing video with instrumental audio")
def convert_mov_to_mp4(self, input_file, output_file):
"""Convert MOV file to MP4 format"""
# fmt: off
ffmpeg_command = (
f'{self.ffmpeg_base_command} -i "{input_file}" '
f'-c:v libx264 -c:a {self.aac_codec} {self.mp4_flags} "{output_file}"'
)
# fmt: on
self.execute_command(ffmpeg_command, "Converting MOV video to MP4")
def encode_lossless_mp4(self, title_mov_file, karaoke_mp4_file, env_mov_input, ffmpeg_filter, output_file):
"""Create the final MP4 with PCM audio (lossless)"""
# fmt: off
ffmpeg_command = (
f"{self.ffmpeg_base_command} -i {title_mov_file} -i {karaoke_mp4_file} {env_mov_input} "
f'{ffmpeg_filter} -map "[outv]" -map "[outa]" -c:v libx264 -c:a pcm_s16le '
f'{self.mp4_flags} "{output_file}"'
)
# fmt: on
self.execute_command(ffmpeg_command, "Creating MP4 version with PCM audio")
def encode_lossy_mp4(self, input_file, output_file):
"""Create MP4 with AAC audio (lossy, for wider compatibility)"""
# fmt: off
ffmpeg_command = (
f'{self.ffmpeg_base_command} -i "{input_file}" '
f'-c:v copy -c:a {self.aac_codec} -b:a 320k {self.mp4_flags} "{output_file}"'
)
# fmt: on
self.execute_command(ffmpeg_command, "Creating MP4 version with AAC audio")
def encode_lossless_mkv(self, input_file, output_file):
"""Create MKV with FLAC audio (for YouTube)"""
# fmt: off
ffmpeg_command = (
f'{self.ffmpeg_base_command} -i "{input_file}" '
f'-c:v copy -c:a flac "{output_file}"'
)
# fmt: on
self.execute_command(ffmpeg_command, "Creating MKV version with FLAC audio for YouTube")
def encode_720p_version(self, input_file, output_file):
"""Create 720p MP4 with AAC audio (for smaller file size)"""
# fmt: off
ffmpeg_command = (
f'{self.ffmpeg_base_command} -i "{input_file}" '
f'-c:v libx264 -vf "scale=1280:720" -b:v 200k -preset medium -tune animation '
f'-c:a {self.aac_codec} -b:a 128k {self.mp4_flags} "{output_file}"'
)
# fmt: on
self.execute_command(ffmpeg_command, "Encoding 720p version of the final video")
def prepare_concat_filter(self, input_files):
"""Prepare the concat filter and additional input for end credits if present"""
env_mov_input = ""
ffmpeg_filter = '-filter_complex "[0:v:0][0:a:0][1:v:0][1:a:0]concat=n=2:v=1:a=1[outv][outa]"'
if "end_mov" in input_files and os.path.isfile(input_files["end_mov"]):
self.logger.info(f"Found end_mov file: {input_files['end_mov']}, including in final MP4")
end_mov_file = shlex.quote(os.path.abspath(input_files["end_mov"]))
env_mov_input = f"-i {end_mov_file}"
ffmpeg_filter = '-filter_complex "[0:v:0][0:a:0][1:v:0][1:a:0][2:v:0][2:a:0]concat=n=3:v=1:a=1[outv][outa]"'
return env_mov_input, ffmpeg_filter
def remux_and_encode_output_video_files(self, with_vocals_file, input_files, output_files):
self.logger.info(f"Remuxing and encoding output video files...")
# Check if output files already exist, if so, ask user to overwrite or skip
if os.path.isfile(output_files["karaoke_mov"]) and os.path.isfile(output_files["final_karaoke_mp4"]):
# Check if output files already exist
if os.path.isfile(output_files["final_karaoke_lossless_mp4"]) and os.path.isfile(output_files["final_karaoke_lossless_mkv"]):
if not self.prompt_user_bool(
f"Found existing Final Karaoke output file: {output_files['final_karaoke_mp4']}. Overwrite (y) or skip (n)?",
f"Found existing Final Karaoke output files. Overwrite (y) or skip (n)?",
):
self.logger.info(f"Skipping Karaoke MOV remux and Final MP4 render, existing files will be used.")
self.logger.info(f"Skipping Karaoke MP4 remux and Final video renders, existing files will be used.")
return
# Remux the synced video with the instrumental audio to produce an instrumental karaoke MOV file
remux_ffmpeg_command = f'{self.ffmpeg_base_command} -an -i "{with_vocals_file}" -vn -i "{input_files["instrumental_audio"]}" -c:v copy -c:a aac "{output_files["karaoke_mov"]}"'
self.execute_command(remux_ffmpeg_command, "Remuxing video with instrumental audio")
# Create karaoke version with instrumental audio
self.remux_with_instrumental(with_vocals_file, input_files["instrumental_audio"], output_files["karaoke_mp4"])
# Convert the with vocals video to MP4 if it isn't already
# Convert the with vocals video to MP4 if needed
if not with_vocals_file.endswith(".mp4"):
with_vocals_mp4_command = (
f'{self.ffmpeg_base_command} -i "{with_vocals_file}" -c:v libx264 -c:a aac "{output_files["with_vocals_mp4"]}"'
)
self.execute_command(with_vocals_mp4_command, "Converting with vocals video to MP4")
self.convert_mov_to_mp4(with_vocals_file, output_files["with_vocals_mp4"])
# Delete the with vocals mov after successfully converting it to mp4
if not self.dry_run and os.path.isfile(with_vocals_file):
@@ -556,36 +690,26 @@ class KaraokeFinalise:
# Quote file paths to handle special characters
title_mov_file = shlex.quote(os.path.abspath(input_files["title_mov"]))
karaoke_mov_file = shlex.quote(os.path.abspath(output_files["karaoke_mov"]))
output_final_mp4_file = shlex.quote(output_files["final_karaoke_mp4"])
karaoke_mp4_file = shlex.quote(os.path.abspath(output_files["karaoke_mp4"]))
env_mov_input = ""
ffmpeg_filter = '-filter_complex "[0:v:0][0:a:0][1:v:0][1:a:0]concat=n=2:v=1:a=1[outv][outa]"'
# Prepare concat filter for combining videos
env_mov_input, ffmpeg_filter = self.prepare_concat_filter(input_files)
# Check if end_mov file exists and include it in the concat command
if "end_mov" in input_files and os.path.isfile(input_files["end_mov"]):
self.logger.info(f"Found end_mov file: {input_files['end_mov']}, including in final MP4")
end_mov_file = shlex.quote(os.path.abspath(input_files["end_mov"]))
env_mov_input = f"-i {end_mov_file}"
ffmpeg_filter = '-filter_complex "[0:v:0][0:a:0][1:v:0][1:a:0][2:v:0][2:a:0]concat=n=3:v=1:a=1[outv][outa]"'
# Create all output versions
self.encode_lossless_mp4(title_mov_file, karaoke_mp4_file, env_mov_input, ffmpeg_filter, output_files["final_karaoke_lossless_mp4"])
self.encode_lossy_mp4(output_files["final_karaoke_lossless_mp4"], output_files["final_karaoke_lossy_mp4"])
self.encode_lossless_mkv(output_files["final_karaoke_lossless_mp4"], output_files["final_karaoke_lossless_mkv"])
self.encode_720p_version(output_files["final_karaoke_lossless_mp4"], output_files["final_karaoke_lossy_720p_mp4"])
aac_codec = "libfdk_aac"
# Check if aac_at codec is available
codec_check_command = f"{self.ffmpeg_base_command} -codecs"
result = os.popen(codec_check_command).read()
if "aac_at" in result:
aac_codec = "aac_at"
join_ffmpeg_command = f'{self.ffmpeg_base_command} -i {title_mov_file} -i {karaoke_mov_file} {env_mov_input} {ffmpeg_filter} -map "[outv]" -map "[outa]" -c:v libx264 -c:a {aac_codec} -q:a 14 {output_final_mp4_file}'
self.logger.debug(f"Running command: {join_ffmpeg_command}")
self.execute_command(join_ffmpeg_command, "Joining title and instrumental videos")
# Prompt user to check final MP4 file before proceeding
# Prompt user to check final video files before proceeding
self.prompt_user_confirmation_or_raise_exception(
f"Final MP4 file created: {output_files['final_karaoke_mp4']}, please check it! Proceed?",
"Refusing to proceed without user confirmation they're happy with the Final MP4.",
f"Final video files created:\n"
f"- Lossless 4K MP4: {output_files['final_karaoke_lossless_mp4']}\n"
f"- Lossless 4K MKV: {output_files['final_karaoke_lossless_mkv']}\n"
f"- Lossy 4K MP4: {output_files['final_karaoke_lossy_mp4']}\n"
f"- Lossy 720p MP4: {output_files['final_karaoke_lossy_720p_mp4']}\n"
f"Please check them! Proceed?",
"Refusing to proceed without user confirmation they're happy with the Final videos.",
allow_empty=True,
)
@@ -600,42 +724,57 @@ class KaraokeFinalise:
self.logger.info(f"Skipping CDG ZIP file creation, existing file will be used.")
return
# Generate CDG and MP3 files
# Check if individual MP3 and CDG files already exist
if os.path.isfile(output_files["karaoke_mp3"]) and os.path.isfile(output_files["karaoke_cdg"]):
self.logger.info(f"Found existing MP3 and CDG files, creating ZIP file directly")
if not self.dry_run:
with zipfile.ZipFile(output_files["final_karaoke_cdg_zip"], "w") as zipf:
zipf.write(output_files["karaoke_mp3"], os.path.basename(output_files["karaoke_mp3"]))
zipf.write(output_files["karaoke_cdg"], os.path.basename(output_files["karaoke_cdg"]))
self.logger.info(f"Created CDG ZIP file: {output_files['final_karaoke_cdg_zip']}")
return
# Generate CDG and MP3 files if they don't exist
if self.dry_run:
self.logger.info(f"DRY RUN: Would generate CDG and MP3 files")
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"
generator = CDGGenerator(output_dir=os.getcwd(), logger=self.logger)
cdg_file, mp3_file, zip_file = generator.generate_cdg_from_lrc(
lrc_file=input_files["karaoke_lrc"],
audio_file=input_files["instrumental_audio"],
title=title,
artist=artist,
cdg_styles=self.cdg_styles,
)
self.logger.info(f"Searching for CDG ZIP file. Expected: {expected_zip}")
# Rename the generated ZIP file to match our expected naming convention
if os.path.isfile(zip_file):
os.rename(zip_file, output_files["final_karaoke_cdg_zip"])
self.logger.info(f"Renamed CDG ZIP file from {zip_file} to {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']}")
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 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']}")
self.logger.info(f"CDG ZIP file created: {output_files['final_karaoke_cdg_zip']}")
self.logger.info(f"CDG ZIP file created: {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()
# 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")
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...")
@@ -670,26 +809,17 @@ class KaraokeFinalise:
self.logger.info(f"TXT ZIP file created: {output_files['final_karaoke_txt_zip']}")
def encode_720p_version(self, input_file, output_file):
ffmpeg_command = (
f'{self.ffmpeg_base_command} -i "{input_file}" '
f'-c:v libx264 -vf "scale=1280:720" -b:v 200k -preset medium -tune animation '
f'-c:a copy "{output_file}"'
)
self.execute_command(ffmpeg_command, "Encoding 720p version of the final video")
def move_files_to_brand_code_folder(self, brand_code, artist, title, output_files):
self.logger.info(f"Moving files to new brand-prefixed directory...")
self.new_brand_code_dir = f"{brand_code} - {artist} - {title}"
self.new_brand_code_dir_path = os.path.join(self.organised_dir, self.new_brand_code_dir)
self.prompt_user_confirmation_or_raise_exception(
f"Move files to new brand-prefixed directory {self.new_brand_code_dir_path} and delete current dir?",
"Refusing to move files without user confirmation of move.",
allow_empty=True,
)
# self.prompt_user_confirmation_or_raise_exception(
# f"Move files to new brand-prefixed directory {self.new_brand_code_dir_path} and delete current dir?",
# "Refusing to move files without user confirmation of move.",
# allow_empty=True,
# )
orig_dir = os.getcwd()
os.chdir(os.path.dirname(orig_dir))
@@ -735,8 +865,8 @@ class KaraokeFinalise:
f"DRY RUN: Would copy final MP4, 720p MP4, and ZIP to {dest_mp4_file}, {dest_720p_mp4_file}, and {dest_zip_file}"
)
else:
shutil.copy2(output_files["final_karaoke_mp4"], dest_mp4_file)
shutil.copy2(output_files["final_karaoke_720p_mp4"], dest_720p_mp4_file)
shutil.copy2(output_files["final_karaoke_lossy_mp4"], dest_mp4_file) # Changed to use lossy MP4
shutil.copy2(output_files["final_karaoke_lossy_720p_mp4"], dest_720p_mp4_file)
shutil.copy2(output_files["final_karaoke_cdg_zip"], dest_zip_file)
self.logger.info(f"Copied final files to public share directory")
@@ -794,6 +924,19 @@ class KaraokeFinalise:
self.logger.error(f"Command output (stderr): {e.stderr}")
self.logger.error(f"Full exception: {e}")
def get_existing_brand_code(self):
"""Extract brand code from current directory name"""
current_dir = os.path.basename(os.getcwd())
if " - " not in current_dir:
raise Exception(f"Current directory '{current_dir}' does not match expected format 'BRAND-XXXX - Artist - Title'")
brand_code = current_dir.split(" - ")[0]
if not brand_code or "-" not in brand_code:
raise Exception(f"Could not extract valid brand code from directory name '{current_dir}'")
self.logger.info(f"Using existing brand code: {brand_code}")
return brand_code
def execute_optional_features(self, artist, title, base_name, input_files, output_files):
self.logger.info(f"Executing optional features...")
@@ -812,7 +955,16 @@ class KaraokeFinalise:
self.post_discord_notification()
if self.folder_organisation_enabled:
self.brand_code = self.get_next_brand_code()
if self.keep_brand_code:
self.brand_code = self.get_existing_brand_code()
self.new_brand_code_dir = os.path.basename(os.getcwd())
self.new_brand_code_dir_path = os.getcwd()
else:
self.brand_code = self.get_next_brand_code()
self.move_files_to_brand_code_folder(self.brand_code, artist, title, output_files)
# Update output file paths after moving
for key in output_files:
output_files[key] = os.path.join(self.new_brand_code_dir_path, os.path.basename(output_files[key]))
if self.public_share_copy_enabled:
self.copy_final_files_to_public_share_dirs(self.brand_code, base_name, output_files)
@@ -820,8 +972,6 @@ class KaraokeFinalise:
if self.public_share_rclone_enabled:
self.sync_public_share_dir_to_rclone_destination()
self.move_files_to_brand_code_folder(self.brand_code, artist, title, output_files)
self.generate_organised_folder_sharing_link()
def authenticate_gmail(self):
@@ -887,6 +1037,23 @@ class KaraokeFinalise:
self.logger.info("Email template test complete. Check your Gmail drafts for the test email.")
def detect_best_aac_codec(self):
"""Detect the best available AAC codec (aac_at > libfdk_aac > aac)"""
self.logger.info("Detecting best available AAC codec...")
codec_check_command = f"{self.ffmpeg_base_command} -codecs"
result = os.popen(codec_check_command).read()
if "aac_at" in result:
self.logger.info("Using aac_at codec (best quality)")
return "aac_at"
elif "libfdk_aac" in result:
self.logger.info("Using libfdk_aac codec (good quality)")
return "libfdk_aac"
else:
self.logger.info("Using built-in aac codec (basic quality)")
return "aac"
def process(self):
if self.dry_run:
self.logger.warning("Dry run enabled. No actions will be performed.")
@@ -909,7 +1076,6 @@ class KaraokeFinalise:
self.create_txt_zip_file(input_files, output_files)
self.remux_and_encode_output_video_files(with_vocals_file, input_files, output_files)
self.encode_720p_version(output_files["final_karaoke_mp4"], output_files["final_karaoke_720p_mp4"])
self.execute_optional_features(artist, title, base_name, input_files, output_files)
@@ -917,9 +1083,11 @@ class KaraokeFinalise:
"artist": artist,
"title": title,
"video_with_vocals": output_files["with_vocals_mp4"],
"video_with_instrumental": output_files["karaoke_mov"],
"final_video": output_files["final_karaoke_mp4"],
"final_video_720p": output_files["final_karaoke_720p_mp4"],
"video_with_instrumental": output_files["karaoke_mp4"],
"final_video": output_files["final_karaoke_lossless_mp4"],
"final_video_mkv": output_files["final_karaoke_lossless_mkv"],
"final_video_lossy": output_files["final_karaoke_lossy_mp4"],
"final_video_720p": output_files["final_karaoke_lossy_720p_mp4"],
"youtube_url": self.youtube_url,
"brand_code": self.brand_code,
"new_brand_code_dir_path": self.new_brand_code_dir_path,
File diff suppressed because it is too large. Load diff
Binary file not shown.
Binary file not shown.
+231
View File
@@ -0,0 +1,231 @@
#!/usr/bin/env python
import argparse
import logging
import pkg_resources
import os
import sys
import asyncio
import json
from karaoke_prep import KaraokePrep
from karaoke_prep.karaoke_finalise import KaraokeFinalise
async def async_main():
logger = logging.getLogger(__name__)
log_handler = logging.StreamHandler()
log_formatter = logging.Formatter(fmt="%(asctime)s.%(msecs)03d - %(levelname)s - %(module)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log_handler.setFormatter(log_formatter)
logger.addHandler(log_handler)
parser = argparse.ArgumentParser(
description="Automatically prepare and finalise karaoke videos in one step, combining karaoke-prep and karaoke-finalise functionality.",
formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=54),
)
# Basic information (from prep_cli.py)
parser.add_argument(
"args",
nargs="*",
help="[Media or playlist URL] [Artist] [Title] of song to prep. If URL is provided, Artist and Title are optional but increase chance of fetching the correct lyrics. If Artist and Title are provided with no URL, the top YouTube search result will be fetched.",
)
package_version = pkg_resources.get_distribution("karaoke-prep").version
parser.add_argument("-v", "--version", action="version", version=f"%(prog)s {package_version}")
# Common arguments for both prep and finalise
parser.add_argument(
"--log_level",
default="info",
help="Optional: logging level, e.g. info, debug, warning (default: %(default)s). Example: --log_level=debug",
)
parser.add_argument(
"--dry_run",
action="store_true",
help="Optional: perform a dry run without making any changes. Example: --dry_run",
)
parser.add_argument(
"--style_params_json",
help="Optional: Path to JSON file containing style configuration. Example: --style_params_json='/path/to/style_params.json'",
)
# Prep-specific arguments (add any additional prep arguments you commonly use)
parser.add_argument(
"--output_dir",
default=".",
help="Optional: directory to write output files (default: <current dir>). Example: --output_dir=/app/karaoke",
)
parser.add_argument(
"--no_track_subfolders",
action="store_false",
dest="create_track_subfolders",
help="Optional: do NOT create a named subfolder for each track. Example: --no_track_subfolders",
)
parser.add_argument(
"--existing_instrumental",
help="Optional: Path to an existing instrumental audio file. If provided, audio separation will be skipped.",
)
parser.add_argument(
"--lyrics_file",
help="Optional: Path to a file containing lyrics to use instead of fetching from online. Example: --lyrics_file='/path/to/lyrics.txt'",
)
parser.add_argument(
"--subtitle_offset_ms",
type=int,
default=0,
help="Optional: Adjust subtitle timing by N milliseconds (+ve delays, -ve advances). Example: --subtitle_offset_ms=500",
)
# Finalise-specific arguments
parser.add_argument(
"--enable_cdg",
action="store_true",
help="Optional: Enable CDG ZIP generation during finalisation. Example: --enable_cdg",
)
parser.add_argument(
"--enable_txt",
action="store_true",
help="Optional: Enable TXT ZIP generation during finalisation. Example: --enable_txt",
)
parser.add_argument(
"--brand_prefix",
help="Optional: Your brand prefix to calculate the next sequential number. Example: --brand_prefix=BRAND",
)
parser.add_argument(
"--organised_dir",
help="Optional: Target directory where the processed folder will be moved. Example: --organised_dir='/path/to/Tracks-Organized'",
)
parser.add_argument(
"--organised_dir_rclone_root",
help="Optional: Rclone path which maps to your organised_dir. Example: --organised_dir_rclone_root='dropbox:Media/Karaoke/Tracks-Organized'",
)
parser.add_argument(
"--public_share_dir",
help="Optional: Public share directory for final files. Example: --public_share_dir='/path/to/Tracks-PublicShare'",
)
parser.add_argument(
"--youtube_client_secrets_file",
help="Optional: Path to youtube client secrets file. Example: --youtube_client_secrets_file='/path/to/client_secret.json'",
)
parser.add_argument(
"--youtube_description_file",
help="Optional: Path to youtube description template. Example: --youtube_description_file='/path/to/description.txt'",
)
parser.add_argument(
"--rclone_destination",
help="Optional: Rclone destination for public_share_dir sync. Example: --rclone_destination='googledrive:KaraokeFolder'",
)
parser.add_argument(
"--discord_webhook_url",
help="Optional: Discord webhook URL for notifications. Example: --discord_webhook_url='https://discord.com/api/webhooks/...'",
)
parser.add_argument(
"--email_template_file",
help="Optional: Path to email template file. Example: --email_template_file='/path/to/template.txt'",
)
args = parser.parse_args()
# Parse input arguments similar to prep_cli.py
input_media, artist, title = None, None, None
if not args.args:
parser.print_help()
sys.exit(1)
if args.args[0].startswith(("http://", "https://")) or os.path.isfile(args.args[0]):
input_media = args.args[0]
if len(args.args) > 2:
artist = args.args[1]
title = args.args[2]
elif len(args.args) > 1:
artist = args.args[0]
title = args.args[1]
else:
parser.print_help()
sys.exit(1)
log_level = getattr(logging, args.log_level.upper())
logger.setLevel(log_level)
# Step 1: Run KaraokePrep
logger.info("Starting preparation phase...")
kprep = KaraokePrep(
artist=artist,
title=title,
input_media=input_media,
dry_run=args.dry_run,
log_formatter=log_formatter,
log_level=log_level,
output_dir=args.output_dir,
create_track_subfolders=True if not hasattr(args, "create_track_subfolders") else args.create_track_subfolders,
style_params_json=args.style_params_json,
existing_instrumental=args.existing_instrumental,
lyrics_file=args.lyrics_file,
subtitle_offset_ms=args.subtitle_offset_ms,
)
tracks = await kprep.process()
# Step 2: For each track, run KaraokeFinalise
for track in tracks:
logger.info(f"Starting finalisation phase for {track['artist']} - {track['title']}...")
# Use the track directory that was actually created by KaraokePrep
track_dir = track["track_output_dir"]
if not os.path.exists(track_dir):
logger.error(f"Track directory not found: {track_dir}")
continue
logger.info(f"Changing to directory: {track_dir}")
os.chdir(track_dir)
# Load CDG styles if CDG generation is enabled
cdg_styles = None
if args.enable_cdg:
if not args.style_params_json:
logger.error("CDG styles JSON file path (--style_params_json) is required when --enable_cdg is used")
sys.exit(1)
try:
with open(args.style_params_json, "r") as f:
style_params = json.loads(f.read())
cdg_styles = style_params["cdg"]
except FileNotFoundError:
logger.error(f"CDG styles configuration file not found: {args.style_params_json}")
sys.exit(1)
except json.JSONDecodeError as e:
logger.error(f"Invalid JSON in CDG styles configuration file: {e}")
sys.exit(1)
# Initialize KaraokeFinalise
kfinalise = KaraokeFinalise(
log_formatter=log_formatter,
log_level=log_level,
dry_run=args.dry_run,
enable_cdg=args.enable_cdg,
enable_txt=args.enable_txt,
brand_prefix=args.brand_prefix,
organised_dir=args.organised_dir,
organised_dir_rclone_root=args.organised_dir_rclone_root,
public_share_dir=args.public_share_dir,
youtube_client_secrets_file=args.youtube_client_secrets_file,
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:
final_track = kfinalise.process()
logger.info(f"Successfully completed auto processing for: {track['artist']} - {track['title']}")
except Exception as e:
logger.error(f"Error during finalisation: {str(e)}")
raise e
def main():
asyncio.run(async_main())
if __name__ == "__main__":
main()
+237
View File
@@ -0,0 +1,237 @@
#!/usr/bin/env python
import argparse
import logging
import pkg_resources
import os
import csv
import asyncio
import json
import sys
from karaoke_prep import KaraokePrep
from karaoke_prep.karaoke_finalise import KaraokeFinalise
# Global logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO) # Set initial log level
async def process_track(row, args, logger, log_formatter):
"""Process a single track through prep and finalise stages"""
original_dir = os.getcwd() # Store the original directory
try:
# Extract track info from CSV row
artist = row["Artist"].strip() # Remove leading/trailing whitespace
title = row["Title"].strip()
guide_file = row["Mixed Audio Filename"].strip()
instrumental_file = row["Instrumental Audio Filename"].strip()
logger.info(f"Processing track: {artist} - {title}")
# Initialize KaraokePrep
kprep = KaraokePrep(
artist=artist,
title=title,
input_media=guide_file,
existing_instrumental=instrumental_file,
style_params_json=args.style_params_json,
log_formatter=log_formatter,
log_level=args.log_level,
dry_run=args.dry_run,
skip_transcription_review=True,
create_track_subfolders=True,
)
tracks = await kprep.process()
# Step 2: For each track, run KaraokeFinalise
for track in tracks:
logger.info(f"Starting finalisation phase for {track['artist']} - {track['title']}...")
# Look for the track directory, trying different possible formats
possible_dirs = [
os.path.join(args.output_dir, f"{track['artist']} - {track['title']}"),
os.path.join(args.output_dir, f"{artist} - {title}"),
os.path.join(args.output_dir, f"{artist.replace(' ', ' ')} - {title}"),
]
track_dir = None
for possible_dir in possible_dirs:
if os.path.exists(possible_dir):
track_dir = possible_dir
break
if track_dir is None:
logger.error(f"Track directory not found. Tried: {possible_dirs}")
continue
logger.info(f"Changing to directory: {track_dir}")
os.chdir(track_dir)
# Load CDG styles if CDG generation is enabled
cdg_styles = None
if args.enable_cdg:
if not args.style_params_json:
logger.error("CDG styles JSON file path (--style_params_json) is required when --enable_cdg is used")
sys.exit(1)
try:
with open(args.style_params_json, "r") as f:
style_params = json.loads(f.read())
cdg_styles = style_params["cdg"]
except FileNotFoundError:
logger.error(f"CDG styles configuration file not found: {args.style_params_json}")
sys.exit(1)
except json.JSONDecodeError as e:
logger.error(f"Invalid JSON in CDG styles configuration file: {e}")
sys.exit(1)
# Initialize KaraokeFinalise
kfinalise = KaraokeFinalise(
log_formatter=log_formatter,
log_level=args.log_level,
dry_run=args.dry_run,
enable_cdg=args.enable_cdg,
enable_txt=args.enable_txt,
cdg_styles=cdg_styles,
non_interactive=True,
)
try:
final_track = kfinalise.process()
logger.info(f"Successfully completed auto processing for: {track['artist']} - {track['title']}")
except Exception as e:
logger.error(f"Error during finalisation: {str(e)}")
raise e
# Always return to the original directory after processing
os.chdir(original_dir)
return True
except Exception as e:
logger.error(f"Failed to process {artist} - {title}: {str(e)}")
return False
finally:
# Ensure we return to the original directory even if an error occurred
os.chdir(original_dir)
def update_csv_status(csv_path, row_index, new_status):
"""Update the status of a processed row in the CSV file"""
# Read all rows
with open(csv_path, "r") as f:
rows = list(csv.DictReader(f))
# Update status for the processed row
rows[row_index]["Status"] = new_status
# Write back to CSV
fieldnames = rows[0].keys()
with open(csv_path, "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
async def async_main():
parser = argparse.ArgumentParser(
description="Process multiple karaoke tracks in bulk from a CSV file.",
formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=54),
)
# Basic information
parser.add_argument(
"input_csv",
help="Path to CSV file containing tracks to process. CSV should have columns: Artist,Title,Mixed Audio Filename,Instrumental Audio Filename,Status",
)
package_version = pkg_resources.get_distribution("karaoke-prep").version
parser.add_argument("-v", "--version", action="version", version=f"%(prog)s {package_version}")
# Required arguments
parser.add_argument(
"--style_params_json",
required=True,
help="Path to style parameters JSON file",
)
parser.add_argument(
"--output_dir",
default=".",
help="Optional: directory to write output files (default: <current dir>). Example: --output_dir=/app/karaoke",
)
# Finalise-specific arguments
parser.add_argument(
"--enable_cdg",
action="store_true",
help="Optional: Enable CDG ZIP generation during finalisation. Example: --enable_cdg",
)
parser.add_argument(
"--enable_txt",
action="store_true",
help="Optional: Enable TXT ZIP generation during finalisation. Example: --enable_txt",
)
# Logging & Debugging
parser.add_argument(
"--log_level",
default="info",
help="Optional: logging level, e.g. info, debug, warning (default: %(default)s). Example: --log_level=debug",
)
parser.add_argument(
"--dry_run",
action="store_true",
help="Optional: perform a dry run without making any changes (default: %(default)s). Example: --dry_run",
)
args = parser.parse_args()
# Convert input_csv to absolute path
args.input_csv = os.path.abspath(args.input_csv)
if not os.path.isfile(args.input_csv):
logger.error(f"Input CSV file not found: {args.input_csv}")
exit(1)
# Fix: Convert log level to uppercase before getting attribute
log_level = getattr(logging, args.log_level.upper())
args.log_level = log_level # Store the numeric log level in args
logger.info(f"Starting bulk processing with input CSV: {args.input_csv}")
# Read and process CSV
with open(args.input_csv, "r") as f:
reader = csv.DictReader(f)
rows = list(reader) # Convert to list to allow multiple passes
for i, row in enumerate(rows):
if row["Status"].lower() != "uploaded":
logger.info(f"Skipping {row['Artist']} - {row['Title']} (Status: {row['Status']})")
continue
logger.info(f"Starting processing of {row['Artist']} - {row['Title']}")
success = await process_track(row, args, logger, log_formatter)
if not args.dry_run:
if success:
update_csv_status(args.input_csv, i, "Completed")
logger.info(f"Successfully processed {row['Artist']} - {row['Title']}")
else:
update_csv_status(args.input_csv, i, "Failed")
logger.error(f"Failed to process {row['Artist']} - {row['Title']}")
def main():
# Set up logging only once
global log_formatter # Make log_formatter accessible to other functions
log_handler = logging.StreamHandler()
log_formatter = logging.Formatter(fmt="%(asctime)s.%(msecs)03d - %(levelname)s - %(module)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log_handler.setFormatter(log_formatter)
logger.addHandler(log_handler)
# Run the async main function using asyncio
asyncio.run(async_main())
if __name__ == "__main__":
main()
+81 -9
View File
@@ -4,6 +4,9 @@ import logging
import pkg_resources
import os
import sys
import json
import pyperclip
import time
from karaoke_prep.karaoke_finalise import KaraokeFinalise
@@ -16,7 +19,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 +122,25 @@ def main():
help="Optional: Test the email template functionality with fake data. Example: --test_email_template",
)
parser.add_argument(
"--style_params_json",
default=None,
help="Optional: Path to JSON file containing CDG style configuration. Required if --enable_cdg is used. Example: --style_params_json='/path/to/cdg_styles.json'",
)
parser.add_argument(
"--keep-brand-code",
action="store_true",
help="Optional: Use existing brand code from current directory instead of generating new one (default: disabled). Example: --keep-brand-code",
)
parser.add_argument(
"-y",
"--yes",
action="store_true",
help="Optional: Run in non-interactive mode, assuming yes to all prompts (default: disabled). Example: -y",
)
args = parser.parse_args()
log_level = getattr(logging, args.log_level.upper())
@@ -126,6 +148,23 @@ 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.style_params_json:
logger.error("CDG styles JSON file path (--style_params_json) is required when --enable_cdg is used")
sys.exit(1)
try:
with open(args.style_params_json, "r") as f:
style_params = json.loads(f.read())
cdg_styles = style_params["cdg"]
except FileNotFoundError:
logger.error(f"CDG styles configuration file not found: {args.style_params_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 +182,9 @@ 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,
keep_brand_code=args.keep_brand_code,
non_interactive=args.yes,
)
if args.test_email_template:
@@ -158,23 +200,53 @@ def main():
logger.info(f"Karaoke finalisation processing complete! Output files:")
logger.info(f"")
logger.info(f"Track: {track['artist']} - {track['title']}")
logger.info(f"")
logger.info(f"Working Files:")
logger.info(f" Video With Vocals: {track['video_with_vocals']}")
logger.info(f" Video With Instrumental: {track['video_with_instrumental']}")
logger.info(f"")
logger.info(f"Final Videos:")
logger.info(f" Lossless 4K MP4 (PCM): {track['final_video']}")
logger.info(f" Lossless 4K MKV (FLAC): {track['final_video_mkv']}")
logger.info(f" Lossy 4K MP4 (AAC): {track['final_video_lossy']}")
logger.info(f" Lossy 720p MP4 (AAC): {track['final_video_720p']}")
if "final_karaoke_cdg_zip" in track or "final_karaoke_txt_zip" in track:
logger.info(f"")
logger.info(f"Karaoke Files:")
if "final_karaoke_cdg_zip" in track:
logger.info(f" Final CDG+MP3 ZIP: {track['final_karaoke_cdg_zip']}")
logger.info(f" CDG+MP3 ZIP: {track['final_karaoke_cdg_zip']}")
if "final_karaoke_txt_zip" in track:
logger.info(f" Final TXT+MP3 ZIP: {track['final_karaoke_txt_zip']}")
logger.info(f" TXT+MP3 ZIP: {track['final_karaoke_txt_zip']}")
logger.info(f" Final Video with Title: {track['final_video']}")
logger.info(f" Final Video 720p: {track['final_video_720p']}")
if track["brand_code"]:
logger.info(f"")
logger.info(f"Organization:")
logger.info(f" Brand Code: {track['brand_code']}")
logger.info(f" New Directory: {track['new_brand_code_dir_path']}")
logger.info(f" Brand Code: {track['brand_code']}")
logger.info(f" New Brand Code Directory: {track['new_brand_code_dir_path']}")
if track["youtube_url"] or track["brand_code_dir_sharing_link"]:
logger.info(f"")
logger.info(f"Sharing:")
logger.info(f" YouTube URL: {track['youtube_url']}")
logger.info(f" Folder Sharing Link: {track['brand_code_dir_sharing_link']}")
if track["brand_code_dir_sharing_link"]:
logger.info(f" Folder Link: {track['brand_code_dir_sharing_link']}")
try:
time.sleep(1) # Brief pause between clipboard operations
pyperclip.copy(track["brand_code_dir_sharing_link"])
logger.info(f" (Folder link copied to clipboard)")
except Exception as e:
logger.warning(f" Failed to copy folder link to clipboard: {str(e)}")
if track["youtube_url"]:
logger.info(f" YouTube URL: {track['youtube_url']}")
try:
pyperclip.copy(track["youtube_url"])
logger.info(f" (YouTube URL copied to clipboard)")
except Exception as e:
logger.warning(f" Failed to copy YouTube URL to clipboard: {str(e)}")
if __name__ == "__main__":
+104 -230
View File
@@ -4,7 +4,10 @@ import logging
import pkg_resources
import tempfile
import os
import json
import sys
from karaoke_prep import KaraokePrep
import asyncio
def is_url(string):
@@ -17,7 +20,7 @@ def is_file(string):
return os.path.isfile(string)
def main():
async def async_main():
logger = logging.getLogger(__name__)
log_handler = logging.StreamHandler()
log_formatter = logging.Formatter(fmt="%(asctime)s.%(msecs)03d - %(levelname)s - %(module)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
@@ -29,6 +32,7 @@ def main():
formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=54),
)
# Basic information
parser.add_argument(
"args",
nargs="*",
@@ -38,36 +42,68 @@ def main():
package_version = pkg_resources.get_distribution("karaoke-prep").version
parser.add_argument("-v", "--version", action="version", version=f"%(prog)s {package_version}")
# Logging & Debugging
parser.add_argument(
"--log_level",
default="info",
help="Optional: logging level, e.g. info, debug, warning (default: %(default)s). Example: --log_level=debug",
)
parser.add_argument(
"--filename_pattern",
help="Required if processing a folder: Python regex pattern to extract track names from filenames. Must contain a named group 'title'. Example: --filename_pattern='(?P<index>\\d+) - (?P<title>.+).mp3'",
)
parser.add_argument(
"--dry_run",
action="store_true",
help="Optional: perform a dry run without making any changes (default: %(default)s). Example: --dry_run=true",
)
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",
)
# Input/Output Configuration
parser.add_argument(
"--filename_pattern",
help="Required if processing a folder: Python regex pattern to extract track names from filenames. Must contain a named group 'title'. Example: --filename_pattern='(?P<index>\\d+) - (?P<title>.+).mp3'",
)
parser.add_argument(
"--output_dir",
default=".",
help="Optional: directory to write output files (default: <current dir>). Example: --output_dir=/app/karaoke",
)
parser.add_argument(
"--no_track_subfolders",
action="store_false",
help="Optional: do NOT create a named subfolder for each track. Example: --no_track_subfolders",
)
parser.add_argument(
"--lossless_output_format",
default="FLAC",
help="Optional: lossless output format for separated audio (default: FLAC). Example: --lossless_output_format=WAV",
)
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",
)
# Audio Processing Configuration
parser.add_argument(
"--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=["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="+",
@@ -87,38 +123,16 @@ def main():
default=default_model_dir,
help="Optional: model files directory (default: %(default)s). Example: --model_file_dir=/app/models",
)
parser.add_argument(
"--output_dir",
default=".",
help="Optional: directory to write output files (default: <current dir>). Example: --output_dir=/app/karaoke",
"--existing_instrumental",
help="Optional: Path to an existing instrumental audio file. If provided, audio separation will be skipped.",
)
parser.add_argument(
"--lossless_output_format",
default="FLAC",
help="Optional: lossless output format for separated audio (default: FLAC). Example: --lossless_output_format=WAV",
)
parser.add_argument(
"--use_cuda",
action="store_true",
help="Optional: use Nvidia GPU with CUDA for separation (default: %(default)s). Example: --use_cuda=true",
)
parser.add_argument(
"--use_coreml",
action="store_true",
help="Optional: use Apple Silicon GPU with CoreML for separation (default: %(default)s). Example: --use_coreml=true",
)
parser.add_argument(
"--denoise",
type=lambda x: (str(x).lower() == "true"),
default=True,
help="Optional: enable or disable denoising during separation (default: %(default)s). Example: --denoise=False",
)
parser.add_argument(
"--normalize",
type=lambda x: (str(x).lower() == "true"),
@@ -126,186 +140,52 @@ def main():
help="Optional: enable or disable normalization during separation (default: %(default)s). Example: --normalize=False",
)
# Hardware Acceleration
parser.add_argument(
"--no_track_subfolders",
action="store_false",
help="Optional: do NOT create a named subfolder for each track. Example: --no_track_subfolders",
"--use_cuda",
action="store_true",
help="Optional: use Nvidia GPU with CUDA for separation (default: %(default)s). Example: --use_cuda=true",
)
parser.add_argument(
"--intro_background_color",
default="#000000",
help="Optional: Background color for intro video (default: black). Example: --intro_background_color=#123456",
)
parser.add_argument(
"--intro_background_image",
help="Optional: Path to background image for intro video. Overrides background color if provided. Example: --intro_background_image=path/to/image.jpg",
)
parser.add_argument(
"--intro_font",
default="Montserrat-Bold.ttf",
help="Optional: Font file for intro video (default: Montserrat-Bold.ttf). Example: --intro_font=AvenirNext-Bold.ttf",
)
parser.add_argument(
"--intro_artist_color",
default="#ffdf6b",
help="Optional: Font color for intro video artist text (default: #ffdf6b). Example: --intro_artist_color=#123456",
)
parser.add_argument(
"--intro_title_color",
default="#ffffff",
help="Optional: Font color for intro video title text (default: #ffffff). Example: --intro_title_color=#123456",
)
parser.add_argument(
"--existing_instrumental",
help="Optional: Path to an existing instrumental audio file. If provided, audio separation will be skipped.",
)
parser.add_argument(
"--existing_title_image",
help="Optional: Path to an existing title image file. If provided, title image generation will be skipped.",
)
parser.add_argument(
"--end_background_color",
default="#000000",
help="Optional: Background color for end screen video (default: black). Example: --end_background_color=#123456",
)
parser.add_argument(
"--end_background_image",
help="Optional: Path to background image for end screen video. Overrides background color if provided. Example: --end_background_image=path/to/image.jpg",
)
parser.add_argument(
"--end_extra_text",
default="THANK YOU FOR SINGING!",
help="Optional: Extra text to display on the end screen video. Example: --end_extra_text='THANK YOU FOR WATCHING!'",
)
parser.add_argument(
"--end_font",
default="Montserrat-Bold.ttf",
help="Optional: Font file for end screen video (default: Montserrat-Bold.ttf). Example: --end_font=AvenirNext-Bold.ttf",
)
parser.add_argument(
"--end_extra_text_color",
default="#ff7acc",
help="Optional: Font color for end screen video text (default: #ffffff). Example: --end_extra_text_color=#123456",
)
parser.add_argument(
"--end_artist_color",
default="#ffdf6b",
help="Optional: Font color for end screen video artist text (default: #ffdf6b). Example: --end_artist_color=#123456",
)
parser.add_argument(
"--end_title_color",
default="#ffffff",
help="Optional: Font color for end screen video title text (default: #ffffff). Example: --end_title_color=#123456",
)
parser.add_argument(
"--existing_end_image",
help="Optional: Path to an existing end screen image file. If provided, end screen image generation will be skipped.",
)
parser.add_argument(
"--intro_video_duration",
type=int,
default=5,
help="Optional: duration of the title video in seconds (default: 5). Example: --intro_video_duration=10",
)
parser.add_argument(
"--end_video_duration",
type=int,
default=5,
help="Optional: duration of the end video in seconds (default: 5). Example: --end_video_duration=10",
"--use_coreml",
action="store_true",
help="Optional: use Apple Silicon GPU with CoreML for separation (default: %(default)s). Example: --use_coreml=true",
)
# Lyrics Configuration
parser.add_argument(
"--lyrics_artist",
help="Optional: Override the artist name used for lyrics search. Example: --lyrics_artist='The Beatles'",
)
parser.add_argument(
"--lyrics_title",
help="Optional: Override the song title used for lyrics search. Example: --lyrics_title='Hey Jude'",
)
parser.add_argument(
"--lyrics_file",
help="Optional: Path to a file containing lyrics to use instead of fetching from online. Example: --lyrics_file='/path/to/lyrics.txt'",
)
parser.add_argument(
"--skip_lyrics",
action="store_true",
help="Optional: Skip fetching and processing lyrics. Example: --skip_lyrics",
)
parser.add_argument(
"--render_bounding_boxes",
"--skip_transcription",
action="store_true",
help="Optional: render bounding boxes around text regions for debugging (default: %(default)s). Example: --render_bounding_boxes",
help="Optional: Skip audio transcription but still attempt to fetch lyrics from Spotify/Genius. Example: --skip_transcription",
)
parser.add_argument(
"--subtitle_offset_ms",
type=int,
default=0,
help="Optional: Adjust subtitle timing by N milliseconds (+ve delays, -ve advances). Example: --subtitle_offset_ms=500",
)
# Style Configuration
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",
"--style_params_json",
help="Optional: Path to JSON file containing style configuration for intro/end videos. Example: --style_params_json='/path/to/style_params.json'",
)
args = parser.parse_args()
@@ -354,66 +234,48 @@ def main():
log_level = getattr(logging, args.log_level.upper())
logger.setLevel(log_level)
if args.existing_instrumental:
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}")
kprep = KaraokePrep(
# Basic inputs
artist=artist,
title=title,
input_media=input_media,
filename_pattern=filename_pattern,
# Logging & Debugging
dry_run=args.dry_run,
log_formatter=log_formatter,
log_level=log_level,
render_bounding_boxes=args.render_bounding_boxes,
# Input/Output Configuration
filename_pattern=filename_pattern,
output_dir=args.output_dir,
create_track_subfolders=args.no_track_subfolders,
lossless_output_format=args.lossless_output_format,
output_png=args.output_png,
output_jpg=args.output_jpg,
# Audio Processing Configuration
existing_instrumental=args.existing_instrumental,
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,
denoise_enabled=args.denoise,
normalization_enabled=args.normalize,
# Hardware Acceleration
use_cuda=args.use_cuda,
use_coreml=args.use_coreml,
normalization_enabled=args.normalize,
denoise_enabled=args.denoise,
create_track_subfolders=args.no_track_subfolders,
existing_instrumental=args.existing_instrumental,
existing_title_image=args.existing_title_image,
existing_end_image=args.existing_end_image,
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,
intro_title_region=args.intro_title_region,
intro_artist_region=args.intro_artist_region,
end_video_duration=args.end_video_duration,
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_title_region=args.end_title_region,
end_artist_region=args.end_artist_region,
# Lyrics Configuration
lyrics_artist=args.lyrics_artist,
lyrics_title=args.lyrics_title,
lyrics_file=args.lyrics_file,
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,
skip_transcription=args.skip_transcription,
subtitle_offset_ms=args.subtitle_offset_ms,
# Style Configuration
style_params_json=args.style_params_json,
)
tracks = kprep.process()
tracks = await kprep.process()
logger.info(f"Karaoke Prep complete! Output files:")
@@ -454,5 +316,17 @@ def main():
logger.info(f" Combined Instrumental: {file_path}")
def main():
# Set up logging
logger = logging.getLogger(__name__)
log_handler = logging.StreamHandler()
log_formatter = logging.Formatter(fmt="%(asctime)s.%(msecs)03d - %(levelname)s - %(module)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log_handler.setFormatter(log_formatter)
logger.addHandler(log_handler)
# Run the async main function using asyncio
asyncio.run(async_main())
if __name__ == "__main__":
main()
Generated
+2689 -1394
View File
File diff suppressed because it is too large. Load diff
+6 -4
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-prep"
version = "0.30.2"
version = "0.44.0"
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"
@@ -12,7 +12,7 @@ documentation = "https://github.com/karaokenerds/karaoke-prep/blob/main/README.m
[tool.poetry.dependencies]
python = ">=3.10,<3.13"
torch = ">=2.3,<2.5"
torch = "<2.5"
requests = ">=2"
beautifulsoup4 = ">=4"
yt-dlp = "*"
@@ -28,13 +28,13 @@ thefuzz = ">=0.22"
numpy = "^1"
audio-separator = { version = ">=0.21.0", extras = ["cpu"] }
lyrics-converter = ">=0.2.1"
lyrics-transcriber = ">=0.18"
lyrics-transcriber = ">=0.34"
kbputils = "^0.0.16"
karaoke-lyrics-processor = ">=0.4.1"
attrs = ">=24.2.0"
cattrs = ">=24.1.2"
toml = ">=0.10"
argparse = ">=1.4.0"
psutil = "^7.0.0"
[tool.poetry.group.dev.dependencies]
black = ">=23"
@@ -43,6 +43,8 @@ poetry = "*"
[tool.poetry.scripts]
karaoke-prep = 'karaoke_prep.utils.prep_cli:main'
karaoke-finalise = 'karaoke_prep.utils.finalise_cli:main'
karaoke-auto = 'karaoke_prep.utils.auto_cli:main'
karaoke-bulk = 'karaoke_prep.utils.bulk_cli:main'
[tool.black]
line-length = 140
+17 -65
View File
@@ -1,3 +1,5 @@
#! /usr/bin/env python3
import os
import json
import logging
@@ -23,57 +25,21 @@ with open("data/artist-titles.json", "r", encoding="utf-8") as 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:]
artist_title_combinations = sorted_combinations[:20] + sorted_combinations[-20:]
# 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",
"style_params_json": "/Users/andrew/AB Dropbox/Andrew Beveridge/MediaUnsynced/Karaoke/NomadBranding/karaoke-prep-styles-nomad.json",
},
{
"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": "vocalstar",
"style_params_json": "/Users/andrew/AB Dropbox/Andrew Beveridge/MediaUnsynced/Karaoke/Tracks-NonPublished/VocalStar/Resources/karaoke-prep-styles-vocalstar.json",
},
{
"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,
"style_params_json": None,
},
]
@@ -87,34 +53,18 @@ for format in formats:
format_output_dir = os.path.join(base_output_dir, format["name"])
os.makedirs(format_output_dir, exist_ok=True)
style_params = None
if format["style_params_json"]:
with open(format["style_params_json"], "r") as f:
style_params = json.loads(f.read())
# 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,
style_params=style_params,
render_bounding_boxes=False,
output_jpg=False,
output_png=True,
)
@@ -128,6 +78,7 @@ for format in formats:
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.intro_video_duration = 0
kprep.create_title_video(
artist=artist,
title=title,
@@ -141,6 +92,7 @@ for format in formats:
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.end_video_duration = 0
kprep.create_end_video(
artist=artist,
title=title,