Compare commits

...
43 Commits
Author SHA1 Message Date
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
Andrew Beveridge ee634ae70a Updated separator to latest to use mel roformer by default 2024-05-25 00:24:09 -04:00
Andrew Beveridge 06b670e62f Updated final mp4 render to use concat filter instead of demuxer which is buggy 2024-04-24 23:19:11 -04:00
Andrew Beveridge 008c09a72e Added folder processing with filename track and title pattern extraction and a dry run mode for easier bulk processing of local files 2024-04-01 17:21:17 -05:00
Andrew Beveridge 0587334eec Modified default models to remove buggy / resource hog HP9 2024-03-28 14:05:24 -05:00
Andrew Beveridge b3319774c2 Fixed audio-separator instantiation to work with latest version 2024-03-28 14:02:36 -05:00
Andrew Beveridge 6306c274cc Updated default models to use newer models 2024-03-24 00:10:21 -05:00
Andrew Beveridge f2bf347234 Updated to latest audio-separator 2024-03-23 22:23:04 -05:00
Andrew Beveridge e225dfcefc Updated to latest audio-separator, added additional default model to CLI 2024-03-02 23:25:39 -05:00
Andrew Beveridge d4ff5878a7 Fixed bug with artist and title only usage 2024-02-09 11:44:36 -05:00
Andrew Beveridge 8d11222f82 Updated to latest audio-separator, added support for multiple models 2024-02-06 23:27:21 -06:00
Andrew Beveridge ☄️ 010632d919 Added PyTorch CUDA instructions to README.md 2024-01-29 11:31:10 -05:00
Andrew Beveridge 299444c3e3 Updated install docs 2024-01-29 10:59:01 -05:00
Andrew Beveridge 6be2e9908f Tweaked logging 2024-01-28 13:31:00 -05:00
Andrew Beveridge d28595e273 Improved instrumental matching logic 2024-01-28 11:52:24 -05:00
Andrew Beveridge 13b3ad1b76 Fixed check for existing video, improved instrumental selection, updated deps 2024-01-28 11:29:08 -05:00
Andrew Beveridge a43cd39186 Added truncation to youtube title to handle long names 2024-01-22 12:35:14 -06:00
Andrew Beveridge e65b7d5c0a Fixed escaping for ffmpeg concat with quotes in filenames 2024-01-22 11:17:45 -06:00
Andrew Beveridge fe354fbad9 Fixed bug with output info 2024-01-22 01:06:58 -06:00
Andrew Beveridge 7d0fcfb33d Added support for local media file as input, not only URLs 2024-01-22 01:02:49 -06:00
Andrew Beveridge da594bdcd1 Added better error handling and user prompted overwrites to allow re-running more easily in case an error occurs 2024-01-21 23:31:19 -06:00
Andrew Beveridge 88eb6717c9 Fixed various bugs, improved log output for new functions 2024-01-21 22:15:06 -06:00
Andrew Beveridge 402aabe960 Bumped version to reflect recent refactoring and improvements 2024-01-21 21:20:10 -06:00
Andrew Beveridge f7fcf49954 Refactored more to break up process further and improve consistency in user input handling 2024-01-21 21:19:27 -06:00
Andrew Beveridge 3da47b69bc Refactored finalise class to split up into more testable functions 2024-01-21 19:46:33 -06:00
Andrew Beveridge e8165149dd Added exclusion of hidden files (e.g. .DS_Store) to rclone 2024-01-21 01:55:16 -06:00
7 changed files with 2846 additions and 1413 deletions

No files matched your search

