Compare commits

...
57 Commits
Author SHA1 Message Date
Andrew Beveridge 17be398a0f Reordered remuxing to leave no unnecessarily large files whilst retaining pure PCM audio in all output MP4 files 2025-01-14 21:27:40 -05:00
Andrew Beveridge ee9958bfe9 Improved text rendering size calculation to make text fill more of the region bounding box areas 2024-12-28 04:08:56 -05:00
Andrew Beveridge fc5eabb588 Added gradients, text transforms, and better font size calculation 2024-12-28 03:34:31 -05:00
Andrew Beveridge 4883a93603 Added support for configurable gradients and text transforms 2024-12-28 03:09:00 -05:00
Andrew Beveridge 5d8b697c61 Made styles configurable by JSON config file with combined config for prep and CDG in finalise, etc. 2024-12-28 02:30:09 -05:00
Andrew Beveridge 94ea24bfea Moved lyrics processing into LyricsTranscriber, added MKV output file with lossless audio, used that for upload to YouTube to improve audio quality 2024-12-27 16:00:12 -05:00
Andrew Beveridge 42fc646954 Fixed broken return in separation, transcriber dependency 2024-12-27 01:55:16 -05:00
Andrew Beveridge bd6db70bcf Updated dependencies, modified prep to use latest version of transcriber and rely on lyrics outputs from that rather than duplicating genius fetch logic etc. 2024-12-27 01:29:52 -05:00
Andrew Beveridge 242c1e03ac Improved cdg maker to have configurable styles 2024-12-26 00:03:50 -05:00
Andrew Beveridge ade7c40af7 Updated to check for fonts in the fonts dir 2024-12-25 00:31:03 -05:00
Andrew Beveridge 162faa9189 Updated cdg generation to use parameters 2024-12-25 00:05:24 -05:00
Andrew Beveridge 7ad1ae8305 Updated to newer karaoke-lyrics-processor with clipboard bug fix 2024-12-24 03:29:44 -05:00
Andrew Beveridge 7852619403 Renamed local output file to Original 2024-12-24 02:17:33 -05:00
Andrew Beveridge ddb70a9c31 Updated to include fixed region and extra text logic, additional font, test for intro and end screen rendering 2024-12-24 00:34:28 -05:00
Andrew Beveridge f9336590fa Updated artist title rendering with region logic 2024-12-23 22:40:37 -05:00
Andrew Beveridge 4151650a90 Fixed combined backing instrumental normalization, added anti-duplicate effort existing file checks 2024-12-07 23:56:23 -05:00
Andrew Beveridge 2c1e9f38f7 Bumped version for fixed release 2024-12-07 16:20:09 -05:00
Andrew Beveridge 164b0309ab Fixed youtube and gmail token scopes 2024-12-07 16:19:55 -05:00
Andrew Beveridge ca080e53a0 Added gmail draft 2024-12-07 02:23:20 -05:00
Andrew Beveridge 7776365c80 Added working re-combination of instrumental+bv 2024-12-07 02:03:48 -05:00
Andrew Beveridge ef3a2dfbe5 Restructured to output stems in subfolder and separate backing vocals properly 2024-12-04 19:09:22 -05:00
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
45 changed files with 8666 additions and 1832 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
+1
View File
@@ -6,6 +6,7 @@
audio/
lyrics/
karaoke/
tests/outputs
# Byte-compiled / optimized / DLL files
+5
View File
@@ -23,6 +23,10 @@ This was created to make it easier for me to prepare the source audio, lyrics an
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`
@@ -56,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",
]
+1919
View File
File diff suppressed because it is too large. Load diff
+151
View File
@@ -0,0 +1,151 @@
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="#000")
active_stroke: RGBColor = field(converter=to_rgbcolor, default="#000")
inactive_fill: RGBColor = field(converter=to_rgbcolor, default="#000")
inactive_stroke: RGBColor = field(converter=to_rgbcolor, default="#000")
@define
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
outro_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="#ffffff")
title_screen_transition: str = "centertexttoplogobottomtext"
title_artist_gap: int = 30
intro_duration_seconds: float = 5.0
first_syllable_buffer_seconds: float = 3.0
outro_transition: str = "centertexttoplogobottomtext"
outro_text_line1: str = "THANK YOU FOR SINGING!"
outro_text_line2: str = "nomadkaraoke.com"
outro_line1_line2_gap: int = 30
outro_line1_color: RGBColor = field(converter=to_rgbcolor, default="#ffffff")
outro_line2_color: RGBColor = field(converter=to_rgbcolor, default="#ffffff")
__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.
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

+476
View File
@@ -0,0 +1,476 @@
#!/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
from cdgmaker.render import get_wrapped_text
import os
import json
# Keep only the truly constant values that aren't style-related
CDG_VISIBLE_WIDTH = 280
# Create a logger specific to this module
logger = logging.getLogger(__name__)
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,
line_tile_height,
instrumental_font_color,
instrumental_background,
instrumental_transition,
instrumental_gap_threshold,
instrumental_text,
):
instrumentals = []
for i in range(len(lyrics_data) - 1):
current_end = lyrics_data[i]["timestamp"]
next_start = lyrics_data[i + 1]["timestamp"]
gap = next_start - current_end
if gap >= instrumental_gap_threshold:
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"{instrumental_text}\n{instrumental_duration} seconds\n",
"text_align": "center",
"text_placement": "bottom middle",
"line_tile_height": 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,
cdg_styles,
):
"""
Generate a TOML configuration file for CDG creation.
Args:
cdg_styles (dict): Must contain all style-related parameters:
- title_color
- artist_color
- background_color
- border_color
- font_path
- font_size
- stroke_width
- stroke_style
- active_fill
- active_stroke
- inactive_fill
- inactive_stroke
- title_screen_background
- instrumental_background
- instrumental_transition
- instrumental_font_color
- title_screen_transition
- row
- line_tile_height
- lines_per_page
- clear_mode
- sync_offset
- instrumental_gap_threshold
- instrumental_text
- lead_in_threshold
- lead_in_symbols
- lead_in_duration
- lead_in_total
- title_artist_gap
- intro_duration_seconds
- first_syllable_buffer_seconds
- outro_background
- outro_transition
- outro_text_line1
- outro_text_line2
- outro_line1_color
- outro_line2_color
- outro_line1_line2_gap
"""
# Validate required style parameters
required_styles = {
"title_color",
"artist_color",
"background_color",
"border_color",
"font_path",
"font_size",
"stroke_width",
"stroke_style",
"active_fill",
"active_stroke",
"inactive_fill",
"inactive_stroke",
"title_screen_background",
"instrumental_background",
"instrumental_transition",
"instrumental_font_color",
"title_screen_transition",
"row",
"line_tile_height",
"lines_per_page",
"clear_mode",
"sync_offset",
"instrumental_gap_threshold",
"instrumental_text",
"lead_in_threshold",
"lead_in_symbols",
"lead_in_duration",
"lead_in_total",
"title_artist_gap",
"intro_duration_seconds",
"first_syllable_buffer_seconds",
"outro_background",
"outro_transition",
"outro_text_line1",
"outro_text_line2",
"outro_line1_color",
"outro_line2_color",
"outro_line1_line2_gap",
}
missing_styles = required_styles - set(cdg_styles.keys())
if missing_styles:
raise ValueError(f"Missing required style parameters: {', '.join(missing_styles)}")
try:
lyrics_data = parse_lrc(lrc_file)
except ValueError as e:
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"] >= cdg_styles["lead_in_threshold"]:
lead_in_start = lyric["timestamp"] - cdg_styles["lead_in_total"]
logger.debug(f"Adding lead-in before lyric {i} at timestamp {lead_in_start}")
for j, symbol in enumerate(cdg_styles["lead_in_symbols"]):
sync_time = lead_in_start + j * cdg_styles["lead_in_duration"]
sync_times.append(sync_time)
formatted_lyrics.append(symbol)
logger.debug(f" Added lead-in symbol {j+1}: '{symbol}' at {sync_time}")
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,
line_tile_height=cdg_styles["line_tile_height"],
instrumental_font_color=cdg_styles["instrumental_font_color"],
instrumental_background=cdg_styles["instrumental_background"],
instrumental_transition=cdg_styles["instrumental_transition"],
instrumental_gap_threshold=cdg_styles["instrumental_gap_threshold"],
instrumental_text=cdg_styles["instrumental_text"],
)
formatted_lyrics = format_lyrics(
formatted_lyrics, instrumentals, sync_times, font_path=cdg_styles["font_path"], font_size=cdg_styles["font_size"]
)
toml_data = {
"title": title,
"artist": artist,
"file": audio_file,
"outname": Path(lrc_file).stem,
"clear_mode": cdg_styles["clear_mode"],
"sync_offset": cdg_styles["sync_offset"],
"background": cdg_styles["background_color"],
"border": cdg_styles["border_color"],
"font": cdg_styles["font_path"],
"font_size": cdg_styles["font_size"],
"stroke_width": cdg_styles["stroke_width"],
"stroke_style": cdg_styles["stroke_style"],
"singers": [
{
"active_fill": cdg_styles["active_fill"],
"active_stroke": cdg_styles["active_stroke"],
"inactive_fill": cdg_styles["inactive_fill"],
"inactive_stroke": cdg_styles["inactive_stroke"],
}
],
"lyrics": [
{
"singer": 1,
"sync": sync_times,
"row": cdg_styles["row"],
"line_tile_height": cdg_styles["line_tile_height"],
"lines_per_page": cdg_styles["lines_per_page"],
"text": formatted_lyrics,
}
],
"title_color": cdg_styles["title_color"],
"artist_color": cdg_styles["artist_color"],
"title_screen_background": cdg_styles["title_screen_background"],
"title_screen_transition": cdg_styles["title_screen_transition"],
"instrumentals": instrumentals,
"intro_duration_seconds": cdg_styles["intro_duration_seconds"],
"first_syllable_buffer_seconds": cdg_styles["first_syllable_buffer_seconds"],
"outro_background": cdg_styles["outro_background"],
"outro_transition": cdg_styles["outro_transition"],
"outro_text_line1": cdg_styles["outro_text_line1"],
"outro_text_line2": cdg_styles["outro_text_line2"],
"outro_line1_color": cdg_styles["outro_line1_color"],
"outro_line2_color": cdg_styles["outro_line2_color"],
"outro_line1_line2_gap": cdg_styles["outro_line1_line2_gap"],
}
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(font_path=None, font_size=18):
try:
return ImageFont.truetype(font_path, font_size) if font_path else ImageFont.load_default()
except IOError:
logger.warning(f"Font file {font_path} 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, font_path=None, font_size=18):
formatted_lyrics = []
font = get_font(font_path, font_size)
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,
cdg_styles,
):
"""
Generate a CDG file from an LRC file and audio file.
Args:
lrc_file (str): Path to the LRC file
audio_file (str): Path to the audio file
title (str): Title of the song
artist (str): Artist of the song
cdg_styles (dict): Dictionary containing all style and layout parameters
"""
# Check if font_path is just a filename and look for it in the package's fonts directory
if cdg_styles["font_path"] and not os.path.isabs(cdg_styles["font_path"]) and not os.path.exists(cdg_styles["font_path"]):
package_font_path = os.path.join(os.path.dirname(__file__), "fonts", cdg_styles["font_path"])
if os.path.exists(package_font_path):
cdg_styles["font_path"] = package_font_path
logger.debug(f"Found font in package fonts directory: {cdg_styles['font_path']}")
else:
logger.warning(f"Font file {cdg_styles['font_path']} not found in package fonts directory, will use default font")
cdg_styles["font_path"] = None
# Set up logging for this function if it hasn't been configured
if not logger.handlers:
handler = logging.StreamHandler()
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
toml_file = f"{Path(lrc_file).stem}.toml"
generate_toml(
lrc_file,
audio_file,
title,
artist,
toml_file,
cdg_styles,
)
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.
"""
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("--cdg-styles-json", required=True, help="Path to JSON file containing CDG style configuration")
args = parser.parse_args()
try:
with open(args.cdg_styles_json, "r") as f:
cdg_styles = json.loads(f.read())
except FileNotFoundError:
logger.error(f"Style configuration file not found: {args.cdg_styles_json}")
sys.exit(1)
except json.JSONDecodeError as e:
logger.error(f"Invalid JSON in style configuration file: {e}")
sys.exit(1)
try:
generate_cdg(
args.lrc_file,
args.audio_file,
args.title,
args.artist,
cdg_styles,
)
except ValueError as e:
logger.error(f"Invalid style configuration: {e}")
sys.exit(1)
if __name__ == "__main__":
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: 36 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: 35 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: 14 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",
]
+379 -76
View File
@@ -8,11 +8,18 @@ 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
from google.oauth2.credentials import Credentials
import base64
from email.mime.text import MIMEText
class KaraokeFinalise:
@@ -23,13 +30,19 @@ 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,
email_template_file=None,
cdg_styles=None,
):
self.logger = logging.getLogger(__name__)
self.logger.setLevel(log_level)
@@ -64,11 +77,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
@@ -77,23 +94,38 @@ 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",
"karaoke_mp4": " (Karaoke).mp4",
"final_karaoke_mp4": " (Final Karaoke).mp4",
"final_karaoke_zip": " (Final Karaoke).zip",
"final_karaoke_720p_mp4": " (Final Karaoke 720p).mp4",
"final_karaoke_cdg_zip": " (Final Karaoke CDG).zip",
"final_karaoke_txt_zip": " (Final Karaoke TXT).zip",
}
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
self.email_template_file = email_template_file
self.gmail_service = None
self.cdg_styles = cdg_styles
def check_input_files_exist(self, base_name, with_vocals_file, instrumental_audio_file):
self.logger.info(f"Checking required input files exist...")
@@ -101,33 +133,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 {
"karaoke_mov": f"{base_name}{self.suffixes['karaoke_mov']}",
output_files = {
"karaoke_mp4": f"{base_name}{self.suffixes['karaoke_mp4']}",
"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:
@@ -198,6 +258,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}")
@@ -213,11 +275,11 @@ class KaraokeFinalise:
def authenticate_youtube(self):
"""Authenticate and return a YouTube service object."""
credentials = None
pickle_file = "/tmp/karaoke-finalise-token.pickle"
youtube_token_file = "/tmp/karaoke-finalise-youtube-token.pickle"
# Token file stores the user's access and refresh tokens.
if os.path.exists(pickle_file):
with open(pickle_file, "rb") as token:
# Token file stores the user's access and refresh tokens for YouTube.
if os.path.exists(youtube_token_file):
with open(youtube_token_file, "rb") as token:
credentials = pickle.load(token)
# If there are no valid credentials, let the user log in.
@@ -231,7 +293,7 @@ class KaraokeFinalise:
credentials = flow.run_local_server(port=0) # This will open a browser for authentication
# Save the credentials for the next run
with open(pickle_file, "wb") as token:
with open(youtube_token_file, "wb") as token:
pickle.dump(credentials, token)
return build("youtube", "v3", credentials=credentials)
@@ -325,11 +387,11 @@ class KaraokeFinalise:
"status": {"privacyStatus": "public"},
}
# Use MediaFileUpload to handle the video file
# Use MediaFileUpload to handle the video file - now using the lossless MKV
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...")
self.logger.info(f"Uploading final lossless MKV to YouTube...")
request = youtube.videos().insert(part="snippet,status", body=body, media_body=media_file)
response = request.execute()
@@ -372,46 +434,67 @@ 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 ending in (With Vocals).mov/.mp4 or (Karaoke).mov/.mp4")
with_vocals_files = [f for f in os.listdir(".") if self.suffixes["with_vocals_mov"] in f]
if not with_vocals_files:
karaoke_files = [f for f in os.listdir(".") if self.suffixes["karaoke_mov"] in f]
if karaoke_files:
for file in karaoke_files:
new_file = file.replace(self.suffixes["karaoke_mov"], self.suffixes["with_vocals_mov"])
# First try to find a properly named with vocals file in either format
with_vocals_files = [
f for f in os.listdir(".") if f.endswith(self.suffixes["with_vocals_mov"]) or f.endswith(self.suffixes["with_vocals_mp4"])
]
self.prompt_user_confirmation_or_raise_exception(
f"Found '{file}' but no '(With Vocals)', rename to {new_file} for vocal input?",
"Unable to proceed without With Vocals file or user confirmation of rename.",
allow_empty=True,
)
if with_vocals_files:
self.logger.info(f"Found with vocals file: {with_vocals_files[0]}")
return with_vocals_files[0]
os.rename(file, new_file)
self.logger.info(f"Renamed '{file}' to '{new_file}'")
return new_file
else:
raise Exception("No suitable files found for processing.")
else:
return with_vocals_files[0] # Assuming only one such file is expected
# If no with vocals file found, look for potentially misnamed karaoke files
karaoke_files = [f for f in os.listdir(".") if f.endswith(self.suffixes["karaoke_mp4"]) or f.endswith(" (Karaoke).mov")]
if karaoke_files:
for file in karaoke_files:
# Determine the correct extension to keep when renaming
current_ext = ".mov" if file.endswith(".mov") else ".mp4"
base_without_suffix = file.replace(" (Karaoke)" + current_ext, "")
new_file = (
f"{base_without_suffix}{self.suffixes['with_vocals_mov']}"
if current_ext == ".mov"
else f"{base_without_suffix}{self.suffixes['with_vocals_mp4']}"
)
self.prompt_user_confirmation_or_raise_exception(
f"Found '{file}' but no '(With Vocals)', rename to {new_file} for vocal input?",
"Unable to proceed without With Vocals file or user confirmation of rename.",
allow_empty=True,
)
os.rename(file, new_file)
self.logger.info(f"Renamed '{file}' to '{new_file}'")
return new_file
raise Exception("No suitable files found for processing.")
def choose_instrumental_audio_file(self, base_name):
self.logger.info(f"Choosing instrumental audio file to use as karaoke audio...")
search_string = " (Instrumental "
search_string = " (Instrumental"
self.logger.info(f"Searching for files in current directory containing {search_string}")
all_instrumental_files = [f for f in os.listdir(".") if search_string in f]
flac_files = set(f.rsplit(".", 1)[0] for f in all_instrumental_files if f.endswith(".flac"))
mp3_files = set(f.rsplit(".", 1)[0] for f in all_instrumental_files if f.endswith(".mp3"))
wav_files = set(f.rsplit(".", 1)[0] for f in all_instrumental_files if f.endswith(".wav"))
self.logger.debug(f"FLAC files found: {flac_files}")
self.logger.debug(f"MP3 files found: {mp3_files}")
self.logger.debug(f"WAV files found: {wav_files}")
# Filter out MP3 files if their FLAC counterpart exists
# Filter out MP3 files if their FLAC or WAV counterpart exists
# Filter out WAV files if their FLAC counterpart exists
filtered_files = [
f for f in all_instrumental_files if f.endswith(".flac") or (f.endswith(".mp3") and f.rsplit(".", 1)[0] not in flac_files)
f
for f in all_instrumental_files
if f.endswith(".flac")
or (f.endswith(".wav") and f.rsplit(".", 1)[0] not in flac_files)
or (f.endswith(".mp3") and f.rsplit(".", 1)[0] not in flac_files and f.rsplit(".", 1)[0] not in wav_files)
]
self.logger.debug(f"Filtered instrumental files: {filtered_files}")
@@ -447,7 +530,13 @@ class KaraokeFinalise:
def get_names_from_withvocals(self, with_vocals_file):
self.logger.info(f"Getting artist and title from {with_vocals_file}")
base_name = with_vocals_file.replace(self.suffixes["with_vocals_mov"], "")
# Remove both possible suffixes and their extensions
base_name = with_vocals_file
for suffix in [self.suffixes["with_vocals_mov"], self.suffixes["with_vocals_mp4"]]:
if suffix in base_name:
base_name = base_name.replace(suffix, "")
break
artist, title = base_name.split(" - ", 1)
return base_name, artist, title
@@ -462,64 +551,161 @@ class KaraokeFinalise:
def remux_and_encode_output_video_files(self, with_vocals_file, input_files, output_files):
self.logger.info(f"Remuxing and encoding output video files...")
# Check if output files already exist, if so, ask user to overwrite or skip
if os.path.isfile(output_files["karaoke_mov"]) and os.path.isfile(output_files["final_karaoke_mp4"]):
# Check if output files already exist
if os.path.isfile(output_files["karaoke_mp4"]) and os.path.isfile(output_files["final_karaoke_mp4"]):
if not self.prompt_user_bool(
f"Found existing Final Karaoke output file: {output_files['final_karaoke_mp4']}. Overwrite (y) or skip (n)?",
f"Found existing Final Karaoke output files. Overwrite (y) or skip (n)?",
):
self.logger.info(f"Skipping Karaoke MOV remux and Final MP4 render, existing files will be used.")
self.logger.info(f"Skipping Karaoke MP4 remux and Final video renders, existing files will be used.")
return
# Remux the synced video with the instrumental audio to produce an instrumental karaoke MOV file
remux_ffmpeg_command = f'{self.ffmpeg_base_command} -an -i "{with_vocals_file}" -vn -i "{input_files["instrumental_audio"]}" -c:v copy -c:a aac "{output_files["karaoke_mov"]}"'
# 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 pcm_s16le "{output_files["with_vocals_mp4"]}"'
)
self.execute_command(with_vocals_mp4_command, "Converting with vocals video to MP4")
# 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)
# Remux the synced video with the instrumental audio to produce an instrumental karaoke MP4 file
remux_ffmpeg_command = f'{self.ffmpeg_base_command} -an -i "{output_files["with_vocals_mp4"]}" -vn -i "{input_files["instrumental_audio"]}" -c:v copy -c:a pcm_s16le "{output_files["karaoke_mp4"]}"'
self.execute_command(remux_ffmpeg_command, "Remuxing video with instrumental audio")
# 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"]))
karaoke_mp4_file = shlex.quote(os.path.abspath(output_files["karaoke_mp4"]))
output_final_mp4_file = shlex.quote(output_files["final_karaoke_mp4"])
# Use ffmpeg concat filter to join the title video and the karaoke video to produce the final MP4
join_ffmpeg_command = f'{self.ffmpeg_base_command} -i {title_mov_file} -i {karaoke_mov_file} -filter_complex "[0:v:0][0:a:0][1:v:0][1:a:0]concat=n=2:v=1:a=1[outv][outa]" -map "[outv]" -map "[outa]" -c:v libx264 -c:a aac_at -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")
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]"'
# Prompt user to check final MP4 file before proceeding
# Check if end_mov file exists and include it in the concat command
if "end_mov" in input_files and os.path.isfile(input_files["end_mov"]):
self.logger.info(f"Found end_mov file: {input_files['end_mov']}, including in final MP4")
end_mov_file = shlex.quote(os.path.abspath(input_files["end_mov"]))
env_mov_input = f"-i {end_mov_file}"
ffmpeg_filter = '-filter_complex "[0:v:0][0:a:0][1:v:0][1:a:0][2:v:0][2:a:0]concat=n=3:v=1:a=1[outv][outa]"'
# Create the final MP4 with PCM audio
join_ffmpeg_command = f'{self.ffmpeg_base_command} -i {title_mov_file} -i {karaoke_mp4_file} {env_mov_input} {ffmpeg_filter} -map "[outv]" -map "[outa]" -c:v libx264 -c:a pcm_s16le "{output_files["final_karaoke_mp4"]}"'
self.execute_command(join_ffmpeg_command, "Creating MP4 version with PCM audio")
# Prompt user to check final video file before proceeding
self.prompt_user_confirmation_or_raise_exception(
f"Final MP4 file created: {output_files['final_karaoke_mp4']}, please check it! Proceed?",
"Refusing to proceed without user confirmation they're happy with the Final MP4.",
f"Final video file created: {output_files['final_karaoke_mp4']}, please check it! Proceed?",
"Refusing to proceed without user confirmation they're happy with the Final video.",
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']}")
if self.cdg_styles is None:
raise ValueError("CDG styles configuration is required when enable_cdg is True")
self.logger.info(f"CDG ZIP file created: {output_files['final_karaoke_zip']}")
generate_cdg(
input_files["karaoke_lrc"],
input_files["instrumental_audio"],
title,
artist,
self.cdg_styles,
)
# 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?",
@@ -537,15 +723,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}")
@@ -553,18 +742,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):
@@ -596,6 +791,31 @@ 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...")
@@ -624,6 +844,71 @@ class KaraokeFinalise:
self.move_files_to_brand_code_folder(self.brand_code, artist, title, output_files)
self.generate_organised_folder_sharing_link()
def authenticate_gmail(self):
"""Authenticate and return a Gmail service object."""
creds = None
gmail_token_file = "/tmp/karaoke-finalise-gmail-token.pickle"
if os.path.exists(gmail_token_file):
with open(gmail_token_file, "rb") as token:
creds = pickle.load(token)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
self.youtube_client_secrets_file, ["https://www.googleapis.com/auth/gmail.compose"]
)
creds = flow.run_local_server(port=0)
with open(gmail_token_file, "wb") as token:
pickle.dump(creds, token)
return build("gmail", "v1", credentials=creds)
def draft_completion_email(self, artist, title, youtube_url, dropbox_url):
if not self.email_template_file:
self.logger.info("Email template file not provided, skipping email draft creation.")
return
with open(self.email_template_file, "r") as f:
template = f.read()
email_body = template.format(youtube_url=youtube_url, dropbox_url=dropbox_url)
subject = f"{self.brand_code}: {artist} - {title}"
if self.dry_run:
self.logger.info(f"DRY RUN: Would create email draft with subject: {subject}")
self.logger.info(f"DRY RUN: Email body:\n{email_body}")
else:
if not self.gmail_service:
self.gmail_service = self.authenticate_gmail()
message = MIMEText(email_body)
message["subject"] = subject
raw_message = base64.urlsafe_b64encode(message.as_bytes()).decode("utf-8")
draft = self.gmail_service.users().drafts().create(userId="me", body={"message": {"raw": raw_message}}).execute()
self.logger.info(f"Email draft created with ID: {draft['id']}")
def test_email_template(self):
if not self.email_template_file:
self.logger.error("Email template file not provided. Use --email_template_file to specify the file path.")
return
fake_artist = "Test Artist"
fake_title = "Test Song"
fake_youtube_url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
fake_dropbox_url = "https://www.dropbox.com/sh/fake/folder/link"
fake_brand_code = "TEST-0001"
self.brand_code = fake_brand_code
self.draft_completion_email(fake_artist, fake_title, fake_youtube_url, fake_dropbox_url)
self.logger.info("Email template test complete. Check your Gmail drafts for the test email.")
def process(self):
if self.dry_run:
self.logger.warning("Dry run enabled. No actions will be performed.")
@@ -631,7 +916,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)
@@ -639,19 +924,37 @@ 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_instrumental": output_files["karaoke_mov"],
"video_with_vocals": output_files["with_vocals_mp4"],
"video_with_instrumental": output_files["karaoke_mp4"],
"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"]
if self.email_template_file:
self.draft_completion_email(artist, title, result["youtube_url"], result["brand_code_dir_sharing_link"])
return result
File diff suppressed because it is too large. Load diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
+89 -10
View File
@@ -4,6 +4,7 @@ import logging
import pkg_resources
import os
import sys
import json
from karaoke_prep.karaoke_finalise import KaraokeFinalise
@@ -16,7 +17,7 @@ def main():
parser = argparse.ArgumentParser(
description="Render, remux and join intermediate files to create final karaoke video, as the third stage after using karaoke-prep. Processes all (Karaoke).mov files in current directory.",
formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=54),
formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=62),
)
package_version = pkg_resources.get_distribution("karaoke-prep").version
@@ -47,6 +48,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 +72,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 +102,30 @@ 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",
)
parser.add_argument(
"--email_template_file",
default=None,
help="Optional: File path to email template for drafting completion email. Example: --email_template_file='/path/to/email_template.txt'",
)
parser.add_argument(
"--test_email_template",
action="store_true",
help="Optional: Test the email template functionality with fake data. Example: --test_email_template",
)
parser.add_argument(
"--style_params_json",
default=None,
help="Optional: Path to JSON file containing CDG style configuration. Required if --enable_cdg is used. Example: --style_params_json='/path/to/cdg_styles.json'",
)
args = parser.parse_args()
log_level = getattr(logging, args.log_level.upper())
@@ -90,38 +133,74 @@ def main():
logger.info(f"KaraokeFinalise CLI beginning initialisation...")
# Load CDG styles if CDG generation is enabled
cdg_styles = None
if args.enable_cdg:
if not args.style_params_json:
logger.error("CDG styles JSON file path (--style_params_json) is required when --enable_cdg is used")
sys.exit(1)
try:
with open(args.style_params_json, "r") as f:
style_params = json.loads(f.read())
cdg_styles = style_params["cdg"]
except FileNotFoundError:
logger.error(f"CDG styles configuration file not found: {args.style_params_json}")
sys.exit(1)
except json.JSONDecodeError as e:
logger.error(f"Invalid JSON in CDG styles configuration file: {e}")
sys.exit(1)
kfinalise = KaraokeFinalise(
log_formatter=log_formatter,
log_level=log_level,
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,
email_template_file=args.email_template_file,
cdg_styles=cdg_styles,
)
try:
track = kfinalise.process()
except Exception as e:
logger.error(f"An error occurred during finalisation, see stack trace below: {str(e)}")
raise e
if args.test_email_template:
logger.info("Testing email template functionality...")
kfinalise.test_email_template()
else:
try:
track = kfinalise.process()
except Exception as e:
logger.error(f"An error occurred during finalisation, see stack trace below: {str(e)}")
raise e
logger.info(f"Karaoke finalisation processing complete! Output files:")
logger.info(f"")
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()
+189 -88
View File
@@ -4,6 +4,8 @@ import logging
import pkg_resources
import tempfile
import os
import json
import sys
from karaoke_prep import KaraokePrep
@@ -29,6 +31,7 @@ def main():
formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=54),
)
# Basic information
parser.add_argument(
"args",
nargs="*",
@@ -38,33 +41,73 @@ def main():
package_version = pkg_resources.get_distribution("karaoke-prep").version
parser.add_argument("-v", "--version", action="version", version=f"%(prog)s {package_version}")
# Logging & Debugging
parser.add_argument(
"--log_level",
default="info",
help="Optional: logging level, e.g. info, debug, warning (default: %(default)s). Example: --log_level=debug",
)
parser.add_argument(
"--filename_pattern",
help="Required if processing a folder: Python regex pattern to extract track names from filenames. Must contain a named group 'title'. Example: --filename_pattern='(?P<index>\\d+) - (?P<title>.+).mp3'",
)
parser.add_argument(
"--dry_run",
action="store_true",
help="Optional: perform a dry run without making any changes (default: %(default)s). Example: --dry_run=true",
)
parser.add_argument(
"--model_names",
"--render_bounding_boxes",
action="store_true",
help="Optional: render bounding boxes around text regions for debugging (default: %(default)s). Example: --render_bounding_boxes",
)
# Input/Output Configuration
parser.add_argument(
"--filename_pattern",
help="Required if processing a folder: Python regex pattern to extract track names from filenames. Must contain a named group 'title'. Example: --filename_pattern='(?P<index>\\d+) - (?P<title>.+).mp3'",
)
parser.add_argument(
"--output_dir",
default=".",
help="Optional: directory to write output files (default: <current dir>). Example: --output_dir=/app/karaoke",
)
parser.add_argument(
"--no_track_subfolders",
action="store_false",
help="Optional: do NOT create a named subfolder for each track. Example: --no_track_subfolders",
)
parser.add_argument(
"--lossless_output_format",
default="FLAC",
help="Optional: lossless output format for separated audio (default: FLAC). Example: --lossless_output_format=WAV",
)
parser.add_argument(
"--output_png",
type=lambda x: (str(x).lower() == "true"),
default=True,
help="Optional: output PNG format for title and end images (default: %(default)s). Example: --output_png=False",
)
parser.add_argument(
"--output_jpg",
type=lambda x: (str(x).lower() == "true"),
default=True,
help="Optional: output JPG format for title and end images (default: %(default)s). Example: --output_jpg=False",
)
# Audio Processing Configuration
parser.add_argument(
"--clean_instrumental_model",
default="model_bs_roformer_ep_317_sdr_12.9755.ckpt",
help="Optional: Model for clean instrumental separation (default: %(default)s).",
)
parser.add_argument(
"--backing_vocals_models",
nargs="+",
default=[
"model_mel_band_roformer_ep_3005_sdr_11.4360.ckpt",
"UVR_MDXNET_KARA_2.onnx",
"2_HP-UVR.pth",
"MDX23C-8KFFT-InstVoc_HQ_2.ckpt",
],
help="Optional: list of model names to be used for separation (default: %(default)s). Example: --model_names UVR_MDXNET_KARA_2.onnx UVR-MDX-NET-Inst_HQ_4.onnx",
default=["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"],
help="Optional: List of models for backing vocals separation (default: %(default)s).",
)
parser.add_argument(
"--other_stems_models",
nargs="+",
default=["htdemucs_6s.yaml"],
help="Optional: List of models for other stems separation (default: %(default)s).",
)
default_model_dir_unix = "/tmp/audio-separator-models/"
@@ -79,44 +122,16 @@ def main():
default=default_model_dir,
help="Optional: model files directory (default: %(default)s). Example: --model_file_dir=/app/models",
)
parser.add_argument(
"--output_dir",
default=".",
help="Optional: directory to write output files (default: <current dir>). Example: --output_dir=/app/karaoke",
"--existing_instrumental",
help="Optional: Path to an existing instrumental audio file. If provided, audio separation will be skipped.",
)
parser.add_argument(
"--lossless_output_format",
default="FLAC",
help="Optional: lossless output format for separated audio (default: FLAC). Example: --lossless_output_format=WAV",
)
parser.add_argument(
"--lossy_output_format",
default="MP3",
help="Optional: lossy output format for separated audio (default: MP3). Example: --lossy_output_format=OGG",
)
parser.add_argument(
"--use_cuda",
action="store_true",
help="Optional: use Nvidia GPU with CUDA for separation (default: %(default)s). Example: --use_cuda=true",
)
parser.add_argument(
"--use_coreml",
action="store_true",
help="Optional: use Apple Silicon GPU with CoreML for separation (default: %(default)s). Example: --use_coreml=true",
)
parser.add_argument(
"--denoise",
type=lambda x: (str(x).lower() == "true"),
default=True,
help="Optional: enable or disable denoising during separation (default: %(default)s). Example: --denoise=False",
)
parser.add_argument(
"--normalize",
type=lambda x: (str(x).lower() == "true"),
@@ -124,39 +139,42 @@ def main():
help="Optional: enable or disable normalization during separation (default: %(default)s). Example: --normalize=False",
)
# Hardware Acceleration
parser.add_argument(
"--no_track_subfolders",
action="store_false",
help="Optional: do NOT create a named subfolder for each track. Example: --no_track_subfolders",
"--use_cuda",
action="store_true",
help="Optional: use Nvidia GPU with CUDA for separation (default: %(default)s). Example: --use_cuda=true",
)
parser.add_argument(
"--use_coreml",
action="store_true",
help="Optional: use Apple Silicon GPU with CoreML for separation (default: %(default)s). Example: --use_coreml=true",
)
# Lyrics Configuration
parser.add_argument(
"--intro_background_color",
default="#000000",
help="Optional: Background color for intro video (default: black). Example: --intro_background_color=#123456",
"--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",
)
parser.add_argument(
"--skip_transcription",
action="store_true",
help="Optional: Skip audio transcription but still attempt to fetch lyrics from Spotify/Genius. Example: --skip_transcription",
)
# Style Configuration
parser.add_argument(
"--intro_background_image",
help="Optional: Path to background image for intro video. Overrides background color if provided. Example: --intro_background_image=path/to/image.jpg",
)
parser.add_argument(
"--intro_font",
default="Montserrat-Bold.ttf",
help="Optional: Font file for intro video (default: Montserrat-Bold.ttf). Example: --intro_font=AvenirNext-Bold.ttf",
)
parser.add_argument(
"--intro_artist_color",
default="#ffdf6b",
help="Optional: Font color for intro video artist text (default: #ffdf6b). Example: --intro_artist_color=#123456",
)
parser.add_argument(
"--intro_title_color",
default="#ffffff",
help="Optional: Font color for intro video title text (default: #ffffff). Example: --intro_title_color=#123456",
"--style_params_json",
help="Optional: Path to JSON file containing style configuration for intro/end videos. Example: --style_params_json='/path/to/style_params.json'",
)
args = parser.parse_args()
@@ -205,31 +223,93 @@ def main():
log_level = getattr(logging, args.log_level.upper())
logger.setLevel(log_level)
# Load style parameters if JSON file is provided
style_params = None
if args.style_params_json:
try:
with open(args.style_params_json, "r") as f:
style_params = json.loads(f.read())
except FileNotFoundError:
logger.error(f"Style parameters configuration file not found: {args.style_params_json}")
sys.exit(1)
except json.JSONDecodeError as e:
logger.error(f"Invalid JSON in style parameters configuration file: {e}")
sys.exit(1)
else:
# Use default values
style_params = {
"intro": {
"video_duration": 5,
"existing_image": None,
"background_color": "#000000",
"background_image": None,
"font": "Montserrat-Bold.ttf",
"artist_color": "#ffdf6b",
"title_color": "#ffffff",
"title_region": "370, 200, 3100, 480",
"artist_region": "370, 700, 3100, 480",
"extra_text": None,
"extra_text_color": "#ffffff",
"extra_text_region": "370, 1200, 3100, 480",
},
"end": {
"video_duration": 5,
"existing_image": None,
"background_color": "#000000",
"background_image": None,
"font": "Montserrat-Bold.ttf",
"artist_color": "#ffdf6b",
"title_color": "#ffffff",
"title_region": None,
"artist_region": None,
"extra_text": "THANK YOU FOR SINGING!",
"extra_text_color": "#ff7acc",
"extra_text_region": None,
},
}
if args.existing_instrumental:
args.clean_instrumental_model = None
args.backing_vocals_models = []
args.other_stems_models = []
logger.info(f"KaraokePrep beginning with input_media: {input_media} artist: {artist} and title: {title}")
kprep = KaraokePrep(
# Basic inputs
artist=artist,
title=title,
input_media=input_media,
filename_pattern=filename_pattern,
# Logging & Debugging
dry_run=args.dry_run,
log_formatter=log_formatter,
log_level=log_level,
model_names=args.model_names,
model_file_dir=args.model_file_dir,
render_bounding_boxes=args.render_bounding_boxes,
# Input/Output Configuration
filename_pattern=filename_pattern,
output_dir=args.output_dir,
create_track_subfolders=args.no_track_subfolders,
lossless_output_format=args.lossless_output_format,
lossy_output_format=args.lossy_output_format,
output_png=args.output_png,
output_jpg=args.output_jpg,
# Audio Processing Configuration
existing_instrumental=args.existing_instrumental,
clean_instrumental_model=args.clean_instrumental_model,
backing_vocals_models=args.backing_vocals_models,
other_stems_models=args.other_stems_models,
model_file_dir=args.model_file_dir,
denoise_enabled=args.denoise,
normalization_enabled=args.normalize,
# Hardware Acceleration
use_cuda=args.use_cuda,
use_coreml=args.use_coreml,
normalization_enabled=args.normalize,
denoise_enabled=args.denoise,
create_track_subfolders=args.no_track_subfolders,
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,
# Lyrics Configuration
lyrics_artist=args.lyrics_artist,
lyrics_title=args.lyrics_title,
skip_lyrics=args.skip_lyrics,
skip_transcription=args.skip_transcription,
# Style Configuration
style_params=style_params,
)
tracks = kprep.process()
@@ -245,11 +325,32 @@ def main():
logger.info(f" Lyrics: {track['lyrics']}")
logger.info(f" Processed Lyrics: {track['processed_lyrics']}")
for model_name in args.model_names:
logger.info(f" Instrumental: {track['separated_audio'][model_name]['instrumental']}")
logger.info(f" Instrumental (Lossy): {track['separated_audio'][model_name]['instrumental_lossy']}")
logger.info(f" Vocals: {track['separated_audio'][model_name]['vocals']}")
logger.info(f" Vocals (Lossy): {track['separated_audio'][model_name]['vocals_lossy']}")
logger.info(f" Separated Audio:")
# Clean Instrumental
logger.info(f" Clean Instrumental Model:")
for stem_type, file_path in track["separated_audio"]["clean_instrumental"].items():
logger.info(f" {stem_type.capitalize()}: {file_path}")
# Other Stems
logger.info(f" Other Stems Models:")
for model, stems in track["separated_audio"]["other_stems"].items():
logger.info(f" Model: {model}")
for stem_type, file_path in stems.items():
logger.info(f" {stem_type.capitalize()}: {file_path}")
# Backing Vocals
logger.info(f" Backing Vocals Models:")
for model, stems in track["separated_audio"]["backing_vocals"].items():
logger.info(f" Model: {model}")
for stem_type, file_path in stems.items():
logger.info(f" {stem_type.capitalize()}: {file_path}")
# Combined Instrumentals
logger.info(f" Combined Instrumentals:")
for model, file_path in track["separated_audio"]["combined_instrumentals"].items():
logger.info(f" Model: {model}")
logger.info(f" Combined Instrumental: {file_path}")
if __name__ == "__main__":
Generated
+2535 -1431
View File
File diff suppressed because it is too large. Load diff
+12 -4
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-prep"
version = "0.19.0"
version = "0.35.3"
description = "Prepare for karaoke video creation, by downloading audio and lyrics for a specified song or playlist from youtube and separating audio stems. After syncing, finalise the video with a title screen!"
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"
@@ -11,7 +11,8 @@ 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,9 +24,16 @@ google-api-python-client = "*"
google-auth = "*"
google-auth-oauthlib = "*"
google-auth-httplib2 = "*"
pyperclip = ">=1.8"
thefuzz = ">=0.22"
audio-separator = { version = ">=0.17", extras = ["cpu"] }
numpy = "^1"
audio-separator = { version = ">=0.21.0", extras = ["cpu"] }
lyrics-converter = ">=0.2.1"
lyrics-transcriber = ">=0.20.0"
kbputils = "^0.0.16"
attrs = ">=24.2.0"
cattrs = ">=24.1.2"
toml = ">=0.10"
argparse = ">=1.4.0"
[tool.poetry.group.dev.dependencies]
black = ">=23"
+714
View File
@@ -0,0 +1,714 @@
[
["This Is Me Smiling", "Prettier"],
["Ленинград", "Алкаш"],
["Cher", "Apples Don't Fall Far From The Tree"],
["The Hush Sound", "Don't Wake Me Up"],
["ABBA", "I Am The City"],
["ABBA", "Under Attack"],
["The Hush Sound", "A Dark Congregation"],
["The Hush Sound", "As You Cry"],
["The Hush Sound", "Boys Are Too Refined"],
["The Hush Sound", "Break the Sky"],
["The Hush Sound", "Carry Me Home"],
["The Hush Sound", "City Traffic Puzzle"],
["The Hush Sound", "Crawling Towards The Sun"],
["The Hush Sound", "Echo"],
["The Hush Sound", "Eileen"],
["The Hush Sound", "Honey"],
["The Hush Sound", "Hospital Bed Crawl"],
["The Hush Sound", "Hourglass"],
["The Hush Sound", "Hurricane"],
["The Hush Sound", "Intro"],
["The Hush Sound", "Lions Roar"],
["The Hush Sound", "Love You Much Better"],
["The Hush Sound", "Magnolia"],
["The Hush Sound", "Medicine Man"],
["The Hush Sound", "Molasses"],
["The Hush Sound", "Momentum"],
["The Hush Sound", "My Apologies"],
["The Hush Sound", "Not Your Concern"],
["The Hush Sound", "Out Through The Curtain"],
["The Hush Sound", "Sweet Tangerine"],
["The Hush Sound", "That's Okay"],
["The Hush Sound", "The Artist"],
["The Hush Sound", "The Market"],
["The Hush Sound", "Tides Change"],
["The Hush Sound", "Unsafe Safe"],
["The Hush Sound", "We Intertwined"],
["The Hush Sound", "Weeping Willow"],
["The Hush Sound", "Where We Went Wrong"],
["The Hush Sound", "Wine Red"],
["The Hush Sound", "You Are The Moon"],
["The Hush Sound", "Lighthouse"],
["Allie X", "GLAM!"],
["Lemaitre", "Rocket Girl (feat. Betty Who)"],
["Just Jack", "253"],
["Just Jack", "All Night Cinema"],
["Just Jack", "Astronaut"],
["Just Jack", "Blood"],
["Just Jack", "Disco Friends"],
["Just Jack", "Doctor Doctor"],
["Just Jack", "Embers"],
["Just Jack", "Glory Days"],
["Just Jack", "Goth In The Disco"],
["Just Jack", "Hold On"],
["Just Jack", "I Talk Too Much"],
["Just Jack", "Life Stories"],
["Just Jack", "Lo And Behold"],
["Just Jack", "Lost"],
["Just Jack", "Mourning Morning"],
["Just Jack", "No Time"],
["Just Jack", "So Wrong"],
["Just Jack", "Spectacular Failures"],
["Just Jack", "Starz in Their Eyes"],
["Just Jack", "Symphony of Sirens"],
["Just Jack", "The Day I Died"],
["Just Jack", "Writers Block"],
[
"Los Campesinos!",
"This Is How You Spell \"HAHAHA, We Destroyed the Hopes and Dreams of a Generation of Faux-Romantics\""
],
["Los Campesinos!", "2007, The Year Punk Broke (My Heart)"],
["Los Campesinos!", "And We Exhale and Roll Our Eyes in Unison"],
["Los Campesinos!", "Broken Heartbeats Sounds Like Breakbeats"],
["Los Campesinos!", "Death to Los Campesinos!"],
["Los Campesinos!", "Don't Tell Me to Do the Math(s)"],
["Los Campesinos!", "Drop It Doe Eyes"],
["Los Campesinos!", "Knee Deep At ATP"],
["Los Campesinos!", "My Year In Lists"],
["Los Campesinos!", "Sweet Dreams, Sweet Cheeks"],
["Los Campesinos!", "We Are All Accelerated Readers"],
["Los Campesinos!", "You! Me! Dancing!"],
["Mew", "156"],
["Mew", "Am I Wry? No"],
["Mew", "Behind the Drapes"],
["Mew", "Comforting Sounds"],
["Mew", "Eight Flew Over, One was Destroyed"],
["Mew", "Her Voice is Beyond Her Years"],
["Mew", "She Came Home for Christmas"],
["Mew", "She Spider"],
["Mew", "Snow Brigade"],
["Mew", "Symmetry"],
["of Montreal", "Gronlandic Edit"],
["Idlewild", "(I Am) What I Am Not"],
["Idlewild", "A Modern Way of Letting Go"],
["Idlewild", "Actually It's Darkness"],
["Idlewild", "American English"],
["Idlewild", "Century After Century"],
["Idlewild", "I Don't Have The Map"],
["Idlewild", "I Never Wanted"],
["Idlewild", "Idea Track"],
["Idlewild", "In Remote Part , Scottish Fiction"],
["Idlewild", "Let Me Sleep (Next To The Mirror)"],
["Idlewild", "Listen To What You've Got"],
["Idlewild", "Little Discourage"],
["Idlewild", "Live in a Hiding Place"],
["Idlewild", "Mistake Pageant"],
["Idlewild", "Out of Routine"],
["Idlewild", "Quiet Crown"],
["Idlewild", "Roseability"],
["Idlewild", "Rusty"],
["Idlewild", "Stay the Same"],
["Idlewild", "Tell Me Ten Words"],
["Idlewild", "The Bronze Medal"],
["Idlewild", "These Wooden Ideas"],
["Idlewild", "You Held the World in Your Arms"],
["Los Campesinos!", "A Heat Rash in the Shape of the Show Me State"],
["Los Campesinos!", "All Your Kayfabe Friends"],
["Los Campesinos!", "Coda A Burn Scar in the Shape of the Sooner State"],
["Los Campesinos!", "Documented Minor Emotional Breakdown #1"],
["Los Campesinos!", "Heart Swells:100-1"],
["Los Campesinos!", "Heart Swells / Pacific Daylight Time"],
["Los Campesinos!", "I Just Sighed, I Just Signed, Just So You Know"],
["Los Campesinos!", "I Warned You, Do Not Make an Enemy of Me"],
["Los Campesinos!", "In Medias Res"],
[
"Los Campesinos!",
"It's Never That Easy Though, Is It (Song For The Other Kurt)"
],
["Los Campesinos!", "Miserabilia"],
["Los Campesinos!", "Plan A"],
["Los Campesinos!", "Romance is Boring"],
["Los Campesinos!", "Straight in at 101"],
["Los Campesinos!", "The End Of The Asterisk"],
["Los Campesinos!", "The Sea is a Good Place to Think of the Future"],
["Los Campesinos!", "There Are Listed Buildings"],
["Los Campesinos!", "This is a Flag, There is No Wind"],
["Los Campesinos!", "Ways To Make It Through The Wall"],
["Los Campesinos!", "We Are Beautiful, We Are Doomed"],
["Los Campesinos!", "We've Got Your Back"],
["Los Campesinos!", "Who Fell Asleep In"],
["Los Campesinos!", "You'll Need Those Fingers For Crossing"],
["Miracles of Modern Science", "Bossa Supernova"],
["Miracles of Modern Science", "Eating Me Alive"],
["Miracles of Modern Science", "Friend Of The Animals"],
["Miracles of Modern Science", "I Found Space"],
["Miracles of Modern Science", "Luminol"],
["Miracles of Modern Science", "MOMS AWAY!"],
["Miracles of Modern Science", "Quantum Of Solace"],
["Miracles of Modern Science", "Secret Track"],
["Miracles of Modern Science", "Space Chopper"],
["Miracles of Modern Science", "Strangerous"],
["Miracles of Modern Science", "Tensity"],
["Miracles of Modern Science", "The Moon & Australia"],
["Nia Archives", "(Over)Thinking"],
["Nia Archives", "18 & Over"],
["Nia Archives", "Crossroads"],
["Nia Archives", "Don't Kid Urself"],
["Nia Archives", "Gud Gudbyez"],
["Nia Archives", "Headz Gone West"],
["Nia Archives", "Luv Like"],
["Nia Archives", "Part Of Me"],
["Nia Archives", "Sober Feels"],
["This Is Me Smiling", "A Better Way to Fall in Love"],
["This Is Me Smiling", "Alive in the Chase"],
["This Is Me Smiling", "Ephemera"],
["This Is Me Smiling", "Feelin' the Time Pass By"],
["This Is Me Smiling", "For When You Don't Hear It Right"],
["This Is Me Smiling", "Goodbye to Each New Day"],
["This Is Me Smiling", "Matter to Matter"],
["This Is Me Smiling", "Mixin' Up Adjectives"],
["This Is Me Smiling", "Say What You're Gonna Say"],
["This Is Me Smiling", "So Excited to Sleep"],
["This Is Me Smiling", "Up in All Directions"],
["Bug Hunter", "Dear McCracken"],
["Ken Ashcorp", "Burgz"],
["Ken Ashcorp", "Absolute Territory"],
["Ken Ashcorp", "I'm Your Slave"],
["Mew", "A Dark Design"],
["Mew", "An Envoy To The Open Fields"],
["Mew", "Apocalypso"],
["Mew", "Chinaberry Tree"],
["Mew", "Fox Cub"],
["Mew", "Louise Louisa"],
["Mew", "Saviours Of Jazz Ballet"],
["Mew", "Special"],
["Mew", "The Seething Rain Weeps For You"],
["Mew", "The Zookeeper's Boy"],
["Mew", "White Lips Kissed"],
["Mew", "Why Are You Looking Grave"],
["Get Cape. Wear Cape. Fly", "An Oak Tree"],
["Get Cape. Wear Cape. Fly", "Call Me Ishmael"],
["Get Cape. Wear Cape. Fly", "Get Cape. Wear Cape. Fly"],
["Get Cape. Wear Cape. Fly", "Glasshouses"],
["Get Cape. Wear Cape. Fly", "I-Spy"],
[
"Get Cape. Wear Cape. Fly",
"If I Had £1 For Every Stale Song Title I'd Be 30 Short Of Getting Out Of This Mess"
],
["Get Cape. Wear Cape. Fly", "Once More With Feeling"],
[
"Get Cape. Wear Cape. Fly",
"The Chronicles Of A Bohemian Teenager (Part Two)"
],
[
"Get Cape. Wear Cape. Fly",
"The Chronicles Of A Bohemian Teenager (Part One)"
],
["Get Cape. Wear Cape. Fly", "The Lighthousekeeper"],
["Get Cape. Wear Cape. Fly", "War Of The Worlds"],
["Get Cape. Wear Cape. Fly", "Whitewash Is Brainwash"],
["Hi I'm Case", "Smoke Damage (Youtube version)"],
["Ken Ashcorp", "Wear"],
["Hi I'm Case", "Smoke Damage (Spotify version)"],
["Neil Diamond", "The Look Of Love"],
["Amy Winehouse", "Valerie (Short Version)"],
["Anastacia", "I'm Outta Love (Short Version)"],
["Calum Scott", "Dancing On My Own (Short Version)"],
["Ed Sheeran", "Shivers (Short Version)"],
["Eminem", "Without Me (Short Version)"],
["Gnarls Barkley", "Crazy (Short Version)"],
["Jess Glynne", "Hold My Hand (Short Version)"],
["Kenny Loggins", "Footloose (Short Version)"],
["Kings Of Leon", "Sex on Fire (Short Version)"],
["Lady Gaga", "Born This Way (Short Version)"],
["Miley Cyrus", "Jolene (Short Version)"],
["Miley Cyrus", "Wrecking Ball (Short Version)"],
["Robbie Williams", "Angels (Short Version)"],
["Shakira", "Whenever, Wherever (Short Version)"],
["Shania Twain", "Man! I Feel Like A Woman (Short Version)"],
["Shirley Bassey", "Big Spender (Short Version)"],
["The Killers", "Mr. Brightside (Short Version)"],
["The Pussycat Dolls", "Sway (Short Version)"],
["Twenty One Pilots", "Stressed Out (Short Version)"],
["Wheatus", "Teenage Dirtbag (Short Version)"],
["Christina Stürmer", "Nie Genug"],
["James Brown", "It's a Man's World (Short Version)"],
["Jerry Lee Lewis", "Great Balls Of Fire (Short Version)"],
["Melanie Martinez", "Toxic (Short Version)"],
["Melissa Etheridge", "Bring Me Some Water (Short Version)"],
["Queen", "Crazy Little Thing Called Love (Short Version)"],
["Tina Turner", "Proud Mary (Short Version)"],
["Tina Turner", "The Best (Short Version)"],
["Tom Jones", "Help Yourself (Short Version)"],
["Tom Jones", "Sex Bomb (Short Version)"],
["Andreas Gabalier", "Hulapalu (Short Version)"],
["Christina Stürmer", "Nie Genug (Short Version)"],
["Die Draufgänger", "Cordula Grün (Short Version)"],
["Jimi Jamison", "I'm Always Here (Short Version)"],
["Jürgen Drews", "Ein Bett im Kornfeld"],
["Jürgen Drews", "Ein Bett im Kornfeld (Short Version)"],
["STS", "Kalt Und Kälter (Short Version)"],
["STS", "Kalt Und Kälter"],
["Udo Jürgens", "Aber bitte mit Sahne"],
["Udo Jürgens", "Aber bitte mit Sahne (Short Version)"],
["Bryan Adams", "Summer of '69 (Short Version)"],
["Dylan Emmet", "Lose This"],
["Loosey LaDuca", "Let Loose"],
["Against Me", "People Who Died"],
["Eleven Hundred Springs", "Thunderbird Will Do Just Fine"],
["Etherwood", "Begin By Letting Go"],
["Foy Vance", "She Burns"],
["Frightened Rabbit", "Late March Death March"],
["George Barnett", "Stone Cold Classic"],
["Get Cape. Wear Cape. Fly", "Better Things (ft. Kate Nash)"],
["Get Cape. Wear Cape. Fly", "Could've Seen It All"],
["Get Cape. Wear Cape. Fly", "Find The Time"],
["Get Cape. Wear Cape. Fly", "I Could Build You A Tower"],
["Get Cape. Wear Cape. Fly", "Keep Singing Out"],
["Get Cape. Wear Cape. Fly", "Let The Journey Begin"],
["Get Cape. Wear Cape. Fly", "Moving Forward"],
["Get Cape. Wear Cape. Fly", "Postcards From Catalunya"],
[
"Get Cape. Wear Cape. Fly",
"The Children Are (The Consumers Of) The Future"
],
["Get Cape. Wear Cape. Fly", "This Could Be All"],
["Get Cape. Wear Cape. Fly", "Waiting For The Monster To Drown"],
["Get Cape. Wear Cape. Fly", "Window Of Your Mind"],
["Get Cape. Wear Cape. Fly", "Young And Lovestruck"],
["K-Os", "The Rain"],
["Nothing But Thieves", "Pop The Balloon"],
["Robbie Basho", "Blue Crystal Fire"],
["Smino", "Lee and Lovie"],
["The Skints", "Murderer"],
["Xan Griffin", "Capricorn (ft. WOLFE)"],
["Pulp", "Cocaine Socialism"],
["Random Hand", "Play Some Ska"],
["Sexyy Red, Nicki Minaj & Tay Keith", "Pound Town 2"],
["Tori Amos", "Liquid Diamonds"],
["Frightened Rabbit", "Music Now"],
["Frightened Rabbit", "Housing (out)"],
["Frightened Rabbit", "The Modern Leper"],
["Frightened Rabbit", "A Lick Of Paint"],
["Frightened Rabbit", "The Greys"],
["Frightened Rabbit", "Head Rolls Off"],
["Frightened Rabbit", "Backyard Skulls"],
["Frightened Rabbit", "The Wreck"],
["Frightened Rabbit", "My Backwards Walk"],
["Frightened Rabbit", "Be Less Rude"],
["Frightened Rabbit", "Die Like A Rich Boy"],
["Frightened Rabbit", "State Hospital"],
["Frightened Rabbit", "Skip the Youth"],
["Frightened Rabbit", "Yes, I Would"],
["Frightened Rabbit", "Floating in the Forth"],
["Frightened Rabbit", "Nitrous Gas"],
["Frightened Rabbit", "Break"],
["Frightened Rabbit", "Things"],
["Frightened Rabbit", "Nothing Like You"],
["Frightened Rabbit", "Good Arms vs Bad Arms"],
["Frightened Rabbit", "Foot Shooter"],
["Frightened Rabbit", "The Twist"],
["Frightened Rabbit", "The Loneliness and the Scream"],
["Frightened Rabbit", "Swim Until You Can't See Land"],
["Frightened Rabbit", "An Otherwise Disappointing Life"],
["Frightened Rabbit", "Holy"],
["Frightened Rabbit", "Behave!"],
["Frightened Rabbit", "Old Old Fashioned"],
["Frightened Rabbit", "Yawns"],
["Frightened Rabbit", "I Feel Better"],
["Frightened Rabbit", "Woke Up Hurting"],
["Frightened Rabbit", "Dead Now"],
["Frightened Rabbit", "Poke"],
["Frightened Rabbit", "400 Bones"],
["Frightened Rabbit", "Little Drum"],
["Frightened Rabbit", "Fast Blood"],
["Frightened Rabbit", "Square 9"],
["Frightened Rabbit", "I Wish I Was Sober"],
["Frightened Rabbit", "The Oil Slick"],
["Frightened Rabbit", "Still Want To Be Here"],
["Frightened Rabbit", "Blood Under The Bridge"],
["Frightened Rabbit", "Death Dream"],
["Frightened Rabbit", "Wait 'Til The Morning"],
["Frightened Rabbit", "Not Miserable"],
["Frightened Rabbit", "Snake"],
["Frightened Rabbit", "Acts of Man"],
["Frightened Rabbit", "Living in Colour"],
["Frightened Rabbit", "Housing (in)"],
["Frightened Rabbit", "The Wrestle"],
["Frightened Rabbit", "Go Go Girls"],
["Frightened Rabbit", "December's Traditions"],
["Frightened Rabbit", "Lump Street"],
["Frightened Rabbit", "Keep Yourself Warm"],
["Frightened Rabbit", "The Woodpile"],
["Frightened Rabbit", "Get Out"],
["Judas Priest", "Living Bad Dreams"],
["The Spits", "Bring Me Down"],
["Voltaire", "Feathery Wings"],
["City and Colour", "The Death of Me"],
["Was (Not Was)", "Out Come the Freaks"],
["Bon Jovi", "Hallelujah"],
["Marilyn Dagenais", "Je serai là"],
["Marilyn Dagenais", "J't'écrirai pas"],
["A Lost People", "Big Booty Bitches"],
["Annika Norlin", "Failure"],
["Ascension", "Monsters"],
["Bonnie Prince Billy and Tortoise", "Pancho"],
["Brandi Carlile", "Raise Hell"],
["Britt Daniel", "Let the Distance Bring Us Together"],
["Cyn", "Drinks"],
["Dan Wriggins", "All Used Up"],
["Davey Dynamite & Absent", "Solidarity Forever"],
["Elliott Smith", "Strung Out Again"],
["Emperor X", "Sad React"],
["Girls", "Hellhole Ratrace"],
["Hercules & Love Affair", "Iris"],
["Iris DeMent", "Easy's Gettin' Harder Every Day"],
["Iris DeMent", "Let the Mystery Be"],
["Iris DeMent", "Wasteland of the Free"],
["Joanna Newsom", "Inflammatory Writ"],
["Jukebox The Ghost", "Jumpstarted"],
["Kevin Devine", "Splittin’ Up Christmas"],
["Kirin J Callinan", "Life Is Life"],
["MJ Lenderman", "TLC Cagematch"],
["Molly Hatchet", "Sailor"],
["Necro", "Pussy Is My Weakness"],
["Nevermore", "The Heart Collector"],
["New Found Glory", "Sincerely Me"],
["New Radicals", "I Hope I Didn't Just Give Away The Ending"],
["No Doubt", "Six Feet Under"],
["Petey", "Dont Tell The Boys"],
["Randy Newman", "A Wedding in Cherokee County"],
["Reverend Horton Heat", "Wiggle Stick"],
["Rough Cutt", "Dreamin' Again"],
["Steve Earle", "Christmas in Washington"],
["The Buttertones", "Baby Doll"],
["The Buttertones", "Eros"],
["Whiskey Myers", "Broken Window Serenade"],
["Yoko Kanno", "Whats it For"],
["Mac McCaughan & Annie Hayden", "Down We Go"],
["The Buttertones", "You and Your Knife"],
["The Doubleclicks", "Really Big Chickens"],
["Tony All", "At The Party"],
["Tony All", "Guitar Case"],
["Velvet Pony", "LESBIAN PONIES WITH WEAPONS"],
["Waxahatchee", "Noccalula"],
["David Bowie", "I Know It’s Gonna Happen Someday"],
["Mary Heather Hickman", "Treasure"],
["Ray Price", "The Wind Beneath My Wings"],
["The Avett Brothers", "Ain't No Man"],
["Dropout Kings", "Scratch & Claw"],
["Gogol Bordello", "Not a Crime"],
["Sparks", "Girl from Germany"],
["Sparks", "Under the Table with Her"],
["Streetlight Manifesto", "One Foot on the Gas, One Foot in the Grave"],
["The Doors", "Not to touch the earth"],
["Weird Al Yankovic", "Money for Nothing Beverly Hillbillies"],
["Adam Sandler", "Mr. Bake-O"],
["Eydie Gormé", "The Gentleman is a Dope"],
["Eydie Gormé", "What Did I Have That I Don't Have"],
["Rickie Lee Jones", "The Ballad Of The Sad Young Men"],
["Eddie Cochran", "Three Stars"],
["Lil Durk", "Broadway Girls"],
["Luude", "Down Under"],
[
"Taylor Swift",
"We Are Never Ever Getting Back Together (Taylor's Version)"
],
["The Fray", "Never Say Never"],
["The Ghost Club", "See Below"],
["General Levy", "Incredible (50% Volume Vocals)"],
["General Levy", "Incredible"],
["Marilyn Dagenais", "Chanson pour Papa"],
["Royal Navy", "Heart of Oak"],
["Tiamat", "Cain"],
["Marilyn Dagenais", "You Make Me Sing"],
["Young and Restless", "B Girls"],
["Bug Hunter", "Pinecones"],
["Streetlight Manifesto", "With Any Sort of Certainty"],
["Marvin Gaye", "God is Love"],
["Ben&Ben", "Maybe the Night"],
["Blink 182", "Fell In Love"],
["Blink 182", "Turpentine"],
["Bryson Tiller", "Right My Wrongs"],
["Chris Stapleton", "Joy of My Life"],
["Marilyn Dagenais", "L'hiver"],
["Metric", "Who Would You Be For Me"],
["Rex Orange County", "Happiness"],
["Sheff G", "Weight on Me"],
["Taylor Swift", "I Knew You Were Trouble (Taylor's Version)"],
["Taylor Swift", "You Belong With Me (Taylor's Version)"],
["The 1975", "Robbers"],
["Unknown", "Before the Screen Reads Fin"],
["ACDC", "Gone Shootin'"],
["Ozzy Osbourne", "You're No Different"],
["Alice Cooper", "He's Back (The Man Behind The Mask)"],
["Echo and The Bunnymen", "New Direction"],
["Iggy Pop", "Tell Me a Story"],
["Left Boy", "Security Check"],
["The Lemonheads", "If I Could Talk I’d Tell You"],
["They Might Be Giants", "Dinner Bell"],
["XTC", "Scissor Man"],
["XTC", "The Smartest Monkeys"],
["Marilyn Dagenais", "Un peu de lumière"],
["Bad Lip Reading", "Black Umbrella"],
["Bruno Mars", "The Lazy Song (Non-Lazy Parody)"],
["Marilyn Dagenais", "Si je t'aime"],
["Jerry Lee Lewis", "Meat Man"],
["Shovels & Rope", "Birmingham"],
["Wolfe Tones", "Rock On Rockall"],
["James Rado", "Where Do I Go? (From Hair)"],
["Andrea Bocelli", "Gloria in Excelsis Deo"],
["ABBA", "The Day Before You Came"],
["Fleet Foxes", "He Doesn’t Know Why"],
["The Drifters", "Up On The Roof"],
["The Seekers", "California Dreamin'"],
["Fleet Foxes", "Silver Dagger"],
["She Wants Revenge", "Broken Promises For Broken Hearts"],
["Ken Ashcorp", "On The Rocks"],
["Z-Ro", "Mo City Don Freestyle"],
["The Time", "Cool"],
["Urban Cookie Collective", "The Key, The Secret"],
["Melissa Etheridge", "Meet Me In The Back"],
["Garfunkel And Oates", "I Get to Do It With You"],
["A Fine Frenzy", "Come On, Come Out"],
["A Fine Frenzy", "Rangers"],
["Ken Ashcorp", "PVP"],
["A Fine Frenzy", "Almost Lover"],
["A Fine Frenzy", "You Picked Me"],
["Peach PRC", "God Is A Freak"],
["Righteous Brothers", "See That Girl"],
["Blue Eyed Blondes", "Maneater"],
["piri & tommy", "on & on"],
["Sudley ft. piri", "fumble"],
["A Fine Frenzy", "Ashes And Wine"],
["A Fine Frenzy", "The Minnow & The Trout"],
["Tame Impala", "The Boat I Row"],
["Spinal Tap", "Rainy Day Sun"],
["Röyksopp", "Running To The Sea"],
["Röyksopp", "Oh, Lover"],
["Röyksopp", "Monument"],
["Röyksopp", "Only This Moment"],
["Röyksopp", "The Girl And The Robot"],
["Röyksopp", "49 Percent"],
["Maisi & piri", "head"],
["Django Django", "Default"],
["Django Django", "Hail Bop"],
["piri & tommy", "silver lining"],
["Daniel O'Donnell", "Galway Bay"],
["Daniel O'Donnell", "I'll Take You Home Again Kathleen"],
["Daniel O'Donnell", "Mountains of Mourne"],
[
"Daniel O'Donnell",
"Medley: It's a Long Way to Tipperary / Pack up Your Troubles / If You're Irish, Come into the Parlour"
],
["Jackson Singleton", "Disguise"],
["Ken Ashcorp", "Dare You To Love Me"],
["A Fine Frenzy", "Borrowed Time"],
["A Fine Frenzy", "Last Of Days"],
["A Fine Frenzy", "Hope For The Hopeless"],
["A Fine Frenzy", "Liar, Liar"],
["A Fine Frenzy", "Lifesize"],
["A Fine Frenzy", "Near To You"],
["A Fine Frenzy", "Think Of You"],
["A Fine Frenzy", "Whisper"],
["piri & tommy", "settle"],
["piri & tommy", "soft spot"],
["piri & tommy", "sunlight"],
["piri & tommy", "beachin"],
["piri & tommy", "player 2"],
["piri & tommy", "can we"],
["piri & tommy", "easy"],
["piri & tommy", "say it"],
["piri & tommy", "slowly but surely"],
["piri & tommy", "words"],
["piri & tommy", "nice 2 me"],
["Tony Bennett & k.d.lang", "What A Wonderful World"],
["Ying Yang Twins", "Georgia Dome"],
[
"Daniel O'Donnell",
"Medley: Galway Bay, The Mountains Of Mourne, I'll Take You Home Again Kathleen"
],
["The Beatles", "In My Life"],
["Truck Stop", "Komm her du bist mein Cowboy"],
["Linda Feller", "Du gabst ihr deinen Namen"],
["Victoria OB", "Yeshua"],
["Matthew Morrison", "Somewhere Over the Rainbow"],
["fun.", "Benson Hedges"],
["fun.", "All the Pretty Girls"],
["fun.", "At Least I'm Not as Sad (As I Used to Be)"],
["fun.", "I Wanna Be the One"],
["fun.", "Walking the Dog"],
["fun.", "Light a Roman Candle with Me"],
["fun.", "Barlights"],
["fun.", "Take Your Time (Coming Home)"],
["Tom Astor", "Sturm Und Drang"],
["Titellied der gleichnamigen Fernsehserie 1962", "Bonanza"],
["Linda Feller", "Billy Bob's Texas"],
["ABBA", "Dancing Queen"],
["Ken Ashcorp", "Touch Fluffy Tail"],
["Mavi Phoenix", "Pretty Life (Whsprs Cover)"],
["Jimi Hendrix", "Remember"],
["Smash Mouth", "All Star"],
["Smash Mouth", "All Star (with Shrek)"],
["The Silent Comedy", "Enemies Multiply"],
["ABBA", "Ring Ring"],
["ABBA", "Another Town, Another Train"],
["ABBA", "Disillusion"],
["ABBA", "People Need Love"],
["Frank Sinatra", "New York, New York"],
["ABBA", "I Saw It In The Mirror"],
["ABBA", "Nina, Pretty Ballerina"],
["ABBA", "Love Isn’t Easy (But It Sure Is Hard Enough)"],
["ABBA", "Me And Bobby And Bobby’s Brother"],
["ABBA", "He Is Your Brother"],
["ABBA", "She’s My Kind Of Girl"],
["ABBA", "I Am Just A Girl"],
["ABBA", "Rock ’N Roll Band"],
["ABBA", "Ring Ring (Bara Du Slog En Signal) (Swedish Version)"],
["ABBA", "Åh, Vilka Tider"],
["ABBA", "Merry‐Go‐Round"],
["ABBA", "Santa Rosa"],
["ABBA", "Ring Ring (Spanish Version)"],
["ABBA", "Wer Im Wartesaal Der Liebe Steht"],
["ABBA", "Ring Ring (German Version)"],
["Fleet Foxes", "Montezuma"],
["Harald Juhnke", "Berlin, Berlin"],
["Shoshana Bean", "Strange Thunder"],
["Michael Callen", "Crazy World"],
["Michael Callen", "Wish I Had A Dime"],
["The Blasters", "One Bad Stud"],
["Michael Callen", "The Healing Power Of Love"],
["Meat Loaf", "Braver Than We Are"],
["Harald Juhnke", "Berlin, Berlin (Lisa, Milan)"],
["Friday", "The Ballad Of Skinny Linguine"],
["Emery", "The Ponytail Parades"],
["Black Sabbath", "Buried Alive"],
["Aloha from space", "Storm Troopin'"],
["NerdOut", "Bounty"],
["Charles Strouse and Lee Adams", "Han's Your Man"],
["Juliane Werding", "Man muß Das Leben Eben Nehmen, Wie Das Leben Eben Ist"],
["Aurelio Voltaire", "Butterfly"],
["Blind Guardian", "Violent Shadows"],
["Jonny Hill & Linda Feller", "Zusammenstehn (Duet)"],
["Tori Amos", "Big Wheel"],
["Chairlift", "Bruises"],
["Jonny Hill & Linda Feller", "London"],
["Life Languages", "The Mover Song"],
["Life Languages", "The Responder Song"],
["Life Languages", "The Contemplator Song"],
["Life Languages", "The Doer Song"],
["Life Languages", "The Shaper Song"],
["Life Languages", "The Influencer Song"],
["Life Languages", "The Producer Song"],
["The Amazing Devil", "That Unwanted Animal"],
["Bobby Capo", "Locamente Enamorado"],
["Dagmar", "Lass mich damit bloß in Ruhe"],
["Los Campesinos!", "You! Me! Dancing! (Daytrotter Session)"],
["Joe P", "Leaves"],
["ABBA", "Waterloo"],
["ABBA", "Sitting In The Palmtree"],
["ABBA", "King Kong Song"],
["ABBA", "Hasta Mañana"],
["ABBA", "My Mama Said"],
["ABBA", "Dance (While The Music Still Goes On)"],
["ABBA", "Honey, Honey"],
["Thomas Borchert", "I Know Those Eyes / This Man Is Dead (Duet)"],
[
"Thomas Borchert",
"I Know Those Eyes / This Man Is Dead (Duet With Female Vocals)"
],
["SHE WANTS REVENGE", "Rachael"],
["Matt Redmond", "Unbroken Praise"],
["Ian McConnell", "Level 429"],
["ABBA", "Watch Out"],
["ABBA", "What About Livingstone"],
["Ten Years After", "Outside My Window"],
["ABBA", "Gonna Sing You My Lovesong"],
["ABBA", "Suzy-Hang-Around"],
["ABBA", "Waterloo (Swedish Version)"],
["ABBA", "Honey, Honey (Swedish Version)"],
["ABBA", "Waterloo (German Version)"],
["ABBA", "Hasta Mañana (Spanish Version)"],
["ABBA", "Waterloo (French Version)"],
["ABBA", "Mamma Mia"],
["ABBA", "Hey, Hey Helen"],
["ABBA", "Tropical Loveland"],
["ABBA", "S.O.S."],
["ABBA", "Man In The Middle"],
["ABBA", "Bang-A-Boomerang"],
["ABBA", "I Do, I Do, I Do, I Do, I Do"],
["ABBA", "Rock Me"],
["ABBA", "I’ve Been Waiting For You"],
["ABBA", "So Long"],
["ABBA", "Crazy World"],
["ABBA", "Medley (1978 Mix)"],
["ABBA", "Mamma Mia (Spanish Version)"],
["Marina and The Diamonds", "Froot"],
["Maxton Waller", "On My Way (Marching Band)"],
["100 gecs", "mememe"],
["Stuck Out Here", "Embarrass You"],
["DCSane", "Heart's Whiskey"],
["Release", "Devil's Handshake"],
["Kelly Clarkson", "Since U Been Gone (Pitch -3: E major)"],
["Justin Townes Earle", "Rogers Park"],
["Armin van Buuren ft. Teddy Swims", "Easy To Love"],
["Willie Nelson", "One More Song to Write"],
["Will Varley", "Seize The Night"],
["Passenger", "However It Comes, Wherever It Goes"],
["Ricky Braddy", "Anyone (Acoustic Cover of Demi Lovato)"],
["Bryan Adams", "Help Me Make It Through The Night"],
["Ivan Rivers", "Mid-Riff"],
["Kane Brown", "American Bad Dream"],
["Mother Mother", "Ghosting"],
["Charlie Terrell", "Libby Anna"],
["Taylor Swift", "Fortnight (feat. Post Malone)"],
["The Gaslight Anthem", "National Anthem"],
["The Lonely Island", "Semicolon (feat. Solange)"],
["Lucky Daye", "Algorithm"],
["The Black Eyed Peas", "They Don't Want Music"],
["Tiger Really", "Fundamentally Unlovable"],
["Da Ali G Show", "Jarvis Cocker"],
["Colin Hay", "Send Somebody (Stripped Mix)"],
["Ernie Taylor", "I Ain't Leavin' Yet"],
["Smashing Pumpkins", "Here Is No Why"],
["Drake", "Virginia Beach"],
["Maverick City Music", "I Thank God"],
["Ax and the Hatchetmen", "Drive-in Movie"],
["Faith No More", "Das Schutzenfest"],
["Miguel", "Use Me"],
["Ivan Rivers", "Sad Around Me"],
["Young The Giant", "Both Sides Now"],
["Jimmy Buffett", "Bob Robert's Society Band"],
["buildspace, MAYV", "the end"],
["Frank Turner", "A Wave Across A Bay"],
["Angel Olsen", "Eyes Without A Face"],
["Deven May", "The Sensitive Song (from Cops)"],
["The Mountain Goats", "Night Light"],
["Steppenwolf", "Born To Be Wild"],
["Bobby Solo", "O sole mio"],
["HCA West", "Driving Quality"],
["Engelbert Humperdinck", "Marry Me"],
["Mark Knopfler", "Are We in Trouble Now"],
["Danny Pynes", "One Night in Spain"],
["The Butterfly Effect", "I’m Not Okay"],
["The Sonic Bridges", "Sweet Evelyn"],
["Carrie and Jake", "Wedding Medley"],
["Gregory Porter", "Insanity (feat. Lalah Hathaway)"],
["Linda Feller", "Ich weiss genau, was ich will"],
["Mikey Chuck Rivers", "She's Cryin' (I'm Drunk Again)"],
["Gregory Porter", "Insanity (feat. Lalah Hathaway) (Duet)"],
["Country Rose", "Spaß Am Leben"],
["Tom Astor", "Du bist da (wenn's drum geht)"],
["Linda Feller", "Wenn überhaupt, dann nur Country"],
["Alabama", "The Fans"],
["Ghost Brothers", "What Kind Of Man Am I"],
["The Stand", "Baby, Can You Dig Your Man"],
["Nu Shooz", "I Can't Wait"],
["Freddie Jackson", "All I'll Ever Ask (feat. Najee)"],
["Linda Feller", "Du bist das Salz in meiner Suppe"],
["Claudia Jung, Tom Astor", "Wer Liebe Sucht"],
["The Smashing Pumpkins", "Tales of a Scorched Earth"],
["The Smashing Pumpkins", "Thru the Eyes of Ruby"],
["Tom Astor", "Geistertruck"]
]
+103
View File
@@ -0,0 +1,103 @@
#! /usr/bin/env python3
import os
import json
import logging
from karaoke_prep.karaoke_prep import KaraokePrep
# Set up logging
logger = logging.getLogger(__name__)
log_handler = logging.StreamHandler()
log_formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
log_handler.setFormatter(log_formatter)
logger.addHandler(log_handler)
logger.setLevel(logging.DEBUG)
# Define the artist/title combinations
def total_length(tuple):
artist, title = tuple
return len(artist) + len(title)
with open("data/artist-titles.json", "r", encoding="utf-8") as f:
all_combinations = json.load(f)
# Sort by length and get shortest and longest 20
sorted_combinations = sorted(all_combinations, key=total_length)
artist_title_combinations = sorted_combinations[:20] + sorted_combinations[-20:]
# Define the format dictionary with expanded configurations
formats = [
{
"name": "nomadkaraoke",
"style_params_json": "/Users/andrew/AB Dropbox/Andrew Beveridge/MediaUnsynced/Karaoke/NomadBranding/karaoke-prep-styles-nomad.json",
},
{
"name": "vocalstar",
"style_params_json": "/Users/andrew/AB Dropbox/Andrew Beveridge/MediaUnsynced/Karaoke/Tracks-NonPublished/VocalStar/Resources/karaoke-prep-styles-vocalstar.json",
},
{
"name": "minimal",
"style_params_json": None,
},
]
# Define other parameters
base_output_dir = "outputs"
os.makedirs(base_output_dir, exist_ok=True)
# Process each format
for format in formats:
# Create format-specific output directory
format_output_dir = os.path.join(base_output_dir, format["name"])
os.makedirs(format_output_dir, exist_ok=True)
style_params = None
if format["style_params_json"]:
with open(format["style_params_json"], "r") as f:
style_params = json.loads(f.read())
# Instantiate KaraokePrep for this format
kprep = KaraokePrep(
log_level=logging.INFO,
log_formatter=log_formatter,
output_dir=format_output_dir,
style_params=style_params,
render_bounding_boxes=False,
output_jpg=False,
output_png=True,
)
# Run the create_title_video and create_end_video functions for each combination
for artist, title in artist_title_combinations:
sanitized_artist = kprep.sanitize_filename(artist)
sanitized_title = kprep.sanitize_filename(title)
# Generate title video
title_image_filepath_noext = os.path.join(format_output_dir, f"{sanitized_artist}_{sanitized_title}_title")
title_video_filepath = os.path.join(format_output_dir, f"{sanitized_artist}_{sanitized_title}_title.mov")
kprep.intro_video_duration = 0
kprep.create_title_video(
artist=artist,
title=title,
format=kprep.title_format,
output_image_filepath_noext=title_image_filepath_noext,
output_video_filepath=title_video_filepath,
)
logger.info(f"Created title video for {artist} - {title} using {format['name']} format")
# Generate end video
end_image_filepath_noext = os.path.join(format_output_dir, f"{sanitized_artist}_{sanitized_title}_end")
end_video_filepath = os.path.join(format_output_dir, f"{sanitized_artist}_{sanitized_title}_end.mov")
kprep.end_video_duration = 0
kprep.create_end_video(
artist=artist,
title=title,
format=kprep.end_format,
output_image_filepath_noext=end_image_filepath_noext,
output_video_filepath=end_video_filepath,
)
logger.info(f"Created end video for {artist} - {title} using {format['name']} format")