mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-01 01:31:32 +09:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fd49ca3c68 | ||
|
|
d064d8388a | ||
|
|
096e499f6a | ||
|
|
ee6874d094 | ||
|
|
798ee11121 | ||
|
|
bbb15b9744 | ||
|
|
c643fa6d73 | ||
|
|
390892ba2d | ||
|
|
aaef3376ae | ||
|
|
ad9492d7e3 | ||
|
|
5560557c3a | ||
|
|
4ce326727d | ||
|
|
fe6b89be9b | ||
|
|
90297bd7ef | ||
|
|
8924875c26 | ||
|
|
27946a1dd8 | ||
|
|
b701920c75 | ||
|
|
0c77999c46 | ||
|
|
341a346865 | ||
|
|
a5a35c710e | ||
|
|
ac774d9aad | ||
|
|
2d988de0a3 | ||
|
|
6a6154fe44 | ||
|
|
f3ebaf5858 | ||
|
|
10554f19ee | ||
|
|
ff90b72a34 | ||
|
|
1e8a23ad50 | ||
|
|
9fbe04ecf8 | ||
|
|
224a9cfd57 | ||
|
|
9f8a6edab3 | ||
|
|
4bd2d121ae | ||
|
|
5a1095556c | ||
|
|
5877b9b8da | ||
|
|
bcc1196152 | ||
|
|
6c93bf3e50 | ||
|
|
292aa75d5d | ||
|
|
cdc4330873 |
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
|
||||
|
||||
@@ -15,6 +15,9 @@ This was created to make it easier for me to prepare the source audio, lyrics an
|
||||
- Easy Configuration: Control the tool's behavior using command-line arguments.
|
||||
- Organized Outputs: Creates structured output directories for easy access to generated tracks and lyrics.
|
||||
- Internet First: Completes operations which require internet first, in case user is preparing last-minute before a period of being offline!
|
||||
- Flexible Input: provide just a YouTube URL, just an artist and title, or both.
|
||||
- Playlist Processing: Capable of processing an entire YouTube playlist, extracting audio and lyrics for each track.
|
||||
- Easy Finalisation: After manually performing your sync (e.g. using [MidiCo](https://www.midicokaraoke.com)), run `karaoke-finalise` to remux and add your title screen!
|
||||
|
||||
## Installation 🛠️
|
||||
|
||||
@@ -22,6 +25,26 @@ You can install Karaoke Prep using pip:
|
||||
|
||||
`pip install karaoke-prep`
|
||||
|
||||
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
|
||||
- Command Line basics Windows: https://www.youtube.com/watch?v=MBBWVgE0ewk
|
||||
- Install Python on Mac: https://www.youtube.com/watch?v=3-sPfR4JEQ8
|
||||
- Command Line basics Mac: https://www.youtube.com/watch?v=FfT8OfMpARM
|
||||
|
||||
## Karaoke production guide using karaoke-prep and MidiCo
|
||||
|
||||
- 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`
|
||||
- Copy/paste the lyrics into MidiCo: `(Lyrics Processed).txt`
|
||||
- Perform the lyrics sync (here's a [video](https://www.youtube.com/watch?v=63-Fk3mfZ7Q) showing me doing it) in MidiCo
|
||||
- Render the video to 4k using the MidiCo "Export Movie" feature, saving it as `Artist - Title (Karaoke).mov` in the same folder
|
||||
- Run `karaoke-finalise` to remux the instrumental audio and join the title clip to the start
|
||||
- Upload the resulting `Artist - Title (Final Karaoke).mp4` video to YouTube!
|
||||
|
||||
Here's my [tutorial video with verbal explanation](https://www.youtube.com/watch?v=ZsROHgqAVHs) of the whole process, and here's a [normal speed demo](https://www.youtube.com/watch?v=63-Fk3mfZ7Q) of me doing it (8 minutes total for a single track).
|
||||
|
||||
|
||||
## Usage 🚀
|
||||
|
||||
@@ -37,9 +60,7 @@ usage: karaoke-prep [-h] [-v] [--log_level LOG_LEVEL] [--model_name MODEL_NAME]
|
||||
Fetch audio and lyrics for a specified song, to prepare karaoke video creation.
|
||||
|
||||
positional arguments:
|
||||
artist Artist name for the song to prep.
|
||||
title Title of the song to prep.
|
||||
url YouTube URL of the song to prep.
|
||||
args [YouTube video or playlist URL] [Artist] [Title] of song to prep. If URL is provided, Artist and Title are optional but increase chance of fetching the correct lyrics. If Artist and Title are provided with no URL, the top YouTube search result will be fetched.
|
||||
|
||||
options:
|
||||
-h, --help show this help message and exit
|
||||
@@ -52,28 +73,99 @@ options:
|
||||
--use_coreml Optional: use Apple Silicon GPU with CoreML for separation (default: False). Example: --use_coreml=true
|
||||
--denoise DENOISE Optional: enable or disable denoising during separation (default: True). Example: --denoise=False
|
||||
--normalize NORMALIZE Optional: enable or disable normalization during separation (default: True). Example: --normalize=False
|
||||
--no_track_subfolders Optional:do NOT create a named subfolder for each track. Example: --no_track_subfolders
|
||||
--no_track_subfolders Optional: do NOT create a named subfolder for each track. Example: --no_track_subfolders
|
||||
--intro_background_color INTRO_BACKGROUND_COLOR Optional: Background color for intro video (default: black). Example: --intro_background_color=#123456
|
||||
--intro_background_image INTRO_BACKGROUND_IMAGE Optional: Path to background image for intro video. Overrides background color if provided. Example: --intro_background_image=path/to/image.jpg
|
||||
--intro_font INTRO_FONT Optional: Font file for intro video (default: Avenir-Next-Bold). Example: --intro_font=AvenirNext-Bold.ttf
|
||||
--intro_artist_color INTRO_ARTIST_COLOR Optional: Font color for intro video artist text (default: #ff7acc). Example: --intro_artist_color=#123456
|
||||
--intro_title_color INTRO_TITLE_COLOR Optional: Font color for intro video title text (default: #ffdf6b). Example: --intro_title_color=#123456
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
### ⭐ YouTube URL with Artist and Title
|
||||
|
||||
For the most consistent results, provide a specific YouTube URL along with the artist and title like so:
|
||||
|
||||
```
|
||||
karaoke-prep "https://www.youtube.com/watch?v=YOUR_VIDEO_ID" "The Fray" "Never Say Never"
|
||||
```
|
||||
|
||||
### Artist and Title Only
|
||||
|
||||
If you don't have a specific YouTube URL, just provide the artist and title. Karaoke Prep will search for and download the top YouTube result.
|
||||
|
||||
```
|
||||
karaoke-prep "The Fray" "Never Say Never"
|
||||
```
|
||||
|
||||
This command will search YouTube for the specified song, download audio from the top result and lyrics from genius, then separate the audio to produce an instrumental track, ready for a karaoke video to be created by whatever process you prefer!
|
||||
### Only YouTube URL
|
||||
|
||||
By default, you'll end up with files in the current folder, neatly organised e.g.
|
||||
This will process the video at the given URL, *guessing the artist and title from the YouTube title*.
|
||||
⚠️ Be aware the downloaded lyrics may be incorrect if the video title doesn't match the standard "Artist - Title" format.
|
||||
|
||||
```
|
||||
├── Artist - Title (Instrumental UVR-MDX-NET-Inst_HQ_3).flac
|
||||
├── Artist - Title (Instrumental UVR_MDXNET_KARA_2).flac
|
||||
├── Artist - Title (Lyrics).txt
|
||||
├── Artist - Title (Vocals UVR-MDX-NET-Inst_HQ_3).flac
|
||||
├── Artist - Title (Vocals UVR_MDXNET_KARA_2).flac
|
||||
└── Artist - Title (YouTube CNUgemJBLTw).wav
|
||||
karaoke-prep "https://www.youtube.com/watch?v=YOUR_VIDEO_ID"
|
||||
```
|
||||
|
||||
### YouTube Playlist URL
|
||||
|
||||
To process a playlist, just provide the playlist URL. The script will process every video in the playlist.
|
||||
⚠️ Be aware the downloaded _lyrics_ for each track may be incorrect if the video titles don't match the standard "Artist - Title" format.
|
||||
|
||||
```
|
||||
karaoke-prep "https://www.youtube.com/playlist?list=YOUR_PLAYLIST_ID"
|
||||
```
|
||||
|
||||
## Files produced by karaoke-prep and what to do with them
|
||||
|
||||
After running `karaoke-prep` you should have the following 11 files, grouped into folder(s) for each track:
|
||||
|
||||
- `Artist - Title (YouTube xxxxxxxxxxx).webm`
|
||||
- Original unmodified video, fetched from YouTube in the highest quality available (may not always be WebM)
|
||||
- You probably don't need this unless you're creating a custom request
|
||||
- `Artist - Title (YouTube xxxxxxxxxxx).png`
|
||||
- A still image taken from 30 seconds into the video, in case that's useful for a custom background
|
||||
- You probably don't need this unless you're creating a custom request
|
||||
- `Artist - Title (YouTube xxxxxxxxxxx).wav`
|
||||
- Unmodified audio from the YouTube video, converted to WAV format for compatibility
|
||||
- You should open this in MidiCo to begin syncing lyrics to make your karaoke video.
|
||||
- `Artist - Title (Lyrics).txt`
|
||||
- Unmodified lyrics fetched from genius.com based on the artist/title provided
|
||||
- Depending on the song, may have lines which are too long for one karaoke screen
|
||||
- `Artist - Title (Lyrics Processed).txt`
|
||||
- Lyrics from genius, split into lines no longer than 40 characters
|
||||
- You should open this and copy/paste the text into the MidiCo lyrics editor
|
||||
- `Artist - Title (Vocals UVR-MDX-NET-Inst_HQ_3).mp3`
|
||||
- Vocal track from the audio, separated using the UVR Inst_HQ_3 model.
|
||||
- You probably don't need this unless you're trying to tweak the backing track
|
||||
- `Artist - Title (Vocals UVR_MDXNET_KARA_2).mp3`
|
||||
- Vocal track from the audio, separated using the UVR KARA_2 model.
|
||||
- You probably don't need this unless you're trying to tweak the backing track
|
||||
- `Artist - Title (Instrumental UVR-MDX-NET-Inst_HQ_3).mp3`
|
||||
- Instrumental track from the audio, separated using the UVR Inst_HQ_3 model.
|
||||
- This is typically a safe bet for the instrumental track but will not include any backing vocals.
|
||||
- `Artist - Title (Instrumental UVR_MDXNET_KARA_2).mp3`
|
||||
- Instrumental track from the audio, separated using the UVR KARA_2 model.
|
||||
- This is the default choice for the finalisation step below as it usually does a good job of keeping backing vocals. However for some songs it includes far too much or is kinda glitchy, so you should check it before finalising and make a judgement call about using this vs. the Inst_HQ_3 one.
|
||||
- `Artist - Title (Title).png`
|
||||
- Title screen static image; if you specify your own background image, font, color etc. this should give you a convenient way to add a title screen to the start of your video.
|
||||
- `Artist - Title (Title).mov`
|
||||
- 5 second video clip version of the title screen image, ready to be joined by the finalisation step.
|
||||
|
||||
|
||||
## Finalisation 🎥
|
||||
|
||||
After completing your manual sync process and rendering your `Artist - Title (Karaoke).mov` file (still using the original audio!) into the same folder, you can now run `karaoke-finalise`.
|
||||
|
||||
This will output some additional files:
|
||||
- `Artist - Title (Karaoke).mov`
|
||||
- Karaoke video without title screen, remuxed to use the instrumental audio
|
||||
- `Artist - Title (With Vocals).mov`
|
||||
- Karaoke video without title screen, using the original audio (useful for practicing!)
|
||||
- `Artist - Title (Final Karaoke).mp4`
|
||||
- Final karaoke video with 5 second title screen intro, instrumental audio and converted to MP4 for compatibility and reduced file size. Upload this to YouTube!
|
||||
|
||||
|
||||
## Requirements 📋
|
||||
|
||||
Python >= 3.9
|
||||
|
||||
@@ -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 +1 @@
|
||||
from .requests_prep import KaraokePrep
|
||||
from .karaoke_prep import KaraokePrep
|
||||
@@ -0,0 +1 @@
|
||||
from .karaoke_finalise import KaraokeFinalise
|
||||
@@ -0,0 +1,244 @@
|
||||
import os
|
||||
import sys
|
||||
import subprocess
|
||||
import tempfile
|
||||
import logging
|
||||
import zipfile
|
||||
import shutil
|
||||
import re
|
||||
|
||||
|
||||
class KaraokeFinalise:
|
||||
def __init__(
|
||||
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,
|
||||
rclone_destination=None,
|
||||
):
|
||||
self.logger = logging.getLogger(__name__)
|
||||
self.logger.setLevel(log_level)
|
||||
self.log_level = log_level
|
||||
self.log_formatter = log_formatter
|
||||
|
||||
self.log_handler = logging.StreamHandler()
|
||||
|
||||
if self.log_formatter is None:
|
||||
self.log_formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(module)s - %(message)s")
|
||||
|
||||
self.log_handler.setFormatter(self.log_formatter)
|
||||
self.logger.addHandler(self.log_handler)
|
||||
|
||||
self.logger.debug(
|
||||
f"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}"
|
||||
)
|
||||
|
||||
# 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.rclone_destination = rclone_destination
|
||||
|
||||
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 = []
|
||||
|
||||
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]
|
||||
|
||||
# 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}).{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"
|
||||
|
||||
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(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 not os.path.isfile(title_file):
|
||||
self.logger.error(f"Title file not found: {title_file}")
|
||||
return []
|
||||
|
||||
if not os.path.isfile(with_vocals_file):
|
||||
self.logger.error(f"With Vocals file not found: {with_vocals_file}")
|
||||
return []
|
||||
|
||||
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
|
||||
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
|
||||
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_mov_file)}'\n")
|
||||
|
||||
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.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 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.info("brand_prefix or target_dir not specified, skipping move")
|
||||
|
||||
# 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")
|
||||
|
||||
# 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
|
||||
@@ -0,0 +1,622 @@
|
||||
import os
|
||||
import sys
|
||||
import re
|
||||
import glob
|
||||
import yt_dlp
|
||||
import logging
|
||||
import lyricsgenius
|
||||
import tempfile
|
||||
import importlib.resources as pkg_resources
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
|
||||
class KaraokePrep:
|
||||
def __init__(
|
||||
self,
|
||||
url=None,
|
||||
artist=None,
|
||||
title=None,
|
||||
log_level=logging.DEBUG,
|
||||
log_formatter=None,
|
||||
model_name="UVR_MDXNET_KARA_2",
|
||||
model_name_2="UVR-MDX-NET-Inst_HQ_3",
|
||||
model_file_dir=os.path.join(tempfile.gettempdir(), "audio-separator-models"),
|
||||
output_dir=".",
|
||||
lossless_output_format="FLAC",
|
||||
lossy_output_format="MP3",
|
||||
use_cuda=False,
|
||||
use_coreml=False,
|
||||
normalization_enabled=True,
|
||||
denoise_enabled=True,
|
||||
create_track_subfolders=False,
|
||||
intro_background_color="#000000",
|
||||
intro_background_image=None,
|
||||
intro_font="Montserrat-Bold.ttf",
|
||||
intro_artist_color="#ffffff",
|
||||
intro_title_color="#ff7acc",
|
||||
):
|
||||
self.logger = logging.getLogger(__name__)
|
||||
self.logger.setLevel(log_level)
|
||||
self.log_level = log_level
|
||||
self.log_formatter = log_formatter
|
||||
|
||||
self.log_handler = logging.StreamHandler()
|
||||
|
||||
if self.log_formatter is None:
|
||||
self.log_formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(module)s - %(message)s")
|
||||
|
||||
self.log_handler.setFormatter(self.log_formatter)
|
||||
self.logger.addHandler(self.log_handler)
|
||||
|
||||
self.logger.debug(f"KaraokePrep instantiating with url: {url} artist: {artist} title: {title}")
|
||||
|
||||
self.url = url
|
||||
self.artist = artist
|
||||
self.title = title
|
||||
self.model_name = model_name
|
||||
self.model_name_2 = model_name_2
|
||||
self.model_file_dir = model_file_dir
|
||||
self.output_dir = output_dir
|
||||
self.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
|
||||
|
||||
# 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.title_format = {
|
||||
"background_color": intro_background_color,
|
||||
"background_image": intro_background_image,
|
||||
"intro_font": intro_font,
|
||||
"artist_color": intro_artist_color,
|
||||
"title_color": intro_title_color,
|
||||
}
|
||||
|
||||
self.persistent_artist = None
|
||||
|
||||
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")
|
||||
os.makedirs(self.output_dir)
|
||||
else:
|
||||
self.logger.debug(f"Overall output dir {self.output_dir} already exists")
|
||||
|
||||
def extract_metadata_from_url(self):
|
||||
"""
|
||||
Extracts metadata from the YouTube URL.
|
||||
"""
|
||||
if self.url:
|
||||
with yt_dlp.YoutubeDL({"quiet": True}) as ydl:
|
||||
info = ydl.extract_info(self.url, download=False)
|
||||
self.artist, self.title = self.parse_metadata(info)
|
||||
if self.persistent_artist:
|
||||
self.artist = self.persistent_artist
|
||||
if self.artist and self.title:
|
||||
self.logger.info(f"Extracted artist: {self.artist}, title: {self.title}")
|
||||
else:
|
||||
self.logger.error("Failed to extract artist and title from the YouTube URL.")
|
||||
|
||||
def parse_metadata(self, info):
|
||||
"""
|
||||
Parses the metadata to extract artist and title.
|
||||
|
||||
:param info: The metadata information extracted from yt_dlp.
|
||||
:return: A tuple containing the artist and title.
|
||||
"""
|
||||
# Default values if parsing fails
|
||||
artist = ""
|
||||
title = ""
|
||||
|
||||
# Example: "Artist - Title"
|
||||
if "title" in info and "-" in info["title"]:
|
||||
artist, title = info["title"].split("-", 1)
|
||||
artist = artist.strip()
|
||||
title = title.strip()
|
||||
elif "uploader" in info:
|
||||
# Fallback to uploader as artist if title parsing fails
|
||||
artist = info["uploader"]
|
||||
if "title" in info:
|
||||
title = info["title"].strip()
|
||||
|
||||
# If unable to parse, log an appropriate message
|
||||
if not artist or not title:
|
||||
self.logger.warning("Could not parse artist and title from the video metadata.")
|
||||
|
||||
return artist, title
|
||||
|
||||
def get_youtube_id_for_top_search_result(self, query):
|
||||
ydl_opts = {"quiet": "True", "format": "bestaudio", "noplaylist": "True", "extract_flat": True}
|
||||
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
||||
video = ydl.extract_info(f"ytsearch1:{query}", download=False)["entries"][0]
|
||||
|
||||
if video:
|
||||
youtube_id = video.get("id")
|
||||
return youtube_id
|
||||
else:
|
||||
self.logger.warning(f"No YouTube results found for query: {query}")
|
||||
return None
|
||||
|
||||
def download_video(self, youtube_id, output_filename_no_extension):
|
||||
self.logger.debug(f"Downloading YouTube video {youtube_id} to filename {output_filename_no_extension} + (as yet) unknown extension")
|
||||
|
||||
downloaded_file_name = output_filename_no_extension
|
||||
actual_file_extension = None
|
||||
|
||||
# TODO: fix file extension for example karaoke-prep --log_level debug "Ken Ashcorp" "Dare You To Love Me"
|
||||
|
||||
def ydl_progress_hook(d):
|
||||
nonlocal actual_file_extension
|
||||
actual_file_extension = d["filename"].split(".")[-1]
|
||||
|
||||
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],
|
||||
"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
|
||||
|
||||
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")
|
||||
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)
|
||||
return output_filename
|
||||
|
||||
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}"'
|
||||
self.logger.debug(f"Running command: {ffmpeg_command}")
|
||||
os.system(ffmpeg_command)
|
||||
return output_filename
|
||||
|
||||
def write_lyrics_from_genius(self, artist, title, filename):
|
||||
genius = lyricsgenius.Genius(access_token=os.environ["GENIUS_API_TOKEN"], verbose=False, remove_section_headers=True)
|
||||
song = genius.search_song(title, artist)
|
||||
if song:
|
||||
lyrics = self.clean_genius_lyrics(song.lyrics)
|
||||
|
||||
with open(filename, "w") as f:
|
||||
f.write(lyrics)
|
||||
|
||||
self.logger.info("Lyrics for %s by %s fetched successfully", title, artist)
|
||||
return lyrics.split("\n")
|
||||
else:
|
||||
self.logger.warning("Could not find lyrics for %s by %s", title, artist)
|
||||
|
||||
def clean_genius_lyrics(self, lyrics):
|
||||
lyrics = lyrics.replace("\\n", "\n")
|
||||
lyrics = re.sub(r"You might also like", "", lyrics)
|
||||
lyrics = re.sub(
|
||||
r".*?Lyrics([A-Z])", r"\1", lyrics
|
||||
) # Remove the song name and word "Lyrics" if this has a non-newline char at the start
|
||||
lyrics = re.sub(r"^[0-9]* Contributors.*Lyrics", "", lyrics) # Remove this example: 27 ContributorsSex Bomb Lyrics
|
||||
lyrics = re.sub(
|
||||
r"See.*Live.*Get tickets as low as \$[0-9]+", "", lyrics
|
||||
) # Remove this example: See Tom Jones LiveGet tickets as low as $71
|
||||
lyrics = re.sub(r"[0-9]+Embed$", "", lyrics) # Remove the word "Embed" at end of line with preceding numbers if found
|
||||
lyrics = re.sub(r"(\S)Embed$", r"\1", lyrics) # Remove the word "Embed" if it has been tacked onto a word at the end of a line
|
||||
lyrics = re.sub(r"^Embed$", r"", lyrics) # Remove the word "Embed" if it has been tacked onto a word at the end of a line
|
||||
lyrics = re.sub(r".*?\[.*?\].*?", "", lyrics) # Remove lines containing square brackets
|
||||
# add any additional cleaning rules here
|
||||
return lyrics
|
||||
|
||||
def find_best_split_point(self, line):
|
||||
"""
|
||||
Find the best split point in a line based on the specified criteria.
|
||||
"""
|
||||
|
||||
self.logger.debug(f"Finding best_split_point for line: {line}")
|
||||
words = line.split()
|
||||
mid_word_index = len(words) // 2
|
||||
|
||||
# Check for a comma within one or two words of the middle word
|
||||
if "," in line:
|
||||
mid_point = len(" ".join(words[:mid_word_index]))
|
||||
comma_indices = [i for i, char in enumerate(line) if char == ","]
|
||||
|
||||
for index in comma_indices:
|
||||
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} and results in a suitable line length, accepting as split point"
|
||||
)
|
||||
return index + 1 # Include the comma in the first line
|
||||
|
||||
# Check for 'and'
|
||||
if " and " in line:
|
||||
mid_point = len(line) // 2
|
||||
and_indices = [m.start() for m in re.finditer(" and ", 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]))
|
||||
|
||||
def process_line(self, line):
|
||||
"""
|
||||
Process a single line to ensure it's within the maximum length,
|
||||
and handle parentheses.
|
||||
"""
|
||||
processed_lines = []
|
||||
while len(line) > 36:
|
||||
# Check if the line contains parentheses
|
||||
if "(" in line and ")" in line:
|
||||
start_paren = line.find("(")
|
||||
end_paren = line.find(")") + 1
|
||||
if end_paren < len(line) and line[end_paren] == ",":
|
||||
end_paren += 1
|
||||
|
||||
if start_paren > 0:
|
||||
processed_lines.append(line[:start_paren].strip())
|
||||
processed_lines.append(line[start_paren:end_paren].strip())
|
||||
line = line[end_paren:].strip()
|
||||
else:
|
||||
split_point = self.find_best_split_point(line)
|
||||
processed_lines.append(line[:split_point].strip())
|
||||
line = line[split_point:].strip()
|
||||
|
||||
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.info(f"Writing processed lyrics to {processed_lyrics_file}")
|
||||
|
||||
with open(processed_lyrics_file, "w") as outfile:
|
||||
all_processed = False
|
||||
while not all_processed:
|
||||
all_processed = True
|
||||
new_lyrics = []
|
||||
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
|
||||
|
||||
# Write the processed lyrics to file
|
||||
for line in lyrics:
|
||||
outfile.write(line + "\n")
|
||||
|
||||
def sanitize_filename(self, filename):
|
||||
"""Replace or remove characters that are unsafe for filenames."""
|
||||
# Replace problematic characters with underscores
|
||||
for char in ["\\", "/", ":", "*", "?", '"', "<", ">", "|"]:
|
||||
filename = filename.replace(char, "_")
|
||||
# Remove any trailing periods or spaces
|
||||
filename = filename.rstrip(". ")
|
||||
return filename
|
||||
|
||||
def separate_audio(self, audio_file, model_name, instrumental_path, vocals_path):
|
||||
if audio_file is None or not os.path.isfile(audio_file):
|
||||
raise Exception("Error: Invalid audio source provided.")
|
||||
|
||||
self.logger.debug(f"audio_file is valid file: {audio_file}")
|
||||
|
||||
self.logger.debug(
|
||||
f"instantiating Separator with model_name: {model_name} instrumental_path: {instrumental_path} and lossless_output_format: {self.lossless_output_format}"
|
||||
)
|
||||
|
||||
from audio_separator.separator import Separator
|
||||
|
||||
separator = Separator(
|
||||
log_level=self.log_level,
|
||||
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)
|
||||
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)
|
||||
sanitized_title = self.sanitize_filename(title)
|
||||
artist_title = f"{sanitized_artist} - {sanitized_title}"
|
||||
|
||||
track_output_dir = self.output_dir
|
||||
if self.create_track_subfolders:
|
||||
track_output_dir = os.path.join(self.output_dir, f"{artist_title}")
|
||||
|
||||
if not os.path.exists(track_output_dir):
|
||||
self.logger.debug(f"Output dir {track_output_dir} did not exist, creating")
|
||||
os.makedirs(track_output_dir)
|
||||
|
||||
return track_output_dir, artist_title
|
||||
|
||||
def calculate_text_size_and_position(self, draw, text, font_path, start_size, resolution, padding):
|
||||
font_size = start_size
|
||||
font = ImageFont.truetype(font_path, size=font_size) if os.path.exists(font_path) else ImageFont.load_default()
|
||||
|
||||
# Initial position for calculating the text bounding box
|
||||
temp_position = (padding, padding)
|
||||
bbox = draw.textbbox(temp_position, text, font=font)
|
||||
text_width = bbox[2] - bbox[0]
|
||||
text_height = bbox[3] - bbox[1]
|
||||
|
||||
while text_width + 2 * padding > resolution[0] or text_height + 2 * padding > resolution[1]:
|
||||
font_size -= 10
|
||||
if font_size <= 0:
|
||||
raise ValueError("Cannot fit text within screen bounds.")
|
||||
font = ImageFont.truetype(font_path, size=font_size) if os.path.exists(font_path) else ImageFont.load_default()
|
||||
bbox = draw.textbbox(temp_position, text, font=font)
|
||||
text_width = bbox[2] - bbox[0]
|
||||
text_height = bbox[3] - bbox[1]
|
||||
|
||||
text_position = ((resolution[0] - text_width) // 2, (resolution[1] - text_height) // 2)
|
||||
return font, text_position
|
||||
|
||||
def calculate_text_position(self, draw, text, font, resolution, vertical_offset):
|
||||
bbox = draw.textbbox((0, 0), text, font=font)
|
||||
text_width = bbox[2] - bbox[0]
|
||||
text_height = bbox[3] - bbox[1]
|
||||
text_x = (resolution[0] - text_width) // 2
|
||||
text_y = vertical_offset
|
||||
return (text_x, text_y), text_height
|
||||
|
||||
def create_title_video(self, artist, title, format, output_image_filepath, output_video_filepath):
|
||||
duration = 5 # Duration in seconds
|
||||
resolution = (3840, 2160) # 4K resolution
|
||||
|
||||
# Load or create background image
|
||||
if format["background_image"] and os.path.exists(format["background_image"]):
|
||||
self.logger.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
|
||||
)
|
||||
|
||||
draw.text(title_text_position, title, fill=format["title_color"], font=title_font)
|
||||
draw.text(artist_text_position, artist, fill=format["artist_color"], font=artist_font)
|
||||
|
||||
# Save static background image
|
||||
background.save(output_image_filepath)
|
||||
|
||||
# Use ffmpeg to create video
|
||||
ffmpeg_command = f'{self.ffmpeg_base_command} -y -loop 1 -framerate 30 -i "{output_image_filepath}" -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.debug(f"Running command: {ffmpeg_command}")
|
||||
os.system(ffmpeg_command)
|
||||
|
||||
def hex_to_rgb(self, hex_color):
|
||||
"""Convert hex color to RGB tuple."""
|
||||
hex_color = hex_color.lstrip("#")
|
||||
return tuple(int(hex_color[i : i + 2], 16) for i in (0, 2, 4))
|
||||
|
||||
def prep_single_track(self):
|
||||
if self.artist is None or self.title is None:
|
||||
self.logger.warn(f"Artist or Title nor specified manually, guessing from YouTube metadata...")
|
||||
self.extract_metadata_from_url()
|
||||
|
||||
artist = self.artist
|
||||
title = self.title
|
||||
|
||||
self.logger.info(f"Preparing output path for track: {title} by {artist}")
|
||||
track_output_dir, artist_title = self.setup_output_paths(artist, title)
|
||||
processed_track = {
|
||||
"track_output_dir": track_output_dir,
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
}
|
||||
|
||||
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"])
|
||||
|
||||
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}")
|
||||
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)
|
||||
|
||||
processed_track["lyrics"] = lyrics_file
|
||||
processed_track["processed_lyrics"] = processed_lyrics_file
|
||||
|
||||
# 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.info(f"YouTube output files already exist, skipping download: {processed_track['youtube_video']} + .wav + .png")
|
||||
else:
|
||||
if self.url is None:
|
||||
self.logger.warn(f"No URL specified - the top result from YouTube will be used.")
|
||||
self.logger.info("Searching YouTube for video ID...")
|
||||
query = f"{artist} {title}"
|
||||
youtube_id = self.get_youtube_id_for_top_search_result(query)
|
||||
else:
|
||||
self.logger.info("Parsing YouTube video ID from URL...")
|
||||
youtube_id = self.url.split("watch?v=")[1]
|
||||
if youtube_id:
|
||||
output_filename_no_extension = os.path.join(track_output_dir, f"{artist_title} (YouTube {youtube_id})")
|
||||
|
||||
self.logger.info("Downloading original video from YouTube...")
|
||||
processed_track["youtube_video"] = self.download_video(youtube_id, output_filename_no_extension)
|
||||
|
||||
self.logger.info("Extracting still image from downloaded video...")
|
||||
processed_track["youtube_still_image"] = self.extract_still_image_from_video(
|
||||
processed_track["youtube_video"], output_filename_no_extension
|
||||
)
|
||||
|
||||
self.logger.info("Converting downloaded video to WAV for audio processing...")
|
||||
processed_track["youtube_audio"] = self.convert_to_wav(processed_track["youtube_video"], output_filename_no_extension)
|
||||
else:
|
||||
self.logger.warning(f"Skipping {title} by {artist} due to missing YouTube ID.")
|
||||
|
||||
self.logger.info(f"Separating audio twice for track: {title} by {artist}")
|
||||
|
||||
instrumental_path = os.path.join(track_output_dir, f"{artist_title} (Instrumental {self.model_name}).{self.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.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}")
|
||||
else:
|
||||
self.separate_audio(processed_track["youtube_audio"], 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 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 is_playlist_url(self):
|
||||
"""
|
||||
Checks if the provided URL is a YouTube playlist URL.
|
||||
"""
|
||||
if self.url and "playlist?list=" in self.url:
|
||||
return True
|
||||
return False
|
||||
|
||||
def process_playlist(self):
|
||||
"""
|
||||
Processes all videos in a YouTube playlist.
|
||||
"""
|
||||
self.logger.debug(f"Querying playlist metadata from YouTube, assuming consistent artist {self.artist}...")
|
||||
with yt_dlp.YoutubeDL({"quiet": True}) as ydl:
|
||||
result = ydl.extract_info(self.url, download=False)
|
||||
if "entries" in result:
|
||||
track_results = []
|
||||
self.logger.info(f"Found {len(result['entries'])} videos in playlist, processing each invididually...")
|
||||
for video in result["entries"]:
|
||||
video_url = f"https://www.youtube.com/watch?v={video['id']}"
|
||||
self.logger.info(f"Processing video: {video_url}")
|
||||
self.url = video_url
|
||||
track_results.append(self.prep_single_track())
|
||||
self.artist = self.persistent_artist
|
||||
self.title = None
|
||||
return track_results
|
||||
|
||||
def process(self):
|
||||
if self.is_playlist_url():
|
||||
self.persistent_artist = self.artist
|
||||
self.logger.info(
|
||||
f"Provided YouTube URL is a playlist, beginning batch operation with persistent artist: {self.persistent_artist}"
|
||||
)
|
||||
return self.process_playlist()
|
||||
else:
|
||||
self.logger.info(f"Provided YouTube URL is NOT a playlist, processing single track")
|
||||
# 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()]
|
||||
@@ -1,245 +0,0 @@
|
||||
import requests
|
||||
import os
|
||||
import re
|
||||
import glob
|
||||
from bs4 import BeautifulSoup
|
||||
import yt_dlp
|
||||
import logging
|
||||
import lyricsgenius
|
||||
from slugify import slugify
|
||||
from audio_separator import Separator
|
||||
|
||||
|
||||
class KaraokePrep:
|
||||
def __init__(
|
||||
self,
|
||||
url=None,
|
||||
artist=None,
|
||||
title=None,
|
||||
log_level=logging.DEBUG,
|
||||
log_formatter=None,
|
||||
model_name="UVR_MDXNET_KARA_2",
|
||||
model_name_2="UVR-MDX-NET-Inst_HQ_3",
|
||||
model_file_dir="/tmp/audio-separator-models/",
|
||||
output_dir=".",
|
||||
output_format="WAV",
|
||||
use_cuda=False,
|
||||
use_coreml=False,
|
||||
normalization_enabled=True,
|
||||
denoise_enabled=True,
|
||||
create_track_subfolders=False,
|
||||
):
|
||||
self.logger = logging.getLogger(__name__)
|
||||
self.logger.setLevel(log_level)
|
||||
self.log_level = log_level
|
||||
self.log_formatter = log_formatter
|
||||
|
||||
self.log_handler = logging.StreamHandler()
|
||||
|
||||
if self.log_formatter is None:
|
||||
self.log_formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(module)s - %(message)s")
|
||||
|
||||
self.log_handler.setFormatter(self.log_formatter)
|
||||
self.logger.addHandler(self.log_handler)
|
||||
|
||||
self.logger.debug(f"KaraokePrep instantiating with url: {url} artist: {artist} title: {title}")
|
||||
|
||||
self.url = url
|
||||
self.artist = artist
|
||||
self.title = title
|
||||
self.model_name = model_name
|
||||
self.model_name_2 = model_name_2
|
||||
self.model_file_dir = model_file_dir
|
||||
self.output_dir = output_dir
|
||||
self.output_format = output_format
|
||||
self.use_cuda = use_cuda
|
||||
self.use_coreml = use_coreml
|
||||
self.normalization_enabled = normalization_enabled
|
||||
self.denoise_enabled = denoise_enabled
|
||||
self.create_track_subfolders = create_track_subfolders
|
||||
|
||||
self.logger.debug(f"KaraokePrep output_format: {self.output_format}")
|
||||
|
||||
if not os.path.exists(self.output_dir):
|
||||
self.logger.debug(f"Overall output dir {self.output_dir} did not exist, creating")
|
||||
os.makedirs(self.output_dir)
|
||||
else:
|
||||
self.logger.debug(f"Overall output dir {self.output_dir} already exists")
|
||||
|
||||
if artist is None or title is None:
|
||||
raise Exception("Error: You must provide an artist and title.")
|
||||
|
||||
def get_youtube_id_for_top_search_result(self, query):
|
||||
ydl_opts = {"quiet": "True", "format": "bestaudio", "noplaylist": "True", "extract_flat": True}
|
||||
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
||||
video = ydl.extract_info(f"ytsearch1:{query}", download=False)["entries"][0]
|
||||
|
||||
if video:
|
||||
youtube_id = video.get("id")
|
||||
return youtube_id
|
||||
else:
|
||||
self.logger.warning(f"No YouTube results found for query: {query}")
|
||||
return None
|
||||
|
||||
def download_audio(self, youtube_id, filename):
|
||||
ydl_opts = {
|
||||
"format": "ba",
|
||||
"postprocessors": [
|
||||
{
|
||||
"key": "FFmpegExtractAudio",
|
||||
"preferredcodec": "wav",
|
||||
"preferredquality": "192",
|
||||
}
|
||||
],
|
||||
"outtmpl": f"{filename}",
|
||||
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",
|
||||
}
|
||||
|
||||
with yt_dlp.YoutubeDL(ydl_opts) as youtube_dl_instance:
|
||||
youtube_dl_instance.download([f"https://www.youtube.com/watch?v={youtube_id}"])
|
||||
|
||||
def write_lyrics_from_genius(self, artist, title, filename):
|
||||
genius = lyricsgenius.Genius(os.environ["GENIUS_API_TOKEN"])
|
||||
song = genius.search_song(title, artist)
|
||||
if song:
|
||||
lyrics = self.clean_genius_lyrics(song.lyrics)
|
||||
|
||||
with open(filename, "w") as f:
|
||||
f.write(lyrics)
|
||||
|
||||
self.logger.info("Lyrics for %s by %s fetched successfully", title, artist)
|
||||
else:
|
||||
self.logger.warning("Could not find lyrics for %s by %s", title, artist)
|
||||
|
||||
def clean_genius_lyrics(self, lyrics):
|
||||
lyrics = lyrics.replace("\\n", "\n")
|
||||
lyrics = re.sub(r"You might also like", "", lyrics)
|
||||
lyrics = re.sub(
|
||||
r".*?Lyrics([A-Z])", r"\1", lyrics
|
||||
) # Remove the song name and word "Lyrics" if this has a non-newline char at the start
|
||||
lyrics = re.sub(r"[0-9]+Embed$", "", lyrics) # Remove the word "Embed" at end of line with preceding numbers if found
|
||||
lyrics = re.sub(r"(\S)Embed$", r"\1", lyrics) # Remove the word "Embed" if it has been tacked onto a word at the end of a line
|
||||
lyrics = re.sub(r"^Embed$", r"", lyrics) # Remove the word "Embed" if it has been tacked onto a word at the end of a line
|
||||
lyrics = re.sub(r".*?\[.*?\].*?", "", lyrics) # Remove lines containing square brackets
|
||||
# add any additional cleaning rules here
|
||||
return lyrics
|
||||
|
||||
def sanitize_filename(self, filename):
|
||||
"""Replace or remove characters that are unsafe for filenames."""
|
||||
# Replace problematic characters with underscores
|
||||
for char in ["\\", "/", ":", "*", "?", '"', "<", ">", "|"]:
|
||||
filename = filename.replace(char, "_")
|
||||
# Remove any trailing periods or spaces
|
||||
filename = filename.rstrip(". ")
|
||||
return filename
|
||||
|
||||
def separate_audio(self, audio_file, model_name, instrumental_path, vocals_path):
|
||||
if audio_file is None or not os.path.isfile(audio_file):
|
||||
raise Exception("Error: Invalid audio source provided.")
|
||||
|
||||
self.logger.debug(f"audio_file is valid file: {audio_file}")
|
||||
|
||||
self.logger.debug(f"instantiating Separator with model_name: {model_name} instrumental_path: {instrumental_path} and output_format: {self.output_format}")
|
||||
separator = Separator(
|
||||
audio_file,
|
||||
log_level=self.log_level,
|
||||
log_formatter=self.log_formatter,
|
||||
model_name=model_name,
|
||||
model_file_dir=self.model_file_dir,
|
||||
output_format=self.output_format,
|
||||
primary_stem_path=instrumental_path,
|
||||
secondary_stem_path=vocals_path,
|
||||
)
|
||||
_, _ = separator.separate()
|
||||
self.logger.debug(f"Separation complete!")
|
||||
|
||||
def setup_output_paths(self, artist, title):
|
||||
sanitized_artist = self.sanitize_filename(artist)
|
||||
sanitized_title = self.sanitize_filename(title)
|
||||
artist_title = f"{sanitized_artist} - {sanitized_title}"
|
||||
|
||||
track_output_dir = self.output_dir
|
||||
if self.create_track_subfolders:
|
||||
track_output_dir = os.path.join(self.output_dir, f"{artist_title}")
|
||||
|
||||
if not os.path.exists(track_output_dir):
|
||||
self.logger.debug(f"Output dir {track_output_dir} did not exist, creating")
|
||||
os.makedirs(track_output_dir)
|
||||
|
||||
return track_output_dir, artist_title
|
||||
|
||||
def prep(self):
|
||||
artist = self.artist
|
||||
title = self.title
|
||||
|
||||
self.logger.info(f"Downloading inputs for track: {title} by {artist}")
|
||||
track_output_dir, artist_title = self.setup_output_paths(artist, title)
|
||||
processed_track = {
|
||||
"track_output_dir": track_output_dir,
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
}
|
||||
|
||||
yt_filename_pattern = os.path.join(track_output_dir, f"{artist_title} (YouTube *.wav")
|
||||
youtube_audio_files = glob.glob(yt_filename_pattern)
|
||||
youtube_audio_file = None
|
||||
|
||||
if youtube_audio_files:
|
||||
youtube_audio_file = youtube_audio_files[0]
|
||||
self.logger.debug(f"Youtube audio already exists, skipping download: {youtube_audio_file}")
|
||||
else:
|
||||
if self.url is None:
|
||||
self.logger.warn(f"No URL specified - the top result from YouTube will be used.")
|
||||
self.logger.info("Searching YouTube for video ID...")
|
||||
query = f"{artist} {title}"
|
||||
youtube_id = self.get_youtube_id_for_top_search_result(query)
|
||||
else:
|
||||
self.logger.info("Parsing YouTube video ID from URL...")
|
||||
youtube_id = self.url.split("watch?v=")[1]
|
||||
if youtube_id:
|
||||
youtube_audio_file = os.path.join(track_output_dir, f"{artist_title} (YouTube {youtube_id})")
|
||||
|
||||
self.logger.info("Downloading original audio from YouTube to filename {original_audio_filename}")
|
||||
self.download_audio(youtube_id, youtube_audio_file)
|
||||
youtube_audio_file = youtube_audio_file + ".wav"
|
||||
else:
|
||||
self.logger.warning(f"Skipping {title} by {artist} due to missing YouTube ID.")
|
||||
|
||||
processed_track["youtube_audio"] = youtube_audio_file
|
||||
|
||||
lyrics_file = os.path.join(track_output_dir, f"{artist_title} (Lyrics).txt")
|
||||
if os.path.exists(lyrics_file):
|
||||
self.logger.debug(f"Lyrics file already exists, skipping fetch: {lyrics_file}")
|
||||
else:
|
||||
self.logger.info("Fetching lyrics from Genius...")
|
||||
self.write_lyrics_from_genius(artist, title, lyrics_file)
|
||||
|
||||
processed_track["lyrics"] = lyrics_file
|
||||
|
||||
self.logger.info(f"Separating audio twice for track: {title} by {artist}")
|
||||
|
||||
instrumental_path = os.path.join(track_output_dir, f"{artist_title} (Instrumental {self.model_name}).flac")
|
||||
vocals_path = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name}).flac")
|
||||
|
||||
if os.path.isfile(instrumental_path) and os.path.isfile(vocals_path):
|
||||
self.logger.debug(f"Separated audio files already exist in output paths, skipping separation: {instrumental_path}")
|
||||
else:
|
||||
self.separate_audio(processed_track["youtube_audio"], self.model_name, instrumental_path, vocals_path)
|
||||
|
||||
processed_track["instrumental_audio"] = instrumental_path
|
||||
processed_track["vocals_audio"] = vocals_path
|
||||
|
||||
instrumental_path_2 = os.path.join(track_output_dir, f"{artist_title} (Instrumental {self.model_name_2}).flac")
|
||||
vocals_path_2 = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name_2}).flac")
|
||||
|
||||
if os.path.isfile(instrumental_path_2) and os.path.isfile(vocals_path_2):
|
||||
self.logger.debug(f"Separated audio files already exist in output paths, skipping separation: {instrumental_path_2}")
|
||||
else:
|
||||
self.separate_audio(processed_track["youtube_audio"], self.model_name_2, instrumental_path_2, vocals_path_2)
|
||||
|
||||
processed_track["instrumental_audio_2"] = instrumental_path_2
|
||||
processed_track["vocals_audio_2"] = vocals_path_2
|
||||
|
||||
self.logger.info("Script finished, audio downloaded, lyrics fetched and audio separated!")
|
||||
|
||||
return processed_track
|
||||
Binary file not shown.
Binary file not shown.
@@ -1,130 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
import argparse
|
||||
import logging
|
||||
import pkg_resources
|
||||
from karaoke_prep import KaraokePrep
|
||||
|
||||
|
||||
def main():
|
||||
logger = logging.getLogger(__name__)
|
||||
log_handler = logging.StreamHandler()
|
||||
log_formatter = logging.Formatter(fmt="%(asctime)s.%(msecs)03d - %(levelname)s - %(module)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
|
||||
log_handler.setFormatter(log_formatter)
|
||||
logger.addHandler(log_handler)
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Fetch audio and lyrics for a specified song, to prepare karaoke video creation.",
|
||||
formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=50),
|
||||
)
|
||||
|
||||
parser.add_argument("artist", nargs="?", help="Artist name for the song to prep.", default=argparse.SUPPRESS)
|
||||
parser.add_argument("title", nargs="?", help="Title of the song to prep.", default=argparse.SUPPRESS)
|
||||
parser.add_argument("url", nargs="?", help="YouTube URL of the song to prep.", default=None)
|
||||
|
||||
package_version = pkg_resources.get_distribution("karaoke-prep").version
|
||||
parser.add_argument("-v", "--version", action="version", version=f"%(prog)s {package_version}")
|
||||
|
||||
parser.add_argument(
|
||||
"--log_level",
|
||||
default="info",
|
||||
help="Optional: logging level, e.g. info, debug, warning (default: %(default)s). Example: --log_level=debug",
|
||||
)
|
||||
|
||||
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(
|
||||
"--model_file_dir",
|
||||
default="/tmp/audio-separator-models/",
|
||||
help="Optional: model files directory (default: %(default)s). Example: --model_file_dir=/app/models",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--output_dir",
|
||||
default=".",
|
||||
help="Optional: directory to write output files (default: <current dir>). Example: --output_dir=/app/karaoke",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--output_format",
|
||||
default="MP3",
|
||||
help="Optional: output format for separated audio (default: MP3). Example: --output_format=FLAC",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--use_cuda",
|
||||
action="store_true",
|
||||
help="Optional: use Nvidia GPU with CUDA for separation (default: %(default)s). Example: --use_cuda=true",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--use_coreml",
|
||||
action="store_true",
|
||||
help="Optional: use Apple Silicon GPU with CoreML for separation (default: %(default)s). Example: --use_coreml=true",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--denoise",
|
||||
type=lambda x: (str(x).lower() == "true"),
|
||||
default=True,
|
||||
help="Optional: enable or disable denoising during separation (default: %(default)s). Example: --denoise=False",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--normalize",
|
||||
type=lambda x: (str(x).lower() == "true"),
|
||||
default=True,
|
||||
help="Optional: enable or disable normalization during separation (default: %(default)s). Example: --normalize=False",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--no_track_subfolders",
|
||||
action="store_false",
|
||||
help="Optional: do NOT create a named subfolder for each track. Example: --no_track_subfolders",
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
log_level = getattr(logging, args.log_level.upper())
|
||||
logger.setLevel(log_level)
|
||||
|
||||
if not hasattr(args, "artist") or not hasattr(args, "title"):
|
||||
parser.print_help()
|
||||
exit(1)
|
||||
|
||||
logger.info(f"KaraokePrep beginning with artist: {args.artist} and title: {args.title} and url: {args.url}")
|
||||
|
||||
kprep = KaraokePrep(
|
||||
artist=args.artist,
|
||||
title=args.title,
|
||||
url=args.url,
|
||||
log_formatter=log_formatter,
|
||||
log_level=log_level,
|
||||
model_name=args.model_name,
|
||||
model_file_dir=args.model_file_dir,
|
||||
output_dir=args.output_dir,
|
||||
output_format=args.output_format,
|
||||
use_cuda=args.use_cuda,
|
||||
use_coreml=args.use_coreml,
|
||||
normalization_enabled=args.normalize,
|
||||
denoise_enabled=args.denoise,
|
||||
create_track_subfolders=args.no_track_subfolders,
|
||||
)
|
||||
|
||||
track = kprep.prep()
|
||||
|
||||
logger.info(f"Karaoke Prep complete! Output files:")
|
||||
|
||||
logger.info(f"")
|
||||
logger.info(f"Track: {track['artist']} - {track['title']}")
|
||||
logger.info(f" YouTube Audio: {track['youtube_audio']}")
|
||||
logger.info(f" Lyrics: {track['lyrics']}")
|
||||
logger.info(f" Instrumental: {track['instrumental_audio']}")
|
||||
logger.info(f" Vocals: {track['vocals_audio']}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,107 @@
|
||||
#!/usr/bin/env python
|
||||
import argparse
|
||||
import logging
|
||||
import pkg_resources
|
||||
from karaoke_prep.karaoke_finalise import KaraokeFinalise
|
||||
|
||||
|
||||
def main():
|
||||
logger = logging.getLogger(__name__)
|
||||
log_handler = logging.StreamHandler()
|
||||
log_formatter = logging.Formatter(fmt="%(asctime)s.%(msecs)03d - %(levelname)s - %(module)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
|
||||
log_handler.setFormatter(log_formatter)
|
||||
logger.addHandler(log_handler)
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Render, remux and join intermediate files to create final karaoke video, as the third stage after using karaoke-prep. Processes all (Karaoke).mov files in current directory.",
|
||||
formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=54),
|
||||
)
|
||||
|
||||
package_version = pkg_resources.get_distribution("karaoke-prep").version
|
||||
parser.add_argument("-v", "--version", action="version", version=f"%(prog)s {package_version}")
|
||||
|
||||
parser.add_argument(
|
||||
"--log_level",
|
||||
default="info",
|
||||
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(
|
||||
"--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(
|
||||
"--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())
|
||||
logger.setLevel(log_level)
|
||||
|
||||
logger.info(f"KaraokeFinalise beginning with model_name: {args.model_name}")
|
||||
|
||||
kfinalise = KaraokeFinalise(
|
||||
log_formatter=log_formatter,
|
||||
log_level=log_level,
|
||||
dry_run=args.dry_run,
|
||||
force=args.force,
|
||||
model_name=args.model_name,
|
||||
brand_prefix=args.brand_prefix,
|
||||
target_dir=args.target_dir,
|
||||
public_share_dir=args.public_share_dir,
|
||||
rclone_destination=args.rclone_destination,
|
||||
)
|
||||
|
||||
tracks = kfinalise.process()
|
||||
|
||||
if len(tracks) == 0:
|
||||
logger.error(f"No tracks found to process.")
|
||||
return
|
||||
|
||||
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']}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+206
@@ -0,0 +1,206 @@
|
||||
#!/usr/bin/env python
|
||||
import argparse
|
||||
import logging
|
||||
import pkg_resources
|
||||
import tempfile
|
||||
import os
|
||||
from karaoke_prep import KaraokePrep
|
||||
|
||||
|
||||
def is_url(string):
|
||||
"""Simple check to determine if a string is a URL."""
|
||||
return string.startswith("http://") or string.startswith("https://")
|
||||
|
||||
|
||||
def main():
|
||||
logger = logging.getLogger(__name__)
|
||||
log_handler = logging.StreamHandler()
|
||||
log_formatter = logging.Formatter(fmt="%(asctime)s.%(msecs)03d - %(levelname)s - %(module)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
|
||||
log_handler.setFormatter(log_formatter)
|
||||
logger.addHandler(log_handler)
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Fetch audio and lyrics for a specified song, to prepare karaoke video creation.",
|
||||
formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=54),
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"args",
|
||||
nargs="*",
|
||||
help="[YouTube video or playlist URL] [Artist] [Title] of song to prep. If URL is provided, Artist and Title are optional but increase chance of fetching the correct lyrics. If Artist and Title are provided with no URL, the top YouTube search result will be fetched.",
|
||||
)
|
||||
|
||||
package_version = pkg_resources.get_distribution("karaoke-prep").version
|
||||
parser.add_argument("-v", "--version", action="version", version=f"%(prog)s {package_version}")
|
||||
|
||||
parser.add_argument(
|
||||
"--log_level",
|
||||
default="info",
|
||||
help="Optional: logging level, e.g. info, debug, warning (default: %(default)s). Example: --log_level=debug",
|
||||
)
|
||||
|
||||
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",
|
||||
)
|
||||
|
||||
# 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,
|
||||
help="Optional: model files directory (default: %(default)s). Example: --model_file_dir=/app/models",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--output_dir",
|
||||
default=".",
|
||||
help="Optional: directory to write output files (default: <current dir>). Example: --output_dir=/app/karaoke",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--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(
|
||||
"--use_cuda",
|
||||
action="store_true",
|
||||
help="Optional: use Nvidia GPU with CUDA for separation (default: %(default)s). Example: --use_cuda=true",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--use_coreml",
|
||||
action="store_true",
|
||||
help="Optional: use Apple Silicon GPU with CoreML for separation (default: %(default)s). Example: --use_coreml=true",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--denoise",
|
||||
type=lambda x: (str(x).lower() == "true"),
|
||||
default=True,
|
||||
help="Optional: enable or disable denoising during separation (default: %(default)s). Example: --denoise=False",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--normalize",
|
||||
type=lambda x: (str(x).lower() == "true"),
|
||||
default=True,
|
||||
help="Optional: enable or disable normalization during separation (default: %(default)s). Example: --normalize=False",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--no_track_subfolders",
|
||||
action="store_false",
|
||||
help="Optional: do NOT create a named subfolder for each track. Example: --no_track_subfolders",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--intro_background_color",
|
||||
default="#000000",
|
||||
help="Optional: Background color for intro video (default: black). Example: --intro_background_color=#123456",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--intro_background_image",
|
||||
help="Optional: Path to background image for intro video. Overrides background color if provided. Example: --intro_background_image=path/to/image.jpg",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--intro_font",
|
||||
default="Montserrat-Bold.ttf",
|
||||
help="Optional: Font file for intro video (default: Montserrat-Bold.ttf). Example: --intro_font=AvenirNext-Bold.ttf",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--intro_artist_color",
|
||||
default="#ffdf6b",
|
||||
help="Optional: Font color for intro video artist text (default: #ffdf6b). Example: --intro_artist_color=#123456",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--intro_title_color",
|
||||
default="#ffffff",
|
||||
help="Optional: Font color for intro video title text (default: #ffffff). Example: --intro_title_color=#123456",
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
url, artist, title = None, None, None
|
||||
|
||||
# Allow 3 forms of positional arguments:
|
||||
# 1. URL only (may be single track URL or playlist URL)
|
||||
# 2. Artist and Title only
|
||||
# 3. URL, Artist, and Title
|
||||
if args.args and is_url(args.args[0]):
|
||||
url = args.args[0]
|
||||
if len(args.args) > 2:
|
||||
artist = args.args[1]
|
||||
title = args.args[2]
|
||||
elif len(args.args) > 1:
|
||||
artist = args.args[1]
|
||||
else:
|
||||
logger.warn("URL provided without Artist and Title, both will be guessed from YouTube Title")
|
||||
|
||||
elif len(args.args) > 1:
|
||||
artist = args.args[0]
|
||||
title = args.args[1]
|
||||
logger.warn(f"No URL provided, the top YouTube search result for {artist} - {title} will be used.")
|
||||
else:
|
||||
parser.print_help()
|
||||
exit(1)
|
||||
|
||||
log_level = getattr(logging, args.log_level.upper())
|
||||
logger.setLevel(log_level)
|
||||
|
||||
logger.info(f"KaraokePrep beginning with url: {url} artist: {artist} and title: {title}")
|
||||
|
||||
kprep = KaraokePrep(
|
||||
artist=artist,
|
||||
title=title,
|
||||
url=url,
|
||||
log_formatter=log_formatter,
|
||||
log_level=log_level,
|
||||
model_name=args.model_name,
|
||||
model_file_dir=args.model_file_dir,
|
||||
output_dir=args.output_dir,
|
||||
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,
|
||||
denoise_enabled=args.denoise,
|
||||
create_track_subfolders=args.no_track_subfolders,
|
||||
intro_background_color=args.intro_background_color,
|
||||
intro_background_image=args.intro_background_image,
|
||||
intro_font=args.intro_font,
|
||||
intro_artist_color=args.intro_artist_color,
|
||||
intro_title_color=args.intro_title_color,
|
||||
)
|
||||
|
||||
tracks = kprep.process()
|
||||
|
||||
logger.info(f"Karaoke Prep complete! Output files:")
|
||||
|
||||
for track in tracks:
|
||||
logger.info(f"")
|
||||
logger.info(f"Track: {track['artist']} - {track['title']}")
|
||||
logger.info(f" YouTube Video: {track['youtube_video']}")
|
||||
logger.info(f" YouTube Audio: {track['youtube_audio']}")
|
||||
logger.info(f" YouTube Still Image: {track['youtube_still_image']}")
|
||||
logger.info(f" Lyrics: {track['lyrics']}")
|
||||
logger.info(f" Processed Lyrics: {track['processed_lyrics']}")
|
||||
logger.info(f" Instrumental: {track['instrumental_audio']}")
|
||||
logger.info(f" Vocals: {track['vocals_audio']}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -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
+1170
-599
File diff suppressed because it is too large.
Load diff
+15
-9
@@ -1,7 +1,7 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-prep"
|
||||
version = "0.1.7"
|
||||
description = "Prepare for karaoke video creation, by downloading audio and lyrics for a specified song."
|
||||
version = "0.9.2"
|
||||
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"
|
||||
@@ -11,19 +11,25 @@ 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"
|
||||
lyricsgenius = ">=3"
|
||||
fetch-lyrics-from-genius = ">=0.1"
|
||||
pillow = ">=10.1"
|
||||
pyinstaller = ">=6.3"
|
||||
audio-separator = { version = ">=0.12", optional = true, extras = ["silicon"] }
|
||||
|
||||
[tool.poetry.extras]
|
||||
silicon = ["audio-separator"]
|
||||
|
||||
[tool.poetry.group.dev.dependencies]
|
||||
black = "^23"
|
||||
|
||||
[tool.poetry.scripts]
|
||||
karaoke-prep = 'karaoke_prep.utils.cli:main'
|
||||
karaoke-prep = 'karaoke_prep.utils.prep_cli:main'
|
||||
karaoke-finalise = 'karaoke_prep.utils.finalise_cli:main'
|
||||
|
||||
[tool.black]
|
||||
line-length = 140
|
||||
|
||||
Reference in new issue
Block a user