Compare commits

...
22 Commits
Author SHA1 Message Date
Andrew Beveridge 2d988de0a3 Fixed persistent artist bug 2023-12-19 14:47:11 -06:00
Andrew Beveridge 6a6154fe44 Improved robustness of title screen rendering 2023-12-18 14:57:58 -06:00
Andrew Beveridge f3ebaf5858 Improved title screen generation, though still not perfect 2023-12-18 14:41:19 -06:00
Andrew Beveridge 10554f19ee Added persistent artist and updated readme 2023-12-18 00:49:29 -06:00
Andrew Beveridge ff90b72a34 Added more robust font size calculation with padding to ensure title screen text fits, added support for passing through artist when fetching all tracks in playlist 2023-12-18 00:41:37 -06:00
Andrew Beveridge 1e8a23ad50 Bumped version 2023-12-18 00:14:07 -06:00
Andrew Beveridge 9fbe04ecf8 Added pillow to dependencies to ensure latest version is used in package 2023-12-18 00:13:39 -06:00
Andrew Beveridge 224a9cfd57 Tidied help output 2023-12-18 00:02:57 -06:00
Andrew Beveridge 9f8a6edab3 Removed unnecessary moviepy dep 2023-12-18 00:01:33 -06:00
Andrew Beveridge 4bd2d121ae Fixed accidental return 2023-12-17 23:42:44 -06:00
Andrew Beveridge 5a1095556c Modified intro screen generation to use ffmpeg for speed 2023-12-17 23:41:57 -06:00
Andrew Beveridge 5877b9b8da Added initial attempt at getting intro video rendering working using moviepy 2023-12-17 23:16:26 -06:00
Andrew Beveridge bcc1196152 Added support for prepping whole playlists, made URL and artist/title optional, lazy-load separator module for faster loading 2023-12-17 20:03:45 -06:00
Andrew Beveridge 6c93bf3e50 Made artist and title optional, if omitted are guessed from title 2023-12-17 18:59:08 -06:00
Andrew Beveridge 292aa75d5d Added output video and still image extracted from video 2023-12-17 18:33:20 -06:00
Andrew Beveridge cdc4330873 Fixed output filename extension 2023-10-19 00:28:49 -05:00
Andrew Beveridge 36a34000c3 Added output format debug 2023-10-19 00:24:29 -05:00
Andrew Beveridge 0851d938a5 Fixed cli param 2023-10-18 23:38:36 -05:00
Andrew Beveridge 4f98a6d286 Updated default output format to MP3 2023-10-18 11:31:11 -05:00
Andrew Beveridge d0712cc4be Fixed output dir to use track-specific subfolder by default 2023-10-18 11:26:34 -05:00
Andrew Beveridge 0dc30a442c Bumped version for release
gp
2023-10-09 16:42:18 -05:00
Andrew Beveridge 88ac617c5f Removed restrictive version req, bumped deps 2023-10-09 16:35:28 -05:00
8 changed files with 1448 additions and 807 deletions

No files matched your search