+27
View File
@@ -21,10 +21,36 @@ This was created to make it easier for me to prepare the source audio, lyrics an
## Installation 🛠️
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`
You'll then also need to install a version of `audio-separator` for your hardware:
- Mac with Apple Silicon: `pip install audio-separator[silicon]`
- Linux/Windows with CUDA GPU: `pip install audio-separator[gpu]`
- Anything else: `pip install audio-separator[cpu]`
#### Install PyTorch with CUDA support
If you're trying to use CUDA for GPU acceleration, you'll also need to ensure the version of PyTorch you have installed is compatible with the CUDA version you have installed.
While PyTorch should get installed as a dependency of `karaoke-prep` anyway, you may need to install PyTorch for your CUDA version by running the installation command provided by the official install wizard: https://pytorch.org/get-started/locally/
#### UnicodeEncodeError
If you encounter this error: `UnicodeEncodeError: 'charmap' codec can't encode character`
Try setting the Python I/O encoding in your environment: `export PYTHONIOENCODING=utf-8`
#### Command-line newbie?
If you aren't sure what `pip` is or how to use the command line, here are some YouTube tutorials which will probably help:
- Install Python on Windows: https://www.youtube.com/watch?v=YKSpANU8jPE
@@ -34,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`
+636 -204
View File
@@ -1,12 +1,15 @@
import os
import sys
import subprocess
import tempfile
import json
import shlex
import logging
import zipfile
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
@@ -19,15 +22,18 @@ class KaraokeFinalise:
log_level=logging.DEBUG,
log_formatter=None,
dry_run=False,
force=False,
model_name="UVR_MDXNET_KARA_2",
model_name=None,
instrumental_format="flac",
enable_cdg=False,
enable_txt=False,
brand_prefix=None,
target_dir=None,
organised_dir=None,
public_share_dir=None,
youtube_client_secrets_file=None,
youtube_description_file=None,
rclone_destination=None,
discord_webhook_url=None,
non_interactive=False,
):
self.logger = logging.getLogger(__name__)
self.logger.setLevel(log_level)
@@ -43,7 +49,7 @@ class KaraokeFinalise:
self.logger.addHandler(self.log_handler)
self.logger.debug(
f"KaraokeFinalise instantiating, dry_run: {dry_run}, model_name: {model_name}, force: {force}, brand_prefix: {brand_prefix}, target_dir: {target_dir}, public_share_dir: {public_share_dir}, rclone_destination: {rclone_destination}"
f"KaraokeFinalise instantiating, dry_run: {dry_run}, model_name: {model_name}, brand_prefix: {brand_prefix}, organised_dir: {organised_dir}, public_share_dir: {public_share_dir}, rclone_destination: {rclone_destination}"
)
# Path to the Windows PyInstaller frozen bundled ffmpeg.exe, or the system-installed FFmpeg binary on Mac/Linux
@@ -57,16 +63,198 @@ class KaraokeFinalise:
self.ffmpeg_base_command += " -loglevel fatal"
self.dry_run = dry_run
self.force = force
self.model_name = model_name
self.instrumental_format = instrumental_format
self.brand_prefix = brand_prefix
self.target_dir = target_dir
self.organised_dir = organised_dir
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
self.folder_organisation_enabled = False
self.public_share_copy_enabled = False
self.public_share_rclone_enabled = False
self.skip_notifications = False
self
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",
"final_karaoke_mp4": " (Final Karaoke).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_path = None
def check_input_files_exist(self, base_name, with_vocals_file, instrumental_audio_file):
self.logger.info(f"Checking required input files exist...")
input_files = {
"title_mov": f"{base_name}{self.suffixes['title_mov']}",
"title_jpg": f"{base_name}{self.suffixes['title_jpg']}",
"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:
input_files["karaoke_cdg"] = f"{base_name}{self.suffixes['karaoke_cdg']}"
input_files["karaoke_mp3"] = f"{base_name}{self.suffixes['karaoke_mp3']}"
if self.enable_txt:
input_files["karaoke_mp3"] = f"{base_name}{self.suffixes['karaoke_mp3']}"
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):
output_files = {
"karaoke_mov": f"{base_name}{self.suffixes['karaoke_mov']}",
"with_vocals_mp4": f"{base_name}{self.suffixes['with_vocals_mp4']}",
"final_karaoke_mp4": f"{base_name}{self.suffixes['final_karaoke_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:
accept_responses.append("")
print()
response = input(f"{prompt_message} {options_string} ").strip().lower()
return response in accept_responses
def validate_input_parameters_for_features(self):
self.logger.info(f"Validating input parameters for enabled features...")
current_directory = os.getcwd()
self.logger.info(f"Current directory to process: {current_directory}")
# Enable youtube upload if client secrets file is provided and is valid JSON
if self.youtube_client_secrets_file is not None and self.youtube_description_file is not None:
if not os.path.isfile(self.youtube_client_secrets_file):
raise Exception(f"YouTube client secrets file does not exist: {self.youtube_client_secrets_file}")
if not os.path.isfile(self.youtube_description_file):
raise Exception(f"YouTube description file does not exist: {self.youtube_description_file}")
# Test parsing the file as JSON to check it's valid
try:
with open(self.youtube_client_secrets_file, "r") as f:
json.load(f)
except json.JSONDecodeError as e:
raise Exception(f"YouTube client secrets file is not valid JSON: {self.youtube_client_secrets_file}") from e
self.logger.debug(f"YouTube upload checks passed, enabling YouTube upload")
self.youtube_upload_enabled = True
# Enable discord notifications if webhook URL is provided and is valid URL
if self.discord_webhook_url is not None:
if not self.discord_webhook_url.startswith("https://discord.com/api/webhooks/"):
raise Exception(f"Discord webhook URL is not valid: {self.discord_webhook_url}")
self.logger.debug(f"Discord webhook URL checks passed, enabling Discord notifications")
self.discord_notication_enabled = True
# Enable folder organisation if brand prefix and target directory are provided and target directory is valid
if self.brand_prefix is not None and self.organised_dir is not None:
if not os.path.isdir(self.organised_dir):
raise Exception(f"Target directory does not exist: {self.organised_dir}")
self.logger.debug(f"Brand prefix and target directory provided, enabling folder organisation")
self.folder_organisation_enabled = True
# Enable public share copy if public share directory is provided and is valid directory with MP4 and CDG subdirectories
if self.public_share_dir is not None:
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, "CDG")):
raise Exception(f"Public share directory does not contain CDG subdirectory: {self.public_share_dir}")
self.logger.debug(f"Public share directory checks passed, enabling public share copy")
self.public_share_copy_enabled = True
# Enable public share rclone if rclone destination is provided
if self.rclone_destination is not None:
self.logger.debug(f"Rclone destination provided, enabling rclone sync")
self.public_share_rclone_enabled = True
# 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}")
self.logger.info(f" Public share copy: {self.public_share_copy_enabled}")
self.logger.info(f" Public share rclone: {self.public_share_rclone_enabled}")
self.prompt_user_confirmation_or_raise_exception(
f"Confirm features enabled log messages above match your expectations for finalisation?",
"Refusing to proceed without user confirmation they're happy with enabled features.",
allow_empty=True,
)
def authenticate_youtube(self):
"""Authenticate and return a YouTube service object."""
@@ -84,7 +272,7 @@ class KaraokeFinalise:
credentials.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
self.youtube_client_secrets_file, scopes=["https://www.googleapis.com/auth/youtube.upload"]
self.youtube_client_secrets_file, scopes=["https://www.googleapis.com/auth/youtube"]
)
credentials = flow.run_local_server(port=0) # This will open a browser for authentication
@@ -94,254 +282,498 @@ class KaraokeFinalise:
return build("youtube", "v3", credentials=credentials)
def upload_to_youtube(self, video_file_path, thumbnail_file_path, title, description, category_id, keywords):
"""Upload video to YouTube and set thumbnail."""
def get_channel_id(self):
youtube = self.authenticate_youtube()
body = {
"snippet": {"title": title, "description": description, "tags": keywords, "categoryId": category_id},
"status": {"privacyStatus": "public"}, # or 'private' or 'unlisted'
}
# Use MediaFileUpload to handle the video file
media_file = MediaFileUpload(video_file_path, mimetype="video/mp4", resumable=True)
# Call the API's videos.insert method to create and upload the video.
request = youtube.videos().insert(part="snippet,status", body=body, media_body=media_file)
# Get the authenticated user's channel
request = youtube.channels().list(part="snippet", mine=True)
response = request.execute()
video_id = response.get("id")
self.logger.info(f"Uploaded video to YouTube: {video_id}")
# Extract the channel ID
if "items" in response:
channel_id = response["items"][0]["id"]
return channel_id
else:
return None
# Uploading the thumbnail
if thumbnail_file_path:
media_thumbnail = MediaFileUpload(thumbnail_file_path, mimetype="image/jpeg")
youtube.thumbnails().set(videoId=video_id, media_body=media_thumbnail).execute()
self.logger.info(f"Uploaded thumbnail for video ID {video_id}")
def check_if_video_title_exists_on_youtube_channel(self, youtube_title):
youtube = self.authenticate_youtube()
channel_id = self.get_channel_id()
def get_next_sequence_number(self):
self.logger.info(f"Searching YouTube channel {channel_id} for title: {youtube_title}")
request = youtube.search().list(part="snippet", channelId=channel_id, q=youtube_title, type="video", maxResults=10)
response = request.execute()
# Check if any videos were found
if "items" in response and len(response["items"]) > 0:
for item in response["items"]:
found_title = item["snippet"]["title"]
similarity_score = fuzz.ratio(youtube_title.lower(), found_title.lower())
if similarity_score >= 70: # 70% similarity
found_id = item["id"]["videoId"]
self.logger.info(
f"Potential match found on YouTube channel with ID: {found_id} and title: {found_title} (similarity: {similarity_score}%)"
)
confirmation = input(f"Is '{found_title}' the video you are finalising? (y/n): ").strip().lower()
if confirmation == "y":
self.youtube_video_id = found_id
self.youtube_url = f"{self.youtube_url_prefix}{self.youtube_video_id}"
self.skip_notifications = True
return True
self.logger.info(f"No matching video found with title: {youtube_title}")
return False
def truncate_to_nearest_word(self, title, max_length):
if len(title) <= max_length:
return title
truncated_title = title[:max_length].rsplit(" ", 1)[0]
if len(truncated_title) < max_length:
truncated_title += " ..."
return truncated_title
def upload_final_mp4_to_youtube_with_title_thumbnail(self, artist, title, input_files, output_files):
self.logger.info(f"Uploading final MP4 to YouTube with title thumbnail...")
if self.dry_run:
self.logger.info(
f'DRY RUN: Would upload {output_files["final_karaoke_mp4"]} to YouTube with thumbnail {input_files["title_jpg"]} using client secrets file: {self.youtube_client_secrets_file}'
)
else:
youtube_title = f"{artist} - {title} (Karaoke)"
# Truncate title to the nearest whole word and add ellipsis if needed
max_length = 95
youtube_title = self.truncate_to_nearest_word(youtube_title, max_length)
if self.check_if_video_title_exists_on_youtube_channel(youtube_title):
self.logger.warning(f"Video already exists on YouTube, skipping upload: {self.youtube_url}")
return
youtube_description = f"Karaoke version of {artist} - {title} created using karaoke-prep python package."
if self.youtube_description_file is not None:
with open(self.youtube_description_file, "r") as f:
youtube_description = f.read()
youtube_category_id = "10" # Category ID for Music
youtube_keywords = ["karaoke", "music", "singing", "instrumental", "lyrics", artist, title]
self.logger.info(f"Authenticating with YouTube...")
# Upload video to YouTube and set thumbnail.
youtube = self.authenticate_youtube()
body = {
"snippet": {
"title": youtube_title,
"description": youtube_description,
"tags": youtube_keywords,
"categoryId": youtube_category_id,
},
"status": {"privacyStatus": "public"},
}
# Use MediaFileUpload to handle the video file
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...")
request = youtube.videos().insert(part="snippet,status", body=body, media_body=media_file)
response = request.execute()
self.youtube_video_id = response.get("id")
self.youtube_url = f"{self.youtube_url_prefix}{self.youtube_video_id}"
self.logger.info(f"Uploaded video to YouTube: {self.youtube_url}")
# Uploading the thumbnail
if input_files["title_jpg"]:
media_thumbnail = MediaFileUpload(input_files["title_jpg"], mimetype="image/jpeg")
youtube.thumbnails().set(videoId=self.youtube_video_id, media_body=media_thumbnail).execute()
self.logger.info(f"Uploaded thumbnail for video ID {self.youtube_video_id}")
def get_next_brand_code(self):
"""
Calculate the next sequence number based on existing directories in the target_dir.
Calculate the next sequence number based on existing directories in the organised_dir.
Assumes directories are named with the format: BRAND-XXXX Artist - Title
"""
max_num = 0
pattern = re.compile(rf"^{re.escape(self.brand_prefix)}-(\d{{4}})")
if not os.path.isdir(self.target_dir):
self.logger.error(f"Target directory does not exist: {self.target_dir}")
return None
if not os.path.isdir(self.organised_dir):
raise Exception(f"Target directory does not exist: {self.organised_dir}")
for dir_name in os.listdir(self.target_dir):
for dir_name in os.listdir(self.organised_dir):
match = pattern.match(dir_name)
if match:
num = int(match.group(1))
max_num = max(max_num, num)
self.logger.info(f"Next sequence number for brand {self.brand_prefix} calculated as: {max_num + 1}")
return max_num + 1
next_seq_number = max_num + 1
def process(self):
tracks = []
return f"{self.brand_prefix}-{next_seq_number:04d}"
def post_discord_message(self, message, webhook_url):
"""Post a message to a Discord channel via webhook."""
data = {"content": message}
response = requests.post(webhook_url, json=data)
response.raise_for_status() # This will raise an exception if the request failed
self.logger.info("Message posted to Discord")
def find_with_vocals_file(self):
self.logger.info("Finding input file in current directory ending (With Vocals).mov or (With Vocals).mp4")
with_vocals_files = [f for f in os.listdir(".") if self.suffixes["with_vocals_mov"] in f]
if not with_vocals_files:
self.logger.info(f"No with vocals MOV file found, looking for with vocals MP4 file instead")
with_vocals_files = [f for f in os.listdir(".") if self.suffixes["with_vocals_mp4"] in f]
if with_vocals_files:
self.logger.info(f"Found with vocals MP4 file: {with_vocals_files[0]}")
return with_vocals_files[0]
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"])
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
else:
raise Exception("No suitable files found for processing.")
else:
return with_vocals_files[0] # Assuming only one such file is expected
def choose_instrumental_audio_file(self, base_name):
self.logger.info(f"Choosing instrumental audio file to use as karaoke audio...")
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"))
self.logger.debug(f"FLAC files found: {flac_files}")
self.logger.debug(f"MP3 files found: {mp3_files}")
# Filter out MP3 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)
]
self.logger.debug(f"Filtered instrumental files: {filtered_files}")
if not filtered_files:
raise Exception(f"No instrumental audio files found containing {search_string}")
if len(filtered_files) == 1:
return filtered_files[0]
# Sort the remaining instrumental options alphabetically
filtered_files.sort(reverse=True)
self.logger.info(f"Found multiple files containing {search_string}:")
for i, file in enumerate(filtered_files):
self.logger.info(f" {i+1}: {file}")
print()
response = input(f"Choose instrumental audio file to use as karaoke audio: [1]/{len(filtered_files)}: ").strip().lower()
if response == "":
response = "1"
try:
response = int(response)
except ValueError:
raise Exception(f"Invalid response to instrumental audio file choice prompt: {response}")
if response < 1 or response > len(filtered_files):
raise Exception(f"Invalid response to instrumental audio file choice prompt: {response}")
return filtered_files[response - 1]
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"], "").replace(self.suffixes["with_vocals_mp4"], "")
artist, title = base_name.split(" - ", 1)
return base_name, artist, title
def execute_command(self, command, description):
self.logger.info(description)
if self.dry_run:
self.logger.info(f"DRY RUN: Would run command: {command}")
else:
self.logger.info(f"Running command: {command}")
os.system(command)
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"]):
if not self.prompt_user_bool(
f"Found existing Final Karaoke output file: {output_files['final_karaoke_mp4']}. Overwrite (y) or skip (n)?",
):
self.logger.info(f"Skipping Karaoke MOV remux and Final MP4 render, 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"]}"'
self.execute_command(remux_ffmpeg_command, "Remuxing video with instrumental audio")
# 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 aac "{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)
# 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"]))
output_final_mp4_file = shlex.quote(output_files["final_karaoke_mp4"])
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]"'
# 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]"'
join_ffmpeg_command = f'{self.ffmpeg_base_command} -i {title_mov_file} -i {karaoke_mov_file} {env_mov_input} {ffmpeg_filter} -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")
# Prompt user to check final MP4 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.",
allow_empty=True,
)
def create_cdg_zip_file(self, input_files, output_files):
self.logger.info(f"Creating CDG ZIP file...")
# Check if CDG file already exists, if so, ask user to overwrite or skip
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_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
if self.dry_run:
self.logger.info(f"DRY RUN: Would create CDG ZIP file: {output_files['final_karaoke_cdg_zip']}")
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_cdg_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"]))
if not os.path.isfile(output_files["final_karaoke_cdg_zip"]):
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']}")
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 {input_files['karaoke_mp3']} and {output_files['karaoke_txt']}")
with zipfile.ZipFile(output_files["final_karaoke_txt_zip"], "w") as zipf:
zipf.write(input_files["karaoke_mp3"], os.path.basename(input_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 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.prompt_user_confirmation_or_raise_exception(
f"Move files to new brand-prefixed directory {self.new_brand_code_dir_path} and delete current dir?",
"Refusing to move files without user confirmation of move.",
allow_empty=True,
)
orig_dir = os.getcwd()
os.chdir(os.path.dirname(orig_dir))
self.logger.info(f"Changed dir to parent directory: {os.getcwd()}")
if self.dry_run:
self.logger.info("Dry run enabled. No actions will be performed.")
self.logger.info(f"DRY RUN: Would move original directory {orig_dir} to: {self.new_brand_code_dir_path}")
else:
os.rename(orig_dir, self.new_brand_code_dir_path)
self.logger.info(f"Searching for files in current directory ending with (With Vocals).mov")
for with_vocals_file in filter(lambda f: " (With Vocals).mov" in f, os.listdir(".")):
base_name = with_vocals_file.replace(" (With Vocals).mov", "")
artist = base_name.split(" - ")[0]
title = base_name.split(" - ")[1]
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...")
# Input files which should already exist after karaoke-prep and manual production process
title_file = f"{base_name} (Title).mov"
thumbnail_file = f"{base_name} (Title).jpg"
instrumental_file = f"{base_name} (Instrumental {self.model_name}).{self.instrumental_format}"
cdg_file = f"{base_name} (Karaoke).cdg"
mp3_file = f"{base_name} (Karaoke).mp3"
# Validate public_share_dir is a valid folder with MP4 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}")
# Output files which will be created by this script
karaoke_mov_file = f"{base_name} (Karaoke).mov"
final_mp4_file = f"{base_name} (Final Karaoke).mp4"
final_zip_file = f"{base_name} (Final Karaoke).zip"
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 os.path.isfile(karaoke_mov_file) and not self.force:
self.logger.error(
f"Karaoke MOV file with instrumental audio already exists: {karaoke_mov_file}. Use --force parameter to override."
)
return []
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}")
if os.path.isfile(final_mp4_file) and not self.force:
self.logger.error(f"Final MP4 file already exists: {final_mp4_file}. Use --force parameter to override.")
return []
if brand_code is None:
raise Exception(f"New track prefix was not set, refusing to copy to public share directory")
if not os.path.isfile(title_file):
self.logger.error(f"Title file not found: {title_file}")
return []
dest_mp4_dir = os.path.join(self.public_share_dir, "MP4")
dest_cdg_dir = os.path.join(self.public_share_dir, "CDG")
os.makedirs(dest_mp4_dir, exist_ok=True)
os.makedirs(dest_cdg_dir, exist_ok=True)
if not os.path.isfile(thumbnail_file):
self.logger.error(f"Thumbnail file not found: {thumbnail_file}")
return []
dest_mp4_file = os.path.join(dest_mp4_dir, f"{brand_code} - {base_name}.mp4")
dest_zip_file = os.path.join(dest_cdg_dir, f"{brand_code} - {base_name}.zip")
if not os.path.isfile(with_vocals_file):
self.logger.error(f"With Vocals file not found: {with_vocals_file}")
return []
if self.dry_run:
self.logger.info(f"DRY RUN: Would copy final MP4 and ZIP to {dest_mp4_file} + .cdg")
else:
shutil.copy2(output_files["final_karaoke_mp4"], dest_mp4_file)
shutil.copy2(output_files["final_karaoke_cdg_zip"], dest_zip_file)
self.logger.info(f"Copied final files to public share directory")
if not os.path.isfile(instrumental_file):
self.logger.error(f"Instrumental file not found: {instrumental_file}")
return []
def sync_public_share_dir_to_rclone_destination(self):
self.logger.info(f"Syncing public share directory to rclone destination...")
if not os.path.isfile(cdg_file):
self.logger.error(f"CDG file not found: {cdg_file}")
return []
# Delete .DS_Store files recursively before syncing
for root, dirs, files in os.walk(self.public_share_dir):
for file in files:
if file == ".DS_Store":
file_path = os.path.join(root, file)
os.remove(file_path)
self.logger.info(f"Deleted .DS_Store file: {file_path}")
if not os.path.isfile(mp3_file):
self.logger.error(f"MP3 file not found: {mp3_file}")
return []
rclone_cmd = f"rclone sync -v '{self.public_share_dir}' '{self.rclone_destination}'"
self.execute_command(rclone_cmd, "Syncing with cloud destination")
def post_discord_notification(self):
self.logger.info(f"Posting Discord notification...")
if self.skip_notifications:
self.logger.info(f"Skipping Discord notification as video was previously uploaded to YouTube")
return
if self.dry_run:
self.logger.info(
f"All 5 input files (Title MOV, With Vocals MOV, Instrumental {self.instrumental_format}, CDG, MP3) found for {base_name}, beginning finalisation"
f"DRY RUN: Would post Discord notification for youtube URL {self.youtube_url} using webhook URL: {self.discord_webhook_url}"
)
else:
discord_message = f"New upload: {self.youtube_url}"
self.post_discord_message(discord_message, self.discord_webhook_url)
# Remux the synced video with the instrumental audio to produce an instrumental karaoke MOV file
if not os.path.isfile(karaoke_mov_file):
self.logger.info(f"Output [With Instrumental]: remuxing synced video with instrumental audio to: {karaoke_mov_file}")
def execute_optional_features(self, artist, title, base_name, input_files, output_files):
self.logger.info(f"Executing optional features...")
remux_ffmpeg_command = f'{self.ffmpeg_base_command} -an -i "{with_vocals_file}" -vn -i "{instrumental_file}" -c:v copy -c:a aac "{karaoke_mov_file}"'
if self.youtube_upload_enabled:
try:
self.upload_final_mp4_to_youtube_with_title_thumbnail(artist, title, input_files, output_files)
except Exception as e:
self.logger.error(f"Failed to upload video to YouTube: {e}")
print("Please manually upload the video to YouTube.")
print()
self.youtube_video_id = input("Enter the manually uploaded YouTube video ID: ").strip()
self.youtube_url = f"{self.youtube_url_prefix}{self.youtube_video_id}"
self.logger.info(f"Using manually provided YouTube video ID: {self.youtube_video_id}")
if self.dry_run:
self.logger.info(f"DRY RUN: Would run command: {remux_ffmpeg_command}")
else:
self.logger.info(f"Running command: {remux_ffmpeg_command}")
os.system(remux_ffmpeg_command)
if self.discord_notication_enabled:
self.post_discord_notification()
# Join the title video and the karaoke video and reencode with fixed 30 FPS to produce the final MP4
if not os.path.isfile(final_mp4_file):
self.logger.info(f"Output [Final Karaoke]: joining title video and instrumental video to produce: {final_mp4_file}")
if self.folder_organisation_enabled:
self.brand_code = self.get_next_brand_code()
with tempfile.NamedTemporaryFile(mode="w+", delete=False, dir="/tmp", suffix=".txt") as tmp_file_list:
tmp_file_list.write(f"file '{os.path.abspath(title_file)}'\n")
tmp_file_list.write(f"file '{os.path.abspath(karaoke_mov_file)}'\n")
if self.public_share_copy_enabled:
self.copy_final_files_to_public_share_dirs(self.brand_code, base_name, output_files)
join_ffmpeg_command = f'{self.ffmpeg_base_command} -f concat -safe 0 -i "{tmp_file_list.name}" -vf settb=AVTB,setpts=N/30/TB,fps=30 "{final_mp4_file}"'
if self.public_share_rclone_enabled:
self.sync_public_share_dir_to_rclone_destination()
if self.dry_run:
self.logger.info(f"DRY RUN: Would run command: {join_ffmpeg_command}")
else:
self.logger.info(f"Running command: {join_ffmpeg_command}")
os.system(join_ffmpeg_command)
os.remove(tmp_file_list.name)
self.move_files_to_brand_code_folder(self.brand_code, artist, title, output_files)
# Create the ZIP file containing the MP3 and CDG files
if not os.path.isfile(final_zip_file):
if self.dry_run:
self.logger.info(f"DRY RUN: Would create ZIP file: {final_zip_file}")
else:
self.logger.info(f"Creating ZIP file containing {mp3_file} and {cdg_file}")
with zipfile.ZipFile(final_zip_file, "w") as zipf:
zipf.write(mp3_file, os.path.basename(mp3_file))
zipf.write(cdg_file, os.path.basename(cdg_file))
self.logger.info(f"ZIP file created: {final_zip_file}")
def process(self):
if self.dry_run:
self.logger.warning("Dry run enabled. No actions will be performed.")
# Create new folder in target folder and move all files to it
new_track_prefix = None
new_dir_path = None
if self.brand_prefix is not None and self.target_dir is not None:
next_num = self.get_next_sequence_number()
new_track_prefix = f"{self.brand_prefix}-{next_num:04d}"
new_dir_name = f"{new_track_prefix} - {artist} - {title}"
new_dir_path = os.path.join(self.target_dir, new_dir_name)
# Check required input files and parameters exist, get user to confirm features before proceeding
self.validate_input_parameters_for_features()
if self.dry_run:
self.logger.info(f"DRY RUN: Would create new folder and move files to: {new_dir_path}")
else:
if not os.path.exists(new_dir_path):
os.makedirs(new_dir_path)
with_vocals_file = self.find_with_vocals_file()
base_name, artist, title = self.get_names_from_withvocals(with_vocals_file)
for file in os.listdir("."):
src_file = os.path.join(".", file)
dest_file = os.path.join(new_dir_path, file)
shutil.move(src_file, dest_file)
instrumental_audio_file = self.choose_instrumental_audio_file(base_name)
self.logger.info(f"Moved all files to: {new_dir_path}")
else:
self.logger.info("brand_prefix or target_dir not specified, skipping move")
input_files = self.check_input_files_exist(base_name, with_vocals_file, instrumental_audio_file)
output_files = self.prepare_output_filenames(base_name)
# Copy files to public share directory with brand prefix
if self.public_share_dir is not None and new_track_prefix is not None and new_dir_path is not None:
self.logger.info(f"public_share_dir specified, will rename and copy final files to public share directory")
if self.enable_cdg:
self.create_cdg_zip_file(input_files, output_files)
src_mp4_file = os.path.join(new_dir_path, final_mp4_file)
src_zip_file = os.path.join(new_dir_path, final_zip_file)
if self.enable_txt:
self.create_txt_zip_file(input_files, output_files)
dest_mp4_dir = os.path.join(self.public_share_dir, "MP4")
dest_cdg_dir = os.path.join(self.public_share_dir, "CDG")
self.remux_and_encode_output_video_files(with_vocals_file, input_files, output_files)
if not os.path.exists(dest_mp4_dir):
os.makedirs(dest_mp4_dir)
self.execute_optional_features(artist, title, base_name, input_files, output_files)
if not os.path.exists(dest_cdg_dir):
os.makedirs(dest_cdg_dir)
result = {
"artist": artist,
"title": title,
"video_with_vocals": output_files["with_vocals_mp4"],
"video_with_instrumental": output_files["karaoke_mov"],
"final_video": output_files["final_karaoke_mp4"],
"youtube_url": self.youtube_url,
"brand_code": self.brand_code,
"new_brand_code_dir_path": self.new_brand_code_dir_path,
}
dest_mp4_file = os.path.join(dest_mp4_dir, f"{new_track_prefix} - {base_name}.mp4")
dest_zip_file = os.path.join(dest_cdg_dir, f"{new_track_prefix} - {base_name}.zip")
if self.enable_cdg:
result["final_karaoke_cdg_zip"] = output_files["final_karaoke_cdg_zip"]
if self.dry_run:
self.logger.info(f"DRY RUN: Would copy {src_mp4_file} to {dest_mp4_file}")
self.logger.info(f"DRY RUN: Would copy {src_zip_file} to {dest_zip_file}")
else:
shutil.copy2(src_mp4_file, dest_mp4_file)
shutil.copy2(src_zip_file, dest_zip_file)
self.logger.info(f"Final files copied to public share directory: {dest_mp4_file}, {dest_zip_file}")
else:
self.logger.info(f"public_share_dir or new_track_prefix not specified, skipping copy to shared dir")
if self.enable_txt:
result["final_karaoke_txt_zip"] = output_files["final_karaoke_txt_zip"]
# Upload to YouTube
if self.youtube_client_secrets_file is not None:
src_mp4_file = os.path.join(new_dir_path, final_mp4_file)
new_thumbnail_path = os.path.join(new_dir_path, thumbnail_file)
if self.dry_run:
self.logger.info(
f"DRY RUN: Would upload {src_mp4_file} to YouTube with thumbnail {new_thumbnail_path} using client secrets file: {self.youtube_client_secrets_file}"
)
else:
description = f"Karaoke version of {artist} - {title} created using karaoke-prep python package."
if self.youtube_description_file is not None:
with open(self.youtube_description_file, "r") as f:
description = f.read()
self.upload_to_youtube(
src_mp4_file,
new_thumbnail_path,
f"{artist} - {title} (Karaoke)",
description,
"10", # Category ID for Music
["karaoke", "music", "singing", "instrumental", "lyrics", artist, title],
)
else:
self.logger.info(f"youtube_client_secrets_file not specified, skipping YouTube upload")
# Sync with various cloud destinations using rclone
if self.rclone_destination is not None and self.public_share_dir is not None:
rclone_cmd = ["rclone", "sync", "-v", self.public_share_dir, self.rclone_destination]
if self.dry_run:
self.logger.info(f"DRY RUN: Would sync {self.public_share_dir} to {self.rclone_destination} using rclone")
else:
self.logger.info(f"Running command: {rclone_cmd}")
subprocess.run(rclone_cmd)
else:
self.logger.info(f"rclone_destination or public_share_dir not specified, skipping sync")
# Add track to list of processed tracks now we've created all of the new output files
tracks.append(
{
"artist": artist,
"title": title,
"video_with_vocals": with_vocals_file,
"video_with_instrumental": karaoke_mov_file,
"final_video": final_mp4_file,
"final_zip": final_zip_file,
}
)
return tracks
return result
+454 -175
View File
@@ -3,9 +3,12 @@ import sys
import re
import glob
import logging
import unicodedata
import lyricsgenius
import tempfile
import shutil
import pyperclip
from pyperclip import PyperclipException
import importlib.resources as pkg_resources
import yt_dlp.YoutubeDL as ydl
from PIL import Image, ImageDraw, ImageFont
@@ -14,13 +17,14 @@ from PIL import Image, ImageDraw, ImageFont
class KaraokePrep:
def __init__(
self,
url=None,
input_media=None,
artist=None,
title=None,
filename_pattern=None,
dry_run=False,
log_level=logging.DEBUG,
log_formatter=None,
model_name="UVR_MDXNET_KARA_2",
model_name_2="UVR-MDX-NET-Inst_HQ_3",
model_names=["UVR_MDXNET_KARA_2.onnx", "model_mel_band_roformer_ep_3005_sdr_11.4360.ckpt"],
model_file_dir=os.path.join(tempfile.gettempdir(), "audio-separator-models"),
output_dir=".",
lossless_output_format="FLAC",
@@ -35,6 +39,32 @@ class KaraokePrep:
intro_font="Montserrat-Bold.ttf",
intro_artist_color="#ffffff",
intro_title_color="#ff7acc",
existing_instrumental=None,
existing_title_image=None,
end_background_color="#000000",
end_background_image=None,
end_font="Montserrat-Bold.ttf",
end_extra_text_color="#ffffff",
end_artist_color="#ffffff",
end_title_color="#ff7acc",
existing_end_image=None,
title_video_duration=5,
end_video_duration=5,
title_initial_font_size=500,
title_top_padding=950,
title_title_padding=400,
title_artist_padding=700,
title_fixed_gap=150,
end_initial_font_size=500,
end_top_padding=950,
end_title_padding=400,
end_artist_padding=700,
end_extra_text_padding=300,
end_fixed_gap=150,
end_extra_text="THANK YOU FOR SINGING!",
lyrics_artist=None,
lyrics_title=None,
skip_lyrics=False,
):
self.logger = logging.getLogger(__name__)
self.logger.setLevel(log_level)
@@ -49,15 +79,18 @@ class KaraokePrep:
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.logger.debug(f"KaraokePrep instantiating with input_media: {input_media} artist: {artist} title: {title}")
self.dry_run = dry_run
self.extractor = None
self.media_id = None
self.url = url
self.url = None
self.input_media = input_media
self.artist = artist
self.title = title
self.model_name = model_name
self.model_name_2 = model_name_2
self.filename_pattern = filename_pattern
self.model_names = model_names
self.model_file_dir = model_file_dir
self.output_dir = output_dir
self.lossless_output_format = lossless_output_format.lower()
@@ -67,6 +100,25 @@ class KaraokePrep:
self.normalization_enabled = normalization_enabled
self.denoise_enabled = denoise_enabled
self.create_track_subfolders = create_track_subfolders
self.existing_instrumental = existing_instrumental
self.existing_title_image = existing_title_image
self.title_video_duration = title_video_duration
self.end_video_duration = end_video_duration
self.title_initial_font_size = title_initial_font_size
self.title_top_padding = title_top_padding
self.title_title_padding = title_title_padding
self.title_artist_padding = title_artist_padding
self.title_fixed_gap = title_fixed_gap
self.end_initial_font_size = end_initial_font_size
self.end_top_padding = end_top_padding
self.end_title_padding = end_title_padding
self.end_artist_padding = end_artist_padding
self.end_extra_text_padding = end_extra_text_padding
self.end_fixed_gap = end_fixed_gap
self.end_extra_text = end_extra_text
self.lyrics_artist = lyrics_artist
self.lyrics_title = lyrics_title
self.skip_lyrics = skip_lyrics
# Path to the Windows PyInstaller frozen bundled ffmpeg.exe, or the system-installed FFmpeg binary on Mac/Linux
ffmpeg_path = os.path.join(sys._MEIPASS, "ffmpeg.exe") if getattr(sys, "frozen", False) else "ffmpeg"
@@ -81,11 +133,23 @@ class KaraokePrep:
self.title_format = {
"background_color": intro_background_color,
"background_image": intro_background_image,
"intro_font": intro_font,
"font": intro_font,
"artist_color": intro_artist_color,
"title_color": intro_title_color,
}
self.end_format = {
"background_color": end_background_color,
"background_image": end_background_image,
"font": end_font,
"extra_text_color": end_extra_text_color,
"artist_color": end_artist_color,
"title_color": end_title_color,
}
self.existing_end_image = existing_end_image
self.extracted_info = None
self.persistent_artist = None
self.logger.debug(f"KaraokePrep lossless_output_format: {self.lossless_output_format}")
@@ -175,6 +239,15 @@ class KaraokePrep:
self.logger.debug(self.extracted_info)
raise Exception("Failed to extract artist and title from the input media metadata.")
def copy_input_media(self, input_media, output_filename_no_extension):
self.logger.debug(f"Copying media from local path {input_media} to filename {output_filename_no_extension} + existing extension")
copied_file_name = output_filename_no_extension + os.path.splitext(input_media)[1]
self.logger.debug(f"Copying {input_media} to {copied_file_name}")
shutil.copy2(input_media, copied_file_name)
return copied_file_name
def download_video(self, url, output_filename_no_extension):
self.logger.debug(f"Downloading media from URL {url} to filename {output_filename_no_extension} + (as yet) unknown extension")
@@ -208,10 +281,11 @@ class KaraokePrep:
def convert_to_wav(self, input_filename, output_filename_no_extension):
output_filename = output_filename_no_extension + ".wav"
self.logger.info(f"Converting input video to audio WAV file")
self.logger.info(f"Converting input media to audio WAV file")
ffmpeg_command = f'{self.ffmpeg_base_command} -n -i "{input_filename}" "{output_filename}"'
self.logger.debug(f"Running command: {ffmpeg_command}")
os.system(ffmpeg_command)
if not self.dry_run:
os.system(ffmpeg_command)
return output_filename
def write_lyrics_from_genius(self, artist, title, filename):
@@ -220,8 +294,9 @@ class KaraokePrep:
if song:
lyrics = self.clean_genius_lyrics(song.lyrics)
with open(filename, "w") as f:
f.write(lyrics)
if not self.dry_run:
with open(filename, "w") as f:
f.write(lyrics)
self.logger.info("Lyrics for %s by %s fetched successfully", title, artist)
return lyrics.split("\n")
@@ -334,32 +409,46 @@ class KaraokePrep:
iteration_count = 0
max_iterations = 100 # Failsafe limit
with open(processed_lyrics_file, "w") as outfile:
all_processed = False
while not all_processed:
if iteration_count > max_iterations:
self.logger.error("Maximum iterations exceeded in write_processed_lyrics.")
break
if not self.dry_run:
with open(processed_lyrics_file, "w") as outfile:
all_processed = False
while not all_processed:
if iteration_count > max_iterations:
self.logger.error("Maximum iterations exceeded in write_processed_lyrics.")
break
all_processed = True
new_lyrics = []
all_processed = True
new_lyrics = []
for line in lyrics:
line = line.strip()
# Check for abnormal space characters and replace them
abnormal_spaces = [chr(i) for i in range(sys.maxunicode) if unicodedata.category(chr(i)) == "Zs" and chr(i) != " "]
if any(space in line for space in abnormal_spaces):
self.logger.warning(f"Replacing abnormal space characters found in line: {line}")
for space in abnormal_spaces:
line = line.replace(space, " ")
processed = self.process_line(line)
new_lyrics.extend(processed)
if any(len(l) > 36 for l in processed):
all_processed = False
lyrics = new_lyrics
iteration_count += 1
# Write the processed lyrics to file
for line in lyrics:
line = line.strip()
processed = self.process_line(line)
new_lyrics.extend(processed)
if any(len(l) > 36 for l in processed):
all_processed = False
lyrics = new_lyrics
outfile.write(line + "\n")
processed_lyrics_lines += line + "\n"
iteration_count += 1
if not self.dry_run:
try:
pyperclip.copy(processed_lyrics_lines)
self.logger.info(f"Processed lyrics copied to clipboard.")
except PyperclipException:
self.logger.warning("Clipboard functionality not available. Skipping clipboard operations.")
# Write the processed lyrics to file
for line in lyrics:
outfile.write(line + "\n")
processed_lyrics_lines += line + "\n"
pyperclip.copy(processed_lyrics_lines)
self.logger.info(f"Processed lyrics copied to clipboard.")
return processed_lyrics_lines
def sanitize_filename(self, filename):
@@ -368,7 +457,7 @@ class KaraokePrep:
for char in ["\\", "/", ":", "*", "?", '"', "<", ">", "|"]:
filename = filename.replace(char, "_")
# Remove any trailing periods or spaces
filename = filename.rstrip(". ")
filename = filename.rstrip(" ")
return filename
def separate_audio(self, audio_file, model_name, instrumental_path, vocals_path):
@@ -377,8 +466,8 @@ class KaraokePrep:
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 lossless_output_format: {self.lossless_output_format}"
self.logger.info(
f"instantiating Separator with model_file_dir: {self.model_file_dir}, model_filename: {model_name} output_format: {self.lossless_output_format}"
)
from audio_separator.separator import Separator
@@ -388,14 +477,18 @@ class KaraokePrep:
log_formatter=self.log_formatter,
model_file_dir=self.model_file_dir,
output_format=self.lossless_output_format,
primary_stem_path=instrumental_path,
secondary_stem_path=vocals_path,
)
separator.load_model(model_name)
separator.load_model(model_filename=model_name)
output_files = separator.separate(audio_file)
self.logger.info(f"Separation complete! Output file(s): {' '.join(output_files)}")
for file in output_files:
if "(Vocals)" in file:
os.rename(file, vocals_path)
elif "(Instrumental)" in file:
os.rename(file, instrumental_path)
self.logger.info(f"Separation complete! Output file(s): {vocals_path} {instrumental_path}")
def setup_output_paths(self, artist, title):
sanitized_artist = self.sanitize_filename(artist)
@@ -442,64 +535,158 @@ class KaraokePrep:
text_y = vertical_offset
return (text_x, text_y), text_height
def create_title_video(self, artist, title, format, output_image_filepath_noext, output_video_filepath):
duration = 5 # Duration in seconds
def create_video(
self,
extra_text,
title_text,
artist_text,
format,
output_image_filepath_noext,
output_video_filepath,
existing_image=None,
extra_text_color=None,
title_color=None,
artist_color=None,
duration=5,
initial_font_size=500,
top_padding=950,
title_padding=400,
artist_padding=700,
extra_text_padding=600,
fixed_gap=150,
):
resolution = (3840, 2160) # 4K resolution
# Load or create background image
if format["background_image"] and os.path.exists(format["background_image"]):
self.logger.info(f"Using title screen background image file: {format['background_image']}")
background = Image.open(format["background_image"])
else:
self.logger.info(f"Using title screen background color: {format['background_color']}")
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)
# Accessing the font file from the package resources
with pkg_resources.path("karaoke_prep.resources", format["intro_font"]) as font_path:
# Calculate positions and sizes for title and artist
title_font, _ = self.calculate_text_size_and_position(draw, title, str(font_path), initial_font_size, resolution, title_padding)
artist_font, _ = self.calculate_text_size_and_position(
draw, artist, str(font_path), 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
self.logger.info(f"Creating video with format: {format}")
self.logger.info(f"extra_text: {extra_text}, artist_text: {artist_text}, title_text: {title_text}")
self.logger.info(
f"top_padding: {top_padding}, title_padding: {title_padding}, artist_padding: {artist_padding}, extra_text_padding: {extra_text_padding}"
)
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)
if existing_image:
self.logger.info(f"Using existing image file: {existing_image}")
existing_extension = os.path.splitext(existing_image)[1]
# Save static background image
background.save(f"{output_image_filepath_noext}.png")
if existing_extension == ".png":
self.logger.info(f"Copying existing PNG image file: {existing_image}")
shutil.copy2(existing_image, output_image_filepath_noext + existing_extension)
else:
self.logger.info(f"Converting existing image to PNG")
existing_image_obj = Image.open(existing_image)
existing_image_obj.save(output_image_filepath_noext + ".png")
# Save static background image as JPG for smaller filesize to upload as YouTube thumbnail
background_rgb = background.convert('RGB')
background_rgb.save(f"{output_image_filepath_noext}.jpg", quality=95)
if existing_extension != ".jpg":
self.logger.info(f"Converting existing image to JPG")
existing_image_obj = Image.open(existing_image)
if existing_image_obj.mode == "RGBA":
existing_image_obj = existing_image_obj.convert("RGB") # Convert RGBA to RGB
existing_image_obj.save(output_image_filepath_noext + ".jpg", quality=95)
else:
# Load or create background image
if format["background_image"] and os.path.exists(format["background_image"]):
self.logger.info(f"Using background image file: {format['background_image']}")
background = Image.open(format["background_image"])
else:
self.logger.info(f"Using background color: {format['background_color']}")
background = Image.new("RGB", resolution, color=self.hex_to_rgb(format["background_color"]))
# Resize background to match resolution
background = background.resize(resolution)
draw = ImageDraw.Draw(background)
# Accessing the font file from the package resources
with pkg_resources.path("karaoke_prep.resources", format["font"]) as font_path:
# Calculate positions and sizes for title, artist, and extra text
title_font, _ = self.calculate_text_size_and_position(
draw, title_text, str(font_path), initial_font_size, resolution, title_padding
)
artist_font, _ = self.calculate_text_size_and_position(
draw, artist_text, str(font_path), initial_font_size, resolution, artist_padding
)
if extra_text:
self.logger.info(f"Calculating extra text font size and position for: {extra_text}")
extra_text_font, _ = self.calculate_text_size_and_position(
draw, extra_text, str(font_path), initial_font_size, resolution, extra_text_padding
)
# Calculate vertical positions with consistent gap
current_y = top_padding
if extra_text:
self.logger.info(f"Calculating extra text position for: {extra_text}")
extra_text_position, extra_text_height = self.calculate_text_position(
draw, extra_text, extra_text_font, resolution, current_y
)
draw.text(extra_text_position, extra_text, fill=extra_text_color, font=extra_text_font)
current_y += extra_text_height + fixed_gap
title_text_position, title_height = self.calculate_text_position(draw, title_text, title_font, resolution, current_y)
draw.text(title_text_position, title_text, fill=title_color, font=title_font)
current_y += title_height + fixed_gap
artist_text_position, _ = self.calculate_text_position(draw, artist_text, artist_font, resolution, current_y)
draw.text(artist_text_position, artist_text, fill=artist_color, font=artist_font)
# Save static background image
background.save(f"{output_image_filepath_noext}.png")
# Save static background image as JPG for smaller filesize to upload as YouTube thumbnail
background_rgb = background.convert("RGB")
background_rgb.save(f"{output_image_filepath_noext}.jpg", quality=95)
# Use ffmpeg to create video
ffmpeg_command = f'{self.ffmpeg_base_command} -y -loop 1 -framerate 30 -i "{output_image_filepath_noext}.png" -f lavfi -i anullsrc '
ffmpeg_command += f'-c:v libx264 -r 30 -t {duration} -pix_fmt yuv420p -vf scale={resolution[0]}:{resolution[1]} -c:a aac -shortest "{output_video_filepath}"'
self.logger.info("Generating title video...")
self.logger.info("Generating video...")
self.logger.debug(f"Running command: {ffmpeg_command}")
os.system(ffmpeg_command)
def create_end_video(self, artist, title, format, output_image_filepath_noext, output_video_filepath):
extra_text = self.end_extra_text
title_text = title.upper()
artist_text = artist.upper()
self.create_video(
extra_text=extra_text,
title_text=title_text,
artist_text=artist_text,
format=format,
output_image_filepath_noext=output_image_filepath_noext,
output_video_filepath=output_video_filepath,
existing_image=self.existing_end_image,
extra_text_color=format["extra_text_color"],
title_color=format["title_color"],
artist_color=format["artist_color"],
duration=self.end_video_duration,
initial_font_size=self.end_initial_font_size,
top_padding=self.end_top_padding,
title_padding=self.end_title_padding,
artist_padding=self.end_artist_padding,
extra_text_padding=self.end_extra_text_padding,
fixed_gap=self.end_fixed_gap,
)
def create_title_video(self, artist, title, format, output_image_filepath_noext, output_video_filepath):
title_text = title.upper()
artist_text = artist.upper()
self.create_video(
extra_text=None,
title_text=title_text,
artist_text=artist_text,
format=format,
output_image_filepath_noext=output_image_filepath_noext,
output_video_filepath=output_video_filepath,
existing_image=self.existing_title_image,
title_color=format["title_color"],
artist_color=format["artist_color"],
duration=self.title_video_duration,
initial_font_size=self.title_initial_font_size,
top_padding=self.title_top_padding,
title_padding=self.title_title_padding,
artist_padding=self.title_artist_padding,
fixed_gap=self.title_fixed_gap,
)
def hex_to_rgb(self, hex_color):
"""Convert hex color to RGB tuple."""
hex_color = hex_color.lstrip("#")
@@ -508,11 +695,18 @@ class KaraokePrep:
def prep_single_track(self):
self.logger.info(f"Preparing single track: {self.artist} - {self.title}")
# Parses metadata in self.extracted_info to set vars: self.url, self.extractor, self.media_id, self.artist, self.title
self.parse_single_track_metadata(input_artist=self.artist, input_title=self.title)
if self.input_media is not None and os.path.isfile(self.input_media):
self.extractor = "Local"
else:
# Parses metadata in self.extracted_info to set vars: self.url, self.extractor, self.media_id, self.artist, self.title
self.parse_single_track_metadata(input_artist=self.artist, input_title=self.title)
self.logger.info(f"Preparing output path for track: {self.title} by {self.artist}")
if self.dry_run:
return None
track_output_dir, artist_title = self.setup_output_paths(self.artist, self.title)
processed_track = {
"track_output_dir": track_output_dir,
"artist": self.artist,
@@ -521,58 +715,83 @@ class KaraokePrep:
"extracted_info": self.extracted_info,
"lyrics": None,
"processed_lyrics": None,
"separated_audio": {},
}
# WebM may not always be the output format from ytdlp, but it's common and this is just a convenience cache
input_webm_filename_pattern = os.path.join(track_output_dir, f"{artist_title} ({self.extractor} *.webm")
input_webm_glob = glob.glob(input_webm_filename_pattern)
input_png_filename_pattern = os.path.join(track_output_dir, f"{artist_title} ({self.extractor} *.png")
input_png_glob = glob.glob(input_png_filename_pattern)
input_wav_filename_pattern = os.path.join(track_output_dir, f"{artist_title} ({self.extractor} *.wav")
input_wav_glob = glob.glob(input_wav_filename_pattern)
processed_track["input_media"] = None
processed_track["input_still_image"] = None
processed_track["input_audio_wav"] = None
if input_webm_glob and input_png_glob and input_wav_glob:
processed_track["input_media"] = input_webm_glob[0]
processed_track["input_still_image"] = input_png_glob[0]
processed_track["input_audio_wav"] = input_wav_glob[0]
if self.input_media is not None and os.path.isfile(self.input_media):
input_wav_filename_pattern = os.path.join(track_output_dir, f"{artist_title} ({self.extractor} *.wav")
input_wav_glob = glob.glob(input_wav_filename_pattern)
self.logger.info(f"Input media files already exist, skipping download: {processed_track['input_media']} + .wav + .png")
else:
if self.url:
output_filename_no_extension = os.path.join(track_output_dir, f"{artist_title} ({self.extractor} {self.media_id})")
if input_wav_glob:
processed_track["input_audio_wav"] = input_wav_glob[0]
self.logger.info(f"Input media WAV file already exists, skipping conversion: {processed_track['input_audio_wav']}")
else:
output_filename_no_extension = os.path.join(track_output_dir, f"{artist_title} ({self.extractor})")
self.logger.info(f"Downloading input media from {self.url}...")
processed_track["input_media"] = self.download_video(self.url, output_filename_no_extension)
self.logger.info(f"Copying input media from {self.input_media} to new directory...")
processed_track["input_media"] = self.copy_input_media(self.input_media, output_filename_no_extension)
self.logger.info("Extracting still image from downloaded media (if input is video)...")
processed_track["input_still_image"] = self.extract_still_image_from_video(
processed_track["input_media"], output_filename_no_extension
)
self.logger.info("Converting downloaded video to WAV for audio processing...")
self.logger.info("Converting input media to WAV for audio processing...")
processed_track["input_audio_wav"] = self.convert_to_wav(processed_track["input_media"], output_filename_no_extension)
else:
self.logger.warning(f"Skipping download due to missing URL.")
processed_track["lyrics"] = os.path.join(track_output_dir, f"{artist_title} (Lyrics).txt")
if os.path.exists(processed_track["lyrics"]):
self.logger.debug(f"Lyrics file already exists, skipping fetch: {processed_track['lyrics']}")
else:
self.logger.info("Fetching lyrics from Genius...")
self.lyrics = self.write_lyrics_from_genius(self.artist, self.title, processed_track["lyrics"])
# WebM may not always be the output format from ytdlp, but it's common and this is just a convenience cache
input_webm_filename_pattern = os.path.join(track_output_dir, f"{artist_title} ({self.extractor} *.webm")
input_webm_glob = glob.glob(input_webm_filename_pattern)
processed_track["processed_lyrics"] = os.path.join(track_output_dir, f"{artist_title} (Lyrics Processed).txt")
if self.lyrics is None:
processed_track["lyrics"] = None
processed_track["processed_lyrics"] = None
input_png_filename_pattern = os.path.join(track_output_dir, f"{artist_title} ({self.extractor} *.png")
input_png_glob = glob.glob(input_png_filename_pattern)
input_wav_filename_pattern = os.path.join(track_output_dir, f"{artist_title} ({self.extractor} *.wav")
input_wav_glob = glob.glob(input_wav_filename_pattern)
if input_webm_glob and input_png_glob and input_wav_glob:
processed_track["input_media"] = input_webm_glob[0]
processed_track["input_still_image"] = input_png_glob[0]
processed_track["input_audio_wav"] = input_wav_glob[0]
self.logger.info(f"Input media files already exist, skipping download: {processed_track['input_media']} + .wav + .png")
else:
self.write_processed_lyrics(self.lyrics, processed_track["processed_lyrics"])
if self.url:
output_filename_no_extension = os.path.join(track_output_dir, f"{artist_title} ({self.extractor} {self.media_id})")
self.logger.info(f"Downloading input media from {self.url}...")
processed_track["input_media"] = self.download_video(self.url, output_filename_no_extension)
self.logger.info("Extracting still image from downloaded media (if input is video)...")
processed_track["input_still_image"] = self.extract_still_image_from_video(
processed_track["input_media"], output_filename_no_extension
)
self.logger.info("Converting downloaded video to WAV for audio processing...")
processed_track["input_audio_wav"] = self.convert_to_wav(processed_track["input_media"], output_filename_no_extension)
else:
self.logger.warning(f"Skipping download due to missing URL.")
if self.skip_lyrics:
self.logger.info("Skipping lyrics fetch as requested.")
processed_track["lyrics"] = None
processed_track["processed_lyrics"] = None
else:
processed_track["lyrics"] = os.path.join(track_output_dir, f"{artist_title} (Lyrics).txt")
if os.path.exists(processed_track["lyrics"]):
self.logger.debug(f"Lyrics file already exists, skipping fetch: {processed_track['lyrics']}")
else:
self.logger.info("Fetching lyrics from Genius...")
lyrics_artist = self.lyrics_artist or self.artist
lyrics_title = self.lyrics_title or self.title
self.lyrics = self.write_lyrics_from_genius(lyrics_artist, lyrics_title, processed_track["lyrics"])
processed_track["processed_lyrics"] = os.path.join(track_output_dir, f"{artist_title} (Lyrics Processed).txt")
if self.lyrics is None:
processed_track["lyrics"] = None
processed_track["processed_lyrics"] = None
else:
self.write_processed_lyrics(self.lyrics, processed_track["processed_lyrics"])
output_image_filepath_noext = os.path.join(track_output_dir, f"{artist_title} (Title)")
processed_track["title_image_png"] = f"{output_image_filepath_noext}.png"
@@ -585,51 +804,55 @@ class KaraokePrep:
self.logger.info(f"Creating title video...")
self.create_title_video(self.artist, self.title, self.title_format, output_image_filepath_noext, processed_track["title_video"])
self.logger.info(f"Separating audio twice for track: {self.title} by {self.artist}")
output_image_filepath_noext = os.path.join(track_output_dir, f"{artist_title} (End)")
processed_track["end_image_png"] = f"{output_image_filepath_noext}.png"
processed_track["end_image_jpg"] = f"{output_image_filepath_noext}.jpg"
processed_track["end_video"] = os.path.join(track_output_dir, f"{artist_title} (End).mov")
instrumental_path = os.path.join(track_output_dir, f"{artist_title} (Instrumental {self.model_name}).{self.lossless_output_format}")
vocals_path = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name}).{self.lossless_output_format}")
instrumental_path_lossy = os.path.join(
track_output_dir, f"{artist_title} (Instrumental {self.model_name}).{self.lossy_output_format}"
)
vocals_path_lossy = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name}).{self.lossy_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}")
if os.path.exists(processed_track["end_video"]):
self.logger.debug(f"End screen video already exists, skipping render: {processed_track['end_video']}")
else:
self.separate_audio(processed_track["input_audio_wav"], self.model_name, instrumental_path, vocals_path)
self.logger.info(f"Creating end screen video...")
self.create_end_video(self.artist, self.title, self.end_format, output_image_filepath_noext, processed_track["end_video"])
if self.existing_instrumental:
self.logger.info(f"Using existing instrumental file: {self.existing_instrumental}")
existing_instrumental_extension = os.path.splitext(self.existing_instrumental)[1]
instrumental_path = os.path.join(track_output_dir, f"{artist_title} (Instrumental Custom){existing_instrumental_extension}")
instrumental_path_lossy = os.path.join(track_output_dir, f"{artist_title} (Instrumental Custom).{self.lossy_output_format}")
shutil.copy2(self.existing_instrumental, instrumental_path)
self.convert_to_lossy(instrumental_path, instrumental_path_lossy)
self.convert_to_lossy(vocals_path, vocals_path_lossy)
processed_track["instrumental_audio"] = instrumental_path
processed_track["vocals_audio"] = vocals_path
processed_track["instrumental_audio_lossy"] = instrumental_path_lossy
processed_track["vocals_audio_lossy"] = vocals_path_lossy
instrumental_path_2 = os.path.join(
track_output_dir, f"{artist_title} (Instrumental {self.model_name_2}).{self.lossless_output_format}"
)
vocals_path_2 = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name_2}).{self.lossless_output_format}")
instrumental_path_2_lossy = os.path.join(
track_output_dir, f"{artist_title} (Instrumental {self.model_name_2}).{self.lossy_output_format}"
)
vocals_path_2_lossy = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name_2}).{self.lossy_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}")
processed_track["separated_audio"]["Custom"] = {
"instrumental": instrumental_path,
"instrumental_lossy": instrumental_path_lossy,
"vocals": None,
"vocals_lossy": None,
}
else:
self.separate_audio(processed_track["input_audio_wav"], self.model_name_2, instrumental_path_2, vocals_path_2)
self.convert_to_lossy(instrumental_path_2, instrumental_path_2_lossy)
self.convert_to_lossy(vocals_path_2, vocals_path_2_lossy)
self.logger.info(f"Separating audio for track: {self.title} by {self.artist} using models: {', '.join(self.model_names)}")
for model_name in self.model_names:
processed_track[f"separated_audio"][model_name] = {}
instrumental_path = os.path.join(
track_output_dir, f"{artist_title} (Instrumental {model_name}).{self.lossless_output_format}"
)
vocals_path = os.path.join(track_output_dir, f"{artist_title} (Vocals {model_name}).{self.lossless_output_format}")
instrumental_path_lossy = os.path.join(
track_output_dir, f"{artist_title} (Instrumental {model_name}).{self.lossy_output_format}"
)
vocals_path_lossy = os.path.join(track_output_dir, f"{artist_title} (Vocals {model_name}).{self.lossy_output_format}")
processed_track["instrumental_audio_2"] = instrumental_path_2
processed_track["vocals_audio_2"] = vocals_path_2
if not (os.path.isfile(instrumental_path) and os.path.isfile(vocals_path)):
self.separate_audio(processed_track["input_audio_wav"], model_name, instrumental_path, vocals_path)
self.convert_to_lossy(instrumental_path, instrumental_path_lossy)
self.convert_to_lossy(vocals_path, vocals_path_lossy)
processed_track["instrumental_audio_2_lossy"] = instrumental_path_2_lossy
processed_track["vocals_audio_2_lossy"] = vocals_path_2_lossy
processed_track[f"separated_audio"][model_name]["instrumental"] = instrumental_path
processed_track[f"separated_audio"][model_name]["vocals"] = vocals_path
processed_track[f"separated_audio"][model_name]["instrumental_lossy"] = instrumental_path_lossy
processed_track[f"separated_audio"][model_name]["vocals_lossy"] = vocals_path_lossy
self.logger.info("Script finished, audio downloaded, lyrics fetched and audio separated!")
@@ -648,29 +871,85 @@ class KaraokePrep:
os.system(ffmpeg_command)
def process_playlist(self):
if self.artist is None or self.title is None:
raise Exception("Error: Artist and Title are required for processing a local file.")
if "entries" in self.extracted_info:
track_results = []
self.logger.info(f"Found {len(self.extracted_info['entries'])} entries in playlist, processing each invididually...")
for entry in self.extracted_info["entries"]:
self.extracted_info = entry
self.logger.info(f"Processing playlist entry with title: {self.extracted_info['title']}")
track_results.append(self.prep_single_track())
if not self.dry_run:
track_results.append(self.prep_single_track())
self.artist = self.persistent_artist
self.title = None
return track_results
else:
raise Exception(f"Failed to find 'entries' in playlist, cannot process")
def process(self):
# Runs yt-dlp extract_info for input URL or artist/title search query to set var: self.extracted_info
# We do this first as the input URL may be a playlist
self.extract_info_for_online_media(input_url=self.url, input_artist=self.artist, input_title=self.title)
def process_folder(self):
if self.filename_pattern is None or self.artist is None:
raise Exception("Error: Filename pattern and artist are required for processing a folder.")
if self.extracted_info and "playlist_count" in self.extracted_info:
self.persistent_artist = self.artist
self.logger.info(f"Input URL is a playlist, beginning batch operation with persistent artist: {self.persistent_artist}")
return self.process_playlist()
folder_path = self.input_media
output_folder_path = os.path.join(os.getcwd(), os.path.basename(folder_path))
if not os.path.exists(output_folder_path):
if not self.dry_run:
self.logger.info(f"DRY RUN: Would create output folder: {output_folder_path}")
os.makedirs(output_folder_path)
else:
self.logger.info(f"Input URL is not a playlist, processing single track")
# TODO: Add support for using karaoke-prep with an existing audio file in any format (e.g. FLAC), not just youtube
self.logger.info(f"Output folder already exists: {output_folder_path}")
pattern = re.compile(self.filename_pattern)
tracks = []
for filename in sorted(os.listdir(folder_path)):
match = pattern.match(filename)
if match:
title = match.group("title")
file_path = os.path.join(folder_path, filename)
self.input_media = file_path
self.title = title
track_index = match.group("index") if "index" in match.groupdict() else None
self.logger.info(f"Processing track: {track_index} with title: {title} from file: {filename}")
track_output_dir = os.path.join(output_folder_path, f"{track_index} - {self.artist} - {title}")
if not self.dry_run:
track = self.prep_single_track()
tracks.append(track)
# Move the track folder to the output folder
track_folder = track["track_output_dir"]
shutil.move(track_folder, track_output_dir)
else:
self.logger.info(f"DRY RUN: Would move track folder to: {os.path.basename(track_output_dir)}")
return tracks
def process(self):
if self.input_media is not None and os.path.isdir(self.input_media):
self.logger.info(f"Input media {self.input_media} is a local folder, processing each file individually...")
return self.process_folder()
elif self.input_media is not None and os.path.isfile(self.input_media):
self.logger.info(f"Input media {self.input_media} is a local file, youtube logic will be skipped")
return [self.prep_single_track()]
else:
self.url = self.input_media
# Runs yt-dlp extract_info for input URL or artist/title search query to set var: self.extracted_info
# We do this first as the input URL may be a playlist
self.extract_info_for_online_media(input_url=self.url, input_artist=self.artist, input_title=self.title)
if self.extracted_info and "playlist_count" in self.extracted_info:
self.persistent_artist = self.artist
self.logger.info(f"Input URL is a playlist, beginning batch operation with persistent artist: {self.persistent_artist}")
return self.process_playlist()
else:
self.logger.info(f"Input URL is not a playlist, processing single track")
return [self.prep_single_track()]
+51 -26
View File
@@ -2,6 +2,8 @@
import argparse
import logging
import pkg_resources
import os
import sys
from karaoke_prep.karaoke_finalise import KaraokeFinalise
@@ -28,20 +30,15 @@ def main():
parser.add_argument(
"--dry_run",
"-n",
action="store_true",
help="Optional: Enable dry run mode to print actions without executing them (default: disabled). Example: --dry_run",
)
parser.add_argument(
"--force",
action="store_true",
help="Optional: Force processing even if final output file exists (default: disabled). Example: --force",
help="Optional: Enable dry run mode to print actions without executing them (default: disabled). Example: -n or --dry_run",
)
parser.add_argument(
"--model_name",
default="UVR_MDXNET_KARA_2",
help="Optional: model name to be used for separation (default: %(default)s). Example: --model_name=UVR-MDX-NET-Inst_HQ_3",
default=None,
help="Optional: specific model name to be used for separation (default: interactive prompt). Example: --model_name=UVR-MDX-NET-Inst_HQ_3",
)
parser.add_argument(
@@ -50,6 +47,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,
@@ -57,9 +66,9 @@ def main():
)
parser.add_argument(
"--target_dir",
"--organised_dir",
default=None,
help="Optional: Target directory where the processed folder will be moved after finalisation. Example: --target_dir='/path/to/Tracks-Organized'",
help="Optional: Target directory where the processed folder will be moved after finalisation. Example: --organised_dir='/path/to/Tracks-Organized'",
)
parser.add_argument(
@@ -86,42 +95,58 @@ 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",
)
args = parser.parse_args()
log_level = getattr(logging, args.log_level.upper())
logger.setLevel(log_level)
logger.info(f"KaraokeFinalise beginning with model_name: {args.model_name}")
logger.info(f"KaraokeFinalise CLI beginning initialisation...")
kfinalise = KaraokeFinalise(
log_formatter=log_formatter,
log_level=log_level,
dry_run=args.dry_run,
force=args.force,
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,
target_dir=args.target_dir,
organised_dir=args.organised_dir,
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=args.discord_webhook_url,
)
tracks = kfinalise.process()
if len(tracks) == 0:
logger.error(f"No tracks found to process.")
return
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:")
for track in tracks:
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"")
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']}")
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" YouTube URL: {track['youtube_url']}")
logger.info(f" Brand Code: {track['brand_code']}")
logger.info(f" New Brand Code Directory: {track['new_brand_code_dir_path']}")
if __name__ == "__main__":
+248 -16
View File
@@ -12,6 +12,11 @@ def is_url(string):
return string.startswith("http://") or string.startswith("https://")
def is_file(string):
"""Check if a string is a valid file."""
return os.path.isfile(string)
def main():
logger = logging.getLogger(__name__)
log_handler = logging.StreamHandler()
@@ -40,13 +45,35 @@ def main():
)
parser.add_argument(
"--model_name",
default="UVR_MDXNET_KARA_2",
help="Optional: model name to be used for separation (default: %(default)s). Example: --model_name=UVR-MDX-NET-Inst_HQ_3",
"--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'",
)
# Use tempfile to get the platform-independent temp directory
default_model_dir = os.path.join(tempfile.gettempdir(), "audio-separator-models")
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",
nargs="+",
default=[
"UVR_MDXNET_KARA_2.onnx",
"2_HP-UVR.pth",
"model_bs_roformer_ep_317_sdr_12.9755.yaml",
"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_model_dir_unix = "/tmp/audio-separator-models/"
if os.name == "posix" and os.path.exists(default_model_dir_unix):
default_model_dir = default_model_dir_unix
else:
# Use tempfile to get the platform-independent temp directory
default_model_dir = os.path.join(tempfile.gettempdir(), "audio-separator-models")
parser.add_argument(
"--model_file_dir",
default=default_model_dir,
@@ -132,28 +159,198 @@ def main():
help="Optional: Font color for intro video title text (default: #ffffff). Example: --intro_title_color=#123456",
)
parser.add_argument(
"--existing_instrumental",
help="Optional: Path to an existing instrumental audio file. If provided, audio separation will be skipped.",
)
parser.add_argument(
"--existing_title_image",
help="Optional: Path to an existing title image file. If provided, title image generation will be skipped.",
)
parser.add_argument(
"--end_background_color",
default="#000000",
help="Optional: Background color for end screen video (default: black). Example: --end_background_color=#123456",
)
parser.add_argument(
"--end_background_image",
help="Optional: Path to background image for end screen video. Overrides background color if provided. Example: --end_background_image=path/to/image.jpg",
)
parser.add_argument(
"--end_extra_text",
default="THANK YOU FOR SINGING!",
help="Optional: Extra text to display on the end screen video. Example: --end_extra_text='THANK YOU FOR WATCHING!'",
)
parser.add_argument(
"--end_font",
default="Montserrat-Bold.ttf",
help="Optional: Font file for end screen video (default: Montserrat-Bold.ttf). Example: --end_font=AvenirNext-Bold.ttf",
)
parser.add_argument(
"--end_extra_text_color",
default="#ff7acc",
help="Optional: Font color for end screen video text (default: #ffffff). Example: --end_extra_text_color=#123456",
)
parser.add_argument(
"--end_artist_color",
default="#ffdf6b",
help="Optional: Font color for end screen video artist text (default: #ffdf6b). Example: --end_artist_color=#123456",
)
parser.add_argument(
"--end_title_color",
default="#ffffff",
help="Optional: Font color for end screen video title text (default: #ffffff). Example: --end_title_color=#123456",
)
parser.add_argument(
"--existing_end_image",
help="Optional: Path to an existing end screen image file. If provided, end screen image generation will be skipped.",
)
parser.add_argument(
"--title_video_duration",
type=int,
default=5,
help="Optional: duration of the title video in seconds (default: 5). Example: --title_video_duration=10",
)
parser.add_argument(
"--end_video_duration",
type=int,
default=5,
help="Optional: duration of the end video in seconds (default: 5). Example: --end_video_duration=10",
)
parser.add_argument(
"--title_initial_font_size",
type=int,
default=500,
help="Optional: Initial font size for title video (default: 500). Example: --title_initial_font_size=600",
)
parser.add_argument(
"--title_top_padding",
type=int,
default=950,
help="Optional: Top padding for title video (default: 950). Example: --title_top_padding=1000",
)
parser.add_argument(
"--title_title_padding",
type=int,
default=400,
help="Optional: Title padding for title video (default: 400). Example: --title_title_padding=450",
)
parser.add_argument(
"--title_artist_padding",
type=int,
default=700,
help="Optional: Artist padding for title video (default: 700). Example: --title_artist_padding=750",
)
parser.add_argument(
"--title_fixed_gap",
type=int,
default=150,
help="Optional: Fixed gap for title video (default: 150). Example: --title_fixed_gap=200",
)
parser.add_argument(
"--end_initial_font_size",
type=int,
default=500,
help="Optional: Initial font size for end video (default: 500). Example: --end_initial_font_size=600",
)
parser.add_argument(
"--end_top_padding",
type=int,
default=950,
help="Optional: Top padding for end video (default: 950). Example: --end_top_padding=1000",
)
parser.add_argument(
"--end_title_padding",
type=int,
default=400,
help="Optional: Title padding for end video (default: 400). Example: --end_title_padding=450",
)
parser.add_argument(
"--end_artist_padding",
type=int,
default=700,
help="Optional: Artist padding for end video (default: 700). Example: --end_artist_padding=750",
)
parser.add_argument(
"--end_extra_text_padding",
type=int,
default=300,
help="Optional: Extra text padding for end video (default: 600). Example: --end_extra_text_padding=650",
)
parser.add_argument(
"--end_fixed_gap",
type=int,
default=150,
help="Optional: Fixed gap for end video (default: 150). Example: --end_fixed_gap=200",
)
parser.add_argument(
"--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",
)
args = parser.parse_args()
url, artist, title = None, None, None
input_media, artist, title, filename_pattern = None, None, None, None
if not args.args:
parser.print_help()
exit(1)
# Allow 3 forms of positional arguments:
# 1. URL only (may be single track URL or playlist URL)
# 1. URL or Media File only (may be single track URL, playlist URL, or local file)
# 2. Artist and Title only
# 3. URL, Artist, and Title
if args.args and is_url(args.args[0]):
url = args.args[0]
if args.args and (is_url(args.args[0]) or is_file(args.args[0])):
input_media = 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 title")
logger.warn("Input media provided without Artist and Title, both will be guessed from title")
elif os.path.isdir(args.args[0]):
if not args.filename_pattern:
logger.error("Filename pattern is required when processing a folder.")
exit(1)
if len(args.args) <= 1:
logger.error("Second parameter provided must be Artist name; Artist is required when processing a folder.")
exit(1)
input_media = args.args[0]
artist = args.args[1]
filename_pattern = args.filename_pattern
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.")
logger.warn(f"No input media provided, the top YouTube search result for {artist} - {title} will be used.")
else:
parser.print_help()
exit(1)
@@ -161,15 +358,20 @@ def main():
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}")
if args.existing_instrumental:
args.model_names = ["Custom"]
logger.info(f"KaraokePrep beginning with input_media: {input_media} artist: {artist} and title: {title}")
kprep = KaraokePrep(
artist=artist,
title=title,
url=url,
input_media=input_media,
filename_pattern=filename_pattern,
dry_run=args.dry_run,
log_formatter=log_formatter,
log_level=log_level,
model_name=args.model_name,
model_names=args.model_names,
model_file_dir=args.model_file_dir,
output_dir=args.output_dir,
lossless_output_format=args.lossless_output_format,
@@ -179,11 +381,37 @@ def main():
normalization_enabled=args.normalize,
denoise_enabled=args.denoise,
create_track_subfolders=args.no_track_subfolders,
existing_instrumental=args.existing_instrumental,
existing_title_image=args.existing_title_image,
existing_end_image=args.existing_end_image,
title_video_duration=args.title_video_duration,
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,
title_initial_font_size=args.title_initial_font_size,
title_top_padding=args.title_top_padding,
title_title_padding=args.title_title_padding,
title_artist_padding=args.title_artist_padding,
title_fixed_gap=args.title_fixed_gap,
end_video_duration=args.end_video_duration,
end_extra_text=args.end_extra_text,
end_background_color=args.end_background_color,
end_background_image=args.end_background_image,
end_font=args.end_font,
end_extra_text_color=args.end_extra_text_color,
end_artist_color=args.end_artist_color,
end_title_color=args.end_title_color,
end_initial_font_size=args.end_initial_font_size,
end_top_padding=args.end_top_padding,
end_title_padding=args.end_title_padding,
end_artist_padding=args.end_artist_padding,
end_extra_text_padding=args.end_extra_text_padding,
end_fixed_gap=args.end_fixed_gap,
lyrics_artist=args.lyrics_artist,
lyrics_title=args.lyrics_title,
skip_lyrics=args.skip_lyrics,
)
tracks = kprep.process()
@@ -198,8 +426,12 @@ def main():
logger.info(f" Input Still Image: {track['input_still_image']}")
logger.info(f" Lyrics: {track['lyrics']}")
logger.info(f" Processed Lyrics: {track['processed_lyrics']}")
logger.info(f" Instrumental: {track['instrumental_audio']}")
logger.info(f" Vocals: {track['vocals_audio']}")
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']}")
if __name__ == "__main__":
Generated
+1422 -984
View File
File diff suppressed because it is too large. Load diff
+8 -8
View File
@@ -1,17 +1,17 @@
[tool.poetry]
name = "karaoke-prep"
version = "0.13.0"
version = "0.22.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"
readme = "README.md"
packages = [{include = "karaoke_prep"}]
packages = [{ include = "karaoke_prep" }]
homepage = "https://github.com/karaokenerds/karaoke-prep"
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"
requests = ">=2"
beautifulsoup4 = ">=4"
yt-dlp = "*"
@@ -23,11 +23,11 @@ google-api-python-client = "*"
google-auth = "*"
google-auth-oauthlib = "*"
google-auth-httplib2 = "*"
audio-separator = { version = ">=0.13", optional = true, extras = ["silicon"] }
pyperclip = "^1.8.2"
[tool.poetry.extras]
silicon = ["audio-separator"]
pyperclip = ">=1.8"
thefuzz = ">=0.22"
numpy = "^1"
audio-separator = { version = ">=0.17.5", extras = ["cpu"] }
lyrics-converter = ">=0.2.1"
[tool.poetry.group.dev.dependencies]
black = ">=23"