mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-30 17:21:26 +09:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ff90b72a34 | ||
|
|
1e8a23ad50 | ||
|
|
9fbe04ecf8 | ||
|
|
224a9cfd57 | ||
|
|
9f8a6edab3 | ||
|
|
4bd2d121ae | ||
|
|
5a1095556c | ||
|
|
5877b9b8da | ||
|
|
bcc1196152 |
No files matched your search
Binary file not shown.
@@ -15,6 +15,8 @@ This was created to make it easier for me to prepare the source audio, lyrics an
|
||||
- Easy Configuration: Control the tool's behavior using command-line arguments.
|
||||
- Organized Outputs: Creates structured output directories for easy access to generated tracks and lyrics.
|
||||
- Internet First: Completes operations which require internet first, in case user is preparing last-minute before a period of being offline!
|
||||
- Flexible Input: provide just a YouTube URL, just an artist and title, or both.
|
||||
- Playlist Processing: Capable of processing an entire YouTube playlist, extracting audio and lyrics for each track.
|
||||
|
||||
## Installation 🛠️
|
||||
|
||||
@@ -37,9 +39,7 @@ usage: karaoke-prep [-h] [-v] [--log_level LOG_LEVEL] [--model_name MODEL_NAME]
|
||||
Fetch audio and lyrics for a specified song, to prepare karaoke video creation.
|
||||
|
||||
positional arguments:
|
||||
artist Artist name for the song to prep.
|
||||
title Title of the song to prep.
|
||||
url YouTube URL of the song to prep.
|
||||
args [YouTube video or playlist URL] [Artist] [Title] of song to prep. If URL is provided, Artist and Title are optional but increase chance of fetching the correct lyrics. If Artist and Title are provided with no URL, the top YouTube search result will be fetched.
|
||||
|
||||
options:
|
||||
-h, --help show this help message and exit
|
||||
@@ -55,15 +55,42 @@ options:
|
||||
--no_track_subfolders Optional:do NOT create a named subfolder for each track. Example: --no_track_subfolders
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
### Only YouTube URL
|
||||
|
||||
This will process the video at the given URL, *guessing the artist and title from the YouTube title*.
|
||||
⚠️ Be aware the downloaded lyrics may be incorrect if the video title doesn't match the standard "Artist - Title" format.
|
||||
|
||||
```
|
||||
karaoke-prep "https://www.youtube.com/watch?v=YOUR_VIDEO_ID"
|
||||
```
|
||||
|
||||
### Artist and Title Only
|
||||
|
||||
If you don't have a specific YouTube URL, just provide the artist and title. Karaoke Prep will search for and download the top YouTube result.
|
||||
|
||||
```
|
||||
karaoke-prep "The Fray" "Never Say Never"
|
||||
```
|
||||
|
||||
This command will search YouTube for the specified song, download audio from the top result and lyrics from genius, then separate the audio to produce an instrumental track, ready for a karaoke video to be created by whatever process you prefer!
|
||||
### ⭐ YouTube URL with Artist and Title
|
||||
|
||||
By default, you'll end up with files in the current folder, neatly organised e.g.
|
||||
For more precise control (and most consistent results), provide the YouTube URL along with the artist and title to avoid any guesswork.
|
||||
|
||||
```
|
||||
karaoke-prep "https://www.youtube.com/watch?v=YOUR_VIDEO_ID" "The Fray" "Never Say Never"
|
||||
```
|
||||
|
||||
### YouTube Playlist URL
|
||||
|
||||
To process a playlist, just provide the playlist URL. The script will process every video in the playlist.
|
||||
⚠️ Be aware the downloaded _lyrics_ for each track may be incorrect if the video titles don't match the standard "Artist - Title" format.
|
||||
|
||||
```
|
||||
karaoke-prep "https://www.youtube.com/playlist?list=YOUR_PLAYLIST_ID"
|
||||
```
|
||||
|
||||
By default, you'll end up with files in the current folder, neatly organised into folders for each track and files named consistently e.g.
|
||||
|
||||
```
|
||||
├── Artist - Title (Instrumental UVR-MDX-NET-Inst_HQ_3).flac
|
||||
|
||||
@@ -1 +1 @@
|
||||
from .requests_prep import KaraokePrep
|
||||
from .karaoke_prep import KaraokePrep
|
||||
@@ -1,13 +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
|
||||
from audio_separator import Separator
|
||||
import subprocess
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
|
||||
class KaraokePrep:
|
||||
@@ -28,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="#ff7acc",
|
||||
intro_title_color="#ffdf6b",
|
||||
):
|
||||
self.logger = logging.getLogger(__name__)
|
||||
self.logger.setLevel(log_level)
|
||||
@@ -57,6 +60,11 @@ 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.logger.debug(f"KaraokePrep output_format: {self.output_format}")
|
||||
|
||||
@@ -66,10 +74,6 @@ class KaraokePrep:
|
||||
else:
|
||||
self.logger.debug(f"Overall output dir {self.output_dir} already exists")
|
||||
|
||||
if artist is None or title is None:
|
||||
self.logger.warn(f"Artist or Title nor specified manually, guessing from YouTube metadata...")
|
||||
self.extract_metadata_from_url()
|
||||
|
||||
def extract_metadata_from_url(self):
|
||||
"""
|
||||
Extracts metadata from the YouTube URL.
|
||||
@@ -193,6 +197,9 @@ class KaraokePrep:
|
||||
self.logger.debug(
|
||||
f"instantiating Separator with model_name: {model_name} instrumental_path: {instrumental_path} and output_format: {self.output_format}"
|
||||
)
|
||||
|
||||
from audio_separator import Separator
|
||||
|
||||
separator = Separator(
|
||||
audio_file,
|
||||
log_level=self.log_level,
|
||||
@@ -221,7 +228,91 @@ class KaraokePrep:
|
||||
|
||||
return track_output_dir, artist_title
|
||||
|
||||
def prep(self):
|
||||
def create_intro_video(self, artist, title, output_filename):
|
||||
duration = 5 # Duration in seconds
|
||||
resolution = (3840, 2160) # 4K resolution
|
||||
font_size = 400 # Initial font size
|
||||
line_spacing = 50 # Adjust as needed
|
||||
padding = 300 # Padding from edges
|
||||
|
||||
# Load or create background image
|
||||
if self.intro_background_image:
|
||||
background = Image.open(self.intro_background_image)
|
||||
else:
|
||||
background = Image.new("RGB", resolution, color=self.hex_to_rgb(self.intro_background_color))
|
||||
|
||||
# Resize background to match resolution
|
||||
background = background.resize(resolution)
|
||||
|
||||
# Create an ImageDraw instance
|
||||
draw = ImageDraw.Draw(background)
|
||||
|
||||
# Function to calculate text width
|
||||
def calculate_text_width(font):
|
||||
artist_text_width = draw.textlength(artist, font=font)
|
||||
title_text_width = draw.textlength(title, font=font)
|
||||
return max(artist_text_width, title_text_width)
|
||||
|
||||
# Adjust font size if necessary
|
||||
while True:
|
||||
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)
|
||||
|
||||
max_text_width = calculate_text_width(font)
|
||||
if max_text_width + padding * 2 > resolution[0]:
|
||||
font_size -= 10 # Reduce font size
|
||||
if font_size <= 0:
|
||||
raise ValueError("Cannot fit text within screen bounds.")
|
||||
else:
|
||||
break
|
||||
|
||||
# Calculate text positions
|
||||
artist_text_position = ((resolution[0] - calculate_text_width(font)) // 2, resolution[1] // 2 - font_size - line_spacing)
|
||||
title_text_position = ((resolution[0] - calculate_text_width(font)) // 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)
|
||||
|
||||
# Use ffmpeg to create video
|
||||
ffmpeg_command = [
|
||||
"ffmpeg",
|
||||
"-y",
|
||||
"-loop",
|
||||
"1",
|
||||
"-i",
|
||||
temp_image_path,
|
||||
"-c:v",
|
||||
"libx264",
|
||||
"-t",
|
||||
str(duration),
|
||||
"-pix_fmt",
|
||||
"yuv420p",
|
||||
"-vf",
|
||||
f"scale={resolution[0]}:{resolution[1]}",
|
||||
output_filename,
|
||||
]
|
||||
|
||||
subprocess.run(ffmpeg_command)
|
||||
os.remove(temp_image_path)
|
||||
|
||||
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...")
|
||||
self.extract_metadata_from_url()
|
||||
|
||||
artist = self.artist
|
||||
title = self.title
|
||||
|
||||
@@ -286,6 +377,9 @@ 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}")
|
||||
@@ -313,3 +407,39 @@ class KaraokePrep:
|
||||
self.logger.info("Script finished, audio downloaded, lyrics fetched and audio separated!")
|
||||
|
||||
return processed_track
|
||||
|
||||
def is_playlist_url(self):
|
||||
"""
|
||||
Checks if the provided URL is a YouTube playlist URL.
|
||||
"""
|
||||
if self.url and "playlist?list=" in self.url:
|
||||
return True
|
||||
return False
|
||||
|
||||
def process_playlist(self):
|
||||
"""
|
||||
Processes all videos in a YouTube playlist.
|
||||
"""
|
||||
self.logger.debug(f"Querying playlist metadata from YouTube, assuming consistent artist {self.artist}...")
|
||||
persistent_artist = self.artist
|
||||
with yt_dlp.YoutubeDL({"quiet": True}) as ydl:
|
||||
result = ydl.extract_info(self.url, download=False)
|
||||
if "entries" in result:
|
||||
track_results = []
|
||||
self.logger.info(f"Found {len(result['entries'])} videos in playlist, processing each invididually...")
|
||||
for video in result["entries"]:
|
||||
video_url = f"https://www.youtube.com/watch?v={video['id']}"
|
||||
self.logger.info(f"Processing video: {video_url}")
|
||||
self.url = video_url
|
||||
track_results.append(self.prep_single_track())
|
||||
self.artist = 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")
|
||||
return self.process_playlist()
|
||||
else:
|
||||
self.logger.info(f"Provided YouTube URL is NOT a playlist, processing single track")
|
||||
return [self.prep_single_track()]
|
||||
+83
-25
@@ -5,6 +5,11 @@ import pkg_resources
|
||||
from karaoke_prep import KaraokePrep
|
||||
|
||||
|
||||
def is_url(string):
|
||||
"""Simple check to determine if a string is a URL."""
|
||||
return string.startswith("http://") or string.startswith("https://")
|
||||
|
||||
|
||||
def main():
|
||||
logger = logging.getLogger(__name__)
|
||||
log_handler = logging.StreamHandler()
|
||||
@@ -14,12 +19,14 @@ 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("url", nargs="?", help="YouTube URL of the song to prep.", default=None)
|
||||
parser.add_argument("artist", nargs="?", help="Artist name for the song to prep.", default=None)
|
||||
parser.add_argument("title", nargs="?", help="Title of the song to prep.", default=None)
|
||||
parser.add_argument(
|
||||
"args",
|
||||
nargs="*",
|
||||
help="[YouTube video or playlist URL] [Artist] [Title] of song to prep. If URL is provided, Artist and Title are optional but increase chance of fetching the correct lyrics. If Artist and Title are provided with no URL, the top YouTube search result will be fetched.",
|
||||
)
|
||||
|
||||
package_version = pkg_resources.get_distribution("karaoke-prep").version
|
||||
parser.add_argument("-v", "--version", action="version", version=f"%(prog)s {package_version}")
|
||||
@@ -86,25 +93,70 @@ 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="#ff7acc",
|
||||
help="Optional: Font color for intro video artist text (default: #ff7acc). 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",
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
url, artist, title = None, None, None
|
||||
|
||||
# Allow 3 forms of positional arguments:
|
||||
# 1. URL only (may be single track URL or playlist URL)
|
||||
# 2. Artist and Title only
|
||||
# 3. URL, Artist, and Title
|
||||
if args.args and is_url(args.args[0]):
|
||||
url = args.args[0]
|
||||
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, both will be guessed from YouTube Title")
|
||||
|
||||
elif len(args.args) > 1:
|
||||
artist = args.args[0]
|
||||
title = args.args[1]
|
||||
logger.warn(f"No URL provided, the top YouTube search result for {artist} - {title} will be used.")
|
||||
else:
|
||||
parser.print_help()
|
||||
exit(1)
|
||||
|
||||
log_level = getattr(logging, args.log_level.upper())
|
||||
logger.setLevel(log_level)
|
||||
|
||||
if not hasattr(args, "artist") or not hasattr(args, "title"):
|
||||
if not args.url:
|
||||
parser.print_help()
|
||||
exit(1)
|
||||
else:
|
||||
# Proceed with only URL
|
||||
logger.info("Artist and title will be guessed from the provided URL.")
|
||||
|
||||
logger.info(f"KaraokePrep beginning with url: {args.url} artist: {args.artist} and title: {args.title}")
|
||||
logger.info(f"KaraokePrep beginning with url: {url} artist: {artist} and title: {title}")
|
||||
|
||||
kprep = KaraokePrep(
|
||||
artist=args.artist,
|
||||
title=args.title,
|
||||
url=args.url,
|
||||
artist=artist,
|
||||
title=title,
|
||||
url=url,
|
||||
log_formatter=log_formatter,
|
||||
log_level=log_level,
|
||||
model_name=args.model_name,
|
||||
@@ -116,20 +168,26 @@ 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,
|
||||
)
|
||||
|
||||
track = kprep.prep()
|
||||
tracks = kprep.process()
|
||||
|
||||
logger.info(f"Karaoke Prep complete! Output files:")
|
||||
|
||||
logger.info(f"")
|
||||
logger.info(f"Track: {track['artist']} - {track['title']}")
|
||||
logger.info(f" YouTube Video: {track['youtube_video']}")
|
||||
logger.info(f" YouTube Audio: {track['youtube_audio']}")
|
||||
logger.info(f" YouTube Still Image: {track['youtube_still_image']}")
|
||||
logger.info(f" Lyrics: {track['lyrics']}")
|
||||
logger.info(f" Instrumental: {track['instrumental_audio']}")
|
||||
logger.info(f" Vocals: {track['vocals_audio']}")
|
||||
for track in tracks:
|
||||
logger.info(f"")
|
||||
logger.info(f"Track: {track['artist']} - {track['title']}")
|
||||
logger.info(f" YouTube Video: {track['youtube_video']}")
|
||||
logger.info(f" YouTube Audio: {track['youtube_audio']}")
|
||||
logger.info(f" YouTube Still Image: {track['youtube_still_image']}")
|
||||
logger.info(f" Lyrics: {track['lyrics']}")
|
||||
logger.info(f" Instrumental: {track['instrumental_audio']}")
|
||||
logger.info(f" Vocals: {track['vocals_audio']}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Generated
+715
-460
File diff suppressed because it is too large.
Load diff
+2
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-prep"
|
||||
version = "0.3.0"
|
||||
version = "0.4.5"
|
||||
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"
|
||||
|
||||
Reference in new issue
Block a user