Binary file not shown.
+40 -8
View File
@@ -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
@@ -52,18 +52,50 @@ 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
--create_track_subfolders Optional: create subfolders in the output folder for each track (default: False). Example: --create_track_subfolders=true
--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
```
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
@@ -76,7 +108,7 @@ By default, you'll end up with files in the current folder, neatly organised e.g
## Requirements 📋
Python <= 3.10 (one of the dependencies doesn't like 3.11 yet)
Python >= 3.9
Libraries: onnx, onnxruntime, numpy, soundfile, librosa, torch, wget, six
+1 -1
View File
@@ -1 +1 @@
from .requests_prep import KaraokePrep
from .karaoke_prep import KaraokePrep
+475
View File
@@ -0,0 +1,475 @@
import os
import re
import glob
import yt_dlp
import logging
import lyricsgenius
import subprocess
from PIL import Image, ImageDraw, ImageFont
class KaraokePrep:
def __init__(
self,
url=None,
artist=None,
title=None,
log_level=logging.DEBUG,
log_formatter=None,
model_name="UVR_MDXNET_KARA_2",
model_name_2="UVR-MDX-NET-Inst_HQ_3",
model_file_dir="/tmp/audio-separator-models/",
output_dir=".",
output_format="WAV",
use_cuda=False,
use_coreml=False,
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)
self.log_level = log_level
self.log_formatter = log_formatter
self.log_handler = logging.StreamHandler()
if self.log_formatter is None:
self.log_formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(module)s - %(message)s")
self.log_handler.setFormatter(self.log_formatter)
self.logger.addHandler(self.log_handler)
self.logger.debug(f"KaraokePrep instantiating with url: {url} artist: {artist} title: {title}")
self.url = url
self.artist = artist
self.title = title
self.model_name = model_name
self.model_name_2 = model_name_2
self.model_file_dir = model_file_dir
self.output_dir = output_dir
self.output_format = output_format
self.use_cuda = use_cuda
self.use_coreml = use_coreml
self.normalization_enabled = normalization_enabled
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.persistent_artist = None
self.logger.debug(f"KaraokePrep output_format: {self.output_format}")
if not os.path.exists(self.output_dir):
self.logger.debug(f"Overall output dir {self.output_dir} did not exist, creating")
os.makedirs(self.output_dir)
else:
self.logger.debug(f"Overall output dir {self.output_dir} already exists")
def extract_metadata_from_url(self):
"""
Extracts metadata from the YouTube URL.
"""
if self.url:
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:
self.logger.error("Failed to extract artist and title from the YouTube URL.")
def parse_metadata(self, info):
"""
Parses the metadata to extract artist and title.
:param info: The metadata information extracted from yt_dlp.
:return: A tuple containing the artist and title.
"""
# Default values if parsing fails
artist = ""
title = ""
# Example: "Artist - Title"
if "title" in info and "-" in info["title"]:
artist, title = info["title"].split("-", 1)
artist = artist.strip()
title = title.strip()
elif "uploader" in info:
# Fallback to uploader as artist if title parsing fails
artist = info["uploader"]
if "title" in info:
title = info["title"].strip()
# If unable to parse, log an appropriate message
if not artist or not title:
self.logger.warning("Could not parse artist and title from the video metadata.")
return artist, title
def get_youtube_id_for_top_search_result(self, query):
ydl_opts = {"quiet": "True", "format": "bestaudio", "noplaylist": "True", "extract_flat": True}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
video = ydl.extract_info(f"ytsearch1:{query}", download=False)["entries"][0]
if video:
youtube_id = video.get("id")
return youtube_id
else:
self.logger.warning(f"No YouTube results found for query: {query}")
return None
def download_video(self, youtube_id, output_filename_no_extension):
self.logger.debug(f"Downloading YouTube video {youtube_id} to filename {output_filename_no_extension} + (as yet) unknown extension")
ydl_opts = {
"format": "bv*+ba/b", # if a combined video + audio format is better than the best video-only format use the combined format
"outtmpl": f"{output_filename_no_extension}",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",
}
with yt_dlp.YoutubeDL(ydl_opts) as youtube_dl_instance:
youtube_dl_instance.download([f"https://www.youtube.com/watch?v={youtube_id}"])
self.logger.warn(f"Download finished, assuming hard-coded webm extension (!) and returning this filename")
# TODO: Replace hard-coded webm extension with the actual extension of the downloaded file using yt-dlp hooks / event callback
return output_filename_no_extension + ".webm"
def extract_still_image_from_video(self, input_filename, output_filename_no_extension):
output_filename = output_filename_no_extension + ".png"
self.logger.debug(f"Extracting still image from position 30s YouTube video to {output_filename}")
os.system(f'ffmpeg -i "{input_filename}" -ss 00:00:30 -vframes 1 "{output_filename}"')
return output_filename
def convert_to_wav(self, input_filename, output_filename_no_extension):
output_filename = output_filename_no_extension + ".wav"
self.logger.debug(f"Converting {input_filename} to WAV file {output_filename}")
os.system(f'ffmpeg -i "{input_filename}" "{output_filename}"')
return output_filename
def write_lyrics_from_genius(self, artist, title, filename):
genius = lyricsgenius.Genius(os.environ["GENIUS_API_TOKEN"])
song = genius.search_song(title, artist)
if song:
lyrics = self.clean_genius_lyrics(song.lyrics)
with open(filename, "w") as f:
f.write(lyrics)
self.logger.info("Lyrics for %s by %s fetched successfully", title, artist)
else:
self.logger.warning("Could not find lyrics for %s by %s", title, artist)
def clean_genius_lyrics(self, lyrics):
lyrics = lyrics.replace("\\n", "\n")
lyrics = re.sub(r"You might also like", "", lyrics)
lyrics = re.sub(
r".*?Lyrics([A-Z])", r"\1", lyrics
) # Remove the song name and word "Lyrics" if this has a non-newline char at the start
lyrics = re.sub(r"[0-9]+Embed$", "", lyrics) # Remove the word "Embed" at end of line with preceding numbers if found
lyrics = re.sub(r"(\S)Embed$", r"\1", lyrics) # Remove the word "Embed" if it has been tacked onto a word at the end of a line
lyrics = re.sub(r"^Embed$", r"", lyrics) # Remove the word "Embed" if it has been tacked onto a word at the end of a line
lyrics = re.sub(r".*?\[.*?\].*?", "", lyrics) # Remove lines containing square brackets
# add any additional cleaning rules here
return lyrics
def sanitize_filename(self, filename):
"""Replace or remove characters that are unsafe for filenames."""
# Replace problematic characters with underscores
for char in ["\\", "/", ":", "*", "?", '"', "<", ">", "|"]:
filename = filename.replace(char, "_")
# Remove any trailing periods or spaces
filename = filename.rstrip(". ")
return filename
def separate_audio(self, audio_file, model_name, instrumental_path, vocals_path):
if audio_file is None or not os.path.isfile(audio_file):
raise Exception("Error: Invalid audio source provided.")
self.logger.debug(f"audio_file is valid file: {audio_file}")
self.logger.debug(
f"instantiating Separator with model_name: {model_name} instrumental_path: {instrumental_path} and output_format: {self.output_format}"
)
from audio_separator import Separator
separator = Separator(
audio_file,
log_level=self.log_level,
log_formatter=self.log_formatter,
model_name=model_name,
model_file_dir=self.model_file_dir,
output_format=self.output_format,
primary_stem_path=instrumental_path,
secondary_stem_path=vocals_path,
)
_, _ = separator.separate()
self.logger.debug(f"Separation complete!")
def setup_output_paths(self, artist, title):
sanitized_artist = self.sanitize_filename(artist)
sanitized_title = self.sanitize_filename(title)
artist_title = f"{sanitized_artist} - {sanitized_title}"
track_output_dir = self.output_dir
if self.create_track_subfolders:
track_output_dir = os.path.join(self.output_dir, f"{artist_title}")
if not os.path.exists(track_output_dir):
self.logger.debug(f"Output dir {track_output_dir} did not exist, creating")
os.makedirs(track_output_dir)
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...")
self.extract_metadata_from_url()
artist = self.artist
title = self.title
self.logger.info(f"Downloading inputs for track: {title} by {artist}")
track_output_dir, artist_title = self.setup_output_paths(artist, title)
processed_track = {
"track_output_dir": track_output_dir,
"artist": artist,
"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)
yt_png_filename_pattern = os.path.join(track_output_dir, f"{artist_title} (YouTube *.png")
yt_png_glob = glob.glob(yt_png_filename_pattern)
yt_wav_filename_pattern = os.path.join(track_output_dir, f"{artist_title} (YouTube *.wav")
yt_wav_glob = glob.glob(yt_wav_filename_pattern)
processed_track["youtube_video"] = None
processed_track["youtube_still_image"] = None
processed_track["youtube_audio"] = None
if yt_webm_glob and yt_png_glob and yt_wav_glob:
processed_track["youtube_video"] = yt_webm_glob[0]
processed_track["youtube_still_image"] = yt_png_glob[0]
processed_track["youtube_audio"] = yt_wav_glob[0]
self.logger.debug(f"YouTube output files already exist, skipping download: {processed_track['youtube_video']} + .wav + .png")
else:
if self.url is None:
self.logger.warn(f"No URL specified - the top result from YouTube will be used.")
self.logger.info("Searching YouTube for video ID...")
query = f"{artist} {title}"
youtube_id = self.get_youtube_id_for_top_search_result(query)
else:
self.logger.info("Parsing YouTube video ID from URL...")
youtube_id = self.url.split("watch?v=")[1]
if youtube_id:
output_filename_no_extension = os.path.join(track_output_dir, f"{artist_title} (YouTube {youtube_id})")
self.logger.info("Downloading original video from YouTube...")
processed_track["youtube_video"] = self.download_video(youtube_id, output_filename_no_extension)
self.logger.info("Extracting still image from downloaded video...")
processed_track["youtube_still_image"] = self.extract_still_image_from_video(
processed_track["youtube_video"], output_filename_no_extension
)
self.logger.info("Converting downloaded video to WAV for audio processing...")
processed_track["youtube_audio"] = self.convert_to_wav(processed_track["youtube_video"], output_filename_no_extension)
else:
self.logger.warning(f"Skipping {title} by {artist} due to missing YouTube ID.")
lyrics_file = os.path.join(track_output_dir, f"{artist_title} (Lyrics).txt")
if os.path.exists(lyrics_file):
self.logger.debug(f"Lyrics file already exists, skipping fetch: {lyrics_file}")
else:
self.logger.info("Fetching lyrics from Genius...")
self.write_lyrics_from_genius(artist, title, lyrics_file)
processed_track["lyrics"] = lyrics_file
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}")
vocals_path = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name}).{self.output_format}")
if os.path.isfile(instrumental_path) and os.path.isfile(vocals_path):
self.logger.debug(f"Separated audio files already exist in output paths, skipping separation: {instrumental_path}")
else:
self.separate_audio(processed_track["youtube_audio"], self.model_name, instrumental_path, vocals_path)
processed_track["instrumental_audio"] = instrumental_path
processed_track["vocals_audio"] = vocals_path
instrumental_path_2 = os.path.join(track_output_dir, f"{artist_title} (Instrumental {self.model_name_2}).{self.output_format}")
vocals_path_2 = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name_2}).{self.output_format}")
if os.path.isfile(instrumental_path_2) and os.path.isfile(vocals_path_2):
self.logger.debug(f"Separated audio files already exist in output paths, skipping separation: {instrumental_path_2}")
else:
self.separate_audio(processed_track["youtube_audio"], self.model_name_2, instrumental_path_2, vocals_path_2)
processed_track["instrumental_audio_2"] = instrumental_path_2
processed_track["vocals_audio_2"] = vocals_path_2
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}...")
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 = self.persistent_artist
self.title = None
return track_results
def process(self):
if self.is_playlist_url():
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")
return [self.prep_single_track()]
-241
View File
@@ -1,241 +0,0 @@
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
class KaraokePrep:
def __init__(
self,
url=None,
artist=None,
title=None,
log_level=logging.DEBUG,
log_formatter=None,
model_name="UVR_MDXNET_KARA_2",
model_name_2="UVR-MDX-NET-Inst_HQ_3",
model_file_dir="/tmp/audio-separator-models/",
output_dir="karaoke",
use_cuda=False,
use_coreml=False,
normalization_enabled=True,
denoise_enabled=True,
create_track_subfolders=False,
):
self.logger = logging.getLogger(__name__)
self.logger.setLevel(log_level)
self.log_level = log_level
self.log_formatter = log_formatter
self.log_handler = logging.StreamHandler()
if self.log_formatter is None:
self.log_formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(module)s - %(message)s")
self.log_handler.setFormatter(self.log_formatter)
self.logger.addHandler(self.log_handler)
self.logger.debug(f"KaraokePrep instantiating with url: {url} artist: {artist} title: {title}")
self.url = url
self.artist = artist
self.title = title
self.model_name = model_name
self.model_name_2 = model_name_2
self.model_file_dir = model_file_dir
self.output_dir = output_dir
self.use_cuda = use_cuda
self.use_coreml = use_coreml
self.normalization_enabled = normalization_enabled
self.denoise_enabled = denoise_enabled
self.create_track_subfolders = create_track_subfolders
if not os.path.exists(self.output_dir):
self.logger.debug(f"Overall output dir {self.output_dir} did not exist, creating")
os.makedirs(self.output_dir)
else:
self.logger.debug(f"Overall output dir {self.output_dir} already exists")
if artist is None or title is None:
raise Exception("Error: You must provide an artist and title.")
def get_youtube_id_for_top_search_result(self, query):
ydl_opts = {"quiet": "True", "format": "bestaudio", "noplaylist": "True", "extract_flat": True}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
video = ydl.extract_info(f"ytsearch1:{query}", download=False)["entries"][0]
if video:
youtube_id = video.get("id")
return youtube_id
else:
self.logger.warning(f"No YouTube results found for query: {query}")
return None
def download_audio(self, youtube_id, filename):
ydl_opts = {
"format": "ba",
"postprocessors": [
{
"key": "FFmpegExtractAudio",
"preferredcodec": "wav",
"preferredquality": "192",
}
],
"outtmpl": f"{filename}",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",
}
with yt_dlp.YoutubeDL(ydl_opts) as youtube_dl_instance:
youtube_dl_instance.download([f"https://www.youtube.com/watch?v={youtube_id}"])
def write_lyrics_from_genius(self, artist, title, filename):
genius = lyricsgenius.Genius(os.environ["GENIUS_API_TOKEN"])
song = genius.search_song(title, artist)
if song:
lyrics = self.clean_genius_lyrics(song.lyrics)
with open(filename, "w") as f:
f.write(lyrics)
self.logger.info("Lyrics for %s by %s fetched successfully", title, artist)
else:
self.logger.warning("Could not find lyrics for %s by %s", title, artist)
def clean_genius_lyrics(self, lyrics):
lyrics = lyrics.replace("\\n", "\n")
lyrics = re.sub(r"You might also like", "", lyrics)
lyrics = re.sub(
r".*?Lyrics([A-Z])", r"\1", lyrics
) # Remove the song name and word "Lyrics" if this has a non-newline char at the start
lyrics = re.sub(r"[0-9]+Embed$", "", lyrics) # Remove the word "Embed" at end of line with preceding numbers if found
lyrics = re.sub(r"(\S)Embed$", r"\1", lyrics) # Remove the word "Embed" if it has been tacked onto a word at the end of a line
lyrics = re.sub(r"^Embed$", r"", lyrics) # Remove the word "Embed" if it has been tacked onto a word at the end of a line
lyrics = re.sub(r".*?\[.*?\].*?", "", lyrics) # Remove lines containing square brackets
# add any additional cleaning rules here
return lyrics
def sanitize_filename(self, filename):
"""Replace or remove characters that are unsafe for filenames."""
# Replace problematic characters with underscores
for char in ["\\", "/", ":", "*", "?", '"', "<", ">", "|"]:
filename = filename.replace(char, "_")
# Remove any trailing periods or spaces
filename = filename.rstrip(". ")
return filename
def separate_audio(self, audio_file, model_name, instrumental_path, vocals_path):
if audio_file is None or not os.path.isfile(audio_file):
raise Exception("Error: Invalid audio source provided.")
self.logger.debug(f"audio_file is valid file: {audio_file}")
self.logger.debug(f"instantiating Separator with model_name: {model_name} and instrumental_path: {instrumental_path}")
separator = Separator(
audio_file,
log_level=self.log_level,
log_formatter=self.log_formatter,
model_name=model_name,
model_file_dir=self.model_file_dir,
output_format="FLAC",
primary_stem_path=instrumental_path,
secondary_stem_path=vocals_path,
)
_, _ = separator.separate()
self.logger.debug(f"Separation complete!")
def setup_output_paths(self, artist, title):
sanitized_artist = self.sanitize_filename(artist)
sanitized_title = self.sanitize_filename(title)
artist_title = f"{sanitized_artist} - {sanitized_title}"
track_output_dir = self.output_dir
if self.create_track_subfolders:
track_output_dir = os.path.join(self.output_dir, f"{artist_title}")
if not os.path.exists(track_output_dir):
self.logger.debug(f"Output dir {track_output_dir} did not exist, creating")
os.makedirs(track_output_dir)
return track_output_dir, artist_title
def prep(self):
artist = self.artist
title = self.title
self.logger.info(f"Downloading inputs for track: {title} by {artist}")
track_output_dir, artist_title = self.setup_output_paths(artist, title)
processed_track = {
"track_output_dir": track_output_dir,
"artist": artist,
"title": title,
}
yt_filename_pattern = os.path.join(track_output_dir, f"{artist_title} (YouTube *.wav")
youtube_audio_files = glob.glob(yt_filename_pattern)
youtube_audio_file = None
if youtube_audio_files:
youtube_audio_file = youtube_audio_files[0]
self.logger.debug(f"Youtube audio already exists, skipping download: {youtube_audio_file}")
else:
if self.url is None:
self.logger.warn(f"No URL specified - the top result from YouTube will be used.")
self.logger.info("Searching YouTube for video ID...")
query = f"{artist} {title}"
youtube_id = self.get_youtube_id_for_top_search_result(query)
else:
self.logger.info("Parsing YouTube video ID from URL...")
youtube_id = self.url.split("watch?v=")[1]
if youtube_id:
youtube_audio_file = os.path.join(track_output_dir, f"{artist_title} (YouTube {youtube_id})")
self.logger.info("Downloading original audio from YouTube to filename {original_audio_filename}")
self.download_audio(youtube_id, youtube_audio_file)
youtube_audio_file = youtube_audio_file + ".wav"
else:
self.logger.warning(f"Skipping {title} by {artist} due to missing YouTube ID.")
processed_track["youtube_audio"] = youtube_audio_file
lyrics_file = os.path.join(track_output_dir, f"{artist_title} (Lyrics).txt")
if os.path.exists(lyrics_file):
self.logger.debug(f"Lyrics file already exists, skipping fetch: {lyrics_file}")
else:
self.logger.info("Fetching lyrics from Genius...")
self.write_lyrics_from_genius(artist, title, lyrics_file)
processed_track["lyrics"] = lyrics_file
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}).flac")
vocals_path = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name}).flac")
if os.path.isfile(instrumental_path) and os.path.isfile(vocals_path):
self.logger.debug(f"Separated audio files already exist in output paths, skipping separation: {instrumental_path}")
else:
self.separate_audio(processed_track["youtube_audio"], self.model_name, instrumental_path, vocals_path)
processed_track["instrumental_audio"] = instrumental_path
processed_track["vocals_audio"] = vocals_path
instrumental_path_2 = os.path.join(track_output_dir, f"{artist_title} (Instrumental {self.model_name_2}).flac")
vocals_path_2 = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name_2}).flac")
if os.path.isfile(instrumental_path_2) and os.path.isfile(vocals_path_2):
self.logger.debug(f"Separated audio files already exist in output paths, skipping separation: {instrumental_path_2}")
else:
self.separate_audio(processed_track["youtube_audio"], self.model_name_2, instrumental_path_2, vocals_path_2)
processed_track["instrumental_audio_2"] = instrumental_path_2
processed_track["vocals_audio_2"] = vocals_path_2
self.logger.info("Script finished, audio downloaded, lyrics fetched and audio separated!")
return processed_track
+95 -24
View File
@@ -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("artist", nargs="?", help="Artist name for the song to prep.", default=argparse.SUPPRESS)
parser.add_argument("title", nargs="?", help="Title of the song to prep.", default=argparse.SUPPRESS)
parser.add_argument("url", nargs="?", help="YouTube URL 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}")
@@ -44,8 +51,14 @@ def main():
parser.add_argument(
"--output_dir",
default="karaoke",
help="Optional: directory to write output files (default: <current dir>/karaoke). Example: --output_dir=/app/karaoke",
default=".",
help="Optional: directory to write output files (default: <current dir>). Example: --output_dir=/app/karaoke",
)
parser.add_argument(
"--output_format",
default="MP3",
help="Optional: output format for separated audio (default: MP3). Example: --output_format=FLAC",
)
parser.add_argument(
@@ -75,48 +88,106 @@ def main():
)
parser.add_argument(
"--create_track_subfolders",
action="store_true",
help="Optional: create subfolders in the output folder for each track (default: %(default)s). Example: --create_track_subfolders=true",
"--no_track_subfolders",
action="store_false",
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()
log_level = getattr(logging, args.log_level.upper())
logger.setLevel(log_level)
url, artist, title = None, None, None
if not hasattr(args, "artist") or not hasattr(args, "title"):
# 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)
logger.info(f"KaraokePrep beginning with artist: {args.artist} and title: {args.title} and url: {args.url}")
log_level = getattr(logging, args.log_level.upper())
logger.setLevel(log_level)
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,
model_file_dir=args.model_file_dir,
output_dir=args.output_dir,
output_format=args.output_format,
use_cuda=args.use_cuda,
use_coreml=args.use_coreml,
normalization_enabled=args.normalize,
denoise_enabled=args.denoise,
create_track_subfolders=args.create_track_subfolders,
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 Audio: {track['youtube_audio']}")
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
+832 -529
View File
File diff suppressed because it is too large. Load diff
+5 -4
View File
@@ -1,7 +1,7 @@
[tool.poetry]
name = "karaoke-prep"
version = "0.1.2"
description = "Prepare for karaoke video creation, by downloading audio and lyrics for a specified song."
version = "0.4.9"
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"
readme = "README.md"
@@ -11,13 +11,14 @@ 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.11"
python = ">=3.9"
requests = "^2"
beautifulsoup4 = "^4"
yt-dlp = "*"
lyricsgenius = "^3"
fetch-lyrics-from-genius = "^0.1"
audio-separator = "^0.7"
audio-separator = "^0.8"
pillow = "^10.1.0"
[tool.poetry.group.dev.dependencies]
black = "^23"