Compare commits

...
51 Commits
Author SHA1 Message Date
Andrew Beveridge 1b26fe9a46 Downgraded PyTorch to 2.4 to fix issue with Demucs on MPS throwing NotImplementedError: Output channels > 65536 not supported at the MPS device 2024-12-04 17:42:06 -05:00
Andrew Beveridge e6b475fc5c Replaced lyrics processing with karaoke-lyrics-processor library 2024-12-04 17:24:31 -05:00
Andrew Beveridge ff98d4d191 Added vendored version of nomad forked and branded cdgmaker to allow publishing this package 2024-12-04 16:40:31 -05:00
Andrew Beveridge df9d1053df Bumped version to fix cdgmaker 2024-11-04 02:59:29 -06:00
Andrew Beveridge 0618574cbf Upgraded cdgmaker 2024-11-04 02:59:06 -06:00
Andrew Beveridge 1028c26a59 Added CDG generation from LRC files 2024-11-04 02:58:16 -06:00
Andrew Beveridge 49982b4ad4 Added audioshake transcription 2024-09-17 12:29:35 -04:00
Andrew Beveridge a9291e97a1 Added lyrics-transcriber 2024-09-17 12:18:12 -04:00
Andrew Beveridge d96b844962 Added functionality to extract individual stems using htdemucs 2024-09-17 12:05:21 -04:00
Andrew Beveridge 5d5cb86494 Added 720p encoding 2024-09-17 11:00:49 -04:00
Andrew Beveridge d0276aafb4 Added support for generating file sharing link (e.g. dropbox folder) as part of finalise 2024-09-17 10:33:15 -04:00
Andrew Beveridge 60d347e812 Added dropbox sharing link to output 2024-09-17 00:06:18 -04:00
Andrew Beveridge 6362c426f2 Updated to latest version of audio-separator, added new karaoke model to defaults 2024-09-16 21:20:48 -04:00
Andrew Beveridge 7247bf2765 Bumped version to relax python restriction 2024-07-22 00:49:58 -04:00
Andrew Beveridge b68dd667a2 Updated dependencies 2024-07-21 03:11:17 -04:00
Andrew Beveridge fba1a1146e Fixed aac codec on non-mac 2024-07-14 04:25:40 -04:00
Andrew Beveridge 951512f236 Disabled windows CI build 2024-07-14 03:54:27 -04:00
Andrew Beveridge 45f13fdd2f Fixed non_interactive 2024-07-14 03:49:48 -04:00
Andrew Beveridge 87abc4720f Added non_interactive mode for finalise 2024-07-14 03:01:53 -04:00
Andrew Beveridge aaf1480964 Fix pyperclip in docker 2024-07-14 00:44:24 -04:00
Andrew Beveridge cc84254988 Updated to latest separator with model default tweak to use bs roformer 2024-07-03 14:36:50 -04:00
Andrew Beveridge 64924f5fee Added params to fix lyrics artist and title 2024-06-30 21:43:21 -04:00
Andrew Beveridge d8327936aa Updated finalise to remove with vocals MOV and allow re-running with only with vocals MP4 existing (to save disk space) 2024-06-26 12:32:37 -04:00
Andrew Beveridge 91c0db6f72 Fixed one more end video concat bug 2024-06-26 01:52:37 -04:00
Andrew Beveridge 1a8503730d Fixed bug with end video 2024-06-26 01:45:06 -04:00
Andrew Beveridge b0914f21dd Got TXT generation working 2024-06-26 01:36:50 -04:00
Andrew Beveridge 4867a6fa0c Added lyrics conversion to generate TXT format output zip 2024-06-26 01:17:06 -04:00
Andrew Beveridge 3e133ef787 Added lots more configuration options for the title and end screens 2024-06-26 00:27:37 -04:00
Andrew Beveridge 4b6845faff Added configurable title video and end video with ability to pass in existing image for either and customise duration 2024-06-25 23:06:33 -04:00
Andrew Beveridge 8181db5278 Added ability to specify existing instrumental track and existing title image file 2024-06-25 21:51:42 -04:00
Andrew Beveridge c17b6ca57e Added with vocals mp4 output 2024-06-25 21:16:58 -04:00
Andrew Beveridge 671eabea78 Updated dependencies, added non-standard space character cleanup 2024-06-18 17:28:12 -04:00
Andrew Beveridge e967a7e1d8 Merge branch 'main' of github.com:karaokenerds/karaoke-prep 2024-05-28 17:24:12 -04:00
Andrew Beveridge bb756c4740 Added skip CDG flag 2024-05-28 16:32:22 -04:00
Andrew Beveridge ☄️ ac4d8d5394 Merge pull request #1 from empz/improve-readme-windows
Improve readme Windows instructions.
2024-05-26 21:34:35 -04:00
Emiliano Parizzi 2530f150bc Improve readme Windows instructions. 2024-05-27 00:58:37 +02:00
Andrew Beveridge ee634ae70a Updated separator to latest to use mel roformer by default 2024-05-25 00:24:09 -04:00
Andrew Beveridge 06b670e62f Updated final mp4 render to use concat filter instead of demuxer which is buggy 2024-04-24 23:19:11 -04:00
Andrew Beveridge 008c09a72e Added folder processing with filename track and title pattern extraction and a dry run mode for easier bulk processing of local files 2024-04-01 17:21:17 -05:00
Andrew Beveridge 0587334eec Modified default models to remove buggy / resource hog HP9 2024-03-28 14:05:24 -05:00
Andrew Beveridge b3319774c2 Fixed audio-separator instantiation to work with latest version 2024-03-28 14:02:36 -05:00
Andrew Beveridge 6306c274cc Updated default models to use newer models 2024-03-24 00:10:21 -05:00
Andrew Beveridge f2bf347234 Updated to latest audio-separator 2024-03-23 22:23:04 -05:00
Andrew Beveridge e225dfcefc Updated to latest audio-separator, added additional default model to CLI 2024-03-02 23:25:39 -05:00
Andrew Beveridge d4ff5878a7 Fixed bug with artist and title only usage 2024-02-09 11:44:36 -05:00
Andrew Beveridge 8d11222f82 Updated to latest audio-separator, added support for multiple models 2024-02-06 23:27:21 -06:00
Andrew Beveridge ☄️ 010632d919 Added PyTorch CUDA instructions to README.md 2024-01-29 11:31:10 -05:00
Andrew Beveridge 299444c3e3 Updated install docs 2024-01-29 10:59:01 -05:00
Andrew Beveridge 6be2e9908f Tweaked logging 2024-01-28 13:31:00 -05:00
Andrew Beveridge d28595e273 Improved instrumental matching logic 2024-01-28 11:52:24 -05:00
Andrew Beveridge 13b3ad1b76 Fixed check for existing video, improved instrumental selection, updated deps 2024-01-28 11:29:08 -05:00
35 changed files with 7836 additions and 1766 deletions

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
2384d2383
< triton = ">=2.0.0,<3"
4185d4183
< triton = {version = "2.3.1", markers = "platform_system == \"Linux\" and platform_machine == \"x86_64\" and python_version < \"3.12\""}
4318,4340d4315
< name = "triton"
< version = "2.3.1"
< description = "A language and compiler for custom Deep Learning operations"
< optional = false
< python-versions = "*"
< files = [
< {file = "triton-2.3.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3c84595cbe5e546b1b290d2a58b1494df5a2ef066dd890655e5b8a8a92205c33"},
< {file = "triton-2.3.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c9d64ae33bcb3a7a18081e3a746e8cf87ca8623ca13d2c362413ce7a486f893e"},
< {file = "triton-2.3.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eaf80e8761a9e3498aa92e7bf83a085b31959c61f5e8ac14eedd018df6fccd10"},
< {file = "triton-2.3.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b13bf35a2b659af7159bf78e92798dc62d877aa991de723937329e2d382f1991"},
< {file = "triton-2.3.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:63381e35ded3304704ea867ffde3b7cfc42c16a55b3062d41e017ef510433d66"},
< {file = "triton-2.3.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1d968264523c7a07911c8fb51b4e0d1b920204dae71491b1fe7b01b62a31e124"},
< ]
<
< [package.dependencies]
< filelock = "*"
<
< [package.extras]
< build = ["cmake (>=3.20)", "lit"]
< tests = ["autopep8", "flake8", "isort", "numpy", "pytest", "scipy (>=1.7.1)", "torch"]
< tutorials = ["matplotlib", "pandas", "tabulate", "torch"]
<
< [[package]]
+24 -24
View File
@@ -18,34 +18,34 @@ jobs:
gh-token: ${{ secrets.GITHUB_TOKEN }}
parse-changelog: false
build-windows:
runs-on: windows-latest
# build-windows:
# runs-on: windows-latest
steps:
- uses: actions/checkout@v2
# steps:
# - uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.9'
# - name: Set up Python
# uses: actions/setup-python@v2
# with:
# python-version: '3.9'
- name: Install dependencies with Poetry
run: |
pip install poetry
poetry install
# - name: Install dependencies with Poetry
# run: |
# pip install poetry
# poetry install
- name: Download ffmpeg binary
run: python platform/download_ffmpeg.py
# - name: Download ffmpeg binary
# run: python platform/download_ffmpeg.py
- name: Build EXE with PyInstaller
run: poetry run pyinstaller karaoke-prep.spec
# - name: Build EXE with PyInstaller
# run: poetry run pyinstaller karaoke-prep.spec
- name: Upload EXE as Artifact
uses: actions/upload-artifact@v2
with:
name: karaoke-prep-windows
path: |
build/
*.exe
*/*.exe
# - name: Upload EXE as Artifact
# uses: actions/upload-artifact@v2
# with:
# name: karaoke-prep-windows
# path: |
# build/
# *.exe
# */*.exe
+27
View File
@@ -21,10 +21,36 @@ This was created to make it easier for me to prepare the source audio, lyrics an
## Installation 🛠️
You'll need Python version 3.9, 3.10 or 3.11 (newer versions aren't supported by PyTorch or ONNX Runtime yet).
### Windows Prerequisites
- [Microsoft C++ Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/)
- [FFmpeg](https://ffmpeg.org/download.html)
You can install Karaoke Prep using pip:
`pip install karaoke-prep`
You'll then also need to install a version of `audio-separator` for your hardware:
- Mac with Apple Silicon: `pip install audio-separator[silicon]`
- Linux/Windows with CUDA GPU: `pip install audio-separator[gpu]`
- Anything else: `pip install audio-separator[cpu]`
#### Install PyTorch with CUDA support
If you're trying to use CUDA for GPU acceleration, you'll also need to ensure the version of PyTorch you have installed is compatible with the CUDA version you have installed.
While PyTorch should get installed as a dependency of `karaoke-prep` anyway, you may need to install PyTorch for your CUDA version by running the installation command provided by the official install wizard: https://pytorch.org/get-started/locally/
#### UnicodeEncodeError
If you encounter this error: `UnicodeEncodeError: 'charmap' codec can't encode character`
Try setting the Python I/O encoding in your environment: `export PYTHONIOENCODING=utf-8`
#### Command-line newbie?
If you aren't sure what `pip` is or how to use the command line, here are some YouTube tutorials which will probably help:
- Install Python on Windows: https://www.youtube.com/watch?v=YKSpANU8jPE
@@ -34,6 +60,7 @@ If you aren't sure what `pip` is or how to use the command line, here are some Y
## Karaoke production guide using karaoke-prep and MidiCo
- Get a Genius API Access Token ([docs](https://docs.genius.com/)) and set it as an environment variable named `GENIUS_API_TOKEN`
- Run `karaoke-prep <Artist> <Title>` to fetch and prep the files above
- Wait for it to output at least the WAV file and lyrics (you can leave it running in the background while you sync)
- Open the WAV file in MidiCo: `(YouTube xxxxxxxxxxx).wav`
View File
Whitespace-only changes.
+262
View File
@@ -0,0 +1,262 @@
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
@@ -0,0 +1,131 @@
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.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

+360
View File
@@ -0,0 +1,360 @@
#!/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
@@ -0,0 +1,507 @@
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
@@ -0,0 +1,346 @@
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.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

+132
View File
@@ -0,0 +1,132 @@
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",
]
+303 -84
View File
@@ -1,17 +1,22 @@
import os
import sys
import json
import tempfile
import shlex
import logging
import zipfile
import shutil
import re
import requests
import pickle
from lyrics_converter import LyricsConverter
from thefuzz import fuzz
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.http import MediaFileUpload
import subprocess
import time
from cdgmaker.lrc_to_cdg import generate_cdg
class KaraokeFinalise:
@@ -22,13 +27,17 @@ class KaraokeFinalise:
dry_run=False,
model_name=None,
instrumental_format="flac",
enable_cdg=False,
enable_txt=False,
brand_prefix=None,
organised_dir=None,
organised_dir_rclone_root=None,
public_share_dir=None,
youtube_client_secrets_file=None,
youtube_description_file=None,
rclone_destination=None,
discord_webhook_url=None,
non_interactive=False,
):
self.logger = logging.getLogger(__name__)
self.logger.setLevel(log_level)
@@ -63,11 +72,15 @@ class KaraokeFinalise:
self.brand_prefix = brand_prefix
self.organised_dir = organised_dir
self.organised_dir_rclone_root = organised_dir_rclone_root
self.public_share_dir = public_share_dir
self.youtube_client_secrets_file = youtube_client_secrets_file
self.youtube_description_file = youtube_description_file
self.rclone_destination = rclone_destination
self.discord_webhook_url = discord_webhook_url
self.enable_cdg = enable_cdg
self.enable_txt = enable_txt
self.youtube_upload_enabled = False
self.discord_notication_enabled = False
@@ -76,23 +89,33 @@ class KaraokeFinalise:
self.public_share_rclone_enabled = False
self.skip_notifications = False
self.non_interactive = non_interactive
self.suffixes = {
"title_mov": " (Title).mov",
"title_jpg": " (Title).jpg",
"end_mov": " (End).mov",
"end_jpg": " (End).jpg",
"with_vocals_mov": " (With Vocals).mov",
"with_vocals_mp4": " (With Vocals).mp4",
"karaoke_lrc": " (Karaoke).lrc",
"karaoke_cdg": " (Karaoke).cdg",
"karaoke_txt": " (Karaoke).txt",
"karaoke_mp3": " (Karaoke).mp3",
"karaoke_mov": " (Karaoke).mov",
"final_karaoke_mp4": " (Final Karaoke).mp4",
"final_karaoke_zip": " (Final Karaoke).zip",
"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="
self.youtube_url = None
self.brand_code = None
self.new_brand_code_dir = None
self.new_brand_code_dir_path = None
self.brand_code_dir_sharing_link = None
def check_input_files_exist(self, base_name, with_vocals_file, instrumental_audio_file):
self.logger.info(f"Checking required input files exist...")
@@ -100,33 +123,61 @@ class KaraokeFinalise:
input_files = {
"title_mov": f"{base_name}{self.suffixes['title_mov']}",
"title_jpg": f"{base_name}{self.suffixes['title_jpg']}",
"karaoke_cdg": f"{base_name}{self.suffixes['karaoke_cdg']}",
"karaoke_mp3": f"{base_name}{self.suffixes['karaoke_mp3']}",
"instrumental_audio": instrumental_audio_file,
"with_vocals_mov": with_vocals_file,
}
optional_input_files = {
"end_mov": f"{base_name}{self.suffixes['end_mov']}",
"end_jpg": f"{base_name}{self.suffixes['end_jpg']}",
}
if self.enable_cdg or self.enable_txt:
input_files["karaoke_lrc"] = f"{base_name}{self.suffixes['karaoke_lrc']}"
for key, file_path in input_files.items():
if not os.path.isfile(file_path):
raise Exception(f"Input file {key} not found: {file_path}")
self.logger.info(f" Input file {key} found: {file_path}")
for key, file_path in optional_input_files.items():
if not os.path.isfile(file_path):
self.logger.info(f" Optional input file {key} not found: {file_path}")
self.logger.info(f" Input file {key} found, adding to input_files: {file_path}")
input_files[key] = file_path
return input_files
def prepare_output_filenames(self, base_name):
return {
output_files = {
"karaoke_mov": f"{base_name}{self.suffixes['karaoke_mov']}",
"karaoke_mp3": f"{base_name}{self.suffixes['karaoke_mp3']}",
"with_vocals_mp4": f"{base_name}{self.suffixes['with_vocals_mp4']}",
"final_karaoke_mp4": f"{base_name}{self.suffixes['final_karaoke_mp4']}",
"final_karaoke_zip": f"{base_name}{self.suffixes['final_karaoke_zip']}",
"final_karaoke_720p_mp4": f"{base_name}{self.suffixes['final_karaoke_720p_mp4']}",
}
if self.enable_cdg:
output_files["final_karaoke_cdg_zip"] = f"{base_name}{self.suffixes['final_karaoke_cdg_zip']}"
if self.enable_txt:
output_files["karaoke_txt"] = f"{base_name}{self.suffixes['karaoke_txt']}"
output_files["final_karaoke_txt_zip"] = f"{base_name}{self.suffixes['final_karaoke_txt_zip']}"
return output_files
def prompt_user_confirmation_or_raise_exception(self, prompt_message, exit_message, allow_empty=False):
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}")
return True
options_string = "[y]/n" if allow_empty else "y/[n]"
accept_responses = ["y", "yes"]
if allow_empty:
@@ -197,6 +248,8 @@ class KaraokeFinalise:
# Tell user which features are enabled, prompt them to confirm before proceeding
self.logger.info(f"Enabled features:")
self.logger.info(f" CDG ZIP creation: {self.enable_cdg}")
self.logger.info(f" TXT ZIP creation: {self.enable_txt}")
self.logger.info(f" YouTube upload: {self.youtube_upload_enabled}")
self.logger.info(f" Discord notifications: {self.discord_notication_enabled}")
self.logger.info(f" Folder organisation: {self.folder_organisation_enabled}")
@@ -253,20 +306,29 @@ class KaraokeFinalise:
youtube = self.authenticate_youtube()
channel_id = self.get_channel_id()
# Search for videos with the given title in the channel
request = youtube.search().list(part="snippet", channelId=channel_id, q=youtube_title, type="video", maxResults=1)
self.logger.info(f"Searching YouTube channel {channel_id} for title: {youtube_title}")
request = youtube.search().list(part="snippet", channelId=channel_id, q=youtube_title, type="video", maxResults=10)
response = request.execute()
# Check if any videos were found
if "items" in response:
if len(response["items"]) > 0:
self.logger.info(f"Found existing video on YouTube channel with title {youtube_title}")
self.youtube_video_id = response["items"][0]["id"]["videoId"]
self.youtube_url = f"{self.youtube_url_prefix}{self.youtube_video_id}"
self.skip_notifications = True
return True
else:
return False
if "items" in response and len(response["items"]) > 0:
for item in response["items"]:
found_title = item["snippet"]["title"]
similarity_score = fuzz.ratio(youtube_title.lower(), found_title.lower())
if similarity_score >= 70: # 70% similarity
found_id = item["id"]["videoId"]
self.logger.info(
f"Potential match found on YouTube channel with ID: {found_id} and title: {found_title} (similarity: {similarity_score}%)"
)
confirmation = input(f"Is '{found_title}' the video you are finalising? (y/n): ").strip().lower()
if confirmation == "y":
self.youtube_video_id = found_id
self.youtube_url = f"{self.youtube_url_prefix}{self.youtube_video_id}"
self.skip_notifications = True
return True
self.logger.info(f"No matching video found with title: {youtube_title}")
return False
def truncate_to_nearest_word(self, title, max_length):
if len(title) <= max_length:
@@ -301,7 +363,8 @@ class KaraokeFinalise:
youtube_category_id = "10" # Category ID for Music
youtube_keywords = ["karaoke", "music", "singing", "instrumental", "lyrics", artist, title]
"""Upload video to YouTube and set thumbnail."""
self.logger.info(f"Authenticating with YouTube...")
# Upload video to YouTube and set thumbnail.
youtube = self.authenticate_youtube()
body = {
@@ -318,6 +381,7 @@ class KaraokeFinalise:
media_file = MediaFileUpload(output_files["final_karaoke_mp4"], mimetype="video/mp4", resumable=True)
# Call the API's videos.insert method to create and upload the video.
self.logger.info(f"Uploading final MP4 to YouTube...")
request = youtube.videos().insert(part="snippet,status", body=body, media_body=media_file)
response = request.execute()
@@ -360,10 +424,19 @@ class KaraokeFinalise:
response.raise_for_status() # This will raise an exception if the request failed
self.logger.info("Message posted to Discord")
def find_with_vocals_mov_file(self):
self.logger.info("Finding input file in current directory ending (With Vocals).mov")
def find_with_vocals_file(self):
self.logger.info("Finding input file in current directory ending (With Vocals).mov or (With Vocals).mp4")
with_vocals_files = [f for f in os.listdir(".") if self.suffixes["with_vocals_mov"] in f]
if not with_vocals_files:
self.logger.info(f"No with vocals MOV file found, looking for with vocals MP4 file instead")
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 not with_vocals_files:
karaoke_files = [f for f in os.listdir(".") if self.suffixes["karaoke_mov"] in f]
if karaoke_files:
@@ -387,37 +460,38 @@ class KaraokeFinalise:
def choose_instrumental_audio_file(self, base_name):
self.logger.info(f"Choosing instrumental audio file to use as karaoke audio...")
# If model name and instrumental format are provided, check for instrumental file with suffix and use it
if self.model_name is not None and self.instrumental_format is not None:
self.logger.debug(f"Model name and instrumental format provided, checking instrumental file exists")
instrumental_suffix = f" (Instrumental {self.model_name}).{self.instrumental_format}"
if any(instrumental_suffix in f for f in os.listdir(".")):
self.logger.debug(f"Instrumental file found: {instrumental_suffix}")
return f"{base_name} {instrumental_suffix}"
else:
raise Exception(f"Instrumental file not found with suffix: {instrumental_suffix}")
search_string = " (Instrumental "
# Check for files containing search string and prompt user to choose one, return filename
self.logger.info(f"Searching for files in current directory containing {search_string}")
instrumental_audio_files = [f for f in os.listdir(".") if search_string in f]
if not instrumental_audio_files:
raise Exception(f"Could not find any files containing {search_string}, exiting.")
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"))
if len(instrumental_audio_files) == 1:
return instrumental_audio_files[0]
self.logger.debug(f"FLAC files found: {flac_files}")
self.logger.debug(f"MP3 files found: {mp3_files}")
# TODO: If there are FLAC and MP3 versions of the same instrumental, only show the FLAC options
# TODO: Sort the remaining instrumental options alphabetically so they're always consistent, for convenient 1/2 choice
# Filter out MP3 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)
]
self.logger.debug(f"Filtered instrumental files: {filtered_files}")
if not filtered_files:
raise Exception(f"No instrumental audio files found containing {search_string}")
if len(filtered_files) == 1:
return filtered_files[0]
# Sort the remaining instrumental options alphabetically
filtered_files.sort(reverse=True)
self.logger.info(f"Found multiple files containing {search_string}:")
for i, file in enumerate(instrumental_audio_files):
for i, file in enumerate(filtered_files):
self.logger.info(f" {i+1}: {file}")
print()
response = input(f"Choose instrumental audio file to use as karaoke audio: [1]/{len(instrumental_audio_files)}: ").strip().lower()
response = input(f"Choose instrumental audio file to use as karaoke audio: [1]/{len(filtered_files)}: ").strip().lower()
if response == "":
response = "1"
@@ -426,15 +500,15 @@ class KaraokeFinalise:
except ValueError:
raise Exception(f"Invalid response to instrumental audio file choice prompt: {response}")
if response < 1 or response > len(instrumental_audio_files):
if response < 1 or response > len(filtered_files):
raise Exception(f"Invalid response to instrumental audio file choice prompt: {response}")
return instrumental_audio_files[response - 1]
return filtered_files[response - 1]
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"], "")
base_name = with_vocals_file.replace(self.suffixes["with_vocals_mov"], "").replace(self.suffixes["with_vocals_mp4"], "")
artist, title = base_name.split(" - ", 1)
return base_name, artist, title
@@ -461,25 +535,45 @@ class KaraokeFinalise:
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")
tmp_file_list = None
try:
# Create a temporary file with the file paths for ffmpeg concat
tmp_file_list = tempfile.NamedTemporaryFile(mode="w+", delete=False, dir="/tmp", suffix=".txt")
# Convert the with vocals video to MP4 if it isn't already
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")
title_mov_path = os.path.abspath(input_files["title_mov"]).replace("'", "'\\''")
karaoke_mov_path = os.path.abspath(output_files["karaoke_mov"]).replace("'", "'\\''")
# Delete the with vocals mov after successfully converting it to mp4
if not self.dry_run and os.path.isfile(with_vocals_file):
self.logger.info(f"Deleting with vocals MOV file: {with_vocals_file}")
os.remove(with_vocals_file)
tmp_file_list.write(f"file '{title_mov_path}'\n")
tmp_file_list.write(f"file '{karaoke_mov_path}'\n")
tmp_file_list.flush()
# 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"])
# Join the title video and the karaoke video to produce the final MP4
join_ffmpeg_command = f'{self.ffmpeg_base_command} -f concat -safe 0 -i "{tmp_file_list.name}" -vf settb=AVTB,setpts=N/30/TB,fps=30 "{output_files["final_karaoke_mp4"]}"'
self.execute_command(join_ffmpeg_command, "Joining title and instrumental videos")
finally:
# Ensure the temporary file is deleted
if tmp_file_list is not None:
os.remove(tmp_file_list.name)
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]"'
# 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]"'
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
self.prompt_user_confirmation_or_raise_exception(
@@ -488,35 +582,101 @@ class KaraokeFinalise:
allow_empty=True,
)
def create_cdg_zip_file(self, input_files, output_files):
self.logger.info(f"Creating CDG ZIP file...")
def create_cdg_zip_file(self, input_files, output_files, artist, title):
self.logger.info(f"Creating CDG and MP3 files, then zipping them...")
# Check if CDG file already exists, if so, ask user to overwrite or skip
if os.path.isfile(output_files["final_karaoke_zip"]):
if os.path.isfile(output_files["final_karaoke_cdg_zip"]):
if not self.prompt_user_bool(
f"Found existing CDG ZIP file: {output_files['final_karaoke_zip']}. Overwrite (y) or skip (n)?",
f"Found existing CDG ZIP file: {output_files['final_karaoke_cdg_zip']}. Overwrite (y) or skip (n)?",
):
self.logger.info(f"Skipping CDG ZIP file creation, existing file will be used.")
return
# Create the ZIP file containing the MP3 and CDG files
# Generate CDG and MP3 files
if self.dry_run:
self.logger.info(f"DRY RUN: Would create CDG ZIP file: {output_files['final_karaoke_zip']}")
self.logger.info(f"DRY RUN: Would generate CDG and MP3 files")
else:
self.logger.info(f"Creating ZIP file containing {input_files['karaoke_mp3']} and {input_files['karaoke_cdg']}")
with zipfile.ZipFile(output_files["final_karaoke_zip"], "w") as zipf:
zipf.write(input_files["karaoke_mp3"], os.path.basename(input_files["karaoke_mp3"]))
zipf.write(input_files["karaoke_cdg"], os.path.basename(input_files["karaoke_cdg"]))
self.logger.info(f"Generating CDG and MP3 files")
if not os.path.isfile(output_files["final_karaoke_zip"]):
raise Exception(f"Failed to create CDG ZIP file: {output_files['final_karaoke_zip']}")
generate_cdg(input_files["karaoke_lrc"], input_files["instrumental_audio"], title, artist)
self.logger.info(f"CDG ZIP file created: {output_files['final_karaoke_zip']}")
# Look for the generated ZIP file
expected_zip = f"{artist} - {title} (Karaoke).zip"
self.logger.info(f"Searching for CDG ZIP file. Expected: {expected_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']}")
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()
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...")
# Check if TXT file already exists, if so, ask user to overwrite or skip
if os.path.isfile(output_files["final_karaoke_txt_zip"]):
if not self.prompt_user_bool(
f"Found existing TXT ZIP file: {output_files['final_karaoke_txt_zip']}. Overwrite (y) or skip (n)?",
):
self.logger.info(f"Skipping TXT ZIP file creation, existing file will be used.")
return
# Create the ZIP file containing the MP3 and TXT files
if self.dry_run:
self.logger.info(f"DRY RUN: Would create TXT ZIP file: {output_files['final_karaoke_txt_zip']}")
else:
self.logger.info(f"Running karaoke-converter to convert MidiCo LRC file {input_files['karaoke_lrc']} to TXT format")
txt_converter = LyricsConverter(output_format="txt", filepath=input_files["karaoke_lrc"])
converted_txt = txt_converter.convert_file()
with open(output_files["karaoke_txt"], "w") as txt_file:
txt_file.write(converted_txt)
self.logger.info(f"TXT file written: {output_files['karaoke_txt']}")
self.logger.info(f"Creating ZIP file containing {output_files['karaoke_mp3']} and {output_files['karaoke_txt']}")
with zipfile.ZipFile(output_files["final_karaoke_txt_zip"], "w") as zipf:
zipf.write(output_files["karaoke_mp3"], os.path.basename(output_files["karaoke_mp3"]))
zipf.write(output_files["karaoke_txt"], os.path.basename(output_files["karaoke_txt"]))
if not os.path.isfile(output_files["final_karaoke_txt_zip"]):
raise Exception(f"Failed to create TXT ZIP file: {output_files['final_karaoke_txt_zip']}")
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_path = os.path.join(self.organised_dir, f"{brand_code} - {artist} - {title}")
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?",
@@ -534,15 +694,18 @@ class KaraokeFinalise:
os.rename(orig_dir, self.new_brand_code_dir_path)
def copy_final_files_to_public_share_dirs(self, brand_code, base_name, output_files):
self.logger.info(f"Copying final MP4 and ZIP to public share directory...")
self.logger.info(f"Copying final MP4, 720p MP4, and ZIP to public share directory...")
# Validate public_share_dir is a valid folder with MP4 and CDG subdirectories
# Validate public_share_dir is a valid folder with MP4, MP4-720p, and CDG subdirectories
if not os.path.isdir(self.public_share_dir):
raise Exception(f"Public share directory does not exist: {self.public_share_dir}")
if not os.path.isdir(os.path.join(self.public_share_dir, "MP4")):
raise Exception(f"Public share directory does not contain MP4 subdirectory: {self.public_share_dir}")
if not os.path.isdir(os.path.join(self.public_share_dir, "MP4-720p")):
raise Exception(f"Public share directory does not contain MP4-720p subdirectory: {self.public_share_dir}")
if not os.path.isdir(os.path.join(self.public_share_dir, "CDG")):
raise Exception(f"Public share directory does not contain CDG subdirectory: {self.public_share_dir}")
@@ -550,18 +713,24 @@ class KaraokeFinalise:
raise Exception(f"New track prefix was not set, refusing to copy to public share directory")
dest_mp4_dir = os.path.join(self.public_share_dir, "MP4")
dest_720p_dir = os.path.join(self.public_share_dir, "MP4-720p")
dest_cdg_dir = os.path.join(self.public_share_dir, "CDG")
os.makedirs(dest_mp4_dir, exist_ok=True)
os.makedirs(dest_720p_dir, exist_ok=True)
os.makedirs(dest_cdg_dir, exist_ok=True)
dest_mp4_file = os.path.join(dest_mp4_dir, f"{brand_code} - {base_name}.mp4")
dest_720p_mp4_file = os.path.join(dest_720p_dir, f"{brand_code} - {base_name}.mp4")
dest_zip_file = os.path.join(dest_cdg_dir, f"{brand_code} - {base_name}.zip")
if self.dry_run:
self.logger.info(f"DRY RUN: Would copy final MP4 and ZIP to {dest_mp4_file} + .cdg")
self.logger.info(
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_zip"], dest_zip_file)
shutil.copy2(output_files["final_karaoke_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")
def sync_public_share_dir_to_rclone_destination(self):
@@ -593,11 +762,44 @@ class KaraokeFinalise:
discord_message = f"New upload: {self.youtube_url}"
self.post_discord_message(discord_message, self.discord_webhook_url)
def generate_organised_folder_sharing_link(self):
self.logger.info(f"Getting Organised Folder sharing link for new brand code directory...")
rclone_dest = f"{self.organised_dir_rclone_root}/{self.new_brand_code_dir}"
rclone_link_cmd = f"rclone link {shlex.quote(rclone_dest)}"
if self.dry_run:
self.logger.info(f"DRY RUN: Would get sharing link with: {rclone_link_cmd}")
return "https://file-sharing-service.com/example"
# Add a 5-second delay to allow dropbox to index the folder before generating a link
self.logger.info("Waiting 5 seconds before generating link...")
time.sleep(5)
try:
self.logger.info(f"Running command: {rclone_link_cmd}")
result = subprocess.run(rclone_link_cmd, shell=True, check=True, capture_output=True, text=True)
self.brand_code_dir_sharing_link = result.stdout.strip()
self.logger.info(f"Got organised folder sharing link: {self.brand_code_dir_sharing_link}")
except subprocess.CalledProcessError as e:
self.logger.error(f"Failed to get organised folder sharing link. Exit code: {e.returncode}")
self.logger.error(f"Command output (stdout): {e.stdout}")
self.logger.error(f"Command output (stderr): {e.stderr}")
self.logger.error(f"Full exception: {e}")
def execute_optional_features(self, artist, title, base_name, input_files, output_files):
self.logger.info(f"Executing optional features...")
if self.youtube_upload_enabled:
self.upload_final_mp4_to_youtube_with_title_thumbnail(artist, title, input_files, output_files)
try:
self.upload_final_mp4_to_youtube_with_title_thumbnail(artist, title, input_files, output_files)
except Exception as e:
self.logger.error(f"Failed to upload video to YouTube: {e}")
print("Please manually upload the video to YouTube.")
print()
self.youtube_video_id = input("Enter the manually uploaded YouTube video ID: ").strip()
self.youtube_url = f"{self.youtube_url_prefix}{self.youtube_video_id}"
self.logger.info(f"Using manually provided YouTube video ID: {self.youtube_video_id}")
if self.discord_notication_enabled:
self.post_discord_notification()
@@ -613,6 +815,8 @@ class KaraokeFinalise:
self.move_files_to_brand_code_folder(self.brand_code, artist, title, output_files)
self.generate_organised_folder_sharing_link()
def process(self):
if self.dry_run:
self.logger.warning("Dry run enabled. No actions will be performed.")
@@ -620,7 +824,7 @@ class KaraokeFinalise:
# Check required input files and parameters exist, get user to confirm features before proceeding
self.validate_input_parameters_for_features()
with_vocals_file = self.find_with_vocals_mov_file()
with_vocals_file = self.find_with_vocals_file()
base_name, artist, title = self.get_names_from_withvocals(with_vocals_file)
instrumental_audio_file = self.choose_instrumental_audio_file(base_name)
@@ -628,19 +832,34 @@ class KaraokeFinalise:
input_files = self.check_input_files_exist(base_name, with_vocals_file, instrumental_audio_file)
output_files = self.prepare_output_filenames(base_name)
self.create_cdg_zip_file(input_files, output_files)
if self.enable_cdg:
self.create_cdg_zip_file(input_files, output_files, artist, title)
if self.enable_txt:
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)
return {
result = {
"artist": artist,
"title": title,
"video_with_vocals": with_vocals_file,
"video_with_vocals": output_files["with_vocals_mp4"],
"video_with_instrumental": output_files["karaoke_mov"],
"final_video": output_files["final_karaoke_mp4"],
"final_zip": output_files["final_karaoke_zip"],
"final_video_720p": output_files["final_karaoke_720p_mp4"],
"youtube_url": self.youtube_url,
"brand_code": self.brand_code,
"new_brand_code_dir_path": self.new_brand_code_dir_path,
"brand_code_dir_sharing_link": self.brand_code_dir_sharing_link,
}
if self.enable_cdg:
result["final_karaoke_cdg_zip"] = output_files["final_karaoke_cdg_zip"]
if self.enable_txt:
result["final_karaoke_txt_zip"] = output_files["final_karaoke_txt_zip"]
return result
+423 -149
View File
@@ -6,10 +6,11 @@ import logging
import lyricsgenius
import tempfile
import shutil
import pyperclip
import importlib.resources as pkg_resources
import yt_dlp.YoutubeDL as ydl
from PIL import Image, ImageDraw, ImageFont
from lyrics_transcriber import LyricsTranscriber
from karaoke_lyrics_processor import KaraokeLyricsProcessor
class KaraokePrep:
@@ -18,10 +19,11 @@ class KaraokePrep:
input_media=None,
artist=None,
title=None,
filename_pattern=None,
dry_run=False,
log_level=logging.DEBUG,
log_formatter=None,
model_name="UVR_MDXNET_KARA_2",
model_name_2="UVR-MDX-NET-Inst_HQ_3",
model_names=["UVR_MDXNET_KARA_2.onnx", "model_mel_band_roformer_ep_3005_sdr_11.4360.ckpt"],
model_file_dir=os.path.join(tempfile.gettempdir(), "audio-separator-models"),
output_dir=".",
lossless_output_format="FLAC",
@@ -36,6 +38,32 @@ class KaraokePrep:
intro_font="Montserrat-Bold.ttf",
intro_artist_color="#ffffff",
intro_title_color="#ff7acc",
existing_instrumental=None,
existing_title_image=None,
end_background_color="#000000",
end_background_image=None,
end_font="Montserrat-Bold.ttf",
end_extra_text_color="#ffffff",
end_artist_color="#ffffff",
end_title_color="#ff7acc",
existing_end_image=None,
title_video_duration=5,
end_video_duration=5,
title_initial_font_size=500,
title_top_padding=950,
title_title_padding=400,
title_artist_padding=700,
title_fixed_gap=150,
end_initial_font_size=500,
end_top_padding=950,
end_title_padding=400,
end_artist_padding=700,
end_extra_text_padding=300,
end_fixed_gap=150,
end_extra_text="THANK YOU FOR SINGING!",
lyrics_artist=None,
lyrics_title=None,
skip_lyrics=False,
):
self.logger = logging.getLogger(__name__)
self.logger.setLevel(log_level)
@@ -52,14 +80,16 @@ class KaraokePrep:
self.logger.debug(f"KaraokePrep instantiating with input_media: {input_media} artist: {artist} title: {title}")
self.dry_run = dry_run
self.extractor = None
self.media_id = None
self.url = None
self.input_media = input_media
self.artist = artist
self.title = title
self.model_name = model_name
self.model_name_2 = model_name_2
self.filename_pattern = filename_pattern
self.model_names = model_names
self.model_file_dir = model_file_dir
self.output_dir = output_dir
self.lossless_output_format = lossless_output_format.lower()
@@ -69,6 +99,25 @@ class KaraokePrep:
self.normalization_enabled = normalization_enabled
self.denoise_enabled = denoise_enabled
self.create_track_subfolders = create_track_subfolders
self.existing_instrumental = existing_instrumental
self.existing_title_image = existing_title_image
self.title_video_duration = title_video_duration
self.end_video_duration = end_video_duration
self.title_initial_font_size = title_initial_font_size
self.title_top_padding = title_top_padding
self.title_title_padding = title_title_padding
self.title_artist_padding = title_artist_padding
self.title_fixed_gap = title_fixed_gap
self.end_initial_font_size = end_initial_font_size
self.end_top_padding = end_top_padding
self.end_title_padding = end_title_padding
self.end_artist_padding = end_artist_padding
self.end_extra_text_padding = end_extra_text_padding
self.end_fixed_gap = end_fixed_gap
self.end_extra_text = end_extra_text
self.lyrics_artist = lyrics_artist
self.lyrics_title = lyrics_title
self.skip_lyrics = skip_lyrics
# Path to the Windows PyInstaller frozen bundled ffmpeg.exe, or the system-installed FFmpeg binary on Mac/Linux
ffmpeg_path = os.path.join(sys._MEIPASS, "ffmpeg.exe") if getattr(sys, "frozen", False) else "ffmpeg"
@@ -83,11 +132,22 @@ class KaraokePrep:
self.title_format = {
"background_color": intro_background_color,
"background_image": intro_background_image,
"intro_font": intro_font,
"font": intro_font,
"artist_color": intro_artist_color,
"title_color": intro_title_color,
}
self.end_format = {
"background_color": end_background_color,
"background_image": end_background_image,
"font": end_font,
"extra_text_color": end_extra_text_color,
"artist_color": end_artist_color,
"title_color": end_title_color,
}
self.existing_end_image = existing_end_image
self.extracted_info = None
self.persistent_artist = None
@@ -184,7 +244,7 @@ class KaraokePrep:
copied_file_name = output_filename_no_extension + os.path.splitext(input_media)[1]
self.logger.debug(f"Copying {input_media} to {copied_file_name}")
shutil.copy2(input_media, copied_file_name)
return copied_file_name
def download_video(self, url, output_filename_no_extension):
@@ -223,7 +283,8 @@ class KaraokePrep:
self.logger.info(f"Converting input media to audio WAV file")
ffmpeg_command = f'{self.ffmpeg_base_command} -n -i "{input_filename}" "{output_filename}"'
self.logger.debug(f"Running command: {ffmpeg_command}")
os.system(ffmpeg_command)
if not self.dry_run:
os.system(ffmpeg_command)
return output_filename
def write_lyrics_from_genius(self, artist, title, filename):
@@ -232,8 +293,9 @@ class KaraokePrep:
if song:
lyrics = self.clean_genius_lyrics(song.lyrics)
with open(filename, "w") as f:
f.write(lyrics)
if not self.dry_run:
with open(filename, "w") as f:
f.write(lyrics)
self.logger.info("Lyrics for %s by %s fetched successfully", title, artist)
return lyrics.split("\n")
@@ -339,40 +401,51 @@ class KaraokePrep:
return processed_lines
def write_processed_lyrics(self, lyrics, processed_lyrics_file):
self.logger.info(f"Writing processed lyrics to {processed_lyrics_file}")
def transcribe_lyrics(self, input_audio_wav, track_output_dir):
self.logger.info(f"Transcribing lyrics from audio file: {input_audio_wav} with output directory: {track_output_dir}")
processed_lyrics_lines = ""
iteration_count = 0
max_iterations = 100 # Failsafe limit
if os.environ.get("AUDIOSHAKE_API_TOKEN") is None:
self.logger.warning("Error: AUDIOSHAKE_API_TOKEN environment variable is not set, skipping transcription")
return
with open(processed_lyrics_file, "w") as outfile:
all_processed = False
while not all_processed:
if iteration_count > max_iterations:
self.logger.error("Maximum iterations exceeded in write_processed_lyrics.")
break
self.logger.debug("Loading LyricsTranscriber class")
all_processed = True
new_lyrics = []
for line in lyrics:
line = line.strip()
processed = self.process_line(line)
new_lyrics.extend(processed)
if any(len(l) > 36 for l in processed):
all_processed = False
lyrics = new_lyrics
transcriber = LyricsTranscriber(
input_audio_wav,
log_level=self.log_level,
log_formatter=self.log_formatter,
audioshake_api_token=os.environ["AUDIOSHAKE_API_TOKEN"],
output_dir=track_output_dir,
artist=self.artist,
title=self.title,
)
iteration_count += 1
transcriber_outputs = transcriber.generate()
# Write the processed lyrics to file
for line in lyrics:
outfile.write(line + "\n")
processed_lyrics_lines += line + "\n"
self.logger.info(f"*** Outputs: ***")
self.logger.info(f"Transcription output data file: {transcriber_outputs['transcription_data_filepath']}")
self.logger.info(f"Transcribed lyrics text file: {transcriber_outputs['transcribed_lyrics_text_filepath']}")
self.logger.info(f"MidiCo LRC output file: {transcriber_outputs['midico_lrc_filepath']}")
pyperclip.copy(processed_lyrics_lines)
self.logger.info(f"Processed lyrics copied to clipboard.")
return processed_lyrics_lines
def write_processed_lyrics(self, lyrics_file, processed_lyrics_file):
self.logger.info(f"Processing lyrics from {lyrics_file} and writing to {processed_lyrics_file}")
if not self.dry_run:
processor = KaraokeLyricsProcessor(
log_level=self.log_level,
log_formatter=self.log_formatter,
input_filename=lyrics_file,
output_filename=processed_lyrics_file,
max_line_length=36, # Using the default max line length
)
processor.process()
processor.write_to_output_file()
self.logger.info(f"Lyrics processing complete, processed lyrics written to: {processed_lyrics_file}")
else:
self.logger.info(f"DRY RUN: Would process lyrics from {lyrics_file} and write to: {processed_lyrics_file}")
return processed_lyrics_file
def sanitize_filename(self, filename):
"""Replace or remove characters that are unsafe for filenames."""
@@ -380,17 +453,17 @@ class KaraokePrep:
for char in ["\\", "/", ":", "*", "?", '"', "<", ">", "|"]:
filename = filename.replace(char, "_")
# Remove any trailing periods or spaces
filename = filename.rstrip(". ")
filename = filename.rstrip(" ")
return filename
def separate_audio(self, audio_file, model_name, instrumental_path, vocals_path):
def separate_audio(self, audio_file, model_name, artist_title, track_output_dir, instrumental_path, vocals_path):
if audio_file is None or not os.path.isfile(audio_file):
raise Exception("Error: Invalid audio source provided.")
self.logger.debug(f"audio_file is valid file: {audio_file}")
self.logger.debug(
f"instantiating Separator with model_name: {model_name} instrumental_path: {instrumental_path} and lossless_output_format: {self.lossless_output_format}"
self.logger.info(
f"instantiating Separator with model_file_dir: {self.model_file_dir}, model_filename: {model_name} output_format: {self.lossless_output_format}"
)
from audio_separator.separator import Separator
@@ -400,14 +473,47 @@ class KaraokePrep:
log_formatter=self.log_formatter,
model_file_dir=self.model_file_dir,
output_format=self.lossless_output_format,
primary_stem_path=instrumental_path,
secondary_stem_path=vocals_path,
)
separator.load_model(model_name)
separator.load_model(model_filename=model_name)
output_files = separator.separate(audio_file)
self.logger.info(f"Separation complete! Output file(s): {' '.join(output_files)}")
self.logger.debug(f"Separator output files: {output_files}")
model_name_no_extension = os.path.splitext(model_name)[0]
for file in output_files:
if "(Vocals)" in file:
self.logger.info(f"Renaming Vocals file {file} to {vocals_path}")
os.rename(file, vocals_path)
elif "(Instrumental)" in file:
self.logger.info(f"Renaming Instrumental file {file} to {instrumental_path}")
os.rename(file, instrumental_path)
elif model_name in file:
# Example filename 1: "Freddie Jackson - All I'll Ever Ask (feat. Najee) (Local)_(Piano)_htdemucs_6s.flac"
# Example filename 2: "Freddie Jackson - All I'll Ever Ask (feat. Najee) (Local)_(Guitar)_htdemucs_6s.flac"
# The stem name in these examples would be "Piano" or "Guitar"
# Extract stem_name from the filename
stem_name = file.split(f"_{model_name}")[0].split("_")[-1]
stem_name = stem_name.strip("()") # Remove parentheses if present
other_stem_path = os.path.join(track_output_dir, f"{artist_title} ({stem_name} {model_name}).{self.lossless_output_format}")
self.logger.info(f"Renaming other stem file {file} to {other_stem_path}")
os.rename(file, other_stem_path)
elif model_name_no_extension in file:
# Example filename 1: "Freddie Jackson - All I'll Ever Ask (feat. Najee) (Local)_(Piano)_htdemucs_6s.flac"
# Example filename 2: "Freddie Jackson - All I'll Ever Ask (feat. Najee) (Local)_(Guitar)_htdemucs_6s.flac"
# The stem name in these examples would be "Piano" or "Guitar"
# Extract stem_name from the filename
stem_name = file.split(f"_{model_name_no_extension}")[0].split("_")[-1]
stem_name = stem_name.strip("()") # Remove parentheses if present
other_stem_path = os.path.join(track_output_dir, f"{artist_title} ({stem_name} {model_name}).{self.lossless_output_format}")
self.logger.info(f"Renaming other stem file {file} to {other_stem_path}")
os.rename(file, other_stem_path)
self.logger.info(f"Separation complete! Output file(s): {vocals_path} {instrumental_path}")
def setup_output_paths(self, artist, title):
sanitized_artist = self.sanitize_filename(artist)
@@ -454,64 +560,158 @@ class KaraokePrep:
text_y = vertical_offset
return (text_x, text_y), text_height
def create_title_video(self, artist, title, format, output_image_filepath_noext, output_video_filepath):
duration = 5 # Duration in seconds
def create_video(
self,
extra_text,
title_text,
artist_text,
format,
output_image_filepath_noext,
output_video_filepath,
existing_image=None,
extra_text_color=None,
title_color=None,
artist_color=None,
duration=5,
initial_font_size=500,
top_padding=950,
title_padding=400,
artist_padding=700,
extra_text_padding=600,
fixed_gap=150,
):
resolution = (3840, 2160) # 4K resolution
# Load or create background image
if format["background_image"] and os.path.exists(format["background_image"]):
self.logger.info(f"Using title screen background image file: {format['background_image']}")
background = Image.open(format["background_image"])
else:
self.logger.info(f"Using title screen background color: {format['background_color']}")
background = Image.new("RGB", resolution, color=self.hex_to_rgb(format["background_color"]))
# Resize background to match resolution
background = background.resize(resolution)
title = title.upper()
artist = artist.upper()
initial_font_size = 500
top_padding = 950
title_padding = 400
artist_padding = 700
fixed_gap = 150
draw = ImageDraw.Draw(background)
# Accessing the font file from the package resources
with pkg_resources.path("karaoke_prep.resources", format["intro_font"]) as font_path:
# Calculate positions and sizes for title and artist
title_font, _ = self.calculate_text_size_and_position(draw, title, str(font_path), initial_font_size, resolution, title_padding)
artist_font, _ = self.calculate_text_size_and_position(
draw, artist, str(font_path), initial_font_size, resolution, artist_padding
)
# Calculate vertical positions with consistent gap
title_text_position, title_height = self.calculate_text_position(draw, title, title_font, resolution, top_padding)
artist_text_position, _ = self.calculate_text_position(
draw, artist, artist_font, resolution, title_text_position[1] + title_height + fixed_gap
self.logger.info(f"Creating video with format: {format}")
self.logger.info(f"extra_text: {extra_text}, artist_text: {artist_text}, title_text: {title_text}")
self.logger.info(
f"top_padding: {top_padding}, title_padding: {title_padding}, artist_padding: {artist_padding}, extra_text_padding: {extra_text_padding}"
)
draw.text(title_text_position, title, fill=format["title_color"], font=title_font)
draw.text(artist_text_position, artist, fill=format["artist_color"], font=artist_font)
if existing_image:
self.logger.info(f"Using existing image file: {existing_image}")
existing_extension = os.path.splitext(existing_image)[1]
# Save static background image
background.save(f"{output_image_filepath_noext}.png")
if existing_extension == ".png":
self.logger.info(f"Copying existing PNG image file: {existing_image}")
shutil.copy2(existing_image, output_image_filepath_noext + existing_extension)
else:
self.logger.info(f"Converting existing image to PNG")
existing_image_obj = Image.open(existing_image)
existing_image_obj.save(output_image_filepath_noext + ".png")
# Save static background image as JPG for smaller filesize to upload as YouTube thumbnail
background_rgb = background.convert("RGB")
background_rgb.save(f"{output_image_filepath_noext}.jpg", quality=95)
if existing_extension != ".jpg":
self.logger.info(f"Converting existing image to JPG")
existing_image_obj = Image.open(existing_image)
if existing_image_obj.mode == "RGBA":
existing_image_obj = existing_image_obj.convert("RGB") # Convert RGBA to RGB
existing_image_obj.save(output_image_filepath_noext + ".jpg", quality=95)
else:
# Load or create background image
if format["background_image"] and os.path.exists(format["background_image"]):
self.logger.info(f"Using background image file: {format['background_image']}")
background = Image.open(format["background_image"])
else:
self.logger.info(f"Using background color: {format['background_color']}")
background = Image.new("RGB", resolution, color=self.hex_to_rgb(format["background_color"]))
# Resize background to match resolution
background = background.resize(resolution)
draw = ImageDraw.Draw(background)
# Accessing the font file from the package resources
with pkg_resources.path("karaoke_prep.resources", format["font"]) as font_path:
# Calculate positions and sizes for title, artist, and extra text
title_font, _ = self.calculate_text_size_and_position(
draw, title_text, str(font_path), initial_font_size, resolution, title_padding
)
artist_font, _ = self.calculate_text_size_and_position(
draw, artist_text, str(font_path), initial_font_size, resolution, artist_padding
)
if extra_text:
self.logger.info(f"Calculating extra text font size and position for: {extra_text}")
extra_text_font, _ = self.calculate_text_size_and_position(
draw, extra_text, str(font_path), initial_font_size, resolution, extra_text_padding
)
# Calculate vertical positions with consistent gap
current_y = top_padding
if extra_text:
self.logger.info(f"Calculating extra text position for: {extra_text}")
extra_text_position, extra_text_height = self.calculate_text_position(
draw, extra_text, extra_text_font, resolution, current_y
)
draw.text(extra_text_position, extra_text, fill=extra_text_color, font=extra_text_font)
current_y += extra_text_height + fixed_gap
title_text_position, title_height = self.calculate_text_position(draw, title_text, title_font, resolution, current_y)
draw.text(title_text_position, title_text, fill=title_color, font=title_font)
current_y += title_height + fixed_gap
artist_text_position, _ = self.calculate_text_position(draw, artist_text, artist_font, resolution, current_y)
draw.text(artist_text_position, artist_text, fill=artist_color, font=artist_font)
# Save static background image
background.save(f"{output_image_filepath_noext}.png")
# Save static background image as JPG for smaller filesize to upload as YouTube thumbnail
background_rgb = background.convert("RGB")
background_rgb.save(f"{output_image_filepath_noext}.jpg", quality=95)
# Use ffmpeg to create video
ffmpeg_command = f'{self.ffmpeg_base_command} -y -loop 1 -framerate 30 -i "{output_image_filepath_noext}.png" -f lavfi -i anullsrc '
ffmpeg_command += f'-c:v libx264 -r 30 -t {duration} -pix_fmt yuv420p -vf scale={resolution[0]}:{resolution[1]} -c:a aac -shortest "{output_video_filepath}"'
self.logger.info("Generating title video...")
self.logger.info("Generating video...")
self.logger.debug(f"Running command: {ffmpeg_command}")
os.system(ffmpeg_command)
def create_end_video(self, artist, title, format, output_image_filepath_noext, output_video_filepath):
extra_text = self.end_extra_text
title_text = title.upper()
artist_text = artist.upper()
self.create_video(
extra_text=extra_text,
title_text=title_text,
artist_text=artist_text,
format=format,
output_image_filepath_noext=output_image_filepath_noext,
output_video_filepath=output_video_filepath,
existing_image=self.existing_end_image,
extra_text_color=format["extra_text_color"],
title_color=format["title_color"],
artist_color=format["artist_color"],
duration=self.end_video_duration,
initial_font_size=self.end_initial_font_size,
top_padding=self.end_top_padding,
title_padding=self.end_title_padding,
artist_padding=self.end_artist_padding,
extra_text_padding=self.end_extra_text_padding,
fixed_gap=self.end_fixed_gap,
)
def create_title_video(self, artist, title, format, output_image_filepath_noext, output_video_filepath):
title_text = title.upper()
artist_text = artist.upper()
self.create_video(
extra_text=None,
title_text=title_text,
artist_text=artist_text,
format=format,
output_image_filepath_noext=output_image_filepath_noext,
output_video_filepath=output_video_filepath,
existing_image=self.existing_title_image,
title_color=format["title_color"],
artist_color=format["artist_color"],
duration=self.title_video_duration,
initial_font_size=self.title_initial_font_size,
top_padding=self.title_top_padding,
title_padding=self.title_title_padding,
artist_padding=self.title_artist_padding,
fixed_gap=self.title_fixed_gap,
)
def hex_to_rgb(self, hex_color):
"""Convert hex color to RGB tuple."""
hex_color = hex_color.lstrip("#")
@@ -520,13 +720,16 @@ class KaraokePrep:
def prep_single_track(self):
self.logger.info(f"Preparing single track: {self.artist} - {self.title}")
if os.path.isfile(self.input_media):
if self.input_media is not None and os.path.isfile(self.input_media):
self.extractor = "Local"
else:
# Parses metadata in self.extracted_info to set vars: self.url, self.extractor, self.media_id, self.artist, self.title
self.parse_single_track_metadata(input_artist=self.artist, input_title=self.title)
self.logger.info(f"Preparing output path for track: {self.title} by {self.artist}")
if self.dry_run:
return None
track_output_dir, artist_title = self.setup_output_paths(self.artist, self.title)
processed_track = {
@@ -537,13 +740,14 @@ class KaraokePrep:
"extracted_info": self.extracted_info,
"lyrics": None,
"processed_lyrics": None,
"separated_audio": {},
}
processed_track["input_media"] = None
processed_track["input_still_image"] = None
processed_track["input_audio_wav"] = None
if os.path.isfile(self.input_media):
if self.input_media is not None and os.path.isfile(self.input_media):
input_wav_filename_pattern = os.path.join(track_output_dir, f"{artist_title} ({self.extractor} *.wav")
input_wav_glob = glob.glob(input_wav_filename_pattern)
@@ -555,7 +759,7 @@ class KaraokePrep:
self.logger.info(f"Copying input media from {self.input_media} to new directory...")
processed_track["input_media"] = self.copy_input_media(self.input_media, output_filename_no_extension)
self.logger.info("Converting input media to WAV for audio processing...")
processed_track["input_audio_wav"] = self.convert_to_wav(processed_track["input_media"], output_filename_no_extension)
@@ -593,19 +797,28 @@ class KaraokePrep:
else:
self.logger.warning(f"Skipping download due to missing URL.")
processed_track["lyrics"] = os.path.join(track_output_dir, f"{artist_title} (Lyrics).txt")
if os.path.exists(processed_track["lyrics"]):
self.logger.debug(f"Lyrics file already exists, skipping fetch: {processed_track['lyrics']}")
if self.skip_lyrics:
self.logger.info("Skipping lyrics fetch as requested.")
processed_track["lyrics"] = None
processed_track["processed_lyrics"] = None
else:
self.logger.info("Fetching lyrics from Genius...")
self.lyrics = self.write_lyrics_from_genius(self.artist, self.title, processed_track["lyrics"])
processed_track["processed_lyrics"] = os.path.join(track_output_dir, f"{artist_title} (Lyrics Processed).txt")
if self.lyrics is None:
processed_track["lyrics"] = None
processed_track["processed_lyrics"] = None
processed_track["lyrics"] = os.path.join(track_output_dir, f"{artist_title} (Lyrics).txt")
if os.path.exists(processed_track["lyrics"]):
self.logger.debug(f"Lyrics file already exists, skipping fetch: {processed_track['lyrics']}")
else:
self.write_processed_lyrics(self.lyrics, processed_track["processed_lyrics"])
self.logger.info("Fetching lyrics from Genius...")
lyrics_artist = self.lyrics_artist or self.artist
lyrics_title = self.lyrics_title or self.title
self.lyrics = self.write_lyrics_from_genius(lyrics_artist, lyrics_title, processed_track["lyrics"])
processed_track["processed_lyrics"] = os.path.join(track_output_dir, f"{artist_title} (Lyrics Processed).txt")
if self.lyrics is None:
processed_track["lyrics"] = None
processed_track["processed_lyrics"] = None
else:
self.write_processed_lyrics(processed_track["lyrics"], processed_track["processed_lyrics"])
self.transcribe_lyrics(processed_track["input_audio_wav"], track_output_dir)
output_image_filepath_noext = os.path.join(track_output_dir, f"{artist_title} (Title)")
processed_track["title_image_png"] = f"{output_image_filepath_noext}.png"
@@ -618,51 +831,64 @@ class KaraokePrep:
self.logger.info(f"Creating title video...")
self.create_title_video(self.artist, self.title, self.title_format, output_image_filepath_noext, processed_track["title_video"])
self.logger.info(f"Separating audio twice for track: {self.title} by {self.artist}")
output_image_filepath_noext = os.path.join(track_output_dir, f"{artist_title} (End)")
processed_track["end_image_png"] = f"{output_image_filepath_noext}.png"
processed_track["end_image_jpg"] = f"{output_image_filepath_noext}.jpg"
processed_track["end_video"] = os.path.join(track_output_dir, f"{artist_title} (End).mov")
instrumental_path = os.path.join(track_output_dir, f"{artist_title} (Instrumental {self.model_name}).{self.lossless_output_format}")
vocals_path = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name}).{self.lossless_output_format}")
instrumental_path_lossy = os.path.join(
track_output_dir, f"{artist_title} (Instrumental {self.model_name}).{self.lossy_output_format}"
)
vocals_path_lossy = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name}).{self.lossy_output_format}")
if os.path.isfile(instrumental_path) and os.path.isfile(vocals_path):
self.logger.debug(f"Separated audio files already exist in output paths, skipping separation: {instrumental_path}")
if os.path.exists(processed_track["end_video"]):
self.logger.debug(f"End screen video already exists, skipping render: {processed_track['end_video']}")
else:
self.separate_audio(processed_track["input_audio_wav"], self.model_name, instrumental_path, vocals_path)
self.logger.info(f"Creating end screen video...")
self.create_end_video(self.artist, self.title, self.end_format, output_image_filepath_noext, processed_track["end_video"])
if self.existing_instrumental:
self.logger.info(f"Using existing instrumental file: {self.existing_instrumental}")
existing_instrumental_extension = os.path.splitext(self.existing_instrumental)[1]
instrumental_path = os.path.join(track_output_dir, f"{artist_title} (Instrumental Custom){existing_instrumental_extension}")
instrumental_path_lossy = os.path.join(track_output_dir, f"{artist_title} (Instrumental Custom).{self.lossy_output_format}")
shutil.copy2(self.existing_instrumental, instrumental_path)
self.convert_to_lossy(instrumental_path, instrumental_path_lossy)
self.convert_to_lossy(vocals_path, vocals_path_lossy)
processed_track["instrumental_audio"] = instrumental_path
processed_track["vocals_audio"] = vocals_path
processed_track["instrumental_audio_lossy"] = instrumental_path_lossy
processed_track["vocals_audio_lossy"] = vocals_path_lossy
instrumental_path_2 = os.path.join(
track_output_dir, f"{artist_title} (Instrumental {self.model_name_2}).{self.lossless_output_format}"
)
vocals_path_2 = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name_2}).{self.lossless_output_format}")
instrumental_path_2_lossy = os.path.join(
track_output_dir, f"{artist_title} (Instrumental {self.model_name_2}).{self.lossy_output_format}"
)
vocals_path_2_lossy = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name_2}).{self.lossy_output_format}")
if os.path.isfile(instrumental_path_2) and os.path.isfile(vocals_path_2):
self.logger.debug(f"Separated audio files already exist in output paths, skipping separation: {instrumental_path_2}")
processed_track["separated_audio"]["Custom"] = {
"instrumental": instrumental_path,
"instrumental_lossy": instrumental_path_lossy,
"vocals": None,
"vocals_lossy": None,
}
else:
self.separate_audio(processed_track["input_audio_wav"], self.model_name_2, instrumental_path_2, vocals_path_2)
self.convert_to_lossy(instrumental_path_2, instrumental_path_2_lossy)
self.convert_to_lossy(vocals_path_2, vocals_path_2_lossy)
self.logger.info(f"Separating audio for track: {self.title} by {self.artist} using models: {', '.join(self.model_names)}")
for model_name in self.model_names:
processed_track[f"separated_audio"][model_name] = {}
instrumental_path = os.path.join(
track_output_dir, f"{artist_title} (Instrumental {model_name}).{self.lossless_output_format}"
)
vocals_path = os.path.join(track_output_dir, f"{artist_title} (Vocals {model_name}).{self.lossless_output_format}")
instrumental_path_lossy = os.path.join(
track_output_dir, f"{artist_title} (Instrumental {model_name}).{self.lossy_output_format}"
)
vocals_path_lossy = os.path.join(track_output_dir, f"{artist_title} (Vocals {model_name}).{self.lossy_output_format}")
processed_track["instrumental_audio_2"] = instrumental_path_2
processed_track["vocals_audio_2"] = vocals_path_2
if not (os.path.isfile(instrumental_path) and os.path.isfile(vocals_path)):
self.separate_audio(
audio_file=processed_track["input_audio_wav"],
model_name=model_name,
track_output_dir=track_output_dir,
artist_title=artist_title,
instrumental_path=instrumental_path,
vocals_path=vocals_path,
)
if os.path.isfile(instrumental_path):
self.convert_to_lossy(instrumental_path, instrumental_path_lossy)
if os.path.isfile(vocals_path):
self.convert_to_lossy(vocals_path, vocals_path_lossy)
processed_track["instrumental_audio_2_lossy"] = instrumental_path_2_lossy
processed_track["vocals_audio_2_lossy"] = vocals_path_2_lossy
processed_track[f"separated_audio"][model_name]["instrumental"] = instrumental_path
processed_track[f"separated_audio"][model_name]["vocals"] = vocals_path
processed_track[f"separated_audio"][model_name]["instrumental_lossy"] = instrumental_path_lossy
processed_track[f"separated_audio"][model_name]["vocals_lossy"] = vocals_path_lossy
self.logger.info("Script finished, audio downloaded, lyrics fetched and audio separated!")
@@ -681,25 +907,73 @@ class KaraokePrep:
os.system(ffmpeg_command)
def process_playlist(self):
if self.artist is None or self.title is None:
raise Exception("Error: Artist and Title are required for processing a local file.")
if "entries" in self.extracted_info:
track_results = []
self.logger.info(f"Found {len(self.extracted_info['entries'])} entries in playlist, processing each invididually...")
for entry in self.extracted_info["entries"]:
self.extracted_info = entry
self.logger.info(f"Processing playlist entry with title: {self.extracted_info['title']}")
track_results.append(self.prep_single_track())
if not self.dry_run:
track_results.append(self.prep_single_track())
self.artist = self.persistent_artist
self.title = None
return track_results
else:
raise Exception(f"Failed to find 'entries' in playlist, cannot process")
def process(self):
if os.path.isfile(self.input_media):
self.logger.info(f"Input media {self.input_media} is a local file, youtube logic will be skipped")
def process_folder(self):
if self.filename_pattern is None or self.artist is None:
raise Exception("Error: Filename pattern and artist are required for processing a folder.")
if self.artist is None or self.title is None:
raise Exception("Error: Artist and Title are required for processing a local file.")
folder_path = self.input_media
output_folder_path = os.path.join(os.getcwd(), os.path.basename(folder_path))
if not os.path.exists(output_folder_path):
if not self.dry_run:
self.logger.info(f"DRY RUN: Would create output folder: {output_folder_path}")
os.makedirs(output_folder_path)
else:
self.logger.info(f"Output folder already exists: {output_folder_path}")
pattern = re.compile(self.filename_pattern)
tracks = []
for filename in sorted(os.listdir(folder_path)):
match = pattern.match(filename)
if match:
title = match.group("title")
file_path = os.path.join(folder_path, filename)
self.input_media = file_path
self.title = title
track_index = match.group("index") if "index" in match.groupdict() else None
self.logger.info(f"Processing track: {track_index} with title: {title} from file: {filename}")
track_output_dir = os.path.join(output_folder_path, f"{track_index} - {self.artist} - {title}")
if not self.dry_run:
track = self.prep_single_track()
tracks.append(track)
# Move the track folder to the output folder
track_folder = track["track_output_dir"]
shutil.move(track_folder, track_output_dir)
else:
self.logger.info(f"DRY RUN: Would move track folder to: {os.path.basename(track_output_dir)}")
return tracks
def process(self):
if self.input_media is not None and os.path.isdir(self.input_media):
self.logger.info(f"Input media {self.input_media} is a local folder, processing each file individually...")
return self.process_folder()
elif self.input_media is not None and os.path.isfile(self.input_media):
self.logger.info(f"Input media {self.input_media} is a local file, youtube logic will be skipped")
return [self.prep_single_track()]
else:
+41 -4
View File
@@ -47,6 +47,18 @@ def main():
help="Optional: format / file extension for instrumental track to use for remux (default: %(default)s). Example: --instrumental_format=mp3",
)
parser.add_argument(
"--enable_cdg",
action="store_true",
help="Optional: Enable CDG ZIP generation during finalisation (default: disabled). Example: --enable_cdg",
)
parser.add_argument(
"--enable_txt",
action="store_true",
help="Optional: Enable TXT ZIP generation during finalisation (default: disabled). Example: --enable_txt",
)
parser.add_argument(
"--brand_prefix",
default=None,
@@ -59,6 +71,12 @@ def main():
help="Optional: Target directory where the processed folder will be moved after finalisation. Example: --organised_dir='/path/to/Tracks-Organized'",
)
parser.add_argument(
"--organised_dir_rclone_root",
default=None,
help="Optional: Rclone path which maps to your organised_dir, to generate a sharing link after adding files to it. Example: --organised_dir_rclone_root='andrewdropbox:Media/Karaoke/Tracks-Organized'",
)
parser.add_argument(
"--public_share_dir",
default=None,
@@ -83,6 +101,12 @@ def main():
help="Optional: Rclone destination to sync your public_share_dir to after adding files to it. Example: --rclone_destination='googledrive:YourBrandNameFolder'",
)
parser.add_argument(
"--discord_webhook_url",
default=None,
help="Optional: Discord webhook URL to send notifications to. Example: --discord_webhook_url='https://discord.com/api/webhooks/1234567890/TOKEN/messages",
)
args = parser.parse_args()
log_level = getattr(logging, args.log_level.upper())
@@ -96,13 +120,16 @@ def main():
dry_run=args.dry_run,
model_name=args.model_name,
instrumental_format=args.instrumental_format,
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=os.environ.get("DISCORD_WEBHOOK_URL"),
discord_webhook_url=args.discord_webhook_url,
)
try:
@@ -116,12 +143,22 @@ def main():
logger.info(f"Track: {track['artist']} - {track['title']}")
logger.info(f" Video With Vocals: {track['video_with_vocals']}")
logger.info(f" Video With Instrumental: {track['video_with_instrumental']}")
logger.info(f" Final CDG+MP3 ZIP: {track['final_video']}")
logger.info(f" Final Video with Title: {track['final_zip']}")
logger.info(f" YouTube URL: {track['youtube_url']}")
if "final_karaoke_cdg_zip" in track:
logger.info(f" Final 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" Final Video with Title: {track['final_video']}")
logger.info(f" Final Video 720p: {track['final_video_720p']}")
logger.info(f" Brand Code: {track['brand_code']}")
logger.info(f" New Brand Code Directory: {track['new_brand_code_dir_path']}")
logger.info(f" YouTube URL: {track['youtube_url']}")
logger.info(f" Folder Sharing Link: {track['brand_code_dir_sharing_link']}")
if __name__ == "__main__":
main()
+238 -9
View File
@@ -45,13 +45,37 @@ def main():
)
parser.add_argument(
"--model_name",
default="UVR_MDXNET_KARA_2",
help="Optional: model name to be used for separation (default: %(default)s). Example: --model_name=UVR-MDX-NET-Inst_HQ_3",
"--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'",
)
# Use tempfile to get the platform-independent temp directory
default_model_dir = os.path.join(tempfile.gettempdir(), "audio-separator-models")
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(
"--model_names",
nargs="+",
default=[
"UVR_MDXNET_KARA_2.onnx",
"mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt",
"2_HP-UVR.pth",
"model_bs_roformer_ep_317_sdr_12.9755.yaml",
"MDX23C-8KFFT-InstVoc_HQ_2.ckpt",
"htdemucs_6s.yaml",
],
help="Optional: list of model names to be used for separation (default: %(default)s). Example: --model_names UVR_MDXNET_KARA_2.onnx UVR-MDX-NET-Inst_HQ_4.onnx",
)
default_model_dir_unix = "/tmp/audio-separator-models/"
if os.name == "posix" and os.path.exists(default_model_dir_unix):
default_model_dir = default_model_dir_unix
else:
# Use tempfile to get the platform-independent temp directory
default_model_dir = os.path.join(tempfile.gettempdir(), "audio-separator-models")
parser.add_argument(
"--model_file_dir",
default=default_model_dir,
@@ -137,9 +161,166 @@ def main():
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(
"--title_video_duration",
type=int,
default=5,
help="Optional: duration of the title video in seconds (default: 5). Example: --title_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",
)
parser.add_argument(
"--title_initial_font_size",
type=int,
default=500,
help="Optional: Initial font size for title video (default: 500). Example: --title_initial_font_size=600",
)
parser.add_argument(
"--title_top_padding",
type=int,
default=950,
help="Optional: Top padding for title video (default: 950). Example: --title_top_padding=1000",
)
parser.add_argument(
"--title_title_padding",
type=int,
default=400,
help="Optional: Title padding for title video (default: 400). Example: --title_title_padding=450",
)
parser.add_argument(
"--title_artist_padding",
type=int,
default=700,
help="Optional: Artist padding for title video (default: 700). Example: --title_artist_padding=750",
)
parser.add_argument(
"--title_fixed_gap",
type=int,
default=150,
help="Optional: Fixed gap for title video (default: 150). Example: --title_fixed_gap=200",
)
parser.add_argument(
"--end_initial_font_size",
type=int,
default=500,
help="Optional: Initial font size for end video (default: 500). Example: --end_initial_font_size=600",
)
parser.add_argument(
"--end_top_padding",
type=int,
default=950,
help="Optional: Top padding for end video (default: 950). Example: --end_top_padding=1000",
)
parser.add_argument(
"--end_title_padding",
type=int,
default=400,
help="Optional: Title padding for end video (default: 400). Example: --end_title_padding=450",
)
parser.add_argument(
"--end_artist_padding",
type=int,
default=700,
help="Optional: Artist padding for end video (default: 700). Example: --end_artist_padding=750",
)
parser.add_argument(
"--end_extra_text_padding",
type=int,
default=300,
help="Optional: Extra text padding for end video (default: 600). Example: --end_extra_text_padding=650",
)
parser.add_argument(
"--end_fixed_gap",
type=int,
default=150,
help="Optional: Fixed gap for end video (default: 150). Example: --end_fixed_gap=200",
)
parser.add_argument(
"--lyrics_artist",
help="Optional: Override the artist name used for lyrics search. Example: --lyrics_artist='The Beatles'",
)
parser.add_argument(
"--lyrics_title",
help="Optional: Override the song title used for lyrics search. Example: --lyrics_title='Hey Jude'",
)
parser.add_argument(
"--skip_lyrics",
action="store_true",
help="Optional: Skip fetching and processing lyrics. Example: --skip_lyrics",
)
args = parser.parse_args()
input_media, artist, title = None, None, None
input_media, artist, title, filename_pattern = None, None, None, None
if not args.args:
parser.print_help()
exit(1)
# Allow 3 forms of positional arguments:
# 1. URL or Media File only (may be single track URL, playlist URL, or local file)
@@ -155,10 +336,23 @@ def main():
else:
logger.warn("Input media provided without Artist and Title, both will be guessed from title")
elif os.path.isdir(args.args[0]):
if not args.filename_pattern:
logger.error("Filename pattern is required when processing a folder.")
exit(1)
if len(args.args) <= 1:
logger.error("Second parameter provided must be Artist name; Artist is required when processing a folder.")
exit(1)
input_media = args.args[0]
artist = args.args[1]
filename_pattern = args.filename_pattern
elif len(args.args) > 1:
artist = args.args[0]
title = args.args[1]
logger.warn(f"No input media provided, the top YouTube search result for {artist} - {title} will be used.")
else:
parser.print_help()
exit(1)
@@ -166,15 +360,20 @@ def main():
log_level = getattr(logging, args.log_level.upper())
logger.setLevel(log_level)
if args.existing_instrumental:
args.model_names = ["Custom"]
logger.info(f"KaraokePrep beginning with input_media: {input_media} artist: {artist} and title: {title}")
kprep = KaraokePrep(
artist=artist,
title=title,
input_media=input_media,
filename_pattern=filename_pattern,
dry_run=args.dry_run,
log_formatter=log_formatter,
log_level=log_level,
model_name=args.model_name,
model_names=args.model_names,
model_file_dir=args.model_file_dir,
output_dir=args.output_dir,
lossless_output_format=args.lossless_output_format,
@@ -184,11 +383,37 @@ def main():
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,
title_video_duration=args.title_video_duration,
intro_background_color=args.intro_background_color,
intro_background_image=args.intro_background_image,
intro_font=args.intro_font,
intro_artist_color=args.intro_artist_color,
intro_title_color=args.intro_title_color,
title_initial_font_size=args.title_initial_font_size,
title_top_padding=args.title_top_padding,
title_title_padding=args.title_title_padding,
title_artist_padding=args.title_artist_padding,
title_fixed_gap=args.title_fixed_gap,
end_video_duration=args.end_video_duration,
end_extra_text=args.end_extra_text,
end_background_color=args.end_background_color,
end_background_image=args.end_background_image,
end_font=args.end_font,
end_extra_text_color=args.end_extra_text_color,
end_artist_color=args.end_artist_color,
end_title_color=args.end_title_color,
end_initial_font_size=args.end_initial_font_size,
end_top_padding=args.end_top_padding,
end_title_padding=args.end_title_padding,
end_artist_padding=args.end_artist_padding,
end_extra_text_padding=args.end_extra_text_padding,
end_fixed_gap=args.end_fixed_gap,
lyrics_artist=args.lyrics_artist,
lyrics_title=args.lyrics_title,
skip_lyrics=args.skip_lyrics,
)
tracks = kprep.process()
@@ -203,8 +428,12 @@ def main():
logger.info(f" Input Still Image: {track['input_still_image']}")
logger.info(f" Lyrics: {track['lyrics']}")
logger.info(f" Processed Lyrics: {track['processed_lyrics']}")
logger.info(f" Instrumental: {track['instrumental_audio']}")
logger.info(f" Vocals: {track['vocals_audio']}")
for model_name in args.model_names:
logger.info(f" Instrumental: {track['separated_audio'][model_name]['instrumental']}")
logger.info(f" Instrumental (Lossy): {track['separated_audio'][model_name]['instrumental_lossy']}")
logger.info(f" Vocals: {track['separated_audio'][model_name]['vocals']}")
logger.info(f" Vocals (Lossy): {track['separated_audio'][model_name]['vocals_lossy']}")
if __name__ == "__main__":
Generated
+3091 -1488
View File
File diff suppressed because it is too large. Load diff
+16 -8
View File
@@ -1,17 +1,18 @@
[tool.poetry]
name = "karaoke-prep"
version = "0.15.3"
version = "0.27.2"
description = "Prepare for karaoke video creation, by downloading audio and lyrics for a specified song or playlist from youtube and separating audio stems. After syncing, finalise the video with a title screen!"
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"
readme = "README.md"
packages = [{include = "karaoke_prep"}]
packages = [{ include = "karaoke_prep" }]
homepage = "https://github.com/karaokenerds/karaoke-prep"
repository = "https://github.com/karaokenerds/karaoke-prep"
documentation = "https://github.com/karaokenerds/karaoke-prep/blob/main/README.md"
[tool.poetry.dependencies]
python = ">=3.9,<3.13"
python = ">=3.10,<3.13"
torch = ">=2.3,<2.5"
requests = ">=2"
beautifulsoup4 = ">=4"
yt-dlp = "*"
@@ -23,11 +24,18 @@ google-api-python-client = "*"
google-auth = "*"
google-auth-oauthlib = "*"
google-auth-httplib2 = "*"
audio-separator = { version = ">=0.13", optional = true, extras = ["silicon"] }
pyperclip = "^1.8.2"
[tool.poetry.extras]
silicon = ["audio-separator"]
pyperclip = ">=1.8"
thefuzz = ">=0.22"
numpy = "^1"
audio-separator = { version = ">=0.21.0", extras = ["cpu"] }
lyrics-converter = ">=0.2.1"
lyrics-transcriber = ">=0.18"
kbputils = "^0.0.16"
karaoke-lyrics-processor = ">=0.4.0"
attrs = ">=24.2.0"
cattrs = ">=24.1.2"
toml = ">=0.10"
argparse = ">=1.4.0"
[tool.poetry.group.dev.dependencies]
black = ">=23"