Compare commits

..
153 Commits
Author SHA1 Message Date
Andrew Beveridge 4e84fec706 Added fixes to this point, removed audacity stuff 2025-03-31 01:20:14 -04:00
Andrew Beveridge 12bea3e0e8 Fixed more post-refactor stuff 2025-03-17 22:32:32 -04:00
Andrew Beveridge c61029a9f3 Fixed a few more issues post-refactor 2025-03-17 19:39:22 -04:00
Andrew Beveridge c1aee2a680 Removed legacy and deprecated code, began testing new architecture CLI tools 2025-03-17 01:19:27 -04:00
Andrew Beveridge 9fa527aa59 Fully renamed karaoke_prep to karaoke_gen 2025-03-17 00:42:12 -04:00
Andrew Beveridge e641b8e639 "Completed" the major refactor - untested so far 2025-03-17 00:32:37 -04:00
Andrew Beveridge abaa9b5351 First pass at refactoring to split up large prep and finalise files into smaller modules 2025-03-16 22:43:58 -04:00
Andrew Beveridge 14b7428606 Renamed to karaoke-gen, replaced prep and finalise CLIs with karaoke-gen combined CLI 2025-03-11 23:12:13 -04:00
Andrew Beveridge d10bdfa3a0 Added additional skip logic, fixed duplicate logging 2025-03-08 12:07:12 -05:00
Andrew Beveridge 42647a7c36 Updated to latest lyrics-transcriber, updated dependencies, added graceful exit and other improvements 2025-02-19 00:55:43 -05:00
Andrew Beveridge cbc6470d3d Updated to latest lyrics-transcriber 2025-02-09 01:00:22 -05:00
Andrew Beveridge 0adc69ed75 Added audacity open and subtitle offset features 2025-02-09 00:52:51 -05:00
Andrew Beveridge b17440fd21 Removed lrc to cdg standalone functionality, now fully integrated with lyrics_transcriber CDGGenerator class 2025-02-07 00:05:14 -05:00
Andrew Beveridge 08b8abf27d Added lrc-to-cdg CLI with consistent styles JSON handling 2025-02-06 11:22:57 -05:00
Andrew Beveridge 1b62b396cb Removed cdgmaker code, migrated to using directly from python-lyrics-transcriber package 2025-02-05 23:27:43 -05:00
Andrew Beveridge f249a841e1 Fixed artist/title filename sanitization in auto mode 2025-02-05 02:18:02 -05:00
Andrew Beveridge 0f8eb3f6d4 Added strip to inputs from csv to fix bug 2025-02-03 00:55:57 -05:00
Andrew Beveridge 586763ae5f Updated bulk CLI 2025-02-03 00:47:01 -05:00
Andrew Beveridge 6092a67ef4 Updated to use latest lyrics transcriber. Added full auto and bulk processing modes. Added ability to pass in existing lyrics input file. 2025-02-02 22:35:16 -05:00
Andrew Beveridge 951b64eaf5 Bumped deps 2025-02-01 00:07:37 -05:00
Andrew Beveridge 78f7412d2d Fixed file rename, updated lyrics transcriber 2025-01-28 15:50:43 -05:00
Andrew Beveridge ef54ba9dc5 Lock poetry 2025-01-28 14:56:10 -05:00
Andrew Beveridge 481a57e0e1 Downgrade torch for now 2025-01-28 14:55:38 -05:00
Andrew Beveridge af5db142ef Move output files from transcriber to parent dir 2025-01-28 14:10:30 -05:00
Andrew Beveridge 54a48cef39 Bumped version for release 2025-01-28 01:00:33 -05:00
Andrew Beveridge 1663f229a3 Improved error handling with invalid inputs 2025-01-28 00:27:00 -05:00
Andrew Beveridge 87ed4799e5 Fixed parameters for integration with LyricsTranscriber 2025-01-27 23:47:04 -05:00
Andrew Beveridge a7a96f2f4b Added non-interactive mode to finalise 2025-01-22 17:37:33 -05:00
Andrew Beveridge 07ee85b304 Made work with MKV input 2025-01-20 00:16:43 -05:00
Andrew Beveridge 595fbbc4e2 Fixed filepaths to copy after moving org dir 2025-01-17 10:40:41 -05:00
Andrew Beveridge dfdbd92269 Added --keep-brand-code param 2025-01-17 01:13:09 -05:00
Andrew Beveridge 78f8880922 Added more output files to CLI output, copy youtube URL and folder sharing link to clipboard automatically 2025-01-15 11:48:24 -05:00
Andrew Beveridge 17be398a0f Reordered remuxing to leave no unnecessarily large files whilst retaining pure PCM audio in all output MP4 files 2025-01-14 21:27:40 -05:00
Andrew Beveridge ee9958bfe9 Improved text rendering size calculation to make text fill more of the region bounding box areas 2024-12-28 04:08:56 -05:00
Andrew Beveridge fc5eabb588 Added gradients, text transforms, and better font size calculation 2024-12-28 03:34:31 -05:00
Andrew Beveridge 4883a93603 Added support for configurable gradients and text transforms 2024-12-28 03:09:00 -05:00
Andrew Beveridge 5d8b697c61 Made styles configurable by JSON config file with combined config for prep and CDG in finalise, etc. 2024-12-28 02:30:09 -05:00
Andrew Beveridge 94ea24bfea Moved lyrics processing into LyricsTranscriber, added MKV output file with lossless audio, used that for upload to YouTube to improve audio quality 2024-12-27 16:00:12 -05:00
Andrew Beveridge 42fc646954 Fixed broken return in separation, transcriber dependency 2024-12-27 01:55:16 -05:00
Andrew Beveridge bd6db70bcf Updated dependencies, modified prep to use latest version of transcriber and rely on lyrics outputs from that rather than duplicating genius fetch logic etc. 2024-12-27 01:29:52 -05:00
Andrew Beveridge 242c1e03ac Improved cdg maker to have configurable styles 2024-12-26 00:03:50 -05:00
Andrew Beveridge ade7c40af7 Updated to check for fonts in the fonts dir 2024-12-25 00:31:03 -05:00
Andrew Beveridge 162faa9189 Updated cdg generation to use parameters 2024-12-25 00:05:24 -05:00
Andrew Beveridge 7ad1ae8305 Updated to newer karaoke-lyrics-processor with clipboard bug fix 2024-12-24 03:29:44 -05:00
Andrew Beveridge 7852619403 Renamed local output file to Original 2024-12-24 02:17:33 -05:00
Andrew Beveridge ddb70a9c31 Updated to include fixed region and extra text logic, additional font, test for intro and end screen rendering 2024-12-24 00:34:28 -05:00
Andrew Beveridge f9336590fa Updated artist title rendering with region logic 2024-12-23 22:40:37 -05:00
Andrew Beveridge 4151650a90 Fixed combined backing instrumental normalization, added anti-duplicate effort existing file checks 2024-12-07 23:56:23 -05:00
Andrew Beveridge 2c1e9f38f7 Bumped version for fixed release 2024-12-07 16:20:09 -05:00
Andrew Beveridge 164b0309ab Fixed youtube and gmail token scopes 2024-12-07 16:19:55 -05:00
Andrew Beveridge ca080e53a0 Added gmail draft 2024-12-07 02:23:20 -05:00
Andrew Beveridge 7776365c80 Added working re-combination of instrumental+bv 2024-12-07 02:03:48 -05:00
Andrew Beveridge ef3a2dfbe5 Restructured to output stems in subfolder and separate backing vocals properly 2024-12-04 19:09:22 -05:00
Andrew Beveridge 1b26fe9a46 Downgraded PyTorch to 2.4 to fix issue with Demucs on MPS throwing NotImplementedError: Output channels > 65536 not supported at the MPS device 2024-12-04 17:42:06 -05:00
Andrew Beveridge e6b475fc5c Replaced lyrics processing with karaoke-lyrics-processor library 2024-12-04 17:24:31 -05:00
Andrew Beveridge ff98d4d191 Added vendored version of nomad forked and branded cdgmaker to allow publishing this package 2024-12-04 16:40:31 -05:00
Andrew Beveridge df9d1053df Bumped version to fix cdgmaker 2024-11-04 02:59:29 -06:00
Andrew Beveridge 0618574cbf Upgraded cdgmaker 2024-11-04 02:59:06 -06:00
Andrew Beveridge 1028c26a59 Added CDG generation from LRC files 2024-11-04 02:58:16 -06:00
Andrew Beveridge 49982b4ad4 Added audioshake transcription 2024-09-17 12:29:35 -04:00
Andrew Beveridge a9291e97a1 Added lyrics-transcriber 2024-09-17 12:18:12 -04:00
Andrew Beveridge d96b844962 Added functionality to extract individual stems using htdemucs 2024-09-17 12:05:21 -04:00
Andrew Beveridge 5d5cb86494 Added 720p encoding 2024-09-17 11:00:49 -04:00
Andrew Beveridge d0276aafb4 Added support for generating file sharing link (e.g. dropbox folder) as part of finalise 2024-09-17 10:33:15 -04:00
Andrew Beveridge 60d347e812 Added dropbox sharing link to output 2024-09-17 00:06:18 -04:00
Andrew Beveridge 6362c426f2 Updated to latest version of audio-separator, added new karaoke model to defaults 2024-09-16 21:20:48 -04:00
Andrew Beveridge 7247bf2765 Bumped version to relax python restriction 2024-07-22 00:49:58 -04:00
Andrew Beveridge b68dd667a2 Updated dependencies 2024-07-21 03:11:17 -04:00
Andrew Beveridge fba1a1146e Fixed aac codec on non-mac 2024-07-14 04:25:40 -04:00
Andrew Beveridge 951512f236 Disabled windows CI build 2024-07-14 03:54:27 -04:00
Andrew Beveridge 45f13fdd2f Fixed non_interactive 2024-07-14 03:49:48 -04:00
Andrew Beveridge 87abc4720f Added non_interactive mode for finalise 2024-07-14 03:01:53 -04:00
Andrew Beveridge aaf1480964 Fix pyperclip in docker 2024-07-14 00:44:24 -04:00
Andrew Beveridge cc84254988 Updated to latest separator with model default tweak to use bs roformer 2024-07-03 14:36:50 -04:00
Andrew Beveridge 64924f5fee Added params to fix lyrics artist and title 2024-06-30 21:43:21 -04:00
Andrew Beveridge d8327936aa Updated finalise to remove with vocals MOV and allow re-running with only with vocals MP4 existing (to save disk space) 2024-06-26 12:32:37 -04:00
Andrew Beveridge 91c0db6f72 Fixed one more end video concat bug 2024-06-26 01:52:37 -04:00
Andrew Beveridge 1a8503730d Fixed bug with end video 2024-06-26 01:45:06 -04:00
Andrew Beveridge b0914f21dd Got TXT generation working 2024-06-26 01:36:50 -04:00
Andrew Beveridge 4867a6fa0c Added lyrics conversion to generate TXT format output zip 2024-06-26 01:17:06 -04:00
Andrew Beveridge 3e133ef787 Added lots more configuration options for the title and end screens 2024-06-26 00:27:37 -04:00
Andrew Beveridge 4b6845faff Added configurable title video and end video with ability to pass in existing image for either and customise duration 2024-06-25 23:06:33 -04:00
Andrew Beveridge 8181db5278 Added ability to specify existing instrumental track and existing title image file 2024-06-25 21:51:42 -04:00
Andrew Beveridge c17b6ca57e Added with vocals mp4 output 2024-06-25 21:16:58 -04:00
Andrew Beveridge 671eabea78 Updated dependencies, added non-standard space character cleanup 2024-06-18 17:28:12 -04:00
Andrew Beveridge e967a7e1d8 Merge branch 'main' of github.com:karaokenerds/karaoke-prep 2024-05-28 17:24:12 -04:00
Andrew Beveridge bb756c4740 Added skip CDG flag 2024-05-28 16:32:22 -04:00
Andrew Beveridge ☄️ ac4d8d5394 Merge pull request #1 from empz/improve-readme-windows
Improve readme Windows instructions.
2024-05-26 21:34:35 -04:00
Emiliano Parizzi 2530f150bc Improve readme Windows instructions. 2024-05-27 00:58:37 +02:00
Andrew Beveridge ee634ae70a Updated separator to latest to use mel roformer by default 2024-05-25 00:24:09 -04:00
Andrew Beveridge 06b670e62f Updated final mp4 render to use concat filter instead of demuxer which is buggy 2024-04-24 23:19:11 -04:00
Andrew Beveridge 008c09a72e Added folder processing with filename track and title pattern extraction and a dry run mode for easier bulk processing of local files 2024-04-01 17:21:17 -05:00
Andrew Beveridge 0587334eec Modified default models to remove buggy / resource hog HP9 2024-03-28 14:05:24 -05:00
Andrew Beveridge b3319774c2 Fixed audio-separator instantiation to work with latest version 2024-03-28 14:02:36 -05:00
Andrew Beveridge 6306c274cc Updated default models to use newer models 2024-03-24 00:10:21 -05:00
Andrew Beveridge f2bf347234 Updated to latest audio-separator 2024-03-23 22:23:04 -05:00
Andrew Beveridge e225dfcefc Updated to latest audio-separator, added additional default model to CLI 2024-03-02 23:25:39 -05:00
Andrew Beveridge d4ff5878a7 Fixed bug with artist and title only usage 2024-02-09 11:44:36 -05:00
Andrew Beveridge 8d11222f82 Updated to latest audio-separator, added support for multiple models 2024-02-06 23:27:21 -06:00
Andrew Beveridge ☄️ 010632d919 Added PyTorch CUDA instructions to README.md 2024-01-29 11:31:10 -05:00
Andrew Beveridge 299444c3e3 Updated install docs 2024-01-29 10:59:01 -05:00
Andrew Beveridge 6be2e9908f Tweaked logging 2024-01-28 13:31:00 -05:00
Andrew Beveridge d28595e273 Improved instrumental matching logic 2024-01-28 11:52:24 -05:00
Andrew Beveridge 13b3ad1b76 Fixed check for existing video, improved instrumental selection, updated deps 2024-01-28 11:29:08 -05:00
Andrew Beveridge a43cd39186 Added truncation to youtube title to handle long names 2024-01-22 12:35:14 -06:00
Andrew Beveridge e65b7d5c0a Fixed escaping for ffmpeg concat with quotes in filenames 2024-01-22 11:17:45 -06:00
Andrew Beveridge fe354fbad9 Fixed bug with output info 2024-01-22 01:06:58 -06:00
Andrew Beveridge 7d0fcfb33d Added support for local media file as input, not only URLs 2024-01-22 01:02:49 -06:00
Andrew Beveridge da594bdcd1 Added better error handling and user prompted overwrites to allow re-running more easily in case an error occurs 2024-01-21 23:31:19 -06:00
Andrew Beveridge 88eb6717c9 Fixed various bugs, improved log output for new functions 2024-01-21 22:15:06 -06:00
Andrew Beveridge 402aabe960 Bumped version to reflect recent refactoring and improvements 2024-01-21 21:20:10 -06:00
Andrew Beveridge f7fcf49954 Refactored more to break up process further and improve consistency in user input handling 2024-01-21 21:19:27 -06:00
Andrew Beveridge 3da47b69bc Refactored finalise class to split up into more testable functions 2024-01-21 19:46:33 -06:00
Andrew Beveridge e8165149dd Added exclusion of hidden files (e.g. .DS_Store) to rclone 2024-01-21 01:55:16 -06:00
Andrew Beveridge 6544edf04b Added jpg output file format for title image and set this as the video thumbnail on youtube automatically in finalisation step. Removed topic from youtube search as was getting worse results than without. Fixed conda env to work with poetry install. 2024-01-21 00:44:07 -06:00
Andrew Beveridge fa9ec1a75a Added MP4 and CDG parent dirs to public folder, added hyphen between track code and name, removed (Karaoke) from public dir 2024-01-12 21:35:19 -06:00
Andrew Beveridge 1dd474d25f Added conda environment with platform lock files generated by conda-lock, bumped poetry dependencies 2024-01-12 20:49:27 -06:00
Andrew Beveridge 4ada4ba039 Upgraded audio-separator to get normalization fixes 2024-01-09 00:38:02 -06:00
Andrew Beveridge ba1a1b90f7 Fixed handling of playlists, added failsafes to lyrics splitting logic to prevent infinite loop 2024-01-08 18:53:59 -06:00
Andrew Beveridge 88d07bb862 Improved media download filename detection, added failsafes for long lines with no spaces in lyrics 2024-01-08 18:15:23 -06:00
Andrew Beveridge 4a292fabd3 Refactored to make less assumptions about input coming from youtube, working towards supporting inputs from other sites too 2024-01-08 17:43:51 -06:00
Andrew Beveridge ceef4f5081 Added copy of processed lyrics to clipboard during prep 2024-01-08 14:35:07 -06:00
Andrew Beveridge d33ad04016 Added instrumental_format to CLI 2024-01-08 13:45:49 -06:00
Andrew Beveridge 513f8181df Added youtube uploading functionality 2024-01-08 02:25:53 -06:00
Andrew Beveridge fd49ca3c68 Reworked finalisation significantly to incorporate more features for nomad workflow, changed prep to also output lossless formats as well as lossy 2024-01-08 01:33:35 -06:00
Andrew Beveridge d064d8388a Fixed misuse of new audio-separator interface 2024-01-07 21:40:09 -06:00
Andrew Beveridge 096e499f6a Updated to use latest version of audio-separator with new module structure and platform-specific extras. FOr now only silicon supported as extra due to Poetry limitations... 2024-01-07 21:29:47 -06:00
Andrew Beveridge ee6874d094 Fixed ffmpeg download path 2023-12-20 23:41:46 -06:00
Andrew Beveridge 798ee11121 Moved to download ffmpeg using script 2023-12-20 23:38:22 -06:00
Andrew Beveridge bbb15b9744 Attempt to build windows binary with ffmpeg bundled 2023-12-20 23:33:40 -06:00
Andrew Beveridge c643fa6d73 Add all executable paths 2023-12-20 23:11:33 -06:00
Andrew Beveridge 390892ba2d One file, upload whole build dir 2023-12-20 23:10:40 -06:00
Andrew Beveridge aaef3376ae Attempt 2 at windows build config 2023-12-20 22:55:16 -06:00
Andrew Beveridge ad9492d7e3 Attempt to get pyinstaller building windows executable from github actions 2023-12-20 22:45:26 -06:00
Andrew Beveridge 5560557c3a Restructured to hopefully include all the right files as needed by Poetry 2023-12-20 19:35:11 -06:00
Andrew Beveridge 4ce326727d Fixed include paths 2023-12-20 19:25:23 -06:00
Andrew Beveridge fe6b89be9b Added title fonts to package, changed default to open-source Montserrat 2023-12-20 19:15:44 -06:00
Andrew Beveridge 90297bd7ef Improved video download logic to not assume format is WebM, now uses YDL progress hook to get correct extension regardless 2023-12-20 18:52:24 -06:00
Andrew Beveridge 8924875c26 Fixed os compatibility for temp folder, improved lyrics cleaning, made finalise more robust with cleaner logging, made default log output quieter 2023-12-20 18:27:35 -06:00
Andrew Beveridge 27946a1dd8 Improved logging, tested, readme, etc. 2023-12-20 16:23:44 -06:00
Andrew Beveridge b701920c75 Moved things around, made finalise a class, improved README to explain much more about usage 2023-12-20 14:10:08 -06:00
Andrew Beveridge 0c77999c46 Fixed title screen rendering bug 2023-12-19 23:04:19 -06:00
Andrew Beveridge 341a346865 Added finalise mode to remux and join output video to produce final version 2023-12-19 17:34:07 -06:00
Andrew Beveridge a5a35c710e Fixed frame rate in title video and added silent audio track to allow for ffmpeg concat without issues 2023-12-19 17:21:47 -06:00
Andrew Beveridge ac774d9aad Added lyrics processing to split lines 2023-12-19 16:21:53 -06:00
Andrew Beveridge 2d988de0a3 Fixed persistent artist bug 2023-12-19 14:47:11 -06:00
Andrew Beveridge 6a6154fe44 Improved robustness of title screen rendering 2023-12-18 14:57:58 -06:00
Andrew Beveridge f3ebaf5858 Improved title screen generation, though still not perfect 2023-12-18 14:41:19 -06:00
Andrew Beveridge 10554f19ee Added persistent artist and updated readme 2023-12-18 00:49:29 -06:00
Andrew Beveridge ff90b72a34 Added more robust font size calculation with padding to ensure title screen text fits, added support for passing through artist when fetching all tracks in playlist 2023-12-18 00:41:37 -06:00
Andrew Beveridge 1e8a23ad50 Bumped version 2023-12-18 00:14:07 -06:00
Andrew Beveridge 9fbe04ecf8 Added pillow to dependencies to ensure latest version is used in package 2023-12-18 00:13:39 -06:00
Andrew Beveridge 224a9cfd57 Tidied help output 2023-12-18 00:02:57 -06:00
77 changed files with 21265 additions and 1752 deletions

No files matched your search

+1 -1
View File
@@ -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
+7 -4
View File
@@ -1,11 +1,14 @@
# Andrew env
.DS_Store
.vscode
*.csv
*.mp3
# Andrew functional adds
audio/
lyrics/
karaoke/
/audio/
/lyrics/
/karaoke/
/tests/outputs
# Byte-compiled / optimized / DLL files
@@ -40,7 +43,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
+1 -1
View File
@@ -1,6 +1,6 @@
MIT License
Copyright (c) 2023 karaokenerds
Copyright (c) 2025 Nomad Karaoke LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+105 -152
View File
@@ -1,191 +1,144 @@
# Karaoke Prep 🎶
# Karaoke Gen
[![PyPI version](https://badge.fury.io/py/karaoke-prep.svg)](https://badge.fury.io/py/karaoke-prep)
Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens.
Prepare for karaoke video creation, by downloading audio from YouTube and lyrics from Genius for a given song.
## Overview
This was created to make it easier for me to prepare the source audio, lyrics and instrumental audio so I can then do the actual karaoke creation in focus mode without internet.
Karaoke Gen is a comprehensive tool for creating high-quality karaoke videos. It automates the entire workflow:
## Features
1. **Download** audio and lyrics for a specified song
2. **Separate** audio stems (vocals, instrumental)
3. **Synchronize** lyrics with the audio
4. **Generate** title and end screens
5. **Combine** everything into a polished final video
6. **Organize** and **share** the output files
- Audio Fetching: Automatically downloads audio in WAV format for the YouTube URL provided (or searches for the song/artist name and fetches the top result).
- Lyrics Fetching: Automatically fetches song lyrics from Genius.com using [LyricsGenius](https://github.com/johnwmillr/LyricsGenius).
- Audio Separation: Separates the downloaded audio into instrumental and vocal tracks, using [audio-separator](https://github.com/karaokenerds/python-audio-separator/).
- Multiple Audio Models: Runs audio separation with 2 different models (by default, `UVR_MDXNET_KARA_2` and `UVR-MDX-NET-Inst_HQ_3`) to give you options for the backing track.
- Easy Configuration: Control the tool's behavior using command-line arguments.
- Organized Outputs: Creates structured output directories for easy access to generated tracks and lyrics.
- Internet First: Completes operations which require internet first, in case user is preparing last-minute before a period of being offline!
- Flexible Input: provide just a YouTube URL, just an artist and title, or both.
- Playlist Processing: Capable of processing an entire YouTube playlist, extracting audio and lyrics for each track.
## Installation
## Installation 🛠️
You can install Karaoke Prep using pip:
`pip install karaoke-prep`
## Usage 🚀
### Command Line Interface (CLI)
You can use Karaoke Prep via the command line:
```sh
usage: karaoke-prep [-h] [-v] [--log_level LOG_LEVEL] [--model_name MODEL_NAME] [--model_file_dir MODEL_FILE_DIR] [--output_dir OUTPUT_DIR] [--use_cuda] [--use_coreml]
[--denoise DENOISE] [--normalize NORMALIZE] [--create_track_subfolders]
[artist] [title] [url]
Fetch audio and lyrics for a specified song, to prepare karaoke video creation.
positional arguments:
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
-v, --version show program's version number and exit
--log_level LOG_LEVEL Optional: logging level, e.g. info, debug, warning (default: info). Example: --log_level=debug
--model_name MODEL_NAME Optional: model name to be used for separation (default: UVR_MDXNET_KARA_2). Example: --model_name=UVR-MDX-NET-Inst_HQ_3
--model_file_dir MODEL_FILE_DIR Optional: model files directory (default: /tmp/audio-separator-models/). Example: --model_file_dir=/app/models
--output_dir OUTPUT_DIR Optional: directory to write output files (default: <current dir>). Example: --output_dir=/app/karaoke
--use_cuda Optional: use Nvidia GPU with CUDA for separation (default: False). Example: --use_cuda=true
--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
```
### Only YouTube URL
This will process the video at the given URL, *guessing the artist and title from the YouTube title*.
⚠️ Be aware the downloaded lyrics may be incorrect if the video title doesn't match the standard "Artist - Title" format.
```
karaoke-prep "https://www.youtube.com/watch?v=YOUR_VIDEO_ID"
```bash
pip install karaoke-gen
```
### Artist and Title Only
## Quick Start
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.
```bash
# Generate a karaoke video from a YouTube URL
karaoke-gen "https://www.youtube.com/watch?v=dQw4w9WgXcQ" "Rick Astley" "Never Gonna Give You Up"
```
karaoke-prep "The Fray" "Never Say Never"
# Or let it search YouTube for you
karaoke-gen "Rick Astley" "Never Gonna Give You Up"
# Process multiple tracks in bulk from a CSV file
karaoke-bulk input.csv --style_params_json=style.json
```
### ⭐ YouTube URL with Artist and Title
## Workflow Options
For more precise control (and most consistent results), provide the YouTube URL along with the artist and title to avoid any guesswork.
Karaoke Gen supports different workflow options to fit your needs:
```
karaoke-prep "https://www.youtube.com/watch?v=YOUR_VIDEO_ID" "The Fray" "Never Say Never"
```bash
# Run only the preparation phase (download, separate stems, create title screens)
karaoke-gen --prep-only "Rick Astley" "Never Gonna Give You Up"
# Run only the finalisation phase (must be run in a directory prepared by the prep phase)
karaoke-gen --finalise-only
# Skip automatic lyrics transcription/synchronization (for manual syncing)
karaoke-gen --skip-transcription "Rick Astley" "Never Gonna Give You Up"
# Skip audio separation (if you already have instrumental)
karaoke-gen --skip-separation --existing-instrumental="path/to/instrumental.mp3" "Rick Astley" "Never Gonna Give You Up"
```
### YouTube Playlist URL
## Advanced Features
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.
### Audio Processing
```
karaoke-prep "https://www.youtube.com/playlist?list=YOUR_PLAYLIST_ID"
```bash
# Specify custom audio separation models
karaoke-gen --clean_instrumental_model="model_name.ckpt" "Rick Astley" "Never Gonna Give You Up"
```
By default, you'll end up with files in the current folder, neatly organised into folders for each track and files named consistently e.g.
### Lyrics Handling
```
├── 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
```bash
# Use a local lyrics file instead of fetching from online
karaoke-gen --lyrics_file="path/to/lyrics.txt" "Rick Astley" "Never Gonna Give You Up"
# Adjust subtitle timing
karaoke-gen --subtitle_offset_ms=500 "Rick Astley" "Never Gonna Give You Up"
```
## Requirements 📋
### Finalisation Options
Python >= 3.9
```bash
# Enable CDG ZIP generation
karaoke-gen --enable_cdg --style_params_json="path/to/style.json" "Rick Astley" "Never Gonna Give You Up"
Libraries: onnx, onnxruntime, numpy, soundfile, librosa, torch, wget, six
# Enable TXT ZIP generation
karaoke-gen --enable_txt "Rick Astley" "Never Gonna Give You Up"
## Developing Locally
# Upload to YouTube
karaoke-gen --youtube_client_secrets_file="path/to/client_secret.json" --youtube_description_file="path/to/description.txt" "Rick Astley" "Never Gonna Give You Up"
This project uses Poetry for dependency management and packaging. Follow these steps to setup a local development environment:
### Prerequisites
- Make sure you have Python 3.9 or newer installed on your machine.
- Install Poetry by following the installation guide here.
### Clone the Repository
Clone the repository to your local machine:
```
git clone https://github.com/YOUR_USERNAME/karaoke-prep.git
cd karaoke-prep
# Organize files with brand code
karaoke-gen --brand_prefix="BRAND" --organised_dir="path/to/Tracks-Organized" "Rick Astley" "Never Gonna Give You Up"
```
Replace YOUR_USERNAME with your GitHub username if you've forked the repository, or use the main repository URL if you have the permissions.
## Python API
### Install Dependencies
Karaoke Gen can also be used as a Python library:
Run the following command to install the project dependencies:
```python
import asyncio
from karaoke_gen import KaraokeController, ProjectConfig
```
poetry install
async def generate_karaoke():
# Create a configuration
config = ProjectConfig(
artist="Rick Astley",
title="Never Gonna Give You Up",
input_media="https://www.youtube.com/watch?v=dQw4w9WgXcQ",
output_dir="output",
create_track_subfolders=True,
)
# Create a controller
controller = KaraokeController(config)
# Process the track
tracks = await controller.process()
# Print the output files
for track in tracks:
print(f"Final video: {track.final_video}")
# Run the async function
asyncio.run(generate_karaoke())
```
### Activate the Virtual Environment
## Architecture
To activate the virtual environment, use the following command:
Karaoke Gen has a modular architecture with the following components:
```
poetry shell
- **Controller**: Orchestrates the entire process
- **Services**: Handle specific aspects of the process
- **Media Service**: Downloads and extracts media
- **Audio Service**: Separates and processes audio
- **Lyrics Service**: Fetches and synchronizes lyrics
- **Video Service**: Renders video with synchronized lyrics
- **Distribution Service**: Organizes and shares the output files
- **Utilities**: Common utility functions for file handling, logging, etc.
## Full Command Reference
For a complete list of options:
```bash
karaoke-gen --help
karaoke-bulk --help
```
### Running the Command-Line Interface Locally
## License
You can run the CLI command directly within the virtual environment. For example:
```
karaoke-prep 1
```
### Deactivate the Virtual Environment
Once you are done with your development work, you can exit the virtual environment by simply typing:
```
exit
```
### Building the Package
To build the package for distribution, use the following command:
```
poetry build
```
This will generate the distribution packages in the dist directory - but for now only @beveradb will be able to publish to PyPI.
## Contributing 🤝
Contributions are very much welcome! Please fork the repository and submit a pull request with your changes, and I'll try to review, merge and publish promptly!
- This project is 100% open-source and free for anyone to use and modify as they wish.
- If the maintenance workload for this repo somehow becomes too much for me I'll ask for volunteers to share maintainership of the repo, though I don't think that is very likely
## License 📄
This project is licensed under the MIT [License](LICENSE).
- **Please Note:** If you choose to integrate this project into some other project using the default model or any other model trained as part of the [UVR](https://github.com/Anjok07/ultimatevocalremovergui) project, please honor the MIT license by providing credit to UVR and its developers!
## Credits 🙏
- [Anjok07](https://github.com/Anjok07) - Author of [Ultimate Vocal Remover GUI](https://github.com/Anjok07/ultimatevocalremovergui), which was essential for the creation of [audio-separator](https://github.com/karaokenerds/python-audio-separator/)! Thank you!
## Contact 💌
For questions or feedback, please raise an issue or reach out to @beveradb ([Andrew Beveridge](mailto:andrew@beveridge.uk)) directly.
MIT
+20
View File
@@ -0,0 +1,20 @@
name: karaoke-gen
channels:
- conda-forge
# We want to have a reproducible setup, so we don't want default channels,
# which may be different for different users. All required channels should
# be listed explicitly here.
- nodefaults
dependencies:
- python>=3.10,<3.12 # or don't specify the version and use the latest stable Python
- mamba
- pip # pip must be mentioned explicitly, or conda-lock will fail
- poetry
# Non-standard section listing target platforms for conda-lock:
platforms:
- linux-64
- osx-64
- win-64
- osx-arm64 # Apple Silicon, e.g. M1/M2
- linux-aarch64 # Docker on Apple Silicon
+87
View File
@@ -0,0 +1,87 @@
# Pre-Refactor Finalise Functionality Map
This document maps the functionality in the original `old_finalise.py` file, organized by major functional areas with specific line ranges.
## Class Definition and Initialization
- **Class Definition**: Lines 23-23
- **Initialization and Configuration**: Lines 23-140
- Logging setup: Lines 46-64
- FFmpeg path and command setup: Lines 67-77
- Configuration parameters: Lines 79-107
- Feature flags: Lines 109-114
- File naming conventions: Lines 116-137
- Codec detection: Line 129
## Configuration and Validation
- **Input Files Validation**: Lines 142-171
- **Output Filenames Preparation**: Lines 173-187
- **User Interaction Utilities**: Lines 189-210
- **Feature Validation**: Lines 212-271
## YouTube Integration
- **YouTube Authentication**: Lines 273-292
- **YouTube Channel ID Retrieval**: Lines 294-305
- **Video Existence Check**: Lines 307-345
- **Video Deletion**: Lines 347-364
- **Title Handling**: Lines 366-371
- **Video Upload**: Lines 373-434
## Folder Organization and Branding
- **Brand Code Generation**: Lines 436-454
- **Discord Notifications**: Lines 456-460
- **File Organization**: Lines 589-607
- **Public Share Directory Management**: Lines 609-652
- **Remote Sync (rclone)**: Lines 654-668
- **Sharing Link Generation**: Lines 682-702
- **Existing Brand Code Extraction**: Lines 704-715
## File Discovery and Processing
- **With Vocals File Finding**: Lines 462-502
- **Instrumental Audio Selection**: Lines 504-562
- **Artist and Title Extraction**: Lines 564-587
## Video Processing (FFmpeg Operations)
- **Command Execution Wrapper**: Lines 589-596
- **Video Remuxing with Instrumental Audio**: Lines 598-606
- **MOV to MP4 Conversion**: Lines 608-616
- **Lossless MP4 Encoding**: Lines 618-629
- **Lossy MP4 Encoding**: Lines 631-639
- **MKV Encoding**: Lines 641-649
- **720p Version Encoding**: Lines 651-661
- **Concatenation Filter Preparation**: Lines 663-675
- **Final Video File Creation**: Lines 677-716
## CDG/TXT Creation (Karaoke File Formats)
- **CDG ZIP File Creation**: Lines 718-783
- **TXT ZIP File Creation**: Lines 785-816
## Distribution and Notifications
- **Discord Notification Posting**: Lines 670-680
- **Email Integration**: Lines 738-809
- Gmail Authentication: Lines 738-757
- Email Draft Creation: Lines 759-783
- Email Template Testing: Lines 785-797
## Codec Detection
- **AAC Codec Detection**: Lines 799-813
## Main Processing Flow
- **Process Method (Main Workflow)**: Lines 815-886
- Feature validation: Line 821
- File discovery: Lines 823-827
- Output preparation: Lines 829-830
- CDG/TXT creation: Lines 832-835
- Video processing: Line 837
- Optional features execution: Line 839
- Result compilation: Lines 841-861
- Email notification: Line 863
+37
View File
@@ -0,0 +1,37 @@
# -*- mode: python ; coding: utf-8 -*-
a = Analysis(
['karaoke_gen/utils/gen_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-gen',
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,
)
+209
View File
@@ -0,0 +1,209 @@
"""
Karaoke Generator package.
This package provides tools for generating karaoke videos with synchronized lyrics.
It handles the entire process from downloading audio and lyrics to creating the final
video with title screens, synchronized lyrics, and distribution options.
"""
__version__ = "0.50.0"
# Import core components
from karaoke_gen.controller import KaraokeController
from karaoke_gen.core import ProjectConfig, Track, KaraokeGenError
# Import services
from karaoke_gen.services import (
MainService,
AudioService,
LyricsService,
MediaService,
VideoService,
DistributionService,
)
# Import utility functions
from karaoke_gen.utils import (
# Config utilities
load_config_file,
save_config_file,
get_config_value,
set_config_value,
merge_configs,
validate_required_config_keys,
get_nested_config_value,
set_nested_config_value,
# File utilities
sanitize_filename,
ensure_directory_exists,
backup_existing_files,
file_exists,
copy_file,
move_file,
delete_file,
create_zip_file,
execute_command,
# Logging utilities
setup_logger,
get_log_level_from_string,
configure_logger_from_config,
log_section,
log_subsection,
log_dict,
log_exception,
# Path utilities
normalize_path,
join_paths,
get_absolute_path,
get_relative_path,
get_parent_directory,
get_filename,
get_filename_without_extension,
get_file_extension,
create_directory,
delete_directory,
list_files,
list_directories,
get_file_info,
find_files_by_extension,
copy_directory,
move_directory,
get_directory_size,
# String utilities
slugify,
truncate_string,
extract_artist_and_title,
format_duration,
format_filesize,
strip_html_tags,
normalize_whitespace,
extract_urls,
replace_placeholders,
generate_random_string,
# Validation utilities
is_url,
is_file,
is_directory,
prompt_user_confirmation_or_raise_exception,
prompt_user_bool,
validate_input_parameters_for_features,
# Date utilities
get_current_timestamp,
get_current_date,
get_current_time,
format_date,
parse_date,
get_date_components,
add_days,
days_between,
is_date_in_range,
get_month_name,
get_day_of_week,
)
__all__ = [
# Version
"__version__",
# Core components
"KaraokeController",
"ProjectConfig",
"Track",
"KaraokeGenError",
# Services
"MainService",
"AudioService",
"LyricsService",
"MediaService",
"VideoService",
"DistributionService",
# Config utilities
"load_config_file",
"save_config_file",
"get_config_value",
"set_config_value",
"merge_configs",
"validate_required_config_keys",
"get_nested_config_value",
"set_nested_config_value",
# File utilities
"sanitize_filename",
"ensure_directory_exists",
"backup_existing_files",
"file_exists",
"copy_file",
"move_file",
"delete_file",
"create_zip_file",
"execute_command",
# Logging utilities
"setup_logger",
"get_log_level_from_string",
"configure_logger_from_config",
"log_section",
"log_subsection",
"log_dict",
"log_exception",
# Path utilities
"normalize_path",
"join_paths",
"get_absolute_path",
"get_relative_path",
"get_parent_directory",
"get_filename",
"get_filename_without_extension",
"get_file_extension",
"create_directory",
"delete_directory",
"list_files",
"list_directories",
"get_file_info",
"find_files_by_extension",
"copy_directory",
"move_directory",
"get_directory_size",
# String utilities
"slugify",
"truncate_string",
"extract_artist_and_title",
"format_duration",
"format_filesize",
"strip_html_tags",
"normalize_whitespace",
"extract_urls",
"replace_placeholders",
"generate_random_string",
# Validation utilities
"is_url",
"is_file",
"is_directory",
"prompt_user_confirmation_or_raise_exception",
"prompt_user_bool",
"validate_input_parameters_for_features",
# Date utilities
"get_current_timestamp",
"get_current_date",
"get_current_time",
"format_date",
"parse_date",
"get_date_components",
"add_days",
"days_between",
"is_date_in_range",
"get_month_name",
"get_day_of_week",
]
+8
View File
@@ -0,0 +1,8 @@
"""
Main entry point for the karaoke generator.
"""
from karaoke_gen.cli import main
if __name__ == "__main__":
main()
+35
View File
@@ -0,0 +1,35 @@
"""
Command-line interface module for the karaoke_gen package.
This module provides the command-line interface for the karaoke generator.
"""
import asyncio
from typing import Dict, Any
from karaoke_gen.cli.parser import parse_args, create_parser
from karaoke_gen.cli.commands import execute_command, get_command, Command, ProcessCommand, TestEmailTemplateCommand, BulkProcessCommand
__all__ = [
"main",
"parse_args",
"create_parser",
"execute_command",
"get_command",
"Command",
"ProcessCommand",
"TestEmailTemplateCommand",
"BulkProcessCommand",
]
def main() -> None:
"""
Main entry point for the CLI.
"""
args = parse_args()
asyncio.run(execute_command(args))
if __name__ == "__main__":
main()
+8
View File
@@ -0,0 +1,8 @@
"""
Main entry point for running the CLI as a module.
"""
from karaoke_gen.cli import main
if __name__ == "__main__":
main()
+339
View File
@@ -0,0 +1,339 @@
#!/usr/bin/env python
import argparse
import logging
import pkg_resources
import os
import csv
import asyncio
import json
import sys
from typing import Dict, Any, List
from karaoke_gen.core.project import ProjectConfig
from karaoke_gen.core.track import Track
from karaoke_gen.controller import KaraokeController
from karaoke_gen.utils.logging import setup_logger
# Global logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO) # Set initial log level
async def process_track_prep(row: Dict[str, str], args: Dict[str, Any], log_formatter: logging.Formatter) -> bool:
"""
First phase: Process a track through prep stage only, without video rendering.
Args:
row: The CSV row containing track information
args: The parsed command-line arguments
log_formatter: The log formatter to use
Returns:
True if processing was successful, False otherwise
"""
original_dir = os.getcwd()
try:
artist = row["Artist"].strip()
title = row["Title"].strip()
guide_file = row["Mixed Audio Filename"].strip()
instrumental_file = row["Instrumental Audio Filename"].strip()
logger.info(f"Initial prep phase for track: {artist} - {title}")
# Create configuration
config = ProjectConfig(
# Basic inputs
artist=artist,
title=title,
input_media=guide_file,
existing_instrumental=instrumental_file,
# Workflow control
prep_only=True, # Only run prep phase
render_video=False, # No video rendering in first phase
# Logging & Debugging
logger=logger,
log_level=args.get("log_level", logging.INFO),
log_formatter=log_formatter,
dry_run=args.get("dry_run", False),
# Input/Output Configuration
output_dir=args.get("output_dir", "."),
create_track_subfolders=True,
# Style Configuration
style_params_json=args.get("style_params_json"),
)
# Create controller and process
controller = KaraokeController(config)
tracks = await controller.process()
return True
except Exception as e:
logger.error(f"Failed initial prep for {artist} - {title}: {str(e)}")
return False
finally:
os.chdir(original_dir)
async def process_track_render(row: Dict[str, str], args: Dict[str, Any], log_formatter: logging.Formatter) -> bool:
"""
Second phase: Re-run prep with video rendering and run finalise.
Args:
row: The CSV row containing track information
args: The parsed command-line arguments
log_formatter: The log formatter to use
Returns:
True if processing was successful, False otherwise
"""
original_dir = os.getcwd()
try:
artist = row["Artist"].strip()
title = row["Title"].strip()
guide_file = row["Mixed Audio Filename"].strip()
instrumental_file = row["Instrumental Audio Filename"].strip()
logger.info(f"Render phase for track: {artist} - {title}")
# Create configuration for the render phase
config = ProjectConfig(
# Basic inputs
artist=artist,
title=title,
input_media=guide_file,
existing_instrumental=instrumental_file,
# Workflow control
render_video=True,
skip_transcription_review=True,
# Logging & Debugging
logger=logger,
log_level=args.get("log_level", logging.INFO),
log_formatter=log_formatter,
dry_run=args.get("dry_run", False),
# Input/Output Configuration
output_dir=args.get("output_dir", "."),
create_track_subfolders=True,
# Style Configuration
style_params_json=args.get("style_params_json"),
# Finalisation Configuration
enable_cdg=args.get("enable_cdg", False),
enable_txt=args.get("enable_txt", False),
brand_prefix=args.get("brand_prefix"),
organised_dir=args.get("organised_dir"),
organised_dir_rclone_root=args.get("organised_dir_rclone_root"),
public_share_dir=args.get("public_share_dir"),
youtube_client_secrets_file=args.get("youtube_client_secrets_file"),
youtube_description_file=args.get("youtube_description_file"),
rclone_destination=args.get("rclone_destination"),
discord_webhook_url=args.get("discord_webhook_url"),
email_template_file=args.get("email_template_file"),
non_interactive=True, # Always run in non-interactive mode for bulk processing
)
# Create controller and process
controller = KaraokeController(config)
tracks = await controller.process()
logger.info(f"Successfully completed auto processing for: {artist} - {title}")
return True
except Exception as e:
logger.error(f"Failed render/finalise for {artist} - {title}: {str(e)}")
return False
finally:
os.chdir(original_dir)
def update_csv_status(csv_path: str, row_index: int, new_status: str) -> None:
"""
Update the status of a processed row in the CSV file.
Args:
csv_path: The path to the CSV file
row_index: The index of the row to update
new_status: The new status to set
"""
# Read all rows
with open(csv_path, "r") as f:
rows = list(csv.DictReader(f))
# Update status for the processed row
rows[row_index]["Status"] = new_status
# Write back to CSV
fieldnames = rows[0].keys()
with open(csv_path, "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
async def async_main() -> None:
"""
Main async function for bulk processing.
"""
parser = argparse.ArgumentParser(
description="Process multiple karaoke tracks in bulk from a CSV file.",
formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=54),
)
# Basic information
parser.add_argument(
"input_csv",
help="Path to CSV file containing tracks to process. CSV should have columns: Artist,Title,Mixed Audio Filename,Instrumental Audio Filename,Status",
)
package_version = pkg_resources.get_distribution("karaoke-gen").version
parser.add_argument("-v", "--version", action="version", version=f"%(prog)s {package_version}")
# Required arguments
parser.add_argument(
"--style_params_json",
required=True,
help="Path to style parameters JSON file",
)
parser.add_argument(
"--output_dir",
default=".",
help="Optional: directory to write output files (default: <current dir>). Example: --output_dir=/app/karaoke",
)
# Finalise-specific arguments
parser.add_argument(
"--enable_cdg",
action="store_true",
help="Optional: Enable CDG ZIP generation during finalisation. Example: --enable_cdg",
)
parser.add_argument(
"--enable_txt",
action="store_true",
help="Optional: Enable TXT ZIP generation during finalisation. Example: --enable_txt",
)
# Distribution-specific arguments
parser.add_argument(
"--brand_prefix",
help="Optional: Your brand prefix to calculate the next sequential number. Example: --brand_prefix=BRAND",
)
parser.add_argument(
"--organised_dir",
help="Optional: Target directory where the processed folder will be moved. Example: --organised_dir='/path/to/Tracks-Organized'",
)
parser.add_argument(
"--organised_dir_rclone_root",
help="Optional: Rclone path which maps to your organised_dir. Example: --organised_dir_rclone_root='dropbox:Media/Karaoke/Tracks-Organized'",
)
parser.add_argument(
"--public_share_dir",
help="Optional: Public share directory for final files. Example: --public_share_dir='/path/to/Tracks-PublicShare'",
)
parser.add_argument(
"--youtube_client_secrets_file",
help="Optional: Path to youtube client secrets file. Example: --youtube_client_secrets_file='/path/to/client_secret.json'",
)
parser.add_argument(
"--youtube_description_file",
help="Optional: Path to youtube description template. Example: --youtube_description_file='/path/to/description.txt'",
)
parser.add_argument(
"--rclone_destination",
help="Optional: Rclone destination for public_share_dir sync. Example: --rclone_destination='googledrive:KaraokeFolder'",
)
parser.add_argument(
"--discord_webhook_url",
help="Optional: Discord webhook URL for notifications. Example: --discord_webhook_url='https://discord.com/api/webhooks/...'",
)
parser.add_argument(
"--email_template_file",
help="Optional: Path to email template file. Example: --email_template_file='/path/to/template.txt'",
)
# Logging & Debugging
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: perform a dry run without making any changes (default: %(default)s). Example: --dry_run",
)
args = parser.parse_args()
# Convert input_csv to absolute path
args.input_csv = os.path.abspath(args.input_csv)
if not os.path.isfile(args.input_csv):
logger.error(f"Input CSV file not found: {args.input_csv}")
exit(1)
# Fix: Convert log level to uppercase before getting attribute
log_level = getattr(logging, args.log_level.upper())
args.log_level = log_level # Store the numeric log level in args
# Convert args to dictionary for easier access
args_dict = vars(args)
logger.info(f"Starting bulk processing with input CSV: {args.input_csv}")
# Read CSV
with open(args.input_csv, "r") as f:
reader = csv.DictReader(f)
rows = list(reader)
# Phase 1: Initial prep for all tracks
logger.info("Starting Phase 1: Initial prep for all tracks")
for i, row in enumerate(rows):
if row["Status"].lower() != "uploaded":
logger.info(f"Skipping {row['Artist']} - {row['Title']} (Status: {row['Status']})")
continue
success = await process_track_prep(row, args_dict, log_formatter)
if not args.dry_run:
if success:
update_csv_status(args.input_csv, i, "Prep_Complete")
else:
update_csv_status(args.input_csv, i, "Prep_Failed")
# Phase 2: Render and finalise all tracks
logger.info("Starting Phase 2: Render and finalise for all tracks")
for i, row in enumerate(rows):
if row["Status"].lower() not in ["prep_complete", "uploaded"]:
logger.info(f"Skipping {row['Artist']} - {row['Title']} (Status: {row['Status']})")
continue
success = await process_track_render(row, args_dict, log_formatter)
if not args.dry_run:
if success:
update_csv_status(args.input_csv, i, "Completed")
else:
update_csv_status(args.input_csv, i, "Render_Failed")
def main() -> None:
"""
Main entry point for bulk processing.
"""
# Set up logging only once
global log_formatter # Make log_formatter accessible to other functions
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)
# Run the async main function using asyncio
asyncio.run(async_main())
if __name__ == "__main__":
main()
+441
View File
@@ -0,0 +1,441 @@
import os
import logging
import asyncio
import time
import pyperclip
import json
import warnings
from typing import Dict, Any, List, Optional
from abc import ABC, abstractmethod
from karaoke_gen.core.project import ProjectConfig
from karaoke_gen.core.track import Track
from karaoke_gen.controller import KaraokeController
from karaoke_gen.cli.bulk_cli import async_main as bulk_async_main
class Command(ABC):
"""Base class for all commands."""
@abstractmethod
async def execute(self, args: Dict[str, Any]) -> None:
"""
Execute the command.
Args:
args: The parsed command-line arguments
"""
pass
class ProcessCommand(Command):
"""Command for processing a track or tracks."""
async def execute(self, args: Dict[str, Any]) -> None:
"""
Execute the process command.
Args:
args: The parsed command-line arguments
"""
# Set up logging
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)
log_level = getattr(logging, args.get("log_level", "INFO").upper())
logger.setLevel(log_level)
# Parse input arguments
input_media, artist, title, filename_pattern = self._parse_input_args(args, logger)
# Set up environment variables for lyrics-only mode
if args.get("lyrics_only"):
args["skip_separation"] = True
os.environ["KARAOKE_GEN_SKIP_AUDIO_SEPARATION"] = "1"
os.environ["KARAOKE_GEN_SKIP_TITLE_END_SCREENS"] = "1"
logger.info("Lyrics-only mode enabled: skipping audio separation and title/end screen generation")
# Create configuration
config = self._create_config(args, input_media, artist, title, filename_pattern, log_formatter, log_level, logger)
# Create controller
controller = KaraokeController(config)
# Process tracks
tracks = await controller.process()
# Display results
self._display_results(tracks, args, logger)
def _parse_input_args(self, args: Dict[str, Any], logger: logging.Logger) -> tuple:
"""
Parse input arguments.
Args:
args: The parsed command-line arguments
logger: The logger
Returns:
Tuple of (input_media, artist, title, filename_pattern)
"""
input_media, artist, title, filename_pattern = None, None, None, None
if not args.get("args"):
logger.error("No input arguments provided")
exit(1)
# Allow 3 forms of positional arguments:
# 1. URL or Media File only (may be single track URL, playlist URL, or local file)
# 2. Artist and Title only
# 3. URL, Artist, and Title
if args["args"] and (self._is_url(args["args"][0]) or self._is_file(args["args"][0])):
input_media = args["args"][0]
if len(args["args"]) > 2:
artist = args["args"][1]
title = args["args"][2]
elif len(args["args"]) > 1:
artist = args["args"][1]
else:
logger.warning("Input media provided without Artist and Title, both will be guessed from title")
elif os.path.isdir(args["args"][0]):
if not args.get("filename_pattern"):
logger.error("Filename pattern is required when processing a folder.")
exit(1)
if len(args["args"]) <= 1:
logger.error("Second parameter provided must be Artist name; Artist is required when processing a folder.")
exit(1)
input_media = args["args"][0]
artist = args["args"][1]
filename_pattern = args.get("filename_pattern")
elif len(args["args"]) > 1:
artist = args["args"][0]
title = args["args"][1]
logger.warning(f"No input media provided, the top YouTube search result for {artist} - {title} will be used.")
else:
logger.error("Invalid input arguments")
exit(1)
return input_media, artist, title, filename_pattern
def _is_url(self, string: str) -> bool:
"""
Check if a string is a URL.
Args:
string: The string to check
Returns:
True if the string is a URL, False otherwise
"""
return string.startswith("http://") or string.startswith("https://")
def _is_file(self, string: str) -> bool:
"""
Check if a string is a file.
Args:
string: The string to check
Returns:
True if the string is a file, False otherwise
"""
return os.path.isfile(string)
def _create_config(self, args: Dict[str, Any], input_media: Optional[str], artist: Optional[str],
title: Optional[str], filename_pattern: Optional[str], log_formatter: logging.Formatter,
log_level: int, logger: logging.Logger) -> ProjectConfig:
"""
Create a project configuration.
Args:
args: The parsed command-line arguments
input_media: The input media
artist: The artist
title: The title
filename_pattern: The filename pattern
log_formatter: The log formatter
log_level: The log level
logger: The logger
Returns:
The project configuration
"""
# Load CDG styles if CDG generation is enabled
cdg_styles = None
if args.get("enable_cdg") and args.get("style_params_json"):
try:
with open(args.get("style_params_json"), "r") as f:
style_params = json.loads(f.read())
cdg_styles = style_params.get("cdg")
except FileNotFoundError:
logger.error(f"CDG styles configuration file not found: {args.get('style_params_json')}")
exit(1)
except json.JSONDecodeError as e:
logger.error(f"Invalid JSON in CDG styles configuration file: {e}")
exit(1)
return ProjectConfig(
# Basic inputs
input_media=input_media,
artist=artist,
title=title,
filename_pattern=filename_pattern,
# Workflow control
prep_only=args.get("prep_only", False),
finalise_only=args.get("finalise_only", False),
skip_transcription=args.get("skip_transcription", False),
skip_separation=args.get("skip_separation", False),
skip_lyrics=args.get("skip_lyrics", False),
lyrics_only=args.get("lyrics_only", False),
edit_lyrics=args.get("edit_lyrics", False),
# Logging & Debugging
dry_run=args.get("dry_run", False),
logger=logger,
log_level=log_level,
log_formatter=log_formatter,
render_bounding_boxes=args.get("render_bounding_boxes", False),
# Input/Output Configuration
output_dir=args.get("output_dir", "."),
create_track_subfolders=args.get("no_track_subfolders", True),
lossless_output_format=args.get("lossless_output_format", "FLAC"),
output_png=args.get("output_png", True),
output_jpg=args.get("output_jpg", True),
# Audio Processing Configuration
clean_instrumental_model=args.get("clean_instrumental_model", "model_bs_roformer_ep_317_sdr_12.9755.ckpt"),
backing_vocals_models=args.get("backing_vocals_models", ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"]),
other_stems_models=args.get("other_stems_models", ["htdemucs_6s.yaml"]),
model_file_dir=args.get("model_file_dir", os.path.join(os.path.dirname(os.path.dirname(__file__)), "models")),
existing_instrumental=args.get("existing_instrumental"),
instrumental_format=args.get("instrumental_format", "flac"),
# Lyrics Configuration
lyrics_artist=args.get("lyrics_artist"),
lyrics_title=args.get("lyrics_title"),
lyrics_file=args.get("lyrics_file"),
skip_transcription_review=args.get("skip_transcription_review", False),
subtitle_offset_ms=args.get("subtitle_offset_ms", 0),
# Style Configuration
style_params_json=args.get("style_params_json"),
# Finalisation Configuration
enable_cdg=args.get("enable_cdg", False),
enable_txt=args.get("enable_txt", False),
brand_prefix=args.get("brand_prefix"),
organised_dir=args.get("organised_dir"),
organised_dir_rclone_root=args.get("organised_dir_rclone_root"),
public_share_dir=args.get("public_share_dir"),
youtube_client_secrets_file=args.get("youtube_client_secrets_file"),
youtube_description_file=args.get("youtube_description_file"),
rclone_destination=args.get("rclone_destination"),
discord_webhook_url=args.get("discord_webhook_url"),
email_template_file=args.get("email_template_file"),
cdg_styles=cdg_styles,
keep_brand_code=args.get("keep_brand_code", False),
non_interactive=args.get("yes", False),
)
def _display_results(self, tracks: List[Track], args: Dict[str, Any], logger: logging.Logger) -> None:
"""
Display the results of processing.
Args:
tracks: The processed tracks
args: The parsed command-line arguments
logger: The logger
"""
# If prep-only mode, display detailed output
if args.get("prep_only"):
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" 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" Separated Audio:")
# Clean Instrumental
if track.separated_audio and "clean_instrumental" in track.separated_audio:
logger.info(f" Clean Instrumental Model:")
for stem_type, file_path in track.separated_audio["clean_instrumental"].items():
logger.info(f" {stem_type.capitalize()}: {file_path}")
# Other Stems
if track.separated_audio and "other_stems" in track.separated_audio:
logger.info(f" Other Stems Models:")
for model, stems in track.separated_audio["other_stems"].items():
logger.info(f" Model: {model}")
for stem_type, file_path in stems.items():
logger.info(f" {stem_type.capitalize()}: {file_path}")
# Backing Vocals
if track.separated_audio and "backing_vocals" in track.separated_audio:
logger.info(f" Backing Vocals Models:")
for model, stems in track.separated_audio["backing_vocals"].items():
logger.info(f" Model: {model}")
for stem_type, file_path in stems.items():
logger.info(f" {stem_type.capitalize()}: {file_path}")
# Combined Instrumentals
if track.separated_audio and "combined_instrumentals" in track.separated_audio:
logger.info(f" Combined Instrumentals:")
for model, file_path in track.separated_audio["combined_instrumentals"].items():
logger.info(f" Model: {model}")
logger.info(f" Combined Instrumental: {file_path}")
logger.info("Preparation phase complete.")
return
# For finalise-only or full workflow, display summary of outputs
for track in tracks:
logger.info(f"Karaoke processing complete! Output files:")
logger.info(f"")
logger.info(f"Track: {track.artist} - {track.title}")
logger.info(f"")
logger.info(f"Working Files:")
logger.info(f" Video With Vocals: {track.video_with_vocals}")
logger.info(f" Video With Instrumental: {track.video_with_instrumental}")
logger.info(f"")
logger.info(f"Final Videos:")
logger.info(f" Lossless 4K MP4 (PCM): {track.final_video}")
logger.info(f" Lossless 4K MKV (FLAC): {track.final_video_mkv}")
logger.info(f" Lossy 4K MP4 (AAC): {track.final_video_lossy}")
logger.info(f" Lossy 720p MP4 (AAC): {track.final_video_720p}")
if hasattr(track, "final_karaoke_cdg_zip") or hasattr(track, "final_karaoke_txt_zip"):
logger.info(f"")
logger.info(f"Karaoke Files:")
if hasattr(track, "final_karaoke_cdg_zip") and track.final_karaoke_cdg_zip:
logger.info(f" CDG+MP3 ZIP: {track.final_karaoke_cdg_zip}")
if hasattr(track, "final_karaoke_txt_zip") and track.final_karaoke_txt_zip:
logger.info(f" TXT+MP3 ZIP: {track.final_karaoke_txt_zip}")
if hasattr(track, "brand_code") and track.brand_code:
logger.info(f"")
logger.info(f"Organization:")
logger.info(f" Brand Code: {track.brand_code}")
logger.info(f" New Directory: {track.new_brand_code_dir_path}")
if (hasattr(track, "youtube_url") and track.youtube_url) or (hasattr(track, "brand_code_dir_sharing_link") and track.brand_code_dir_sharing_link):
logger.info(f"")
logger.info(f"Sharing:")
if hasattr(track, "brand_code_dir_sharing_link") and track.brand_code_dir_sharing_link:
logger.info(f" Folder Link: {track.brand_code_dir_sharing_link}")
try:
time.sleep(1) # Brief pause between clipboard operations
pyperclip.copy(track.brand_code_dir_sharing_link)
logger.info(f" (Folder link copied to clipboard)")
except Exception as e:
logger.warning(f" Failed to copy folder link to clipboard: {str(e)}")
if hasattr(track, "youtube_url") and track.youtube_url:
logger.info(f" YouTube URL: {track.youtube_url}")
try:
pyperclip.copy(track.youtube_url)
logger.info(f" (YouTube URL copied to clipboard)")
except Exception as e:
logger.warning(f" Failed to copy YouTube URL to clipboard: {str(e)}")
class TestEmailTemplateCommand(Command):
"""Command for testing the email template."""
async def execute(self, args: Dict[str, Any]) -> None:
"""
Execute the test email template command.
Args:
args: The parsed command-line arguments
"""
# Set up logging
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)
log_level = getattr(logging, args.get("log_level", "INFO").upper())
logger.setLevel(log_level)
logger.info("Testing email template functionality...")
# Create configuration
config = ProjectConfig(
log_formatter=log_formatter,
log_level=log_level,
email_template_file=args.get("email_template_file"),
)
# Create controller
controller = KaraokeController(config)
# Test email template
await controller.distribution_service._test_email_template()
class BulkProcessCommand(Command):
"""Command for bulk processing tracks."""
async def execute(self, args: Dict[str, Any]) -> None:
"""
Execute the bulk process command.
Args:
args: The parsed command-line arguments
"""
# Execute the bulk CLI
await bulk_async_main()
def get_command(args: Dict[str, Any]) -> Command:
"""
Get the appropriate command based on the arguments.
Args:
args: The parsed command-line arguments
Returns:
The command to execute
"""
if args.get("test_email_template"):
return TestEmailTemplateCommand()
elif args.get("bulk"):
return BulkProcessCommand()
else:
return ProcessCommand()
async def execute_command(args: Dict[str, Any]) -> None:
"""
Execute the appropriate command based on the arguments.
Args:
args: The parsed command-line arguments
"""
command = get_command(args)
await command.execute(args)
+287
View File
@@ -0,0 +1,287 @@
import argparse
import logging
import pkg_resources
import tempfile
import os
from typing import Dict, Any
def create_parser() -> argparse.ArgumentParser:
"""
Create the command-line argument parser.
Returns:
The argument parser
"""
parser = argparse.ArgumentParser(
description="Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video.",
formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=54),
)
# Basic information
parser.add_argument(
"args",
nargs="*",
help="[Media or playlist URL] [Artist] [Title] of song to process. 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-gen").version
parser.add_argument("-v", "--version", action="version", version=f"%(prog)s {package_version}")
# Workflow control
workflow_group = parser.add_argument_group("Workflow Control")
workflow_group.add_argument(
"--prep-only",
action="store_true",
help="Only run the preparation phase (download audio, lyrics, separate stems, create title screens). Example: --prep-only",
)
workflow_group.add_argument(
"--finalise-only",
action="store_true",
help="Only run the finalisation phase (remux, encode, organize). Must be run in a directory prepared by the prep phase. Example: --finalise-only",
)
workflow_group.add_argument(
"--bulk",
action="store_true",
help="Process multiple tracks in bulk from a CSV file. Example: --bulk",
)
workflow_group.add_argument(
"--input_csv",
help="Path to CSV file containing tracks to process when using --bulk. CSV should have columns: Artist,Title,Mixed Audio Filename,Instrumental Audio Filename,Status. Example: --input_csv=/path/to/tracks.csv",
)
workflow_group.add_argument(
"--skip-transcription",
action="store_true",
help="Skip automatic lyrics transcription/synchronization. Use this to fall back to manual syncing. Example: --skip-transcription",
)
workflow_group.add_argument(
"--skip-separation",
action="store_true",
help="Skip audio separation process. Example: --skip-separation",
)
workflow_group.add_argument(
"--skip-lyrics",
action="store_true",
help="Skip fetching and processing lyrics. Example: --skip-lyrics",
)
workflow_group.add_argument(
"--lyrics-only",
action="store_true",
help="Only process lyrics, skipping audio separation and title/end screen generation. Example: --lyrics-only",
)
workflow_group.add_argument(
"--edit-lyrics",
action="store_true",
help="Edit lyrics of an existing track. This will backup existing outputs, re-run the lyrics transcription process, and update all outputs. Example: --edit-lyrics",
)
# Logging & Debugging
debug_group = parser.add_argument_group("Logging & Debugging")
debug_group.add_argument(
"--log_level",
default="info",
help="Optional: logging level, e.g. info, debug, warning (default: %(default)s). Example: --log_level=debug",
)
debug_group.add_argument(
"--dry_run",
action="store_true",
help="Optional: perform a dry run without making any changes. Example: --dry_run",
)
debug_group.add_argument(
"--render_bounding_boxes",
action="store_true",
help="Optional: render bounding boxes around text regions for debugging. Example: --render_bounding_boxes",
)
# Input/Output Configuration
io_group = parser.add_argument_group("Input/Output Configuration")
io_group.add_argument(
"--filename_pattern",
help="Required if processing a folder: Python regex pattern to extract track names from filenames. Must contain a named group 'title'. Example: --filename_pattern='(?P<index>\\d+) - (?P<title>.+).mp3'",
)
io_group.add_argument(
"--output_dir",
default=".",
help="Optional: directory to write output files (default: <current dir>). Example: --output_dir=/app/karaoke",
)
io_group.add_argument(
"--no_track_subfolders",
action="store_false",
dest="no_track_subfolders",
help="Optional: do NOT create a named subfolder for each track. Example: --no_track_subfolders",
)
io_group.add_argument(
"--lossless_output_format",
default="FLAC",
help="Optional: lossless output format for separated audio (default: FLAC). Example: --lossless_output_format=WAV",
)
io_group.add_argument(
"--output_png",
type=lambda x: (str(x).lower() == "true"),
default=True,
help="Optional: output PNG format for title and end images (default: %(default)s). Example: --output_png=False",
)
io_group.add_argument(
"--output_jpg",
type=lambda x: (str(x).lower() == "true"),
default=True,
help="Optional: output JPG format for title and end images (default: %(default)s). Example: --output_jpg=False",
)
# Audio Processing Configuration
audio_group = parser.add_argument_group("Audio Processing Configuration")
audio_group.add_argument(
"--clean_instrumental_model",
default="model_bs_roformer_ep_317_sdr_12.9755.ckpt",
help="Optional: Model for clean instrumental separation (default: %(default)s).",
)
audio_group.add_argument(
"--backing_vocals_models",
nargs="+",
default=["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"],
help="Optional: List of models for backing vocals separation (default: %(default)s).",
)
audio_group.add_argument(
"--other_stems_models",
nargs="+",
default=["htdemucs_6s.yaml"],
help="Optional: List of models for other stems separation (default: %(default)s).",
)
default_model_dir_unix = "/tmp/audio-separator-models/"
if os.name == "posix" and os.path.exists(default_model_dir_unix):
default_model_dir = default_model_dir_unix
else:
# Use tempfile to get the platform-independent temp directory
default_model_dir = os.path.join(tempfile.gettempdir(), "audio-separator-models")
audio_group.add_argument(
"--model_file_dir",
default=default_model_dir,
help="Optional: model files directory (default: %(default)s). Example: --model_file_dir=/app/models",
)
audio_group.add_argument(
"--existing_instrumental",
help="Optional: Path to an existing instrumental audio file. If provided, audio separation will be skipped.",
)
audio_group.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",
)
# Lyrics Configuration
lyrics_group = parser.add_argument_group("Lyrics Configuration")
lyrics_group.add_argument(
"--lyrics_artist",
help="Optional: Override the artist name used for lyrics search. Example: --lyrics_artist='The Beatles'",
)
lyrics_group.add_argument(
"--lyrics_title",
help="Optional: Override the song title used for lyrics search. Example: --lyrics_title='Hey Jude'",
)
lyrics_group.add_argument(
"--lyrics_file",
help="Optional: Path to a file containing lyrics to use instead of fetching from online. Example: --lyrics_file='/path/to/lyrics.txt'",
)
lyrics_group.add_argument(
"--subtitle_offset_ms",
type=int,
default=0,
help="Optional: Adjust subtitle timing by N milliseconds (+ve delays, -ve advances). Example: --subtitle_offset_ms=500",
)
lyrics_group.add_argument(
"--skip_transcription_review",
action="store_true",
help="Optional: Skip the review step after transcription. Example: --skip_transcription_review",
)
# Style Configuration
style_group = parser.add_argument_group("Style Configuration")
style_group.add_argument(
"--style_params_json",
help="Optional: Path to JSON file containing style configuration. Example: --style_params_json='/path/to/style_params.json'",
)
# Finalisation Configuration
finalise_group = parser.add_argument_group("Finalisation Configuration")
finalise_group.add_argument(
"--enable_cdg",
action="store_true",
help="Optional: Enable CDG ZIP generation during finalisation. Example: --enable_cdg",
)
finalise_group.add_argument(
"--enable_txt",
action="store_true",
help="Optional: Enable TXT ZIP generation during finalisation. Example: --enable_txt",
)
finalise_group.add_argument(
"--brand_prefix",
help="Optional: Your brand prefix to calculate the next sequential number. Example: --brand_prefix=BRAND",
)
finalise_group.add_argument(
"--organised_dir",
help="Optional: Target directory where the processed folder will be moved. Example: --organised_dir='/path/to/Tracks-Organized'",
)
finalise_group.add_argument(
"--organised_dir_rclone_root",
help="Optional: Rclone path which maps to your organised_dir. Example: --organised_dir_rclone_root='dropbox:Media/Karaoke/Tracks-Organized'",
)
finalise_group.add_argument(
"--public_share_dir",
help="Optional: Public share directory for final files. Example: --public_share_dir='/path/to/Tracks-PublicShare'",
)
finalise_group.add_argument(
"--youtube_client_secrets_file",
help="Optional: Path to youtube client secrets file. Example: --youtube_client_secrets_file='/path/to/client_secret.json'",
)
finalise_group.add_argument(
"--youtube_description_file",
help="Optional: Path to youtube description template. Example: --youtube_description_file='/path/to/description.txt'",
)
finalise_group.add_argument(
"--rclone_destination",
help="Optional: Rclone destination for public_share_dir sync. Example: --rclone_destination='googledrive:KaraokeFolder'",
)
finalise_group.add_argument(
"--discord_webhook_url",
help="Optional: Discord webhook URL for notifications. Example: --discord_webhook_url='https://discord.com/api/webhooks/...'",
)
finalise_group.add_argument(
"--email_template_file",
help="Optional: Path to email template file. Example: --email_template_file='/path/to/template.txt'",
)
finalise_group.add_argument(
"--keep-brand-code",
action="store_true",
help="Optional: Use existing brand code from current directory instead of generating new one. Example: --keep-brand-code",
)
finalise_group.add_argument(
"-y",
"--yes",
action="store_true",
help="Optional: Run in non-interactive mode, assuming yes to all prompts. Example: -y",
)
finalise_group.add_argument(
"--test_email_template",
action="store_true",
help="Optional: Test the email template functionality with fake data. Example: --test_email_template",
)
return parser
def parse_args() -> Dict[str, Any]:
"""
Parse command-line arguments.
Returns:
Dictionary of parsed arguments
"""
parser = create_parser()
args = parser.parse_args()
# Convert args to dictionary
args_dict = vars(args)
return args_dict
+273
View File
@@ -0,0 +1,273 @@
import asyncio
import logging
import os
from typing import List, Optional
from karaoke_gen.core.project import ProjectConfig
from karaoke_gen.core.track import Track
from karaoke_gen.core.exceptions import KaraokeGenError
class KaraokeController:
"""
Main controller for the karaoke generation process.
This class orchestrates the entire workflow by delegating to specialized services.
"""
def __init__(self, config: ProjectConfig):
"""
Initialize the controller with the given configuration.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger or logging.getLogger(__name__)
# Services will be imported and initialized lazily to avoid circular imports
self._audio_service = None
self._lyrics_service = None
self._media_service = None
self._video_service = None
self._distribution_service = None
@property
def audio_service(self):
"""Lazy-loaded audio service"""
if self._audio_service is None:
from karaoke_gen.services.audio import AudioService
self._audio_service = AudioService(self.config)
return self._audio_service
@property
def lyrics_service(self):
"""Lazy-loaded lyrics service"""
if self._lyrics_service is None:
from karaoke_gen.services.lyrics import LyricsService
self._lyrics_service = LyricsService(self.config)
return self._lyrics_service
@property
def media_service(self):
"""Lazy-loaded media service"""
if self._media_service is None:
from karaoke_gen.services.media import MediaService
self._media_service = MediaService(self.config)
return self._media_service
@property
def video_service(self):
"""Lazy-loaded video service"""
if self._video_service is None:
from karaoke_gen.services.video import VideoService
self._video_service = VideoService(self.config)
return self._video_service
@property
def distribution_service(self):
"""Lazy-loaded distribution service"""
if self._distribution_service is None:
from karaoke_gen.services.distribution.service import DistributionService
self._distribution_service = DistributionService(self.config)
return self._distribution_service
async def process_track(self, track: Track) -> Track:
"""
Process a single track through the entire workflow.
Args:
track: The track to process
Returns:
The processed track with updated information
"""
self.logger.info(f"Processing track: {track.base_name}")
try:
# Setup output directory
track = await self._setup_output_directory(track)
# Media acquisition and preparation
if track.is_url:
track = await self.media_service.download_media(track)
elif track.is_file:
track = await self.media_service.process_media(track)
# Skip further processing if we're only doing lyrics
if self.config.lyrics_only:
track = await self.lyrics_service.process_lyrics(track)
return track
# Audio processing (if not skipped)
if not self.config.skip_separation:
track = await self.audio_service.separate_audio(track)
# Lyrics processing (if not skipped)
if not self.config.skip_lyrics:
track = await self.lyrics_service.process_lyrics(track)
# Video generation
track = await self.video_service.process_video(track)
# Distribution (if not prep_only)
if not self.config.prep_only:
track = await self.distribution_service.distribute(track)
self.logger.info(f"Successfully processed track: {track.base_name}")
return track
except KaraokeGenError as e:
self.logger.error(f"Error processing track {track.base_name}: {str(e)}")
raise
async def _setup_output_directory(self, track: Track) -> Track:
"""
Set up the output directory for the track.
Args:
track: The track to set up the output directory for
Returns:
The track with updated output directory information
"""
if self.config.create_track_subfolders and track.artist and track.title:
# Create a subfolder for the track
track_dir_name = f"{track.artist} - {track.title}"
track_dir_name = self._sanitize_filename(track_dir_name)
track_output_dir = os.path.join(self.config.output_dir, track_dir_name)
# Create the directory if it doesn't exist
if not os.path.exists(track_output_dir) and not self.config.dry_run:
os.makedirs(track_output_dir, exist_ok=True)
self.logger.info(f"Created output directory: {track_output_dir}")
else:
# Use the output directory directly
track_output_dir = self.config.output_dir
track.track_output_dir = track_output_dir
return track
def _sanitize_filename(self, filename: str) -> str:
"""
Sanitize a filename by removing invalid characters.
Args:
filename: The filename to sanitize
Returns:
The sanitized filename
"""
# Replace characters that are invalid in filenames
invalid_chars = ['<', '>', ':', '"', '/', '\\', '|', '?', '*']
for char in invalid_chars:
filename = filename.replace(char, '_')
return filename
async def process_tracks(self, tracks: List[Track] = None) -> List[Track]:
"""
Process multiple tracks.
Args:
tracks: List of tracks to process. If None, a track will be created from the config.
Returns:
List of processed tracks
"""
if tracks is None:
# Create a track from the configuration
track = Track(
artist=self.config.artist,
title=self.config.title,
input_media=self.config.input_media
)
tracks = [track]
processed_tracks = []
for track in tracks:
processed_track = await self.process_track(track)
processed_tracks.append(processed_track)
return processed_tracks
async def process(self) -> List[Track]:
"""
Process tracks based on the configuration.
This is the main entry point for the controller.
Returns:
List of processed tracks
"""
# Handle edit lyrics mode
if self.config.edit_lyrics:
return await self._handle_edit_lyrics_mode()
# Handle finalise only mode
if self.config.finalise_only:
return await self._handle_finalise_only_mode()
# Normal processing
return await self.process_tracks()
async def _handle_edit_lyrics_mode(self) -> List[Track]:
"""
Handle edit lyrics mode.
Returns:
List of processed tracks
"""
self.logger.info("Running in edit-lyrics mode...")
# Get the current directory name to extract artist and title
current_dir = os.path.basename(os.getcwd())
self.logger.info(f"Current directory: {current_dir}")
# Extract artist and title from directory name
if " - " not in current_dir:
raise ValueError("Current directory name does not contain ' - ' separator. Cannot extract artist and title.")
parts = current_dir.split(" - ")
if len(parts) == 2:
artist, title = parts
elif len(parts) >= 3:
# Handle brand code format: "BRAND-XXXX - Artist - Title"
artist = parts[1]
title = " - ".join(parts[2:])
else:
raise ValueError(f"Could not parse artist and title from directory name: {current_dir}")
self.logger.info(f"Extracted artist: {artist}, title: {title}")
# Create a track
track = Track(
artist=artist,
title=title,
track_output_dir=os.getcwd()
)
# Backup existing outputs and get the input audio file
track = await self.lyrics_service.backup_and_prepare_for_edit(track)
# Process lyrics
track = await self.lyrics_service.process_lyrics(track)
# Distribute
track = await self.distribution_service.distribute(track, replace_existing=True)
return [track]
async def _handle_finalise_only_mode(self) -> List[Track]:
"""
Handle finalise only mode.
Returns:
List of processed tracks
"""
self.logger.info("Running in finalise-only mode...")
# Create a track with the current directory
track = Track(track_output_dir=os.getcwd())
# Distribute
track = await self.distribution_service.distribute(track)
return [track]
+11
View File
@@ -0,0 +1,11 @@
"""
Core module for the karaoke_gen package.
This module contains the core domain models and exceptions.
"""
from karaoke_gen.core.project import ProjectConfig
from karaoke_gen.core.track import Track
from karaoke_gen.core.exceptions import KaraokeGenError
__all__ = ["ProjectConfig", "Track", "KaraokeGenError"]
+83
View File
@@ -0,0 +1,83 @@
class KaraokeGenError(Exception):
"""Base exception for all karaoke generator errors"""
pass
class MediaError(KaraokeGenError):
"""Exception raised for errors related to media handling"""
pass
class DownloadError(MediaError):
"""Exception raised when a download fails"""
pass
class ConversionError(MediaError):
"""Exception raised when a media conversion fails"""
pass
class LyricsError(KaraokeGenError):
"""Exception raised for errors related to lyrics processing"""
pass
class LyricsFetchError(LyricsError):
"""Exception raised when lyrics fetching fails"""
pass
class TranscriptionError(LyricsError):
"""Exception raised when lyrics transcription fails"""
pass
class SynchronizationError(LyricsError):
"""Exception raised when lyrics synchronization fails"""
pass
class FormattingError(LyricsError):
"""Exception raised when lyrics formatting fails"""
pass
class AudioError(KaraokeGenError):
"""Exception raised for errors related to audio processing"""
pass
class SeparationError(AudioError):
"""Exception raised when audio separation fails"""
pass
class NormalizationError(AudioError):
"""Exception raised when audio normalization fails"""
pass
class VideoError(KaraokeGenError):
"""Exception raised for errors related to video processing"""
pass
class RenderingError(VideoError):
"""Exception raised when video rendering fails"""
pass
class DistributionError(KaraokeGenError):
"""Exception raised for errors related to distribution"""
pass
class YouTubeError(DistributionError):
"""Exception raised when YouTube operations fail"""
pass
class UserCancellationError(KaraokeGenError):
"""Exception raised when the user cancels an operation"""
pass
+107
View File
@@ -0,0 +1,107 @@
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Any
import logging
import os
import tempfile
@dataclass
class ProjectConfig:
"""
Configuration for a karaoke generation project.
This class holds all the configuration parameters for the karaoke generation process.
"""
# Basic inputs
input_media: Optional[str] = None
artist: Optional[str] = None
title: Optional[str] = None
filename_pattern: Optional[str] = None
# Workflow control
prep_only: bool = False
finalise_only: bool = False
skip_transcription: bool = False
skip_separation: bool = False
skip_lyrics: bool = False
skip_download: bool = False
lyrics_only: bool = False
edit_lyrics: bool = False
# Logging & Debugging
dry_run: bool = False
logger: Optional[logging.Logger] = None
log_level: int = logging.DEBUG
log_formatter: Optional[logging.Formatter] = None
render_bounding_boxes: bool = False
# Input/Output Configuration
output_dir: str = "."
create_track_subfolders: bool = True
lossless_output_format: str = "flac"
output_png: bool = True
output_jpg: bool = True
# Audio Processing Configuration
clean_instrumental_model: str = "model_bs_roformer_ep_317_sdr_12.9755.ckpt"
backing_vocals_models: List[str] = field(default_factory=lambda: ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"])
other_stems_models: List[str] = field(default_factory=lambda: ["htdemucs_6s.yaml"])
model_file_dir: str = field(default_factory=lambda: os.path.join(tempfile.gettempdir(), "audio-separator-models"))
existing_instrumental: Optional[str] = None
instrumental_format: str = "flac"
# Lyrics Configuration
lyrics_artist: Optional[str] = None
lyrics_title: Optional[str] = None
lyrics_file: Optional[str] = None
skip_transcription_review: bool = False
render_video: bool = True
subtitle_offset_ms: int = 0
# Style Configuration
style_params_json: Optional[str] = None
# Video Configuration
title_screen_duration: float = 5.0
end_screen_duration: float = 5.0
title_fade_in: float = 1.0
title_fade_out: float = 1.0
end_fade_in: float = 1.0
end_fade_out: float = 1.0
# Finalisation Configuration
enable_cdg: bool = False
enable_txt: bool = False
brand_prefix: Optional[str] = None
organised_dir: Optional[str] = None
organised_dir_rclone_root: Optional[str] = None
public_share_dir: Optional[str] = None
youtube_client_secrets_file: Optional[str] = None
youtube_description_file: Optional[str] = None
rclone_destination: Optional[str] = None
discord_webhook_url: Optional[str] = None
email_template_file: Optional[str] = None
cdg_styles: Optional[Dict[str, Any]] = None
keep_brand_code: bool = False
non_interactive: bool = False
def __post_init__(self):
"""Perform post-initialization setup"""
# Set up logger if not provided
if self.logger is None:
self.logger = logging.getLogger("karaoke_gen")
handler = logging.StreamHandler()
if self.log_formatter is None:
self.log_formatter = logging.Formatter(
fmt="%(asctime)s.%(msecs)03d - %(levelname)s - %(module)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
)
handler.setFormatter(self.log_formatter)
self.logger.addHandler(handler)
self.logger.setLevel(self.log_level)
# If lyrics_artist/title not specified, use the main artist/title
if self.lyrics_artist is None and self.artist is not None:
self.lyrics_artist = self.artist
if self.lyrics_title is None and self.title is not None:
self.lyrics_title = self.title
+116
View File
@@ -0,0 +1,116 @@
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Any
import os
@dataclass
class Track:
"""
Represents a track being processed through the karaoke generation pipeline.
This class holds all the data related to a single track throughout its lifecycle.
"""
# Basic track information
artist: Optional[str] = None
title: Optional[str] = None
input_media: Optional[str] = None
# Media source information
extractor: Optional[str] = "Original" # Default to "Original" for local files
media_id: Optional[str] = None
# Paths to generated files
track_output_dir: Optional[str] = None
input_audio_wav: Optional[str] = None
input_still_image: Optional[str] = None
# Lyrics information
lyrics: Optional[str] = None
processed_lyrics: Optional[str] = None
# Separated audio files
separated_audio: Dict[str, Any] = field(default_factory=lambda: {
"clean_instrumental": {},
"other_stems": {},
"backing_vocals": {},
"combined_instrumentals": {}
})
# Video files
title_video: Optional[str] = None
end_video: Optional[str] = None
video_with_lyrics: Optional[str] = None
video_with_instrumental: Optional[str] = None
# Final output files
final_video: Optional[str] = None
final_video_mkv: Optional[str] = None
final_video_lossy: Optional[str] = None
final_video_720p: Optional[str] = None
final_karaoke_cdg_zip: Optional[str] = None
final_karaoke_txt_zip: Optional[str] = None
# Distribution information
brand_code: Optional[str] = None
new_brand_code_dir_path: Optional[str] = None
youtube_url: Optional[str] = None
brand_code_dir_sharing_link: Optional[str] = None
# Metadata
metadata: Dict[str, Any] = field(default_factory=dict)
@property
def base_name(self) -> str:
"""Returns the base name for the track (artist - title)"""
if self.artist and self.title:
return f"{self.artist} - {self.title}"
return os.path.basename(self.input_media) if self.input_media else "unknown"
@property
def is_url(self) -> bool:
"""Returns True if the input_media is a URL"""
if not self.input_media:
return False
return self.input_media.startswith("http://") or self.input_media.startswith("https://")
@property
def is_file(self) -> bool:
"""Returns True if the input_media is a file"""
if not self.input_media:
return False
return os.path.isfile(self.input_media)
@property
def is_directory(self) -> bool:
"""Returns True if the input_media is a directory"""
if not self.input_media:
return False
return os.path.isdir(self.input_media)
@property
def instrumental(self) -> Optional[str]:
"""Returns the path to the instrumental audio file"""
if self.separated_audio and "clean_instrumental" in self.separated_audio:
return self.separated_audio["clean_instrumental"].get("instrumental")
return None
@property
def duration(self) -> float:
"""Returns the duration of the track in seconds"""
if self.metadata and "duration" in self.metadata:
return self.metadata["duration"]
return 0.0
@property
def audio_file(self) -> Optional[str]:
"""Returns the path to the input audio file (WAV)"""
return self.input_audio_wav
@property
def wav_file(self) -> Optional[str]:
"""Alias for input_audio_wav"""
return self.input_audio_wav
@property
def video_with_vocals(self) -> Optional[str]:
"""Alias for video_with_lyrics for backward compatibility"""
return self.video_with_lyrics
File renamed without changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+24
View File
@@ -0,0 +1,24 @@
"""
Services module for the karaoke_gen package.
This module contains the various services used by the karaoke generator.
"""
# Import and re-export service modules
from karaoke_gen.services.audio import AudioService
from karaoke_gen.services.lyrics import LyricsService
from karaoke_gen.services.media import MediaService
from karaoke_gen.services.video import VideoService
from karaoke_gen.services.distribution import DistributionService
# Import main service
from karaoke_gen.services.main import MainService
__all__ = [
"MainService",
"AudioService",
"LyricsService",
"MediaService",
"VideoService",
"DistributionService",
]
+5
View File
@@ -0,0 +1,5 @@
from karaoke_gen.services.audio.service import AudioService
from karaoke_gen.services.audio.converter import AudioConverter
from karaoke_gen.services.audio.separator import AudioSeparator
from karaoke_gen.services.audio.normalizer import AudioNormalizer
from karaoke_gen.services.audio.mixer import AudioMixer
+91
View File
@@ -0,0 +1,91 @@
import os
import subprocess
import asyncio
from karaoke_gen.core.track import Track
from karaoke_gen.core.exceptions import AudioError
class AudioConverter:
"""
Handles audio format conversion operations.
"""
def __init__(self, config):
"""
Initialize the audio converter.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger
# Path to ffmpeg
self.ffmpeg_path = "ffmpeg"
# Set up ffmpeg base command
self.ffmpeg_base_command = f"{self.ffmpeg_path} -hide_banner -nostats"
if self.config.log_level <= 10: # DEBUG
self.ffmpeg_base_command += " -loglevel verbose"
else:
self.ffmpeg_base_command += " -loglevel fatal"
async def convert_to_wav(self, track):
"""
Convert the input audio to WAV format.
Args:
track: The track to process
Returns:
The track with updated audio information
"""
self.logger.info(f"Converting audio to WAV for {track.base_name}")
# Determine input file
input_file = track.input_media
if not os.path.isfile(input_file):
raise AudioError(f"Input file not found: {input_file}")
# Determine output file
output_filename_no_extension = os.path.join(
track.track_output_dir,
f"{track.base_name}"
)
output_wav = f"{output_filename_no_extension}.wav"
# Skip if output already exists
if os.path.isfile(output_wav):
self.logger.info(f"WAV file already exists: {output_wav}")
track.input_audio_wav = output_wav
return track
# Build ffmpeg command
command = f'{self.ffmpeg_base_command} -i "{input_file}" -vn -acodec pcm_s16le -ar 44100 -ac 2 "{output_wav}"'
# Execute command
if not self.config.dry_run:
self.logger.debug(f"Executing command: {command}")
try:
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_message = stderr.decode() if stderr else "Unknown error"
raise AudioError(f"Failed to convert audio to WAV: {error_message}")
self.logger.info(f"Successfully converted audio to WAV: {output_wav}")
track.input_audio_wav = output_wav
except Exception as e:
raise AudioError(f"Failed to convert audio to WAV: {str(e)}") from e
else:
self.logger.info(f"[DRY RUN] Would convert audio to WAV: {output_wav}")
track.input_audio_wav = output_wav
return track
+283
View File
@@ -0,0 +1,283 @@
import os
import asyncio
import subprocess
from typing import List, Optional
from pydub import AudioSegment
from karaoke_gen.core.track import Track
from karaoke_gen.core.exceptions import AudioError
class AudioMixer:
"""
Handles audio mixing operations.
"""
def __init__(self, config):
"""
Initialize the audio mixer.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger
# Set up ffmpeg base command
self.ffmpeg_base_command = "ffmpeg -hide_banner"
if self.config.log_level <= 10: # DEBUG
self.ffmpeg_base_command += " -loglevel verbose"
else:
self.ffmpeg_base_command += " -loglevel fatal"
async def mix_audio_files(self, input_files: List[str], output_file: str, weights: Optional[List[float]] = None):
"""
Mix multiple audio files into a single output file.
Args:
input_files: List of input audio file paths
output_file: Output file path
weights: Optional list of weights for each input file (default: equal weights)
Returns:
The path to the mixed audio file
"""
self.logger.info(f"Mixing {len(input_files)} audio files into {output_file}")
# Validate inputs
if not input_files:
raise AudioError("No input files provided for mixing")
for input_file in input_files:
if not os.path.isfile(input_file):
raise AudioError(f"Input file not found: {input_file}")
# Set default weights if not provided
if weights is None:
weights = [1.0] * len(input_files)
# Ensure weights match input files
if len(weights) != len(input_files):
raise AudioError(f"Number of weights ({len(weights)}) does not match number of input files ({len(input_files)})")
# Build ffmpeg command
input_args = " ".join([f'-i "{input_file}"' for input_file in input_files])
weight_str = " ".join([str(w) for w in weights])
filter_complex = f'"'
for i in range(len(input_files)):
filter_complex += f"[{i}:a]"
filter_complex += f"amix=inputs={len(input_files)}:duration=longest:weights={weight_str}[outa]"
filter_complex += f'"'
output_format = os.path.splitext(output_file)[1][1:].lower()
if not output_format:
output_format = self.config.lossless_output_format.lower()
ffmpeg_command = (
f'{self.ffmpeg_base_command} {input_args} '
f'-filter_complex {filter_complex} '
f'-map "[outa]" -c:a {output_format} "{output_file}"'
)
# Execute command
if not self.config.dry_run:
self.logger.debug(f"Running command: {ffmpeg_command}")
try:
process = await asyncio.create_subprocess_shell(
ffmpeg_command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_message = stderr.decode() if stderr else "Unknown error"
raise AudioError(f"Failed to mix audio files: {error_message}")
self.logger.info(f"Successfully mixed audio files to {output_file}")
return output_file
except Exception as e:
raise AudioError(f"Error mixing audio files: {str(e)}") from e
else:
self.logger.info(f"[DRY RUN] Would mix audio files to {output_file}")
return output_file
async def mix_audio(self, track):
"""
Mix audio for a track.
Args:
track: The track to process
Returns:
The track with updated mixed audio information
"""
self.logger.info(f"Mixing audio for {track.base_name}")
# Skip if no separated audio
if not track.separated_audio["clean_instrumental"].get("instrumental"):
self.logger.info("No instrumental available for mixing, skipping")
return track
# Mix instrumental with backing vocals if available
if track.separated_audio["backing_vocals"]:
for model, paths in track.separated_audio["backing_vocals"].items():
if "backing_vocals" not in paths:
continue
instrumental_path = track.separated_audio["clean_instrumental"]["instrumental"]
backing_vocals_path = paths["backing_vocals"]
output_path = os.path.join(
track.track_output_dir,
f"{track.base_name} (Karaoke Mix {model}).{self.config.lossless_output_format.lower()}"
)
# Skip if output already exists
if os.path.isfile(output_path):
self.logger.info(f"Mixed audio for model {model} already exists")
track.metadata[f"karaoke_mix_{model}"] = output_path
continue
# Mix files
try:
mixed_path = await self.mix_audio_files(
[instrumental_path, backing_vocals_path],
output_path,
weights=[1.0, 0.8] # Slightly reduce backing vocals volume
)
track.metadata[f"karaoke_mix_{model}"] = mixed_path
self.logger.info(f"Created karaoke mix for model {model}")
except Exception as e:
self.logger.error(f"Failed to create karaoke mix for model {model}: {str(e)}")
return track
async def generate_combined_instrumentals(self, track, stems_dir):
"""
Generate combined instrumental tracks by mixing different stems.
Args:
track: The track to process
stems_dir: The directory containing stems
Returns:
The track with updated audio information
"""
self.logger.info(f"Generating combined instrumentals for {track.base_name}")
# Skip if no clean instrumental
if not track.separated_audio.get("clean_instrumental", {}).get("instrumental"):
self.logger.info("No clean instrumental available, skipping combined instrumentals")
track.separated_audio["combined_instrumentals"] = {}
return track
# Initialize combined instrumentals
track.separated_audio["combined_instrumentals"] = {}
# Get clean instrumental path
instrumental_path = track.separated_audio["clean_instrumental"]["instrumental"]
# Get backing vocals path if available
backing_vocals_path = None
for model_name, stems in track.separated_audio.get("backing_vocals", {}).items():
if stems.get("backing_vocals"):
backing_vocals_path = stems["backing_vocals"]
break
# Generate instrumental with backing vocals if available
if backing_vocals_path:
output_path = os.path.join(
stems_dir,
f"{track.base_name} (Instrumental with Backing Vocals).{self.config.lossless_output_format.lower()}"
)
# Skip if output already exists
if os.path.isfile(output_path):
self.logger.info(f"Instrumental with backing vocals already exists: {output_path}")
track.separated_audio["combined_instrumentals"]["instrumental_with_backing_vocals"] = output_path
else:
# Mix instrumental and backing vocals
if not self.config.dry_run:
try:
await self._mix_audio_files(
[instrumental_path, backing_vocals_path],
output_path
)
track.separated_audio["combined_instrumentals"]["instrumental_with_backing_vocals"] = output_path
except Exception as e:
self.logger.error(f"Failed to mix instrumental with backing vocals: {str(e)}")
else:
self.logger.info(f"[DRY RUN] Would mix instrumental with backing vocals: {output_path}")
track.separated_audio["combined_instrumentals"]["instrumental_with_backing_vocals"] = output_path
# Generate other combined instrumentals from demucs stems if available
demucs_stems = {}
for model_name, stems in track.separated_audio.get("other_stems", {}).items():
if "demucs" in model_name.lower():
demucs_stems = stems
break
if demucs_stems:
# Mix drums + bass + other (no vocals)
if all(stem in demucs_stems for stem in ["drums", "bass", "other"]):
output_path = os.path.join(
stems_dir,
f"{track.base_name} (Demucs Instrumental).{self.config.lossless_output_format.lower()}"
)
# Skip if output already exists
if os.path.isfile(output_path):
self.logger.info(f"Demucs instrumental already exists: {output_path}")
track.separated_audio["combined_instrumentals"]["demucs_instrumental"] = output_path
else:
# Mix drums, bass, and other
if not self.config.dry_run:
try:
await self._mix_audio_files(
[demucs_stems["drums"], demucs_stems["bass"], demucs_stems["other"]],
output_path
)
track.separated_audio["combined_instrumentals"]["demucs_instrumental"] = output_path
except Exception as e:
self.logger.error(f"Failed to mix demucs instrumental: {str(e)}")
else:
self.logger.info(f"[DRY RUN] Would mix demucs instrumental: {output_path}")
track.separated_audio["combined_instrumentals"]["demucs_instrumental"] = output_path
return track
async def _mix_audio_files(self, input_paths, output_path):
"""
Mix multiple audio files together.
Args:
input_paths: List of input audio file paths
output_path: Output audio file path
Returns:
True if successful, False otherwise
"""
try:
# Load first audio file
mixed = AudioSegment.from_file(input_paths[0])
# Mix in additional audio files
for path in input_paths[1:]:
audio = AudioSegment.from_file(path)
mixed = mixed.overlay(audio)
# Export mixed audio
mixed.export(output_path, format=os.path.splitext(output_path)[1][1:])
self.logger.info(f"Successfully mixed audio files: {output_path}")
return True
except Exception as e:
self.logger.error(f"Failed to mix audio files: {str(e)}")
raise AudioError(f"Failed to mix audio files: {str(e)}") from e
+308
View File
@@ -0,0 +1,308 @@
import os
import asyncio
import subprocess
from pydub import AudioSegment
from karaoke_gen.core.track import Track
from karaoke_gen.core.exceptions import AudioError
class AudioNormalizer:
"""
Handles audio normalization operations.
"""
def __init__(self, config):
"""
Initialize the audio normalizer.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger
# Path to ffmpeg
self.ffmpeg_path = "ffmpeg"
# Set up ffmpeg base command
self.ffmpeg_base_command = f"{self.ffmpeg_path} -hide_banner -nostats"
if self.config.log_level <= 10: # DEBUG
self.ffmpeg_base_command += " -loglevel verbose"
else:
self.ffmpeg_base_command += " -loglevel fatal"
async def normalize_audio_file(self, input_path, output_path, target_level=0.0):
"""
Normalize an audio file to a target level.
Args:
input_path: The input audio file path
output_path: The output audio file path
target_level: The target level in dB (default: 0.0)
Returns:
The path to the normalized audio file
"""
self.logger.info(f"Normalizing audio file: {input_path}")
# Validate input
if not os.path.isfile(input_path):
raise AudioError(f"Input file not found: {input_path}")
if os.path.getsize(input_path) == 0:
raise AudioError(f"Input file is empty: {input_path}")
# Skip if dry run
if self.config.dry_run:
self.logger.info(f"[DRY RUN] Would normalize audio file: {input_path}")
return output_path
try:
# Load audio file
audio = AudioSegment.from_file(input_path)
# Calculate the peak amplitude
peak_amplitude = float(audio.max_dBFS)
# Calculate the necessary gain
gain_db = target_level - peak_amplitude
# Apply gain
normalized_audio = audio.apply_gain(gain_db)
# Ensure the audio is not completely silent
if normalized_audio.rms == 0:
self.logger.warning(f"Normalized audio is silent for {input_path}. Using original audio.")
normalized_audio = audio
# Export normalized audio
normalized_audio.export(
output_path,
format=self.config.lossless_output_format.lower()
)
self.logger.info(f"Normalized audio saved to: {output_path}")
self.logger.debug(f"Original peak: {peak_amplitude} dB, Applied gain: {gain_db} dB")
return output_path
except Exception as e:
raise AudioError(f"Failed to normalize audio file: {str(e)}") from e
async def normalize_audio(self, track):
"""
Normalize audio for a track.
Args:
track: The track to process
Returns:
The track with normalized audio
"""
self.logger.info(f"Normalizing audio for {track.base_name}")
files_to_normalize = []
# Add clean instrumental
if track.separated_audio["clean_instrumental"].get("instrumental"):
files_to_normalize.append(
("clean_instrumental", track.separated_audio["clean_instrumental"]["instrumental"])
)
# Add combined instrumentals
for model, path in track.separated_audio["combined_instrumentals"].items():
files_to_normalize.append(("combined_instrumentals", path))
# Add karaoke mixes
for key, path in track.metadata.items():
if key.startswith("karaoke_mix_") and os.path.isfile(path):
files_to_normalize.append(("karaoke_mix", path))
# Skip if no files to normalize
if not files_to_normalize:
self.logger.info("No files to normalize, skipping")
return track
# Normalize each file
for key, file_path in files_to_normalize:
if os.path.isfile(file_path):
try:
# Normalize in-place
await self.normalize_audio_file(file_path, file_path)
# Verify the normalized file
if os.path.getsize(file_path) > 0:
self.logger.info(f"Successfully normalized: {file_path}")
else:
raise AudioError("Normalized file is empty")
except Exception as e:
self.logger.error(f"Error during normalization of {file_path}: {e}")
self.logger.warning(f"Normalization failed for {file_path}. Original file remains unchanged.")
else:
self.logger.warning(f"File not found for normalization: {file_path}")
self.logger.info("Audio normalization process completed")
return track
async def normalize_audio_files(self, track):
"""
Normalize all separated audio files.
Args:
track: The track to process
Returns:
The track with updated audio information
"""
self.logger.info(f"Normalizing audio files for {track.base_name}")
# Skip if no separated audio
if not track.separated_audio:
self.logger.info("No separated audio to normalize")
return track
# Normalize clean instrumental
if track.separated_audio.get("clean_instrumental"):
instrumental_path = track.separated_audio["clean_instrumental"].get("instrumental")
if instrumental_path and os.path.isfile(instrumental_path):
normalized_path = self._get_normalized_path(instrumental_path)
await self._normalize_audio(instrumental_path, normalized_path)
track.separated_audio["clean_instrumental"]["instrumental"] = normalized_path
vocals_path = track.separated_audio["clean_instrumental"].get("vocals")
if vocals_path and os.path.isfile(vocals_path):
normalized_path = self._get_normalized_path(vocals_path)
await self._normalize_audio(vocals_path, normalized_path)
track.separated_audio["clean_instrumental"]["vocals"] = normalized_path
# Normalize backing vocals
for model_name, stems in track.separated_audio.get("backing_vocals", {}).items():
lead_vocals_path = stems.get("lead_vocals")
if lead_vocals_path and os.path.isfile(lead_vocals_path):
normalized_path = self._get_normalized_path(lead_vocals_path)
await self._normalize_audio(lead_vocals_path, normalized_path)
track.separated_audio["backing_vocals"][model_name]["lead_vocals"] = normalized_path
backing_vocals_path = stems.get("backing_vocals")
if backing_vocals_path and os.path.isfile(backing_vocals_path):
normalized_path = self._get_normalized_path(backing_vocals_path)
await self._normalize_audio(backing_vocals_path, normalized_path)
track.separated_audio["backing_vocals"][model_name]["backing_vocals"] = normalized_path
# Normalize other stems
for model_name, stems in track.separated_audio.get("other_stems", {}).items():
for stem_name, stem_path in stems.items():
if stem_path and os.path.isfile(stem_path):
normalized_path = self._get_normalized_path(stem_path)
await self._normalize_audio(stem_path, normalized_path)
track.separated_audio["other_stems"][model_name][stem_name] = normalized_path
# Normalize combined instrumentals
for name, path in track.separated_audio.get("combined_instrumentals", {}).items():
if path and os.path.isfile(path):
normalized_path = self._get_normalized_path(path)
await self._normalize_audio(path, normalized_path)
track.separated_audio["combined_instrumentals"][name] = normalized_path
return track
def _get_normalized_path(self, input_path):
"""
Get the path for the normalized audio file.
Args:
input_path: The input audio file path
Returns:
The path for the normalized audio file
"""
# Replace extension with .normalized.ext
base, ext = os.path.splitext(input_path)
return f"{base}.normalized{ext}"
async def _normalize_audio(self, input_path, output_path, target_level=-14.0):
"""
Normalize an audio file to a target loudness level.
Args:
input_path: The input audio file path
output_path: The output audio file path
target_level: The target loudness level in LUFS
Returns:
True if successful, False otherwise
"""
# Skip if output already exists
if os.path.isfile(output_path):
self.logger.debug(f"Normalized audio already exists: {output_path}")
return True
# Skip if input doesn't exist
if not os.path.isfile(input_path):
self.logger.warning(f"Input audio file not found: {input_path}")
return False
# Build ffmpeg command
command = (
f'{self.ffmpeg_base_command} -i "{input_path}" '
f'-af loudnorm=I={target_level}:TP=-1.0:LRA=11.0:print_format=json '
f'-f null -'
)
# Execute command to get loudness stats
if not self.config.dry_run:
try:
self.logger.debug(f"Analyzing audio loudness: {command}")
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
self.logger.error(f"Failed to analyze audio loudness: {stderr.decode()}")
return False
# Extract loudnorm stats from stderr
stderr_text = stderr.decode()
stats_start = stderr_text.rfind("{")
stats_end = stderr_text.rfind("}") + 1
if stats_start >= 0 and stats_end > stats_start:
loudness_stats = stderr_text[stats_start:stats_end]
# Build second pass command with measured stats
command = (
f'{self.ffmpeg_base_command} -i "{input_path}" '
f'-af loudnorm=I={target_level}:TP=-1.0:LRA=11.0:measured_I={target_level}:measured_TP=-1.0:measured_LRA=11.0:measured_thresh=-25.0:offset=0.0:linear=true:print_format=json '
f'"{output_path}"'
)
# Execute second pass command
self.logger.debug(f"Normalizing audio: {command}")
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
self.logger.error(f"Failed to normalize audio: {stderr.decode()}")
return False
self.logger.info(f"Successfully normalized audio: {output_path}")
return True
else:
self.logger.error("Failed to extract loudness stats from ffmpeg output")
return False
except Exception as e:
self.logger.error(f"Failed to normalize audio: {str(e)}")
return False
else:
self.logger.info(f"[DRY RUN] Would normalize audio: {output_path}")
return True
+724
View File
@@ -0,0 +1,724 @@
import os
import asyncio
import json
import time
import fcntl
import errno
import tempfile
import shutil
from datetime import datetime
from karaoke_gen.core.track import Track
from karaoke_gen.core.exceptions import AudioError
import platform
import subprocess
import logging
from typing import Dict, List, Optional, Any
import re
class AudioSeparator:
"""
Handles audio stem separation operations.
"""
def __init__(self, config):
"""
Initialize the audio separator.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger
# Initialize separator lazily to avoid circular imports
self._separator = None
@property
def separator(self):
"""Lazy-loaded separator instance"""
if self._separator is None:
# Import here to avoid circular imports
from audio_separator.separator import Separator
self._separator = Separator(
log_level=self.config.log_level,
log_formatter=self.config.log_formatter,
model_file_dir=self.config.model_file_dir,
output_format=self.config.lossless_output_format,
)
return self._separator
async def separate_clean_instrumental(self, track, input_audio, stems_dir):
"""
Separate clean instrumental from a track.
Args:
track: The track to process
input_audio: The input audio file
stems_dir: The directory to store stems
Returns:
The track with updated audio information
"""
self.logger.info(f"Separating clean instrumental for {track.base_name}")
# Skip if existing instrumental is provided
if self.config.existing_instrumental:
self.logger.info(f"Using existing instrumental: {self.config.existing_instrumental}")
track.separated_audio["clean_instrumental"] = {
"instrumental": self.config.existing_instrumental,
"vocals": None
}
return track
# Acquire lock for audio separation
with self._acquire_lock(track.base_name):
artist_title = track.base_name
# Define output paths
instrumental_path = os.path.join(
stems_dir,
f"{artist_title} (Clean Instrumental).{self.config.lossless_output_format.lower()}"
)
vocals_path = os.path.join(
stems_dir,
f"{artist_title} (Clean Vocals).{self.config.lossless_output_format.lower()}"
)
# Skip if output already exists
if os.path.isfile(instrumental_path) and os.path.isfile(vocals_path):
self.logger.info(f"Clean instrumental and vocals already exist")
track.separated_audio["clean_instrumental"] = {
"instrumental": instrumental_path,
"vocals": vocals_path
}
return track
# Perform separation
if not self.config.dry_run:
try:
self.logger.info(f"Separating clean instrumental using model: {self.config.clean_instrumental_model}")
# Load model first
self.separator.load_model(model_filename=self.config.clean_instrumental_model)
# Convert input_audio to absolute path
input_audio_abs = os.path.abspath(input_audio)
# Call separate with the absolute path to the audio file
output_files = self.separator.separate(input_audio_abs)
# Process the output files
result = {}
for file in output_files:
# The file path returned by separator.separate()
# may already be the full path or just the filename
file_name = os.path.basename(file)
file_path = file # Use the path as returned by separator
if "(Vocals)" in file_name:
if os.path.exists(file_path) and not os.path.exists(vocals_path):
shutil.move(file_path, vocals_path)
result["vocals"] = vocals_path
elif "(Instrumental)" in file_name:
if os.path.exists(file_path) and not os.path.exists(instrumental_path):
shutil.move(file_path, instrumental_path)
result["instrumental"] = instrumental_path
# Update track with separation results
track.separated_audio["clean_instrumental"] = result
self.logger.info(f"Successfully separated clean instrumental")
except Exception as e:
raise AudioError(f"Failed to separate clean instrumental: {str(e)}") from e
else:
self.logger.info(f"[DRY RUN] Would separate clean instrumental")
track.separated_audio["clean_instrumental"] = {
"instrumental": instrumental_path,
"vocals": vocals_path
}
return track
async def separate_other_stems(self, track, input_audio, stems_dir):
"""
Separate other stems from the input audio.
Args:
track: The track to process
input_audio: The input audio file
stems_dir: The directory to store stems
Returns:
The track with updated audio information
"""
self.logger.info(f"Separating other stems for {track.base_name}")
# Skip if no models are specified
if not self.config.other_stems_models:
self.logger.info("No other stems models specified, skipping")
track.separated_audio["other_stems"] = {}
return track
# Acquire lock for audio separation
with self._acquire_lock(track.base_name):
artist_title = track.base_name
# Initialize results
track.separated_audio["other_stems"] = {}
# Process each model
for model_name in self.config.other_stems_models:
self.logger.info(f"Separating stems using model: {model_name}")
# Define output paths based on model
if "demucs" in model_name.lower():
stems = ["drums", "bass", "other", "vocals"]
output_paths = {
stem: os.path.join(
stems_dir,
f"{artist_title} ({stem.capitalize()} {model_name}).{self.config.lossless_output_format.lower()}"
) for stem in stems
}
else:
# Default to 2-stem separation
stems = ["instrumental", "vocals"]
output_paths = {
stem: os.path.join(
stems_dir,
f"{artist_title} ({model_name} {stem.capitalize()}).{self.config.lossless_output_format.lower()}"
) for stem in stems
}
# Check if all output files already exist
if all(os.path.isfile(path) for path in output_paths.values()):
self.logger.info(f"All stems for model {model_name} already exist")
track.separated_audio["other_stems"][model_name] = output_paths
continue
# Perform separation
if not self.config.dry_run:
try:
# Load model first
self.separator.load_model(model_filename=model_name)
# Convert input_audio to absolute path
input_audio_abs = os.path.abspath(input_audio)
# Call separate with the absolute path to the audio file
output_files = self.separator.separate(input_audio_abs)
# Process the output files
result = {}
for file in output_files:
# The file path returned by separator.separate()
# may already be the full path or just the filename
file_name = os.path.basename(file)
file_path = file
if "demucs" in model_name.lower():
# Extract stem name from demucs output
if "_(Drums)_" in file_name or "_drums." in file_name.lower():
stem_path = output_paths["drums"]
if os.path.exists(file_path) and not os.path.exists(stem_path):
shutil.move(file_path, stem_path)
result["drums"] = stem_path
elif "_(Bass)_" in file_name or "_bass." in file_name.lower():
stem_path = output_paths["bass"]
if os.path.exists(file_path) and not os.path.exists(stem_path):
shutil.move(file_path, stem_path)
result["bass"] = stem_path
elif "_(Other)_" in file_name or "_other." in file_name.lower():
stem_path = output_paths["other"]
if os.path.exists(file_path) and not os.path.exists(stem_path):
shutil.move(file_path, stem_path)
result["other"] = stem_path
elif "_(Vocals)_" in file_name or "_vocals." in file_name.lower():
stem_path = output_paths["vocals"]
if os.path.exists(file_path) and not os.path.exists(stem_path):
shutil.move(file_path, stem_path)
result["vocals"] = stem_path
elif "_(Guitar)_" in file_name:
# For additional stems like guitar and piano, add them to the other stems too
stem_name = "guitar"
stem_path = os.path.join(
stems_dir,
f"{artist_title} ({stem_name.capitalize()} {model_name}).{self.config.lossless_output_format.lower()}"
)
if os.path.exists(file_path) and not os.path.exists(stem_path):
shutil.move(file_path, stem_path)
result[stem_name] = stem_path
elif "_(Piano)_" in file_name:
stem_name = "piano"
stem_path = os.path.join(
stems_dir,
f"{artist_title} ({stem_name.capitalize()} {model_name}).{self.config.lossless_output_format.lower()}"
)
if os.path.exists(file_path) and not os.path.exists(stem_path):
shutil.move(file_path, stem_path)
result[stem_name] = stem_path
else:
# Try to extract stem name for any other stems that might be present
try:
# Extract stem name from patterns like "_(StemName)_"
stem_match = re.search(r"_\(([^)]+)\)_", file_name)
if stem_match:
stem_name = stem_match.group(1)
stem_path = os.path.join(
stems_dir,
f"{artist_title} ({stem_name} {model_name}).{self.config.lossless_output_format.lower()}"
)
if os.path.exists(file_path) and not os.path.exists(stem_path):
shutil.move(file_path, stem_path)
result[stem_name.lower()] = stem_path
except Exception as e:
self.logger.warning(f"Could not process stem file {file_name}: {e}")
else:
# Handle 2-stem models
if "(Vocals)" in file_name:
stem_path = output_paths["vocals"]
if os.path.exists(file_path) and not os.path.exists(stem_path):
shutil.move(file_path, stem_path)
result["vocals"] = stem_path
elif "(Instrumental)" in file_name:
stem_path = output_paths["instrumental"]
if os.path.exists(file_path) and not os.path.exists(stem_path):
shutil.move(file_path, stem_path)
result["instrumental"] = stem_path
# Update track with separation results
track.separated_audio["other_stems"][model_name] = result
self.logger.info(f"Successfully separated stems using model: {model_name}")
except Exception as e:
self.logger.error(f"Failed to separate stems using model {model_name}: {str(e)}")
# Continue with other models
else:
self.logger.info(f"[DRY RUN] Would separate stems using model: {model_name}")
track.separated_audio["other_stems"][model_name] = output_paths
return track
async def separate_backing_vocals(self, track, stems_dir):
"""
Separate backing vocals from the clean vocals.
Args:
track: The track to process
stems_dir: The directory to store stems
Returns:
The track with updated audio information
"""
self.logger.info(f"Separating backing vocals for {track.base_name}")
# Skip if no models are specified or no clean vocals
if not self.config.backing_vocals_models or not track.separated_audio["clean_instrumental"].get("vocals"):
self.logger.info("No backing vocals models specified or no clean vocals available, skipping")
track.separated_audio["backing_vocals"] = {}
return track
# Get vocals path
vocals_path = track.separated_audio["clean_instrumental"]["vocals"]
# Acquire lock for audio separation
with self._acquire_lock(track.base_name):
artist_title = track.base_name
# Initialize results
track.separated_audio["backing_vocals"] = {}
# Process each model
for model_name in self.config.backing_vocals_models:
self.logger.info(f"Separating backing vocals using model: {model_name}")
# Define output paths
lead_vocals_path = os.path.join(
stems_dir,
f"{artist_title} (Lead Vocals {model_name}).{self.config.lossless_output_format.lower()}"
)
backing_vocals_path = os.path.join(
stems_dir,
f"{artist_title} (Backing Vocals {model_name}).{self.config.lossless_output_format.lower()}"
)
# Check if output files already exist
if os.path.isfile(lead_vocals_path) and os.path.isfile(backing_vocals_path):
self.logger.info(f"Backing vocals for model {model_name} already exist")
track.separated_audio["backing_vocals"][model_name] = {
"lead_vocals": lead_vocals_path,
"backing_vocals": backing_vocals_path
}
continue
# Perform separation
if not self.config.dry_run:
try:
# Load model first
self.separator.load_model(model_filename=model_name)
# Convert vocals_path to absolute path
vocals_path_abs = os.path.abspath(vocals_path)
# Call separate with the absolute path to the audio file
output_files = self.separator.separate(vocals_path_abs)
# Process the output files
result = {}
for file in output_files:
# The file path returned by separator.separate()
# may already be the full path or just the filename
file_name = os.path.basename(file)
file_path = file # Use the path as returned by separator
if "(Vocals)" in file_name:
# This is the lead vocals
if os.path.exists(file_path) and not os.path.exists(lead_vocals_path):
shutil.move(file_path, lead_vocals_path)
result["lead_vocals"] = lead_vocals_path
elif "(Instrumental)" in file_name:
# This is the backing vocals
if os.path.exists(file_path) and not os.path.exists(backing_vocals_path):
shutil.move(file_path, backing_vocals_path)
result["backing_vocals"] = backing_vocals_path
# Update track with separation results
track.separated_audio["backing_vocals"][model_name] = result
self.logger.info(f"Successfully separated backing vocals using model: {model_name}")
except Exception as e:
self.logger.error(f"Failed to separate backing vocals using model {model_name}: {str(e)}")
# Continue with other models
else:
self.logger.info(f"[DRY RUN] Would separate backing vocals using model: {model_name}")
track.separated_audio["backing_vocals"][model_name] = {
"lead_vocals": lead_vocals_path,
"backing_vocals": backing_vocals_path
}
return track
async def separate_audio(self, track):
"""
Orchestrate the entire audio separation process.
Args:
track: The track to process
Returns:
The track with updated audio information
"""
self.logger.info(f"Starting audio separation process for {track.base_name}")
# Skip if requested
if self.config.skip_separation:
self.logger.info("Skipping audio separation as requested")
track.separated_audio = {
"clean_instrumental": {},
"backing_vocals": {},
"other_stems": {},
"combined_instrumentals": {}
}
return track
# Create stems directory
stems_dir = os.path.join(track.track_output_dir, "stems")
os.makedirs(stems_dir, exist_ok=True)
self.logger.info(f"Created stems directory: {stems_dir}")
# Check for existing instrumental
if self.config.existing_instrumental:
self.logger.info(f"Using existing instrumental file: {self.config.existing_instrumental}")
existing_instrumental_extension = os.path.splitext(self.config.existing_instrumental)[1]
instrumental_path = os.path.join(
track.track_output_dir,
f"{track.base_name} (Instrumental Custom){existing_instrumental_extension}"
)
if not os.path.exists(instrumental_path):
shutil.copy2(self.config.existing_instrumental, instrumental_path)
track.separated_audio["clean_instrumental"] = {
"instrumental": instrumental_path,
"vocals": None
}
return track
# Perform separation steps
try:
# Step 1: Separate clean instrumental
track = await self.separate_clean_instrumental(track, track.input_audio_wav, stems_dir)
# Step 2: Separate other stems
track = await self.separate_other_stems(track, track.input_audio_wav, stems_dir)
# Step 3: Separate backing vocals
track = await self.separate_backing_vocals(track, stems_dir)
# Step 4: Generate combined instrumentals
track = await self.generate_combined_instrumentals(track, stems_dir)
# Step 5: Normalize audio files
track = await self.normalize_audio_files(track)
self.logger.info("Audio separation process completed successfully")
return track
except Exception as e:
raise AudioError(f"Error during audio separation: {str(e)}") from e
async def generate_combined_instrumentals(self, track, stems_dir):
"""
Generate combined instrumental tracks with backing vocals.
Args:
track: The track to process
stems_dir: The directory to store stems
Returns:
The track with updated audio information
"""
self.logger.info(f"Generating combined instrumental tracks with backing vocals for {track.base_name}")
# Skip if no backing vocals or clean instrumental
if (not track.separated_audio["backing_vocals"] or
not track.separated_audio["clean_instrumental"].get("instrumental")):
self.logger.info("No backing vocals or clean instrumental available, skipping")
track.separated_audio["combined_instrumentals"] = {}
return track
instrumental_path = track.separated_audio["clean_instrumental"]["instrumental"]
track.separated_audio["combined_instrumentals"] = {}
# Process each backing vocals model
for model, paths in track.separated_audio["backing_vocals"].items():
if "backing_vocals" not in paths:
continue
backing_vocals_path = paths["backing_vocals"]
combined_path = os.path.join(
track.track_output_dir,
f"{track.base_name} (Instrumental +BV {model}).{self.config.lossless_output_format.lower()}"
)
# Skip if output already exists
if os.path.isfile(combined_path):
self.logger.info(f"Combined instrumental for model {model} already exists")
track.separated_audio["combined_instrumentals"][model] = combined_path
continue
# Perform mixing
if not self.config.dry_run:
try:
from karaoke_gen.services.audio.mixer import AudioMixer
mixer = AudioMixer(self.config)
# Mix instrumental and backing vocals
await mixer.mix_audio_files(
[instrumental_path, backing_vocals_path],
combined_path,
weights=[1, 1]
)
track.separated_audio["combined_instrumentals"][model] = combined_path
self.logger.info(f"Successfully created combined instrumental for model {model}")
except Exception as e:
self.logger.error(f"Failed to create combined instrumental for model {model}: {str(e)}")
# Continue with other models
else:
self.logger.info(f"[DRY RUN] Would create combined instrumental for model {model}")
track.separated_audio["combined_instrumentals"][model] = combined_path
return track
async def normalize_audio_files(self, track):
"""
Normalize audio levels for instrumental and combined tracks.
Args:
track: The track to process
Returns:
The track with normalized audio files
"""
self.logger.info(f"Normalizing audio files for {track.base_name}")
files_to_normalize = []
# Add clean instrumental
if track.separated_audio["clean_instrumental"].get("instrumental"):
files_to_normalize.append(
("clean_instrumental", track.separated_audio["clean_instrumental"]["instrumental"])
)
# Add combined instrumentals
for model, path in track.separated_audio["combined_instrumentals"].items():
files_to_normalize.append(("combined_instrumentals", path))
# Skip if no files to normalize
if not files_to_normalize:
self.logger.info("No files to normalize, skipping")
return track
# Normalize each file
for key, file_path in files_to_normalize:
if os.path.isfile(file_path):
try:
from karaoke_gen.services.audio.normalizer import AudioNormalizer
normalizer = AudioNormalizer(self.config)
# Normalize in-place
await normalizer.normalize_audio_file(file_path, file_path)
# Verify the normalized file
if os.path.getsize(file_path) > 0:
self.logger.info(f"Successfully normalized: {file_path}")
else:
raise AudioError("Normalized file is empty")
except Exception as e:
self.logger.error(f"Error during normalization of {file_path}: {e}")
self.logger.warning(f"Normalization failed for {file_path}. Original file remains unchanged.")
else:
self.logger.warning(f"File not found for normalization: {file_path}")
self.logger.info("Audio normalization process completed")
return track
async def cleanup(self):
"""
Perform cleanup operations for the audio separator.
"""
self.logger.info("Cleaning up audio separator resources")
# Release any locks
for lock in self._locks.values():
if lock.locked():
lock.release()
# Close any open resources
if hasattr(self, 'demucs_model') and self.demucs_model:
# Clean up demucs model resources if needed
pass
if hasattr(self, 'spleeter_model') and self.spleeter_model:
# Clean up spleeter model resources if needed
pass
self.logger.info("Audio separator cleanup complete")
def _acquire_lock(self, track_name):
"""
Acquire a lock for audio separation.
Args:
track_name: The name of the track being processed
Returns:
A context manager for the lock
"""
class LockContextManager:
def __init__(self, separator, track_name):
self.separator = separator
self.track_name = track_name
self.lock_file = None
self.lock_file_path = os.path.join(tempfile.gettempdir(), "audio_separator.lock")
def __enter__(self):
# Try to acquire lock
while True:
try:
# First check if there's a stale lock
if os.path.exists(self.lock_file_path):
try:
with open(self.lock_file_path, "r") as f:
lock_data = json.load(f)
pid = lock_data.get("pid")
start_time = datetime.fromisoformat(lock_data.get("start_time"))
running_track = lock_data.get("track")
# Check if the process is still running
if pid and self.separator._is_process_running(pid):
# Process is still running
self.separator.logger.info(f"Waiting for another separation process to complete: {running_track}")
time.sleep(5)
continue
else:
# Stale lock, remove it
self.separator.logger.info(f"Removing stale lock file")
os.remove(self.lock_file_path)
except (json.JSONDecodeError, KeyError, ValueError):
# Invalid lock file, remove it
self.separator.logger.info(f"Removing invalid lock file")
os.remove(self.lock_file_path)
# Create lock file
lock_data = {
"pid": os.getpid(),
"start_time": datetime.now().isoformat(),
"track": self.track_name
}
with open(self.lock_file_path, "w") as f:
json.dump(lock_data, f)
self.lock_file = self.lock_file_path
self.separator.logger.info(f"Acquired lock for {self.track_name}")
return self
except Exception as e:
self.separator.logger.error(f"Error acquiring lock: {str(e)}")
time.sleep(5)
def __exit__(self, exc_type, exc_val, exc_tb):
# Release lock
if self.lock_file and os.path.exists(self.lock_file):
try:
os.remove(self.lock_file)
self.separator.logger.info(f"Released lock for {self.track_name}")
except Exception as e:
self.separator.logger.error(f"Error releasing lock: {str(e)}")
return LockContextManager(self, track_name)
def _is_process_running(self, pid):
"""
Check if a process with the given PID is running.
Args:
pid: The process ID to check
Returns:
True if the process is running, False otherwise
"""
try:
# For Unix/Linux/Mac
if os.name == 'posix':
# Send signal 0 to the process - this doesn't actually send a signal,
# but it does error checking to see if the process exists
os.kill(pid, 0)
return True
# For Windows
elif os.name == 'nt':
import ctypes
kernel32 = ctypes.windll.kernel32
SYNCHRONIZE = 0x00100000
process = kernel32.OpenProcess(SYNCHRONIZE, False, pid)
if process != 0:
kernel32.CloseHandle(process)
return True
return False
else:
# Fallback for other OS
return False
except OSError:
return False
except Exception as e:
self.logger.error(f"Error checking if process {pid} is running: {str(e)}")
return False
+90
View File
@@ -0,0 +1,90 @@
import logging
import os
import asyncio
from karaoke_gen.core.project import ProjectConfig
from karaoke_gen.core.track import Track
from karaoke_gen.core.exceptions import AudioError
from karaoke_gen.services.audio.converter import AudioConverter
from karaoke_gen.services.audio.separator import AudioSeparator
from karaoke_gen.services.audio.normalizer import AudioNormalizer
from karaoke_gen.services.audio.mixer import AudioMixer
class AudioService:
"""
Service for orchestrating the audio processing workflow.
"""
def __init__(self, config: ProjectConfig):
"""
Initialize the audio service.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger or logging.getLogger(__name__)
# Initialize components
self.converter = AudioConverter(config)
self.separator = AudioSeparator(config)
self.normalizer = AudioNormalizer(config)
self.mixer = AudioMixer(config)
async def separate_audio(self, track: Track) -> Track:
"""
Separate audio for a track.
Args:
track: The track to process
Returns:
The track with separated audio
"""
self.logger.info(f"Separating audio for {track.base_name}")
return await self.separator.separate_audio(track)
async def process_audio(self, track: Track) -> Track:
"""
Process audio for a track, including separation, mixing, and normalization.
Args:
track: The track to process
Returns:
The track with updated audio information
"""
self.logger.info(f"Processing audio for {track.base_name}")
try:
# Skip if instrumental already exists and we're not forcing regeneration
if track.instrumental and os.path.isfile(track.instrumental) and not self.config.force_regenerate:
self.logger.info(f"Instrumental already exists for {track.base_name}, skipping audio processing")
return track
# Separate audio
track = await self.separator.separate_audio(track)
# Mix audio
track = await self.mixer.mix_audio(track)
# Normalize audio
track = await self.normalizer.normalize_audio(track)
return track
except Exception as e:
self.logger.error(f"Failed to process audio for {track.base_name}: {str(e)}")
# Continue with other processing
return track
async def cleanup(self):
"""
Perform cleanup operations for audio processing.
"""
self.logger.info("Cleaning up audio processing resources")
# Close any open resources
await self.separator.cleanup()
self.logger.info("Audio processing cleanup complete")
@@ -0,0 +1,21 @@
"""
Distribution service module for the karaoke_gen package.
This module contains the distribution service and related components.
"""
from karaoke_gen.services.distribution.service import DistributionService
from karaoke_gen.services.distribution.youtube import YouTubeUploader
from karaoke_gen.services.distribution.organizer import FileOrganizer
from karaoke_gen.services.distribution.cdg import CDGGenerator
from karaoke_gen.services.distribution.txt import TXTGenerator
from karaoke_gen.services.distribution.notifier import Notifier
__all__ = [
"DistributionService",
"YouTubeUploader",
"FileOrganizer",
"CDGGenerator",
"TXTGenerator",
"Notifier",
]
+159
View File
@@ -0,0 +1,159 @@
"""
CDG file generation functionality for the distribution service.
"""
import os
import zipfile
import logging
from typing import Optional, Dict, Any, Tuple
from lyrics_transcriber.output.cdg import CDGGenerator as LyricsTranscriberCDGGenerator
from karaoke_gen.core.project import ProjectConfig
from karaoke_gen.core.track import Track
from karaoke_gen.core.exceptions import DistributionError
class CDGGenerator:
"""
Class for handling CDG file generation.
"""
def __init__(self, config: ProjectConfig):
"""
Initialize the CDG generator.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger or logging.getLogger(__name__)
def create_cdg_zip_file(self, track: Track) -> Track:
"""
Create a CDG zip file for the track.
Args:
track: The track to process
Returns:
The track with updated CDG zip file information
Raises:
DistributionError: If creating the CDG zip file fails
"""
self.logger.info(f"Creating CDG and MP3 files, then zipping them...")
if not self.config.enable_cdg:
self.logger.warning("CDG generation not enabled, skipping")
return track
if not track.processed_lyrics:
self.logger.warning("No processed lyrics available, cannot create CDG file")
return track
if not track.instrumental:
self.logger.warning("No instrumental audio available, cannot create CDG file")
return track
# Determine the output file paths
cdg_zip_file = os.path.join(track.track_output_dir, f"{track.base_name} (Final Karaoke CDG).zip")
cdg_file = os.path.join(track.track_output_dir, f"{track.base_name} (Karaoke).cdg")
mp3_file = os.path.join(track.track_output_dir, f"{track.base_name} (Karaoke).mp3")
lrc_file = os.path.join(track.track_output_dir, f"{track.base_name} (Karaoke).lrc")
# Check if CDG file already exists, if so, ask user to overwrite or skip
if os.path.isfile(cdg_zip_file):
if self.config.non_interactive:
self.logger.info(f"Non-interactive mode, automatically overwriting existing CDG ZIP file: {cdg_zip_file}")
else:
from karaoke_gen.utils.validation import prompt_user_bool
if not prompt_user_bool(
f"Found existing CDG ZIP file: {cdg_zip_file}. Overwrite (y) or skip (n)?",
):
self.logger.info(f"Skipping CDG ZIP file creation, existing file will be used.")
track.final_karaoke_cdg_zip = cdg_zip_file
return track
# Check if individual MP3 and CDG files already exist
if os.path.isfile(mp3_file) and os.path.isfile(cdg_file):
self.logger.info(f"Found existing MP3 and CDG files, creating ZIP file directly")
if self.config.dry_run:
self.logger.info(f"DRY RUN: Would create ZIP file from existing MP3 and CDG files")
track.final_karaoke_cdg_zip = cdg_zip_file
return track
try:
with zipfile.ZipFile(cdg_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"Created CDG ZIP file: {cdg_zip_file}")
track.final_karaoke_cdg_zip = cdg_zip_file
return track
except Exception as e:
self.logger.error(f"Failed to create CDG ZIP file: {str(e)}")
raise DistributionError(f"Failed to create CDG ZIP file: {str(e)}")
# Generate CDG and MP3 files if they don't exist
if self.config.dry_run:
self.logger.info(f"DRY RUN: Would generate CDG and MP3 files")
track.final_karaoke_cdg_zip = cdg_zip_file
return track
try:
self.logger.info(f"Generating CDG and MP3 files")
if not self.config.cdg_styles:
raise DistributionError("CDG styles configuration is required when enable_cdg is True")
# Create the LRC file if it doesn't exist
if not os.path.isfile(lrc_file) and track.processed_lyrics:
with open(lrc_file, "w", encoding="utf-8") as f:
f.write(track.processed_lyrics)
# Use the CDGGenerator from lyrics_transcriber to generate the CDG file
generator = LyricsTranscriberCDGGenerator(output_dir=track.track_output_dir, logger=self.logger)
cdg_file_generated, mp3_file_generated, zip_file_generated = generator.generate_cdg_from_lrc(
lrc_file=lrc_file,
audio_file=track.instrumental,
title=track.title,
artist=track.artist,
cdg_styles=self.config.cdg_styles,
)
# Rename the generated ZIP file to match our expected naming convention
if os.path.isfile(zip_file_generated) and zip_file_generated != cdg_zip_file:
os.rename(zip_file_generated, cdg_zip_file)
self.logger.info(f"Renamed CDG ZIP file from {zip_file_generated} to {cdg_zip_file}")
# Verify the CDG ZIP file was created
if not os.path.isfile(cdg_zip_file):
self.logger.error(f"Failed to find any CDG ZIP file. Listing directory contents:")
for file in os.listdir(track.track_output_dir):
self.logger.error(f" - {file}")
raise DistributionError(f"Failed to create CDG ZIP file: {cdg_zip_file}")
self.logger.info(f"CDG ZIP file created: {cdg_zip_file}")
# Extract the CDG ZIP file to get the individual files
self.logger.info(f"Extracting CDG ZIP file: {cdg_zip_file}")
with zipfile.ZipFile(cdg_zip_file, "r") as zip_ref:
zip_ref.extractall(track.track_output_dir)
# Verify the MP3 file was extracted
if os.path.isfile(mp3_file):
self.logger.info(f"Found extracted MP3 file: {mp3_file}")
else:
self.logger.error("Failed to find extracted MP3 file")
raise DistributionError("Failed to extract MP3 file from CDG ZIP")
track.final_karaoke_cdg_zip = cdg_zip_file
return track
except Exception as e:
self.logger.error(f"Failed to create CDG ZIP file: {str(e)}")
raise DistributionError(f"Failed to create CDG ZIP file: {str(e)}")
@@ -0,0 +1,285 @@
"""
Notification functionality for the distribution service.
"""
import os
import pickle
import logging
import base64
import requests
from typing import Optional, Dict, Any
from email.mime.text import MIMEText
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
from karaoke_gen.core.project import ProjectConfig
from karaoke_gen.core.track import Track
from karaoke_gen.core.exceptions import DistributionError
class Notifier:
"""
Class for handling notifications.
"""
def __init__(self, config: ProjectConfig):
"""
Initialize the notifier.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger or logging.getLogger(__name__)
self.gmail_token_file = "/tmp/karaoke-finalise-gmail-token.pickle"
self.gmail_service = None
def post_discord_message(self, message: str, webhook_url: str) -> None:
"""
Post a message to a Discord channel via webhook.
Args:
message: The message to post
webhook_url: The Discord webhook URL
Raises:
DistributionError: If posting the message fails
"""
self.logger.info(f"Posting message to Discord...")
if self.config.dry_run:
self.logger.info(f"DRY RUN: Would post message to Discord: {message}")
return
try:
data = {"content": message}
response = requests.post(webhook_url, json=data)
response.raise_for_status() # This will raise an exception if the request failed
self.logger.info("Message posted to Discord")
except Exception as e:
self.logger.error(f"Failed to post message to Discord: {str(e)}")
raise DistributionError(f"Failed to post message to Discord: {str(e)}")
def post_discord_notification(self, track: Track, skip_notifications: bool = False) -> None:
"""
Post a notification to Discord.
Args:
track: The track to notify about
skip_notifications: Whether to skip notifications
Raises:
DistributionError: If posting the notification fails
"""
self.logger.info(f"Posting Discord notification...")
if not self.config.discord_webhook_url:
self.logger.warning("Discord webhook URL not set, cannot post notification")
return
if skip_notifications:
self.logger.info(f"Skipping Discord notification as requested")
return
if self.config.dry_run:
self.logger.info(
f"DRY RUN: Would post Discord notification for YouTube URL {track.youtube_url} using webhook URL: {self.config.discord_webhook_url}"
)
return
try:
# Create a rich embed for Discord
embed = {
"title": f"{track.artist} - {track.title}",
"description": "New karaoke track available!",
"color": 0x00ff00, # Green color
"fields": []
}
# Add brand code if available
if track.brand_code:
embed["fields"].append({
"name": "Brand Code",
"value": track.brand_code,
"inline": True
})
# Add YouTube URL if available
if track.youtube_url:
embed["fields"].append({
"name": "YouTube",
"value": track.youtube_url,
"inline": True
})
# Add sharing link if available
if track.brand_code_dir_sharing_link:
embed["fields"].append({
"name": "Download",
"value": track.brand_code_dir_sharing_link,
"inline": True
})
# Create the payload
payload = {
"embeds": [embed]
}
# Post to Discord
response = requests.post(self.config.discord_webhook_url, json=payload)
response.raise_for_status()
self.logger.info("Discord notification posted successfully")
except Exception as e:
self.logger.error(f"Failed to post Discord notification: {str(e)}")
raise DistributionError(f"Failed to post Discord notification: {str(e)}")
def authenticate_gmail(self) -> Any:
"""
Authenticate and return a Gmail service object.
Returns:
The authenticated Gmail service
Raises:
DistributionError: If authentication fails
"""
self.logger.info("Authenticating with Gmail...")
if self.config.dry_run:
self.logger.info("DRY RUN: Would authenticate with Gmail")
return None
try:
creds = None
# Token file stores the user's access and refresh tokens for Gmail.
if os.path.exists(self.gmail_token_file):
with open(self.gmail_token_file, "rb") as token:
creds = pickle.load(token)
# If there are no valid credentials, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
self.config.youtube_client_secrets_file, # Reuse the YouTube client secrets file
["https://www.googleapis.com/auth/gmail.compose"]
)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open(self.gmail_token_file, "wb") as token:
pickle.dump(creds, token)
return build("gmail", "v1", credentials=creds)
except Exception as e:
self.logger.error(f"Failed to authenticate with Gmail: {str(e)}")
raise DistributionError(f"Failed to authenticate with Gmail: {str(e)}")
def draft_completion_email(self, track: Track) -> None:
"""
Draft a completion email.
Args:
track: The track to draft an email for
Raises:
DistributionError: If drafting the email fails
"""
self.logger.info(f"Drafting completion email...")
if not self.config.email_template_file:
self.logger.info("Email template file not provided, skipping email draft creation.")
return
if not track.youtube_url or not track.brand_code_dir_sharing_link:
self.logger.warning("YouTube URL or sharing link not available, cannot draft completion email")
return
if self.config.dry_run:
self.logger.info(f"DRY RUN: Would draft completion email for {track.artist} - {track.title}")
return
try:
# Read the email template
with open(self.config.email_template_file, "r", encoding="utf-8") as f:
template = f.read()
# Format the email body
email_body = template.format(
youtube_url=track.youtube_url,
dropbox_url=track.brand_code_dir_sharing_link,
artist=track.artist,
title=track.title,
brand_code=track.brand_code
)
# Create the email subject
subject = f"{track.brand_code}: {track.artist} - {track.title}"
# Create the email message
message = MIMEText(email_body)
message["subject"] = subject
# Encode the message
raw_message = base64.urlsafe_b64encode(message.as_bytes()).decode("utf-8")
# Get the Gmail service
if not self.gmail_service:
self.gmail_service = self.authenticate_gmail()
# Create the draft
draft = self.gmail_service.users().drafts().create(
userId="me",
body={"message": {"raw": raw_message}}
).execute()
self.logger.info(f"Email draft created with ID: {draft['id']}")
except Exception as e:
self.logger.error(f"Failed to draft completion email: {str(e)}")
raise DistributionError(f"Failed to draft completion email: {str(e)}")
def test_email_template(self) -> None:
"""
Test the email template by creating a draft with fake data.
Raises:
DistributionError: If testing the email template fails
"""
self.logger.info(f"Testing email template...")
if not self.config.email_template_file:
self.logger.error("Email template file not provided. Use --email_template_file to specify the file path.")
return
if self.config.dry_run:
self.logger.info(f"DRY RUN: Would test email template")
return
try:
# Create a fake track
fake_track = Track(
artist="Test Artist",
title="Test Song",
brand_code="TEST-0001",
youtube_url="https://www.youtube.com/watch?v=dQw4w9WgXcQ",
brand_code_dir_sharing_link="https://www.dropbox.com/sh/fake/folder/link"
)
# Draft the email
self.draft_completion_email(fake_track)
self.logger.info("Email template test complete. Check your Gmail drafts for the test email.")
except Exception as e:
self.logger.error(f"Failed to test email template: {str(e)}")
raise DistributionError(f"Failed to test email template: {str(e)}")
@@ -0,0 +1,329 @@
"""
File organization functionality for the distribution service.
"""
import os
import re
import shutil
import subprocess
import time
import logging
import shlex
from typing import Optional, Dict, Any, List
from karaoke_gen.core.project import ProjectConfig
from karaoke_gen.core.track import Track
from karaoke_gen.core.exceptions import DistributionError
class FileOrganizer:
"""
Class for handling file organization operations.
"""
def __init__(self, config: ProjectConfig):
"""
Initialize the file organizer.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger or logging.getLogger(__name__)
def get_next_brand_code(self) -> str:
"""
Calculate the next sequence number based on existing directories in the organised_dir.
Assumes directories are named with the format: BRAND-XXXX Artist - Title
Returns:
The next brand code
Raises:
DistributionError: If the target directory does not exist
"""
self.logger.info(f"Getting next brand code for prefix {self.config.brand_prefix}")
if not self.config.brand_prefix or not self.config.organised_dir:
self.logger.warning("Brand prefix or organised directory not set, cannot get next brand code")
return None
if not os.path.isdir(self.config.organised_dir):
raise DistributionError(f"Target directory does not exist: {self.config.organised_dir}")
max_num = 0
pattern = re.compile(rf"^{re.escape(self.config.brand_prefix)}-(\d{{4}})")
for dir_name in os.listdir(self.config.organised_dir):
match = pattern.match(dir_name)
if match:
num = int(match.group(1))
max_num = max(max_num, num)
self.logger.info(f"Next sequence number for brand {self.config.brand_prefix} calculated as: {max_num + 1}")
next_seq_number = max_num + 1
return f"{self.config.brand_prefix}-{next_seq_number:04d}"
def get_existing_brand_code(self, track: Track) -> str:
"""
Extract brand code from current directory name.
Args:
track: The track to process
Returns:
The existing brand code
Raises:
DistributionError: If the current directory name does not match the expected format
"""
self.logger.info("Getting existing brand code from current directory")
if not self.config.brand_prefix:
self.logger.warning("Brand prefix not set, cannot get existing brand code")
return None
current_dir = os.path.basename(track.track_output_dir)
if " - " not in current_dir:
raise DistributionError(f"Current directory '{current_dir}' does not match expected format 'BRAND-XXXX - Artist - Title'")
brand_code = current_dir.split(" - ")[0]
if not brand_code or "-" not in brand_code:
raise DistributionError(f"Could not extract valid brand code from directory name '{current_dir}'")
self.logger.info(f"Using existing brand code: {brand_code}")
return brand_code
def move_files_to_brand_code_folder(self, track: Track, brand_code: str) -> Track:
"""
Move files to a brand code folder.
Args:
track: The track to process
brand_code: The brand code to use
Returns:
The track with updated file paths
Raises:
DistributionError: If moving the files fails
"""
self.logger.info(f"Moving files to new brand-prefixed directory...")
if not brand_code:
self.logger.warning("Brand code not set, cannot move files")
return track
new_brand_code_dir = f"{brand_code} - {track.artist} - {track.title}"
new_brand_code_dir_path = os.path.join(self.config.organised_dir, new_brand_code_dir)
# Store the new directory path in the track
track.new_brand_code_dir_path = new_brand_code_dir_path
if self.config.dry_run:
self.logger.info(f"DRY RUN: Would move original directory {track.track_output_dir} to: {new_brand_code_dir_path}")
return track
try:
# Create the parent directory if it doesn't exist
os.makedirs(os.path.dirname(new_brand_code_dir_path), exist_ok=True)
# Move the directory
shutil.move(track.track_output_dir, new_brand_code_dir_path)
# Update the track's output directory
track.track_output_dir = new_brand_code_dir_path
# Update file paths
if track.final_video:
track.final_video = os.path.join(new_brand_code_dir_path, os.path.basename(track.final_video))
if track.final_video_mkv:
track.final_video_mkv = os.path.join(new_brand_code_dir_path, os.path.basename(track.final_video_mkv))
if track.final_video_lossy:
track.final_video_lossy = os.path.join(new_brand_code_dir_path, os.path.basename(track.final_video_lossy))
if track.final_video_720p:
track.final_video_720p = os.path.join(new_brand_code_dir_path, os.path.basename(track.final_video_720p))
if track.final_karaoke_cdg_zip:
track.final_karaoke_cdg_zip = os.path.join(new_brand_code_dir_path, os.path.basename(track.final_karaoke_cdg_zip))
if track.final_karaoke_txt_zip:
track.final_karaoke_txt_zip = os.path.join(new_brand_code_dir_path, os.path.basename(track.final_karaoke_txt_zip))
return track
except Exception as e:
self.logger.error(f"Failed to move files to brand code folder: {str(e)}")
raise DistributionError(f"Failed to move files to brand code folder: {str(e)}")
def copy_final_files_to_public_share_dirs(self, track: Track, brand_code: str) -> Track:
"""
Copy final files to public share directories.
Args:
track: The track to process
brand_code: The brand code to use
Returns:
The track with updated file paths
Raises:
DistributionError: If copying the files fails
"""
self.logger.info(f"Copying final MP4, 720p MP4, and ZIP to public share directory...")
if not self.config.public_share_dir:
self.logger.warning("Public share directory not set, cannot copy files")
return track
if not brand_code:
raise DistributionError(f"Brand code not set, refusing to copy to public share directory")
# Validate public_share_dir is a valid folder with MP4, MP4-720p, and CDG subdirectories
if not os.path.isdir(self.config.public_share_dir):
raise DistributionError(f"Public share directory does not exist: {self.config.public_share_dir}")
dest_mp4_dir = os.path.join(self.config.public_share_dir, "MP4")
dest_720p_dir = os.path.join(self.config.public_share_dir, "MP4-720p")
dest_cdg_dir = os.path.join(self.config.public_share_dir, "CDG")
# Create directories if they don't exist
for dir_path in [dest_mp4_dir, dest_720p_dir, dest_cdg_dir]:
if not os.path.isdir(dir_path):
if self.config.dry_run:
self.logger.info(f"DRY RUN: Would create directory: {dir_path}")
else:
os.makedirs(dir_path, exist_ok=True)
# Prepare destination file paths
dest_mp4_file = os.path.join(dest_mp4_dir, f"{brand_code} - {track.base_name}.mp4")
dest_720p_mp4_file = os.path.join(dest_720p_dir, f"{brand_code} - {track.base_name}.mp4")
dest_zip_file = os.path.join(dest_cdg_dir, f"{brand_code} - {track.base_name}.zip")
if self.config.dry_run:
self.logger.info(
f"DRY RUN: Would copy final MP4, 720p MP4, and ZIP to {dest_mp4_file}, {dest_720p_mp4_file}, and {dest_zip_file}"
)
return track
try:
# Copy files
if track.final_video_lossy and os.path.isfile(track.final_video_lossy):
shutil.copy2(track.final_video_lossy, dest_mp4_file)
if track.final_video_720p and os.path.isfile(track.final_video_720p):
shutil.copy2(track.final_video_720p, dest_720p_mp4_file)
if track.final_karaoke_cdg_zip and os.path.isfile(track.final_karaoke_cdg_zip):
shutil.copy2(track.final_karaoke_cdg_zip, dest_zip_file)
self.logger.info(f"Copied final files to public share directory")
return track
except Exception as e:
self.logger.error(f"Failed to copy files to public share directory: {str(e)}")
raise DistributionError(f"Failed to copy files to public share directory: {str(e)}")
def sync_public_share_dir_to_rclone_destination(self) -> None:
"""
Sync public share directory to rclone destination.
Raises:
DistributionError: If syncing fails
"""
self.logger.info(f"Syncing public share directory to rclone destination...")
if not self.config.rclone_destination or not self.config.public_share_dir:
self.logger.warning("Rclone destination or public share directory not set, cannot sync")
return
if self.config.dry_run:
self.logger.info(f"DRY RUN: Would sync {self.config.public_share_dir} to {self.config.rclone_destination}")
return
try:
# Delete .DS_Store files recursively before syncing
for root, dirs, files in os.walk(self.config.public_share_dir):
for file in files:
if file == ".DS_Store":
file_path = os.path.join(root, file)
os.remove(file_path)
self.logger.info(f"Deleted .DS_Store file: {file_path}")
# Build the rclone command
rclone_cmd = f"rclone sync -v '{self.config.public_share_dir}' '{self.config.rclone_destination}'"
# Execute the command
self.logger.info(f"Running command: {rclone_cmd}")
process = subprocess.run(rclone_cmd, shell=True, check=True, capture_output=True, text=True)
if process.returncode != 0:
raise DistributionError(f"rclone sync failed: {process.stderr}")
self.logger.info(f"Successfully synced public share directory to rclone destination")
except subprocess.CalledProcessError as e:
self.logger.error(f"Failed to sync to rclone destination. Exit code: {e.returncode}")
self.logger.error(f"Command output (stdout): {e.stdout}")
self.logger.error(f"Command output (stderr): {e.stderr}")
raise DistributionError(f"Failed to sync to rclone destination: {e.stderr}")
except Exception as e:
self.logger.error(f"Failed to sync to rclone destination: {str(e)}")
raise DistributionError(f"Failed to sync to rclone destination: {str(e)}")
def generate_organised_folder_sharing_link(self, track: Track) -> Optional[str]:
"""
Generate a sharing link for the organised folder.
Args:
track: The track to process
Returns:
The sharing link
Raises:
DistributionError: If generating the link fails
"""
self.logger.info(f"Getting Organised Folder sharing link for new brand code directory...")
if not self.config.organised_dir_rclone_root or not track.brand_code or not track.new_brand_code_dir_path:
self.logger.warning("Organised directory rclone root, brand code, or new brand code directory path not set, cannot generate sharing link")
return None
if self.config.dry_run:
self.logger.info(f"DRY RUN: Would get sharing link for {track.new_brand_code_dir_path}")
return "https://file-sharing-service.com/example"
try:
# Build the rclone destination path
rclone_dest = f"{self.config.organised_dir_rclone_root}/{os.path.basename(track.new_brand_code_dir_path)}"
rclone_link_cmd = f"rclone link {shlex.quote(rclone_dest)}"
# Add a 5-second delay to allow the service to index the folder before generating a link
self.logger.info("Waiting 5 seconds before generating link...")
time.sleep(5)
# Execute the command
self.logger.info(f"Running command: {rclone_link_cmd}")
result = subprocess.run(rclone_link_cmd, shell=True, check=True, capture_output=True, text=True)
sharing_link = result.stdout.strip()
self.logger.info(f"Got organised folder sharing link: {sharing_link}")
return sharing_link
except subprocess.CalledProcessError as e:
self.logger.error(f"Failed to get organised folder sharing link. Exit code: {e.returncode}")
self.logger.error(f"Command output (stdout): {e.stdout}")
self.logger.error(f"Command output (stderr): {e.stderr}")
raise DistributionError(f"Failed to get organised folder sharing link: {e.stderr}")
except Exception as e:
self.logger.error(f"Failed to get organised folder sharing link: {str(e)}")
raise DistributionError(f"Failed to get organised folder sharing link: {str(e)}")
@@ -0,0 +1,312 @@
from karaoke_gen.core.project import ProjectConfig
from karaoke_gen.core.track import Track
from karaoke_gen.core.exceptions import DistributionError, YouTubeError
from karaoke_gen.services.distribution.youtube import YouTubeUploader
from karaoke_gen.services.distribution.organizer import FileOrganizer
from karaoke_gen.services.distribution.cdg import CDGGenerator
from karaoke_gen.services.distribution.txt import TXTGenerator
from karaoke_gen.services.distribution.notifier import Notifier
import logging
import os
import asyncio
import shutil
import glob
import re
import subprocess
from typing import Dict, Any, Optional, List, Tuple
class DistributionService:
"""
Service for distribution operations including file organization, YouTube uploading, and notifications.
"""
def __init__(self, config: ProjectConfig):
"""
Initialize the distribution service.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger or logging.getLogger(__name__)
# Initialize components
self.youtube_uploader = YouTubeUploader(config)
self.file_organizer = FileOrganizer(config)
self.cdg_generator = CDGGenerator(config)
self.txt_generator = TXTGenerator(config)
self.notifier = Notifier(config)
# Detect best available AAC codec
self.aac_codec = self._detect_best_aac_codec()
async def distribute(self, track: Track, replace_existing: bool = False) -> Track:
"""
Distribute the track.
Args:
track: The track to process
replace_existing: Whether to replace existing files
Returns:
The track with updated distribution information
"""
self.logger.info(f"Distributing {track.base_name}")
# Remux and encode output video files
track = await self._remux_and_encode_output_video_files(track)
# Create CDG zip file if enabled
if self.config.enable_cdg:
track = self.cdg_generator.create_cdg_zip_file(track)
# Create TXT zip file if enabled
if self.config.enable_txt:
track = self.txt_generator.create_txt_zip_file(track)
# Get brand code
if self.config.keep_brand_code:
track.brand_code = self.file_organizer.get_existing_brand_code(track)
else:
track.brand_code = self.file_organizer.get_next_brand_code()
# Move files to brand code folder
if track.brand_code and self.config.organised_dir:
track = self.file_organizer.move_files_to_brand_code_folder(track, track.brand_code)
# Copy final files to public share directory
if self.config.public_share_dir and track.brand_code:
track = self.file_organizer.copy_final_files_to_public_share_dirs(track, track.brand_code)
# Sync public share directory to rclone destination
if self.config.rclone_destination and self.config.public_share_dir:
self.file_organizer.sync_public_share_dir_to_rclone_destination()
# Upload to YouTube
if self.config.youtube_client_secrets_file and track.final_video_mkv:
thumbnail_file = os.path.join(track.track_output_dir, f"{track.base_name} (Title).jpg")
if not os.path.isfile(thumbnail_file):
thumbnail_file = None
track.youtube_url = self.youtube_uploader.upload_video(
video_file=track.final_video_mkv,
thumbnail_file=thumbnail_file,
artist=track.artist,
title=track.title,
replace_existing=replace_existing
)
# Generate sharing link
if self.config.organised_dir_rclone_root and track.brand_code and track.new_brand_code_dir_path:
track.brand_code_dir_sharing_link = self.file_organizer.generate_organised_folder_sharing_link(track)
# Post Discord notification
if self.config.discord_webhook_url and track.youtube_url:
self.notifier.post_discord_notification(track)
# Draft completion email
if self.config.email_template_file and track.youtube_url and track.brand_code_dir_sharing_link:
self.notifier.draft_completion_email(track)
return track
async def _remux_and_encode_output_video_files(self, track: Track) -> Track:
"""
Remux and encode output video files.
Args:
track: The track to process
Returns:
The track with updated video file information
"""
self.logger.info(f"Remuxing and encoding output video files for {track.base_name}")
if not track.video_with_lyrics or not track.instrumental:
self.logger.warning("No video with lyrics or instrumental audio available, cannot remux/encode")
return track
# Determine output file paths
final_video = os.path.join(track.track_output_dir, f"{track.base_name} (Final Karaoke Lossless 4k).mp4")
final_video_mkv = os.path.join(track.track_output_dir, f"{track.base_name} (Final Karaoke Lossless 4k).mkv")
final_video_lossy = os.path.join(track.track_output_dir, f"{track.base_name} (Final Karaoke Lossy 4k).mp4")
final_video_720p = os.path.join(track.track_output_dir, f"{track.base_name} (Final Karaoke Lossy 720p).mp4")
# Check if output files already exist
if os.path.isfile(final_video) and os.path.isfile(final_video_mkv):
if self.config.non_interactive:
self.logger.info(f"Non-interactive mode, automatically overwriting existing final video files")
else:
from karaoke_gen.utils.validation import prompt_user_bool
if not prompt_user_bool(
f"Found existing Final Karaoke output files. Overwrite (y) or skip (n)?",
):
self.logger.info(f"Skipping Karaoke MP4 remux and Final video renders, existing files will be used.")
track.final_video = final_video
track.final_video_mkv = final_video_mkv
track.final_video_lossy = final_video_lossy
track.final_video_720p = final_video_720p
return track
if self.config.dry_run:
self.logger.info(f"DRY RUN: Would remux and encode output video files")
track.final_video = final_video
track.final_video_mkv = final_video_mkv
track.final_video_lossy = final_video_lossy
track.final_video_720p = final_video_720p
return track
try:
# MP4 output flags for better compatibility and streaming
mp4_flags = "-pix_fmt yuv420p -movflags +faststart+frag_keyframe+empty_moov"
# Path to ffmpeg
ffmpeg_path = "ffmpeg"
# Base ffmpeg command
ffmpeg_base_command = f"{ffmpeg_path} -hide_banner -nostats"
if self.logger.level == logging.DEBUG:
ffmpeg_base_command += " -loglevel verbose"
else:
ffmpeg_base_command += " -loglevel fatal"
# Add -y if non-interactive
if self.config.non_interactive:
ffmpeg_base_command += " -y"
# Create karaoke version with instrumental audio
karaoke_mp4 = os.path.join(track.track_output_dir, f"{track.base_name} (Karaoke).mp4")
# Remux the video with instrumental audio
remux_command = (
f'{ffmpeg_base_command} -an -i "{track.video_with_lyrics}" '
f'-vn -i "{track.instrumental}" -c:v copy -c:a pcm_s16le "{karaoke_mp4}"'
)
self.logger.info(f"Remuxing video with instrumental audio: {remux_command}")
process = await asyncio.create_subprocess_shell(
remux_command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
await process.communicate()
# Prepare title and end videos
title_video = os.path.join(track.track_output_dir, f"{track.base_name} (Title).mov")
end_video = os.path.join(track.track_output_dir, f"{track.base_name} (End).mov")
# Prepare concat filter for combining videos
env_mov_input = ""
ffmpeg_filter = '-filter_complex "[0:v:0][0:a:0][1:v:0][1:a:0]concat=n=2:v=1:a=1[outv][outa]"'
if os.path.isfile(end_video):
self.logger.info(f"Found end video: {end_video}, including in final MP4")
env_mov_input = f'-i "{end_video}"'
ffmpeg_filter = '-filter_complex "[0:v:0][0:a:0][1:v:0][1:a:0][2:v:0][2:a:0]concat=n=3:v=1:a=1[outv][outa]"'
# Create lossless MP4
lossless_mp4_command = (
f'{ffmpeg_base_command} -i "{title_video}" -i "{karaoke_mp4}" {env_mov_input} '
f'{ffmpeg_filter} -map "[outv]" -map "[outa]" -c:v libx264 -c:a pcm_s16le '
f'{mp4_flags} "{final_video}"'
)
self.logger.info(f"Creating MP4 version with PCM audio: {lossless_mp4_command}")
process = await asyncio.create_subprocess_shell(
lossless_mp4_command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
await process.communicate()
# Create lossy MP4
lossy_mp4_command = (
f'{ffmpeg_base_command} -i "{final_video}" '
f'-c:v copy -c:a {self.aac_codec} -b:a 320k {mp4_flags} "{final_video_lossy}"'
)
self.logger.info(f"Creating MP4 version with AAC audio: {lossy_mp4_command}")
process = await asyncio.create_subprocess_shell(
lossy_mp4_command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
await process.communicate()
# Create MKV with FLAC audio
mkv_command = (
f'{ffmpeg_base_command} -i "{final_video}" '
f'-c:v copy -c:a flac "{final_video_mkv}"'
)
self.logger.info(f"Creating MKV version with FLAC audio: {mkv_command}")
process = await asyncio.create_subprocess_shell(
mkv_command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
await process.communicate()
# Create 720p MP4
mp4_720p_command = (
f'{ffmpeg_base_command} -i "{final_video}" '
f'-c:v libx264 -vf "scale=1280:720" -b:v 200k -preset medium -tune animation '
f'-c:a {self.aac_codec} -b:a 128k {mp4_flags} "{final_video_720p}"'
)
self.logger.info(f"Creating 720p version: {mp4_720p_command}")
process = await asyncio.create_subprocess_shell(
mp4_720p_command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
await process.communicate()
# Update track with file paths
track.final_video = final_video
track.final_video_mkv = final_video_mkv
track.final_video_lossy = final_video_lossy
track.final_video_720p = final_video_720p
return track
except Exception as e:
self.logger.error(f"Failed to remux and encode output video files: {str(e)}")
raise DistributionError(f"Failed to remux and encode output video files: {str(e)}")
def _detect_best_aac_codec(self) -> str:
"""
Detect the best available AAC codec (aac_at > libfdk_aac > aac).
Returns:
The best available AAC codec
"""
self.logger.info("Detecting best available AAC codec...")
if self.config.dry_run:
self.logger.info("DRY RUN: Would detect best available AAC codec")
return "aac"
try:
# Run ffmpeg -codecs to get available codecs
codec_check_command = "ffmpeg -codecs"
result = subprocess.run(codec_check_command, shell=True, capture_output=True, text=True)
output = result.stdout
if "aac_at" in output:
self.logger.info("Using aac_at codec (best quality)")
return "aac_at"
elif "libfdk_aac" in output:
self.logger.info("Using libfdk_aac codec (good quality)")
return "libfdk_aac"
else:
self.logger.info("Using built-in aac codec (basic quality)")
return "aac"
except Exception as e:
self.logger.error(f"Failed to detect best AAC codec: {str(e)}")
return "aac"
+116
View File
@@ -0,0 +1,116 @@
"""
TXT file generation functionality for the distribution service.
"""
import os
import zipfile
import logging
from typing import Optional, Dict, Any
from lyrics_converter import LyricsConverter
from karaoke_gen.core.project import ProjectConfig
from karaoke_gen.core.track import Track
from karaoke_gen.core.exceptions import DistributionError
class TXTGenerator:
"""
Class for handling TXT file generation.
"""
def __init__(self, config: ProjectConfig):
"""
Initialize the TXT generator.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger or logging.getLogger(__name__)
def create_txt_zip_file(self, track: Track) -> Track:
"""
Create a TXT zip file for the track.
Args:
track: The track to process
Returns:
The track with updated TXT zip file information
Raises:
DistributionError: If creating the TXT zip file fails
"""
self.logger.info(f"Creating TXT ZIP file...")
if not self.config.enable_txt:
self.logger.warning("TXT generation not enabled, skipping")
return track
if not track.processed_lyrics:
self.logger.warning("No processed lyrics available, cannot create TXT file")
return track
# Determine the output file paths
txt_zip_file = os.path.join(track.track_output_dir, f"{track.base_name} (Final Karaoke TXT).zip")
txt_file = os.path.join(track.track_output_dir, f"{track.base_name} (Karaoke).txt")
mp3_file = os.path.join(track.track_output_dir, f"{track.base_name} (Karaoke).mp3")
lrc_file = os.path.join(track.track_output_dir, f"{track.base_name} (Karaoke).lrc")
# Check if TXT file already exists, if so, ask user to overwrite or skip
if os.path.isfile(txt_zip_file):
if self.config.non_interactive:
self.logger.info(f"Non-interactive mode, automatically overwriting existing TXT ZIP file: {txt_zip_file}")
else:
from karaoke_gen.utils.validation import prompt_user_bool
if not prompt_user_bool(
f"Found existing TXT ZIP file: {txt_zip_file}. Overwrite (y) or skip (n)?",
):
self.logger.info(f"Skipping TXT ZIP file creation, existing file will be used.")
track.final_karaoke_txt_zip = txt_zip_file
return track
if self.config.dry_run:
self.logger.info(f"DRY RUN: Would create TXT ZIP file: {txt_zip_file}")
track.final_karaoke_txt_zip = txt_zip_file
return track
try:
# Create the LRC file if it doesn't exist
if not os.path.isfile(lrc_file) and track.processed_lyrics:
with open(lrc_file, "w", encoding="utf-8") as f:
f.write(track.processed_lyrics)
# Convert LRC to TXT format
self.logger.info(f"Running karaoke-converter to convert MidiCo LRC file {lrc_file} to TXT format")
txt_converter = LyricsConverter(output_format="txt", filepath=lrc_file)
converted_txt = txt_converter.convert_file()
# Write the TXT file
with open(txt_file, "w", encoding="utf-8") as txt_file_handle:
txt_file_handle.write(converted_txt)
self.logger.info(f"TXT file written: {txt_file}")
# Ensure the MP3 file exists
if not os.path.isfile(mp3_file):
self.logger.warning(f"MP3 file not found: {mp3_file}, cannot create TXT ZIP file")
return track
# Create the ZIP file containing the MP3 and TXT files
self.logger.info(f"Creating ZIP file containing {mp3_file} and {txt_file}")
with zipfile.ZipFile(txt_zip_file, "w") as zipf:
zipf.write(mp3_file, os.path.basename(mp3_file))
zipf.write(txt_file, os.path.basename(txt_file))
# Verify the TXT ZIP file was created
if not os.path.isfile(txt_zip_file):
raise DistributionError(f"Failed to create TXT ZIP file: {txt_zip_file}")
self.logger.info(f"TXT ZIP file created: {txt_zip_file}")
track.final_karaoke_txt_zip = txt_zip_file
return track
except Exception as e:
self.logger.error(f"Failed to create TXT ZIP file: {str(e)}")
raise DistributionError(f"Failed to create TXT ZIP file: {str(e)}")
@@ -0,0 +1,327 @@
"""
YouTube uploading functionality for the distribution service.
"""
import os
import pickle
import logging
from typing import Optional, Dict, Any, List, Tuple
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from google.oauth2.credentials import Credentials
from thefuzz import fuzz
from karaoke_gen.core.project import ProjectConfig
from karaoke_gen.core.exceptions import YouTubeError
class YouTubeUploader:
"""
Class for handling YouTube uploads and related operations.
"""
def __init__(self, config: ProjectConfig):
"""
Initialize the YouTube uploader.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger or logging.getLogger(__name__)
self.youtube_url_prefix = "https://www.youtube.com/watch?v="
self.youtube_token_file = "/tmp/karaoke-finalise-youtube-token.pickle"
def authenticate_youtube(self) -> Any:
"""
Authenticate and return a YouTube service object.
Returns:
The authenticated YouTube service
Raises:
YouTubeError: If authentication fails
"""
self.logger.info("Authenticating with YouTube...")
if self.config.dry_run:
self.logger.info("DRY RUN: Would authenticate with YouTube")
return None
try:
credentials = None
# Token file stores the user's access and refresh tokens for YouTube.
if os.path.exists(self.youtube_token_file):
with open(self.youtube_token_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.config.youtube_client_secrets_file,
scopes=["https://www.googleapis.com/auth/youtube"]
)
credentials = flow.run_local_server(port=0) # This will open a browser for authentication
# Save the credentials for the next run
with open(self.youtube_token_file, "wb") as token:
pickle.dump(credentials, token)
return build("youtube", "v3", credentials=credentials)
except Exception as e:
self.logger.error(f"Failed to authenticate with YouTube: {str(e)}")
raise YouTubeError(f"Failed to authenticate with YouTube: {str(e)}")
def get_channel_id(self) -> Optional[str]:
"""
Get the authenticated user's channel ID.
Returns:
The channel ID or None if not found
Raises:
YouTubeError: If getting the channel ID fails
"""
self.logger.info("Getting YouTube channel ID...")
if self.config.dry_run:
self.logger.info("DRY RUN: Would get YouTube channel ID")
return "DUMMY_CHANNEL_ID"
try:
youtube = self.authenticate_youtube()
# Get the authenticated user's channel
request = youtube.channels().list(part="snippet", mine=True)
response = request.execute()
# Extract the channel ID
if "items" in response:
channel_id = response["items"][0]["id"]
self.logger.info(f"Found YouTube channel ID: {channel_id}")
return channel_id
else:
self.logger.warning("No YouTube channel found for the authenticated user")
return None
except Exception as e:
self.logger.error(f"Failed to get YouTube channel ID: {str(e)}")
raise YouTubeError(f"Failed to get YouTube channel ID: {str(e)}")
def check_if_video_title_exists(self, youtube_title: str) -> Tuple[bool, Optional[str]]:
"""
Check if a video with the given title already exists on the authenticated user's channel.
Args:
youtube_title: The title to check
Returns:
A tuple of (exists, video_id) where exists is True if the video exists and video_id is the ID of the video
Raises:
YouTubeError: If checking for the video fails
"""
self.logger.info(f"Checking if video with title '{youtube_title}' exists on YouTube channel...")
if self.config.dry_run:
self.logger.info(f"DRY RUN: Would check if video with title '{youtube_title}' exists on YouTube channel")
return False, None
try:
youtube = self.authenticate_youtube()
channel_id = self.get_channel_id()
if not channel_id:
self.logger.warning("No YouTube channel ID found, cannot check for existing videos")
return False, None
self.logger.info(f"Searching YouTube channel {channel_id} for title: {youtube_title}")
request = youtube.search().list(
part="snippet",
channelId=channel_id,
q=youtube_title,
type="video",
maxResults=10
)
response = request.execute()
# Check if any videos were found
if "items" in response and len(response["items"]) > 0:
for item in response["items"]:
found_title = item["snippet"]["title"]
similarity_score = fuzz.ratio(youtube_title.lower(), found_title.lower())
if similarity_score >= 70: # 70% similarity
found_id = item["id"]["videoId"]
self.logger.info(
f"Potential match found on YouTube channel with ID: {found_id} and title: {found_title} (similarity: {similarity_score}%)"
)
# In non-interactive mode, automatically confirm if similarity is high enough
if self.config.non_interactive:
self.logger.info(f"Non-interactive mode, automatically confirming match with similarity score {similarity_score}%")
return True, found_id
confirmation = input(f"Is '{found_title}' the video you are finalising? (y/n): ").strip().lower()
if confirmation == "y":
return True, found_id
self.logger.info(f"No matching video found with title: {youtube_title}")
return False, None
except Exception as e:
self.logger.error(f"Failed to check if video exists on YouTube: {str(e)}")
raise YouTubeError(f"Failed to check if video exists on YouTube: {str(e)}")
def delete_youtube_video(self, video_id: str) -> bool:
"""
Delete a YouTube video by its ID.
Args:
video_id: The YouTube video ID to delete
Returns:
True if successful, False otherwise
Raises:
YouTubeError: If deleting the video fails
"""
self.logger.info(f"Deleting YouTube video with ID: {video_id}")
if self.config.dry_run:
self.logger.info(f"DRY RUN: Would delete YouTube video with ID: {video_id}")
return True
try:
youtube = self.authenticate_youtube()
youtube.videos().delete(id=video_id).execute()
self.logger.info(f"Successfully deleted YouTube video with ID: {video_id}")
return True
except Exception as e:
self.logger.error(f"Failed to delete YouTube video with ID {video_id}: {e}")
return False
def truncate_to_nearest_word(self, title: str, max_length: int) -> str:
"""
Truncate a string to the nearest word within the maximum length.
Args:
title: The string to truncate
max_length: The maximum length
Returns:
The truncated string
"""
if len(title) <= max_length:
return title
truncated_title = title[:max_length].rsplit(" ", 1)[0]
if len(truncated_title) < max_length:
truncated_title += " ..."
return truncated_title
def upload_video(
self,
video_file: str,
thumbnail_file: Optional[str],
artist: str,
title: str,
replace_existing: bool = False
) -> Optional[str]:
"""
Upload a video to YouTube with the given title and thumbnail.
Args:
video_file: The path to the video file
thumbnail_file: The path to the thumbnail file
artist: The artist name
title: The track title
replace_existing: Whether to replace an existing video
Returns:
The YouTube URL of the uploaded video or None if upload failed
Raises:
YouTubeError: If uploading the video fails
"""
self.logger.info(f"Uploading video to YouTube: {video_file}")
if self.config.dry_run:
self.logger.info(f"DRY RUN: Would upload {video_file} to YouTube with thumbnail {thumbnail_file}")
return f"{self.youtube_url_prefix}DUMMY_VIDEO_ID"
try:
youtube_title = f"{artist} - {title} (Karaoke)"
# Truncate title to the nearest whole word and add ellipsis if needed
max_length = 95
youtube_title = self.truncate_to_nearest_word(youtube_title, max_length)
# Check if video already exists
exists, video_id = self.check_if_video_title_exists(youtube_title)
if exists:
if replace_existing:
self.logger.info(f"Video already exists on YouTube, deleting before re-upload: {self.youtube_url_prefix}{video_id}")
if self.delete_youtube_video(video_id):
self.logger.info(f"Successfully deleted existing video, proceeding with upload")
else:
self.logger.error(f"Failed to delete existing video, aborting upload")
return None
else:
self.logger.warning(f"Video already exists on YouTube, skipping upload: {self.youtube_url_prefix}{video_id}")
return f"{self.youtube_url_prefix}{video_id}"
# Load description from file if available
youtube_description = f"Karaoke version of {artist} - {title} created using karaoke-gen python package."
if self.config.youtube_description_file and os.path.isfile(self.config.youtube_description_file):
with open(self.config.youtube_description_file, "r") as f:
youtube_description = f.read()
youtube_category_id = "10" # Category ID for Music
youtube_keywords = ["karaoke", "music", "singing", "instrumental", "lyrics", artist, title]
self.logger.info(f"Authenticating with YouTube...")
youtube = self.authenticate_youtube()
body = {
"snippet": {
"title": youtube_title,
"description": youtube_description,
"tags": youtube_keywords,
"categoryId": youtube_category_id,
},
"status": {"privacyStatus": "public"},
}
# Use MediaFileUpload to handle the video file
media_file = MediaFileUpload(video_file, resumable=True)
# Call the API's videos.insert method to create and upload the video.
self.logger.info(f"Uploading video to YouTube...")
request = youtube.videos().insert(part="snippet,status", body=body, media_body=media_file)
response = request.execute()
video_id = response.get("id")
youtube_url = f"{self.youtube_url_prefix}{video_id}"
self.logger.info(f"Uploaded video to YouTube: {youtube_url}")
# Uploading the thumbnail
if thumbnail_file and os.path.isfile(thumbnail_file):
media_thumbnail = MediaFileUpload(thumbnail_file, mimetype="image/jpeg")
youtube.thumbnails().set(videoId=video_id, media_body=media_thumbnail).execute()
self.logger.info(f"Uploaded thumbnail for video ID {video_id}")
return youtube_url
except Exception as e:
self.logger.error(f"Failed to upload video to YouTube: {str(e)}")
raise YouTubeError(f"Failed to upload video to YouTube: {str(e)}")
+3
View File
@@ -0,0 +1,3 @@
from karaoke_gen.services.lyrics.service import LyricsService
from karaoke_gen.services.lyrics.transcriber import LyricsTranscriber
from karaoke_gen.services.lyrics.formatter import LyricsFormatter
+162
View File
@@ -0,0 +1,162 @@
import os
import glob
import shutil
import datetime
from karaoke_gen.core.track import Track
from karaoke_gen.core.exceptions import FormattingError
class LyricsFormatter:
"""
Handles lyrics formatting and backup operations.
"""
def __init__(self, config):
"""
Initialize the lyrics formatter.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger
async def format_lyrics(self, track):
"""
Format lyrics for a track.
Args:
track: The track to process
Returns:
The track with updated formatting information
"""
self.logger.info(f"Formatting lyrics for {track.base_name}")
# Skip if no lyrics
if not track.lyrics:
self.logger.warning("No lyrics found, cannot format")
return track
# Skip if already formatted
if track.processed_lyrics and track.processed_lyrics.get("formatted_lyrics"):
self.logger.info(f"Lyrics already formatted")
return track
try:
# Read lyrics file
if isinstance(track.lyrics, str) and os.path.isfile(track.lyrics):
with open(track.lyrics, "r", encoding="utf-8") as f:
lyrics_text = f.read()
else:
lyrics_text = track.lyrics
# Format lyrics
formatted_lyrics = self._format_lyrics_text(lyrics_text)
# Save formatted lyrics
formatted_lyrics_file = os.path.join(track.track_output_dir, f"{track.base_name} (Formatted Lyrics).txt")
if not self.config.dry_run:
with open(formatted_lyrics_file, "w", encoding="utf-8") as f:
f.write(formatted_lyrics)
# Update track
if not track.processed_lyrics:
track.processed_lyrics = {}
track.processed_lyrics["formatted_lyrics"] = formatted_lyrics
track.processed_lyrics["formatted_lyrics_file"] = formatted_lyrics_file
return track
except Exception as e:
raise FormattingError(f"Failed to format lyrics: {str(e)}") from e
def _format_lyrics_text(self, lyrics_text):
"""
Format lyrics text.
Args:
lyrics_text: The lyrics text to format
Returns:
The formatted lyrics text
"""
# Remove extra whitespace
formatted_text = lyrics_text.strip()
# Split into lines
lines = formatted_text.split("\n")
# Remove empty lines at the beginning and end
while lines and not lines[0].strip():
lines.pop(0)
while lines and not lines[-1].strip():
lines.pop()
# Remove duplicate empty lines
formatted_lines = []
prev_empty = False
for line in lines:
is_empty = not line.strip()
if not (is_empty and prev_empty):
formatted_lines.append(line)
prev_empty = is_empty
# Join lines
formatted_text = "\n".join(formatted_lines)
return formatted_text
async def backup_existing_outputs(self, track):
"""
Backup existing outputs for a track.
Args:
track: The track to process
Returns:
The track with updated backup information
"""
self.logger.info(f"Backing up existing outputs for {track.base_name}")
# Create backup directory
backup_dir = os.path.join(track.track_output_dir, "backup_" + self._get_timestamp())
if not self.config.dry_run:
os.makedirs(backup_dir, exist_ok=True)
# Find existing files to backup
files_to_backup = []
# Lyrics files
lyrics_files = glob.glob(os.path.join(track.track_output_dir, "*.lrc"))
files_to_backup.extend(lyrics_files)
# Video files
video_files = glob.glob(os.path.join(track.track_output_dir, "*.mkv"))
video_files.extend(glob.glob(os.path.join(track.track_output_dir, "*.mp4")))
files_to_backup.extend(video_files)
# Subtitle files
subtitle_files = glob.glob(os.path.join(track.track_output_dir, "*.srt"))
subtitle_files.extend(glob.glob(os.path.join(track.track_output_dir, "*.ass")))
files_to_backup.extend(subtitle_files)
# Backup files
for file_path in files_to_backup:
if os.path.exists(file_path) and not self.config.dry_run:
backup_path = os.path.join(backup_dir, os.path.basename(file_path))
shutil.copy2(file_path, backup_path)
self.logger.info(f"Backed up {file_path} to {backup_path}")
return track
def _get_timestamp(self):
"""
Get a timestamp string.
Returns:
A timestamp string
"""
return datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
+239
View File
@@ -0,0 +1,239 @@
import logging
import os
import glob
import shutil
from typing import Dict, Any, Optional
from karaoke_gen.core.project import ProjectConfig
from karaoke_gen.core.track import Track
from karaoke_gen.core.exceptions import LyricsError
from karaoke_gen.services.lyrics.transcriber import LyricsTranscriber
from karaoke_gen.services.lyrics.formatter import LyricsFormatter
import datetime
class LyricsService:
"""
Service for lyrics processing operations including transcription.
"""
def __init__(self, config: ProjectConfig):
"""
Initialize the lyrics service.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger or logging.getLogger(__name__)
# Initialize components
self.transcriber = LyricsTranscriber(config)
self.formatter = LyricsFormatter(config)
async def process_lyrics(self, track: Track) -> Track:
"""
Process lyrics for the track.
Args:
track: The track to process
Returns:
The track with updated lyrics information
"""
if self.config.skip_lyrics:
self.logger.info(f"Skipping lyrics processing for {track.base_name}")
return track
self.logger.info(f"Processing lyrics for {track.base_name}")
# Check for existing lyrics files
track = await self._check_existing_lyrics(track)
if track.processed_lyrics:
self.logger.info("Found existing lyrics files, skipping transcription")
return track
# The LyricsTranscriber library handles both fetching lyrics and transcribing,
# so we don't need to do the fetching separately
if not self.config.skip_transcription:
track = await self.transcriber.transcribe_lyrics(track)
return track
async def _check_existing_lyrics(self, track: Track) -> Track:
"""
Check for existing lyrics files.
Args:
track: The track to process
Returns:
The track with updated lyrics information if existing files are found
"""
self.logger.info(f"Checking for existing lyrics files for {track.base_name}")
# Check for existing files in parent directory
parent_video_path = os.path.join(track.track_output_dir, f"{track.base_name} (With Vocals).mkv")
parent_lrc_path = os.path.join(track.track_output_dir, f"{track.base_name} (Karaoke).lrc")
# Check lyrics directory for existing files
lyrics_dir = os.path.join(track.track_output_dir, "lyrics")
lyrics_video_path = os.path.join(lyrics_dir, f"{track.base_name} (With Vocals).mkv")
lyrics_lrc_path = os.path.join(lyrics_dir, f"{track.base_name} (Karaoke).lrc")
# If files exist in parent directory, use them
if os.path.exists(parent_video_path) and os.path.exists(parent_lrc_path):
self.logger.info(f"Found existing video and LRC files in parent directory")
track.processed_lyrics = {
"lrc_filepath": parent_lrc_path,
"ass_filepath": parent_video_path,
}
return track
# If files exist in lyrics directory, copy to parent and use them
if os.path.exists(lyrics_video_path) and os.path.exists(lyrics_lrc_path):
self.logger.info(f"Found existing video and LRC files in lyrics directory, copying to parent")
os.makedirs(track.track_output_dir, exist_ok=True)
# Copy files to parent directory
shutil.copy2(lyrics_video_path, parent_video_path)
shutil.copy2(lyrics_lrc_path, parent_lrc_path)
track.processed_lyrics = {
"lrc_filepath": parent_lrc_path,
"ass_filepath": parent_video_path,
}
return track
return track
async def backup_and_prepare_for_edit(self, track: Track) -> Track:
"""
Backup existing outputs and prepare for lyrics editing.
Args:
track: The track to process
Returns:
The track with updated backup information
"""
self.logger.info(f"Backing up and preparing for lyrics editing for {track.base_name}")
# Create backup directory
backup_dir = os.path.join(track.track_output_dir, "backups")
if not os.path.exists(backup_dir):
os.makedirs(backup_dir)
# Create versioned backup directory
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
version_dir = os.path.join(backup_dir, f"version_{timestamp}")
os.makedirs(version_dir)
# Backup existing files
files_to_backup = []
# Backup processed lyrics
if track.processed_lyrics:
for key, value in track.processed_lyrics.items():
if isinstance(value, str) and os.path.isfile(value):
files_to_backup.append(value)
# Backup videos
for video_attr in ["video_with_lyrics", "final_video"]:
video_path = getattr(track, video_attr, None)
if video_path and os.path.isfile(video_path):
files_to_backup.append(video_path)
# Copy files to backup directory
for file_path in files_to_backup:
backup_path = os.path.join(version_dir, os.path.basename(file_path))
shutil.copy2(file_path, backup_path)
self.logger.info(f"Backed up {file_path} to {backup_path}")
# Prepare input audio file for editing
if track.instrumental and os.path.isfile(track.instrumental):
edit_audio = os.path.join(track.track_output_dir, f"{track.base_name} (Edit).wav")
shutil.copy2(track.instrumental, edit_audio)
track.metadata["edit_audio"] = edit_audio
self.logger.info(f"Prepared audio for editing: {edit_audio}")
# Store backup information
track.metadata["backup_dir"] = backup_dir
track.metadata["last_backup"] = version_dir
return track
async def cleanup(self):
"""
Perform cleanup operations for the lyrics service.
"""
self.logger.info("Cleaning up lyrics service resources")
# Close any open resources
if hasattr(self, 'transcriber') and self.transcriber:
await self.transcriber.cleanup()
if hasattr(self, 'formatter') and self.formatter:
await self.formatter.cleanup()
self.logger.info("Lyrics service cleanup complete")
async def _find_input_audio_file(self, track: Track) -> Track:
"""
Find the input audio file for lyrics editing.
Args:
track: The track to process
Returns:
The track with updated input audio information
"""
self.logger.info(f"Finding input audio file for {track.base_name}")
# Look for WAV file
wav_files = glob.glob(os.path.join(track.track_output_dir, "*.wav"))
if wav_files:
track.input_audio_wav = wav_files[0]
self.logger.info(f"Found input audio file: {track.input_audio_wav}")
return track
# Look for other audio files
audio_extensions = ['.mp3', '.flac', '.ogg', '.m4a', '.aac']
for ext in audio_extensions:
audio_files = glob.glob(os.path.join(track.track_output_dir, f"*{ext}"))
if audio_files:
# Convert to WAV
from karaoke_gen.services.audio.converter import AudioConverter
converter = AudioConverter(self.config)
track.input_media = audio_files[0]
track = await converter.convert_to_wav(track)
self.logger.info(f"Converted audio file to WAV: {track.input_audio_wav}")
return track
self.logger.warning(f"No input audio file found for {track.base_name}")
return track
def _get_timestamp(self) -> str:
"""
Get a timestamp string for backup directory naming.
Returns:
A timestamp string
"""
return datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
def _sanitize_filename(self, filename: str) -> str:
"""
Sanitize a filename by removing invalid characters.
Args:
filename: The filename to sanitize
Returns:
The sanitized filename
"""
# Replace problematic characters with underscores
for char in ["\\", "/", ":", "*", "?", '"', "<", ">", "|"]:
filename = filename.replace(char, "_")
# Remove any trailing periods or spaces
filename = filename.rstrip(". ")
return filename
+177
View File
@@ -0,0 +1,177 @@
import os
import shutil
from dotenv import load_dotenv
from lyrics_transcriber import LyricsTranscriber as LyricsTranscriberLib
from lyrics_transcriber import OutputConfig, TranscriberConfig, LyricsConfig
from lyrics_transcriber.core.controller import LyricsControllerResult
from karaoke_gen.core.track import Track
from karaoke_gen.core.exceptions import TranscriptionError
class LyricsTranscriber:
"""
Handles lyrics transcription and synchronization.
"""
def __init__(self, config):
"""
Initialize the lyrics transcriber.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger
async def transcribe_lyrics(self, track):
"""
Transcribe lyrics for a track.
Args:
track: The track to process
Returns:
The track with updated transcription information
"""
self.logger.info(f"Transcribing lyrics for {track.base_name}")
if not track.input_audio_wav or not os.path.exists(track.input_audio_wav):
self.logger.warning("No input audio file found, cannot transcribe")
return track
try:
# Check for existing files first using sanitized names
parent_video_path = os.path.join(track.track_output_dir, f"{track.base_name} (With Vocals).mkv")
parent_lrc_path = os.path.join(track.track_output_dir, f"{track.base_name} (Karaoke).lrc")
# Check lyrics directory for existing files
lyrics_dir = os.path.join(track.track_output_dir, "lyrics")
lyrics_video_path = os.path.join(lyrics_dir, f"{track.base_name} (With Vocals).mkv")
lyrics_lrc_path = os.path.join(lyrics_dir, f"{track.base_name} (Karaoke).lrc")
# If files exist in parent directory, return early
if os.path.exists(parent_video_path) and os.path.exists(parent_lrc_path):
self.logger.info(f"Found existing video and LRC files in parent directory, skipping transcription")
track.processed_lyrics = {
"lrc_filepath": parent_lrc_path,
"ass_filepath": parent_video_path,
}
return track
# If files exist in lyrics directory, copy to parent and return
if os.path.exists(lyrics_video_path) and os.path.exists(lyrics_lrc_path):
self.logger.info(f"Found existing video and LRC files in lyrics directory, copying to parent")
os.makedirs(track.track_output_dir, exist_ok=True)
shutil.copy2(lyrics_video_path, parent_video_path)
shutil.copy2(lyrics_lrc_path, parent_lrc_path)
track.processed_lyrics = {
"lrc_filepath": parent_lrc_path,
"ass_filepath": parent_video_path,
}
return track
# Create lyrics subdirectory for new transcription
os.makedirs(lyrics_dir, exist_ok=True)
self.logger.info(f"Created lyrics directory: {lyrics_dir}")
# Load environment variables
load_dotenv()
env_config = {
"audioshake_api_token": os.getenv("AUDIOSHAKE_API_TOKEN"),
"genius_api_token": os.getenv("GENIUS_API_TOKEN"),
"spotify_cookie": os.getenv("SPOTIFY_COOKIE_SP_DC"),
"runpod_api_key": os.getenv("RUNPOD_API_KEY"),
"whisper_runpod_id": os.getenv("WHISPER_RUNPOD_ID"),
}
# Create config objects for LyricsTranscriber
transcriber_config = TranscriberConfig(
audioshake_api_token=env_config.get("audioshake_api_token"),
)
# Get lyrics artist and title from config if specified
lyrics_artist = self.config.lyrics_artist or track.artist
lyrics_title = self.config.lyrics_title or track.title
lyrics_config = LyricsConfig(
genius_api_token=env_config.get("genius_api_token"),
spotify_cookie=env_config.get("spotify_cookie"),
lyrics_file=self.config.lyrics_file,
)
output_config = OutputConfig(
output_styles_json=self.config.style_params_json,
output_dir=lyrics_dir,
render_video=self.config.render_video,
fetch_lyrics=True,
run_transcription=not self.config.skip_transcription,
run_correction=True,
generate_plain_text=True,
generate_lrc=True,
generate_cdg=True,
video_resolution="4k",
enable_review=not self.config.skip_transcription_review,
subtitle_offset_ms=self.config.subtitle_offset_ms,
)
# Add this log entry to debug the OutputConfig
self.logger.info(f"Instantiating LyricsTranscriber with OutputConfig: {output_config}")
# Initialize transcriber with new config objects
transcriber = LyricsTranscriberLib(
audio_filepath=track.input_audio_wav,
artist=lyrics_artist,
title=lyrics_title,
transcriber_config=transcriber_config,
lyrics_config=lyrics_config,
output_config=output_config,
logger=self.logger,
)
# Process and get results
results: LyricsControllerResult = transcriber.process()
self.logger.info(f"Transcriber Results Filepaths:")
for key, value in results.__dict__.items():
if key.endswith("_filepath"):
self.logger.info(f" {key}: {value}")
# Build output dictionary
transcriber_outputs = {}
if results.lrc_filepath:
transcriber_outputs["lrc_filepath"] = results.lrc_filepath
self.logger.info(f"Moving LRC file from {results.lrc_filepath} to {parent_lrc_path}")
shutil.copy2(results.lrc_filepath, parent_lrc_path)
if results.video_filepath:
transcriber_outputs["video_filepath"] = results.video_filepath
self.logger.info(f"Moving video file from {results.video_filepath} to {parent_video_path}")
shutil.copy2(results.video_filepath, parent_video_path)
if results.ass_filepath:
transcriber_outputs["ass_filepath"] = results.ass_filepath
if results.transcription_corrected:
transcriber_outputs["corrected_lyrics_text"] = "\n".join(
segment.text for segment in results.transcription_corrected.corrected_segments
)
transcriber_outputs["corrected_lyrics_text_filepath"] = results.corrected_txt
if transcriber_outputs:
self.logger.info(f"*** Transcriber Filepath Outputs: ***")
for key, value in transcriber_outputs.items():
if key.endswith("_filepath"):
self.logger.info(f" {key}: {value}")
track.processed_lyrics = transcriber_outputs
return track
except Exception as e:
raise TranscriptionError(f"Failed to transcribe lyrics: {str(e)}") from e
async def cleanup(self):
"""
Perform cleanup operations for the transcriber.
"""
self.logger.info("Cleaning up transcriber resources")
# No resources to clean up currently
pass
+152
View File
@@ -0,0 +1,152 @@
import os
import asyncio
import logging
from typing import List, Optional
from karaoke_gen.core.track import Track
from karaoke_gen.services.audio.service import AudioService
from karaoke_gen.services.lyrics.service import LyricsService
from karaoke_gen.services.video.service import VideoService
class MainService:
"""
Main service for orchestrating the entire karaoke preparation process.
"""
def __init__(self, config):
"""
Initialize the karaoke service.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger
# Initialize component services
self.audio_service = AudioService(config)
self.lyrics_service = LyricsService(config)
self.video_service = VideoService(config)
async def process_track(self, track: Track) -> Track:
"""
Process a single track through the entire karaoke preparation pipeline.
Args:
track: The track to process
Returns:
The processed track
"""
self.logger.info(f"Processing track: {track.base_name}")
try:
# Create output directory if it doesn't exist
if not os.path.exists(track.track_output_dir):
os.makedirs(track.track_output_dir)
# Process audio
track = await self.audio_service.process_audio(track)
# Process lyrics
track = await self.lyrics_service.process_lyrics(track)
# Process video
track = await self.video_service.process_video(track)
self.logger.info(f"Successfully processed track: {track.base_name}")
return track
except Exception as e:
self.logger.error(f"Failed to process track {track.base_name}: {str(e)}")
return track
async def process_tracks(self, tracks: List[Track]) -> List[Track]:
"""
Process multiple tracks through the entire karaoke preparation pipeline.
Args:
tracks: The list of tracks to process
Returns:
The list of processed tracks
"""
self.logger.info(f"Processing {len(tracks)} tracks")
processed_tracks = []
# Process tracks sequentially or in parallel based on configuration
if self.config.parallel_processing:
# Process tracks in parallel with a limit on concurrency
semaphore = asyncio.Semaphore(self.config.max_concurrent_tracks)
async def process_with_semaphore(track):
async with semaphore:
return await self.process_track(track)
tasks = [process_with_semaphore(track) for track in tracks]
processed_tracks = await asyncio.gather(*tasks)
else:
# Process tracks sequentially
for track in tracks:
processed_track = await self.process_track(track)
processed_tracks.append(processed_track)
self.logger.info(f"Finished processing {len(processed_tracks)} tracks")
return processed_tracks
async def cleanup(self):
"""
Perform cleanup operations after processing is complete.
"""
self.logger.info("Performing cleanup operations")
# Cleanup temporary files if configured
if self.config.cleanup_temp_files:
self.logger.info("Cleaning up temporary files")
# Implement cleanup logic here
# Close any open resources
await self.audio_service.cleanup()
await self.lyrics_service.cleanup()
await self.video_service.cleanup()
self.logger.info("Cleanup complete")
def get_summary(self, tracks: List[Track]) -> str:
"""
Generate a summary of the processed tracks.
Args:
tracks: The list of processed tracks
Returns:
A summary string
"""
summary = []
summary.append(f"Processed {len(tracks)} tracks:")
for track in tracks:
track_summary = f"- {track.base_name}:"
# Add audio processing summary
if track.instrumental:
track_summary += " [Audio: ✓]"
else:
track_summary += " [Audio: ✗]"
# Add lyrics processing summary
if track.processed_lyrics:
track_summary += " [Lyrics: ✓]"
else:
track_summary += " [Lyrics: ✗]"
# Add video processing summary
if track.final_video:
track_summary += " [Video: ✓]"
else:
track_summary += " [Video: ✗]"
summary.append(track_summary)
return "\n".join(summary)
+3
View File
@@ -0,0 +1,3 @@
from karaoke_gen.services.media.service import MediaService
from karaoke_gen.services.media.downloader import MediaDownloader
from karaoke_gen.services.media.extractor import MediaExtractor
+167
View File
@@ -0,0 +1,167 @@
import os
import asyncio
import mimetypes
from karaoke_gen.core.track import Track
from karaoke_gen.core.exceptions import MediaError
class MediaDetector:
"""
Handles detecting media types.
"""
def __init__(self, config):
"""
Initialize the media detector.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger
# Initialize mimetypes
mimetypes.init()
async def detect_media_type(self, file_path):
"""
Detect the type of a media file.
Args:
file_path: The path to the media file
Returns:
The media type (audio, video, image, or unknown)
"""
self.logger.debug(f"Detecting media type for {file_path}")
if not os.path.isfile(file_path):
raise MediaError(f"File not found: {file_path}")
# Get file extension
_, ext = os.path.splitext(file_path)
ext = ext.lower()
# Check file extension
if ext in ['.mp3', '.wav', '.flac', '.ogg', '.m4a', '.aac']:
self.logger.debug(f"Detected audio file by extension: {ext}")
return "audio"
elif ext in ['.mp4', '.avi', '.mov', '.mkv', '.webm', '.flv', '.wmv', '.m4v']:
self.logger.debug(f"Detected video file by extension: {ext}")
return "video"
elif ext in ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff']:
self.logger.debug(f"Detected image file by extension: {ext}")
return "image"
# Check mimetype
mime_type, _ = mimetypes.guess_type(file_path)
if mime_type:
if mime_type.startswith('audio/'):
self.logger.debug(f"Detected audio file by mimetype: {mime_type}")
return "audio"
elif mime_type.startswith('video/'):
self.logger.debug(f"Detected video file by mimetype: {mime_type}")
return "video"
elif mime_type.startswith('image/'):
self.logger.debug(f"Detected image file by mimetype: {mime_type}")
return "image"
# Use ffprobe as a fallback
media_type = await self._detect_media_type_with_ffprobe(file_path)
if media_type:
self.logger.debug(f"Detected {media_type} file with ffprobe")
return media_type
self.logger.warning(f"Could not detect media type for {file_path}")
return "unknown"
async def _detect_media_type_with_ffprobe(self, file_path):
"""
Detect the type of a media file using ffprobe.
Args:
file_path: The path to the media file
Returns:
The media type (audio, video, image, or None if detection failed)
"""
# Build ffprobe command
command = f'ffprobe -v error -show_entries stream=codec_type -of default=noprint_wrappers=1 "{file_path}"'
try:
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
self.logger.debug(f"ffprobe failed: {stderr.decode()}")
return None
output = stdout.decode()
if "codec_type=video" in output and "codec_type=audio" in output:
return "video"
elif "codec_type=audio" in output:
return "audio"
elif "codec_type=video" in output:
# Check if it's a single frame (image) or a video
duration_command = f'ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "{file_path}"'
process = await asyncio.create_subprocess_shell(
duration_command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode == 0:
try:
duration = float(stdout.decode().strip())
if duration < 0.1: # Very short duration, likely an image
return "image"
else:
return "video"
except (ValueError, TypeError):
pass
return "video" # Default to video if duration check fails
return None
except Exception as e:
self.logger.debug(f"Error detecting media type with ffprobe: {str(e)}")
return None
async def detect_media_info(self, track: Track) -> Track:
"""
Detect media information for the track.
Args:
track: The track to process
Returns:
The track with updated media information
"""
self.logger.info(f"Detecting media info for {track.base_name}")
# Detect media type for input media
if track.input_media and os.path.isfile(track.input_media):
media_type = await self.detect_media_type(track.input_media)
track.input_media_type = media_type
self.logger.info(f"Detected input media type: {media_type}")
# Detect media type for input audio
if track.input_audio_wav and os.path.isfile(track.input_audio_wav):
media_type = await self.detect_media_type(track.input_audio_wav)
track.input_audio_type = media_type
self.logger.info(f"Detected input audio type: {media_type}")
# Detect media type for input still image
if track.input_still_image and os.path.isfile(track.input_still_image):
media_type = await self.detect_media_type(track.input_still_image)
track.input_image_type = media_type
self.logger.info(f"Detected input image type: {media_type}")
return track
+231
View File
@@ -0,0 +1,231 @@
import os
import asyncio
import re
import yt_dlp
from karaoke_gen.core.track import Track
from karaoke_gen.core.exceptions import DownloadError
class MediaDownloader:
"""
Handles downloading media from URLs.
"""
def __init__(self, config):
"""
Initialize the media downloader.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger
async def download_media(self, track):
"""
Download media from a URL.
Args:
track: The track to process
Returns:
The track with updated media information
"""
self.logger.info(f"Downloading media from {track.input_media}")
if not track.is_url:
self.logger.warning(f"Input media is not a URL: {track.input_media}")
return track
try:
# Extract info for online media
track = await self._extract_info_for_online_media(track)
# Download the video with extractor and media_id in the filename
output_filename = f"{self._sanitize_filename(track.base_name)} ({track.extractor}"
# Add media_id if available
if track.media_id:
output_filename += f" {track.media_id}"
output_filename += ")"
output_filename_no_extension = os.path.join(
track.track_output_dir,
output_filename
)
downloaded_file = await self._download_video(track.input_media, output_filename_no_extension)
# Update track information
track.input_media = downloaded_file
return track
except Exception as e:
raise DownloadError(f"Failed to download media: {str(e)}") from e
async def _extract_info_for_online_media(self, track):
"""
Extract information for online media.
Args:
track: The track to process
Returns:
The track with updated information
"""
self.logger.info(f"Extracting info for online media: {track.input_media}")
# Skip artist and title extraction if already provided
extract_metadata = not (track.artist and track.title)
# Extract info from URL
try:
ydl_opts = {
"quiet": True,
"no_warnings": True,
"extract_flat": "in_playlist",
"skip_download": True,
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl_instance:
info = ydl_instance.extract_info(track.input_media, download=False)
# Handle playlists
if "entries" in info:
# Get the first video in the playlist
if not info["entries"]:
raise DownloadError("Playlist is empty")
info = info["entries"][0]
# Extract extractor and media_id (always do this)
if "extractor_key" in info:
track.extractor = info["extractor_key"]
elif "ie_key" in info:
track.extractor = info["ie_key"]
else:
self.logger.warning("Could not extract extractor from media info")
if "id" in info:
track.media_id = info["id"]
# Extract artist and title if needed
if extract_metadata:
artist, title = self._parse_video_title(info.get("title", ""))
if not track.artist:
track.artist = artist
if not track.title:
track.title = title
self.logger.info(f"Extracted info - artist: {track.artist}, title: {track.title}, extractor: {track.extractor}, id: {track.media_id}")
return track
except Exception as e:
raise DownloadError(f"Failed to extract info for online media: {str(e)}") from e
async def _download_video(self, url, output_filename_no_extension):
"""
Download a video from a URL.
Args:
url: The URL to download from
output_filename_no_extension: The output filename without extension
Returns:
The path to the downloaded file
"""
self.logger.info(f"Downloading video from {url}")
# Define output template
output_template = f"{output_filename_no_extension}.%(ext)s"
# Set up yt-dlp options
ydl_opts = {
"format": "bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best",
"outtmpl": output_template,
"quiet": self.config.log_level > 10, # Only show output if log level is DEBUG
"no_warnings": self.config.log_level > 10,
"ignoreerrors": False,
"noplaylist": True,
}
if self.config.dry_run:
self.logger.info(f"[DRY RUN] Would download video from {url} to {output_template}")
return f"{output_filename_no_extension}.mp4"
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl_instance:
info = ydl_instance.extract_info(url, download=True)
# Get the downloaded file path
if info and "requested_downloads" in info:
for download in info["requested_downloads"]:
if "filepath" in download:
downloaded_file = download["filepath"]
self.logger.info(f"Successfully downloaded video: {downloaded_file}")
return downloaded_file
# Fallback: try to guess the file path
extensions = ["mp4", "webm", "mkv", "m4a", "mp3"]
for ext in extensions:
possible_path = f"{output_filename_no_extension}.{ext}"
if os.path.isfile(possible_path):
self.logger.info(f"Found downloaded file: {possible_path}")
return possible_path
raise DownloadError("Failed to determine downloaded file path")
except Exception as e:
raise DownloadError(f"Failed to download video: {str(e)}") from e
def _parse_video_title(self, video_title):
"""
Parse artist and title from a video title.
Args:
video_title: The video title
Returns:
Tuple of (artist, title)
"""
self.logger.debug(f"Parsing video title: {video_title}")
# Try to match "Artist - Title" pattern
match = re.search(r"(.+?)\s*[-–—]\s*(.+)", video_title)
if match:
artist = match.group(1).strip()
title = match.group(2).strip()
# Clean up title (remove things like "Official Video", etc.)
title = re.sub(r"\(Official\s+Video\)", "", title, flags=re.IGNORECASE).strip()
title = re.sub(r"\(Official\s+Music\s+Video\)", "", title, flags=re.IGNORECASE).strip()
title = re.sub(r"\(Official\s+Lyric\s+Video\)", "", title, flags=re.IGNORECASE).strip()
title = re.sub(r"\(Lyric\s+Video\)", "", title, flags=re.IGNORECASE).strip()
title = re.sub(r"\(Audio\)", "", title, flags=re.IGNORECASE).strip()
title = re.sub(r"\(Official\s+Audio\)", "", title, flags=re.IGNORECASE).strip()
return artist, title
# If no match, use the whole title as both artist and title
return video_title, video_title
def _sanitize_filename(self, filename):
"""
Sanitize a filename by removing invalid characters.
Args:
filename: The filename to sanitize
Returns:
The sanitized filename
"""
# Replace characters that are invalid in filenames
invalid_chars = ['<', '>', ':', '"', '/', '\\', '|', '?', '*']
for char in invalid_chars:
filename = filename.replace(char, '_')
return filename
+322
View File
@@ -0,0 +1,322 @@
import os
import asyncio
import shutil
from PIL import Image
from karaoke_gen.core.track import Track
from karaoke_gen.core.exceptions import MediaError
class MediaExtractor:
"""
Handles extracting content from media files.
"""
def __init__(self, config):
"""
Initialize the media extractor.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger
# Path to ffmpeg
self.ffmpeg_path = "ffmpeg"
# Set up ffmpeg base command
self.ffmpeg_base_command = f"{self.ffmpeg_path} -hide_banner -nostats"
if self.config.log_level <= 10: # DEBUG
self.ffmpeg_base_command += " -loglevel verbose"
else:
self.ffmpeg_base_command += " -loglevel fatal"
async def extract_still_image(self, track):
"""
Extract a still image from a video file.
Args:
track: The track to process
Returns:
The track with updated media information
"""
self.logger.info(f"Extracting still image for {track.base_name}")
# Skip if input is not a video file
if not self._is_video_file(track.input_media):
self.logger.info(f"Input is not a video file, skipping still image extraction")
return track
# Define output path with (Original) label
output_filename_no_extension = os.path.join(
track.track_output_dir,
f"{track.base_name} (Original)"
)
output_image = f"{output_filename_no_extension}.jpg"
# Skip if output already exists
if os.path.isfile(output_image):
self.logger.info(f"Still image already exists: {output_image}")
track.input_still_image = output_image
return track
# Build ffmpeg command
command = f'{self.ffmpeg_base_command} -i "{track.input_media}" -vf "select=eq(n\\,0)" -q:v 1 "{output_image}"'
# Execute command
if not self.config.dry_run:
try:
self.logger.debug(f"Executing command: {command}")
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_message = stderr.decode() if stderr else "Unknown error"
raise MediaError(f"Failed to extract still image: {error_message}")
self.logger.info(f"Successfully extracted still image: {output_image}")
track.input_still_image = output_image
except Exception as e:
self.logger.error(f"Failed to extract still image: {str(e)}")
# Continue without still image
else:
self.logger.info(f"[DRY RUN] Would extract still image: {output_image}")
track.input_still_image = output_image
return track
async def extract_audio_from_video(self, track):
"""
Extract audio from a video file.
Args:
track: The track to process
Returns:
The track with updated media information
"""
self.logger.info(f"Extracting audio from video for {track.base_name}")
# Skip if input is not a video file
if not self._is_video_file(track.input_media):
self.logger.info(f"Input is not a video file, skipping audio extraction")
return track
# Define output path with (Original) label
output_filename_no_extension = os.path.join(
track.track_output_dir,
f"{track.base_name} (Original)"
)
output_wav = f"{output_filename_no_extension}.wav"
# Skip if output already exists
if os.path.isfile(output_wav):
self.logger.info(f"Audio file already exists: {output_wav}")
track.input_audio_wav = output_wav
return track
# Build ffmpeg command
command = f'{self.ffmpeg_base_command} -i "{track.input_media}" -vn -acodec pcm_s16le -ar 44100 -ac 2 "{output_wav}"'
# Execute command
if not self.config.dry_run:
try:
self.logger.debug(f"Executing command: {command}")
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_message = stderr.decode() if stderr else "Unknown error"
raise MediaError(f"Failed to extract audio: {error_message}")
self.logger.info(f"Successfully extracted audio: {output_wav}")
track.input_audio_wav = output_wav
except Exception as e:
raise MediaError(f"Failed to extract audio: {str(e)}") from e
else:
self.logger.info(f"[DRY RUN] Would extract audio: {output_wav}")
track.input_audio_wav = output_wav
return track
async def copy_audio_file(self, track):
"""
Copy an audio file to the output directory.
Args:
track: The track to process
Returns:
The track with updated media information
"""
self.logger.info(f"Copying audio file for {track.base_name}")
# Define output path with (Original) label
output_filename_no_extension = os.path.join(
track.track_output_dir,
f"{track.base_name} (Original)"
)
# Determine output extension
input_ext = os.path.splitext(track.input_media)[1].lower()
output_file = f"{output_filename_no_extension}{input_ext}"
# Skip if output already exists
if os.path.isfile(output_file) and os.path.abspath(output_file) != os.path.abspath(track.input_media):
self.logger.info(f"Audio file already exists: {output_file}")
elif not self.config.dry_run:
try:
# Copy file
shutil.copy2(track.input_media, output_file)
self.logger.info(f"Successfully copied audio file: {output_file}")
except Exception as e:
raise MediaError(f"Failed to copy audio file: {str(e)}") from e
else:
self.logger.info(f"[DRY RUN] Would copy audio file: {output_file}")
# Convert to WAV if needed
output_wav = f"{output_filename_no_extension}.wav"
# Skip if output already exists
if os.path.isfile(output_wav):
self.logger.info(f"WAV file already exists: {output_wav}")
track.input_audio_wav = output_wav
return track
# Build ffmpeg command
command = f'{self.ffmpeg_base_command} -i "{output_file}" -vn -acodec pcm_s16le -ar 44100 -ac 2 "{output_wav}"'
# Execute command
if not self.config.dry_run:
try:
self.logger.debug(f"Executing command: {command}")
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_message = stderr.decode() if stderr else "Unknown error"
raise MediaError(f"Failed to convert audio to WAV: {error_message}")
self.logger.info(f"Successfully converted audio to WAV: {output_wav}")
track.input_audio_wav = output_wav
except Exception as e:
raise MediaError(f"Failed to convert audio to WAV: {str(e)}") from e
else:
self.logger.info(f"[DRY RUN] Would convert audio to WAV: {output_wav}")
track.input_audio_wav = output_wav
return track
async def copy_image_file(self, track):
"""
Copy an image file to the output directory.
Args:
track: The track to process
Returns:
The track with updated media information
"""
self.logger.info(f"Copying image file for {track.base_name}")
# Define output path with (Original) label
output_filename_no_extension = os.path.join(
track.track_output_dir,
f"{track.base_name} (Original)"
)
# Determine output extension
input_ext = os.path.splitext(track.input_media)[1].lower()
output_file = f"{output_filename_no_extension}{input_ext}"
# Skip if output already exists
if os.path.isfile(output_file) and os.path.abspath(output_file) != os.path.abspath(track.input_media):
self.logger.info(f"Image file already exists: {output_file}")
elif not self.config.dry_run:
try:
# Copy file
shutil.copy2(track.input_media, output_file)
self.logger.info(f"Successfully copied image file: {output_file}")
except Exception as e:
raise MediaError(f"Failed to copy image file: {str(e)}") from e
else:
self.logger.info(f"[DRY RUN] Would copy image file: {output_file}")
# Set still image
track.input_still_image = output_file
return track
def _is_video_file(self, file_path):
"""
Check if a file is a video file.
Args:
file_path: The path to the file
Returns:
True if the file is a video file, False otherwise
"""
if not file_path or not os.path.isfile(file_path):
return False
video_extensions = ['.mp4', '.avi', '.mov', '.mkv', '.webm', '.flv', '.wmv', '.m4v']
_, ext = os.path.splitext(file_path)
return ext.lower() in video_extensions
async def extract_media(self, track: Track) -> Track:
"""
Extract media from the input file based on its type.
Args:
track: The track to process
Returns:
The track with updated media information
"""
self.logger.info(f"Extracting media for {track.base_name}")
# Check if the input is a video file
if self._is_video_file(track.input_media):
# Extract still image and audio from video
track = await self.extract_still_image(track)
track = await self.extract_audio_from_video(track)
elif self._is_image_file(track.input_media):
# Copy image file
track = await self.copy_image_file(track)
else:
# Assume it's an audio file
track = await self.copy_audio_file(track)
return track
def _is_image_file(self, file_path):
"""
Check if a file is an image file.
Args:
file_path: The path to the file
Returns:
True if the file is an image file, False otherwise
"""
image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp']
ext = os.path.splitext(file_path)[1].lower()
return ext in image_extensions
+115
View File
@@ -0,0 +1,115 @@
import logging
import os
import asyncio
import shutil
import glob
from typing import Dict, Any, Optional, Tuple
from karaoke_gen.core.project import ProjectConfig
from karaoke_gen.core.track import Track
from karaoke_gen.core.exceptions import MediaError, DownloadError, ConversionError
from karaoke_gen.services.media.downloader import MediaDownloader
from karaoke_gen.services.media.extractor import MediaExtractor
from karaoke_gen.services.media.detector import MediaDetector
class MediaService:
"""
Service for media handling operations including downloading, extraction, and detection.
"""
def __init__(self, config: ProjectConfig):
"""
Initialize the media service.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger or logging.getLogger(__name__)
# Initialize components
self.downloader = MediaDownloader(config)
self.extractor = MediaExtractor(config)
self.detector = MediaDetector(config)
async def download_media(self, track: Track) -> Track:
"""
Download media for the track.
Args:
track: The track to process
Returns:
The track with updated media information
"""
if self.config.skip_download:
self.logger.info("Skipping media download")
return track
self.logger.info(f"Downloading media for {track.base_name}")
# Download media
track = await self.downloader.download_media(track)
return track
async def extract_media(self, track: Track) -> Track:
"""
Extract audio and other components from media.
Args:
track: The track to process
Returns:
The track with updated extracted media information
"""
if self.config.skip_separation:
self.logger.info("Skipping media extraction")
return track
self.logger.info(f"Extracting media for {track.base_name}")
# Extract media
track = await self.extractor.extract_media(track)
return track
async def detect_media_info(self, track: Track) -> Track:
"""
Detect media information.
Args:
track: The track to process
Returns:
The track with updated media information
"""
self.logger.info(f"Detecting media info for {track.base_name}")
# Detect media info
track = await self.detector.detect_media_info(track)
return track
async def process_media(self, track: Track) -> Track:
"""
Process media for the track.
Args:
track: The track to process
Returns:
The track with updated media information
"""
self.logger.info(f"Processing media for {track.base_name}")
# Download media
track = await self.download_media(track)
# Extract media
track = await self.extract_media(track)
# Detect media info
track = await self.detect_media_info(track)
return track
+5
View File
@@ -0,0 +1,5 @@
from karaoke_gen.services.video.service import VideoService
from karaoke_gen.services.video.renderer import VideoRenderer
from karaoke_gen.services.video.text import TextRenderer
from karaoke_gen.services.video.screens import ScreenGenerator
from karaoke_gen.services.video.compositor import VideoCompositor
+626
View File
@@ -0,0 +1,626 @@
import os
import asyncio
import tempfile
from karaoke_gen.core.exceptions import VideoError
class VideoCompositor:
"""
Handles video composition operations.
"""
def __init__(self, config):
"""
Initialize the video compositor.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger
# Path to ffmpeg
self.ffmpeg_path = "ffmpeg"
# Set up ffmpeg base command
self.ffmpeg_base_command = f"{self.ffmpeg_path} -hide_banner -nostats"
if self.config.log_level <= 10: # DEBUG
self.ffmpeg_base_command += " -loglevel verbose"
else:
self.ffmpeg_base_command += " -loglevel fatal"
# Initialize temporary files list
self._temp_files = []
async def compose_final_video(self, track):
"""
Compose the final video by combining title, content, and end videos.
Args:
track: The track to process
Returns:
The track with updated video information
"""
self.logger.info(f"Composing final video for {track.base_name}")
# Define output path
output_path = os.path.join(track.track_output_dir, f"{track.base_name} (Final Karaoke).mp4")
# Skip if output already exists
if os.path.isfile(output_path):
self.logger.info(f"Final video already exists: {output_path}")
track.final_video = output_path
return track
# Check for required videos
title_video = track.title_video
content_video = track.video_with_lyrics or track.video_with_instrumental
end_video = track.end_video
if not title_video or not os.path.isfile(title_video):
self.logger.warning("Title video not found, skipping final video composition")
return track
if not content_video or not os.path.isfile(content_video):
self.logger.warning("Content video not found, skipping final video composition")
return track
# Compose video
if not self.config.dry_run:
try:
# Build ffmpeg command
command = f'{self.ffmpeg_base_command} -i "{title_video}" -i "{content_video}" '
# Add end video if available
if end_video and os.path.isfile(end_video):
command += f'-i "{end_video}" '
filter_complex = '[0:v][0:a][1:v][1:a][2:v][2:a]concat=n=3:v=1:a=1[outv][outa]'
else:
filter_complex = '[0:v][0:a][1:v][1:a]concat=n=2:v=1:a=1[outv][outa]'
# Add filter complex and output options
command += (
f'-filter_complex "{filter_complex}" '
f'-map "[outv]" -map "[outa]" '
f'-c:v libx264 -preset medium -crf 22 -c:a aac -b:a 192k '
f'-pix_fmt yuv420p "{output_path}"'
)
# Execute command
self.logger.debug(f"Composing final video: {command}")
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_message = stderr.decode() if stderr else "Unknown error"
raise VideoError(f"Failed to compose final video: {error_message}")
track.final_video = output_path
self.logger.info(f"Successfully composed final video: {output_path}")
except Exception as e:
self.logger.error(f"Failed to compose final video: {str(e)}")
# Continue with other processing
else:
self.logger.info(f"[DRY RUN] Would compose final video: {output_path}")
track.final_video = output_path
return track
async def create_lossless_version(self, track):
"""
Create a lossless version of the final video.
Args:
track: The track to process
Returns:
The track with updated video information
"""
self.logger.info(f"Creating lossless version for {track.base_name}")
# Skip if no final video
if not track.final_video or not os.path.isfile(track.final_video):
self.logger.info("No final video available, skipping lossless version creation")
return track
# Define output path
output_path = os.path.join(track.track_output_dir, f"{track.base_name} (Final Karaoke).mkv")
# Skip if output already exists
if os.path.isfile(output_path):
self.logger.info(f"Lossless version already exists: {output_path}")
track.final_video_mkv = output_path
return track
# Create lossless version
if not self.config.dry_run:
try:
# Build ffmpeg command
command = (
f'{self.ffmpeg_base_command} -i "{track.final_video}" '
f'-c:v copy -c:a flac "{output_path}"'
)
# Execute command
self.logger.debug(f"Creating lossless version: {command}")
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_message = stderr.decode() if stderr else "Unknown error"
raise VideoError(f"Failed to create lossless version: {error_message}")
track.final_video_mkv = output_path
self.logger.info(f"Successfully created lossless version: {output_path}")
except Exception as e:
self.logger.error(f"Failed to create lossless version: {str(e)}")
# Continue with other processing
else:
self.logger.info(f"[DRY RUN] Would create lossless version: {output_path}")
track.final_video_mkv = output_path
return track
async def create_720p_version(self, track):
"""
Create a 720p version of the final video.
Args:
track: The track to process
Returns:
The track with updated video information
"""
self.logger.info(f"Creating 720p version for {track.base_name}")
# Skip if no final video
if not track.final_video or not os.path.isfile(track.final_video):
self.logger.info("No final video available, skipping 720p version creation")
return track
# Define output path
output_path = os.path.join(track.track_output_dir, f"{track.base_name} (Final Karaoke 720p).mp4")
# Skip if output already exists
if os.path.isfile(output_path):
self.logger.info(f"720p version already exists: {output_path}")
track.final_video_720p = output_path
return track
# Create 720p version
if not self.config.dry_run:
try:
# Build ffmpeg command
command = (
f'{self.ffmpeg_base_command} -i "{track.final_video}" '
f'-c:v libx264 -vf "scale=1280:720" -b:v 2000k -preset medium -tune animation '
f'-c:a aac -b:a 128k -pix_fmt yuv420p "{output_path}"'
)
# Execute command
self.logger.debug(f"Creating 720p version: {command}")
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_message = stderr.decode() if stderr else "Unknown error"
raise VideoError(f"Failed to create 720p version: {error_message}")
track.final_video_720p = output_path
self.logger.info(f"Successfully created 720p version: {output_path}")
except Exception as e:
self.logger.error(f"Failed to create 720p version: {str(e)}")
# Continue with other processing
else:
self.logger.info(f"[DRY RUN] Would create 720p version: {output_path}")
track.final_video_720p = output_path
return track
async def create_lossy_version(self, track):
"""
Create a lossy version of the final video.
Args:
track: The track to process
Returns:
The track with updated video information
"""
self.logger.info(f"Creating lossy version for {track.base_name}")
# Skip if no final video
if not track.final_video or not os.path.isfile(track.final_video):
self.logger.warning(f"No final video found for {track.base_name}")
return track
# Define output path
output_path = os.path.join(track.track_output_dir, f"{track.base_name} (Final Karaoke Lossy).mp4")
# Skip if output already exists
if os.path.isfile(output_path) and not self.config.force_regenerate:
self.logger.info(f"Lossy version already exists: {output_path}")
track.final_video_lossy = output_path
return track
# Create lossy version
if not self.config.dry_run:
try:
# Build ffmpeg command
command = (
f'{self.ffmpeg_base_command} -i "{track.final_video}" '
f'-c:v libx264 -preset slow -crf 23 -c:a aac -b:a 128k '
f'-pix_fmt yuv420p "{output_path}"'
)
# Execute command
self.logger.debug(f"Creating lossy version: {command}")
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_message = stderr.decode() if stderr else "Unknown error"
raise VideoError(f"Failed to create lossy version: {error_message}")
track.final_video_lossy = output_path
self.logger.info(f"Successfully created lossy version: {output_path}")
except Exception as e:
self.logger.error(f"Failed to create lossy version: {str(e)}")
# Continue with other processing
else:
self.logger.info(f"[DRY RUN] Would create lossy version: {output_path}")
track.final_video_lossy = output_path
return track
async def add_subtitles_to_video(self, track, subtitles_file, output_file=None):
"""
Add subtitles to a video.
Args:
track: The track to process
subtitles_file: The subtitles file
output_file: The output file path
Returns:
The track with updated subtitled video information
"""
self.logger.info(f"Adding subtitles to video for {track.base_name}")
# Set default output file
if output_file is None:
output_file = os.path.join(track.track_output_dir, f"{track.base_name} (Subtitled).mov")
# Skip if output already exists
if os.path.isfile(output_file):
self.logger.info(f"Subtitled video already exists: {output_file}")
track.subtitled_video = output_file
return track
# Check if required files exist
if not track.video or not os.path.isfile(track.video):
self.logger.error(f"Video not found: {track.video}")
raise VideoError(f"Video not found: {track.video}")
if not os.path.isfile(subtitles_file):
self.logger.error(f"Subtitles file not found: {subtitles_file}")
raise VideoError(f"Subtitles file not found: {subtitles_file}")
# Add subtitles to video
if not self.config.dry_run:
try:
await self._add_subtitles_to_video(track.video, subtitles_file, output_file)
track.subtitled_video = output_file
self.logger.info(f"Successfully added subtitles to video: {output_file}")
except Exception as e:
raise VideoError(f"Failed to add subtitles to video: {str(e)}") from e
else:
self.logger.info(f"[DRY RUN] Would add subtitles to video: {output_file}")
track.subtitled_video = output_file
return track
async def overlay_videos(self, background_video, overlay_video, output_file, position=None,
start_time=None, end_time=None, opacity=None):
"""
Overlay one video on top of another.
Args:
background_video: The background video file
overlay_video: The overlay video file
output_file: The output file path
position: The position (x:y)
start_time: The start time in seconds
end_time: The end time in seconds
opacity: The opacity (0.0-1.0)
Returns:
The output file path
"""
self.logger.info(f"Overlaying video on {background_video}")
# Skip if output already exists
if os.path.isfile(output_file):
self.logger.info(f"Overlaid video already exists: {output_file}")
return output_file
# Check if required files exist
if not os.path.isfile(background_video):
self.logger.error(f"Background video not found: {background_video}")
raise VideoError(f"Background video not found: {background_video}")
if not os.path.isfile(overlay_video):
self.logger.error(f"Overlay video not found: {overlay_video}")
raise VideoError(f"Overlay video not found: {overlay_video}")
# Set default values
position = position or self.config.overlay_position or "10:10"
opacity = opacity or self.config.overlay_opacity or 1.0
# Overlay video
if not self.config.dry_run:
try:
# Create filter complex
filter_complex = (
f"[0:v][1:v]overlay={position}"
)
# Add start time if specified
if start_time is not None:
filter_complex += f":enable='between(t,{start_time},{end_time or 999999})'"
# Add opacity if less than 1.0
if opacity < 1.0:
filter_complex += f":alpha={opacity}"
# Overlay video
command = (
f'{self.ffmpeg_base_command} -i "{background_video}" -i "{overlay_video}" '
f'-filter_complex "{filter_complex}" -c:v prores_ks -profile:v 3 '
f'-vendor ap10 -bits_per_mb 8000 -pix_fmt yuv422p10le -c:a copy "{output_file}"'
)
self.logger.debug(f"Overlaying video: {command}")
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_message = stderr.decode() if stderr else "Unknown error"
raise VideoError(f"Failed to overlay video: {error_message}")
self.logger.info(f"Successfully overlaid video: {output_file}")
except Exception as e:
raise VideoError(f"Failed to overlay video: {str(e)}") from e
else:
self.logger.info(f"[DRY RUN] Would overlay video: {output_file}")
return output_file
async def create_picture_in_picture(self, main_video, pip_video, output_file, position=None,
size=None, start_time=None, end_time=None, border=None,
border_color=None):
"""
Create a picture-in-picture video.
Args:
main_video: The main video file
pip_video: The picture-in-picture video file
output_file: The output file path
position: The position (x:y)
size: The size (width:height)
start_time: The start time in seconds
end_time: The end time in seconds
border: The border width
border_color: The border color
Returns:
The output file path
"""
self.logger.info(f"Creating picture-in-picture video with {main_video} and {pip_video}")
# Skip if output already exists
if os.path.isfile(output_file):
self.logger.info(f"Picture-in-picture video already exists: {output_file}")
return output_file
# Check if required files exist
if not os.path.isfile(main_video):
self.logger.error(f"Main video not found: {main_video}")
raise VideoError(f"Main video not found: {main_video}")
if not os.path.isfile(pip_video):
self.logger.error(f"Picture-in-picture video not found: {pip_video}")
raise VideoError(f"Picture-in-picture video not found: {pip_video}")
# Set default values
position = position or self.config.pip_position or "main_w-overlay_w-10:main_h-overlay_h-10"
size = size or self.config.pip_size or "iw/4:ih/4"
border = border or self.config.pip_border or 0
border_color = border_color or self.config.pip_border_color or "black"
# Create picture-in-picture video
if not self.config.dry_run:
try:
# Create filter complex
filter_complex = (
f"[1:v]scale={size}"
)
# Add border if specified
if border > 0:
filter_complex += f",pad=iw+{border*2}:ih+{border*2}:{border}:{border}:{border_color}"
filter_complex += f"[pip]; [0:v][pip]overlay={position}"
# Add start time if specified
if start_time is not None:
filter_complex += f":enable='between(t,{start_time},{end_time or 999999})'"
# Create picture-in-picture video
command = (
f'{self.ffmpeg_base_command} -i "{main_video}" -i "{pip_video}" '
f'-filter_complex "{filter_complex}" -c:v prores_ks -profile:v 3 '
f'-vendor ap10 -bits_per_mb 8000 -pix_fmt yuv422p10le -c:a copy "{output_file}"'
)
self.logger.debug(f"Creating picture-in-picture video: {command}")
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_message = stderr.decode() if stderr else "Unknown error"
raise VideoError(f"Failed to create picture-in-picture video: {error_message}")
self.logger.info(f"Successfully created picture-in-picture video: {output_file}")
except Exception as e:
raise VideoError(f"Failed to create picture-in-picture video: {str(e)}") from e
else:
self.logger.info(f"[DRY RUN] Would create picture-in-picture video: {output_file}")
return output_file
async def _combine_videos(self, videos, output_file):
"""
Combine multiple videos into one.
Args:
videos: The list of video files
output_file: The output file path
Returns:
The output file path
"""
# Create a temporary file for the concat list
with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as temp_file:
concat_list = temp_file.name
self._temp_files.append(concat_list) # Track temporary file
# Write concat list
with open(concat_list, "w") as f:
for video in videos:
f.write(f"file '{video}'\n")
# Combine videos
command = (
f'{self.ffmpeg_base_command} -f concat -safe 0 -i "{concat_list}" '
f'-c:v prores_ks -profile:v 3 -vendor ap10 -bits_per_mb 8000 '
f'-pix_fmt yuv422p10le -c:a pcm_s24le "{output_file}"'
)
self.logger.debug(f"Combining videos: {command}")
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_message = stderr.decode() if stderr else "Unknown error"
raise VideoError(f"Failed to combine videos: {error_message}")
return output_file
async def _add_subtitles_to_video(self, video_file, subtitles_file, output_file):
"""
Add subtitles to a video.
Args:
video_file: The video file
subtitles_file: The subtitles file
output_file: The output file path
Returns:
The output file path
"""
# Determine subtitles format
subtitles_format = os.path.splitext(subtitles_file)[1].lower()
# Add subtitles to video
if subtitles_format == ".srt":
# Use subtitles filter for SRT
command = (
f'{self.ffmpeg_base_command} -i "{video_file}" '
f'-vf "subtitles={subtitles_file}" -c:v prores_ks -profile:v 3 '
f'-vendor ap10 -bits_per_mb 8000 -pix_fmt yuv422p10le -c:a copy "{output_file}"'
)
elif subtitles_format == ".ass":
# Use ASS filter for ASS/SSA
command = (
f'{self.ffmpeg_base_command} -i "{video_file}" '
f'-vf "ass={subtitles_file}" -c:v prores_ks -profile:v 3 '
f'-vendor ap10 -bits_per_mb 8000 -pix_fmt yuv422p10le -c:a copy "{output_file}"'
)
else:
# Use subtitles filter for other formats
command = (
f'{self.ffmpeg_base_command} -i "{video_file}" -i "{subtitles_file}" '
f'-c:v prores_ks -profile:v 3 -vendor ap10 -bits_per_mb 8000 '
f'-pix_fmt yuv422p10le -c:a copy -c:s mov_text "{output_file}"'
)
self.logger.debug(f"Adding subtitles to video: {command}")
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_message = stderr.decode() if stderr else "Unknown error"
raise VideoError(f"Failed to add subtitles to video: {error_message}")
return output_file
async def cleanup(self):
"""
Perform cleanup operations for the video compositor.
"""
self.logger.info("Cleaning up video compositor resources")
# Clean up any temporary files
if hasattr(self, '_temp_files') and self._temp_files:
for temp_file in self._temp_files:
if os.path.exists(temp_file):
try:
os.remove(temp_file)
self.logger.debug(f"Removed temporary file: {temp_file}")
except Exception as e:
self.logger.warning(f"Failed to remove temporary file {temp_file}: {str(e)}")
self.logger.info("Video compositor cleanup complete")
+803
View File
@@ -0,0 +1,803 @@
import os
import asyncio
import tempfile
import subprocess
import shutil
from karaoke_gen.core.exceptions import VideoError
class VideoRenderer:
"""
Handles video rendering operations.
"""
def __init__(self, config):
"""
Initialize the video renderer.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger
# Path to ffmpeg
self.ffmpeg_path = "ffmpeg"
# Set up ffmpeg base command
self.ffmpeg_base_command = f"{self.ffmpeg_path} -hide_banner -nostats"
if self.config.log_level <= 10: # DEBUG
self.ffmpeg_base_command += " -loglevel verbose"
else:
self.ffmpeg_base_command += " -loglevel fatal"
# Initialize temporary files list
self._temp_files = []
async def render_video(self, track, output_file=None, resolution=None, fps=None,
codec=None, bitrate=None, background_color=None):
"""
Render a video for a track.
Args:
track: The track to process
output_file: The output file path
resolution: The resolution
fps: The frames per second
codec: The codec
bitrate: The bitrate
background_color: The background color
Returns:
The output file path
"""
self.logger.info(f"Rendering video for {track.base_name}")
# Set default output file
if output_file is None:
output_file = os.path.join(track.track_output_dir, f"{track.base_name} (Video).mov")
# Skip if output already exists
if os.path.isfile(output_file):
self.logger.info(f"Video already exists: {output_file}")
track.video = output_file
return track
# Set default values
resolution = resolution or self.config.video_resolution or "1920x1080"
fps = fps or self.config.video_fps or 30
codec = codec or self.config.video_codec or "prores_ks"
bitrate = bitrate or self.config.video_bitrate or "8000k"
background_color = background_color or self.config.video_background_color or "black"
# Check if audio file exists
if not track.audio_file or not os.path.isfile(track.audio_file):
self.logger.error(f"Audio file not found: {track.audio_file}")
raise VideoError(f"Audio file not found: {track.audio_file}")
# Create video
if not self.config.dry_run:
try:
# Create a video from audio
await self._create_video_from_audio(
track.audio_file,
output_file,
track.duration,
resolution,
fps,
codec,
bitrate,
background_color
)
track.video = output_file
self.logger.info(f"Successfully rendered video: {output_file}")
except Exception as e:
raise VideoError(f"Failed to render video: {str(e)}") from e
else:
self.logger.info(f"[DRY RUN] Would render video: {output_file}")
track.video = output_file
return track
async def combine_videos(self, videos, output_file, transition_duration=None):
"""
Combine multiple videos into one.
Args:
videos: The list of video files to combine
output_file: The output file path
transition_duration: The transition duration in seconds
Returns:
The output file path
"""
self.logger.info(f"Combining {len(videos)} videos")
# Skip if output already exists
if os.path.isfile(output_file):
self.logger.info(f"Combined video already exists: {output_file}")
return output_file
# Check if videos exist
for video in videos:
if not os.path.isfile(video):
self.logger.error(f"Video file not found: {video}")
raise VideoError(f"Video file not found: {video}")
# Set default transition duration
transition_duration = transition_duration or self.config.transition_duration or 0.5
# Create video
if not self.config.dry_run:
try:
# Create a temporary file for the concat list
with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as temp_file:
concat_list = temp_file.name
self._temp_files.append(concat_list) # Track temporary file
# Write concat list
with open(concat_list, "w") as f:
for video in videos:
f.write(f"file '{video}'\n")
# Combine videos
if transition_duration > 0:
await self._combine_videos_with_transitions(videos, output_file, transition_duration)
else:
await self._combine_videos_simple(concat_list, output_file)
self.logger.info(f"Successfully combined videos: {output_file}")
except Exception as e:
raise VideoError(f"Failed to combine videos: {str(e)}") from e
else:
self.logger.info(f"[DRY RUN] Would combine videos: {output_file}")
return output_file
async def add_audio_to_video(self, video_file, audio_file, output_file):
"""
Add audio to a video.
Args:
video_file: The video file
audio_file: The audio file
output_file: The output file path
Returns:
The output file path
"""
self.logger.info(f"Adding audio to video: {video_file}")
# Skip if output already exists
if os.path.isfile(output_file):
self.logger.info(f"Video with audio already exists: {output_file}")
return output_file
# Check if files exist
if not os.path.isfile(video_file):
self.logger.error(f"Video file not found: {video_file}")
raise VideoError(f"Video file not found: {video_file}")
if not os.path.isfile(audio_file):
self.logger.error(f"Audio file not found: {audio_file}")
raise VideoError(f"Audio file not found: {audio_file}")
# Add audio to video
if not self.config.dry_run:
try:
command = (
f'{self.ffmpeg_base_command} -i "{video_file}" -i "{audio_file}" '
f'-c:v copy -c:a pcm_s24le -shortest "{output_file}"'
)
self.logger.debug(f"Adding audio to video: {command}")
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_message = stderr.decode() if stderr else "Unknown error"
raise VideoError(f"Failed to add audio to video: {error_message}")
self.logger.info(f"Successfully added audio to video: {output_file}")
except Exception as e:
raise VideoError(f"Failed to add audio to video: {str(e)}") from e
else:
self.logger.info(f"[DRY RUN] Would add audio to video: {output_file}")
return output_file
async def _create_video_from_audio(self, audio_file, output_file, duration, resolution,
fps, codec, bitrate, background_color):
"""
Create a video from an audio file.
Args:
audio_file: The audio file
output_file: The output file path
duration: The duration in seconds
resolution: The resolution
fps: The frames per second
codec: The codec
bitrate: The bitrate
background_color: The background color
Returns:
The output file path
"""
# Create a video from audio
command = (
f'{self.ffmpeg_base_command} -f lavfi -i color=c={background_color}:s={resolution}:r={fps} '
f'-i "{audio_file}" -t {duration} -c:v {codec} -profile:v 3 -vendor ap10 '
f'-b:v {bitrate} -pix_fmt yuv422p10le -c:a pcm_s24le "{output_file}"'
)
self.logger.debug(f"Creating video from audio: {command}")
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_message = stderr.decode() if stderr else "Unknown error"
raise VideoError(f"Failed to create video from audio: {error_message}")
return output_file
async def _combine_videos_simple(self, concat_list, output_file):
"""
Combine videos using the concat demuxer.
Args:
concat_list: The concat list file
output_file: The output file path
Returns:
The output file path
"""
# Combine videos
command = (
f'{self.ffmpeg_base_command} -f concat -safe 0 -i "{concat_list}" '
f'-c:v prores_ks -profile:v 3 -vendor ap10 -bits_per_mb 8000 '
f'-pix_fmt yuv422p10le -c:a pcm_s24le "{output_file}"'
)
self.logger.debug(f"Combining videos: {command}")
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_message = stderr.decode() if stderr else "Unknown error"
raise VideoError(f"Failed to combine videos: {error_message}")
return output_file
async def _combine_videos_with_transitions(self, videos, output_file, transition_duration):
"""
Combine videos with crossfade transitions.
Args:
videos: The list of video files
output_file: The output file path
transition_duration: The transition duration in seconds
Returns:
The output file path
"""
# Create a complex filter for crossfade transitions
filter_complex = ""
inputs = ""
# Add input files
for i, video in enumerate(videos):
inputs += f' -i "{video}"'
# Create filter complex
for i in range(len(videos)):
filter_complex += f"[{i}:v]setpts=PTS-STARTPTS[v{i}];"
# Add crossfade transitions
for i in range(len(videos) - 1):
filter_complex += (
f"[v{i}][v{i+1}]xfade=transition=fade:duration={transition_duration}:offset="
f"{self._get_video_duration(videos[i]) - transition_duration}[v{i}out];"
)
# Finalize filter complex
if len(videos) > 2:
for i in range(len(videos) - 2):
filter_complex += f"[v{i}out][v{i+2}]concat=n=2:v=1:a=0[v{i+1}out];"
filter_complex = filter_complex[:-1] # Remove last semicolon
output_label = f"[v{len(videos)-2}out]"
else:
output_label = "[v0out]"
# Combine videos with transitions
command = (
f'{self.ffmpeg_base_command}{inputs} -filter_complex "{filter_complex}" '
f'-map "{output_label}" -c:v prores_ks -profile:v 3 -vendor ap10 '
f'-bits_per_mb 8000 -pix_fmt yuv422p10le "{output_file}"'
)
self.logger.debug(f"Combining videos with transitions: {command}")
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_message = stderr.decode() if stderr else "Unknown error"
raise VideoError(f"Failed to combine videos with transitions: {error_message}")
return output_file
async def _get_video_duration(self, video_file):
"""
Get the duration of a video file.
Args:
video_file: The video file
Returns:
The duration in seconds
"""
# Get video duration
command = (
f'{self.ffmpeg_path} -i "{video_file}" -hide_banner 2>&1 | '
f'grep "Duration" | cut -d " " -f 4 | sed s/,//'
)
self.logger.debug(f"Getting video duration: {command}")
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
shell=True
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_message = stderr.decode() if stderr else "Unknown error"
raise VideoError(f"Failed to get video duration: {error_message}")
# Parse duration
duration_str = stdout.decode().strip()
if not duration_str:
raise VideoError(f"Failed to get video duration: {video_file}")
# Convert HH:MM:SS.ms to seconds
hours, minutes, seconds = duration_str.split(":")
seconds, milliseconds = seconds.split(".")
duration = (
int(hours) * 3600 +
int(minutes) * 60 +
int(seconds) +
int(milliseconds) / 100
)
return duration
async def render_lyrics_video(self, track):
"""
Render a video with lyrics.
Args:
track: The track to process
Returns:
The track with updated video information
"""
self.logger.info(f"Rendering lyrics video for {track.base_name}")
# Define output path
output_path = os.path.join(track.track_output_dir, f"{track.base_name} (With Vocals).mp4")
# Skip if output already exists
if os.path.isfile(output_path):
self.logger.info(f"Lyrics video already exists: {output_path}")
track.video_with_lyrics = output_path
return track
# Debug logging
self.logger.debug(f"processed_lyrics: {track.processed_lyrics}, type: {type(track.processed_lyrics)}")
self.logger.debug(f"title_video: {track.title_video}, type: {type(track.title_video)}")
self.logger.debug(f"instrumental: {track.instrumental}, type: {type(track.instrumental)}")
# Handle case where processed_lyrics is a dictionary
lyrics_file = None
if isinstance(track.processed_lyrics, dict):
# Try to get the formatted lyrics file
if 'formatted_lyrics_file' in track.processed_lyrics:
lyrics_file = track.processed_lyrics['formatted_lyrics_file']
elif 'formatted_lyrics' in track.processed_lyrics:
lyrics_file = track.processed_lyrics['formatted_lyrics']
elif 'ass_filepath' in track.processed_lyrics:
lyrics_file = track.processed_lyrics['ass_filepath']
else:
lyrics_file = track.processed_lyrics
# Check for processed lyrics
if not lyrics_file or not os.path.isfile(lyrics_file):
self.logger.warning(f"No processed lyrics found for {track.base_name}")
return track
# Check for audio file
audio_file = track.audio_file
if not audio_file or not os.path.isfile(audio_file):
self.logger.warning(f"No audio file found for {track.base_name}")
return track
# Render video
if not self.config.dry_run:
try:
# Determine if we have a valid title video
has_title_video = track.title_video and os.path.isfile(track.title_video)
# Create temporary subtitle file in ASS format if needed
if lyrics_file.endswith('.lrc'):
subtitle_file = await self._convert_lrc_to_ass(lyrics_file, track.track_output_dir)
else:
subtitle_file = lyrics_file
# Build ffmpeg command
if has_title_video:
# Use title video if available
command = (
f'{self.ffmpeg_base_command} -i "{track.title_video}" -i "{audio_file}" '
f'-vf "ass={subtitle_file}" '
f'-c:v libx264 -preset medium -crf 22 -c:a aac -b:a 192k '
f'-pix_fmt yuv420p -shortest "{output_path}"'
)
else:
# Create video from audio with black background
command = (
f'{self.ffmpeg_base_command} -f lavfi -i color=c=black:s=1920x1080:r=30 '
f'-i "{audio_file}" -vf "ass={subtitle_file}" '
f'-c:v libx264 -preset medium -crf 22 -c:a aac -b:a 192k '
f'-pix_fmt yuv420p -shortest -t {track.duration} "{output_path}"'
)
# Execute command
self.logger.debug(f"Rendering lyrics video: {command}")
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_message = stderr.decode() if stderr else "Unknown error"
raise VideoError(f"Failed to render lyrics video: {error_message}")
track.video_with_lyrics = output_path
self.logger.info(f"Successfully rendered lyrics video: {output_path}")
# Clean up temporary files
if lyrics_file.endswith('.lrc') and os.path.isfile(subtitle_file) and subtitle_file != lyrics_file:
os.remove(subtitle_file)
except Exception as e:
self.logger.error(f"Failed to render lyrics video: {str(e)}")
# Continue with other processing
else:
self.logger.info(f"[DRY RUN] Would render lyrics video: {output_path}")
track.video_with_lyrics = output_path
return track
async def render_instrumental_video(self, track):
"""
Render a video with instrumental audio.
Args:
track: The track to process
Returns:
The track with updated video information
"""
self.logger.info(f"Rendering instrumental video for {track.base_name}")
# Define output path
output_path = os.path.join(track.track_output_dir, f"{track.base_name} (Instrumental).mp4")
# Skip if output already exists
if os.path.isfile(output_path):
self.logger.info(f"Instrumental video already exists: {output_path}")
track.video_with_instrumental = output_path
return track
# Check for title video
if not track.title_video or not os.path.isfile(track.title_video):
self.logger.warning(f"No title video found for {track.base_name}")
return track
# Check for instrumental audio
if not track.instrumental or not os.path.isfile(track.instrumental):
self.logger.warning(f"No instrumental audio found for {track.base_name}")
return track
# Render video
if not self.config.dry_run:
try:
# Build ffmpeg command
command = (
f'{self.ffmpeg_base_command} -i "{track.title_video}" -i "{track.instrumental}" '
f'-map 0:v -map 1:a -c:v libx264 -preset medium -crf 22 -c:a aac -b:a 192k '
f'-pix_fmt yuv420p -shortest "{output_path}"'
)
# Execute command
self.logger.debug(f"Rendering instrumental video: {command}")
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_message = stderr.decode() if stderr else "Unknown error"
raise VideoError(f"Failed to render instrumental video: {error_message}")
track.video_with_instrumental = output_path
self.logger.info(f"Successfully rendered instrumental video: {output_path}")
except Exception as e:
self.logger.error(f"Failed to render instrumental video: {str(e)}")
# Continue with other processing
else:
self.logger.info(f"[DRY RUN] Would render instrumental video: {output_path}")
track.video_with_instrumental = output_path
return track
async def render_karaoke_video(self, track):
"""
Render a karaoke video with lyrics and instrumental audio.
Args:
track: The track to process
Returns:
The track with updated video information
"""
self.logger.info(f"Rendering karaoke video for {track.base_name}")
# Skip if no processed lyrics
if not track.processed_lyrics or not track.processed_lyrics.get("lrc_filepath"):
self.logger.info("No processed lyrics available, skipping karaoke video rendering")
return track
# Skip if no instrumental audio
if not track.separated_audio["clean_instrumental"].get("instrumental"):
self.logger.info("No instrumental audio available, skipping karaoke video rendering")
return track
# Define output path
output_path = os.path.join(track.track_output_dir, f"{track.base_name} (Karaoke).mp4")
# Skip if output already exists
if os.path.isfile(output_path):
self.logger.info(f"Karaoke video already exists: {output_path}")
track.final_video = output_path
return track
# Get input paths
title_video = track.title_video
end_video = track.end_video
instrumental_audio = track.separated_audio["clean_instrumental"]["instrumental"]
lyrics_file = track.processed_lyrics.get("lrc_filepath")
# Check if all required files exist
if not all(os.path.isfile(f) for f in [title_video, instrumental_audio, lyrics_file]):
self.logger.warning("Missing required files for karaoke video rendering")
return track
# Render video
if not self.config.dry_run:
try:
# Create temporary subtitle file in ASS format
ass_file = await self._convert_lrc_to_ass(lyrics_file, track.track_output_dir)
# Build ffmpeg command
command = (
f'{self.ffmpeg_base_command} -i "{title_video}" -i "{instrumental_audio}" '
)
# Add end video if available
if end_video and os.path.isfile(end_video):
command += f'-i "{end_video}" '
filter_complex = (
f'-filter_complex "[0:v][1:a][2:v][1:a]concat=n=2:v=1:a=1[outv][outa]" '
f'-map "[outv]" -map "[outa]" '
)
else:
filter_complex = ""
command += f'-map 0:v -map 1:a '
# Add subtitle filter
if filter_complex:
command = command.replace("-filter_complex", f'-filter_complex "ass={ass_file}:')
else:
command += f'-vf "ass={ass_file}" '
# Add output options
command += (
f'-c:v libx264 -preset medium -crf 22 -c:a aac -b:a 192k '
f'-pix_fmt yuv420p -shortest "{output_path}"'
)
# Execute command
self.logger.debug(f"Rendering karaoke video: {command}")
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_message = stderr.decode() if stderr else "Unknown error"
raise VideoError(f"Failed to render karaoke video: {error_message}")
track.final_video = output_path
self.logger.info(f"Successfully rendered karaoke video: {output_path}")
# Clean up temporary files
if os.path.isfile(ass_file):
os.remove(ass_file)
except Exception as e:
self.logger.error(f"Failed to render karaoke video: {str(e)}")
# Continue with other processing
else:
self.logger.info(f"[DRY RUN] Would render karaoke video: {output_path}")
track.final_video = output_path
return track
async def _convert_lrc_to_ass(self, lrc_file, output_dir):
"""
Convert LRC file to ASS subtitle format.
Args:
lrc_file: The LRC file path
output_dir: The output directory
Returns:
The path to the ASS file
"""
self.logger.info(f"Converting LRC file to ASS: {lrc_file}")
# Define output path
ass_file = os.path.join(output_dir, os.path.basename(lrc_file).replace(".lrc", ".ass"))
# Skip if output already exists
if os.path.isfile(ass_file):
self.logger.info(f"ASS file already exists: {ass_file}")
return ass_file
# Create a temporary file for the ASS file
with tempfile.NamedTemporaryFile(suffix=".ass", delete=False) as temp_file:
temp_ass_file = temp_file.name
self._temp_files.append(temp_ass_file) # Track temporary file
# Read LRC file
with open(lrc_file, "r", encoding="utf-8") as f:
lrc_content = f.readlines()
# Parse LRC content
lyrics = []
for line in lrc_content:
line = line.strip()
if not line or line.startswith("[ti:") or line.startswith("[ar:") or line.startswith("[al:"):
continue
# Extract timestamp and text
if line.startswith("[") and "]" in line:
timestamp = line[1:line.find("]")]
text = line[line.find("]") + 1:].strip()
# Parse timestamp
if ":" in timestamp and "." in timestamp:
minutes, seconds = timestamp.split(":")
seconds, milliseconds = seconds.split(".")
start_time = int(minutes) * 60 + int(seconds) + int(milliseconds) / 100
lyrics.append((start_time, text))
# Sort lyrics by timestamp
lyrics.sort(key=lambda x: x[0])
# Calculate end times
for i in range(len(lyrics) - 1):
lyrics[i] = (lyrics[i][0], lyrics[i + 1][0], lyrics[i][1])
# Add end time for last lyric
if lyrics:
lyrics[-1] = (lyrics[-1][0], lyrics[-1][0] + 5, lyrics[-1][1])
# Create ASS file
with open(temp_ass_file, "w", encoding="utf-8") as f:
# Write header
f.write("[Script Info]\n")
f.write("Title: Karaoke Lyrics\n")
f.write("ScriptType: v4.00+\n")
f.write("PlayResX: 3840\n")
f.write("PlayResY: 2160\n")
f.write("Collisions: Normal\n\n")
# Write styles
f.write("[V4+ Styles]\n")
f.write("Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n")
f.write("Style: Default,Arial,72,&H00FFFFFF,&H00FFFFFF,&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,3,0,2,20,20,20,1\n\n")
# Write events
f.write("[Events]\n")
f.write("Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n")
# Write lyrics
for start_time, end_time, text in lyrics:
start_str = self._format_time(start_time)
end_str = self._format_time(end_time)
f.write(f"Dialogue: 0,{start_str},{end_str},Default,,0,0,0,,{text}\n")
# Copy to output path
shutil.copy2(temp_ass_file, ass_file)
self.logger.info(f"Successfully converted LRC to ASS: {ass_file}")
return ass_file
def _format_time(self, seconds):
"""
Format time in seconds to ASS format (h:mm:ss.cc).
Args:
seconds: The time in seconds
Returns:
The formatted time string
"""
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
seconds = seconds % 60
centiseconds = int((seconds - int(seconds)) * 100)
seconds = int(seconds)
return f"{hours}:{minutes:02d}:{seconds:02d}.{centiseconds:02d}"
async def cleanup(self):
"""
Perform cleanup operations for the video renderer.
"""
self.logger.info("Cleaning up video renderer resources")
# Clean up any temporary files
if hasattr(self, '_temp_files') and self._temp_files:
for temp_file in self._temp_files:
if os.path.exists(temp_file):
try:
os.remove(temp_file)
self.logger.debug(f"Removed temporary file: {temp_file}")
except Exception as e:
self.logger.warning(f"Failed to remove temporary file {temp_file}: {str(e)}")
self.logger.info("Video renderer cleanup complete")
File diff suppressed because it is too large. Load diff
+236
View File
@@ -0,0 +1,236 @@
import os
import asyncio
import logging
from typing import List, Optional
from karaoke_gen.core.track import Track
from karaoke_gen.core.exceptions import VideoError
from karaoke_gen.services.video.screens import ScreenGenerator
from karaoke_gen.services.video.renderer import VideoRenderer
from karaoke_gen.services.video.compositor import VideoCompositor
class VideoService:
"""
Service for orchestrating the video generation process.
"""
def __init__(self, config):
"""
Initialize the video service.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger or logging.getLogger(__name__)
# Initialize components
self.screen_generator = ScreenGenerator(config)
self.renderer = VideoRenderer(config)
self.compositor = VideoCompositor(config)
async def process_video(self, track: Track) -> Track:
"""
Process video for a track, including screen generation, rendering, and composition.
Args:
track: The track to process
Returns:
The track with updated video information
"""
self.logger.info(f"Processing video for {track.base_name}")
try:
# Skip if final video already exists and we're not forcing regeneration
if track.final_video and os.path.isfile(track.final_video) and not self.config.force_regenerate:
self.logger.info(f"Final video already exists for {track.base_name}, skipping video processing")
return track
# Generate screens
track = await self.generate_screens(track)
# Render videos
track = await self.render_videos(track)
# Compose final video
track = await self.compose_final_video(track)
# Create additional versions
track = await self.create_additional_versions(track)
return track
except Exception as e:
self.logger.error(f"Failed to process video for {track.base_name}: {str(e)}")
# Continue with other processing
return track
async def generate_screens(self, track: Track) -> Track:
"""
Generate title and end screens for the track.
Args:
track: The track to process
Returns:
The track with updated screen information
"""
self.logger.info(f"Generating screens for {track.base_name}")
try:
# Generate title screen
if not track.title_video or not os.path.isfile(track.title_video) or self.config.force_regenerate:
track = await self.screen_generator.generate_title_screen(track)
else:
self.logger.info(f"Title screen already exists: {track.title_video}")
# Generate end screen
if not track.end_video or not os.path.isfile(track.end_video) or self.config.force_regenerate:
track = await self.screen_generator.generate_end_screen(track)
else:
self.logger.info(f"End screen already exists: {track.end_video}")
return track
except Exception as e:
self.logger.error(f"Failed to generate screens for {track.base_name}: {str(e)}")
# Continue with other processing
return track
async def render_videos(self, track: Track) -> Track:
"""
Render videos for the track.
Args:
track: The track to process
Returns:
The track with updated video information
"""
self.logger.info(f"Rendering videos for {track.base_name}")
try:
# Render lyrics video
if (not track.video_with_lyrics or not os.path.isfile(track.video_with_lyrics) or
self.config.force_regenerate):
track = await self.renderer.render_lyrics_video(track)
else:
self.logger.info(f"Lyrics video already exists: {track.video_with_lyrics}")
# Render instrumental video
if (not track.video_with_instrumental or not os.path.isfile(track.video_with_instrumental) or
self.config.force_regenerate):
track = await self.renderer.render_instrumental_video(track)
else:
self.logger.info(f"Instrumental video already exists: {track.video_with_instrumental}")
return track
except Exception as e:
self.logger.error(f"Failed to render videos for {track.base_name}: {str(e)}")
# Continue with other processing
return track
async def compose_final_video(self, track: Track) -> Track:
"""
Compose the final video for the track.
Args:
track: The track to process
Returns:
The track with updated final video information
"""
self.logger.info(f"Composing final video for {track.base_name}")
try:
# Skip if final video already exists
if track.final_video and os.path.isfile(track.final_video) and not self.config.force_regenerate:
self.logger.info(f"Final video already exists: {track.final_video}")
return track
# Check for required videos
if not track.title_video or not os.path.isfile(track.title_video):
self.logger.warning(f"Title video not found for {track.base_name}")
return track
if not track.video_with_lyrics and not track.video_with_instrumental:
self.logger.warning(f"No content videos found for {track.base_name}")
return track
# Compose final video
track = await self.compositor.compose_final_video(track)
return track
except Exception as e:
self.logger.error(f"Failed to compose final video for {track.base_name}: {str(e)}")
# Continue with other processing
return track
async def create_additional_versions(self, track: Track) -> Track:
"""
Create additional versions of the final video.
Args:
track: The track to process
Returns:
The track with updated video version information
"""
self.logger.info(f"Creating additional video versions for {track.base_name}")
try:
# Skip if no final video
if not track.final_video or not os.path.isfile(track.final_video):
self.logger.warning(f"No final video found for {track.base_name}")
return track
# Create lossless version
if not track.final_video_mkv or not os.path.isfile(track.final_video_mkv) or self.config.force_regenerate:
track = await self.compositor.create_lossless_version(track)
else:
self.logger.info(f"Lossless version already exists: {track.final_video_mkv}")
# Create 720p version
if not track.final_video_720p or not os.path.isfile(track.final_video_720p) or self.config.force_regenerate:
track = await self.compositor.create_720p_version(track)
else:
self.logger.info(f"720p version already exists: {track.final_video_720p}")
# Create lossy version
if not track.final_video_lossy or not os.path.isfile(track.final_video_lossy) or self.config.force_regenerate:
track = await self.compositor.create_lossy_version(track)
else:
self.logger.info(f"Lossy version already exists: {track.final_video_lossy}")
return track
except Exception as e:
self.logger.error(f"Failed to create additional versions for {track.base_name}: {str(e)}")
# Continue with other processing
return track
async def cleanup(self):
"""
Perform cleanup operations for the video service.
"""
self.logger.info("Cleaning up video service resources")
# Clean up temporary files
if self.config.cleanup_temp_files:
self.logger.info("Cleaning up temporary video files")
# Implementation would depend on what temporary files are created
# Close any open resources
if hasattr(self, 'screen_generator'):
await self.screen_generator.cleanup()
if hasattr(self, 'renderer'):
await self.renderer.cleanup()
if hasattr(self, 'compositor'):
await self.compositor.cleanup()
self.logger.info("Video service cleanup complete")
+545
View File
@@ -0,0 +1,545 @@
import os
import asyncio
import tempfile
from PIL import Image, ImageDraw, ImageFont
import pkg_resources
from karaoke_gen.core.exceptions import VideoError
class TextRenderer:
"""
Handles text rendering for videos.
"""
def __init__(self, config):
"""
Initialize the text renderer.
Args:
config: The project configuration
"""
self.config = config
self.logger = config.logger
# Path to ffmpeg
self.ffmpeg_path = "ffmpeg"
# Set up ffmpeg base command
self.ffmpeg_base_command = f"{self.ffmpeg_path} -hide_banner -nostats"
if self.config.log_level <= 10: # DEBUG
self.ffmpeg_base_command += " -loglevel verbose"
else:
self.ffmpeg_base_command += " -loglevel fatal"
async def render_lyrics(self, track, lyrics_file, output_file, font_name=None, font_size=None,
font_color=None, outline_color=None, outline_width=None,
position=None, alignment=None, background_color=None):
"""
Render lyrics to a video file.
Args:
track: The track to process
lyrics_file: The lyrics file to render
output_file: The output file path
font_name: The font name
font_size: The font size
font_color: The font color
outline_color: The outline color
outline_width: The outline width
position: The position
alignment: The alignment
background_color: The background color
Returns:
The output file path
"""
self.logger.info(f"Rendering lyrics for {track.base_name}")
# Skip if output already exists
if os.path.isfile(output_file):
self.logger.info(f"Lyrics video already exists: {output_file}")
return output_file
# Check if lyrics file exists
if not os.path.isfile(lyrics_file):
self.logger.error(f"Lyrics file not found: {lyrics_file}")
raise VideoError(f"Lyrics file not found: {lyrics_file}")
# Set default values
font_name = font_name or self.config.lyrics_font or "Arial"
font_size = font_size or self.config.lyrics_font_size or 48
font_color = font_color or self.config.lyrics_font_color or "white"
outline_color = outline_color or self.config.lyrics_outline_color or "black"
outline_width = outline_width or self.config.lyrics_outline_width or 2
position = position or self.config.lyrics_position or "bottom"
alignment = alignment or self.config.lyrics_alignment or "center"
background_color = background_color or self.config.lyrics_background_color or "transparent"
# Get font path
font_path = self._get_font_path(font_name)
# Create subtitles file
subtitles_file = await self._create_subtitles_file(
lyrics_file,
font_path,
font_size,
font_color,
outline_color,
outline_width,
position,
alignment,
background_color
)
# Create video with subtitles
if not self.config.dry_run:
try:
# Create a black video if no input video is provided
temp_video = await self._create_temp_black_video(track.duration)
# Add subtitles to video
await self._add_subtitles_to_video(temp_video, subtitles_file, output_file)
# Clean up temporary files
os.remove(temp_video)
os.remove(subtitles_file)
self.logger.info(f"Successfully rendered lyrics: {output_file}")
except Exception as e:
raise VideoError(f"Failed to render lyrics: {str(e)}") from e
else:
self.logger.info(f"[DRY RUN] Would render lyrics: {output_file}")
return output_file
async def render_text_overlay(self, input_video, output_video, text, font_name=None, font_size=None,
font_color=None, outline_color=None, outline_width=None,
position=None, alignment=None, background_color=None,
start_time=None, end_time=None):
"""
Render text overlay on a video.
Args:
input_video: The input video file
output_video: The output video file
text: The text to render
font_name: The font name
font_size: The font size
font_color: The font color
outline_color: The outline color
outline_width: The outline width
position: The position
alignment: The alignment
background_color: The background color
start_time: The start time
end_time: The end time
Returns:
The output video file
"""
self.logger.info(f"Rendering text overlay on {input_video}")
# Skip if output already exists
if os.path.isfile(output_video):
self.logger.info(f"Text overlay video already exists: {output_video}")
return output_video
# Check if input video exists
if not os.path.isfile(input_video):
self.logger.error(f"Input video not found: {input_video}")
raise VideoError(f"Input video not found: {input_video}")
# Set default values
font_name = font_name or self.config.overlay_font or "Arial"
font_size = font_size or self.config.overlay_font_size or 48
font_color = font_color or self.config.overlay_font_color or "white"
outline_color = outline_color or self.config.overlay_outline_color or "black"
outline_width = outline_width or self.config.overlay_outline_width or 2
position = position or self.config.overlay_position or "bottom"
alignment = alignment or self.config.overlay_alignment or "center"
background_color = background_color or self.config.overlay_background_color or "transparent"
# Get font path
font_path = self._get_font_path(font_name)
# Create subtitles file with single entry
subtitles_file = await self._create_simple_subtitles_file(
text,
start_time or 0,
end_time or 999999,
font_path,
font_size,
font_color,
outline_color,
outline_width,
position,
alignment,
background_color
)
# Add subtitles to video
if not self.config.dry_run:
try:
await self._add_subtitles_to_video(input_video, subtitles_file, output_video)
# Clean up temporary files
os.remove(subtitles_file)
self.logger.info(f"Successfully rendered text overlay: {output_video}")
except Exception as e:
raise VideoError(f"Failed to render text overlay: {str(e)}") from e
else:
self.logger.info(f"[DRY RUN] Would render text overlay: {output_video}")
return output_video
def _get_font_path(self, font_name):
"""
Get the path to a font file.
Args:
font_name: The font name
Returns:
The font path
"""
# Check if font is a path
if os.path.isfile(font_name):
return font_name
# Check in resources directory
resources_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "resources")
font_path = os.path.join(resources_dir, font_name)
if os.path.isfile(font_path):
return font_path
# Try to find font in package resources
try:
font_path = pkg_resources.resource_filename("karaoke_gen", f"resources/{font_name}")
if os.path.isfile(font_path):
return font_path
except Exception:
pass
# Default to a system font
self.logger.warning(f"Font not found: {font_name}, using default font")
return font_name
async def _create_subtitles_file(self, lyrics_file, font_path, font_size, font_color,
outline_color, outline_width, position, alignment, background_color):
"""
Create a subtitles file from a lyrics file.
Args:
lyrics_file: The lyrics file
font_path: The font path
font_size: The font size
font_color: The font color
outline_color: The outline color
outline_width: The outline width
position: The position
alignment: The alignment
background_color: The background color
Returns:
The subtitles file path
"""
# Create a temporary file for subtitles
with tempfile.NamedTemporaryFile(suffix=".ass", delete=False) as temp_file:
subtitles_file = temp_file.name
# Parse LRC file and convert to ASS format
with open(lyrics_file, "r", encoding="utf-8") as f:
lrc_lines = f.readlines()
# Write ASS header
with open(subtitles_file, "w", encoding="utf-8") as f:
f.write("[Script Info]\n")
f.write("Title: Lyrics\n")
f.write("ScriptType: v4.00+\n")
f.write("WrapStyle: 0\n")
f.write("ScaledBorderAndShadow: yes\n")
f.write("YCbCr Matrix: None\n\n")
f.write("[V4+ Styles]\n")
f.write("Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n")
# Convert colors to ASS format
primary_color = self._color_to_ass(font_color)
outline_color_ass = self._color_to_ass(outline_color)
background_color_ass = self._color_to_ass(background_color)
# Set alignment based on position and alignment
ass_alignment = self._get_ass_alignment(position, alignment)
# Set margin based on position
margin_v = 20 if position == "bottom" else (20 if position == "top" else 10)
f.write(f"Style: Default,{os.path.basename(font_path)},{font_size},{primary_color},{primary_color},{outline_color_ass},{background_color_ass},0,0,0,0,100,100,0,0,1,{outline_width},0,{ass_alignment},10,10,{margin_v},1\n\n")
f.write("[Events]\n")
f.write("Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n")
# Parse LRC lines
events = []
for line in lrc_lines:
line = line.strip()
if line and "[" in line and "]" in line:
try:
time_tag = line[line.find("[") + 1:line.find("]")]
if ":" in time_tag and "." in time_tag:
minutes, rest = time_tag.split(":")
seconds, milliseconds = rest.split(".")
start_time_seconds = int(minutes) * 60 + int(seconds) + int(milliseconds) / 100
text = line[line.find("]") + 1:].strip()
if text: # Only add non-empty lines
events.append((start_time_seconds, text))
except Exception as e:
self.logger.warning(f"Failed to parse LRC line: {line}, error: {str(e)}")
# Sort events by start time
events.sort(key=lambda x: x[0])
# Write events with end times
for i, (start_time, text) in enumerate(events):
# Set end time to the start time of the next event, or 5 seconds after if it's the last event
end_time = events[i + 1][0] if i < len(events) - 1 else start_time + 5
# Format times as h:mm:ss.cc
start_time_formatted = self._format_ass_time(start_time)
end_time_formatted = self._format_ass_time(end_time)
# Escape special characters
text = text.replace("\\", "\\\\").replace("{", "\\{").replace("}", "\\}")
f.write(f"Dialogue: 0,{start_time_formatted},{end_time_formatted},Default,,0,0,0,,{text}\n")
return subtitles_file
async def _create_simple_subtitles_file(self, text, start_time, end_time, font_path, font_size,
font_color, outline_color, outline_width, position,
alignment, background_color):
"""
Create a simple subtitles file with a single entry.
Args:
text: The text
start_time: The start time in seconds
end_time: The end time in seconds
font_path: The font path
font_size: The font size
font_color: The font color
outline_color: The outline color
outline_width: The outline width
position: The position
alignment: The alignment
background_color: The background color
Returns:
The subtitles file path
"""
# Create a temporary file for subtitles
with tempfile.NamedTemporaryFile(suffix=".ass", delete=False) as temp_file:
subtitles_file = temp_file.name
# Write ASS header
with open(subtitles_file, "w", encoding="utf-8") as f:
f.write("[Script Info]\n")
f.write("Title: Text Overlay\n")
f.write("ScriptType: v4.00+\n")
f.write("WrapStyle: 0\n")
f.write("ScaledBorderAndShadow: yes\n")
f.write("YCbCr Matrix: None\n\n")
f.write("[V4+ Styles]\n")
f.write("Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n")
# Convert colors to ASS format
primary_color = self._color_to_ass(font_color)
outline_color_ass = self._color_to_ass(outline_color)
background_color_ass = self._color_to_ass(background_color)
# Set alignment based on position and alignment
ass_alignment = self._get_ass_alignment(position, alignment)
# Set margin based on position
margin_v = 20 if position == "bottom" else (20 if position == "top" else 10)
f.write(f"Style: Default,{os.path.basename(font_path)},{font_size},{primary_color},{primary_color},{outline_color_ass},{background_color_ass},0,0,0,0,100,100,0,0,1,{outline_width},0,{ass_alignment},10,10,{margin_v},1\n\n")
f.write("[Events]\n")
f.write("Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n")
# Format times as h:mm:ss.cc
start_time_formatted = self._format_ass_time(start_time)
end_time_formatted = self._format_ass_time(end_time)
# Escape special characters
text = text.replace("\\", "\\\\").replace("{", "\\{").replace("}", "\\}")
f.write(f"Dialogue: 0,{start_time_formatted},{end_time_formatted},Default,,0,0,0,,{text}\n")
return subtitles_file
def _color_to_ass(self, color):
"""
Convert a color to ASS format.
Args:
color: The color
Returns:
The ASS color
"""
if color == "transparent":
return "&H00FFFFFF" # Transparent
# Handle hex colors
if color.startswith("#"):
r = int(color[1:3], 16)
g = int(color[3:5], 16)
b = int(color[5:7], 16)
return f"&H00{b:02X}{g:02X}{r:02X}"
# Handle named colors
color_map = {
"white": "&H00FFFFFF",
"black": "&H00000000",
"red": "&H000000FF",
"green": "&H0000FF00",
"blue": "&H00FF0000",
"yellow": "&H0000FFFF",
"cyan": "&H00FFFF00",
"magenta": "&H00FF00FF",
}
return color_map.get(color.lower(), "&H00FFFFFF") # Default to white
def _get_ass_alignment(self, position, alignment):
"""
Get the ASS alignment value.
Args:
position: The position
alignment: The alignment
Returns:
The ASS alignment value
"""
# ASS alignment values:
# 1: bottom left, 2: bottom center, 3: bottom right
# 4: middle left, 5: middle center, 6: middle right
# 7: top left, 8: top center, 9: top right
if position == "bottom":
if alignment == "left":
return 1
elif alignment == "right":
return 3
else: # center
return 2
elif position == "middle":
if alignment == "left":
return 4
elif alignment == "right":
return 6
else: # center
return 5
elif position == "top":
if alignment == "left":
return 7
elif alignment == "right":
return 9
else: # center
return 8
else:
return 2 # Default to bottom center
def _format_ass_time(self, seconds):
"""
Format seconds as h:mm:ss.cc for ASS format.
Args:
seconds: The time in seconds
Returns:
The formatted time
"""
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
seconds_remainder = seconds % 60
centiseconds = int((seconds_remainder - int(seconds_remainder)) * 100)
return f"{hours}:{minutes:02d}:{int(seconds_remainder):02d}.{centiseconds:02d}"
async def _create_temp_black_video(self, duration):
"""
Create a temporary black video.
Args:
duration: The duration in seconds
Returns:
The temporary video file path
"""
# Create a temporary file for the video
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as temp_file:
temp_video = temp_file.name
# Create a black video
command = (
f'{self.ffmpeg_base_command} -f lavfi -i color=c=black:s=1920x1080:r=30 '
f'-t {duration} -c:v libx264 -pix_fmt yuv420p "{temp_video}"'
)
self.logger.debug(f"Creating temporary black video: {command}")
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_message = stderr.decode() if stderr else "Unknown error"
raise VideoError(f"Failed to create temporary black video: {error_message}")
return temp_video
async def _add_subtitles_to_video(self, input_video, subtitles_file, output_video):
"""
Add subtitles to a video.
Args:
input_video: The input video file
subtitles_file: The subtitles file
output_video: The output video file
Returns:
The output video file
"""
# Add subtitles to video
command = (
f'{self.ffmpeg_base_command} -i "{input_video}" -vf '
f'ass="{subtitles_file}" -c:v prores_ks -profile:v 3 -vendor ap10 '
f'-bits_per_mb 8000 -pix_fmt yuv422p10le "{output_video}"'
)
self.logger.debug(f"Adding subtitles to video: {command}")
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_message = stderr.decode() if stderr else "Unknown error"
raise VideoError(f"Failed to add subtitles to video: {error_message}")
return output_video
+108
View File
@@ -0,0 +1,108 @@
"""
Utility functions for the karaoke_gen package.
"""
# Import utility modules
from karaoke_gen.utils import config
from karaoke_gen.utils import date
from karaoke_gen.utils import file
from karaoke_gen.utils import logging
from karaoke_gen.utils import path
from karaoke_gen.utils import string
from karaoke_gen.utils import validation
# Re-export functions from config module
from karaoke_gen.utils.config import (
load_config_file,
save_config_file,
get_config_value,
set_config_value,
merge_configs,
validate_required_config_keys,
get_nested_config_value,
set_nested_config_value,
)
# Re-export functions from date module
from karaoke_gen.utils.date import (
get_current_timestamp,
get_current_date,
get_current_time,
format_date,
parse_date,
get_date_components,
add_days,
days_between,
is_date_in_range,
get_month_name,
get_day_of_week,
)
# Re-export functions from file module
from karaoke_gen.utils.file import (
sanitize_filename,
ensure_directory_exists,
backup_existing_files,
file_exists,
copy_file,
move_file,
delete_file,
create_zip_file,
execute_command,
)
# Re-export functions from logging module
from karaoke_gen.utils.logging import (
setup_logger,
get_log_level_from_string,
configure_logger_from_config,
log_section,
log_subsection,
log_dict,
log_exception,
)
# Re-export functions from path module
from karaoke_gen.utils.path import (
normalize_path,
join_paths,
get_absolute_path,
get_relative_path,
get_parent_directory,
get_filename,
get_filename_without_extension,
get_file_extension,
create_directory,
delete_directory,
list_files,
list_directories,
get_file_info,
find_files_by_extension,
copy_directory,
move_directory,
get_directory_size,
)
# Re-export functions from string module
from karaoke_gen.utils.string import (
slugify,
truncate_string,
extract_artist_and_title,
format_duration,
format_filesize,
strip_html_tags,
normalize_whitespace,
extract_urls,
replace_placeholders,
generate_random_string,
)
# Re-export functions from validation module
from karaoke_gen.utils.validation import (
is_url,
is_file,
is_directory,
prompt_user_confirmation_or_raise_exception,
prompt_user_bool,
validate_input_parameters_for_features,
)
+204
View File
@@ -0,0 +1,204 @@
"""
Configuration utility functions.
"""
import os
import json
import logging
from typing import Dict, Any, Optional, List, Union
def load_config_file(config_file: str, logger: Optional[logging.Logger] = None) -> Dict[str, Any]:
"""
Load a configuration file.
Args:
config_file: The configuration file to load
logger: The logger to use
Returns:
The loaded configuration
Raises:
FileNotFoundError: If the configuration file does not exist
json.JSONDecodeError: If the configuration file is not valid JSON
"""
if logger:
logger.info(f"Loading configuration from {config_file}")
if not os.path.isfile(config_file):
error_msg = f"Configuration file not found: {config_file}"
if logger:
logger.error(error_msg)
raise FileNotFoundError(error_msg)
try:
with open(config_file, "r") as f:
config = json.load(f)
if logger:
logger.info(f"Successfully loaded configuration from {config_file}")
return config
except json.JSONDecodeError as e:
error_msg = f"Invalid JSON in configuration file {config_file}: {str(e)}"
if logger:
logger.error(error_msg)
raise
def save_config_file(config_file: str, config: Dict[str, Any], logger: Optional[logging.Logger] = None) -> bool:
"""
Save a configuration file.
Args:
config_file: The configuration file to save
config: The configuration to save
logger: The logger to use
Returns:
True if the configuration was saved successfully, False otherwise
"""
if logger:
logger.info(f"Saving configuration to {config_file}")
try:
# Create directory if it doesn't exist
os.makedirs(os.path.dirname(config_file), exist_ok=True)
with open(config_file, "w") as f:
json.dump(config, f, indent=4)
if logger:
logger.info(f"Successfully saved configuration to {config_file}")
return True
except Exception as e:
if logger:
logger.error(f"Failed to save configuration to {config_file}: {str(e)}")
return False
def get_config_value(config: Dict[str, Any], key: str, default: Any = None) -> Any:
"""
Get a value from a configuration dictionary.
Args:
config: The configuration dictionary
key: The key to get
default: The default value to return if the key is not found
Returns:
The value for the key, or the default value if the key is not found
"""
return config.get(key, default)
def set_config_value(config: Dict[str, Any], key: str, value: Any) -> Dict[str, Any]:
"""
Set a value in a configuration dictionary.
Args:
config: The configuration dictionary
key: The key to set
value: The value to set
Returns:
The updated configuration dictionary
"""
config[key] = value
return config
def merge_configs(base_config: Dict[str, Any], override_config: Dict[str, Any]) -> Dict[str, Any]:
"""
Merge two configuration dictionaries.
Args:
base_config: The base configuration dictionary
override_config: The override configuration dictionary
Returns:
The merged configuration dictionary
"""
result = base_config.copy()
for key, value in override_config.items():
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
result[key] = merge_configs(result[key], value)
else:
result[key] = value
return result
def validate_required_config_keys(config: Dict[str, Any], required_keys: List[str], logger: Optional[logging.Logger] = None) -> bool:
"""
Validate that a configuration dictionary contains all required keys.
Args:
config: The configuration dictionary
required_keys: The required keys
logger: The logger to use
Returns:
True if all required keys are present, False otherwise
"""
missing_keys = [key for key in required_keys if key not in config]
if missing_keys:
if logger:
logger.error(f"Missing required configuration keys: {', '.join(missing_keys)}")
return False
return True
def get_nested_config_value(config: Dict[str, Any], key_path: str, default: Any = None) -> Any:
"""
Get a nested value from a configuration dictionary using a dot-separated path.
Args:
config: The configuration dictionary
key_path: The dot-separated path to the key
default: The default value to return if the key is not found
Returns:
The value for the key, or the default value if the key is not found
"""
keys = key_path.split(".")
current = config
for key in keys:
if not isinstance(current, dict) or key not in current:
return default
current = current[key]
return current
def set_nested_config_value(config: Dict[str, Any], key_path: str, value: Any) -> Dict[str, Any]:
"""
Set a nested value in a configuration dictionary using a dot-separated path.
Args:
config: The configuration dictionary
key_path: The dot-separated path to the key
value: The value to set
Returns:
The updated configuration dictionary
"""
keys = key_path.split(".")
current = config
# Navigate to the parent of the final key
for key in keys[:-1]:
if key not in current:
current[key] = {}
elif not isinstance(current[key], dict):
current[key] = {}
current = current[key]
# Set the value at the final key
current[keys[-1]] = value
return config
+223
View File
@@ -0,0 +1,223 @@
"""
Date utility functions.
"""
import datetime
from typing import Optional, Union, Dict, Any
def get_current_timestamp() -> str:
"""
Get the current timestamp in ISO 8601 format.
Returns:
The current timestamp in ISO 8601 format
"""
return datetime.datetime.now().isoformat()
def get_current_date() -> str:
"""
Get the current date in YYYY-MM-DD format.
Returns:
The current date in YYYY-MM-DD format
"""
return datetime.date.today().isoformat()
def get_current_time() -> str:
"""
Get the current time in HH:MM:SS format.
Returns:
The current time in HH:MM:SS format
"""
return datetime.datetime.now().strftime("%H:%M:%S")
def format_date(date: Union[datetime.date, datetime.datetime, str], format_string: str = "%Y-%m-%d") -> str:
"""
Format a date object or string as a string.
Args:
date: The date to format
format_string: The format string to use
Returns:
The formatted date string
Raises:
ValueError: If the date is not a valid date object or string
"""
if isinstance(date, str):
try:
date = datetime.datetime.fromisoformat(date)
except ValueError:
try:
date = datetime.datetime.strptime(date, "%Y-%m-%d")
except ValueError:
raise ValueError(f"Invalid date string: {date}")
return date.strftime(format_string)
def parse_date(date_string: str, format_string: Optional[str] = None) -> datetime.date:
"""
Parse a date string into a date object.
Args:
date_string: The date string to parse
format_string: The format string to use (optional)
Returns:
The parsed date object
Raises:
ValueError: If the date string is not valid
"""
if format_string:
return datetime.datetime.strptime(date_string, format_string).date()
try:
return datetime.date.fromisoformat(date_string)
except ValueError:
try:
return datetime.datetime.fromisoformat(date_string).date()
except ValueError:
raise ValueError(f"Invalid date string: {date_string}")
def get_date_components(date: Union[datetime.date, datetime.datetime, str]) -> Dict[str, int]:
"""
Get the components of a date.
Args:
date: The date to get components from
Returns:
A dictionary with "year", "month", and "day" keys
Raises:
ValueError: If the date is not a valid date object or string
"""
if isinstance(date, str):
date = parse_date(date)
return {
"year": date.year,
"month": date.month,
"day": date.day,
}
def add_days(date: Union[datetime.date, datetime.datetime, str], days: int) -> datetime.date:
"""
Add days to a date.
Args:
date: The date to add days to
days: The number of days to add
Returns:
The new date
Raises:
ValueError: If the date is not a valid date object or string
"""
if isinstance(date, str):
date = parse_date(date)
return date + datetime.timedelta(days=days)
def days_between(start_date: Union[datetime.date, datetime.datetime, str],
end_date: Union[datetime.date, datetime.datetime, str]) -> int:
"""
Calculate the number of days between two dates.
Args:
start_date: The start date
end_date: The end date
Returns:
The number of days between the dates
Raises:
ValueError: If either date is not a valid date object or string
"""
if isinstance(start_date, str):
start_date = parse_date(start_date)
if isinstance(end_date, str):
end_date = parse_date(end_date)
delta = end_date - start_date
return delta.days
def is_date_in_range(date: Union[datetime.date, datetime.datetime, str],
start_date: Union[datetime.date, datetime.datetime, str],
end_date: Union[datetime.date, datetime.datetime, str]) -> bool:
"""
Check if a date is within a range.
Args:
date: The date to check
start_date: The start date of the range
end_date: The end date of the range
Returns:
True if the date is within the range, False otherwise
Raises:
ValueError: If any date is not a valid date object or string
"""
if isinstance(date, str):
date = parse_date(date)
if isinstance(start_date, str):
start_date = parse_date(start_date)
if isinstance(end_date, str):
end_date = parse_date(end_date)
return start_date <= date <= end_date
def get_month_name(month: int) -> str:
"""
Get the name of a month.
Args:
month: The month number (1-12)
Returns:
The month name
Raises:
ValueError: If the month is not valid
"""
if not 1 <= month <= 12:
raise ValueError(f"Invalid month: {month}")
return datetime.date(2000, month, 1).strftime("%B")
def get_day_of_week(date: Union[datetime.date, datetime.datetime, str]) -> str:
"""
Get the day of the week for a date.
Args:
date: The date to get the day of the week for
Returns:
The day of the week
Raises:
ValueError: If the date is not a valid date object or string
"""
if isinstance(date, str):
date = parse_date(date)
return date.strftime("%A")
+233
View File
@@ -0,0 +1,233 @@
"""
File utility functions.
"""
import os
import re
import shutil
import subprocess
import logging
import zipfile
from typing import Optional, List, Dict, Any
def sanitize_filename(filename: str) -> str:
"""
Sanitize a filename to be safe for all operating systems.
Args:
filename: The filename to sanitize
Returns:
The sanitized filename
"""
# Replace invalid characters with underscores
sanitized = re.sub(r'[\\/*?:"<>|]', "_", filename)
# Remove leading/trailing whitespace and dots
sanitized = sanitized.strip(". ")
# Ensure the filename is not empty
if not sanitized:
sanitized = "unnamed"
return sanitized
def ensure_directory_exists(directory: str) -> None:
"""
Ensure a directory exists, creating it if necessary.
Args:
directory: The directory to ensure exists
"""
os.makedirs(directory, exist_ok=True)
def backup_existing_files(file_path: str, max_backups: int = 5) -> None:
"""
Backup existing files to prevent overwriting.
Args:
file_path: The file to backup
max_backups: The maximum number of backups to keep
"""
if not os.path.exists(file_path):
return
# Create backup directory
backup_dir = os.path.join(os.path.dirname(file_path), "backups")
ensure_directory_exists(backup_dir)
# Get base filename
base_name = os.path.basename(file_path)
# Create backup filename with timestamp
from datetime import datetime
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_file = os.path.join(backup_dir, f"{base_name}.{timestamp}")
# Copy the file to the backup location
shutil.copy2(file_path, backup_file)
# Remove old backups if there are too many
backup_files = [
os.path.join(backup_dir, f) for f in os.listdir(backup_dir)
if f.startswith(base_name + ".")
]
backup_files.sort(key=os.path.getmtime)
if len(backup_files) > max_backups:
for old_backup in backup_files[:-max_backups]:
os.remove(old_backup)
def file_exists(file_path: str) -> bool:
"""
Check if a file exists with proper error handling.
Args:
file_path: The file to check
Returns:
True if the file exists, False otherwise
"""
try:
return os.path.isfile(file_path)
except Exception:
return False
def copy_file(source: str, destination: str, logger: Optional[logging.Logger] = None) -> bool:
"""
Copy a file with proper error handling.
Args:
source: The source file
destination: The destination file
logger: The logger to use
Returns:
True if the copy was successful, False otherwise
"""
try:
shutil.copy2(source, destination)
if logger:
logger.info(f"Copied {source} to {destination}")
return True
except Exception as e:
if logger:
logger.error(f"Failed to copy {source} to {destination}: {str(e)}")
return False
def move_file(source: str, destination: str, logger: Optional[logging.Logger] = None) -> bool:
"""
Move a file with proper error handling.
Args:
source: The source file
destination: The destination file
logger: The logger to use
Returns:
True if the move was successful, False otherwise
"""
try:
shutil.move(source, destination)
if logger:
logger.info(f"Moved {source} to {destination}")
return True
except Exception as e:
if logger:
logger.error(f"Failed to move {source} to {destination}: {str(e)}")
return False
def delete_file(file_path: str, logger: Optional[logging.Logger] = None) -> bool:
"""
Delete a file with proper error handling.
Args:
file_path: The file to delete
logger: The logger to use
Returns:
True if the deletion was successful, False otherwise
"""
try:
os.remove(file_path)
if logger:
logger.info(f"Deleted {file_path}")
return True
except Exception as e:
if logger:
logger.error(f"Failed to delete {file_path}: {str(e)}")
return False
def create_zip_file(zip_file: str, files: List[str], logger: Optional[logging.Logger] = None) -> bool:
"""
Create a zip file from a list of files.
Args:
zip_file: The zip file to create
files: The files to include in the zip file
logger: The logger to use
Returns:
True if the zip file was created successfully, False otherwise
"""
try:
with zipfile.ZipFile(zip_file, "w") as zipf:
for file in files:
if os.path.isfile(file):
zipf.write(file, os.path.basename(file))
if logger:
logger.info(f"Added {file} to {zip_file}")
if logger:
logger.info(f"Created zip file: {zip_file}")
return True
except Exception as e:
if logger:
logger.error(f"Failed to create zip file {zip_file}: {str(e)}")
return False
def execute_command(command: str, description: str, logger: Optional[logging.Logger] = None, dry_run: bool = False) -> bool:
"""
Execute a shell command with proper error handling.
Args:
command: The command to execute
description: A description of the command
logger: The logger to use
dry_run: Whether to perform a dry run
Returns:
True if the command was executed successfully, False otherwise
"""
if logger:
logger.info(description)
if dry_run:
if logger:
logger.info(f"DRY RUN: Would run command: {command}")
return True
if logger:
logger.info(f"Running command: {command}")
try:
result = subprocess.run(command, shell=True, check=True, capture_output=True, text=True)
if logger and result.stdout:
logger.debug(f"Command output: {result.stdout}")
return True
except subprocess.CalledProcessError as e:
if logger:
logger.error(f"Command failed with exit code {e.returncode}")
logger.error(f"Command output (stdout): {e.stdout}")
logger.error(f"Command output (stderr): {e.stderr}")
return False
except Exception as e:
if logger:
logger.error(f"Failed to execute command: {str(e)}")
return False
+220
View File
@@ -0,0 +1,220 @@
"""
Logging utility functions.
"""
import os
import logging
from typing import Optional, Dict, Any
def setup_logger(
name: str,
log_file: Optional[str] = None,
level: int = logging.INFO,
format_string: Optional[str] = None,
file_level: Optional[int] = None,
console_level: Optional[int] = None,
) -> logging.Logger:
"""
Set up a logger with console and file handlers.
Args:
name: The name of the logger
log_file: The log file to write to (optional)
level: The default logging level
format_string: The format string to use for log messages
file_level: The logging level for the file handler (defaults to level)
console_level: The logging level for the console handler (defaults to level)
Returns:
The configured logger
"""
if format_string is None:
format_string = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
if file_level is None:
file_level = level
if console_level is None:
console_level = level
# Create logger
logger = logging.getLogger(name)
logger.setLevel(level)
# Remove existing handlers to avoid duplicates
for handler in logger.handlers[:]:
logger.removeHandler(handler)
# Create formatter
formatter = logging.Formatter(format_string)
# Create console handler
console_handler = logging.StreamHandler()
console_handler.setLevel(console_level)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
# Create file handler if log_file is provided
if log_file:
# Create directory if it doesn't exist
os.makedirs(os.path.dirname(log_file), exist_ok=True)
file_handler = logging.FileHandler(log_file)
file_handler.setLevel(file_level)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
return logger
def get_log_level_from_string(level_str: str) -> int:
"""
Convert a string log level to a logging level constant.
Args:
level_str: The string log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
Returns:
The corresponding logging level constant
Raises:
ValueError: If the string log level is invalid
"""
level_map = {
"DEBUG": logging.DEBUG,
"INFO": logging.INFO,
"WARNING": logging.WARNING,
"ERROR": logging.ERROR,
"CRITICAL": logging.CRITICAL,
}
level_str = level_str.upper()
if level_str not in level_map:
valid_levels = ", ".join(level_map.keys())
raise ValueError(f"Invalid log level: {level_str}. Valid levels are: {valid_levels}")
return level_map[level_str]
def configure_logger_from_config(
name: str,
config: Dict[str, Any],
default_level: int = logging.INFO,
default_format: str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
) -> logging.Logger:
"""
Configure a logger from a configuration dictionary.
Args:
name: The name of the logger
config: The configuration dictionary
default_level: The default logging level
default_format: The default format string
Returns:
The configured logger
"""
log_config = config.get("logging", {})
# Get log level
level_str = log_config.get("level", "INFO")
try:
level = get_log_level_from_string(level_str)
except ValueError:
level = default_level
# Get log format
format_string = log_config.get("format", default_format)
# Get log file
log_file = log_config.get("file")
# Get file and console levels
file_level_str = log_config.get("file_level")
console_level_str = log_config.get("console_level")
file_level = None
if file_level_str:
try:
file_level = get_log_level_from_string(file_level_str)
except ValueError:
pass
console_level = None
if console_level_str:
try:
console_level = get_log_level_from_string(console_level_str)
except ValueError:
pass
return setup_logger(
name=name,
log_file=log_file,
level=level,
format_string=format_string,
file_level=file_level,
console_level=console_level,
)
def log_section(logger: logging.Logger, section_name: str, level: int = logging.INFO) -> None:
"""
Log a section header.
Args:
logger: The logger to use
section_name: The name of the section
level: The logging level
"""
separator = "=" * 80
logger.log(level, separator)
logger.log(level, f" {section_name} ".center(80, "="))
logger.log(level, separator)
def log_subsection(logger: logging.Logger, subsection_name: str, level: int = logging.INFO) -> None:
"""
Log a subsection header.
Args:
logger: The logger to use
subsection_name: The name of the subsection
level: The logging level
"""
separator = "-" * 60
logger.log(level, separator)
logger.log(level, f" {subsection_name} ".center(60, "-"))
logger.log(level, separator)
def log_dict(logger: logging.Logger, data: Dict[str, Any], title: Optional[str] = None, level: int = logging.INFO) -> None:
"""
Log a dictionary.
Args:
logger: The logger to use
data: The dictionary to log
title: The title to use (optional)
level: The logging level
"""
import json
if title:
logger.log(level, f"{title}:")
formatted_json = json.dumps(data, indent=2)
for line in formatted_json.splitlines():
logger.log(level, line)
def log_exception(logger: logging.Logger, exception: Exception, message: str = "An error occurred") -> None:
"""
Log an exception.
Args:
logger: The logger to use
exception: The exception to log
message: The message to log
"""
logger.error(f"{message}: {str(exception)}", exc_info=True)
+311
View File
@@ -0,0 +1,311 @@
"""
Path utility functions.
"""
import os
import glob
import shutil
from typing import List, Optional, Dict, Any, Union
import logging
def normalize_path(path: str) -> str:
"""
Normalize a path to use the correct path separator for the current OS.
Args:
path: The path to normalize
Returns:
The normalized path
"""
return os.path.normpath(path)
def join_paths(*paths: str) -> str:
"""
Join paths using the correct path separator for the current OS.
Args:
*paths: The paths to join
Returns:
The joined path
"""
return os.path.join(*paths)
def get_absolute_path(path: str) -> str:
"""
Get the absolute path of a path.
Args:
path: The path to get the absolute path of
Returns:
The absolute path
"""
return os.path.abspath(path)
def get_relative_path(path: str, start: Optional[str] = None) -> str:
"""
Get the relative path of a path.
Args:
path: The path to get the relative path of
start: The start path (defaults to the current working directory)
Returns:
The relative path
"""
if start is None:
start = os.getcwd()
return os.path.relpath(path, start)
def get_parent_directory(path: str) -> str:
"""
Get the parent directory of a path.
Args:
path: The path to get the parent directory of
Returns:
The parent directory
"""
return os.path.dirname(path)
def get_filename(path: str) -> str:
"""
Get the filename from a path.
Args:
path: The path to get the filename from
Returns:
The filename
"""
return os.path.basename(path)
def get_filename_without_extension(path: str) -> str:
"""
Get the filename without extension from a path.
Args:
path: The path to get the filename without extension from
Returns:
The filename without extension
"""
return os.path.splitext(os.path.basename(path))[0]
def get_file_extension(path: str) -> str:
"""
Get the file extension from a path.
Args:
path: The path to get the file extension from
Returns:
The file extension (including the dot)
"""
return os.path.splitext(path)[1]
def create_directory(directory: str, logger: Optional[logging.Logger] = None) -> bool:
"""
Create a directory if it doesn't exist.
Args:
directory: The directory to create
logger: The logger to use
Returns:
True if the directory was created or already exists, False otherwise
"""
try:
os.makedirs(directory, exist_ok=True)
if logger:
logger.info(f"Created directory: {directory}")
return True
except Exception as e:
if logger:
logger.error(f"Failed to create directory {directory}: {str(e)}")
return False
def delete_directory(directory: str, logger: Optional[logging.Logger] = None) -> bool:
"""
Delete a directory if it exists.
Args:
directory: The directory to delete
logger: The logger to use
Returns:
True if the directory was deleted or doesn't exist, False otherwise
"""
if not os.path.exists(directory):
return True
try:
shutil.rmtree(directory)
if logger:
logger.info(f"Deleted directory: {directory}")
return True
except Exception as e:
if logger:
logger.error(f"Failed to delete directory {directory}: {str(e)}")
return False
def list_files(directory: str, pattern: str = "*") -> List[str]:
"""
List files in a directory matching a pattern.
Args:
directory: The directory to list files in
pattern: The glob pattern to match files against
Returns:
A list of file paths
"""
return glob.glob(os.path.join(directory, pattern))
def list_directories(directory: str) -> List[str]:
"""
List subdirectories in a directory.
Args:
directory: The directory to list subdirectories in
Returns:
A list of directory paths
"""
return [
os.path.join(directory, d) for d in os.listdir(directory)
if os.path.isdir(os.path.join(directory, d))
]
def get_file_info(file_path: str) -> Dict[str, Any]:
"""
Get information about a file.
Args:
file_path: The path to the file
Returns:
A dictionary with file information
"""
if not os.path.isfile(file_path):
return {}
stat = os.stat(file_path)
return {
"path": file_path,
"size": stat.st_size,
"created": stat.st_ctime,
"modified": stat.st_mtime,
"accessed": stat.st_atime,
"filename": os.path.basename(file_path),
"extension": os.path.splitext(file_path)[1],
"directory": os.path.dirname(file_path),
}
def find_files_by_extension(directory: str, extension: str, recursive: bool = True) -> List[str]:
"""
Find files with a specific extension in a directory.
Args:
directory: The directory to search in
extension: The file extension to search for (with or without the dot)
recursive: Whether to search recursively
Returns:
A list of file paths
"""
if not extension.startswith("."):
extension = f".{extension}"
if recursive:
pattern = os.path.join(directory, f"**/*{extension}")
return glob.glob(pattern, recursive=True)
else:
pattern = os.path.join(directory, f"*{extension}")
return glob.glob(pattern)
def copy_directory(source: str, destination: str, logger: Optional[logging.Logger] = None) -> bool:
"""
Copy a directory.
Args:
source: The source directory
destination: The destination directory
logger: The logger to use
Returns:
True if the directory was copied successfully, False otherwise
"""
try:
shutil.copytree(source, destination)
if logger:
logger.info(f"Copied directory from {source} to {destination}")
return True
except Exception as e:
if logger:
logger.error(f"Failed to copy directory from {source} to {destination}: {str(e)}")
return False
def move_directory(source: str, destination: str, logger: Optional[logging.Logger] = None) -> bool:
"""
Move a directory.
Args:
source: The source directory
destination: The destination directory
logger: The logger to use
Returns:
True if the directory was moved successfully, False otherwise
"""
try:
shutil.move(source, destination)
if logger:
logger.info(f"Moved directory from {source} to {destination}")
return True
except Exception as e:
if logger:
logger.error(f"Failed to move directory from {source} to {destination}: {str(e)}")
return False
def get_directory_size(directory: str) -> int:
"""
Get the total size of a directory in bytes.
Args:
directory: The directory to get the size of
Returns:
The total size in bytes
"""
total_size = 0
for dirpath, dirnames, filenames in os.walk(directory):
for filename in filenames:
file_path = os.path.join(dirpath, filename)
if os.path.isfile(file_path):
total_size += os.path.getsize(file_path)
return total_size
+187
View File
@@ -0,0 +1,187 @@
"""
String utility functions.
"""
import re
import unicodedata
from typing import Optional, List, Dict, Any
def slugify(value: str, allow_unicode: bool = False) -> str:
"""
Convert a string to a URL-friendly slug.
Args:
value: The string to convert
allow_unicode: Whether to allow Unicode characters
Returns:
The slugified string
"""
if allow_unicode:
value = unicodedata.normalize("NFKC", value)
else:
value = (
unicodedata.normalize("NFKD", value)
.encode("ascii", "ignore")
.decode("ascii")
)
value = re.sub(r"[^\w\s-]", "", value.lower())
value = re.sub(r"[-\s]+", "-", value).strip("-_")
return value
def truncate_string(value: str, max_length: int, suffix: str = "...") -> str:
"""
Truncate a string to a maximum length.
Args:
value: The string to truncate
max_length: The maximum length
suffix: The suffix to append if truncated
Returns:
The truncated string
"""
if len(value) <= max_length:
return value
return value[:max_length - len(suffix)] + suffix
def extract_artist_and_title(filename: str) -> Dict[str, str]:
"""
Extract artist and title from a filename.
Args:
filename: The filename to extract from
Returns:
A dictionary with "artist" and "title" keys
"""
# Remove file extension
name_without_ext = re.sub(r"\.[^.]+$", "", filename)
# Try to split by " - " first
parts = name_without_ext.split(" - ", 1)
if len(parts) == 2:
return {"artist": parts[0].strip(), "title": parts[1].strip()}
# Try to split by "-" if " - " didn't work
parts = name_without_ext.split("-", 1)
if len(parts) == 2:
return {"artist": parts[0].strip(), "title": parts[1].strip()}
# If no separator found, use the whole name as the title
return {"artist": "", "title": name_without_ext.strip()}
def format_duration(seconds: int) -> str:
"""
Format a duration in seconds to a human-readable string.
Args:
seconds: The duration in seconds
Returns:
The formatted duration string (MM:SS)
"""
minutes, seconds = divmod(seconds, 60)
return f"{minutes:02d}:{seconds:02d}"
def format_filesize(size_bytes: int) -> str:
"""
Format a file size in bytes to a human-readable string.
Args:
size_bytes: The file size in bytes
Returns:
The formatted file size string
"""
if size_bytes < 1024:
return f"{size_bytes} B"
size_kb = size_bytes / 1024
if size_kb < 1024:
return f"{size_kb:.1f} KB"
size_mb = size_kb / 1024
if size_mb < 1024:
return f"{size_mb:.1f} MB"
size_gb = size_mb / 1024
return f"{size_gb:.1f} GB"
def strip_html_tags(html: str) -> str:
"""
Strip HTML tags from a string.
Args:
html: The HTML string
Returns:
The string with HTML tags removed
"""
return re.sub(r"<[^>]+>", "", html)
def normalize_whitespace(text: str) -> str:
"""
Normalize whitespace in a string.
Args:
text: The string to normalize
Returns:
The string with normalized whitespace
"""
# Replace multiple whitespace characters with a single space
return re.sub(r"\s+", " ", text).strip()
def extract_urls(text: str) -> List[str]:
"""
Extract URLs from a string.
Args:
text: The string to extract URLs from
Returns:
A list of URLs
"""
url_pattern = r"https?://[^\s]+"
return re.findall(url_pattern, text)
def replace_placeholders(template: str, data: Dict[str, Any]) -> str:
"""
Replace placeholders in a template string with values from a dictionary.
Args:
template: The template string with {placeholder} syntax
data: The dictionary with placeholder values
Returns:
The template with placeholders replaced
"""
return template.format(**data)
def generate_random_string(length: int = 8) -> str:
"""
Generate a random string of a specified length.
Args:
length: The length of the random string
Returns:
The random string
"""
import random
import string
characters = string.ascii_letters + string.digits
return "".join(random.choice(characters) for _ in range(length))
+230
View File
@@ -0,0 +1,230 @@
"""
Validation utility functions.
"""
import os
import logging
from typing import Optional, Dict, Any, List, Callable
def is_url(string: str) -> bool:
"""
Check if a string is a URL.
Args:
string: The string to check
Returns:
True if the string is a URL, False otherwise
"""
return string.startswith("http://") or string.startswith("https://")
def is_file(string: str) -> bool:
"""
Check if a string is a valid file.
Args:
string: The string to check
Returns:
True if the string is a valid file, False otherwise
"""
return os.path.isfile(string)
def is_directory(string: str) -> bool:
"""
Check if a string is a valid directory.
Args:
string: The string to check
Returns:
True if the string is a valid directory, False otherwise
"""
return os.path.isdir(string)
def prompt_user_confirmation_or_raise_exception(
prompt_message: str,
exit_message: str,
allow_empty: bool = False,
non_interactive: bool = False,
logger: Optional[logging.Logger] = None
) -> None:
"""
Prompt the user for confirmation or raise an exception.
Args:
prompt_message: The message to display to the user
exit_message: The message to display if the user does not confirm
allow_empty: Whether to allow an empty response
non_interactive: Whether to automatically confirm in non-interactive mode
logger: The logger to use
Raises:
Exception: If the user does not confirm
"""
if non_interactive:
if logger:
logger.info(f"Non-interactive mode, automatically confirming: {prompt_message}")
return
if not prompt_user_bool(prompt_message, allow_empty=allow_empty):
if logger:
logger.error(exit_message)
raise Exception(exit_message)
def prompt_user_bool(prompt_message: str, allow_empty: bool = False) -> bool:
"""
Prompt the user for a boolean value.
Args:
prompt_message: The message to display to the user
allow_empty: Whether to allow an empty response
Returns:
True if the user confirms, False otherwise
"""
options_string = "[y]/n" if allow_empty else "y/[n]"
accept_responses = ["y", "yes"]
if allow_empty:
accept_responses.append("")
print()
response = input(f"{prompt_message} {options_string} ").strip().lower()
return response in accept_responses
def validate_input_parameters_for_features(
config: Dict[str, Any],
logger: Optional[logging.Logger] = None,
prompt_confirmation: Optional[Callable] = None
) -> Dict[str, bool]:
"""
Validate input parameters for enabled features.
Args:
config: The configuration dictionary
logger: The logger to use
prompt_confirmation: A function to prompt the user for confirmation
Returns:
A dictionary of enabled features
Raises:
Exception: If validation fails
"""
if logger:
logger.info(f"Validating input parameters for enabled features...")
current_directory = os.getcwd()
if logger:
logger.info(f"Current directory to process: {current_directory}")
enabled_features = {
"youtube_upload": False,
"discord_notification": False,
"folder_organisation": False,
"public_share_copy": False,
"public_share_rclone": False,
"cdg_zip_creation": config.get("enable_cdg", False),
"txt_zip_creation": config.get("enable_txt", False)
}
# Enable youtube upload if client secrets file is provided and is valid JSON
youtube_client_secrets_file = config.get("youtube_client_secrets_file")
youtube_description_file = config.get("youtube_description_file")
if youtube_client_secrets_file is not None and youtube_description_file is not None:
if not os.path.isfile(youtube_client_secrets_file):
raise Exception(f"YouTube client secrets file does not exist: {youtube_client_secrets_file}")
if not os.path.isfile(youtube_description_file):
raise Exception(f"YouTube description file does not exist: {youtube_description_file}")
# Test parsing the file as JSON to check it's valid
try:
import json
with open(youtube_client_secrets_file, "r") as f:
json.load(f)
except json.JSONDecodeError as e:
raise Exception(f"YouTube client secrets file is not valid JSON: {youtube_client_secrets_file}") from e
if logger:
logger.debug(f"YouTube upload checks passed, enabling YouTube upload")
enabled_features["youtube_upload"] = True
# Enable discord notifications if webhook URL is provided and is valid URL
discord_webhook_url = config.get("discord_webhook_url")
if discord_webhook_url is not None:
if not discord_webhook_url.startswith("https://discord.com/api/webhooks/"):
raise Exception(f"Discord webhook URL is not valid: {discord_webhook_url}")
if logger:
logger.debug(f"Discord webhook URL checks passed, enabling Discord notifications")
enabled_features["discord_notification"] = True
# Enable folder organisation if brand prefix and target directory are provided and target directory is valid
brand_prefix = config.get("brand_prefix")
organised_dir = config.get("organised_dir")
if brand_prefix is not None and organised_dir is not None:
if not os.path.isdir(organised_dir):
raise Exception(f"Target directory does not exist: {organised_dir}")
if logger:
logger.debug(f"Brand prefix and target directory provided, enabling folder organisation")
enabled_features["folder_organisation"] = True
# Enable public share copy if public share directory is provided and is valid directory with MP4 and CDG subdirectories
public_share_dir = config.get("public_share_dir")
if public_share_dir is not None:
if not os.path.isdir(public_share_dir):
raise Exception(f"Public share directory does not exist: {public_share_dir}")
mp4_dir = os.path.join(public_share_dir, "MP4")
cdg_dir = os.path.join(public_share_dir, "CDG")
if not os.path.isdir(mp4_dir):
os.makedirs(mp4_dir, exist_ok=True)
if logger:
logger.info(f"Created MP4 subdirectory: {mp4_dir}")
if not os.path.isdir(cdg_dir):
os.makedirs(cdg_dir, exist_ok=True)
if logger:
logger.info(f"Created CDG subdirectory: {cdg_dir}")
if logger:
logger.debug(f"Public share directory checks passed, enabling public share copy")
enabled_features["public_share_copy"] = True
# Enable public share rclone if rclone destination is provided
rclone_destination = config.get("rclone_destination")
if rclone_destination is not None:
if logger:
logger.debug(f"Rclone destination provided, enabling rclone sync")
enabled_features["public_share_rclone"] = True
# Tell user which features are enabled, prompt them to confirm before proceeding
if logger:
logger.info(f"Enabled features:")
logger.info(f" CDG ZIP creation: {enabled_features['cdg_zip_creation']}")
logger.info(f" TXT ZIP creation: {enabled_features['txt_zip_creation']}")
logger.info(f" YouTube upload: {enabled_features['youtube_upload']}")
logger.info(f" Discord notifications: {enabled_features['discord_notification']}")
logger.info(f" Folder organisation: {enabled_features['folder_organisation']}")
logger.info(f" Public share copy: {enabled_features['public_share_copy']}")
logger.info(f" Public share rclone: {enabled_features['public_share_rclone']}")
if prompt_confirmation:
prompt_confirmation(
f"Confirm features enabled log messages above match your expectations for finalisation?",
"Refusing to proceed without user confirmation they're happy with enabled features.",
allow_empty=True,
)
return enabled_features
-1
View File
@@ -1 +0,0 @@
from .karaoke_prep import KaraokePrep
-433
View File
@@ -1,433 +0,0 @@
import os
import re
import glob
import yt_dlp
import logging
import lyricsgenius
import subprocess
from PIL import Image, ImageDraw, ImageFont
class KaraokePrep:
def __init__(
self,
url=None,
artist=None,
title=None,
log_level=logging.DEBUG,
log_formatter=None,
model_name="UVR_MDXNET_KARA_2",
model_name_2="UVR-MDX-NET-Inst_HQ_3",
model_file_dir="/tmp/audio-separator-models/",
output_dir=".",
output_format="WAV",
use_cuda=False,
use_coreml=False,
normalization_enabled=True,
denoise_enabled=True,
create_track_subfolders=False,
intro_background_color="#000000",
intro_background_image=None,
intro_font="AvenirNext-Bold.ttf",
intro_artist_color="#ff7acc",
intro_title_color="#ffdf6b",
):
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.intro_background_color = intro_background_color
self.intro_background_image = intro_background_image
self.intro_font = intro_font
self.intro_artist_color = intro_artist_color
self.intro_title_color = intro_title_color
self.logger.debug(f"KaraokePrep output_format: {self.output_format}")
if not os.path.exists(self.output_dir):
self.logger.debug(f"Overall output dir {self.output_dir} did not exist, creating")
os.makedirs(self.output_dir)
else:
self.logger.debug(f"Overall output dir {self.output_dir} already exists")
def extract_metadata_from_url(self):
"""
Extracts metadata from the YouTube URL.
"""
if self.url:
with yt_dlp.YoutubeDL({"quiet": True}) as ydl:
info = ydl.extract_info(self.url, download=False)
self.artist, self.title = self.parse_metadata(info)
if self.artist and self.title:
self.logger.info(f"Extracted artist: {self.artist}, title: {self.title}")
else:
self.logger.error("Failed to extract artist and title from the YouTube URL.")
def parse_metadata(self, info):
"""
Parses the metadata to extract artist and title.
:param info: The metadata information extracted from yt_dlp.
:return: A tuple containing the artist and title.
"""
# Default values if parsing fails
artist = ""
title = ""
# Example: "Artist - Title"
if "title" in info and "-" in info["title"]:
artist, title = info["title"].split("-", 1)
artist = artist.strip()
title = title.strip()
elif "uploader" in info:
# Fallback to uploader as artist if title parsing fails
artist = info["uploader"]
if "title" in info:
title = info["title"].strip()
# If unable to parse, log an appropriate message
if not artist or not title:
self.logger.warning("Could not parse artist and title from the video metadata.")
return artist, title
def get_youtube_id_for_top_search_result(self, query):
ydl_opts = {"quiet": "True", "format": "bestaudio", "noplaylist": "True", "extract_flat": True}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
video = ydl.extract_info(f"ytsearch1:{query}", download=False)["entries"][0]
if video:
youtube_id = video.get("id")
return youtube_id
else:
self.logger.warning(f"No YouTube results found for query: {query}")
return None
def download_video(self, youtube_id, output_filename_no_extension):
self.logger.debug(f"Downloading YouTube video {youtube_id} to filename {output_filename_no_extension} + (as yet) unknown extension")
ydl_opts = {
"format": "bv*+ba/b", # if a combined video + audio format is better than the best video-only format use the combined format
"outtmpl": f"{output_filename_no_extension}",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",
}
with yt_dlp.YoutubeDL(ydl_opts) as youtube_dl_instance:
youtube_dl_instance.download([f"https://www.youtube.com/watch?v={youtube_id}"])
self.logger.warn(f"Download finished, assuming hard-coded webm extension (!) and returning this filename")
# TODO: Replace hard-coded webm extension with the actual extension of the downloaded file using yt-dlp hooks / event callback
return output_filename_no_extension + ".webm"
def extract_still_image_from_video(self, input_filename, output_filename_no_extension):
output_filename = output_filename_no_extension + ".png"
self.logger.debug(f"Extracting still image from position 30s YouTube video to {output_filename}")
os.system(f'ffmpeg -i "{input_filename}" -ss 00:00:30 -vframes 1 "{output_filename}"')
return output_filename
def convert_to_wav(self, input_filename, output_filename_no_extension):
output_filename = output_filename_no_extension + ".wav"
self.logger.debug(f"Converting {input_filename} to WAV file {output_filename}")
os.system(f'ffmpeg -i "{input_filename}" "{output_filename}"')
return output_filename
def write_lyrics_from_genius(self, artist, title, filename):
genius = lyricsgenius.Genius(os.environ["GENIUS_API_TOKEN"])
song = genius.search_song(title, artist)
if song:
lyrics = self.clean_genius_lyrics(song.lyrics)
with open(filename, "w") as f:
f.write(lyrics)
self.logger.info("Lyrics for %s by %s fetched successfully", title, artist)
else:
self.logger.warning("Could not find lyrics for %s by %s", title, artist)
def clean_genius_lyrics(self, lyrics):
lyrics = lyrics.replace("\\n", "\n")
lyrics = re.sub(r"You might also like", "", lyrics)
lyrics = re.sub(
r".*?Lyrics([A-Z])", r"\1", lyrics
) # Remove the song name and word "Lyrics" if this has a non-newline char at the start
lyrics = re.sub(r"[0-9]+Embed$", "", lyrics) # Remove the word "Embed" at end of line with preceding numbers if found
lyrics = re.sub(r"(\S)Embed$", r"\1", lyrics) # Remove the word "Embed" if it has been tacked onto a word at the end of a line
lyrics = re.sub(r"^Embed$", r"", lyrics) # Remove the word "Embed" if it has been tacked onto a word at the end of a line
lyrics = re.sub(r".*?\[.*?\].*?", "", lyrics) # Remove lines containing square brackets
# add any additional cleaning rules here
return lyrics
def sanitize_filename(self, filename):
"""Replace or remove characters that are unsafe for filenames."""
# Replace problematic characters with underscores
for char in ["\\", "/", ":", "*", "?", '"', "<", ">", "|"]:
filename = filename.replace(char, "_")
# Remove any trailing periods or spaces
filename = filename.rstrip(". ")
return filename
def separate_audio(self, audio_file, model_name, instrumental_path, vocals_path):
if audio_file is None or not os.path.isfile(audio_file):
raise Exception("Error: Invalid audio source provided.")
self.logger.debug(f"audio_file is valid file: {audio_file}")
self.logger.debug(
f"instantiating Separator with model_name: {model_name} instrumental_path: {instrumental_path} and output_format: {self.output_format}"
)
from audio_separator import Separator
separator = Separator(
audio_file,
log_level=self.log_level,
log_formatter=self.log_formatter,
model_name=model_name,
model_file_dir=self.model_file_dir,
output_format=self.output_format,
primary_stem_path=instrumental_path,
secondary_stem_path=vocals_path,
)
_, _ = separator.separate()
self.logger.debug(f"Separation complete!")
def setup_output_paths(self, artist, title):
sanitized_artist = self.sanitize_filename(artist)
sanitized_title = self.sanitize_filename(title)
artist_title = f"{sanitized_artist} - {sanitized_title}"
track_output_dir = self.output_dir
if self.create_track_subfolders:
track_output_dir = os.path.join(self.output_dir, f"{artist_title}")
if not os.path.exists(track_output_dir):
self.logger.debug(f"Output dir {track_output_dir} did not exist, creating")
os.makedirs(track_output_dir)
return track_output_dir, artist_title
def create_intro_video(self, artist, title, output_filename):
duration = 5 # Duration in seconds
resolution = (3840, 2160) # 4K resolution
font_size = 400 # Adjust as needed
line_spacing = 50 # Adjust as needed
# Load or create background image
if self.intro_background_image:
background = Image.open(self.intro_background_image)
else:
background = Image.new("RGB", resolution, color=self.hex_to_rgb(self.intro_background_color))
# Resize background to match resolution
background = background.resize(resolution)
# Create an ImageDraw instance
draw = ImageDraw.Draw(background)
# Check if the font file exists, if not use a default font
if os.path.exists(self.intro_font):
font = ImageFont.truetype(self.intro_font, size=font_size)
else:
self.logger.warning(f"Font file not found: {self.intro_font}. Using default font.")
font = ImageFont.load_default(size=font_size)
# Calculate text width using the ImageDraw instance
artist_text_width = draw.textlength(artist, font=font)
title_text_width = draw.textlength(title, font=font)
# Calculate text positions
artist_text_position = ((resolution[0] - artist_text_width) // 2, resolution[1] // 2 - font_size - line_spacing)
title_text_position = ((resolution[0] - title_text_width) // 2, resolution[1] // 2 + line_spacing)
# Draw text
draw.text(artist_text_position, artist, fill=self.intro_artist_color, font=font)
draw.text(title_text_position, title, fill=self.intro_title_color, font=font)
# Save to a temporary image file
temp_image_path = "/tmp/temp_background.png"
background.save(temp_image_path)
self.logger.warning(f"Temporarily saving background image to {temp_image_path}")
# Use ffmpeg to create video
ffmpeg_command = [
"ffmpeg",
"-y", # Overwrite output files without asking
"-loop", # Loop the input image
"1", # Loop the input image
"-i", # Input file
temp_image_path, # Input file
"-c:v", # Video codec
"libx264", # Video codec
"-t", # Duration
str(duration), # Duration
"-pix_fmt", # Pixel format
"yuv420p", # Pixel format
"-vf", # Video filter
f"scale={resolution[0]}:{resolution[1]}", # Video filter
output_filename, # Output filename
]
subprocess.run(ffmpeg_command)
# os.remove(temp_image_path)
def hex_to_rgb(self, hex_color):
"""Convert hex color to RGB tuple."""
hex_color = hex_color.lstrip("#")
return tuple(int(hex_color[i : i + 2], 16) for i in (0, 2, 4))
def prep_single_track(self):
if self.artist is None or self.title is None:
self.logger.warn(f"Artist or Title nor specified manually, guessing from YouTube metadata...")
self.extract_metadata_from_url()
artist = self.artist
title = self.title
self.logger.info(f"Downloading inputs for track: {title} by {artist}")
track_output_dir, artist_title = self.setup_output_paths(artist, title)
processed_track = {
"track_output_dir": track_output_dir,
"artist": artist,
"title": title,
}
yt_webm_filename_pattern = os.path.join(track_output_dir, f"{artist_title} (YouTube *.webm")
yt_webm_glob = glob.glob(yt_webm_filename_pattern)
yt_png_filename_pattern = os.path.join(track_output_dir, f"{artist_title} (YouTube *.png")
yt_png_glob = glob.glob(yt_png_filename_pattern)
yt_wav_filename_pattern = os.path.join(track_output_dir, f"{artist_title} (YouTube *.wav")
yt_wav_glob = glob.glob(yt_wav_filename_pattern)
processed_track["youtube_video"] = None
processed_track["youtube_still_image"] = None
processed_track["youtube_audio"] = None
if yt_webm_glob and yt_png_glob and yt_wav_glob:
processed_track["youtube_video"] = yt_webm_glob[0]
processed_track["youtube_still_image"] = yt_png_glob[0]
processed_track["youtube_audio"] = yt_wav_glob[0]
self.logger.debug(f"YouTube output files already exist, skipping download: {processed_track['youtube_video']} + .wav + .png")
else:
if self.url is None:
self.logger.warn(f"No URL specified - the top result from YouTube will be used.")
self.logger.info("Searching YouTube for video ID...")
query = f"{artist} {title}"
youtube_id = self.get_youtube_id_for_top_search_result(query)
else:
self.logger.info("Parsing YouTube video ID from URL...")
youtube_id = self.url.split("watch?v=")[1]
if youtube_id:
output_filename_no_extension = os.path.join(track_output_dir, f"{artist_title} (YouTube {youtube_id})")
self.logger.info("Downloading original video from YouTube...")
processed_track["youtube_video"] = self.download_video(youtube_id, output_filename_no_extension)
self.logger.info("Extracting still image from downloaded video...")
processed_track["youtube_still_image"] = self.extract_still_image_from_video(
processed_track["youtube_video"], output_filename_no_extension
)
self.logger.info("Converting downloaded video to WAV for audio processing...")
processed_track["youtube_audio"] = self.convert_to_wav(processed_track["youtube_video"], output_filename_no_extension)
else:
self.logger.warning(f"Skipping {title} by {artist} due to missing YouTube ID.")
lyrics_file = os.path.join(track_output_dir, f"{artist_title} (Lyrics).txt")
if os.path.exists(lyrics_file):
self.logger.debug(f"Lyrics file already exists, skipping fetch: {lyrics_file}")
else:
self.logger.info("Fetching lyrics from Genius...")
self.write_lyrics_from_genius(artist, title, lyrics_file)
processed_track["lyrics"] = lyrics_file
intro_filename = os.path.join(track_output_dir, f"{artist_title} (Intro).mp4")
self.create_intro_video(artist, title, intro_filename)
self.logger.info(f"Separating audio twice for track: {title} by {artist}")
instrumental_path = os.path.join(track_output_dir, f"{artist_title} (Instrumental {self.model_name}).{self.output_format}")
vocals_path = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name}).{self.output_format}")
if os.path.isfile(instrumental_path) and os.path.isfile(vocals_path):
self.logger.debug(f"Separated audio files already exist in output paths, skipping separation: {instrumental_path}")
else:
self.separate_audio(processed_track["youtube_audio"], self.model_name, instrumental_path, vocals_path)
processed_track["instrumental_audio"] = instrumental_path
processed_track["vocals_audio"] = vocals_path
instrumental_path_2 = os.path.join(track_output_dir, f"{artist_title} (Instrumental {self.model_name_2}).{self.output_format}")
vocals_path_2 = os.path.join(track_output_dir, f"{artist_title} (Vocals {self.model_name_2}).{self.output_format}")
if os.path.isfile(instrumental_path_2) and os.path.isfile(vocals_path_2):
self.logger.debug(f"Separated audio files already exist in output paths, skipping separation: {instrumental_path_2}")
else:
self.separate_audio(processed_track["youtube_audio"], self.model_name_2, instrumental_path_2, vocals_path_2)
processed_track["instrumental_audio_2"] = instrumental_path_2
processed_track["vocals_audio_2"] = vocals_path_2
self.logger.info("Script finished, audio downloaded, lyrics fetched and audio separated!")
return processed_track
def is_playlist_url(self):
"""
Checks if the provided URL is a YouTube playlist URL.
"""
if self.url and "playlist?list=" in self.url:
return True
return False
def process_playlist(self):
"""
Processes all videos in a YouTube playlist.
"""
self.logger.debug("Querying playlist metadata from YouTube...")
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 = None
self.title = None
return track_results
def process(self):
if self.is_playlist_url():
self.logger.info(f"Provided YouTube URL is a playlist, beginning batch operation")
return self.process_playlist()
else:
self.logger.info(f"Provided YouTube URL is NOT a playlist, processing single track")
return [self.prep_single_track()]
View File
Whitespace-only changes.
-192
View File
@@ -1,192 +0,0 @@
#!/usr/bin/env python
import argparse
import logging
import pkg_resources
from karaoke_prep import KaraokePrep
def is_url(string):
"""Simple check to determine if a string is a URL."""
return string.startswith("http://") or string.startswith("https://")
def main():
logger = logging.getLogger(__name__)
log_handler = logging.StreamHandler()
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(
"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",
)
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",
)
parser.add_argument(
"--intro_background_color",
default="black",
help="Optional: Background color for intro video (default: black). Example: --intro_background_color=#123456",
)
parser.add_argument(
"--intro_background_image",
help="Optional: Path to background image for intro video. Overrides background color if provided. Example: --intro_background_image=path/to/image.jpg",
)
parser.add_argument(
"--intro_font",
default="AvenirNext-Bold.ttf",
help="Optional: Font file for intro video (default: Avenir-Next-Bold). Example: --intro_font=AvenirNext-Bold.ttf",
)
parser.add_argument(
"--intro_artist_color",
default="#ff7acc",
help="Optional: Font color for intro video artist text (default: #ff7acc). Example: --intro_artist_color=#123456",
)
parser.add_argument(
"--intro_title_color",
default="#ffdf6b",
help="Optional: Font color for intro video title text (default: #ffdf6b). 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]
else:
logger.warn("URL provided without Artist and Title, these 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,
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,
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" Instrumental: {track['instrumental_audio']}")
logger.info(f" Vocals: {track['vocals_audio']}")
if __name__ == "__main__":
main()
Generated
+5273 -953
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+91
View File
@@ -0,0 +1,91 @@
# Karaoke Prep Functionality Map
This document maps the functionality in the original `old_prep.py` file, showing the line ranges for different functional components.
## Class Definition and Initialization
- **Class Definition**: Lines 25-1808
- **Constructor `__init__`**: Lines 26-306
- Parameter initialization: Lines 26-91
- Logger setup: Lines 92-123
- Basic parameters: Lines 125-133
- Audio processing parameters: Lines 135-141
- Input/Output parameters: Lines 143-148
- Lyrics parameters: Lines 150-160
- Style parameters and loading: Lines 162-237
- Title/End format setup: Lines 239-280
- Video settings: Lines 282-286
- FFmpeg configuration: Lines 288-296
- Debug logging: Lines 298-302
- Initialization of output directory: Lines 304-306
## Helper Methods
- **`parse_region`**: Lines 308-315 - Parses region string to tuple
- **`sanitize_filename`**: Lines 530-536 - Sanitizes filenames for safe use
- **`hex_to_rgb`**: Lines 1181-1184 - Converts hex color to RGB tuple
- **`_file_exists`**: Lines 1499-1505 - Checks if file exists and logs result
- **`_transform_text`**: Lines 1174-1181 - Transforms text based on specified type
## Media Information Extraction
- **`extract_info_for_online_media`**: Lines 317-330 - Extracts info from online media
- **`parse_single_track_metadata`**: Lines 332-382 - Parses metadata from extracted info
## Media Handling
- **`copy_input_media`**: Lines 384-401 - Copies local media file
- **`download_video`**: Lines 403-427 - Downloads video from URL
- **`extract_still_image_from_video`**: Lines 429-436 - Extracts still image from video
- **`convert_to_wav`**: Lines 438-462 - Converts media to WAV format
## Lyrics Processing
- **`find_best_split_point`**: Lines 464-497 - Finds optimal split points for long lines
- **`process_line`**: Lines 499-532 - Processes lyrics lines for optimal display
- **`transcribe_lyrics`**: Lines 538-637 - Handles lyrics transcription via external module
- **`backup_existing_outputs`**: Lines 538-599 - Backs up existing outputs to versioned folder
## Audio Separation
- **`separate_audio`**: Lines 601-653 - Separates audio using audio-separator
- **`process_audio_separation`**: Lines 1186-1311 - Main audio separation process
- **`_create_stems_directory`**: Lines 1313-1318 - Creates stems directory
- **`_separate_clean_instrumental`**: Lines 1320-1344 - Separates clean instrumental
- **`_separate_other_stems`**: Lines 1346-1379 - Separates other stems
- **`_separate_backing_vocals`**: Lines 1381-1405 - Separates backing vocals
- **`_generate_combined_instrumentals`**: Lines 1407-1429 - Combines instrumentals with backing vocals
- **`_normalize_audio_files`**: Lines 1431-1457 - Normalizes audio files
- **`_normalize_audio`**: Lines 1459-1497 - Performs audio normalization
## Output Path Handling
- **`setup_output_paths`**: Lines 655-677 - Sets up output paths for track
## Video and Image Generation
- **`_create_gradient_mask`**: Lines 679-718 - Creates gradient mask for text coloring
- **`calculate_text_size_to_fit`**: Lines 720-771 - Calculates text size to fit in region
- **`_render_text_in_region`**: Lines 773-876 - Renders text in specified region
- **`_draw_bounding_box`**: Lines 878-887 - Draws bounding box around region
- **`create_video`**: Lines 889-934 - Creates video with title, artist, and text
- **`_handle_existing_image`**: Lines 936-960 - Handles existing image for video
- **`_create_background`**: Lines 962-972 - Creates or loads background image
- **`_render_all_text`**: Lines 974-1000 - Renders all text elements on image
- **`_save_output_files`**: Lines 1002-1017 - Saves output image files and creates video
- **`_create_video_from_image`**: Lines 1019-1032 - Creates video from static image
- **`create_title_video`**: Lines 1133-1149 - Creates title video
- **`create_end_video`**: Lines 1151-1167 - Creates end video
## Main Processing Methods
- **`prep_single_track`**: Lines 1507-1661 - Prepares a single track
- **`shutdown`**: Lines 1663-1690 - Handles shutdown signals gracefully
- **`process_playlist`**: Lines 1692-1708 - Processes a playlist
- **`process_folder`**: Lines 1710-1748 - Processes a folder of audio files
- **`process`**: Lines 1750-1782 - Main entry point for processing
## Concurrency and Error Handling
- Signal handling in `prep_single_track`: Lines 1508-1510, 1655-1659
- Task management: Lines 1580-1606
- Exception handling: Throughout methods
## External Dependencies
- Media handling: yt-dlp.YoutubeDL
- Audio processing: audio_separator.separator
- Image processing: PIL (Image, ImageDraw, ImageFont)
- Lyrics transcription: lyrics_transcriber
- Audio manipulation: pydub.AudioSegment
- System utilities: os, sys, re, glob, logging, tempfile, shutil, asyncio, signal, time, fcntl, errno, psutil
- Others: dotenv, json, datetime
+35 -15
View File
@@ -1,29 +1,49 @@
[tool.poetry]
name = "karaoke-prep"
version = "0.4.2"
description = "Prepare for karaoke video creation, by downloading audio and lyrics for a specified song or youtube playlist and separatung audio stems."
name = "karaoke-gen"
version = "0.50.0"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"
readme = "README.md"
packages = [{include = "karaoke_prep"}]
homepage = "https://github.com/karaokenerds/karaoke-prep"
repository = "https://github.com/karaokenerds/karaoke-prep"
documentation = "https://github.com/karaokenerds/karaoke-prep/blob/main/README.md"
packages = [{ include = "karaoke_gen" }]
homepage = "https://github.com/karaokenerds/karaoke-gen"
repository = "https://github.com/karaokenerds/karaoke-gen"
documentation = "https://github.com/karaokenerds/karaoke-gen/blob/main/README.md"
[tool.poetry.dependencies]
python = ">=3.9"
requests = "^2"
beautifulsoup4 = "^4"
python = ">=3.10,<3.13"
torch = "<2.5"
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"
google-api-python-client = "*"
google-auth = "*"
google-auth-oauthlib = "*"
google-auth-httplib2 = "*"
thefuzz = ">=0.22"
numpy = ">=1"
audio-separator = { version = ">=0.21.0", extras = ["cpu"] }
lyrics-converter = ">=0.2.1"
lyrics-transcriber = ">=0.34"
kbputils = "^0.0.16"
attrs = ">=24.2.0"
cattrs = ">=24.1.2"
toml = ">=0.10"
argparse = ">=1.4.0"
psutil = "^7.0.0"
pyperclip = "*"
[tool.poetry.group.dev.dependencies]
black = "^23"
black = ">=23"
poetry = "*"
[tool.poetry.scripts]
karaoke-prep = 'karaoke_prep.utils.cli:main'
karaoke-gen = 'karaoke_gen.cli:main'
karaoke-bulk = 'karaoke_gen.cli.bulk_cli:main'
[tool.black]
line-length = 140
+3
View File
@@ -0,0 +1,3 @@
"""
Test package for the karaoke_gen package.
"""
+714
View File
@@ -0,0 +1,714 @@
[
["This Is Me Smiling", "Prettier"],
["Ленинград", "Алкаш"],
["Cher", "Apples Don't Fall Far From The Tree"],
["The Hush Sound", "Don't Wake Me Up"],
["ABBA", "I Am The City"],
["ABBA", "Under Attack"],
["The Hush Sound", "A Dark Congregation"],
["The Hush Sound", "As You Cry"],
["The Hush Sound", "Boys Are Too Refined"],
["The Hush Sound", "Break the Sky"],
["The Hush Sound", "Carry Me Home"],
["The Hush Sound", "City Traffic Puzzle"],
["The Hush Sound", "Crawling Towards The Sun"],
["The Hush Sound", "Echo"],
["The Hush Sound", "Eileen"],
["The Hush Sound", "Honey"],
["The Hush Sound", "Hospital Bed Crawl"],
["The Hush Sound", "Hourglass"],
["The Hush Sound", "Hurricane"],
["The Hush Sound", "Intro"],
["The Hush Sound", "Lions Roar"],
["The Hush Sound", "Love You Much Better"],
["The Hush Sound", "Magnolia"],
["The Hush Sound", "Medicine Man"],
["The Hush Sound", "Molasses"],
["The Hush Sound", "Momentum"],
["The Hush Sound", "My Apologies"],
["The Hush Sound", "Not Your Concern"],
["The Hush Sound", "Out Through The Curtain"],
["The Hush Sound", "Sweet Tangerine"],
["The Hush Sound", "That's Okay"],
["The Hush Sound", "The Artist"],
["The Hush Sound", "The Market"],
["The Hush Sound", "Tides Change"],
["The Hush Sound", "Unsafe Safe"],
["The Hush Sound", "We Intertwined"],
["The Hush Sound", "Weeping Willow"],
["The Hush Sound", "Where We Went Wrong"],
["The Hush Sound", "Wine Red"],
["The Hush Sound", "You Are The Moon"],
["The Hush Sound", "Lighthouse"],
["Allie X", "GLAM!"],
["Lemaitre", "Rocket Girl (feat. Betty Who)"],
["Just Jack", "253"],
["Just Jack", "All Night Cinema"],
["Just Jack", "Astronaut"],
["Just Jack", "Blood"],
["Just Jack", "Disco Friends"],
["Just Jack", "Doctor Doctor"],
["Just Jack", "Embers"],
["Just Jack", "Glory Days"],
["Just Jack", "Goth In The Disco"],
["Just Jack", "Hold On"],
["Just Jack", "I Talk Too Much"],
["Just Jack", "Life Stories"],
["Just Jack", "Lo And Behold"],
["Just Jack", "Lost"],
["Just Jack", "Mourning Morning"],
["Just Jack", "No Time"],
["Just Jack", "So Wrong"],
["Just Jack", "Spectacular Failures"],
["Just Jack", "Starz in Their Eyes"],
["Just Jack", "Symphony of Sirens"],
["Just Jack", "The Day I Died"],
["Just Jack", "Writers Block"],
[
"Los Campesinos!",
"This Is How You Spell \"HAHAHA, We Destroyed the Hopes and Dreams of a Generation of Faux-Romantics\""
],
["Los Campesinos!", "2007, The Year Punk Broke (My Heart)"],
["Los Campesinos!", "And We Exhale and Roll Our Eyes in Unison"],
["Los Campesinos!", "Broken Heartbeats Sounds Like Breakbeats"],
["Los Campesinos!", "Death to Los Campesinos!"],
["Los Campesinos!", "Don't Tell Me to Do the Math(s)"],
["Los Campesinos!", "Drop It Doe Eyes"],
["Los Campesinos!", "Knee Deep At ATP"],
["Los Campesinos!", "My Year In Lists"],
["Los Campesinos!", "Sweet Dreams, Sweet Cheeks"],
["Los Campesinos!", "We Are All Accelerated Readers"],
["Los Campesinos!", "You! Me! Dancing!"],
["Mew", "156"],
["Mew", "Am I Wry? No"],
["Mew", "Behind the Drapes"],
["Mew", "Comforting Sounds"],
["Mew", "Eight Flew Over, One was Destroyed"],
["Mew", "Her Voice is Beyond Her Years"],
["Mew", "She Came Home for Christmas"],
["Mew", "She Spider"],
["Mew", "Snow Brigade"],
["Mew", "Symmetry"],
["of Montreal", "Gronlandic Edit"],
["Idlewild", "(I Am) What I Am Not"],
["Idlewild", "A Modern Way of Letting Go"],
["Idlewild", "Actually It's Darkness"],
["Idlewild", "American English"],
["Idlewild", "Century After Century"],
["Idlewild", "I Don't Have The Map"],
["Idlewild", "I Never Wanted"],
["Idlewild", "Idea Track"],
["Idlewild", "In Remote Part , Scottish Fiction"],
["Idlewild", "Let Me Sleep (Next To The Mirror)"],
["Idlewild", "Listen To What You've Got"],
["Idlewild", "Little Discourage"],
["Idlewild", "Live in a Hiding Place"],
["Idlewild", "Mistake Pageant"],
["Idlewild", "Out of Routine"],
["Idlewild", "Quiet Crown"],
["Idlewild", "Roseability"],
["Idlewild", "Rusty"],
["Idlewild", "Stay the Same"],
["Idlewild", "Tell Me Ten Words"],
["Idlewild", "The Bronze Medal"],
["Idlewild", "These Wooden Ideas"],
["Idlewild", "You Held the World in Your Arms"],
["Los Campesinos!", "A Heat Rash in the Shape of the Show Me State"],
["Los Campesinos!", "All Your Kayfabe Friends"],
["Los Campesinos!", "Coda A Burn Scar in the Shape of the Sooner State"],
["Los Campesinos!", "Documented Minor Emotional Breakdown #1"],
["Los Campesinos!", "Heart Swells:100-1"],
["Los Campesinos!", "Heart Swells / Pacific Daylight Time"],
["Los Campesinos!", "I Just Sighed, I Just Signed, Just So You Know"],
["Los Campesinos!", "I Warned You, Do Not Make an Enemy of Me"],
["Los Campesinos!", "In Medias Res"],
[
"Los Campesinos!",
"It's Never That Easy Though, Is It (Song For The Other Kurt)"
],
["Los Campesinos!", "Miserabilia"],
["Los Campesinos!", "Plan A"],
["Los Campesinos!", "Romance is Boring"],
["Los Campesinos!", "Straight in at 101"],
["Los Campesinos!", "The End Of The Asterisk"],
["Los Campesinos!", "The Sea is a Good Place to Think of the Future"],
["Los Campesinos!", "There Are Listed Buildings"],
["Los Campesinos!", "This is a Flag, There is No Wind"],
["Los Campesinos!", "Ways To Make It Through The Wall"],
["Los Campesinos!", "We Are Beautiful, We Are Doomed"],
["Los Campesinos!", "We've Got Your Back"],
["Los Campesinos!", "Who Fell Asleep In"],
["Los Campesinos!", "You'll Need Those Fingers For Crossing"],
["Miracles of Modern Science", "Bossa Supernova"],
["Miracles of Modern Science", "Eating Me Alive"],
["Miracles of Modern Science", "Friend Of The Animals"],
["Miracles of Modern Science", "I Found Space"],
["Miracles of Modern Science", "Luminol"],
["Miracles of Modern Science", "MOMS AWAY!"],
["Miracles of Modern Science", "Quantum Of Solace"],
["Miracles of Modern Science", "Secret Track"],
["Miracles of Modern Science", "Space Chopper"],
["Miracles of Modern Science", "Strangerous"],
["Miracles of Modern Science", "Tensity"],
["Miracles of Modern Science", "The Moon & Australia"],
["Nia Archives", "(Over)Thinking"],
["Nia Archives", "18 & Over"],
["Nia Archives", "Crossroads"],
["Nia Archives", "Don't Kid Urself"],
["Nia Archives", "Gud Gudbyez"],
["Nia Archives", "Headz Gone West"],
["Nia Archives", "Luv Like"],
["Nia Archives", "Part Of Me"],
["Nia Archives", "Sober Feels"],
["This Is Me Smiling", "A Better Way to Fall in Love"],
["This Is Me Smiling", "Alive in the Chase"],
["This Is Me Smiling", "Ephemera"],
["This Is Me Smiling", "Feelin' the Time Pass By"],
["This Is Me Smiling", "For When You Don't Hear It Right"],
["This Is Me Smiling", "Goodbye to Each New Day"],
["This Is Me Smiling", "Matter to Matter"],
["This Is Me Smiling", "Mixin' Up Adjectives"],
["This Is Me Smiling", "Say What You're Gonna Say"],
["This Is Me Smiling", "So Excited to Sleep"],
["This Is Me Smiling", "Up in All Directions"],
["Bug Hunter", "Dear McCracken"],
["Ken Ashcorp", "Burgz"],
["Ken Ashcorp", "Absolute Territory"],
["Ken Ashcorp", "I'm Your Slave"],
["Mew", "A Dark Design"],
["Mew", "An Envoy To The Open Fields"],
["Mew", "Apocalypso"],
["Mew", "Chinaberry Tree"],
["Mew", "Fox Cub"],
["Mew", "Louise Louisa"],
["Mew", "Saviours Of Jazz Ballet"],
["Mew", "Special"],
["Mew", "The Seething Rain Weeps For You"],
["Mew", "The Zookeeper's Boy"],
["Mew", "White Lips Kissed"],
["Mew", "Why Are You Looking Grave"],
["Get Cape. Wear Cape. Fly", "An Oak Tree"],
["Get Cape. Wear Cape. Fly", "Call Me Ishmael"],
["Get Cape. Wear Cape. Fly", "Get Cape. Wear Cape. Fly"],
["Get Cape. Wear Cape. Fly", "Glasshouses"],
["Get Cape. Wear Cape. Fly", "I-Spy"],
[
"Get Cape. Wear Cape. Fly",
"If I Had £1 For Every Stale Song Title I'd Be 30 Short Of Getting Out Of This Mess"
],
["Get Cape. Wear Cape. Fly", "Once More With Feeling"],
[
"Get Cape. Wear Cape. Fly",
"The Chronicles Of A Bohemian Teenager (Part Two)"
],
[
"Get Cape. Wear Cape. Fly",
"The Chronicles Of A Bohemian Teenager (Part One)"
],
["Get Cape. Wear Cape. Fly", "The Lighthousekeeper"],
["Get Cape. Wear Cape. Fly", "War Of The Worlds"],
["Get Cape. Wear Cape. Fly", "Whitewash Is Brainwash"],
["Hi I'm Case", "Smoke Damage (Youtube version)"],
["Ken Ashcorp", "Wear"],
["Hi I'm Case", "Smoke Damage (Spotify version)"],
["Neil Diamond", "The Look Of Love"],
["Amy Winehouse", "Valerie (Short Version)"],
["Anastacia", "I'm Outta Love (Short Version)"],
["Calum Scott", "Dancing On My Own (Short Version)"],
["Ed Sheeran", "Shivers (Short Version)"],
["Eminem", "Without Me (Short Version)"],
["Gnarls Barkley", "Crazy (Short Version)"],
["Jess Glynne", "Hold My Hand (Short Version)"],
["Kenny Loggins", "Footloose (Short Version)"],
["Kings Of Leon", "Sex on Fire (Short Version)"],
["Lady Gaga", "Born This Way (Short Version)"],
["Miley Cyrus", "Jolene (Short Version)"],
["Miley Cyrus", "Wrecking Ball (Short Version)"],
["Robbie Williams", "Angels (Short Version)"],
["Shakira", "Whenever, Wherever (Short Version)"],
["Shania Twain", "Man! I Feel Like A Woman (Short Version)"],
["Shirley Bassey", "Big Spender (Short Version)"],
["The Killers", "Mr. Brightside (Short Version)"],
["The Pussycat Dolls", "Sway (Short Version)"],
["Twenty One Pilots", "Stressed Out (Short Version)"],
["Wheatus", "Teenage Dirtbag (Short Version)"],
["Christina Stürmer", "Nie Genug"],
["James Brown", "It's a Man's World (Short Version)"],
["Jerry Lee Lewis", "Great Balls Of Fire (Short Version)"],
["Melanie Martinez", "Toxic (Short Version)"],
["Melissa Etheridge", "Bring Me Some Water (Short Version)"],
["Queen", "Crazy Little Thing Called Love (Short Version)"],
["Tina Turner", "Proud Mary (Short Version)"],
["Tina Turner", "The Best (Short Version)"],
["Tom Jones", "Help Yourself (Short Version)"],
["Tom Jones", "Sex Bomb (Short Version)"],
["Andreas Gabalier", "Hulapalu (Short Version)"],
["Christina Stürmer", "Nie Genug (Short Version)"],
["Die Draufgänger", "Cordula Grün (Short Version)"],
["Jimi Jamison", "I'm Always Here (Short Version)"],
["Jürgen Drews", "Ein Bett im Kornfeld"],
["Jürgen Drews", "Ein Bett im Kornfeld (Short Version)"],
["STS", "Kalt Und Kälter (Short Version)"],
["STS", "Kalt Und Kälter"],
["Udo Jürgens", "Aber bitte mit Sahne"],
["Udo Jürgens", "Aber bitte mit Sahne (Short Version)"],
["Bryan Adams", "Summer of '69 (Short Version)"],
["Dylan Emmet", "Lose This"],
["Loosey LaDuca", "Let Loose"],
["Against Me", "People Who Died"],
["Eleven Hundred Springs", "Thunderbird Will Do Just Fine"],
["Etherwood", "Begin By Letting Go"],
["Foy Vance", "She Burns"],
["Frightened Rabbit", "Late March Death March"],
["George Barnett", "Stone Cold Classic"],
["Get Cape. Wear Cape. Fly", "Better Things (ft. Kate Nash)"],
["Get Cape. Wear Cape. Fly", "Could've Seen It All"],
["Get Cape. Wear Cape. Fly", "Find The Time"],
["Get Cape. Wear Cape. Fly", "I Could Build You A Tower"],
["Get Cape. Wear Cape. Fly", "Keep Singing Out"],
["Get Cape. Wear Cape. Fly", "Let The Journey Begin"],
["Get Cape. Wear Cape. Fly", "Moving Forward"],
["Get Cape. Wear Cape. Fly", "Postcards From Catalunya"],
[
"Get Cape. Wear Cape. Fly",
"The Children Are (The Consumers Of) The Future"
],
["Get Cape. Wear Cape. Fly", "This Could Be All"],
["Get Cape. Wear Cape. Fly", "Waiting For The Monster To Drown"],
["Get Cape. Wear Cape. Fly", "Window Of Your Mind"],
["Get Cape. Wear Cape. Fly", "Young And Lovestruck"],
["K-Os", "The Rain"],
["Nothing But Thieves", "Pop The Balloon"],
["Robbie Basho", "Blue Crystal Fire"],
["Smino", "Lee and Lovie"],
["The Skints", "Murderer"],
["Xan Griffin", "Capricorn (ft. WOLFE)"],
["Pulp", "Cocaine Socialism"],
["Random Hand", "Play Some Ska"],
["Sexyy Red, Nicki Minaj & Tay Keith", "Pound Town 2"],
["Tori Amos", "Liquid Diamonds"],
["Frightened Rabbit", "Music Now"],
["Frightened Rabbit", "Housing (out)"],
["Frightened Rabbit", "The Modern Leper"],
["Frightened Rabbit", "A Lick Of Paint"],
["Frightened Rabbit", "The Greys"],
["Frightened Rabbit", "Head Rolls Off"],
["Frightened Rabbit", "Backyard Skulls"],
["Frightened Rabbit", "The Wreck"],
["Frightened Rabbit", "My Backwards Walk"],
["Frightened Rabbit", "Be Less Rude"],
["Frightened Rabbit", "Die Like A Rich Boy"],
["Frightened Rabbit", "State Hospital"],
["Frightened Rabbit", "Skip the Youth"],
["Frightened Rabbit", "Yes, I Would"],
["Frightened Rabbit", "Floating in the Forth"],
["Frightened Rabbit", "Nitrous Gas"],
["Frightened Rabbit", "Break"],
["Frightened Rabbit", "Things"],
["Frightened Rabbit", "Nothing Like You"],
["Frightened Rabbit", "Good Arms vs Bad Arms"],
["Frightened Rabbit", "Foot Shooter"],
["Frightened Rabbit", "The Twist"],
["Frightened Rabbit", "The Loneliness and the Scream"],
["Frightened Rabbit", "Swim Until You Can't See Land"],
["Frightened Rabbit", "An Otherwise Disappointing Life"],
["Frightened Rabbit", "Holy"],
["Frightened Rabbit", "Behave!"],
["Frightened Rabbit", "Old Old Fashioned"],
["Frightened Rabbit", "Yawns"],
["Frightened Rabbit", "I Feel Better"],
["Frightened Rabbit", "Woke Up Hurting"],
["Frightened Rabbit", "Dead Now"],
["Frightened Rabbit", "Poke"],
["Frightened Rabbit", "400 Bones"],
["Frightened Rabbit", "Little Drum"],
["Frightened Rabbit", "Fast Blood"],
["Frightened Rabbit", "Square 9"],
["Frightened Rabbit", "I Wish I Was Sober"],
["Frightened Rabbit", "The Oil Slick"],
["Frightened Rabbit", "Still Want To Be Here"],
["Frightened Rabbit", "Blood Under The Bridge"],
["Frightened Rabbit", "Death Dream"],
["Frightened Rabbit", "Wait 'Til The Morning"],
["Frightened Rabbit", "Not Miserable"],
["Frightened Rabbit", "Snake"],
["Frightened Rabbit", "Acts of Man"],
["Frightened Rabbit", "Living in Colour"],
["Frightened Rabbit", "Housing (in)"],
["Frightened Rabbit", "The Wrestle"],
["Frightened Rabbit", "Go Go Girls"],
["Frightened Rabbit", "December's Traditions"],
["Frightened Rabbit", "Lump Street"],
["Frightened Rabbit", "Keep Yourself Warm"],
["Frightened Rabbit", "The Woodpile"],
["Frightened Rabbit", "Get Out"],
["Judas Priest", "Living Bad Dreams"],
["The Spits", "Bring Me Down"],
["Voltaire", "Feathery Wings"],
["City and Colour", "The Death of Me"],
["Was (Not Was)", "Out Come the Freaks"],
["Bon Jovi", "Hallelujah"],
["Marilyn Dagenais", "Je serai là"],
["Marilyn Dagenais", "J't'écrirai pas"],
["A Lost People", "Big Booty Bitches"],
["Annika Norlin", "Failure"],
["Ascension", "Monsters"],
["Bonnie Prince Billy and Tortoise", "Pancho"],
["Brandi Carlile", "Raise Hell"],
["Britt Daniel", "Let the Distance Bring Us Together"],
["Cyn", "Drinks"],
["Dan Wriggins", "All Used Up"],
["Davey Dynamite & Absent", "Solidarity Forever"],
["Elliott Smith", "Strung Out Again"],
["Emperor X", "Sad React"],
["Girls", "Hellhole Ratrace"],
["Hercules & Love Affair", "Iris"],
["Iris DeMent", "Easy's Gettin' Harder Every Day"],
["Iris DeMent", "Let the Mystery Be"],
["Iris DeMent", "Wasteland of the Free"],
["Joanna Newsom", "Inflammatory Writ"],
["Jukebox The Ghost", "Jumpstarted"],
["Kevin Devine", "Splittin’ Up Christmas"],
["Kirin J Callinan", "Life Is Life"],
["MJ Lenderman", "TLC Cagematch"],
["Molly Hatchet", "Sailor"],
["Necro", "Pussy Is My Weakness"],
["Nevermore", "The Heart Collector"],
["New Found Glory", "Sincerely Me"],
["New Radicals", "I Hope I Didn't Just Give Away The Ending"],
["No Doubt", "Six Feet Under"],
["Petey", "Dont Tell The Boys"],
["Randy Newman", "A Wedding in Cherokee County"],
["Reverend Horton Heat", "Wiggle Stick"],
["Rough Cutt", "Dreamin' Again"],
["Steve Earle", "Christmas in Washington"],
["The Buttertones", "Baby Doll"],
["The Buttertones", "Eros"],
["Whiskey Myers", "Broken Window Serenade"],
["Yoko Kanno", "Whats it For"],
["Mac McCaughan & Annie Hayden", "Down We Go"],
["The Buttertones", "You and Your Knife"],
["The Doubleclicks", "Really Big Chickens"],
["Tony All", "At The Party"],
["Tony All", "Guitar Case"],
["Velvet Pony", "LESBIAN PONIES WITH WEAPONS"],
["Waxahatchee", "Noccalula"],
["David Bowie", "I Know It’s Gonna Happen Someday"],
["Mary Heather Hickman", "Treasure"],
["Ray Price", "The Wind Beneath My Wings"],
["The Avett Brothers", "Ain't No Man"],
["Dropout Kings", "Scratch & Claw"],
["Gogol Bordello", "Not a Crime"],
["Sparks", "Girl from Germany"],
["Sparks", "Under the Table with Her"],
["Streetlight Manifesto", "One Foot on the Gas, One Foot in the Grave"],
["The Doors", "Not to touch the earth"],
["Weird Al Yankovic", "Money for Nothing Beverly Hillbillies"],
["Adam Sandler", "Mr. Bake-O"],
["Eydie Gormé", "The Gentleman is a Dope"],
["Eydie Gormé", "What Did I Have That I Don't Have"],
["Rickie Lee Jones", "The Ballad Of The Sad Young Men"],
["Eddie Cochran", "Three Stars"],
["Lil Durk", "Broadway Girls"],
["Luude", "Down Under"],
[
"Taylor Swift",
"We Are Never Ever Getting Back Together (Taylor's Version)"
],
["The Fray", "Never Say Never"],
["The Ghost Club", "See Below"],
["General Levy", "Incredible (50% Volume Vocals)"],
["General Levy", "Incredible"],
["Marilyn Dagenais", "Chanson pour Papa"],
["Royal Navy", "Heart of Oak"],
["Tiamat", "Cain"],
["Marilyn Dagenais", "You Make Me Sing"],
["Young and Restless", "B Girls"],
["Bug Hunter", "Pinecones"],
["Streetlight Manifesto", "With Any Sort of Certainty"],
["Marvin Gaye", "God is Love"],
["Ben&Ben", "Maybe the Night"],
["Blink 182", "Fell In Love"],
["Blink 182", "Turpentine"],
["Bryson Tiller", "Right My Wrongs"],
["Chris Stapleton", "Joy of My Life"],
["Marilyn Dagenais", "L'hiver"],
["Metric", "Who Would You Be For Me"],
["Rex Orange County", "Happiness"],
["Sheff G", "Weight on Me"],
["Taylor Swift", "I Knew You Were Trouble (Taylor's Version)"],
["Taylor Swift", "You Belong With Me (Taylor's Version)"],
["The 1975", "Robbers"],
["Unknown", "Before the Screen Reads Fin"],
["ACDC", "Gone Shootin'"],
["Ozzy Osbourne", "You're No Different"],
["Alice Cooper", "He's Back (The Man Behind The Mask)"],
["Echo and The Bunnymen", "New Direction"],
["Iggy Pop", "Tell Me a Story"],
["Left Boy", "Security Check"],
["The Lemonheads", "If I Could Talk I’d Tell You"],
["They Might Be Giants", "Dinner Bell"],
["XTC", "Scissor Man"],
["XTC", "The Smartest Monkeys"],
["Marilyn Dagenais", "Un peu de lumière"],
["Bad Lip Reading", "Black Umbrella"],
["Bruno Mars", "The Lazy Song (Non-Lazy Parody)"],
["Marilyn Dagenais", "Si je t'aime"],
["Jerry Lee Lewis", "Meat Man"],
["Shovels & Rope", "Birmingham"],
["Wolfe Tones", "Rock On Rockall"],
["James Rado", "Where Do I Go? (From Hair)"],
["Andrea Bocelli", "Gloria in Excelsis Deo"],
["ABBA", "The Day Before You Came"],
["Fleet Foxes", "He Doesn’t Know Why"],
["The Drifters", "Up On The Roof"],
["The Seekers", "California Dreamin'"],
["Fleet Foxes", "Silver Dagger"],
["She Wants Revenge", "Broken Promises For Broken Hearts"],
["Ken Ashcorp", "On The Rocks"],
["Z-Ro", "Mo City Don Freestyle"],
["The Time", "Cool"],
["Urban Cookie Collective", "The Key, The Secret"],
["Melissa Etheridge", "Meet Me In The Back"],
["Garfunkel And Oates", "I Get to Do It With You"],
["A Fine Frenzy", "Come On, Come Out"],
["A Fine Frenzy", "Rangers"],
["Ken Ashcorp", "PVP"],
["A Fine Frenzy", "Almost Lover"],
["A Fine Frenzy", "You Picked Me"],
["Peach PRC", "God Is A Freak"],
["Righteous Brothers", "See That Girl"],
["Blue Eyed Blondes", "Maneater"],
["piri & tommy", "on & on"],
["Sudley ft. piri", "fumble"],
["A Fine Frenzy", "Ashes And Wine"],
["A Fine Frenzy", "The Minnow & The Trout"],
["Tame Impala", "The Boat I Row"],
["Spinal Tap", "Rainy Day Sun"],
["Röyksopp", "Running To The Sea"],
["Röyksopp", "Oh, Lover"],
["Röyksopp", "Monument"],
["Röyksopp", "Only This Moment"],
["Röyksopp", "The Girl And The Robot"],
["Röyksopp", "49 Percent"],
["Maisi & piri", "head"],
["Django Django", "Default"],
["Django Django", "Hail Bop"],
["piri & tommy", "silver lining"],
["Daniel O'Donnell", "Galway Bay"],
["Daniel O'Donnell", "I'll Take You Home Again Kathleen"],
["Daniel O'Donnell", "Mountains of Mourne"],
[
"Daniel O'Donnell",
"Medley: It's a Long Way to Tipperary / Pack up Your Troubles / If You're Irish, Come into the Parlour"
],
["Jackson Singleton", "Disguise"],
["Ken Ashcorp", "Dare You To Love Me"],
["A Fine Frenzy", "Borrowed Time"],
["A Fine Frenzy", "Last Of Days"],
["A Fine Frenzy", "Hope For The Hopeless"],
["A Fine Frenzy", "Liar, Liar"],
["A Fine Frenzy", "Lifesize"],
["A Fine Frenzy", "Near To You"],
["A Fine Frenzy", "Think Of You"],
["A Fine Frenzy", "Whisper"],
["piri & tommy", "settle"],
["piri & tommy", "soft spot"],
["piri & tommy", "sunlight"],
["piri & tommy", "beachin"],
["piri & tommy", "player 2"],
["piri & tommy", "can we"],
["piri & tommy", "easy"],
["piri & tommy", "say it"],
["piri & tommy", "slowly but surely"],
["piri & tommy", "words"],
["piri & tommy", "nice 2 me"],
["Tony Bennett & k.d.lang", "What A Wonderful World"],
["Ying Yang Twins", "Georgia Dome"],
[
"Daniel O'Donnell",
"Medley: Galway Bay, The Mountains Of Mourne, I'll Take You Home Again Kathleen"
],
["The Beatles", "In My Life"],
["Truck Stop", "Komm her du bist mein Cowboy"],
["Linda Feller", "Du gabst ihr deinen Namen"],
["Victoria OB", "Yeshua"],
["Matthew Morrison", "Somewhere Over the Rainbow"],
["fun.", "Benson Hedges"],
["fun.", "All the Pretty Girls"],
["fun.", "At Least I'm Not as Sad (As I Used to Be)"],
["fun.", "I Wanna Be the One"],
["fun.", "Walking the Dog"],
["fun.", "Light a Roman Candle with Me"],
["fun.", "Barlights"],
["fun.", "Take Your Time (Coming Home)"],
["Tom Astor", "Sturm Und Drang"],
["Titellied der gleichnamigen Fernsehserie 1962", "Bonanza"],
["Linda Feller", "Billy Bob's Texas"],
["ABBA", "Dancing Queen"],
["Ken Ashcorp", "Touch Fluffy Tail"],
["Mavi Phoenix", "Pretty Life (Whsprs Cover)"],
["Jimi Hendrix", "Remember"],
["Smash Mouth", "All Star"],
["Smash Mouth", "All Star (with Shrek)"],
["The Silent Comedy", "Enemies Multiply"],
["ABBA", "Ring Ring"],
["ABBA", "Another Town, Another Train"],
["ABBA", "Disillusion"],
["ABBA", "People Need Love"],
["Frank Sinatra", "New York, New York"],
["ABBA", "I Saw It In The Mirror"],
["ABBA", "Nina, Pretty Ballerina"],
["ABBA", "Love Isn’t Easy (But It Sure Is Hard Enough)"],
["ABBA", "Me And Bobby And Bobby’s Brother"],
["ABBA", "He Is Your Brother"],
["ABBA", "She’s My Kind Of Girl"],
["ABBA", "I Am Just A Girl"],
["ABBA", "Rock ’N Roll Band"],
["ABBA", "Ring Ring (Bara Du Slog En Signal) (Swedish Version)"],
["ABBA", "Åh, Vilka Tider"],
["ABBA", "Merry‐Go‐Round"],
["ABBA", "Santa Rosa"],
["ABBA", "Ring Ring (Spanish Version)"],
["ABBA", "Wer Im Wartesaal Der Liebe Steht"],
["ABBA", "Ring Ring (German Version)"],
["Fleet Foxes", "Montezuma"],
["Harald Juhnke", "Berlin, Berlin"],
["Shoshana Bean", "Strange Thunder"],
["Michael Callen", "Crazy World"],
["Michael Callen", "Wish I Had A Dime"],
["The Blasters", "One Bad Stud"],
["Michael Callen", "The Healing Power Of Love"],
["Meat Loaf", "Braver Than We Are"],
["Harald Juhnke", "Berlin, Berlin (Lisa, Milan)"],
["Friday", "The Ballad Of Skinny Linguine"],
["Emery", "The Ponytail Parades"],
["Black Sabbath", "Buried Alive"],
["Aloha from space", "Storm Troopin'"],
["NerdOut", "Bounty"],
["Charles Strouse and Lee Adams", "Han's Your Man"],
["Juliane Werding", "Man muß Das Leben Eben Nehmen, Wie Das Leben Eben Ist"],
["Aurelio Voltaire", "Butterfly"],
["Blind Guardian", "Violent Shadows"],
["Jonny Hill & Linda Feller", "Zusammenstehn (Duet)"],
["Tori Amos", "Big Wheel"],
["Chairlift", "Bruises"],
["Jonny Hill & Linda Feller", "London"],
["Life Languages", "The Mover Song"],
["Life Languages", "The Responder Song"],
["Life Languages", "The Contemplator Song"],
["Life Languages", "The Doer Song"],
["Life Languages", "The Shaper Song"],
["Life Languages", "The Influencer Song"],
["Life Languages", "The Producer Song"],
["The Amazing Devil", "That Unwanted Animal"],
["Bobby Capo", "Locamente Enamorado"],
["Dagmar", "Lass mich damit bloß in Ruhe"],
["Los Campesinos!", "You! Me! Dancing! (Daytrotter Session)"],
["Joe P", "Leaves"],
["ABBA", "Waterloo"],
["ABBA", "Sitting In The Palmtree"],
["ABBA", "King Kong Song"],
["ABBA", "Hasta Mañana"],
["ABBA", "My Mama Said"],
["ABBA", "Dance (While The Music Still Goes On)"],
["ABBA", "Honey, Honey"],
["Thomas Borchert", "I Know Those Eyes / This Man Is Dead (Duet)"],
[
"Thomas Borchert",
"I Know Those Eyes / This Man Is Dead (Duet With Female Vocals)"
],
["SHE WANTS REVENGE", "Rachael"],
["Matt Redmond", "Unbroken Praise"],
["Ian McConnell", "Level 429"],
["ABBA", "Watch Out"],
["ABBA", "What About Livingstone"],
["Ten Years After", "Outside My Window"],
["ABBA", "Gonna Sing You My Lovesong"],
["ABBA", "Suzy-Hang-Around"],
["ABBA", "Waterloo (Swedish Version)"],
["ABBA", "Honey, Honey (Swedish Version)"],
["ABBA", "Waterloo (German Version)"],
["ABBA", "Hasta Mañana (Spanish Version)"],
["ABBA", "Waterloo (French Version)"],
["ABBA", "Mamma Mia"],
["ABBA", "Hey, Hey Helen"],
["ABBA", "Tropical Loveland"],
["ABBA", "S.O.S."],
["ABBA", "Man In The Middle"],
["ABBA", "Bang-A-Boomerang"],
["ABBA", "I Do, I Do, I Do, I Do, I Do"],
["ABBA", "Rock Me"],
["ABBA", "I’ve Been Waiting For You"],
["ABBA", "So Long"],
["ABBA", "Crazy World"],
["ABBA", "Medley (1978 Mix)"],
["ABBA", "Mamma Mia (Spanish Version)"],
["Marina and The Diamonds", "Froot"],
["Maxton Waller", "On My Way (Marching Band)"],
["100 gecs", "mememe"],
["Stuck Out Here", "Embarrass You"],
["DCSane", "Heart's Whiskey"],
["Release", "Devil's Handshake"],
["Kelly Clarkson", "Since U Been Gone (Pitch -3: E major)"],
["Justin Townes Earle", "Rogers Park"],
["Armin van Buuren ft. Teddy Swims", "Easy To Love"],
["Willie Nelson", "One More Song to Write"],
["Will Varley", "Seize The Night"],
["Passenger", "However It Comes, Wherever It Goes"],
["Ricky Braddy", "Anyone (Acoustic Cover of Demi Lovato)"],
["Bryan Adams", "Help Me Make It Through The Night"],
["Ivan Rivers", "Mid-Riff"],
["Kane Brown", "American Bad Dream"],
["Mother Mother", "Ghosting"],
["Charlie Terrell", "Libby Anna"],
["Taylor Swift", "Fortnight (feat. Post Malone)"],
["The Gaslight Anthem", "National Anthem"],
["The Lonely Island", "Semicolon (feat. Solange)"],
["Lucky Daye", "Algorithm"],
["The Black Eyed Peas", "They Don't Want Music"],
["Tiger Really", "Fundamentally Unlovable"],
["Da Ali G Show", "Jarvis Cocker"],
["Colin Hay", "Send Somebody (Stripped Mix)"],
["Ernie Taylor", "I Ain't Leavin' Yet"],
["Smashing Pumpkins", "Here Is No Why"],
["Drake", "Virginia Beach"],
["Maverick City Music", "I Thank God"],
["Ax and the Hatchetmen", "Drive-in Movie"],
["Faith No More", "Das Schutzenfest"],
["Miguel", "Use Me"],
["Ivan Rivers", "Sad Around Me"],
["Young The Giant", "Both Sides Now"],
["Jimmy Buffett", "Bob Robert's Society Band"],
["buildspace, MAYV", "the end"],
["Frank Turner", "A Wave Across A Bay"],
["Angel Olsen", "Eyes Without A Face"],
["Deven May", "The Sensitive Song (from Cops)"],
["The Mountain Goats", "Night Light"],
["Steppenwolf", "Born To Be Wild"],
["Bobby Solo", "O sole mio"],
["HCA West", "Driving Quality"],
["Engelbert Humperdinck", "Marry Me"],
["Mark Knopfler", "Are We in Trouble Now"],
["Danny Pynes", "One Night in Spain"],
["The Butterfly Effect", "I’m Not Okay"],
["The Sonic Bridges", "Sweet Evelyn"],
["Carrie and Jake", "Wedding Medley"],
["Gregory Porter", "Insanity (feat. Lalah Hathaway)"],
["Linda Feller", "Ich weiss genau, was ich will"],
["Mikey Chuck Rivers", "She's Cryin' (I'm Drunk Again)"],
["Gregory Porter", "Insanity (feat. Lalah Hathaway) (Duet)"],
["Country Rose", "Spaß Am Leben"],
["Tom Astor", "Du bist da (wenn's drum geht)"],
["Linda Feller", "Wenn überhaupt, dann nur Country"],
["Alabama", "The Fans"],
["Ghost Brothers", "What Kind Of Man Am I"],
["The Stand", "Baby, Can You Dig Your Man"],
["Nu Shooz", "I Can't Wait"],
["Freddie Jackson", "All I'll Ever Ask (feat. Najee)"],
["Linda Feller", "Du bist das Salz in meiner Suppe"],
["Claudia Jung, Tom Astor", "Wer Liebe Sucht"],
["The Smashing Pumpkins", "Tales of a Scorched Earth"],
["The Smashing Pumpkins", "Thru the Eyes of Ruby"],
["Tom Astor", "Geistertruck"]
]
Binary file not shown.
+98
View File
@@ -0,0 +1,98 @@
"""
Tests for the core components.
"""
import unittest
from unittest.mock import MagicMock, patch
from karaoke_gen.core import ProjectConfig, Track, KaraokeGenError
class TestProjectConfig(unittest.TestCase):
"""Test ProjectConfig class."""
def test_init_with_minimal_args(self):
"""Test initialization with minimal arguments."""
config = ProjectConfig()
# Check default values
self.assertIsNone(config.artist)
self.assertIsNone(config.title)
self.assertIsNone(config.input_media)
self.assertFalse(config.dry_run)
self.assertEqual(config.output_dir, ".")
def test_init_with_all_args(self):
"""Test initialization with all arguments."""
logger = MagicMock()
config = ProjectConfig(
artist="Test Artist",
title="Test Title",
input_media="test.mp3",
dry_run=True,
logger=logger,
output_dir="/tmp",
create_track_subfolders=True,
)
# Check values
self.assertEqual(config.artist, "Test Artist")
self.assertEqual(config.title, "Test Title")
self.assertEqual(config.input_media, "test.mp3")
self.assertTrue(config.dry_run)
self.assertEqual(config.logger, logger)
self.assertEqual(config.output_dir, "/tmp")
self.assertTrue(config.create_track_subfolders)
class TestTrack(unittest.TestCase):
"""Test Track class."""
def test_init_with_minimal_args(self):
"""Test initialization with minimal arguments."""
track = Track(artist="Test Artist", title="Test Title")
# Check values
self.assertEqual(track.artist, "Test Artist")
self.assertEqual(track.title, "Test Title")
self.assertIsNone(track.input_media)
def test_init_with_all_args(self):
"""Test initialization with all arguments."""
track = Track(
artist="Test Artist",
title="Test Title",
input_media="test.mp3",
input_audio_wav="test.wav",
input_still_image="test.jpg",
lyrics="Test lyrics",
)
# Check values
self.assertEqual(track.artist, "Test Artist")
self.assertEqual(track.title, "Test Title")
self.assertEqual(track.input_media, "test.mp3")
self.assertEqual(track.input_audio_wav, "test.wav")
self.assertEqual(track.input_still_image, "test.jpg")
self.assertEqual(track.lyrics, "Test lyrics")
class TestKaraokeGenError(unittest.TestCase):
"""Test KaraokeGenError class."""
def test_error_message(self):
"""Test error message."""
error = KaraokeGenError("Test error")
self.assertEqual(str(error), "Test error")
def test_error_with_cause(self):
"""Test error with cause."""
cause = ValueError("Original error")
error = KaraokeGenError("Test error", cause=cause)
self.assertEqual(str(error), "Test error")
self.assertEqual(error.__cause__, cause)
if __name__ == "__main__":
unittest.main()
+103
View File
@@ -0,0 +1,103 @@
#! /usr/bin/env python3
import os
import json
import logging
from karaoke_gen.karaoke_gen import KaraokePrep
# Set up logging
logger = logging.getLogger(__name__)
log_handler = logging.StreamHandler()
log_formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
log_handler.setFormatter(log_formatter)
logger.addHandler(log_handler)
logger.setLevel(logging.DEBUG)
# Define the artist/title combinations
def total_length(tuple):
artist, title = tuple
return len(artist) + len(title)
with open("data/artist-titles.json", "r", encoding="utf-8") as f:
all_combinations = json.load(f)
# Sort by length and get shortest and longest 20
sorted_combinations = sorted(all_combinations, key=total_length)
artist_title_combinations = sorted_combinations[:20] + sorted_combinations[-20:]
# Define the format dictionary with expanded configurations
formats = [
{
"name": "nomadkaraoke",
"style_params_json": "/Users/andrew/AB Dropbox/Andrew Beveridge/MediaUnsynced/Karaoke/NomadBranding/karaoke-prep-styles-nomad.json",
},
{
"name": "vocalstar",
"style_params_json": "/Users/andrew/AB Dropbox/Andrew Beveridge/MediaUnsynced/Karaoke/Tracks-NonPublished/VocalStar/Resources/karaoke-prep-styles-vocalstar.json",
},
{
"name": "minimal",
"style_params_json": None,
},
]
# Define other parameters
base_output_dir = "outputs"
os.makedirs(base_output_dir, exist_ok=True)
# Process each format
for format in formats:
# Create format-specific output directory
format_output_dir = os.path.join(base_output_dir, format["name"])
os.makedirs(format_output_dir, exist_ok=True)
style_params = None
if format["style_params_json"]:
with open(format["style_params_json"], "r") as f:
style_params = json.loads(f.read())
# Instantiate KaraokePrep for this format
kprep = KaraokePrep(
log_level=logging.INFO,
log_formatter=log_formatter,
output_dir=format_output_dir,
style_params=style_params,
render_bounding_boxes=False,
output_jpg=False,
output_png=True,
)
# Run the create_title_video and create_end_video functions for each combination
for artist, title in artist_title_combinations:
sanitized_artist = kprep.sanitize_filename(artist)
sanitized_title = kprep.sanitize_filename(title)
# Generate title video
title_image_filepath_noext = os.path.join(format_output_dir, f"{sanitized_artist}_{sanitized_title}_title")
title_video_filepath = os.path.join(format_output_dir, f"{sanitized_artist}_{sanitized_title}_title.mov")
kprep.intro_video_duration = 0
kprep.create_title_video(
artist=artist,
title=title,
format=kprep.title_format,
output_image_filepath_noext=title_image_filepath_noext,
output_video_filepath=title_video_filepath,
)
logger.info(f"Created title video for {artist} - {title} using {format['name']} format")
# Generate end video
end_image_filepath_noext = os.path.join(format_output_dir, f"{sanitized_artist}_{sanitized_title}_end")
end_video_filepath = os.path.join(format_output_dir, f"{sanitized_artist}_{sanitized_title}_end.mov")
kprep.end_video_duration = 0
kprep.create_end_video(
artist=artist,
title=title,
format=kprep.end_format,
output_image_filepath_noext=end_image_filepath_noext,
output_video_filepath=end_video_filepath,
)
logger.info(f"Created end video for {artist} - {title} using {format['name']} format")
+174
View File
@@ -0,0 +1,174 @@
"""
Tests for the utility functions.
"""
import os
import tempfile
import unittest
from pathlib import Path
from karaoke_gen.utils import (
# File utilities
sanitize_filename,
ensure_directory_exists,
file_exists,
# Path utilities
normalize_path,
join_paths,
get_absolute_path,
get_relative_path,
get_filename,
get_filename_without_extension,
get_file_extension,
# String utilities
slugify,
truncate_string,
extract_artist_and_title,
format_duration,
format_filesize,
)
class TestFileUtils(unittest.TestCase):
"""Test file utility functions."""
def test_sanitize_filename(self):
"""Test sanitize_filename function."""
# Test with invalid characters
self.assertEqual(sanitize_filename("file/with\\invalid:chars"), "file_with_invalid_chars")
# Test with leading/trailing spaces and dots
self.assertEqual(sanitize_filename(" file.with.spaces. "), "file.with.spaces")
# Test with empty string
self.assertEqual(sanitize_filename(""), "unnamed")
def test_ensure_directory_exists(self):
"""Test ensure_directory_exists function."""
with tempfile.TemporaryDirectory() as temp_dir:
test_dir = os.path.join(temp_dir, "test_dir")
# Directory should not exist initially
self.assertFalse(os.path.exists(test_dir))
# Create directory
ensure_directory_exists(test_dir)
# Directory should exist now
self.assertTrue(os.path.exists(test_dir))
# Should not raise exception when called on existing directory
ensure_directory_exists(test_dir)
def test_file_exists(self):
"""Test file_exists function."""
with tempfile.TemporaryDirectory() as temp_dir:
# Create a test file
test_file = os.path.join(temp_dir, "test_file.txt")
with open(test_file, "w") as f:
f.write("test")
# Test with existing file
self.assertTrue(file_exists(test_file))
# Test with non-existing file
self.assertFalse(file_exists(os.path.join(temp_dir, "non_existing_file.txt")))
class TestPathUtils(unittest.TestCase):
"""Test path utility functions."""
def test_normalize_path(self):
"""Test normalize_path function."""
# Test with mixed separators
self.assertEqual(normalize_path("path/to\\file"), os.path.normpath("path/to/file"))
def test_join_paths(self):
"""Test join_paths function."""
# Test joining paths
self.assertEqual(join_paths("path", "to", "file"), os.path.join("path", "to", "file"))
def test_get_absolute_path(self):
"""Test get_absolute_path function."""
# Test with relative path
self.assertEqual(get_absolute_path("."), os.path.abspath("."))
def test_get_relative_path(self):
"""Test get_relative_path function."""
# Test with absolute path
abs_path = os.path.abspath(".")
self.assertEqual(get_relative_path(abs_path, os.path.dirname(abs_path)), os.path.basename(abs_path))
def test_get_filename(self):
"""Test get_filename function."""
# Test with path
self.assertEqual(get_filename("/path/to/file.txt"), "file.txt")
def test_get_filename_without_extension(self):
"""Test get_filename_without_extension function."""
# Test with path and extension
self.assertEqual(get_filename_without_extension("/path/to/file.txt"), "file")
def test_get_file_extension(self):
"""Test get_file_extension function."""
# Test with path and extension
self.assertEqual(get_file_extension("/path/to/file.txt"), ".txt")
class TestStringUtils(unittest.TestCase):
"""Test string utility functions."""
def test_slugify(self):
"""Test slugify function."""
# Test with spaces and special characters
self.assertEqual(slugify("Hello World!"), "hello-world")
# Test with unicode characters
self.assertEqual(slugify("Héllö Wörld"), "hello-world")
def test_truncate_string(self):
"""Test truncate_string function."""
# Test with string shorter than max length
self.assertEqual(truncate_string("Hello", 10), "Hello")
# Test with string longer than max length
self.assertEqual(truncate_string("Hello World", 8), "Hello...")
def test_extract_artist_and_title(self):
"""Test extract_artist_and_title function."""
# Test with standard format
self.assertEqual(
extract_artist_and_title("Artist - Title.mp3"),
{"artist": "Artist", "title": "Title"}
)
# Test with no separator
self.assertEqual(
extract_artist_and_title("Title.mp3"),
{"artist": "", "title": "Title"}
)
def test_format_duration(self):
"""Test format_duration function."""
# Test with seconds
self.assertEqual(format_duration(65), "01:05")
# Test with minutes
self.assertEqual(format_duration(125), "02:05")
def test_format_filesize(self):
"""Test format_filesize function."""
# Test with bytes
self.assertEqual(format_filesize(500), "500 B")
# Test with kilobytes
self.assertEqual(format_filesize(1500), "1.5 KB")
# Test with megabytes
self.assertEqual(format_filesize(1500000), "1.4 MB")
if __name__ == "__main__":
unittest.main()