Compare commits

..
11 Commits
7 changed files with 890 additions and 471 deletions

No files matched your search

Binary file not shown.
+6 -1
View File
@@ -52,7 +52,12 @@ options:
--use_coreml Optional: use Apple Silicon GPU with CoreML for separation (default: False). Example: --use_coreml=true
--denoise DENOISE Optional: enable or disable denoising during separation (default: True). Example: --denoise=False
--normalize NORMALIZE Optional: enable or disable normalization during separation (default: True). Example: --normalize=False
--no_track_subfolders Optional:do NOT create a named subfolder for each track. Example: --no_track_subfolders
--no_track_subfolders Optional: do NOT create a named subfolder for each track. Example: --no_track_subfolders
--intro_background_color INTRO_BACKGROUND_COLOR Optional: Background color for intro video (default: black). Example: --intro_background_color=#123456
--intro_background_image INTRO_BACKGROUND_IMAGE Optional: Path to background image for intro video. Overrides background color if provided. Example: --intro_background_image=path/to/image.jpg
--intro_font INTRO_FONT Optional: Font file for intro video (default: Avenir-Next-Bold). Example: --intro_font=AvenirNext-Bold.ttf
--intro_artist_color INTRO_ARTIST_COLOR Optional: Font color for intro video artist text (default: #ff7acc). Example: --intro_artist_color=#123456
--intro_title_color INTRO_TITLE_COLOR Optional: Font color for intro video title text (default: #ffdf6b). Example: --intro_title_color=#123456
```
+1 -1
View File
@@ -1 +1 @@
from .requests_prep import KaraokePrep
from .karaoke_prep import KaraokePrep
@@ -1,12 +1,11 @@
import requests
import os
import re
import glob
from bs4 import BeautifulSoup
import yt_dlp
import logging
import lyricsgenius
from slugify import slugify
import subprocess
from PIL import Image, ImageDraw, ImageFont
class KaraokePrep:
@@ -27,6 +26,11 @@ class KaraokePrep:
normalization_enabled=True,
denoise_enabled=True,
create_track_subfolders=False,
intro_background_color="#000000",
intro_background_image=None,
intro_font="AvenirNext-Bold.ttf",
intro_artist_color="#ffffff",
intro_title_color="#ff7acc",
):
self.logger = logging.getLogger(__name__)
self.logger.setLevel(log_level)
@@ -57,6 +61,15 @@ class KaraokePrep:
self.denoise_enabled = denoise_enabled
self.create_track_subfolders = create_track_subfolders
self.title_format = {
"background_color": intro_background_color,
"background_image": intro_background_image,
"artist_font": intro_font,
"title_font": intro_font,
"artist_color": intro_artist_color,
"title_color": intro_title_color,
}
self.logger.debug(f"KaraokePrep output_format: {self.output_format}")
if not os.path.exists(self.output_dir):
@@ -73,6 +86,8 @@ class KaraokePrep:
with yt_dlp.YoutubeDL({"quiet": True}) as ydl:
info = ydl.extract_info(self.url, download=False)
self.artist, self.title = self.parse_metadata(info)
if self.persistent_artist:
self.artist = self.persistent_artist
if self.artist and self.title:
self.logger.info(f"Extracted artist: {self.artist}, title: {self.title}")
else:
@@ -190,6 +205,7 @@ class KaraokePrep:
)
from audio_separator import Separator
separator = Separator(
audio_file,
log_level=self.log_level,
@@ -218,6 +234,105 @@ class KaraokePrep:
return track_output_dir, artist_title
def calculate_text_size_and_position(self, draw, text, font_path, start_size, resolution, padding):
font_size = start_size
font = ImageFont.truetype(font_path, size=font_size) if os.path.exists(font_path) else ImageFont.load_default()
# Initial position for calculating the text bounding box
temp_position = (padding, padding)
bbox = draw.textbbox(temp_position, text, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
while text_width + 2 * padding > resolution[0] or text_height + 2 * padding > resolution[1]:
font_size -= 10
if font_size <= 0:
raise ValueError("Cannot fit text within screen bounds.")
font = ImageFont.truetype(font_path, size=font_size) if os.path.exists(font_path) else ImageFont.load_default()
bbox = draw.textbbox(temp_position, text, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
text_position = ((resolution[0] - text_width) // 2, (resolution[1] - text_height) // 2)
return font, text_position
def calculate_text_position(self, draw, text, font, resolution, vertical_offset):
bbox = draw.textbbox((0, 0), text, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
text_x = (resolution[0] - text_width) // 2
text_y = vertical_offset
return (text_x, text_y), text_height
def create_intro_video(self, artist, title, format, output_image_filepath, output_video_filepath):
duration = 5 # Duration in seconds
resolution = (3840, 2160) # 4K resolution
# Load or create background image
if format["background_image"] and os.path.exists(format["background_image"]):
self.logger.debug(f"Title screen background image file found: {format['background_image']}")
background = Image.open(format["background_image"])
else:
background = Image.new("RGB", resolution, color=self.hex_to_rgb(format["background_color"]))
# Resize background to match resolution
background = background.resize(resolution)
title = title.upper()
artist = artist.upper()
initial_font_size = 500
top_padding = 950
title_padding = 400
artist_padding = 700
fixed_gap = 150
draw = ImageDraw.Draw(background)
# Calculate positions and sizes for title and artist
title_font, _ = self.calculate_text_size_and_position(
draw, title, format["title_font"], initial_font_size, resolution, title_padding
)
artist_font, _ = self.calculate_text_size_and_position(
draw, artist, format["artist_font"], initial_font_size, resolution, artist_padding
)
# Calculate vertical positions with consistent gap
title_text_position, title_height = self.calculate_text_position(draw, title, title_font, resolution, top_padding)
artist_text_position, _ = self.calculate_text_position(draw, artist, artist_font, resolution, title_text_position[1] + title_height + fixed_gap)
draw.text(title_text_position, title, fill=format["title_color"], font=title_font)
draw.text(artist_text_position, artist, fill=format["artist_color"], font=artist_font)
# Save static background image
background.save(output_image_filepath)
# Use ffmpeg to create video
ffmpeg_command = [
"ffmpeg",
"-y",
"-loop",
"1",
"-i",
output_image_filepath,
"-c:v",
"libx264",
"-t",
str(duration),
"-pix_fmt",
"yuv420p",
"-vf",
f"scale={resolution[0]}:{resolution[1]}",
output_video_filepath,
]
subprocess.run(ffmpeg_command)
def hex_to_rgb(self, hex_color):
"""Convert hex color to RGB tuple."""
hex_color = hex_color.lstrip("#")
return tuple(int(hex_color[i : i + 2], 16) for i in (0, 2, 4))
def prep_single_track(self):
if self.artist is None or self.title is None:
self.logger.warn(f"Artist or Title nor specified manually, guessing from YouTube metadata...")
@@ -234,6 +349,10 @@ class KaraokePrep:
"title": title,
}
processed_track["title_image"] = os.path.join(track_output_dir, f"{artist_title} (Title).png")
processed_track["title_video"] = os.path.join(track_output_dir, f"{artist_title} (Title).mov")
self.create_intro_video(artist, title, self.title_format, processed_track["title_image"], processed_track["title_video"])
yt_webm_filename_pattern = os.path.join(track_output_dir, f"{artist_title} (YouTube *.webm")
yt_webm_glob = glob.glob(yt_webm_filename_pattern)
@@ -327,7 +446,7 @@ class KaraokePrep:
"""
Processes all videos in a YouTube playlist.
"""
self.logger.debug("Querying playlist metadata from YouTube...")
self.logger.debug(f"Querying playlist metadata from YouTube, assuming consistent artist {self.artist}...")
with yt_dlp.YoutubeDL({"quiet": True}) as ydl:
result = ydl.extract_info(self.url, download=False)
if "entries" in result:
@@ -338,13 +457,16 @@ class KaraokePrep:
self.logger.info(f"Processing video: {video_url}")
self.url = video_url
track_results.append(self.prep_single_track())
self.artist = None
self.artist = self.persistent_artist
self.title = None
return track_results
def process(self):
if self.is_playlist_url():
self.logger.info(f"Provided YouTube URL is a playlist, beginning batch operation")
self.persistent_artist = self.artist
self.logger.info(
f"Provided YouTube URL is a playlist, beginning batch operation with persistent artist: {self.persistent_artist}"
)
return self.process_playlist()
else:
self.logger.info(f"Provided YouTube URL is NOT a playlist, processing single track")
+38 -2
View File
@@ -19,7 +19,7 @@ def main():
parser = argparse.ArgumentParser(
description="Fetch audio and lyrics for a specified song, to prepare karaoke video creation.",
formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=50),
formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=54),
)
parser.add_argument(
@@ -93,6 +93,35 @@ def main():
help="Optional: do NOT create a named subfolder for each track. Example: --no_track_subfolders",
)
parser.add_argument(
"--intro_background_color",
default="black",
help="Optional: Background color for intro video (default: black). Example: --intro_background_color=#123456",
)
parser.add_argument(
"--intro_background_image",
help="Optional: Path to background image for intro video. Overrides background color if provided. Example: --intro_background_image=path/to/image.jpg",
)
parser.add_argument(
"--intro_font",
default="AvenirNext-Bold.ttf",
help="Optional: Font file for intro video (default: Avenir-Next-Bold). 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",
)
args = parser.parse_args()
url, artist, title = None, None, None
@@ -106,8 +135,10 @@ def main():
if len(args.args) > 2:
artist = args.args[1]
title = args.args[2]
elif len(args.args) > 1:
artist = args.args[1]
else:
logger.warn("URL provided without Artist and Title, these will be guessed from YouTube Title")
logger.warn("URL provided without Artist and Title, both will be guessed from YouTube Title")
elif len(args.args) > 1:
artist = args.args[0]
@@ -137,6 +168,11 @@ def main():
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,
)
tracks = kprep.process()
Generated
+715 -460
View File
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-prep"
version = "0.3.1"
version = "0.4.8"
description = "Prepare for karaoke video creation, by downloading audio and lyrics for a specified song or youtube playlist and separatung audio stems."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"
@@ -18,6 +18,7 @@ yt-dlp = "*"
lyricsgenius = "^3"
fetch-lyrics-from-genius = "^0.1"
audio-separator = "^0.8"
pillow = "^10.1.0"
[tool.poetry.group.dev.dependencies]
black = "^23"