Compare commits

...
8 Commits
5 changed files with 117 additions and 197 deletions

No files matched your search

+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
```
+96 -56
View File
@@ -29,8 +29,8 @@ class KaraokePrep:
intro_background_color="#000000",
intro_background_image=None,
intro_font="AvenirNext-Bold.ttf",
intro_artist_color="#ff7acc",
intro_title_color="#ffdf6b",
intro_artist_color="#ffffff",
intro_title_color="#ff7acc",
):
self.logger = logging.getLogger(__name__)
self.logger.setLevel(log_level)
@@ -60,11 +60,15 @@ class KaraokePrep:
self.normalization_enabled = normalization_enabled
self.denoise_enabled = denoise_enabled
self.create_track_subfolders = create_track_subfolders
self.intro_background_color = intro_background_color
self.intro_background_image = intro_background_image
self.intro_font = intro_font
self.intro_artist_color = intro_artist_color
self.intro_title_color = intro_title_color
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}")
@@ -82,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:
@@ -228,69 +234,99 @@ class KaraokePrep:
return track_output_dir, artist_title
def create_intro_video(self, artist, title, output_filename):
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
font_size = 400 # Adjust as needed
line_spacing = 50 # Adjust as needed
# Load or create background image
if self.intro_background_image:
background = Image.open(self.intro_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(self.intro_background_color))
background = Image.new("RGB", resolution, color=self.hex_to_rgb(format["background_color"]))
# Resize background to match resolution
background = background.resize(resolution)
# Create an ImageDraw instance
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)
# Check if the font file exists, if not use a default font
if os.path.exists(self.intro_font):
font = ImageFont.truetype(self.intro_font, size=font_size)
else:
self.logger.warning(f"Font file not found: {self.intro_font}. Using default font.")
font = ImageFont.load_default(size=font_size)
# 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)
# Calculate text width using the ImageDraw instance
artist_text_width = draw.textlength(artist, font=font)
title_text_width = draw.textlength(title, font=font)
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)
# Calculate text positions
artist_text_position = ((resolution[0] - artist_text_width) // 2, resolution[1] // 2 - font_size - line_spacing)
title_text_position = ((resolution[0] - title_text_width) // 2, resolution[1] // 2 + line_spacing)
# Draw text
draw.text(artist_text_position, artist, fill=self.intro_artist_color, font=font)
draw.text(title_text_position, title, fill=self.intro_title_color, font=font)
# Save to a temporary image file
temp_image_path = "/tmp/temp_background.png"
background.save(temp_image_path)
self.logger.warning(f"Temporarily saving background image to {temp_image_path}")
# Save static background image
background.save(output_image_filepath)
# Use ffmpeg to create video
ffmpeg_command = [
"ffmpeg",
"-y", # Overwrite output files without asking
"-loop", # Loop the input image
"1", # Loop the input image
"-i", # Input file
temp_image_path, # Input file
"-c:v", # Video codec
"libx264", # Video codec
"-t", # Duration
str(duration), # Duration
"-pix_fmt", # Pixel format
"yuv420p", # Pixel format
"-vf", # Video filter
f"scale={resolution[0]}:{resolution[1]}", # Video filter
output_filename, # Output filename
"-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)
# os.remove(temp_image_path)
def hex_to_rgb(self, hex_color):
"""Convert hex color to RGB tuple."""
@@ -313,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)
@@ -366,9 +406,6 @@ class KaraokePrep:
processed_track["lyrics"] = lyrics_file
intro_filename = os.path.join(track_output_dir, f"{artist_title} (Intro).mp4")
self.create_intro_video(artist, title, intro_filename)
self.logger.info(f"Separating audio twice for track: {title} by {artist}")
instrumental_path = os.path.join(track_output_dir, f"{artist_title} (Instrumental {self.model_name}).{self.output_format}")
@@ -409,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:
@@ -420,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")
+8 -6
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(
@@ -112,14 +112,14 @@ def main():
parser.add_argument(
"--intro_artist_color",
default="#ff7acc",
help="Optional: Font color for intro video artist text (default: #ff7acc). Example: --intro_artist_color=#123456",
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="#ffdf6b",
help="Optional: Font color for intro video title text (default: #ffdf6b). Example: --intro_title_color=#123456",
default="#ffffff",
help="Optional: Font color for intro video title text (default: #ffffff). Example: --intro_title_color=#123456",
)
args = parser.parse_args()
@@ -135,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]
Generated
+5 -132
View File
@@ -449,13 +449,13 @@ cron = ["capturer (>=2.4)"]
[[package]]
name = "decorator"
version = "4.4.2"
version = "5.1.1"
description = "Decorators for Humans"
optional = false
python-versions = ">=2.6, !=3.0.*, !=3.1.*"
python-versions = ">=3.5"
files = [
{file = "decorator-4.4.2-py2.py3-none-any.whl", hash = "sha256:41fa54c2a0cc4ba648be4fd43cff00aedf5b9465c9bf18d64325bc225f08f760"},
{file = "decorator-4.4.2.tar.gz", hash = "sha256:e3a62f0520172440ca0dcc823749319382e377f37f140a0b99ef45fecb84bfe7"},
{file = "decorator-5.1.1-py3-none-any.whl", hash = "sha256:b8c3f85900b9dc423225913c5aace94729fe1fa9763b38939a95226f02d37186"},
{file = "decorator-5.1.1.tar.gz", hash = "sha256:637996211036b6385ef91435e4fae22989472f9d571faba8927ba8253acbc330"},
]
[[package]]
@@ -558,56 +558,6 @@ files = [
{file = "idna-3.6.tar.gz", hash = "sha256:9ecdbbd083b06798ae1e86adcbfe8ab1479cf864e4ee30fe4e46a003d12491ca"},
]
[[package]]
name = "imageio"
version = "2.33.1"
description = "Library for reading and writing a wide range of image, video, scientific, and volumetric data formats."
optional = false
python-versions = ">=3.8"
files = [
{file = "imageio-2.33.1-py3-none-any.whl", hash = "sha256:c5094c48ccf6b2e6da8b4061cd95e1209380afafcbeae4a4e280938cce227e1d"},
{file = "imageio-2.33.1.tar.gz", hash = "sha256:78722d40b137bd98f5ec7312119f8aea9ad2049f76f434748eb306b6937cc1ce"},
]
[package.dependencies]
numpy = "*"
pillow = ">=8.3.2"
[package.extras]
all-plugins = ["astropy", "av", "imageio-ffmpeg", "pillow-heif", "psutil", "tifffile"]
all-plugins-pypy = ["av", "imageio-ffmpeg", "pillow-heif", "psutil", "tifffile"]
build = ["wheel"]
dev = ["black", "flake8", "fsspec[github]", "pytest", "pytest-cov"]
docs = ["numpydoc", "pydata-sphinx-theme", "sphinx (<6)"]
ffmpeg = ["imageio-ffmpeg", "psutil"]
fits = ["astropy"]
full = ["astropy", "av", "black", "flake8", "fsspec[github]", "gdal", "imageio-ffmpeg", "itk", "numpydoc", "pillow-heif", "psutil", "pydata-sphinx-theme", "pytest", "pytest-cov", "sphinx (<6)", "tifffile", "wheel"]
gdal = ["gdal"]
itk = ["itk"]
linting = ["black", "flake8"]
pillow-heif = ["pillow-heif"]
pyav = ["av"]
test = ["fsspec[github]", "pytest", "pytest-cov"]
tifffile = ["tifffile"]
[[package]]
name = "imageio-ffmpeg"
version = "0.4.9"
description = "FFMPEG wrapper for Python"
optional = false
python-versions = ">=3.5"
files = [
{file = "imageio-ffmpeg-0.4.9.tar.gz", hash = "sha256:39bcd1660118ef360fa4047456501071364661aa9d9021d3d26c58f1ee2081f5"},
{file = "imageio_ffmpeg-0.4.9-py3-none-macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl", hash = "sha256:24095e882a126a0d217197b86265f821b4bb3cf9004104f67c1384a2b4b49168"},
{file = "imageio_ffmpeg-0.4.9-py3-none-manylinux2010_x86_64.whl", hash = "sha256:2996c64af3e5489227096580269317719ea1a8121d207f2e28d6c24ebc4a253e"},
{file = "imageio_ffmpeg-0.4.9-py3-none-manylinux2014_aarch64.whl", hash = "sha256:7eead662d2f46d748c0ab446b68f423eb63d2b54d0a8ef96f80607245540866d"},
{file = "imageio_ffmpeg-0.4.9-py3-none-win32.whl", hash = "sha256:b6de1e18911687c538d5585d8287ab1a23624ca9dc2044fcc4607de667bcf11e"},
{file = "imageio_ffmpeg-0.4.9-py3-none-win_amd64.whl", hash = "sha256:7e900c695c6541b1cb17feb1baacd4009b30a53a45b81c23d53a67ab13ffb766"},
]
[package.dependencies]
setuptools = "*"
[[package]]
name = "jinja2"
version = "3.1.2"
@@ -787,33 +737,6 @@ files = [
{file = "MarkupSafe-2.1.3.tar.gz", hash = "sha256:af598ed32d6ae86f1b747b82783958b1a4ab8f617b06fe68795c7f026abbdcad"},
]
[[package]]
name = "moviepy"
version = "1.0.3"
description = "Video editing with Python"
optional = false
python-versions = "*"
files = [
{file = "moviepy-1.0.3.tar.gz", hash = "sha256:2884e35d1788077db3ff89e763c5ba7bfddbd7ae9108c9bc809e7ba58fa433f5"},
]
[package.dependencies]
decorator = ">=4.0.2,<5.0"
imageio = {version = ">=2.5,<3.0", markers = "python_version >= \"3.4\""}
imageio_ffmpeg = {version = ">=0.2.0", markers = "python_version >= \"3.4\""}
numpy = [
{version = ">=1.17.3", markers = "python_version != \"2.7\""},
{version = "*", markers = "python_version >= \"2.7\""},
]
proglog = "<=1.0.0"
requests = ">=2.8.1,<3.0"
tqdm = ">=4.11.2,<5.0"
[package.extras]
doc = ["Sphinx (>=1.5.2,<2.0)", "numpydoc (>=0.6.0,<1.0)", "pygame (>=1.9.3,<2.0)", "sphinx_rtd_theme (>=0.1.10b0,<1.0)"]
optional = ["matplotlib (>=2.0.0,<3.0)", "opencv-python (>=3.0,<4.0)", "scikit-image (>=0.13.0,<1.0)", "scikit-learn", "scipy (>=0.19.0,<1.5)", "youtube_dl"]
test = ["coverage (<5.0)", "coveralls (>=1.1,<2.0)", "pytest (>=3.0.0,<4.0)", "pytest-cov (>=2.5.1,<3.0)", "requests (>=2.8.1,<3.0)"]
[[package]]
name = "mpmath"
version = "1.3.0"
@@ -1330,20 +1253,6 @@ progress = ["tqdm (>=4.41.0,<5.0.0)"]
sftp = ["paramiko (>=2.7.0)"]
xxhash = ["xxhash (>=1.4.3)"]
[[package]]
name = "proglog"
version = "0.1.10"
description = "Log and progress bar manager for console, notebooks, web..."
optional = false
python-versions = "*"
files = [
{file = "proglog-0.1.10-py3-none-any.whl", hash = "sha256:19d5da037e8c813da480b741e3fa71fb1ac0a5b02bf21c41577c7f327485ec50"},
{file = "proglog-0.1.10.tar.gz", hash = "sha256:658c28c9c82e4caeb2f25f488fff9ceace22f8d69b15d0c1c86d64275e4ddab4"},
]
[package.dependencies]
tqdm = "*"
[[package]]
name = "protobuf"
version = "4.25.1"
@@ -1563,22 +1472,6 @@ dev = ["click", "cython-lint (>=0.12.2)", "doit (>=0.36.0)", "mypy", "pycodestyl
doc = ["jupytext", "matplotlib (>2)", "myst-nb", "numpydoc", "pooch", "pydata-sphinx-theme (==0.9.0)", "sphinx (!=4.1.0)", "sphinx-design (>=0.2.0)"]
test = ["asv", "gmpy2", "mpmath", "pooch", "pytest", "pytest-cov", "pytest-timeout", "pytest-xdist", "scikit-umfpack", "threadpoolctl"]
[[package]]
name = "setuptools"
version = "69.0.2"
description = "Easily download, build, install, upgrade, and uninstall Python packages"
optional = false
python-versions = ">=3.8"
files = [
{file = "setuptools-69.0.2-py3-none-any.whl", hash = "sha256:1e8fdff6797d3865f37397be788a4e3cba233608e9b509382a2777d25ebde7f2"},
{file = "setuptools-69.0.2.tar.gz", hash = "sha256:735896e78a4742605974de002ac60562d286fa8051a7e2299445e8e8fbb01aa6"},
]
[package.extras]
docs = ["furo", "jaraco.packaging (>=9.3)", "jaraco.tidelift (>=1.4)", "pygments-github-lexers (==0.0.5)", "rst.linker (>=1.9)", "sphinx (<7.2.5)", "sphinx (>=3.5)", "sphinx-favicon", "sphinx-inline-tabs", "sphinx-lint", "sphinx-notfound-page (>=1,<2)", "sphinx-reredirects", "sphinxcontrib-towncrier"]
testing = ["build[virtualenv]", "filelock (>=3.4.0)", "flake8-2020", "ini2toml[lite] (>=0.9)", "jaraco.develop (>=7.21)", "jaraco.envs (>=2.2)", "jaraco.path (>=3.2.0)", "pip (>=19.1)", "pytest (>=6)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=2.2)", "pytest-mypy (>=0.9.1)", "pytest-perf", "pytest-ruff", "pytest-timeout", "pytest-xdist", "tomli-w (>=1.0.0)", "virtualenv (>=13.0.0)", "wheel"]
testing-integration = ["build[virtualenv] (>=1.0.3)", "filelock (>=3.4.0)", "jaraco.envs (>=2.2)", "jaraco.path (>=3.2.0)", "packaging (>=23.1)", "pytest", "pytest-enabler", "pytest-xdist", "tomli", "virtualenv (>=13.0.0)", "wheel"]
[[package]]
name = "six"
version = "1.16.0"
@@ -1722,26 +1615,6 @@ typing-extensions = "*"
dynamo = ["jinja2"]
opt-einsum = ["opt-einsum (>=3.3)"]
[[package]]
name = "tqdm"
version = "4.66.1"
description = "Fast, Extensible Progress Meter"
optional = false
python-versions = ">=3.7"
files = [
{file = "tqdm-4.66.1-py3-none-any.whl", hash = "sha256:d302b3c5b53d47bce91fea46679d9c3c6508cf6332229aa1e7d8653723793386"},
{file = "tqdm-4.66.1.tar.gz", hash = "sha256:d88e651f9db8d8551a62556d3cff9e3034274ca5d66e93197cf2490e2dcb69c7"},
]
[package.dependencies]
colorama = {version = "*", markers = "platform_system == \"Windows\""}
[package.extras]
dev = ["pytest (>=6)", "pytest-cov", "pytest-timeout", "pytest-xdist"]
notebook = ["ipywidgets (>=6)"]
slack = ["slack-sdk"]
telegram = ["requests"]
[[package]]
name = "triton"
version = "2.1.0"
@@ -1909,4 +1782,4 @@ websockets = "*"
[metadata]
lock-version = "2.0"
python-versions = ">=3.9"
content-hash = "e0e22aaa0dc419581769ab298c832eaf2323537da0c060e33516ca41f17675ff"
content-hash = "b36700c08629f5c61e7a0332791c0688650c6b9c428e3bf9dd441290249f44ac"
+2 -2
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-prep"
version = "0.4.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,7 +18,7 @@ yt-dlp = "*"
lyricsgenius = "^3"
fetch-lyrics-from-genius = "^0.1"
audio-separator = "^0.8"
moviepy = "^1.0.3"
pillow = "^10.1.0"
[tool.poetry.group.dev.dependencies]
black = "^23"