mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-01 09:37:12 +09:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ada4ba039 | ||
|
|
ba1a1b90f7 | ||
|
|
88d07bb862 | ||
|
|
4a292fabd3 | ||
|
|
ceef4f5081 | ||
|
|
d33ad04016 | ||
|
|
513f8181df | ||
|
|
fd49ca3c68 | ||
|
|
d064d8388a | ||
|
|
096e499f6a | ||
|
|
ee6874d094 | ||
|
|
798ee11121 | ||
|
|
bbb15b9744 | ||
|
|
c643fa6d73 | ||
|
|
390892ba2d | ||
|
|
aaef3376ae | ||
|
|
ad9492d7e3 |
No files matched your search
@@ -4,7 +4,7 @@ on: [push, workflow_dispatch]
|
||||
|
||||
jobs:
|
||||
# Auto-publish when version is increased
|
||||
publish-job:
|
||||
publish-pypi:
|
||||
# Only publish on `main` branch
|
||||
if: github.ref == 'refs/heads/main'
|
||||
runs-on: ubuntu-latest
|
||||
@@ -17,3 +17,35 @@ jobs:
|
||||
pypi-token: ${{ secrets.PYPI_API_TOKEN }}
|
||||
gh-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
parse-changelog: false
|
||||
|
||||
build-windows:
|
||||
runs-on: windows-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v2
|
||||
with:
|
||||
python-version: '3.9'
|
||||
|
||||
- name: Install dependencies with Poetry
|
||||
run: |
|
||||
pip install poetry
|
||||
poetry install
|
||||
|
||||
- name: Download ffmpeg binary
|
||||
run: python platform/download_ffmpeg.py
|
||||
|
||||
- name: Build EXE with PyInstaller
|
||||
run: poetry run pyinstaller karaoke-prep.spec
|
||||
|
||||
- name: Upload EXE as Artifact
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: karaoke-prep-windows
|
||||
path: |
|
||||
build/
|
||||
*.exe
|
||||
*/*.exe
|
||||
|
||||
+1
-1
@@ -40,7 +40,7 @@ MANIFEST
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
# *.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
# -*- mode: python ; coding: utf-8 -*-
|
||||
|
||||
|
||||
a = Analysis(
|
||||
['karaoke_prep/utils/prep_cli.py'],
|
||||
pathex=[],
|
||||
binaries=[('platform/ffmpeg.exe', '.')],
|
||||
datas=[],
|
||||
hiddenimports=[],
|
||||
hookspath=[],
|
||||
hooksconfig={},
|
||||
runtime_hooks=[],
|
||||
excludes=[],
|
||||
noarchive=False,
|
||||
)
|
||||
pyz = PYZ(a.pure)
|
||||
|
||||
exe = EXE(
|
||||
pyz,
|
||||
a.scripts,
|
||||
a.binaries,
|
||||
a.datas,
|
||||
[],
|
||||
name='karaoke-prep',
|
||||
debug=False,
|
||||
bootloader_ignore_signals=False,
|
||||
strip=False,
|
||||
upx=True,
|
||||
upx_exclude=[],
|
||||
runtime_tmpdir=None,
|
||||
console=True,
|
||||
disable_windowed_traceback=False,
|
||||
argv_emulation=False,
|
||||
target_arch=None,
|
||||
codesign_identity=None,
|
||||
entitlements_file=None,
|
||||
)
|
||||
@@ -1,7 +1,16 @@
|
||||
import os
|
||||
import sys
|
||||
import subprocess
|
||||
import tempfile
|
||||
import logging
|
||||
import zipfile
|
||||
import shutil
|
||||
import re
|
||||
import pickle
|
||||
from googleapiclient.discovery import build
|
||||
from google_auth_oauthlib.flow import InstalledAppFlow
|
||||
from google.auth.transport.requests import Request
|
||||
from googleapiclient.http import MediaFileUpload
|
||||
|
||||
|
||||
class KaraokeFinalise:
|
||||
@@ -9,7 +18,16 @@ class KaraokeFinalise:
|
||||
self,
|
||||
log_level=logging.DEBUG,
|
||||
log_formatter=None,
|
||||
dry_run=False,
|
||||
force=False,
|
||||
model_name="UVR_MDXNET_KARA_2",
|
||||
instrumental_format="flac",
|
||||
brand_prefix=None,
|
||||
target_dir=None,
|
||||
public_share_dir=None,
|
||||
youtube_client_secrets_file=None,
|
||||
youtube_description_file=None,
|
||||
rclone_destination=None,
|
||||
):
|
||||
self.logger = logging.getLogger(__name__)
|
||||
self.logger.setLevel(log_level)
|
||||
@@ -24,66 +42,283 @@ class KaraokeFinalise:
|
||||
self.log_handler.setFormatter(self.log_formatter)
|
||||
self.logger.addHandler(self.log_handler)
|
||||
|
||||
self.logger.debug(f"KaraokeFinalise instantiating")
|
||||
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}"
|
||||
)
|
||||
|
||||
self.ffmpeg_base_command = "ffmpeg -hide_banner -nostats"
|
||||
# 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"
|
||||
|
||||
self.ffmpeg_base_command = f"{ffmpeg_path} -hide_banner -nostats"
|
||||
|
||||
if self.log_level == logging.DEBUG:
|
||||
self.ffmpeg_base_command += " -loglevel verbose"
|
||||
else:
|
||||
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.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
|
||||
|
||||
def authenticate_youtube(self):
|
||||
"""Authenticate and return a YouTube service object."""
|
||||
credentials = None
|
||||
pickle_file = "/tmp/karaoke-finalise-token.pickle"
|
||||
|
||||
# Token file stores the user's access and refresh tokens.
|
||||
if os.path.exists(pickle_file):
|
||||
with open(pickle_file, "rb") as token:
|
||||
credentials = pickle.load(token)
|
||||
|
||||
# If there are no valid credentials, let the user log in.
|
||||
if not credentials or not credentials.valid:
|
||||
if credentials and credentials.expired and credentials.refresh_token:
|
||||
credentials.refresh(Request())
|
||||
else:
|
||||
flow = InstalledAppFlow.from_client_secrets_file(
|
||||
self.youtube_client_secrets_file, scopes=["https://www.googleapis.com/auth/youtube.upload"]
|
||||
)
|
||||
credentials = flow.run_local_server(port=0) # This will open a browser for authentication
|
||||
|
||||
# Save the credentials for the next run
|
||||
with open(pickle_file, "wb") as token:
|
||||
pickle.dump(credentials, token)
|
||||
|
||||
return build("youtube", "v3", credentials=credentials)
|
||||
|
||||
def upload_to_youtube(self, video_file_path, title, description, category_id, keywords):
|
||||
"""Upload video to YouTube."""
|
||||
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)
|
||||
response = request.execute()
|
||||
|
||||
self.logger.info(f"Uploaded video to YouTube: {response.get('id')}")
|
||||
|
||||
def get_next_sequence_number(self):
|
||||
"""
|
||||
Calculate the next sequence number based on existing directories in the target_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
|
||||
|
||||
for dir_name in os.listdir(self.target_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
|
||||
|
||||
def process(self):
|
||||
tracks = []
|
||||
|
||||
self.logger.info(f"Searching for files in current directory ending with (Karaoke).mov")
|
||||
for karaoke_file in filter(lambda f: " (Karaoke).mov" in f, os.listdir(".")):
|
||||
base_name = karaoke_file.replace(" (Karaoke).mov", "")
|
||||
if self.dry_run:
|
||||
self.logger.info("Dry run enabled. No actions will be performed.")
|
||||
|
||||
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]
|
||||
|
||||
with_vocals_file = f"{base_name} (With Vocals).mov"
|
||||
# Input files which should already exist after karaoke-prep and manual production process
|
||||
title_file = f"{base_name} (Title).mov"
|
||||
instrumental_file = f"{base_name} (Instrumental {self.model_name}).mp3"
|
||||
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"
|
||||
|
||||
# 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"
|
||||
|
||||
track = {
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
"video_with_vocals": with_vocals_file,
|
||||
"video_with_instrumental": karaoke_file,
|
||||
"final_video": final_mp4_file,
|
||||
}
|
||||
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 os.path.isfile(title_file) and os.path.isfile(karaoke_file) and os.path.isfile(instrumental_file):
|
||||
self.logger.info(f"All 3 input files found for {base_name}, beginning finalisation")
|
||||
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 []
|
||||
|
||||
self.logger.info(f"Output [With Vocals]: renaming synced video to: {with_vocals_file}")
|
||||
os.rename(karaoke_file, with_vocals_file)
|
||||
if not os.path.isfile(title_file):
|
||||
self.logger.error(f"Title file not found: {title_file}")
|
||||
return []
|
||||
|
||||
self.logger.info(f"Output [With Instrumental]: remuxing synced video with instrumental audio to: {karaoke_file}")
|
||||
if not os.path.isfile(with_vocals_file):
|
||||
self.logger.error(f"With Vocals file not found: {with_vocals_file}")
|
||||
return []
|
||||
|
||||
ffmpeg_command = f'{self.ffmpeg_base_command} -an -i "{with_vocals_file}" -vn -i "{instrumental_file}" -c:v copy -c:a aac "{karaoke_file}"'
|
||||
self.logger.debug(f"Running command: {ffmpeg_command}")
|
||||
os.system(ffmpeg_command)
|
||||
if not os.path.isfile(instrumental_file):
|
||||
self.logger.error(f"Instrumental file not found: {instrumental_file}")
|
||||
return []
|
||||
|
||||
if not os.path.isfile(cdg_file):
|
||||
self.logger.error(f"CDG file not found: {cdg_file}")
|
||||
return []
|
||||
|
||||
if not os.path.isfile(mp3_file):
|
||||
self.logger.error(f"MP3 file not found: {mp3_file}")
|
||||
return []
|
||||
|
||||
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"
|
||||
)
|
||||
|
||||
# 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}")
|
||||
|
||||
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.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)
|
||||
|
||||
# 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}")
|
||||
|
||||
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_file)}'\n")
|
||||
tmp_file_list.write(f"file '{os.path.abspath(karaoke_mov_file)}'\n")
|
||||
|
||||
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}"'
|
||||
self.logger.debug(f"Running command: {ffmpeg_command}")
|
||||
os.system(ffmpeg_command)
|
||||
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}"'
|
||||
|
||||
os.remove(tmp_file_list.name)
|
||||
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)
|
||||
|
||||
# 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}")
|
||||
|
||||
# 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)
|
||||
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
self.logger.info(f"Moved all files to: {new_dir_path}")
|
||||
else:
|
||||
self.logger.error(f"Unable to find all 3 required input files:\n {title_file}\n {karaoke_file}\n {instrumental_file}")
|
||||
self.logger.info("brand_prefix or target_dir not specified, skipping move")
|
||||
|
||||
tracks.append(track)
|
||||
# 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")
|
||||
|
||||
src_mp4_file = os.path.join(new_dir_path, final_mp4_file)
|
||||
src_zip_file = os.path.join(new_dir_path, final_zip_file)
|
||||
|
||||
dest_mp4_file = os.path.join(self.public_share_dir, f"{new_track_prefix} {base_name} (Karaoke).mp4")
|
||||
dest_zip_file = os.path.join(self.public_share_dir, f"{new_track_prefix} {base_name} (Karaoke).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")
|
||||
|
||||
# Upload to YouTube
|
||||
if self.youtube_client_secrets_file is not None:
|
||||
src_mp4_file = os.path.join(new_dir_path, final_mp4_file)
|
||||
|
||||
if self.dry_run:
|
||||
self.logger.info(
|
||||
f"DRY RUN: Would upload {src_mp4_file} to YouTube 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,
|
||||
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
|
||||
+275
-183
@@ -1,11 +1,13 @@
|
||||
import os
|
||||
import sys
|
||||
import re
|
||||
import glob
|
||||
import yt_dlp
|
||||
import logging
|
||||
import lyricsgenius
|
||||
import tempfile
|
||||
import pyperclip
|
||||
import importlib.resources as pkg_resources
|
||||
import yt_dlp.YoutubeDL as ydl
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
|
||||
@@ -21,7 +23,8 @@ class KaraokePrep:
|
||||
model_name_2="UVR-MDX-NET-Inst_HQ_3",
|
||||
model_file_dir=os.path.join(tempfile.gettempdir(), "audio-separator-models"),
|
||||
output_dir=".",
|
||||
output_format="WAV",
|
||||
lossless_output_format="FLAC",
|
||||
lossy_output_format="MP3",
|
||||
use_cuda=False,
|
||||
use_coreml=False,
|
||||
normalization_enabled=True,
|
||||
@@ -48,6 +51,8 @@ class KaraokePrep:
|
||||
|
||||
self.logger.debug(f"KaraokePrep instantiating with url: {url} artist: {artist} title: {title}")
|
||||
|
||||
self.extractor = None
|
||||
self.media_id = None
|
||||
self.url = url
|
||||
self.artist = artist
|
||||
self.title = title
|
||||
@@ -55,14 +60,18 @@ class KaraokePrep:
|
||||
self.model_name_2 = model_name_2
|
||||
self.model_file_dir = model_file_dir
|
||||
self.output_dir = output_dir
|
||||
self.output_format = output_format
|
||||
self.lossless_output_format = lossless_output_format.lower()
|
||||
self.lossy_output_format = lossy_output_format.lower()
|
||||
self.use_cuda = use_cuda
|
||||
self.use_coreml = use_coreml
|
||||
self.normalization_enabled = normalization_enabled
|
||||
self.denoise_enabled = denoise_enabled
|
||||
self.create_track_subfolders = create_track_subfolders
|
||||
|
||||
self.ffmpeg_base_command = "ffmpeg -hide_banner -nostats"
|
||||
# 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"
|
||||
|
||||
self.ffmpeg_base_command = f"{ffmpeg_path} -hide_banner -nostats"
|
||||
|
||||
if self.log_level == logging.DEBUG:
|
||||
self.ffmpeg_base_command += " -loglevel verbose"
|
||||
@@ -79,7 +88,7 @@ class KaraokePrep:
|
||||
|
||||
self.persistent_artist = None
|
||||
|
||||
self.logger.debug(f"KaraokePrep output_format: {self.output_format}")
|
||||
self.logger.debug(f"KaraokePrep lossless_output_format: {self.lossless_output_format}")
|
||||
|
||||
if not os.path.exists(self.output_dir):
|
||||
self.logger.debug(f"Overall output dir {self.output_dir} did not exist, creating")
|
||||
@@ -87,89 +96,111 @@ class KaraokePrep:
|
||||
else:
|
||||
self.logger.debug(f"Overall output dir {self.output_dir} already exists")
|
||||
|
||||
def extract_metadata_from_url(self):
|
||||
"""
|
||||
Extracts metadata from the YouTube URL.
|
||||
"""
|
||||
if self.url:
|
||||
with yt_dlp.YoutubeDL({"quiet": True}) as ydl:
|
||||
info = ydl.extract_info(self.url, download=False)
|
||||
self.artist, self.title = self.parse_metadata(info)
|
||||
if self.persistent_artist:
|
||||
self.artist = self.persistent_artist
|
||||
if self.artist and self.title:
|
||||
self.logger.info(f"Extracted artist: {self.artist}, title: {self.title}")
|
||||
else:
|
||||
self.logger.error("Failed to extract artist and title from the YouTube URL.")
|
||||
def extract_info_for_online_media(self, input_url=None, input_artist=None, input_title=None):
|
||||
self.logger.info(f"Extracting info for input_url: {input_url} input_artist: {input_artist} input_title: {input_title}")
|
||||
if input_url is not None:
|
||||
# If a URL is provided, use it to extract the metadata
|
||||
with ydl({"quiet": True}) as ydl_instance:
|
||||
self.extracted_info = ydl_instance.extract_info(input_url, download=False)
|
||||
else:
|
||||
# If no URL is provided, use the query to search for the top result
|
||||
ydl_opts = {"quiet": "True", "format": "bestaudio", "noplaylist": "True", "extract_flat": True}
|
||||
with ydl(ydl_opts) as ydl_instance:
|
||||
query = f"{input_artist} {input_title} topic"
|
||||
self.extracted_info = ydl_instance.extract_info(f"ytsearch1:{query}", download=False)["entries"][0]
|
||||
if not self.extracted_info:
|
||||
raise Exception(f"No search results found on YouTube for query: {input_artist} {input_title}")
|
||||
|
||||
def parse_metadata(self, info):
|
||||
def parse_single_track_metadata(self, input_artist, input_title):
|
||||
"""
|
||||
Parses the metadata to extract artist and title.
|
||||
|
||||
:param info: The metadata information extracted from yt_dlp.
|
||||
:return: A tuple containing the artist and title.
|
||||
Parses self.extracted_info to extract URL, extractor, ID, artist and title.
|
||||
"""
|
||||
# Default values if parsing fails
|
||||
artist = ""
|
||||
title = ""
|
||||
self.url = None
|
||||
self.extractor = None
|
||||
self.media_id = None
|
||||
|
||||
metadata_artist = ""
|
||||
metadata_title = ""
|
||||
|
||||
if "url" in self.extracted_info:
|
||||
self.url = self.extracted_info["url"]
|
||||
elif "webpage_url" in self.extracted_info:
|
||||
self.url = self.extracted_info["webpage_url"]
|
||||
else:
|
||||
raise Exception(f"Failed to extract URL from input media metadata: {self.extracted_info}")
|
||||
|
||||
if "extractor_key" in self.extracted_info:
|
||||
self.extractor = self.extracted_info["extractor_key"]
|
||||
elif "ie_key" in self.extracted_info:
|
||||
self.extractor = self.extracted_info["ie_key"]
|
||||
else:
|
||||
raise Exception(f"Failed to find extractor name from input media metadata: {self.extracted_info}")
|
||||
|
||||
if "id" in self.extracted_info:
|
||||
self.media_id = self.extracted_info["id"]
|
||||
|
||||
# Example: "Artist - Title"
|
||||
if "title" in info and "-" in info["title"]:
|
||||
artist, title = info["title"].split("-", 1)
|
||||
artist = artist.strip()
|
||||
title = title.strip()
|
||||
elif "uploader" in info:
|
||||
if "title" in self.extracted_info and "-" in self.extracted_info["title"]:
|
||||
metadata_artist, metadata_title = self.extracted_info["title"].split("-", 1)
|
||||
metadata_artist = metadata_artist.strip()
|
||||
metadata_title = metadata_title.strip()
|
||||
elif "uploader" in self.extracted_info:
|
||||
# Fallback to uploader as artist if title parsing fails
|
||||
artist = info["uploader"]
|
||||
if "title" in info:
|
||||
title = info["title"].strip()
|
||||
metadata_artist = self.extracted_info["uploader"]
|
||||
if "title" in self.extracted_info:
|
||||
metadata_title = self.extracted_info["title"].strip()
|
||||
|
||||
# If unable to parse, log an appropriate message
|
||||
if not artist or not title:
|
||||
self.logger.warning("Could not parse artist and title from the video metadata.")
|
||||
if not metadata_artist or not metadata_title:
|
||||
self.logger.warning("Could not parse artist and title from the input media metadata.")
|
||||
|
||||
return artist, title
|
||||
if input_artist is None:
|
||||
self.logger.warn(f"Artist not provided as input, setting to {metadata_artist} from input media metadata...")
|
||||
self.artist = metadata_artist
|
||||
|
||||
def get_youtube_id_for_top_search_result(self, query):
|
||||
ydl_opts = {"quiet": "True", "format": "bestaudio", "noplaylist": "True", "extract_flat": True}
|
||||
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
||||
video = ydl.extract_info(f"ytsearch1:{query}", download=False)["entries"][0]
|
||||
if input_title is None:
|
||||
self.logger.warn(f"Title not provided as input, setting to {metadata_title} from input media metadata...")
|
||||
self.title = metadata_title
|
||||
|
||||
if video:
|
||||
youtube_id = video.get("id")
|
||||
return youtube_id
|
||||
else:
|
||||
self.logger.warning(f"No YouTube results found for query: {query}")
|
||||
return None
|
||||
if self.persistent_artist:
|
||||
self.logger.debug(
|
||||
f"Resetting self.artist from {self.artist} to persistent artist: {self.persistent_artist} for consistency while processing playlist..."
|
||||
)
|
||||
self.artist = self.persistent_artist
|
||||
|
||||
def download_video(self, youtube_id, output_filename_no_extension):
|
||||
self.logger.debug(f"Downloading YouTube video {youtube_id} to filename {output_filename_no_extension} + (as yet) unknown extension")
|
||||
if self.artist and self.title:
|
||||
self.logger.info(f"Extracted url: {self.url}, artist: {self.artist}, title: {self.title}")
|
||||
else:
|
||||
self.logger.debug(self.extracted_info)
|
||||
raise Exception("Failed to extract artist and title from the input media metadata.")
|
||||
|
||||
downloaded_file_name = output_filename_no_extension
|
||||
actual_file_extension = None
|
||||
|
||||
def ydl_progress_hook(d):
|
||||
nonlocal actual_file_extension
|
||||
if d["status"] == "finished":
|
||||
actual_file_extension = d["filename"].split(".")[-1]
|
||||
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")
|
||||
|
||||
ydl_opts = {
|
||||
"quiet": True,
|
||||
"format": "bv*+ba/b", # if a combined video + audio format is better than the best video-only format use the combined format
|
||||
"outtmpl": f"{output_filename_no_extension}",
|
||||
"progress_hooks": [ydl_progress_hook],
|
||||
"outtmpl": f"{output_filename_no_extension}.%(ext)s",
|
||||
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",
|
||||
}
|
||||
|
||||
with yt_dlp.YoutubeDL(ydl_opts) as youtube_dl_instance:
|
||||
youtube_dl_instance.download([f"https://www.youtube.com/watch?v={youtube_id}"])
|
||||
downloaded_file_name += f".{actual_file_extension}"
|
||||
self.logger.info(f"Download finished, returning downloaded filename: {downloaded_file_name}")
|
||||
return downloaded_file_name
|
||||
with ydl(ydl_opts) as ydl_instance:
|
||||
ydl_instance.download([url])
|
||||
|
||||
# Search for the file with any extension
|
||||
downloaded_files = glob.glob(f"{output_filename_no_extension}.*")
|
||||
if downloaded_files:
|
||||
downloaded_file_name = downloaded_files[0] # Assume the first match is the correct one
|
||||
self.logger.info(f"Download finished, returning downloaded filename: {downloaded_file_name}")
|
||||
return downloaded_file_name
|
||||
else:
|
||||
self.logger.error("No files found matching the download pattern.")
|
||||
return None
|
||||
|
||||
def extract_still_image_from_video(self, input_filename, output_filename_no_extension):
|
||||
output_filename = output_filename_no_extension + ".png"
|
||||
self.logger.info(f"Extracting still image from position 30s YouTube video")
|
||||
self.logger.info(f"Extracting still image from position 30s input media")
|
||||
ffmpeg_command = f'{self.ffmpeg_base_command} -i "{input_filename}" -ss 00:00:30 -vframes 1 "{output_filename}"'
|
||||
self.logger.debug(f"Running command: {ffmpeg_command}")
|
||||
os.system(ffmpeg_command)
|
||||
@@ -178,7 +209,7 @@ 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")
|
||||
ffmpeg_command = f'{self.ffmpeg_base_command} -i "{input_filename}" "{output_filename}"'
|
||||
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)
|
||||
return output_filename
|
||||
@@ -196,6 +227,7 @@ class KaraokePrep:
|
||||
return lyrics.split("\n")
|
||||
else:
|
||||
self.logger.warning("Could not find lyrics for %s by %s", title, artist)
|
||||
return None
|
||||
|
||||
def clean_genius_lyrics(self, lyrics):
|
||||
lyrics = lyrics.replace("\\n", "\n")
|
||||
@@ -222,6 +254,7 @@ class KaraokePrep:
|
||||
self.logger.debug(f"Finding best_split_point for line: {line}")
|
||||
words = line.split()
|
||||
mid_word_index = len(words) // 2
|
||||
self.logger.debug(f"words: {words} mid_word_index: {mid_word_index}")
|
||||
|
||||
# Check for a comma within one or two words of the middle word
|
||||
if "," in line:
|
||||
@@ -229,9 +262,9 @@ class KaraokePrep:
|
||||
comma_indices = [i for i, char in enumerate(line) if char == ","]
|
||||
|
||||
for index in comma_indices:
|
||||
if abs(mid_point - index) < 20: # Roughly the length of two average words
|
||||
if abs(mid_point - index) < 20 and len(line[: index + 1].strip()) <= 36:
|
||||
self.logger.debug(
|
||||
f"Found comma at index {index} which is within 20 characters of mid_point {mid_point}, accepting as split point"
|
||||
f"Found comma at index {index} which is within 20 characters of mid_point {mid_point} and results in a suitable line length, accepting as split point"
|
||||
)
|
||||
return index + 1 # Include the comma in the first line
|
||||
|
||||
@@ -239,13 +272,23 @@ class KaraokePrep:
|
||||
if " and " in line:
|
||||
mid_point = len(line) // 2
|
||||
and_indices = [m.start() for m in re.finditer(" and ", line)]
|
||||
split_point = min(and_indices, key=lambda x: abs(x - mid_point))
|
||||
self.logger.debug(f"Found 'and' at index {split_point} which is close to mid_point {mid_point}, accepting as split point")
|
||||
return split_point + len(" and ") # Include 'and' in the first line
|
||||
for index in sorted(and_indices, key=lambda x: abs(x - mid_point)):
|
||||
if len(line[: index + len(" and ")].strip()) <= 36:
|
||||
self.logger.debug(f"Found 'and' at index {index} which results in a suitable line length, accepting as split point")
|
||||
return index + len(" and ")
|
||||
|
||||
# Split at the middle word
|
||||
self.logger.debug(f"No comma or suitable 'and' found, using middle word as split point")
|
||||
return len(" ".join(words[:mid_word_index]))
|
||||
# If no better split point is found, try splitting at the middle word
|
||||
if len(words) > 2 and mid_word_index > 0:
|
||||
split_at_middle = len(" ".join(words[:mid_word_index]))
|
||||
if split_at_middle <= 36:
|
||||
self.logger.debug(f"Splitting at middle word index: {mid_word_index}")
|
||||
return split_at_middle
|
||||
|
||||
# If the line is still too long, forcibly split at the maximum length
|
||||
forced_split_point = 36
|
||||
if len(line) > forced_split_point:
|
||||
self.logger.debug(f"Line is still too long, forcibly splitting at position {forced_split_point}")
|
||||
return forced_split_point
|
||||
|
||||
def process_line(self, line):
|
||||
"""
|
||||
@@ -253,7 +296,14 @@ class KaraokePrep:
|
||||
and handle parentheses.
|
||||
"""
|
||||
processed_lines = []
|
||||
iteration_count = 0
|
||||
max_iterations = 100 # Failsafe limit
|
||||
|
||||
while len(line) > 36:
|
||||
if iteration_count > max_iterations:
|
||||
self.logger.error(f"Maximum iterations exceeded in process_line for line: {line}")
|
||||
break
|
||||
|
||||
# Check if the line contains parentheses
|
||||
if "(" in line and ")" in line:
|
||||
start_paren = line.find("(")
|
||||
@@ -270,17 +320,27 @@ class KaraokePrep:
|
||||
processed_lines.append(line[:split_point].strip())
|
||||
line = line[split_point:].strip()
|
||||
|
||||
iteration_count += 1
|
||||
|
||||
if line: # Add the remaining part if not empty
|
||||
processed_lines.append(line)
|
||||
|
||||
return processed_lines
|
||||
|
||||
def write_processed_lyrics(self, lyrics, processed_lyrics_file):
|
||||
self.logger.debug(f"Writing processed lyrics to {processed_lyrics_file}")
|
||||
self.logger.info(f"Writing processed lyrics to {processed_lyrics_file}")
|
||||
|
||||
processed_lyrics_lines = ""
|
||||
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
|
||||
|
||||
all_processed = True
|
||||
new_lyrics = []
|
||||
for line in lyrics:
|
||||
@@ -291,9 +351,16 @@ class KaraokePrep:
|
||||
all_processed = False
|
||||
lyrics = new_lyrics
|
||||
|
||||
iteration_count += 1
|
||||
|
||||
# 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):
|
||||
"""Replace or remove characters that are unsafe for filenames."""
|
||||
@@ -311,23 +378,24 @@ 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 output_format: {self.output_format}"
|
||||
f"instantiating Separator with model_name: {model_name} instrumental_path: {instrumental_path} and lossless_output_format: {self.lossless_output_format}"
|
||||
)
|
||||
|
||||
from audio_separator import Separator
|
||||
from audio_separator.separator import Separator
|
||||
|
||||
separator = Separator(
|
||||
audio_file,
|
||||
log_level=self.log_level,
|
||||
log_formatter=self.log_formatter,
|
||||
model_name=model_name,
|
||||
model_file_dir=self.model_file_dir,
|
||||
output_format=self.output_format,
|
||||
output_format=self.lossless_output_format,
|
||||
primary_stem_path=instrumental_path,
|
||||
secondary_stem_path=vocals_path,
|
||||
)
|
||||
_, _ = separator.separate()
|
||||
self.logger.debug(f"Separation complete!")
|
||||
|
||||
separator.load_model(model_name)
|
||||
output_files = separator.separate(audio_file)
|
||||
|
||||
self.logger.info(f"Separation complete! Output file(s): {' '.join(output_files)}")
|
||||
|
||||
def setup_output_paths(self, artist, title):
|
||||
sanitized_artist = self.sanitize_filename(artist)
|
||||
@@ -401,11 +469,9 @@ class KaraokePrep:
|
||||
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:
|
||||
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
|
||||
)
|
||||
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
|
||||
)
|
||||
@@ -436,145 +502,171 @@ class KaraokePrep:
|
||||
return tuple(int(hex_color[i : i + 2], 16) for i in (0, 2, 4))
|
||||
|
||||
def prep_single_track(self):
|
||||
if self.artist is None or self.title is None:
|
||||
self.logger.warn(f"Artist or Title nor specified manually, guessing from YouTube metadata...")
|
||||
self.extract_metadata_from_url()
|
||||
self.logger.info(f"Preparing single track: {self.artist} - {self.title}")
|
||||
|
||||
artist = self.artist
|
||||
title = 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)
|
||||
|
||||
self.logger.info(f"Preparing output path for track: {title} by {artist}")
|
||||
track_output_dir, artist_title = self.setup_output_paths(artist, title)
|
||||
self.logger.info(f"Preparing output path for track: {self.title} by {self.artist}")
|
||||
track_output_dir, artist_title = self.setup_output_paths(self.artist, self.title)
|
||||
processed_track = {
|
||||
"track_output_dir": track_output_dir,
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
"artist": self.artist,
|
||||
"title": self.title,
|
||||
"extractor": self.extractor,
|
||||
"extracted_info": self.extracted_info,
|
||||
"lyrics": None,
|
||||
"processed_lyrics": None,
|
||||
}
|
||||
|
||||
self.logger.info(f"Creating title video...")
|
||||
processed_track["title_image"] = os.path.join(track_output_dir, f"{artist_title} (Title).png")
|
||||
processed_track["title_video"] = os.path.join(track_output_dir, f"{artist_title} (Title).mov")
|
||||
self.create_title_video(artist, title, self.title_format, processed_track["title_image"], processed_track["title_video"])
|
||||
# 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)
|
||||
|
||||
lyrics_file = os.path.join(track_output_dir, f"{artist_title} (Lyrics).txt")
|
||||
processed_lyrics_file = os.path.join(track_output_dir, f"{artist_title} (Lyrics Processed).txt")
|
||||
if os.path.exists(lyrics_file):
|
||||
self.logger.debug(f"Lyrics file already exists, skipping fetch: {lyrics_file}")
|
||||
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]
|
||||
|
||||
self.logger.info(f"Input media files already exist, skipping download: {processed_track['input_media']} + .wav + .png")
|
||||
else:
|
||||
self.logger.info("Fetching lyrics from Genius...")
|
||||
lyrics = self.write_lyrics_from_genius(artist, title, lyrics_file)
|
||||
self.write_processed_lyrics(lyrics, processed_lyrics_file)
|
||||
if self.url:
|
||||
output_filename_no_extension = os.path.join(track_output_dir, f"{artist_title} ({self.extractor} {self.media_id})")
|
||||
|
||||
processed_track["lyrics"] = lyrics_file
|
||||
processed_track["processed_lyrics"] = processed_lyrics_file
|
||||
self.logger.info(f"Downloading input media from {self.url}...")
|
||||
processed_track["input_media"] = self.download_video(self.url, output_filename_no_extension)
|
||||
|
||||
# WebM may not always be the output format from YouTubeDL, but it's the most common and this is just a convenience cache
|
||||
yt_webm_filename_pattern = os.path.join(track_output_dir, f"{artist_title} (YouTube *.webm")
|
||||
yt_webm_glob = glob.glob(yt_webm_filename_pattern)
|
||||
|
||||
yt_png_filename_pattern = os.path.join(track_output_dir, f"{artist_title} (YouTube *.png")
|
||||
yt_png_glob = glob.glob(yt_png_filename_pattern)
|
||||
|
||||
yt_wav_filename_pattern = os.path.join(track_output_dir, f"{artist_title} (YouTube *.wav")
|
||||
yt_wav_glob = glob.glob(yt_wav_filename_pattern)
|
||||
|
||||
processed_track["youtube_video"] = None
|
||||
processed_track["youtube_still_image"] = None
|
||||
processed_track["youtube_audio"] = None
|
||||
|
||||
if yt_webm_glob and yt_png_glob and yt_wav_glob:
|
||||
processed_track["youtube_video"] = yt_webm_glob[0]
|
||||
processed_track["youtube_still_image"] = yt_png_glob[0]
|
||||
processed_track["youtube_audio"] = yt_wav_glob[0]
|
||||
|
||||
self.logger.debug(f"YouTube output files already exist, skipping download: {processed_track['youtube_video']} + .wav + .png")
|
||||
else:
|
||||
if self.url is None:
|
||||
self.logger.warn(f"No URL specified - the top result from YouTube will be used.")
|
||||
self.logger.info("Searching YouTube for video ID...")
|
||||
query = f"{artist} {title}"
|
||||
youtube_id = self.get_youtube_id_for_top_search_result(query)
|
||||
else:
|
||||
self.logger.info("Parsing YouTube video ID from URL...")
|
||||
youtube_id = self.url.split("watch?v=")[1]
|
||||
if youtube_id:
|
||||
output_filename_no_extension = os.path.join(track_output_dir, f"{artist_title} (YouTube {youtube_id})")
|
||||
|
||||
self.logger.info("Downloading original video from YouTube...")
|
||||
processed_track["youtube_video"] = self.download_video(youtube_id, output_filename_no_extension)
|
||||
|
||||
self.logger.info("Extracting still image from downloaded video...")
|
||||
processed_track["youtube_still_image"] = self.extract_still_image_from_video(
|
||||
processed_track["youtube_video"], output_filename_no_extension
|
||||
self.logger.info("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["youtube_audio"] = self.convert_to_wav(processed_track["youtube_video"], output_filename_no_extension)
|
||||
processed_track["input_audio_wav"] = self.convert_to_wav(processed_track["input_media"], output_filename_no_extension)
|
||||
else:
|
||||
self.logger.warning(f"Skipping {title} by {artist} due to missing YouTube ID.")
|
||||
self.logger.warning(f"Skipping download due to missing URL.")
|
||||
|
||||
self.logger.info(f"Separating audio twice for track: {title} by {artist}")
|
||||
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"])
|
||||
|
||||
instrumental_path = os.path.join(track_output_dir, f"{artist_title} (Instrumental {self.model_name}).{self.output_format}")
|
||||
vocals_path = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name}).{self.output_format}")
|
||||
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"])
|
||||
|
||||
processed_track["title_image"] = os.path.join(track_output_dir, f"{artist_title} (Title).png")
|
||||
processed_track["title_video"] = os.path.join(track_output_dir, f"{artist_title} (Title).mov")
|
||||
|
||||
if os.path.exists(processed_track["title_video"]):
|
||||
self.logger.debug(f"Title video already exists, skipping render: {processed_track['title_video']}")
|
||||
else:
|
||||
self.logger.info(f"Creating title video...")
|
||||
self.create_title_video(
|
||||
self.artist, self.title, self.title_format, processed_track["title_image"], processed_track["title_video"]
|
||||
)
|
||||
|
||||
self.logger.info(f"Separating audio twice for track: {self.title} by {self.artist}")
|
||||
|
||||
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}")
|
||||
else:
|
||||
self.separate_audio(processed_track["youtube_audio"], self.model_name, instrumental_path, vocals_path)
|
||||
self.separate_audio(processed_track["input_audio_wav"], self.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"] = instrumental_path
|
||||
processed_track["vocals_audio"] = vocals_path
|
||||
|
||||
instrumental_path_2 = os.path.join(track_output_dir, f"{artist_title} (Instrumental {self.model_name_2}).{self.output_format}")
|
||||
vocals_path_2 = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name_2}).{self.output_format}")
|
||||
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}")
|
||||
else:
|
||||
self.separate_audio(processed_track["youtube_audio"], self.model_name_2, instrumental_path_2, vocals_path_2)
|
||||
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)
|
||||
|
||||
processed_track["instrumental_audio_2"] = instrumental_path_2
|
||||
processed_track["vocals_audio_2"] = vocals_path_2
|
||||
|
||||
processed_track["instrumental_audio_2_lossy"] = instrumental_path_2_lossy
|
||||
processed_track["vocals_audio_2_lossy"] = vocals_path_2_lossy
|
||||
|
||||
self.logger.info("Script finished, audio downloaded, lyrics fetched and audio separated!")
|
||||
|
||||
return processed_track
|
||||
|
||||
def is_playlist_url(self):
|
||||
"""
|
||||
Checks if the provided URL is a YouTube playlist URL.
|
||||
"""
|
||||
if self.url and "playlist?list=" in self.url:
|
||||
return True
|
||||
return False
|
||||
def convert_to_lossy(self, input_filename, output_filename):
|
||||
if input_filename is None or not os.path.isfile(input_filename):
|
||||
raise Exception(f"Error: Invalid input file provided for convert_to_lossy: {input_filename}")
|
||||
|
||||
self.logger.info(f"Converting {self.lossless_output_format} audio to lossy {self.lossy_output_format} format")
|
||||
|
||||
ffmpeg_extras = "-q:a 0" if self.lossy_output_format == "mp3" else ""
|
||||
|
||||
ffmpeg_command = f'{self.ffmpeg_base_command} -i "{input_filename}" {ffmpeg_extras} "{output_filename}"'
|
||||
self.logger.debug(f"Running command: {ffmpeg_command}")
|
||||
os.system(ffmpeg_command)
|
||||
|
||||
def process_playlist(self):
|
||||
"""
|
||||
Processes all videos in a YouTube playlist.
|
||||
"""
|
||||
self.logger.debug(f"Querying playlist metadata from YouTube, assuming consistent artist {self.artist}...")
|
||||
with yt_dlp.YoutubeDL({"quiet": True}) as ydl:
|
||||
result = ydl.extract_info(self.url, download=False)
|
||||
if "entries" in result:
|
||||
track_results = []
|
||||
self.logger.info(f"Found {len(result['entries'])} videos in playlist, processing each invididually...")
|
||||
for video in result["entries"]:
|
||||
video_url = f"https://www.youtube.com/watch?v={video['id']}"
|
||||
self.logger.info(f"Processing video: {video_url}")
|
||||
self.url = video_url
|
||||
track_results.append(self.prep_single_track())
|
||||
self.artist = self.persistent_artist
|
||||
self.title = None
|
||||
return track_results
|
||||
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())
|
||||
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):
|
||||
if self.is_playlist_url():
|
||||
# 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"Provided YouTube URL is a playlist, beginning batch operation with persistent artist: {self.persistent_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"Provided YouTube URL is NOT a playlist, processing single track")
|
||||
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
|
||||
return [self.prep_single_track()]
|
||||
@@ -26,12 +26,66 @@ def main():
|
||||
help="Optional: logging level, e.g. info, debug, warning (default: %(default)s). Example: --log_level=debug",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--dry_run",
|
||||
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",
|
||||
)
|
||||
|
||||
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",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--instrumental_format",
|
||||
default="flac",
|
||||
help="Optional: format / file extension for instrumental track to use for remux (default: %(default)s). Example: --instrumental_format=mp3",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--brand_prefix",
|
||||
default=None,
|
||||
help="Optional: Your brand prefix to calculate the next sequential number and move the resulting folder. Example: --brand_prefix=BRAND",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--target_dir",
|
||||
default=None,
|
||||
help="Optional: Target directory where the processed folder will be moved after finalisation. Example: --target_dir='/path/to/Tracks-Organized'",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--public_share_dir",
|
||||
default=None,
|
||||
help="Optional: Public share directory where final MP4 and ZIP files will be copied. Example: --public_share_dir='/path/to/Tracks-PublicShare'",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--youtube_client_secrets_file",
|
||||
default=None,
|
||||
help="Optional: File path to youtube client secrets file. Example: --youtube_client_secrets_file='/path/to/client_secret_1234567890_apps.googleusercontent.com.json'",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--youtube_description_file",
|
||||
default=None,
|
||||
help="Optional: File path to youtube video description text for uploaded videos. Example: --youtube_description_file='/path/to/youtube_description.txt'",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--rclone_destination",
|
||||
default=None,
|
||||
help="Optional: Rclone destination to sync your public_share_dir to after adding files to it. Example: --rclone_destination='googledrive:YourBrandNameFolder'",
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
log_level = getattr(logging, args.log_level.upper())
|
||||
@@ -42,7 +96,16 @@ def main():
|
||||
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,
|
||||
brand_prefix=args.brand_prefix,
|
||||
target_dir=args.target_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,
|
||||
)
|
||||
|
||||
tracks = kfinalise.process()
|
||||
@@ -57,7 +120,8 @@ def main():
|
||||
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 Video with Title: {track['final_video']}")
|
||||
logger.info(f" Final CDG+MP3 ZIP: {track['final_video']}")
|
||||
logger.info(f" Final Video with Title: {track['final_zip']}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -27,7 +27,7 @@ def main():
|
||||
parser.add_argument(
|
||||
"args",
|
||||
nargs="*",
|
||||
help="[YouTube video or playlist URL] [Artist] [Title] of song to prep. If URL is provided, Artist and Title are optional but increase chance of fetching the correct lyrics. If Artist and Title are provided with no URL, the top YouTube search result will be fetched.",
|
||||
help="[Media or playlist URL] [Artist] [Title] of song to prep. If URL is provided, Artist and Title are optional but increase chance of fetching the correct lyrics. If Artist and Title are provided with no URL, the top YouTube search result will be fetched.",
|
||||
)
|
||||
|
||||
package_version = pkg_resources.get_distribution("karaoke-prep").version
|
||||
@@ -60,9 +60,15 @@ def main():
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--output_format",
|
||||
default="mp3",
|
||||
help="Optional: output format for separated audio (default: mp3). Example: --output_format=flac",
|
||||
"--lossless_output_format",
|
||||
default="FLAC",
|
||||
help="Optional: lossless output format for separated audio (default: FLAC). Example: --lossless_output_format=WAV",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--lossy_output_format",
|
||||
default="MP3",
|
||||
help="Optional: lossy output format for separated audio (default: MP3). Example: --lossy_output_format=OGG",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
@@ -142,7 +148,7 @@ def main():
|
||||
elif len(args.args) > 1:
|
||||
artist = args.args[1]
|
||||
else:
|
||||
logger.warn("URL provided without Artist and Title, both will be guessed from YouTube Title")
|
||||
logger.warn("URL provided without Artist and Title, both will be guessed from title")
|
||||
|
||||
elif len(args.args) > 1:
|
||||
artist = args.args[0]
|
||||
@@ -166,7 +172,8 @@ def main():
|
||||
model_name=args.model_name,
|
||||
model_file_dir=args.model_file_dir,
|
||||
output_dir=args.output_dir,
|
||||
output_format=args.output_format,
|
||||
lossless_output_format=args.lossless_output_format,
|
||||
lossy_output_format=args.lossy_output_format,
|
||||
use_cuda=args.use_cuda,
|
||||
use_coreml=args.use_coreml,
|
||||
normalization_enabled=args.normalize,
|
||||
@@ -186,9 +193,9 @@ def main():
|
||||
for track in tracks:
|
||||
logger.info(f"")
|
||||
logger.info(f"Track: {track['artist']} - {track['title']}")
|
||||
logger.info(f" YouTube Video: {track['youtube_video']}")
|
||||
logger.info(f" YouTube Audio: {track['youtube_audio']}")
|
||||
logger.info(f" YouTube Still Image: {track['youtube_still_image']}")
|
||||
logger.info(f" Input Media: {track['input_media']}")
|
||||
logger.info(f" Input WAV Audio: {track['input_audio_wav']}")
|
||||
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']}")
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import requests
|
||||
|
||||
|
||||
def download_file(url, filename):
|
||||
# Send a GET request to the URL
|
||||
response = requests.get(url, stream=True)
|
||||
|
||||
# Check if the request was successful
|
||||
if response.status_code == 200:
|
||||
# Open a file with the specified filename in binary write mode
|
||||
with open(filename, "wb") as file:
|
||||
# Write the content of the response to the file
|
||||
for chunk in response.iter_content(chunk_size=8192):
|
||||
file.write(chunk)
|
||||
print("Download completed.")
|
||||
else:
|
||||
print(f"Failed to download. Status code: {response.status_code}")
|
||||
|
||||
|
||||
# URL of the file to be downloaded
|
||||
url = "https://github.com/karaokenerds/karaoke-prep/releases/download/v0.8.3/ffmpeg.exe"
|
||||
# Filename to save the downloaded file
|
||||
filename = "platform/ffmpeg.exe"
|
||||
|
||||
# Call the function to download the file
|
||||
download_file(url, filename)
|
||||
Generated
+848
-286
File diff suppressed because it is too large.
Load diff
+18
-9
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-prep"
|
||||
version = "0.8.2"
|
||||
version = "0.11.1"
|
||||
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"
|
||||
@@ -11,17 +11,26 @@ repository = "https://github.com/karaokenerds/karaoke-prep"
|
||||
documentation = "https://github.com/karaokenerds/karaoke-prep/blob/main/README.md"
|
||||
|
||||
[tool.poetry.dependencies]
|
||||
python = ">=3.9"
|
||||
requests = "^2"
|
||||
beautifulsoup4 = "^4"
|
||||
python = ">=3.9,<3.13"
|
||||
requests = ">=2"
|
||||
beautifulsoup4 = ">=4"
|
||||
yt-dlp = "*"
|
||||
lyricsgenius = "^3"
|
||||
fetch-lyrics-from-genius = "^0.1"
|
||||
audio-separator = "^0.8"
|
||||
pillow = "^10.1.0"
|
||||
lyricsgenius = ">=3"
|
||||
fetch-lyrics-from-genius = ">=0.1"
|
||||
pillow = ">=10.1"
|
||||
pyinstaller = ">=6.3"
|
||||
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"]
|
||||
|
||||
[tool.poetry.group.dev.dependencies]
|
||||
black = "^23"
|
||||
black = ">=23"
|
||||
|
||||
[tool.poetry.scripts]
|
||||
karaoke-prep = 'karaoke_prep.utils.prep_cli:main'
|
||||
|
||||
Reference in new issue
Block a user