Compare commits

...
2 Commits
5 changed files with 72 additions and 102 deletions

No files matched your search

@@ -109,6 +109,7 @@ class KaraokeFinalise:
"karaoke_mp3": " (Karaoke).mp3",
"karaoke_mov": " (Karaoke).mov",
"final_karaoke_mp4": " (Final Karaoke).mp4",
"final_karaoke_lossless_mkv": " (Final Karaoke Lossless).mkv",
"final_karaoke_cdg_zip": " (Final Karaoke CDG).zip",
"final_karaoke_txt_zip": " (Final Karaoke TXT).zip",
"final_karaoke_720p_mp4": " (Final Karaoke 720p).mp4",
@@ -166,6 +167,7 @@ class KaraokeFinalise:
"karaoke_mp3": f"{base_name}{self.suffixes['karaoke_mp3']}",
"with_vocals_mp4": f"{base_name}{self.suffixes['with_vocals_mp4']}",
"final_karaoke_mp4": f"{base_name}{self.suffixes['final_karaoke_mp4']}",
"final_karaoke_lossless_mkv": f"{base_name}{self.suffixes['final_karaoke_lossless_mkv']}",
"final_karaoke_720p_mp4": f"{base_name}{self.suffixes['final_karaoke_720p_mp4']}",
}
@@ -349,10 +351,10 @@ class KaraokeFinalise:
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...")
self.logger.info(f"Uploading final lossless MKV 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}'
f'DRY RUN: Would upload {output_files["final_karaoke_lossless_mkv"]} to YouTube with thumbnail {input_files["title_jpg"]} using client secrets file: {self.youtube_client_secrets_file}'
)
else:
youtube_title = f"{artist} - {title} (Karaoke)"
@@ -387,11 +389,11 @@ class KaraokeFinalise:
"status": {"privacyStatus": "public"},
}
# Use MediaFileUpload to handle the video file
media_file = MediaFileUpload(output_files["final_karaoke_mp4"], mimetype="video/mp4", resumable=True)
# Use MediaFileUpload to handle the video file - now using the lossless MKV
media_file = MediaFileUpload(output_files["final_karaoke_lossless_mkv"], mimetype="video/x-matroska", resumable=True)
# Call the API's videos.insert method to create and upload the video.
self.logger.info(f"Uploading final MP4 to YouTube...")
self.logger.info(f"Uploading final lossless MKV to YouTube...")
request = youtube.videos().insert(part="snippet,status", body=body, media_body=media_file)
response = request.execute()
@@ -541,11 +543,15 @@ class KaraokeFinalise:
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 (
os.path.isfile(output_files["karaoke_mov"])
and os.path.isfile(output_files["final_karaoke_mp4"])
and os.path.isfile(output_files["final_karaoke_lossless_mkv"])
):
if not self.prompt_user_bool(
f"Found existing Final Karaoke output file: {output_files['final_karaoke_mp4']}. Overwrite (y) or skip (n)?",
f"Found existing Final Karaoke output files. Overwrite (y) or skip (n)?",
):
self.logger.info(f"Skipping Karaoke MOV remux and Final MP4 render, existing files will be used.")
self.logger.info(f"Skipping Karaoke MOV remux and Final video renders, existing files will be used.")
return
# Remux the synced video with the instrumental audio to produce an instrumental karaoke MOV file
@@ -574,7 +580,7 @@ class KaraokeFinalise:
# 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")
self.logger.info(f"Found end_mov file: {input_files['end_mov']}, including in final MKV")
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]"'
@@ -587,15 +593,31 @@ class KaraokeFinalise:
if "aac_at" in result:
aac_codec = "aac_at"
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_codec} -q:a 14 {output_final_mp4_file}'
# Create the lossless MKV version first (for YouTube upload)
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]"'
self.logger.debug(f"Running command: {join_ffmpeg_command}")
self.execute_command(join_ffmpeg_command, "Joining title and instrumental videos")
# 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 MKV")
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]"'
# Prompt user to check final MP4 file before proceeding
# Create lossless MKV with FLAC audio
join_ffmpeg_command_mkv = 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 flac "{output_files["final_karaoke_lossless_mkv"]}"'
self.execute_command(join_ffmpeg_command_mkv, "Creating lossless MKV version with FLAC audio")
# Create the regular MP4 version (for sharing)
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_codec} -q:a 14 "{output_files["final_karaoke_mp4"]}"'
self.execute_command(join_ffmpeg_command, "Creating MP4 version with AAC audio")
# Prompt user to check final video files 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.",
f"Final video files created: {output_files['final_karaoke_mp4']} and {output_files['final_karaoke_lossless_mkv']}, please check them! Proceed?",
"Refusing to proceed without user confirmation they're happy with the Final videos.",
allow_empty=True,
)
+20 -79
View File
@@ -9,7 +9,6 @@ import importlib.resources as pkg_resources
import yt_dlp.YoutubeDL as ydl
from PIL import Image, ImageDraw, ImageFont
from lyrics_transcriber import LyricsTranscriber
from karaoke_lyrics_processor import KaraokeLyricsProcessor
from pydub import AudioSegment
@@ -38,6 +37,7 @@ class KaraokePrep:
lyrics_artist=None,
lyrics_title=None,
skip_lyrics=False,
skip_transcription=False,
output_png=True,
output_jpg=True,
render_bounding_boxes=False,
@@ -103,6 +103,8 @@ class KaraokePrep:
self.create_track_subfolders = create_track_subfolders
self.existing_instrumental = existing_instrumental
self.existing_title_image = existing_title_image
self.lyrics = None
self.lyrics_artist = lyrics_artist
self.lyrics_title = lyrics_title
self.skip_lyrics = skip_lyrics
@@ -111,6 +113,7 @@ class KaraokePrep:
self.output_jpg = output_jpg
self.intro_video_duration = intro_video_duration
self.end_video_duration = end_video_duration
self.skip_transcription = skip_transcription
# 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"
@@ -390,10 +393,10 @@ class KaraokePrep:
f"Transcribing lyrics for track {artist} - {title} from audio file: {input_audio_wav} with output directory: {track_output_dir}"
)
if os.environ.get("AUDIOSHAKE_API_TOKEN") is None:
self.logger.warning("AUDIOSHAKE_API_TOKEN environment variable is not set, AudioShake transcription will be skipped")
self.logger.debug("Loading LyricsTranscriber class")
# Create lyrics subdirectory
lyrics_dir = os.path.join(track_output_dir, "lyrics")
os.makedirs(lyrics_dir, exist_ok=True)
self.logger.info(f"Created lyrics directory: {lyrics_dir}")
transcriber = LyricsTranscriber(
input_audio_wav,
@@ -401,42 +404,20 @@ class KaraokePrep:
log_formatter=self.log_formatter,
artist=artist,
title=title,
output_dir=track_output_dir,
output_dir=lyrics_dir,
skip_transcription=self.skip_transcription,
)
transcriber_outputs = transcriber.generate()
if transcriber_outputs:
self.logger.info(f"*** Outputs: ***")
self.logger.info(f"Transcription output data file: {transcriber_outputs.get('transcription_data_filepath')}")
self.logger.info(f"Transcribed lyrics text file: {transcriber_outputs.get('transcribed_lyrics_text_filepath')}")
self.logger.info(f"MidiCo LRC output file: {transcriber_outputs.get('midico_lrc_filepath')}")
self.logger.info(f"*** Transcriber Filepath Outputs: ***")
for key, value in transcriber_outputs.items():
if key.endswith("_filepath"):
self.logger.info(f" {key}: {value}")
return transcriber_outputs
def write_processed_lyrics(self, lyrics_file, processed_lyrics_file):
if self._file_exists(processed_lyrics_file):
return processed_lyrics_file
self.logger.info(f"Processing lyrics from {lyrics_file} and writing to {processed_lyrics_file}")
if not self.dry_run:
processor = KaraokeLyricsProcessor(
log_level=self.log_level,
log_formatter=self.log_formatter,
input_filename=lyrics_file,
output_filename=processed_lyrics_file,
max_line_length=36, # Using the default max line length
)
processor.process()
processor.write_to_output_file()
self.logger.info(f"Lyrics processing complete, processed lyrics written to: {processed_lyrics_file}")
else:
self.logger.info(f"DRY RUN: Would process lyrics from {lyrics_file} and write to: {processed_lyrics_file}")
return processed_lyrics_file
def sanitize_filename(self, filename):
"""Replace or remove characters that are unsafe for filenames."""
# Replace problematic characters with underscores
@@ -790,7 +771,9 @@ class KaraokePrep:
stems_dir = self._create_stems_directory(track_output_dir)
result = {"clean_instrumental": {}, "other_stems": {}, "backing_vocals": {}, "combined_instrumentals": {}}
return result
if os.environ.get("KARAOKE_PREP_SKIP_AUDIO_SEPARATION"):
return result
result["clean_instrumental"] = self._separate_clean_instrumental(separator, audio_file, artist_title, track_output_dir, stems_dir)
result["other_stems"] = self._separate_other_stems(separator, audio_file, artist_title, stems_dir)
@@ -1053,63 +1036,21 @@ class KaraokePrep:
processed_track["lyrics"] = None
processed_track["processed_lyrics"] = None
else:
# transcriber_outputs = {
# "transcription_data_dict_whisper": None,
# "transcription_data_whisper_filepath": None,
# "transcribed_lyrics_text_whisper": None,
# "transcribed_lyrics_text_whisper_filepath": None,
# "transcription_data_dict_audioshake": None,
# "transcription_data_audioshake_filepath": None,
# "transcribed_lyrics_text_audioshake": None,
# "transcribed_lyrics_text_audioshake_filepath": None,
# "transcription_data_dict_primary": None,
# "transcription_data_primary_filepath": None,
# "transcribed_lyrics_text_primary": None,
# "transcribed_lyrics_text_primary_filepath": None,
# "genius_lyrics_text": None,
# "genius_lyrics_filepath": None,
# "spotify_lyrics_data_dict": None,
# "spotify_lyrics_data_filepath": None,
# "spotify_lyrics_text_filepath": None,
# "llm_token_usage": {"input": 0, "output": 0},
# "llm_costs_usd": {"input": 0.0, "output": 0.0, "total": 0.0},
# "llm_transcript": None,
# "llm_transcript_filepath": None,
# "corrected_lyrics_text": None,
# "corrected_lyrics_text_filepath": None,
# "midico_lrc_filepath": None,
# "ass_subtitles_filepath": None,
# "karaoke_video_filepath": None,
# "singing_percentage": None,
# "total_singing_duration": None,
# "song_duration": None,
# "output_dir": None,
# }
lyrics_artist = self.lyrics_artist or self.artist
lyrics_title = self.lyrics_title or self.title
transcriber_outputs = self.transcribe_lyrics(processed_track["input_audio_wav"], lyrics_artist, lyrics_title, track_output_dir)
if transcriber_outputs:
self.lyrics = transcriber_outputs.get("corrected_lyrics_text")
processed_track["lyrics"] = transcriber_outputs.get("corrected_lyrics_text_filepath")
else:
self.lyrics = None
processed_track["lyrics"] = None
processed_track["processed_lyrics"] = os.path.join(track_output_dir, f"{artist_title} (Lyrics Corrected Processed).txt")
if self.lyrics is None:
processed_track["lyrics"] = None
processed_track["processed_lyrics"] = None
else:
self.write_processed_lyrics(processed_track["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"
processed_track["title_image_jpg"] = f"{output_image_filepath_noext}.jpg"
processed_track["title_video"] = os.path.join(track_output_dir, f"{artist_title} (Title).mov")
if not self._file_exists(processed_track["title_video"]):
if not self._file_exists(processed_track["title_video"]) and not os.environ.get("KARAOKE_PREP_SKIP_TITLE_END_SCREENS"):
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"])
@@ -1118,7 +1059,7 @@ class KaraokePrep:
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")
if not self._file_exists(processed_track["end_video"]):
if not self._file_exists(processed_track["end_video"]) and not os.environ.get("KARAOKE_PREP_SKIP_TITLE_END_SCREENS"):
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"])
+7
View File
@@ -308,6 +308,12 @@ def main():
help="Optional: Region for artist text in end video (x, y, width, height; default: 370,1210,3100,480). Example: --end_artist_region=370,1210,3100,480",
)
parser.add_argument(
"--skip_transcription",
action="store_true",
help="Optional: Skip audio transcription but still attempt to fetch lyrics from Spotify/Genius. Example: --skip_transcription",
)
args = parser.parse_args()
input_media, artist, title, filename_pattern = None, None, None, None
@@ -411,6 +417,7 @@ def main():
intro_extra_text_region=args.intro_extra_text_region,
end_extra_text=args.end_extra_text,
end_extra_text_region=args.end_extra_text_region,
skip_transcription=args.skip_transcription,
)
tracks = kprep.process()
Generated
+6 -5
View File
@@ -1824,18 +1824,19 @@ files = [
[[package]]
name = "lyrics-transcriber"
version = "0.19.0"
version = "0.20.0"
description = "Automatically create synchronised lyrics files in ASS and MidiCo LRC formats with word-level timestamps, using Whisper and lyrics from Genius and Spotify"
optional = false
python-versions = ">=3.9"
python-versions = "<3.13,>=3.9"
files = [
{file = "lyrics_transcriber-0.19.0-py3-none-any.whl", hash = "sha256:5aa265d8349e0edd271488b73750c33a471ca3bfa6c5c8b60200c9c2503109c5"},
{file = "lyrics_transcriber-0.19.0.tar.gz", hash = "sha256:8805b3d610774ba2d784b920778505227325a6348e9566ff09a1cb5cbe00ac58"},
{file = "lyrics_transcriber-0.20.0-py3-none-any.whl", hash = "sha256:791d1b8b8d729c77632370710be012eef26df606a9be56800b14d465ef6bcf0d"},
{file = "lyrics_transcriber-0.20.0.tar.gz", hash = "sha256:cdca5937efad586bb9ca8a3f304de4eaca0b5f41923605a1e715bf6c92f7a0b4"},
]
[package.dependencies]
Cython = ">=0"
dtw-python = ">=1"
karaoke-lyrics-processor = ">=0.4.1"
llvmlite = ">=0"
lyricsgenius = ">=3"
numba = ">=0.57"
@@ -4582,4 +4583,4 @@ type = ["pytest-mypy"]
[metadata]
lock-version = "2.0"
python-versions = ">=3.10,<3.13"
content-hash = "55bbc21dd3b9215475ebb89689fb6e0dd6189d36a2eb01f0bd270956ffa95d29"
content-hash = "94de51a3701fd3e1a5218e6ebdea786397896dd27f850e27d6aac0216af13794"
+2 -3
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-prep"
version = "0.31.0"
version = "0.32.0"
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"
@@ -28,9 +28,8 @@ thefuzz = ">=0.22"
numpy = "^1"
audio-separator = { version = ">=0.21.0", extras = ["cpu"] }
lyrics-converter = ">=0.2.1"
lyrics-transcriber = ">=0.19"
lyrics-transcriber = ">=0.20.0"
kbputils = "^0.0.16"
karaoke-lyrics-processor = ">=0.4.1"
attrs = ">=24.2.0"
cattrs = ">=24.1.2"
toml = ">=0.10"