Compare commits

...
232 Commits
Author SHA1 Message Date
Andrew Beveridge e9f18118ca Added support for automatic audio padding based on output from LyricsTranscriber 2025-10-24 15:48:19 -04:00
Andrew Beveridge 9ae13ed8b9 Update to latest lyrics-transcriber 2025-10-14 21:29:19 -04:00
Andrew Beveridge b9cc45ab83 Updated dependencies 2025-09-30 10:16:04 -04:00
Andrew Beveridge 349ac90ba6 Updated dependencies, added spec-kit scaffolds 2025-09-28 15:54:10 -04:00
Andrew Beveridge edc720d1e6 Fixed logic bug causing duplicate separation 2025-09-25 17:58:11 -04:00
Andrew Beveridge 7c81822fc0 Added CLI parameter to override specific style JSON values 2025-08-30 22:17:29 -04:00
Andrew Beveridge 6d9e015833 Fixed bug with youtube match always yes in headless on modal 2025-08-08 17:30:30 -04:00
Andrew Beveridge 49c9a82034 Fixed duplicate audio separation, finished implementing remote audio separation on modal when env var is set 2025-07-26 01:30:07 -04:00
Andrew Beveridge 8407990b53 Fixed apostrophe copy bug 2025-07-25 18:27:10 -04:00
Andrew Beveridge d349778ec3 Added functionality to create custom instrumental from web UI 2025-07-25 18:23:20 -04:00
Andrew Beveridge fd428febc7 Changed rclone sync to skip existing files to prevent overwriting fixes in cloud destinations 2025-07-19 12:15:57 -04:00
Andrew Beveridge dab88f0868 Skipped nvenc tests due to temporary disablement 2025-07-19 11:40:28 -04:00
Andrew Beveridge 5cbffc5f25 Update to latest lyrics-transcriber version, disable nvidia encoding for now as the resulting videos were huge 2025-07-19 11:26:38 -04:00
Andrew Beveridge 2b4ea1dfa3 Fixed filename sanitization bug 2025-07-13 17:01:06 -04:00
Andrew Beveridge 8af4a2911f Fixed bug with special chars in filenames 2025-07-13 16:13:10 -04:00
Andrew Beveridge 343241a82f Fixed instrumental selection bug 2025-07-13 15:33:35 -04:00
Andrew Beveridge c05857f304 Remove auto scroll functionality as it was annoying 2025-07-12 17:04:44 -04:00
Andrew Beveridge c0816f6b31 Added stricter job timeouts for Modal functions, added job delivery message template, updated to newer lyrics transcriber to fix hung jobs 2025-07-12 14:17:44 -04:00
Andrew Beveridge 93090504d9 Fixed bug with job id clear between instrumental selection and youtube auth modal 2025-07-10 17:13:10 -04:00
Andrew Beveridge e885edb2ca Implemented waveform/spectrogram visualizations as part of instrumental selection 2025-07-10 17:04:52 -04:00
Andrew Beveridge 42b8ce0977 Finished refining dark theme, nomad branded UI 2025-07-08 18:00:23 -04:00
Andrew Beveridge 5ac6eaba80 Tidied up frontend styles more 2025-07-08 16:56:01 -04:00
Andrew Beveridge b549c35515 Tidied up frontend styles, made instrumental selection cleaner 2025-07-08 16:25:14 -04:00
Andrew Beveridge 9c9d0b5b27 Fix job action button styles on mobile 2025-07-08 11:55:53 -04:00
Andrew Beveridge 3776f4d803 FIxed tests, fixed modal web implementation (at least for a first end to end successful job with upload to youtube, dropbox and google drive etc.) 2025-07-08 02:22:05 -04:00
Andrew Beveridge 7c8c57cd26 Fixed tests, fixed some other issues in finalizaion 2025-07-08 00:50:55 -04:00
Andrew Beveridge abc36e28cf Made finalization work in modal deployment 2025-07-08 00:00:01 -04:00
Andrew Beveridge 2308b553c8 Upgraded to latest lyrics-transcriber to fix CUDA hardware acceleration, fixed job cloning 2025-07-07 20:17:32 -04:00
Andrew Beveridge c9d2e90dbb Implement comprehensive YouTube OAuth authentication system
- Add complete OAuth 2.0 flow for YouTube authentication
- Support user-specific credential storage with Modal Dict
- Add secure state parameter handling for CSRF protection
- Implement token refresh logic for expired credentials
- Add YouTube auth UI to instrumental selection modal
- Support non-interactive mode with pre-stored credentials
- Enhanced NVENC detection and hardware acceleration
- Improved error handling and logging throughout
- Maintain backward compatibility with CLI usage

Features:
- /api/youtube/auth-url - Generate OAuth authorization URL
- /api/youtube/oauth-callback - Handle OAuth callback and store credentials
- /api/youtube/auth-status - Check user authentication status
- /api/youtube/auth (DELETE) - Revoke user authentication
- Frontend popup-based OAuth flow with automatic callback handling
- User credentials automatically passed to finalization process
- Graceful fallback when YouTube authentication unavailable
2025-07-07 18:50:39 -04:00
Andrew Beveridge 67fa0b6c71 Switched to nvidia cuda base image to try and get nvenc encoding working, added volume for preview videos to prevent clash with reloading shared output volume 2025-07-07 16:46:17 -04:00
Andrew Beveridge a08fa5cc5b Added more finalization logic, improved logging, added tests for nvenc to try and speed up video rendering 2025-07-07 00:58:05 -04:00
Andrew Beveridge 3b523ec98c Fixed rapidapi env var passthrough from karaoke-gen, switched to audio-separator GPU accel package, began adding frontend playwright tests 2025-07-05 18:05:02 -04:00
Andrew Beveridge 0c4925f219 Updated to latest lyrics-transcriber (with fixed lyrics sources) and fixed file upload in frontend 2025-07-05 16:58:02 -04:00
Andrew Beveridge 68d2f36bd5 Fixed GHA perms to create tag 2025-07-05 11:41:47 -04:00
Andrew Beveridge 6de0d6d883 Removed dedicated timeline button 2025-07-05 11:40:47 -04:00
Andrew Beveridge e3b71cfc1c Fixed tests, bumped version for release 0.56 2025-07-05 11:26:49 -04:00
Andrew Beveridge 6f0760235b Finally got youtube upload working fully end to end 2025-07-05 00:36:23 -04:00
Andrew Beveridge c9ed433bf4 Improve management of cookies for youtube download, artist/title etc. 2025-07-04 22:34:32 -04:00
Andrew Beveridge 625feba75a Simplify download link filename 2025-07-04 20:47:11 -04:00
Andrew Beveridge f0c02b15c4 Finally got finalization working on modal with latest ffmpeg version 2025-07-04 20:32:20 -04:00
Andrew Beveridge 0f2c6da2b9 Upgrade to latest lyrics-transcriber to fix ASS font path issue, change auto scroll on logs tail to off by default 2025-07-04 18:03:00 -04:00
Andrew Beveridge 9497c5b260 Fixed frontend youtube toggle style 2025-07-04 16:43:19 -04:00
Andrew Beveridge 2cf216d4c2 Updated to support youtube too 2025-07-04 12:10:21 -04:00
Andrew Beveridge fc4caf6382 Improved timeline modal styles 2025-07-03 22:52:31 -04:00
Andrew Beveridge af61c12e13 Updated frontend to work with backend auth 2025-07-03 21:44:50 -04:00
Andrew Beveridge f51e619798 Hopefully fix timestamp tiemzone conversion in frontend and font rendering on backend 2025-07-03 13:21:35 -04:00
Andrew Beveridge 761b9d5104 Fixed progress bar style at all breakpoints 2025-07-03 13:09:37 -04:00
Andrew Beveridge 139a868dbe Fixed preview video render and progress bar styles 2025-07-03 13:08:12 -04:00
Andrew Beveridge cf1fc0aa09 Fixed lyrics_transcriber_local ref in main package 2025-07-03 12:29:22 -04:00
Andrew Beveridge e4042932f7 Maybe fix tests 2025-07-03 12:23:49 -04:00
Andrew Beveridge b4ef812c60 Updated to latest frontent 2025-07-03 05:59:49 -04:00
Andrew Beveridge 2b6e34395d Made progress towards phase 2 working with modal app 2025-07-03 05:05:20 -04:00
Andrew Beveridge 48875ebeff Got initial part of the modal-backend web UI flow working with frontend submitting jobs to modal with live tail logs, job history management admin tools etc. Actual generation runs half of the job but gets stuck at review stage right now. Prompt written to work on that next. 2025-07-03 01:37:38 -04:00
Andrew Beveridge 45f4c6a741 Updated to support file uploads 2025-07-02 21:01:35 -04:00
Andrew Beveridge 614d1cab12 Updated frontend to point to new api_endpoint on Modal 2025-07-02 17:57:43 -04:00
Andrew Beveridge 80105fe315 Fix CI 2025-07-02 15:57:21 -04:00
Andrew Beveridge bd093fb7a7 Maybe fix CI 2025-07-02 15:55:14 -04:00
Andrew Beveridge b523be752f Add GitHub Pages deployment for frontend
- Update GitHub Actions workflow to deploy frontend automatically
- Add permissions and environment for GitHub Pages deployment
- Frontend will be deployed from /frontend directory to gen.nomadkaraoke.com
- Deployment happens automatically on pushes to main branch
2025-07-02 15:40:39 -04:00
Andrew Beveridge b74d7027c5 Renamed frontend dir 2025-07-02 15:35:00 -04:00
Andrew Beveridge 398c100785 Add Modal web application with separated frontend/backend
- Add Modal backend (app.py, core.py) with GPU-powered processing
- Add static frontend in docs/ for GitHub Pages deployment
- Frontend communicates with Modal API via CORS
- Supports custom domain deployment (gen.nomadkaraoke.com)
- Comprehensive admin dashboard with real-time monitoring
2025-07-02 15:29:41 -04:00
Andrew Beveridge 06397b7a60 Added modal migration plan doc 2025-07-02 01:21:24 -04:00
Andrew Beveridge 8c283c7987 Added architecture documentation 2025-07-02 01:21:00 -04:00
Andrew Beveridge f3f508b563 Simplify CI pipeline to replace etils publish action with single build 2025-07-01 23:37:23 -04:00
Andrew Beveridge c9c1456dbb Fix CI disk space fail 2025-07-01 23:28:42 -04:00
Andrew Beveridge efa9e85121 Fixed integration test 2025-07-01 23:16:42 -04:00
Andrew Beveridge 7c6e6992b9 Hopefully fix CI 2025-07-01 16:38:49 -04:00
Andrew Beveridge 54ecde878f Fixed integration tests 2025-07-01 15:53:09 -04:00
Andrew Beveridge aada7c84e7 Fix bug with lyrics_title param 2025-07-01 14:11:39 -04:00
Andrew Beveridge cc76db0c04 Hopefully fix CI, upgrade to latest version of lyrics-transcriber 2025-06-29 20:59:04 -04:00
Andrew Beveridge aa9a6e8659 Fix unit test mocking to fix CI 2025-06-29 16:55:50 -04:00
Andrew Beveridge 9169e5b4a7 Restructured tests, fixed support for python 3.13, updated to latest audio-separator and numpy etc. 2025-06-29 16:36:59 -04:00
Andrew Beveridge 9599dd595e Fixed integration tests by generating background images for use in styles.json and copying files to /tmp for test 2025-06-29 16:12:45 -04:00
Andrew Beveridge 4775d97d3f Hopefully fix CI 2025-06-29 15:22:22 -04:00
Andrew Beveridge bd42951779 Added badges / shields to readme 2025-06-29 15:12:30 -04:00
Andrew Beveridge d53d015e72 Fixed tests, tidied up pytest config to match other projects 2025-06-29 15:05:45 -04:00
Andrew Beveridge 193f8367b8 Update to latest pytorch and lyrics-transcriber 2025-06-29 02:09:25 -04:00
Andrew Beveridge ☄️ 3d3393ab89 Merge pull request #2 from nomadkaraoke/test-everything
Major refactor, rename to Karaoke Gen, implement tests for everything
2025-06-28 18:35:39 -04:00
Andrew Beveridge 1218926d92 Fixed bulk CLI, updated to latest lyrics-transcriber 2025-04-12 16:25:17 -04:00
Andrew Beveridge 792305682e Removed slow marker from edit lyrics test as it's now quick with proper mocks 2025-04-06 23:24:04 -04:00
Andrew Beveridge ab686359dc All tests now pass again! 2025-04-06 23:04:21 -04:00
Andrew Beveridge 5012c5d0a1 Fixed edit mode and began adding integration test for it (currently failing) 2025-04-06 21:47:30 -04:00
Andrew Beveridge 2d7b0f1c26 Fixed all tests 2025-04-03 11:31:09 -04:00
Andrew Beveridge cfe16f6184 Only 3 more failing unit tests to go 2025-04-03 01:44:33 -04:00
Andrew Beveridge f1c0cbac8f Began extracting more methods out of karaokeprep 2025-04-03 01:09:06 -04:00
Andrew Beveridge 30c3f7c804 Fixed missing ffmpeg dependency needed by cdgmaker 2025-04-03 01:08:53 -04:00
Andrew Beveridge cf9e0df626 Updated dependencies 2025-04-03 00:27:36 -04:00
Andrew Beveridge 510c3bf10e Fixed CLI tests 2025-04-02 22:48:34 -04:00
Andrew Beveridge 6a3bf940d5 Fixed karaoke-gen CLI but broke the tests 2025-04-02 22:44:54 -04:00
Andrew Beveridge 8ba63b2947 In theory, fixed all tests after the first iteration of extracting functionality. Full integration test failing though. 2025-04-02 09:47:42 -04:00
Andrew Beveridge 84faf54256 Fixed all tests 2025-04-02 00:21:48 -04:00
Andrew Beveridge ebca11c8f1 Improved a few more bulk_cli tests 2025-04-01 23:49:00 -04:00
Andrew Beveridge 8fd2287566 Fixed/skipped all tests 2025-04-01 23:27:46 -04:00
Andrew Beveridge 3cedf10243 Fixed more CLI tests, 9 failing 2025-04-01 23:09:58 -04:00
Andrew Beveridge e2383634ed Added more tests for CLI bits, 16 still failin 2025-04-01 22:19:57 -04:00
Andrew Beveridge 4157076365 Fixed all tests 2025-04-01 14:34:14 -04:00
Andrew Beveridge a0c50367e3 Fixed all but 13 finalise tests 2025-04-01 13:10:30 -04:00
Andrew Beveridge 716ea76fa8 First pass at finalise tests (41 failing) 2025-04-01 12:54:14 -04:00
Andrew Beveridge ec08054d99 Exclude slow integration test from default pytest 2025-04-01 12:33:22 -04:00
Andrew Beveridge d71047bace Fixed all but 2 tests 2025-04-01 12:16:24 -04:00
Andrew Beveridge d02dc69f25 Continued work to fix tests, 19 still failing 2025-04-01 01:58:18 -04:00
Andrew Beveridge b3a37f21da Began adding unit tests for existing karaoke_prep functionality 2025-04-01 01:46:09 -04:00
Andrew Beveridge 5bc97306ef Added thorough integration test 2025-04-01 00:27:47 -04:00
Andrew Beveridge c581353dfe Deleted old conda stuff which isn't used any more, updated deps 2025-03-31 02:39:25 -04:00
Andrew Beveridge dc712508ad Deleted old ffmpeg platform download thing for windows. Added test audio file 2025-03-31 02:34:48 -04:00
Andrew Beveridge 5276b8ea9a Began adding integration tests 2025-03-31 02:32:37 -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
118 changed files with 51831 additions and 2271 deletions

No files matched your search

+101
View File
@@ -0,0 +1,101 @@
---
description: Perform a non-destructive cross-artifact consistency and quality analysis across spec.md, plan.md, and tasks.md after task generation.
---
The user input to you can be provided directly by the agent or as a command argument - you **MUST** consider it before proceeding with the prompt (if not empty).
User input:
$ARGUMENTS
Goal: Identify inconsistencies, duplications, ambiguities, and underspecified items across the three core artifacts (`spec.md`, `plan.md`, `tasks.md`) before implementation. This command MUST run only after `/tasks` has successfully produced a complete `tasks.md`.
STRICTLY READ-ONLY: Do **not** modify any files. Output a structured analysis report. Offer an optional remediation plan (user must explicitly approve before any follow-up editing commands would be invoked manually).
Constitution Authority: The project constitution (`.specify/memory/constitution.md`) is **non-negotiable** within this analysis scope. Constitution conflicts are automatically CRITICAL and require adjustment of the spec, plan, or tasks—not dilution, reinterpretation, or silent ignoring of the principle. If a principle itself needs to change, that must occur in a separate, explicit constitution update outside `/analyze`.
Execution steps:
1. Run `.specify/scripts/bash/check-prerequisites.sh --json --require-tasks --include-tasks` once from repo root and parse JSON for FEATURE_DIR and AVAILABLE_DOCS. Derive absolute paths:
- SPEC = FEATURE_DIR/spec.md
- PLAN = FEATURE_DIR/plan.md
- TASKS = FEATURE_DIR/tasks.md
Abort with an error message if any required file is missing (instruct the user to run missing prerequisite command).
2. Load artifacts:
- Parse spec.md sections: Overview/Context, Functional Requirements, Non-Functional Requirements, User Stories, Edge Cases (if present).
- Parse plan.md: Architecture/stack choices, Data Model references, Phases, Technical constraints.
- Parse tasks.md: Task IDs, descriptions, phase grouping, parallel markers [P], referenced file paths.
- Load constitution `.specify/memory/constitution.md` for principle validation.
3. Build internal semantic models:
- Requirements inventory: Each functional + non-functional requirement with a stable key (derive slug based on imperative phrase; e.g., "User can upload file" -> `user-can-upload-file`).
- User story/action inventory.
- Task coverage mapping: Map each task to one or more requirements or stories (inference by keyword / explicit reference patterns like IDs or key phrases).
- Constitution rule set: Extract principle names and any MUST/SHOULD normative statements.
4. Detection passes:
A. Duplication detection:
- Identify near-duplicate requirements. Mark lower-quality phrasing for consolidation.
B. Ambiguity detection:
- Flag vague adjectives (fast, scalable, secure, intuitive, robust) lacking measurable criteria.
- Flag unresolved placeholders (TODO, TKTK, ???, <placeholder>, etc.).
C. Underspecification:
- Requirements with verbs but missing object or measurable outcome.
- User stories missing acceptance criteria alignment.
- Tasks referencing files or components not defined in spec/plan.
D. Constitution alignment:
- Any requirement or plan element conflicting with a MUST principle.
- Missing mandated sections or quality gates from constitution.
E. Coverage gaps:
- Requirements with zero associated tasks.
- Tasks with no mapped requirement/story.
- Non-functional requirements not reflected in tasks (e.g., performance, security).
F. Inconsistency:
- Terminology drift (same concept named differently across files).
- Data entities referenced in plan but absent in spec (or vice versa).
- Task ordering contradictions (e.g., integration tasks before foundational setup tasks without dependency note).
- Conflicting requirements (e.g., one requires to use Next.js while other says to use Vue as the framework).
5. Severity assignment heuristic:
- CRITICAL: Violates constitution MUST, missing core spec artifact, or requirement with zero coverage that blocks baseline functionality.
- HIGH: Duplicate or conflicting requirement, ambiguous security/performance attribute, untestable acceptance criterion.
- MEDIUM: Terminology drift, missing non-functional task coverage, underspecified edge case.
- LOW: Style/wording improvements, minor redundancy not affecting execution order.
6. Produce a Markdown report (no file writes) with sections:
### Specification Analysis Report
| ID | Category | Severity | Location(s) | Summary | Recommendation |
|----|----------|----------|-------------|---------|----------------|
| A1 | Duplication | HIGH | spec.md:L120-134 | Two similar requirements ... | Merge phrasing; keep clearer version |
(Add one row per finding; generate stable IDs prefixed by category initial.)
Additional subsections:
- Coverage Summary Table:
| Requirement Key | Has Task? | Task IDs | Notes |
- Constitution Alignment Issues (if any)
- Unmapped Tasks (if any)
- Metrics:
* Total Requirements
* Total Tasks
* Coverage % (requirements with >=1 task)
* Ambiguity Count
* Duplication Count
* Critical Issues Count
7. At end of report, output a concise Next Actions block:
- If CRITICAL issues exist: Recommend resolving before `/implement`.
- If only LOW/MEDIUM: User may proceed, but provide improvement suggestions.
- Provide explicit command suggestions: e.g., "Run /specify with refinement", "Run /plan to adjust architecture", "Manually edit tasks.md to add coverage for 'performance-metrics'".
8. Ask the user: "Would you like me to suggest concrete remediation edits for the top N issues?" (Do NOT apply them automatically.)
Behavior rules:
- NEVER modify files.
- NEVER hallucinate missing sections—if absent, report them.
- KEEP findings deterministic: if rerun without changes, produce consistent IDs and counts.
- LIMIT total findings in the main table to 50; aggregate remainder in a summarized overflow note.
- If zero issues found, emit a success report with coverage statistics and proceed recommendation.
Context: $ARGUMENTS
+158
View File
@@ -0,0 +1,158 @@
---
description: Identify underspecified areas in the current feature spec by asking up to 5 highly targeted clarification questions and encoding answers back into the spec.
---
The user input to you can be provided directly by the agent or as a command argument - you **MUST** consider it before proceeding with the prompt (if not empty).
User input:
$ARGUMENTS
Goal: Detect and reduce ambiguity or missing decision points in the active feature specification and record the clarifications directly in the spec file.
Note: This clarification workflow is expected to run (and be completed) BEFORE invoking `/plan`. If the user explicitly states they are skipping clarification (e.g., exploratory spike), you may proceed, but must warn that downstream rework risk increases.
Execution steps:
1. Run `.specify/scripts/bash/check-prerequisites.sh --json --paths-only` from repo root **once** (combined `--json --paths-only` mode / `-Json -PathsOnly`). Parse minimal JSON payload fields:
- `FEATURE_DIR`
- `FEATURE_SPEC`
- (Optionally capture `IMPL_PLAN`, `TASKS` for future chained flows.)
- If JSON parsing fails, abort and instruct user to re-run `/specify` or verify feature branch environment.
2. Load the current spec file. Perform a structured ambiguity & coverage scan using this taxonomy. For each category, mark status: Clear / Partial / Missing. Produce an internal coverage map used for prioritization (do not output raw map unless no questions will be asked).
Functional Scope & Behavior:
- Core user goals & success criteria
- Explicit out-of-scope declarations
- User roles / personas differentiation
Domain & Data Model:
- Entities, attributes, relationships
- Identity & uniqueness rules
- Lifecycle/state transitions
- Data volume / scale assumptions
Interaction & UX Flow:
- Critical user journeys / sequences
- Error/empty/loading states
- Accessibility or localization notes
Non-Functional Quality Attributes:
- Performance (latency, throughput targets)
- Scalability (horizontal/vertical, limits)
- Reliability & availability (uptime, recovery expectations)
- Observability (logging, metrics, tracing signals)
- Security & privacy (authN/Z, data protection, threat assumptions)
- Compliance / regulatory constraints (if any)
Integration & External Dependencies:
- External services/APIs and failure modes
- Data import/export formats
- Protocol/versioning assumptions
Edge Cases & Failure Handling:
- Negative scenarios
- Rate limiting / throttling
- Conflict resolution (e.g., concurrent edits)
Constraints & Tradeoffs:
- Technical constraints (language, storage, hosting)
- Explicit tradeoffs or rejected alternatives
Terminology & Consistency:
- Canonical glossary terms
- Avoided synonyms / deprecated terms
Completion Signals:
- Acceptance criteria testability
- Measurable Definition of Done style indicators
Misc / Placeholders:
- TODO markers / unresolved decisions
- Ambiguous adjectives ("robust", "intuitive") lacking quantification
For each category with Partial or Missing status, add a candidate question opportunity unless:
- Clarification would not materially change implementation or validation strategy
- Information is better deferred to planning phase (note internally)
3. Generate (internally) a prioritized queue of candidate clarification questions (maximum 5). Do NOT output them all at once. Apply these constraints:
- Maximum of 5 total questions across the whole session.
- Each question must be answerable with EITHER:
* A short multiple‑choice selection (2–5 distinct, mutually exclusive options), OR
* A one-word / short‑phrase answer (explicitly constrain: "Answer in <=5 words").
- Only include questions whose answers materially impact architecture, data modeling, task decomposition, test design, UX behavior, operational readiness, or compliance validation.
- Ensure category coverage balance: attempt to cover the highest impact unresolved categories first; avoid asking two low-impact questions when a single high-impact area (e.g., security posture) is unresolved.
- Exclude questions already answered, trivial stylistic preferences, or plan-level execution details (unless blocking correctness).
- Favor clarifications that reduce downstream rework risk or prevent misaligned acceptance tests.
- If more than 5 categories remain unresolved, select the top 5 by (Impact * Uncertainty) heuristic.
4. Sequential questioning loop (interactive):
- Present EXACTLY ONE question at a time.
- For multiple‑choice questions render options as a Markdown table:
| Option | Description |
|--------|-------------|
| A | <Option A description> |
| B | <Option B description> |
| C | <Option C description> | (add D/E as needed up to 5)
| Short | Provide a different short answer (<=5 words) | (Include only if free-form alternative is appropriate)
- For short‑answer style (no meaningful discrete options), output a single line after the question: `Format: Short answer (<=5 words)`.
- After the user answers:
* Validate the answer maps to one option or fits the <=5 word constraint.
* If ambiguous, ask for a quick disambiguation (count still belongs to same question; do not advance).
* Once satisfactory, record it in working memory (do not yet write to disk) and move to the next queued question.
- Stop asking further questions when:
* All critical ambiguities resolved early (remaining queued items become unnecessary), OR
* User signals completion ("done", "good", "no more"), OR
* You reach 5 asked questions.
- Never reveal future queued questions in advance.
- If no valid questions exist at start, immediately report no critical ambiguities.
5. Integration after EACH accepted answer (incremental update approach):
- Maintain in-memory representation of the spec (loaded once at start) plus the raw file contents.
- For the first integrated answer in this session:
* Ensure a `## Clarifications` section exists (create it just after the highest-level contextual/overview section per the spec template if missing).
* Under it, create (if not present) a `### Session YYYY-MM-DD` subheading for today.
- Append a bullet line immediately after acceptance: `- Q: <question> → A: <final answer>`.
- Then immediately apply the clarification to the most appropriate section(s):
* Functional ambiguity → Update or add a bullet in Functional Requirements.
* User interaction / actor distinction → Update User Stories or Actors subsection (if present) with clarified role, constraint, or scenario.
* Data shape / entities → Update Data Model (add fields, types, relationships) preserving ordering; note added constraints succinctly.
* Non-functional constraint → Add/modify measurable criteria in Non-Functional / Quality Attributes section (convert vague adjective to metric or explicit target).
* Edge case / negative flow → Add a new bullet under Edge Cases / Error Handling (or create such subsection if template provides placeholder for it).
* Terminology conflict → Normalize term across spec; retain original only if necessary by adding `(formerly referred to as "X")` once.
- If the clarification invalidates an earlier ambiguous statement, replace that statement instead of duplicating; leave no obsolete contradictory text.
- Save the spec file AFTER each integration to minimize risk of context loss (atomic overwrite).
- Preserve formatting: do not reorder unrelated sections; keep heading hierarchy intact.
- Keep each inserted clarification minimal and testable (avoid narrative drift).
6. Validation (performed after EACH write plus final pass):
- Clarifications session contains exactly one bullet per accepted answer (no duplicates).
- Total asked (accepted) questions ≤ 5.
- Updated sections contain no lingering vague placeholders the new answer was meant to resolve.
- No contradictory earlier statement remains (scan for now-invalid alternative choices removed).
- Markdown structure valid; only allowed new headings: `## Clarifications`, `### Session YYYY-MM-DD`.
- Terminology consistency: same canonical term used across all updated sections.
7. Write the updated spec back to `FEATURE_SPEC`.
8. Report completion (after questioning loop ends or early termination):
- Number of questions asked & answered.
- Path to updated spec.
- Sections touched (list names).
- Coverage summary table listing each taxonomy category with Status: Resolved (was Partial/Missing and addressed), Deferred (exceeds question quota or better suited for planning), Clear (already sufficient), Outstanding (still Partial/Missing but low impact).
- If any Outstanding or Deferred remain, recommend whether to proceed to `/plan` or run `/clarify` again later post-plan.
- Suggested next command.
Behavior rules:
- If no meaningful ambiguities found (or all potential questions would be low-impact), respond: "No critical ambiguities detected worth formal clarification." and suggest proceeding.
- If spec file missing, instruct user to run `/specify` first (do not create a new spec here).
- Never exceed 5 total asked questions (clarification retries for a single question do not count as new questions).
- Avoid speculative tech stack questions unless the absence blocks functional clarity.
- Respect user early termination signals ("stop", "done", "proceed").
- If no questions asked due to full coverage, output a compact coverage summary (all categories Clear) then suggest advancing.
- If quota reached with unresolved high-impact categories remaining, explicitly flag them under Deferred with rationale.
Context for prioritization: $ARGUMENTS
+73
View File
@@ -0,0 +1,73 @@
---
description: Create or update the project constitution from interactive or provided principle inputs, ensuring all dependent templates stay in sync.
---
The user input to you can be provided directly by the agent or as a command argument - you **MUST** consider it before proceeding with the prompt (if not empty).
User input:
$ARGUMENTS
You are updating the project constitution at `.specify/memory/constitution.md`. This file is a TEMPLATE containing placeholder tokens in square brackets (e.g. `[PROJECT_NAME]`, `[PRINCIPLE_1_NAME]`). Your job is to (a) collect/derive concrete values, (b) fill the template precisely, and (c) propagate any amendments across dependent artifacts.
Follow this execution flow:
1. Load the existing constitution template at `.specify/memory/constitution.md`.
- Identify every placeholder token of the form `[ALL_CAPS_IDENTIFIER]`.
**IMPORTANT**: The user might require less or more principles than the ones used in the template. If a number is specified, respect that - follow the general template. You will update the doc accordingly.
2. Collect/derive values for placeholders:
- If user input (conversation) supplies a value, use it.
- Otherwise infer from existing repo context (README, docs, prior constitution versions if embedded).
- For governance dates: `RATIFICATION_DATE` is the original adoption date (if unknown ask or mark TODO), `LAST_AMENDED_DATE` is today if changes are made, otherwise keep previous.
- `CONSTITUTION_VERSION` must increment according to semantic versioning rules:
* MAJOR: Backward incompatible governance/principle removals or redefinitions.
* MINOR: New principle/section added or materially expanded guidance.
* PATCH: Clarifications, wording, typo fixes, non-semantic refinements.
- If version bump type ambiguous, propose reasoning before finalizing.
3. Draft the updated constitution content:
- Replace every placeholder with concrete text (no bracketed tokens left except intentionally retained template slots that the project has chosen not to define yet—explicitly justify any left).
- Preserve heading hierarchy and comments can be removed once replaced unless they still add clarifying guidance.
- Ensure each Principle section: succinct name line, paragraph (or bullet list) capturing non‑negotiable rules, explicit rationale if not obvious.
- Ensure Governance section lists amendment procedure, versioning policy, and compliance review expectations.
4. Consistency propagation checklist (convert prior checklist into active validations):
- Read `.specify/templates/plan-template.md` and ensure any "Constitution Check" or rules align with updated principles.
- Read `.specify/templates/spec-template.md` for scope/requirements alignment—update if constitution adds/removes mandatory sections or constraints.
- Read `.specify/templates/tasks-template.md` and ensure task categorization reflects new or removed principle-driven task types (e.g., observability, versioning, testing discipline).
- Read each command file in `.specify/templates/commands/*.md` (including this one) to verify no outdated references (agent-specific names like CLAUDE only) remain when generic guidance is required.
- Read any runtime guidance docs (e.g., `README.md`, `docs/quickstart.md`, or agent-specific guidance files if present). Update references to principles changed.
5. Produce a Sync Impact Report (prepend as an HTML comment at top of the constitution file after update):
- Version change: old → new
- List of modified principles (old title → new title if renamed)
- Added sections
- Removed sections
- Templates requiring updates (✅ updated / ⚠ pending) with file paths
- Follow-up TODOs if any placeholders intentionally deferred.
6. Validation before final output:
- No remaining unexplained bracket tokens.
- Version line matches report.
- Dates ISO format YYYY-MM-DD.
- Principles are declarative, testable, and free of vague language ("should" → replace with MUST/SHOULD rationale where appropriate).
7. Write the completed constitution back to `.specify/memory/constitution.md` (overwrite).
8. Output a final summary to the user with:
- New version and bump rationale.
- Any files flagged for manual follow-up.
- Suggested commit message (e.g., `docs: amend constitution to vX.Y.Z (principle additions + governance update)`).
Formatting & Style Requirements:
- Use Markdown headings exactly as in the template (do not demote/promote levels).
- Wrap long rationale lines to keep readability (<100 chars ideally) but do not hard enforce with awkward breaks.
- Keep a single blank line between sections.
- Avoid trailing whitespace.
If the user supplies partial updates (e.g., only one principle revision), still perform validation and version decision steps.
If critical info missing (e.g., ratification date truly unknown), insert `TODO(<FIELD_NAME>): explanation` and include in the Sync Impact Report under deferred items.
Do not create a new template; always operate on the existing `.specify/memory/constitution.md` file.
+56
View File
@@ -0,0 +1,56 @@
---
description: Execute the implementation plan by processing and executing all tasks defined in tasks.md
---
The user input can be provided directly by the agent or as a command argument - you **MUST** consider it before proceeding with the prompt (if not empty).
User input:
$ARGUMENTS
1. Run `.specify/scripts/bash/check-prerequisites.sh --json --require-tasks --include-tasks` from repo root and parse FEATURE_DIR and AVAILABLE_DOCS list. All paths must be absolute.
2. Load and analyze the implementation context:
- **REQUIRED**: Read tasks.md for the complete task list and execution plan
- **REQUIRED**: Read plan.md for tech stack, architecture, and file structure
- **IF EXISTS**: Read data-model.md for entities and relationships
- **IF EXISTS**: Read contracts/ for API specifications and test requirements
- **IF EXISTS**: Read research.md for technical decisions and constraints
- **IF EXISTS**: Read quickstart.md for integration scenarios
3. Parse tasks.md structure and extract:
- **Task phases**: Setup, Tests, Core, Integration, Polish
- **Task dependencies**: Sequential vs parallel execution rules
- **Task details**: ID, description, file paths, parallel markers [P]
- **Execution flow**: Order and dependency requirements
4. Execute implementation following the task plan:
- **Phase-by-phase execution**: Complete each phase before moving to the next
- **Respect dependencies**: Run sequential tasks in order, parallel tasks [P] can run together
- **Follow TDD approach**: Execute test tasks before their corresponding implementation tasks
- **File-based coordination**: Tasks affecting the same files must run sequentially
- **Validation checkpoints**: Verify each phase completion before proceeding
5. Implementation execution rules:
- **Setup first**: Initialize project structure, dependencies, configuration
- **Tests before code**: If you need to write tests for contracts, entities, and integration scenarios
- **Core development**: Implement models, services, CLI commands, endpoints
- **Integration work**: Database connections, middleware, logging, external services
- **Polish and validation**: Unit tests, performance optimization, documentation
6. Progress tracking and error handling:
- Report progress after each completed task
- Halt execution if any non-parallel task fails
- For parallel tasks [P], continue with successful tasks, report failed ones
- Provide clear error messages with context for debugging
- Suggest next steps if implementation cannot proceed
- **IMPORTANT** For completed tasks, make sure to mark the task off as [X] in the tasks file.
7. Completion validation:
- Verify all required tasks are completed
- Check that implemented features match the original specification
- Validate that tests pass and coverage meets requirements
- Confirm the implementation follows the technical plan
- Report final status with summary of completed work
Note: This command assumes a complete task breakdown exists in tasks.md. If tasks are incomplete or missing, suggest running `/tasks` first to regenerate the task list.
+43
View File
@@ -0,0 +1,43 @@
---
description: Execute the implementation planning workflow using the plan template to generate design artifacts.
---
The user input to you can be provided directly by the agent or as a command argument - you **MUST** consider it before proceeding with the prompt (if not empty).
User input:
$ARGUMENTS
Given the implementation details provided as an argument, do this:
1. Run `.specify/scripts/bash/setup-plan.sh --json` from the repo root and parse JSON for FEATURE_SPEC, IMPL_PLAN, SPECS_DIR, BRANCH. All future file paths must be absolute.
- BEFORE proceeding, inspect FEATURE_SPEC for a `## Clarifications` section with at least one `Session` subheading. If missing or clearly ambiguous areas remain (vague adjectives, unresolved critical choices), PAUSE and instruct the user to run `/clarify` first to reduce rework. Only continue if: (a) Clarifications exist OR (b) an explicit user override is provided (e.g., "proceed without clarification"). Do not attempt to fabricate clarifications yourself.
2. Read and analyze the feature specification to understand:
- The feature requirements and user stories
- Functional and non-functional requirements
- Success criteria and acceptance criteria
- Any technical constraints or dependencies mentioned
3. Read the constitution at `.specify/memory/constitution.md` to understand constitutional requirements.
4. Execute the implementation plan template:
- Load `.specify/templates/plan-template.md` (already copied to IMPL_PLAN path)
- Set Input path to FEATURE_SPEC
- Run the Execution Flow (main) function steps 1-9
- The template is self-contained and executable
- Follow error handling and gate checks as specified
- Let the template guide artifact generation in $SPECS_DIR:
* Phase 0 generates research.md
* Phase 1 generates data-model.md, contracts/, quickstart.md
* Phase 2 generates tasks.md
- Incorporate user-provided details from arguments into Technical Context: $ARGUMENTS
- Update Progress Tracking as you complete each phase
5. Verify execution completed:
- Check Progress Tracking shows all phases complete
- Ensure all required artifacts were generated
- Confirm no ERROR states in execution
6. Report results with branch name, file paths, and generated artifacts.
Use absolute paths with the repository root for all file operations to avoid path issues.
+21
View File
@@ -0,0 +1,21 @@
---
description: Create or update the feature specification from a natural language feature description.
---
The user input to you can be provided directly by the agent or as a command argument - you **MUST** consider it before proceeding with the prompt (if not empty).
User input:
$ARGUMENTS
The text the user typed after `/specify` in the triggering message **is** the feature description. Assume you always have it available in this conversation even if `$ARGUMENTS` appears literally below. Do not ask the user to repeat it unless they provided an empty command.
Given that feature description, do this:
1. Run the script `.specify/scripts/bash/create-new-feature.sh --json "$ARGUMENTS"` from repo root and parse its JSON output for BRANCH_NAME and SPEC_FILE. All file paths must be absolute.
**IMPORTANT** You must only ever run this script once. The JSON is provided in the terminal as output - always refer to it to get the actual content you're looking for.
2. Load `.specify/templates/spec-template.md` to understand required sections.
3. Write the specification to SPEC_FILE using the template structure, replacing placeholders with concrete details derived from the feature description (arguments) while preserving section order and headings.
4. Report completion with branch name, spec file path, and readiness for the next phase.
Note: The script creates and checks out the new branch and initializes the spec file before writing.
+62
View File
@@ -0,0 +1,62 @@
---
description: Generate an actionable, dependency-ordered tasks.md for the feature based on available design artifacts.
---
The user input to you can be provided directly by the agent or as a command argument - you **MUST** consider it before proceeding with the prompt (if not empty).
User input:
$ARGUMENTS
1. Run `.specify/scripts/bash/check-prerequisites.sh --json` from repo root and parse FEATURE_DIR and AVAILABLE_DOCS list. All paths must be absolute.
2. Load and analyze available design documents:
- Always read plan.md for tech stack and libraries
- IF EXISTS: Read data-model.md for entities
- IF EXISTS: Read contracts/ for API endpoints
- IF EXISTS: Read research.md for technical decisions
- IF EXISTS: Read quickstart.md for test scenarios
Note: Not all projects have all documents. For example:
- CLI tools might not have contracts/
- Simple libraries might not need data-model.md
- Generate tasks based on what's available
3. Generate tasks following the template:
- Use `.specify/templates/tasks-template.md` as the base
- Replace example tasks with actual tasks based on:
* **Setup tasks**: Project init, dependencies, linting
* **Test tasks [P]**: One per contract, one per integration scenario
* **Core tasks**: One per entity, service, CLI command, endpoint
* **Integration tasks**: DB connections, middleware, logging
* **Polish tasks [P]**: Unit tests, performance, docs
4. Task generation rules:
- Each contract file → contract test task marked [P]
- Each entity in data-model → model creation task marked [P]
- Each endpoint → implementation task (not parallel if shared files)
- Each user story → integration test marked [P]
- Different files = can be parallel [P]
- Same file = sequential (no [P])
5. Order tasks by dependencies:
- Setup before everything
- Tests before implementation (TDD)
- Models before services
- Services before endpoints
- Core before integration
- Everything before polish
6. Include parallel execution examples:
- Group [P] tasks that can run together
- Show actual Task agent commands
7. Create FEATURE_DIR/tasks.md with:
- Correct feature name from implementation plan
- Numbered tasks (T001, T002, etc.)
- Clear file paths for each task
- Dependency notes
- Parallel execution guidance
Context for task generation: $ARGUMENTS
The tasks.md should be immediately executable - each task must be specific enough that an LLM can complete it without additional context.
+28
View File
@@ -0,0 +1,28 @@
2384d2383
< triton = ">=2.0.0,<3"
4185d4183
< triton = {version = "2.3.1", markers = "platform_system == \"Linux\" and platform_machine == \"x86_64\" and python_version < \"3.12\""}
4318,4340d4315
< name = "triton"
< version = "2.3.1"
< description = "A language and compiler for custom Deep Learning operations"
< optional = false
< python-versions = "*"
< files = [
< {file = "triton-2.3.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3c84595cbe5e546b1b290d2a58b1494df5a2ef066dd890655e5b8a8a92205c33"},
< {file = "triton-2.3.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c9d64ae33bcb3a7a18081e3a746e8cf87ca8623ca13d2c362413ce7a486f893e"},
< {file = "triton-2.3.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eaf80e8761a9e3498aa92e7bf83a085b31959c61f5e8ac14eedd018df6fccd10"},
< {file = "triton-2.3.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b13bf35a2b659af7159bf78e92798dc62d877aa991de723937329e2d382f1991"},
< {file = "triton-2.3.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:63381e35ded3304704ea867ffde3b7cfc42c16a55b3062d41e017ef510433d66"},
< {file = "triton-2.3.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1d968264523c7a07911c8fb51b4e0d1b920204dae71491b1fe7b01b62a31e124"},
< ]
<
< [package.dependencies]
< filelock = "*"
<
< [package.extras]
< build = ["cmake (>=3.20)", "lit"]
< tests = ["autopep8", "flake8", "isort", "numpy", "pytest", "scipy (>=1.7.1)", "torch"]
< tutorials = ["matplotlib", "pandas", "tabulate", "torch"]
<
< [[package]]
-19
View File
@@ -1,19 +0,0 @@
name: Auto-publish
on: [push, workflow_dispatch]
jobs:
# Auto-publish when version is increased
publish-job:
# Only publish on `main` branch
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
permissions: # Don't forget permissions
contents: write
steps:
- uses: etils-actions/pypi-auto-publish@v1
with:
pypi-token: ${{ secrets.PYPI_API_TOKEN }}
gh-token: ${{ secrets.GITHUB_TOKEN }}
parse-changelog: false
+187
View File
@@ -0,0 +1,187 @@
name: Test and Publish
on: [push, pull_request, workflow_dispatch]
# Add permissions for GitHub Pages deployment and git operations
permissions:
contents: write # Changed from 'read' to 'write' to allow creating git tags
pages: write
id-token: write
# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
concurrency:
group: "pages"
cancel-in-progress: false
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.13']
steps:
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install Poetry
uses: snok/install-poetry@v1
with:
virtualenvs-create: true
virtualenvs-in-project: true
- name: Install dependencies
run: |
poetry install --with dev
- name: Install system dependencies
run: |
sudo apt-get update
sudo apt-get install -y ffmpeg
- name: Install spaCy language models
run: |
poetry run python -m spacy download en_core_web_sm
- name: Run unit tests
run: |
poetry run pytest tests/unit/ -v --cov=karaoke_gen --cov-report=xml --cov-report=term-missing --cov-fail-under=70
- name: Upload coverage reports
uses: codecov/codecov-action@v5
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: ./coverage.xml
flags: unittests
name: codecov-umbrella
- name: Run integration tests
run: |
poetry run pytest tests/integration/ -v
- name: Build package
run: |
poetry build
- name: Free Disk Space (GHA Ubuntu Runner)
uses: jlumbroso/free-disk-space@main
with:
# this might remove tools that are actually needed,
# if set to "true" but frees about 6 GB
tool-cache: false
# all of these default to true, but feel free to set to
# "false" if necessary for your workflow
android: true
haskell: true
dotnet: false
large-packages: false
docker-images: false
swap-storage: false
- name: Test package installation
run: |
pip install dist/*.whl
python -m karaoke_gen.utils.gen_cli --help
- if: github.ref == 'refs/heads/main' && github.event_name == 'push'
name: Extract version
id: extract_version
run: |
VERSION=$(poetry version --short)
echo "version=$VERSION" >> $GITHUB_OUTPUT
echo "📋 Extracted version: $VERSION"
- if: github.ref == 'refs/heads/main' && github.event_name == 'push'
name: Check if tag exists
id: check_tag
run: |
VERSION="${{ steps.extract_version.outputs.version }}"
if git ls-remote --tags origin | grep -q "refs/tags/v$VERSION$"; then
echo "tag_exists=true" >> $GITHUB_OUTPUT
echo "🏷️ Tag v$VERSION already exists, skipping release"
else
echo "tag_exists=false" >> $GITHUB_OUTPUT
echo "✨ Tag v$VERSION does not exist, proceeding with release"
fi
- if: github.ref == 'refs/heads/main' && github.event_name == 'push' && steps.check_tag.outputs.tag_exists == 'false'
name: Publish to PyPI
run: |
echo "📦 Publishing the following files to PyPI:"
ls -la dist/
echo "🚀 Publishing to PyPI..."
poetry config pypi-token.pypi ${{ secrets.PYPI_API_TOKEN }}
poetry publish
- if: github.ref == 'refs/heads/main' && github.event_name == 'push' && steps.check_tag.outputs.tag_exists == 'false'
name: Create Git Tag
run: |
git config user.name github-actions
git config user.email github-actions@github.com
git tag -a "v${{ steps.extract_version.outputs.version }}" -m "Release v${{ steps.extract_version.outputs.version }}"
git push https://${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }} "v${{ steps.extract_version.outputs.version }}"
- if: github.ref == 'refs/heads/main' && github.event_name == 'push' && steps.check_tag.outputs.tag_exists == 'false'
name: Create GitHub Release
uses: softprops/action-gh-release@v1
with:
tag_name: "v${{ steps.extract_version.outputs.version }}"
name: "v${{ steps.extract_version.outputs.version }}"
body: |
## Changes in v${{ steps.extract_version.outputs.version }}
This release was automatically created from the main branch.
### Installation
```bash
pip install karaoke-gen==${{ steps.extract_version.outputs.version }}
```
### Assets
- Python package published to PyPI
- Frontend deployed to GitHub Pages at gen.nomadkaraoke.com
For detailed changes, see the commit history.
draft: false
prerelease: false
files: |
dist/*.whl
dist/*.tar.gz
# Deploy frontend to GitHub Pages
deploy-frontend:
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Pages
uses: actions/configure-pages@v4
- name: Prepare frontend files
run: |
echo "📁 Preparing frontend files for deployment..."
mkdir -p _site
cp -r frontend/* _site/
echo "✅ Frontend files copied to _site/"
ls -la _site/
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: '_site'
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
+6 -2
View File
@@ -1,12 +1,16 @@
# Andrew env
.DS_Store
.vscode
*.csv
*.mp3
# lyrics_transcriber_local
# Andrew functional adds
audio/
lyrics/
karaoke/
tests/outputs
input
# Byte-compiled / optimized / DLL files
__pycache__/
@@ -40,7 +44,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
+50
View File
@@ -0,0 +1,50 @@
# [PROJECT_NAME] Constitution
<!-- Example: Spec Constitution, TaskFlow Constitution, etc. -->
## Core Principles
### [PRINCIPLE_1_NAME]
<!-- Example: I. Library-First -->
[PRINCIPLE_1_DESCRIPTION]
<!-- Example: Every feature starts as a standalone library; Libraries must be self-contained, independently testable, documented; Clear purpose required - no organizational-only libraries -->
### [PRINCIPLE_2_NAME]
<!-- Example: II. CLI Interface -->
[PRINCIPLE_2_DESCRIPTION]
<!-- Example: Every library exposes functionality via CLI; Text in/out protocol: stdin/args → stdout, errors → stderr; Support JSON + human-readable formats -->
### [PRINCIPLE_3_NAME]
<!-- Example: III. Test-First (NON-NEGOTIABLE) -->
[PRINCIPLE_3_DESCRIPTION]
<!-- Example: TDD mandatory: Tests written → User approved → Tests fail → Then implement; Red-Green-Refactor cycle strictly enforced -->
### [PRINCIPLE_4_NAME]
<!-- Example: IV. Integration Testing -->
[PRINCIPLE_4_DESCRIPTION]
<!-- Example: Focus areas requiring integration tests: New library contract tests, Contract changes, Inter-service communication, Shared schemas -->
### [PRINCIPLE_5_NAME]
<!-- Example: V. Observability, VI. Versioning & Breaking Changes, VII. Simplicity -->
[PRINCIPLE_5_DESCRIPTION]
<!-- Example: Text I/O ensures debuggability; Structured logging required; Or: MAJOR.MINOR.BUILD format; Or: Start simple, YAGNI principles -->
## [SECTION_2_NAME]
<!-- Example: Additional Constraints, Security Requirements, Performance Standards, etc. -->
[SECTION_2_CONTENT]
<!-- Example: Technology stack requirements, compliance standards, deployment policies, etc. -->
## [SECTION_3_NAME]
<!-- Example: Development Workflow, Review Process, Quality Gates, etc. -->
[SECTION_3_CONTENT]
<!-- Example: Code review requirements, testing gates, deployment approval process, etc. -->
## Governance
<!-- Example: Constitution supersedes all other practices; Amendments require documentation, approval, migration plan -->
[GOVERNANCE_RULES]
<!-- Example: All PRs/reviews must verify compliance; Complexity must be justified; Use [GUIDANCE_FILE] for runtime development guidance -->
**Version**: [CONSTITUTION_VERSION] | **Ratified**: [RATIFICATION_DATE] | **Last Amended**: [LAST_AMENDED_DATE]
<!-- Example: Version: 2.1.1 | Ratified: 2025-06-13 | Last Amended: 2025-07-16 -->
+166
View File
@@ -0,0 +1,166 @@
#!/usr/bin/env bash
# Consolidated prerequisite checking script
#
# This script provides unified prerequisite checking for Spec-Driven Development workflow.
# It replaces the functionality previously spread across multiple scripts.
#
# Usage: ./check-prerequisites.sh [OPTIONS]
#
# OPTIONS:
# --json Output in JSON format
# --require-tasks Require tasks.md to exist (for implementation phase)
# --include-tasks Include tasks.md in AVAILABLE_DOCS list
# --paths-only Only output path variables (no validation)
# --help, -h Show help message
#
# OUTPUTS:
# JSON mode: {"FEATURE_DIR":"...", "AVAILABLE_DOCS":["..."]}
# Text mode: FEATURE_DIR:... \n AVAILABLE_DOCS: \n ✓/✗ file.md
# Paths only: REPO_ROOT: ... \n BRANCH: ... \n FEATURE_DIR: ... etc.
set -e
# Parse command line arguments
JSON_MODE=false
REQUIRE_TASKS=false
INCLUDE_TASKS=false
PATHS_ONLY=false
for arg in "$@"; do
case "$arg" in
--json)
JSON_MODE=true
;;
--require-tasks)
REQUIRE_TASKS=true
;;
--include-tasks)
INCLUDE_TASKS=true
;;
--paths-only)
PATHS_ONLY=true
;;
--help|-h)
cat << 'EOF'
Usage: check-prerequisites.sh [OPTIONS]
Consolidated prerequisite checking for Spec-Driven Development workflow.
OPTIONS:
--json Output in JSON format
--require-tasks Require tasks.md to exist (for implementation phase)
--include-tasks Include tasks.md in AVAILABLE_DOCS list
--paths-only Only output path variables (no prerequisite validation)
--help, -h Show this help message
EXAMPLES:
# Check task prerequisites (plan.md required)
./check-prerequisites.sh --json
# Check implementation prerequisites (plan.md + tasks.md required)
./check-prerequisites.sh --json --require-tasks --include-tasks
# Get feature paths only (no validation)
./check-prerequisites.sh --paths-only
EOF
exit 0
;;
*)
echo "ERROR: Unknown option '$arg'. Use --help for usage information." >&2
exit 1
;;
esac
done
# Source common functions
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"
# Get feature paths and validate branch
eval $(get_feature_paths)
check_feature_branch "$CURRENT_BRANCH" "$HAS_GIT" || exit 1
# If paths-only mode, output paths and exit (support JSON + paths-only combined)
if $PATHS_ONLY; then
if $JSON_MODE; then
# Minimal JSON paths payload (no validation performed)
printf '{"REPO_ROOT":"%s","BRANCH":"%s","FEATURE_DIR":"%s","FEATURE_SPEC":"%s","IMPL_PLAN":"%s","TASKS":"%s"}\n' \
"$REPO_ROOT" "$CURRENT_BRANCH" "$FEATURE_DIR" "$FEATURE_SPEC" "$IMPL_PLAN" "$TASKS"
else
echo "REPO_ROOT: $REPO_ROOT"
echo "BRANCH: $CURRENT_BRANCH"
echo "FEATURE_DIR: $FEATURE_DIR"
echo "FEATURE_SPEC: $FEATURE_SPEC"
echo "IMPL_PLAN: $IMPL_PLAN"
echo "TASKS: $TASKS"
fi
exit 0
fi
# Validate required directories and files
if [[ ! -d "$FEATURE_DIR" ]]; then
echo "ERROR: Feature directory not found: $FEATURE_DIR" >&2
echo "Run /specify first to create the feature structure." >&2
exit 1
fi
if [[ ! -f "$IMPL_PLAN" ]]; then
echo "ERROR: plan.md not found in $FEATURE_DIR" >&2
echo "Run /plan first to create the implementation plan." >&2
exit 1
fi
# Check for tasks.md if required
if $REQUIRE_TASKS && [[ ! -f "$TASKS" ]]; then
echo "ERROR: tasks.md not found in $FEATURE_DIR" >&2
echo "Run /tasks first to create the task list." >&2
exit 1
fi
# Build list of available documents
docs=()
# Always check these optional docs
[[ -f "$RESEARCH" ]] && docs+=("research.md")
[[ -f "$DATA_MODEL" ]] && docs+=("data-model.md")
# Check contracts directory (only if it exists and has files)
if [[ -d "$CONTRACTS_DIR" ]] && [[ -n "$(ls -A "$CONTRACTS_DIR" 2>/dev/null)" ]]; then
docs+=("contracts/")
fi
[[ -f "$QUICKSTART" ]] && docs+=("quickstart.md")
# Include tasks.md if requested and it exists
if $INCLUDE_TASKS && [[ -f "$TASKS" ]]; then
docs+=("tasks.md")
fi
# Output results
if $JSON_MODE; then
# Build JSON array of documents
if [[ ${#docs[@]} -eq 0 ]]; then
json_docs="[]"
else
json_docs=$(printf '"%s",' "${docs[@]}")
json_docs="[${json_docs%,}]"
fi
printf '{"FEATURE_DIR":"%s","AVAILABLE_DOCS":%s}\n' "$FEATURE_DIR" "$json_docs"
else
# Text output
echo "FEATURE_DIR:$FEATURE_DIR"
echo "AVAILABLE_DOCS:"
# Show status of each potential document
check_file "$RESEARCH" "research.md"
check_file "$DATA_MODEL" "data-model.md"
check_dir "$CONTRACTS_DIR" "contracts/"
check_file "$QUICKSTART" "quickstart.md"
if $INCLUDE_TASKS; then
check_file "$TASKS" "tasks.md"
fi
fi
+113
View File
@@ -0,0 +1,113 @@
#!/usr/bin/env bash
# Common functions and variables for all scripts
# Get repository root, with fallback for non-git repositories
get_repo_root() {
if git rev-parse --show-toplevel >/dev/null 2>&1; then
git rev-parse --show-toplevel
else
# Fall back to script location for non-git repos
local script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
(cd "$script_dir/../../.." && pwd)
fi
}
# Get current branch, with fallback for non-git repositories
get_current_branch() {
# First check if SPECIFY_FEATURE environment variable is set
if [[ -n "${SPECIFY_FEATURE:-}" ]]; then
echo "$SPECIFY_FEATURE"
return
fi
# Then check git if available
if git rev-parse --abbrev-ref HEAD >/dev/null 2>&1; then
git rev-parse --abbrev-ref HEAD
return
fi
# For non-git repos, try to find the latest feature directory
local repo_root=$(get_repo_root)
local specs_dir="$repo_root/specs"
if [[ -d "$specs_dir" ]]; then
local latest_feature=""
local highest=0
for dir in "$specs_dir"/*; do
if [[ -d "$dir" ]]; then
local dirname=$(basename "$dir")
if [[ "$dirname" =~ ^([0-9]{3})- ]]; then
local number=${BASH_REMATCH[1]}
number=$((10#$number))
if [[ "$number" -gt "$highest" ]]; then
highest=$number
latest_feature=$dirname
fi
fi
fi
done
if [[ -n "$latest_feature" ]]; then
echo "$latest_feature"
return
fi
fi
echo "main" # Final fallback
}
# Check if we have git available
has_git() {
git rev-parse --show-toplevel >/dev/null 2>&1
}
check_feature_branch() {
local branch="$1"
local has_git_repo="$2"
# For non-git repos, we can't enforce branch naming but still provide output
if [[ "$has_git_repo" != "true" ]]; then
echo "[specify] Warning: Git repository not detected; skipped branch validation" >&2
return 0
fi
if [[ ! "$branch" =~ ^[0-9]{3}- ]]; then
echo "ERROR: Not on a feature branch. Current branch: $branch" >&2
echo "Feature branches should be named like: 001-feature-name" >&2
return 1
fi
return 0
}
get_feature_dir() { echo "$1/specs/$2"; }
get_feature_paths() {
local repo_root=$(get_repo_root)
local current_branch=$(get_current_branch)
local has_git_repo="false"
if has_git; then
has_git_repo="true"
fi
local feature_dir=$(get_feature_dir "$repo_root" "$current_branch")
cat <<EOF
REPO_ROOT='$repo_root'
CURRENT_BRANCH='$current_branch'
HAS_GIT='$has_git_repo'
FEATURE_DIR='$feature_dir'
FEATURE_SPEC='$feature_dir/spec.md'
IMPL_PLAN='$feature_dir/plan.md'
TASKS='$feature_dir/tasks.md'
RESEARCH='$feature_dir/research.md'
DATA_MODEL='$feature_dir/data-model.md'
QUICKSTART='$feature_dir/quickstart.md'
CONTRACTS_DIR='$feature_dir/contracts'
EOF
}
check_file() { [[ -f "$1" ]] && echo " ✓ $2" || echo " ✗ $2"; }
check_dir() { [[ -d "$1" && -n $(ls -A "$1" 2>/dev/null) ]] && echo " ✓ $2" || echo " ✗ $2"; }
+97
View File
@@ -0,0 +1,97 @@
#!/usr/bin/env bash
set -e
JSON_MODE=false
ARGS=()
for arg in "$@"; do
case "$arg" in
--json) JSON_MODE=true ;;
--help|-h) echo "Usage: $0 [--json] <feature_description>"; exit 0 ;;
*) ARGS+=("$arg") ;;
esac
done
FEATURE_DESCRIPTION="${ARGS[*]}"
if [ -z "$FEATURE_DESCRIPTION" ]; then
echo "Usage: $0 [--json] <feature_description>" >&2
exit 1
fi
# Function to find the repository root by searching for existing project markers
find_repo_root() {
local dir="$1"
while [ "$dir" != "/" ]; do
if [ -d "$dir/.git" ] || [ -d "$dir/.specify" ]; then
echo "$dir"
return 0
fi
dir="$(dirname "$dir")"
done
return 1
}
# Resolve repository root. Prefer git information when available, but fall back
# to searching for repository markers so the workflow still functions in repositories that
# were initialised with --no-git.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if git rev-parse --show-toplevel >/dev/null 2>&1; then
REPO_ROOT=$(git rev-parse --show-toplevel)
HAS_GIT=true
else
REPO_ROOT="$(find_repo_root "$SCRIPT_DIR")"
if [ -z "$REPO_ROOT" ]; then
echo "Error: Could not determine repository root. Please run this script from within the repository." >&2
exit 1
fi
HAS_GIT=false
fi
cd "$REPO_ROOT"
SPECS_DIR="$REPO_ROOT/specs"
mkdir -p "$SPECS_DIR"
HIGHEST=0
if [ -d "$SPECS_DIR" ]; then
for dir in "$SPECS_DIR"/*; do
[ -d "$dir" ] || continue
dirname=$(basename "$dir")
number=$(echo "$dirname" | grep -o '^[0-9]\+' || echo "0")
number=$((10#$number))
if [ "$number" -gt "$HIGHEST" ]; then HIGHEST=$number; fi
done
fi
NEXT=$((HIGHEST + 1))
FEATURE_NUM=$(printf "%03d" "$NEXT")
BRANCH_NAME=$(echo "$FEATURE_DESCRIPTION" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/-\+/-/g' | sed 's/^-//' | sed 's/-$//')
WORDS=$(echo "$BRANCH_NAME" | tr '-' '\n' | grep -v '^$' | head -3 | tr '\n' '-' | sed 's/-$//')
BRANCH_NAME="${FEATURE_NUM}-${WORDS}"
if [ "$HAS_GIT" = true ]; then
git checkout -b "$BRANCH_NAME"
else
>&2 echo "[specify] Warning: Git repository not detected; skipped branch creation for $BRANCH_NAME"
fi
FEATURE_DIR="$SPECS_DIR/$BRANCH_NAME"
mkdir -p "$FEATURE_DIR"
TEMPLATE="$REPO_ROOT/.specify/templates/spec-template.md"
SPEC_FILE="$FEATURE_DIR/spec.md"
if [ -f "$TEMPLATE" ]; then cp "$TEMPLATE" "$SPEC_FILE"; else touch "$SPEC_FILE"; fi
# Set the SPECIFY_FEATURE environment variable for the current session
export SPECIFY_FEATURE="$BRANCH_NAME"
if $JSON_MODE; then
printf '{"BRANCH_NAME":"%s","SPEC_FILE":"%s","FEATURE_NUM":"%s"}\n' "$BRANCH_NAME" "$SPEC_FILE" "$FEATURE_NUM"
else
echo "BRANCH_NAME: $BRANCH_NAME"
echo "SPEC_FILE: $SPEC_FILE"
echo "FEATURE_NUM: $FEATURE_NUM"
echo "SPECIFY_FEATURE environment variable set to: $BRANCH_NAME"
fi
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env bash
set -e
# Parse command line arguments
JSON_MODE=false
ARGS=()
for arg in "$@"; do
case "$arg" in
--json)
JSON_MODE=true
;;
--help|-h)
echo "Usage: $0 [--json]"
echo " --json Output results in JSON format"
echo " --help Show this help message"
exit 0
;;
*)
ARGS+=("$arg")
;;
esac
done
# Get script directory and load common functions
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"
# Get all paths and variables from common functions
eval $(get_feature_paths)
# Check if we're on a proper feature branch (only for git repos)
check_feature_branch "$CURRENT_BRANCH" "$HAS_GIT" || exit 1
# Ensure the feature directory exists
mkdir -p "$FEATURE_DIR"
# Copy plan template if it exists
TEMPLATE="$REPO_ROOT/.specify/templates/plan-template.md"
if [[ -f "$TEMPLATE" ]]; then
cp "$TEMPLATE" "$IMPL_PLAN"
echo "Copied plan template to $IMPL_PLAN"
else
echo "Warning: Plan template not found at $TEMPLATE"
# Create a basic plan file if template doesn't exist
touch "$IMPL_PLAN"
fi
# Output results
if $JSON_MODE; then
printf '{"FEATURE_SPEC":"%s","IMPL_PLAN":"%s","SPECS_DIR":"%s","BRANCH":"%s","HAS_GIT":"%s"}\n' \
"$FEATURE_SPEC" "$IMPL_PLAN" "$FEATURE_DIR" "$CURRENT_BRANCH" "$HAS_GIT"
else
echo "FEATURE_SPEC: $FEATURE_SPEC"
echo "IMPL_PLAN: $IMPL_PLAN"
echo "SPECS_DIR: $FEATURE_DIR"
echo "BRANCH: $CURRENT_BRANCH"
echo "HAS_GIT: $HAS_GIT"
fi
+719
View File
@@ -0,0 +1,719 @@
#!/usr/bin/env bash
# Update agent context files with information from plan.md
#
# This script maintains AI agent context files by parsing feature specifications
# and updating agent-specific configuration files with project information.
#
# MAIN FUNCTIONS:
# 1. Environment Validation
# - Verifies git repository structure and branch information
# - Checks for required plan.md files and templates
# - Validates file permissions and accessibility
#
# 2. Plan Data Extraction
# - Parses plan.md files to extract project metadata
# - Identifies language/version, frameworks, databases, and project types
# - Handles missing or incomplete specification data gracefully
#
# 3. Agent File Management
# - Creates new agent context files from templates when needed
# - Updates existing agent files with new project information
# - Preserves manual additions and custom configurations
# - Supports multiple AI agent formats and directory structures
#
# 4. Content Generation
# - Generates language-specific build/test commands
# - Creates appropriate project directory structures
# - Updates technology stacks and recent changes sections
# - Maintains consistent formatting and timestamps
#
# 5. Multi-Agent Support
# - Handles agent-specific file paths and naming conventions
# - Supports: Claude, Gemini, Copilot, Cursor, Qwen, opencode, Codex, Windsurf
# - Can update single agents or all existing agent files
# - Creates default Claude file if no agent files exist
#
# Usage: ./update-agent-context.sh [agent_type]
# Agent types: claude|gemini|copilot|cursor|qwen|opencode|codex|windsurf
# Leave empty to update all existing agent files
set -e
# Enable strict error handling
set -u
set -o pipefail
#==============================================================================
# Configuration and Global Variables
#==============================================================================
# Get script directory and load common functions
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"
# Get all paths and variables from common functions
eval $(get_feature_paths)
NEW_PLAN="$IMPL_PLAN" # Alias for compatibility with existing code
AGENT_TYPE="${1:-}"
# Agent-specific file paths
CLAUDE_FILE="$REPO_ROOT/CLAUDE.md"
GEMINI_FILE="$REPO_ROOT/GEMINI.md"
COPILOT_FILE="$REPO_ROOT/.github/copilot-instructions.md"
CURSOR_FILE="$REPO_ROOT/.cursor/rules/specify-rules.mdc"
QWEN_FILE="$REPO_ROOT/QWEN.md"
AGENTS_FILE="$REPO_ROOT/AGENTS.md"
WINDSURF_FILE="$REPO_ROOT/.windsurf/rules/specify-rules.md"
KILOCODE_FILE="$REPO_ROOT/.kilocode/rules/specify-rules.md"
AUGGIE_FILE="$REPO_ROOT/.augment/rules/specify-rules.md"
ROO_FILE="$REPO_ROOT/.roo/rules/specify-rules.md"
# Template file
TEMPLATE_FILE="$REPO_ROOT/.specify/templates/agent-file-template.md"
# Global variables for parsed plan data
NEW_LANG=""
NEW_FRAMEWORK=""
NEW_DB=""
NEW_PROJECT_TYPE=""
#==============================================================================
# Utility Functions
#==============================================================================
log_info() {
echo "INFO: $1"
}
log_success() {
echo "✓ $1"
}
log_error() {
echo "ERROR: $1" >&2
}
log_warning() {
echo "WARNING: $1" >&2
}
# Cleanup function for temporary files
cleanup() {
local exit_code=$?
rm -f /tmp/agent_update_*_$$
rm -f /tmp/manual_additions_$$
exit $exit_code
}
# Set up cleanup trap
trap cleanup EXIT INT TERM
#==============================================================================
# Validation Functions
#==============================================================================
validate_environment() {
# Check if we have a current branch/feature (git or non-git)
if [[ -z "$CURRENT_BRANCH" ]]; then
log_error "Unable to determine current feature"
if [[ "$HAS_GIT" == "true" ]]; then
log_info "Make sure you're on a feature branch"
else
log_info "Set SPECIFY_FEATURE environment variable or create a feature first"
fi
exit 1
fi
# Check if plan.md exists
if [[ ! -f "$NEW_PLAN" ]]; then
log_error "No plan.md found at $NEW_PLAN"
log_info "Make sure you're working on a feature with a corresponding spec directory"
if [[ "$HAS_GIT" != "true" ]]; then
log_info "Use: export SPECIFY_FEATURE=your-feature-name or create a new feature first"
fi
exit 1
fi
# Check if template exists (needed for new files)
if [[ ! -f "$TEMPLATE_FILE" ]]; then
log_warning "Template file not found at $TEMPLATE_FILE"
log_warning "Creating new agent files will fail"
fi
}
#==============================================================================
# Plan Parsing Functions
#==============================================================================
extract_plan_field() {
local field_pattern="$1"
local plan_file="$2"
grep "^\*\*${field_pattern}\*\*: " "$plan_file" 2>/dev/null | \
head -1 | \
sed "s|^\*\*${field_pattern}\*\*: ||" | \
sed 's/^[ \t]*//;s/[ \t]*$//' | \
grep -v "NEEDS CLARIFICATION" | \
grep -v "^N/A$" || echo ""
}
parse_plan_data() {
local plan_file="$1"
if [[ ! -f "$plan_file" ]]; then
log_error "Plan file not found: $plan_file"
return 1
fi
if [[ ! -r "$plan_file" ]]; then
log_error "Plan file is not readable: $plan_file"
return 1
fi
log_info "Parsing plan data from $plan_file"
NEW_LANG=$(extract_plan_field "Language/Version" "$plan_file")
NEW_FRAMEWORK=$(extract_plan_field "Primary Dependencies" "$plan_file")
NEW_DB=$(extract_plan_field "Storage" "$plan_file")
NEW_PROJECT_TYPE=$(extract_plan_field "Project Type" "$plan_file")
# Log what we found
if [[ -n "$NEW_LANG" ]]; then
log_info "Found language: $NEW_LANG"
else
log_warning "No language information found in plan"
fi
if [[ -n "$NEW_FRAMEWORK" ]]; then
log_info "Found framework: $NEW_FRAMEWORK"
fi
if [[ -n "$NEW_DB" ]] && [[ "$NEW_DB" != "N/A" ]]; then
log_info "Found database: $NEW_DB"
fi
if [[ -n "$NEW_PROJECT_TYPE" ]]; then
log_info "Found project type: $NEW_PROJECT_TYPE"
fi
}
format_technology_stack() {
local lang="$1"
local framework="$2"
local parts=()
# Add non-empty parts
[[ -n "$lang" && "$lang" != "NEEDS CLARIFICATION" ]] && parts+=("$lang")
[[ -n "$framework" && "$framework" != "NEEDS CLARIFICATION" && "$framework" != "N/A" ]] && parts+=("$framework")
# Join with proper formatting
if [[ ${#parts[@]} -eq 0 ]]; then
echo ""
elif [[ ${#parts[@]} -eq 1 ]]; then
echo "${parts[0]}"
else
# Join multiple parts with " + "
local result="${parts[0]}"
for ((i=1; i<${#parts[@]}; i++)); do
result="$result + ${parts[i]}"
done
echo "$result"
fi
}
#==============================================================================
# Template and Content Generation Functions
#==============================================================================
get_project_structure() {
local project_type="$1"
if [[ "$project_type" == *"web"* ]]; then
echo "backend/\\nfrontend/\\ntests/"
else
echo "src/\\ntests/"
fi
}
get_commands_for_language() {
local lang="$1"
case "$lang" in
*"Python"*)
echo "cd src && pytest && ruff check ."
;;
*"Rust"*)
echo "cargo test && cargo clippy"
;;
*"JavaScript"*|*"TypeScript"*)
echo "npm test && npm run lint"
;;
*)
echo "# Add commands for $lang"
;;
esac
}
get_language_conventions() {
local lang="$1"
echo "$lang: Follow standard conventions"
}
create_new_agent_file() {
local target_file="$1"
local temp_file="$2"
local project_name="$3"
local current_date="$4"
if [[ ! -f "$TEMPLATE_FILE" ]]; then
log_error "Template not found at $TEMPLATE_FILE"
return 1
fi
if [[ ! -r "$TEMPLATE_FILE" ]]; then
log_error "Template file is not readable: $TEMPLATE_FILE"
return 1
fi
log_info "Creating new agent context file from template..."
if ! cp "$TEMPLATE_FILE" "$temp_file"; then
log_error "Failed to copy template file"
return 1
fi
# Replace template placeholders
local project_structure
project_structure=$(get_project_structure "$NEW_PROJECT_TYPE")
local commands
commands=$(get_commands_for_language "$NEW_LANG")
local language_conventions
language_conventions=$(get_language_conventions "$NEW_LANG")
# Perform substitutions with error checking using safer approach
# Escape special characters for sed by using a different delimiter or escaping
local escaped_lang=$(printf '%s\n' "$NEW_LANG" | sed 's/[\[\.*^$()+{}|]/\\&/g')
local escaped_framework=$(printf '%s\n' "$NEW_FRAMEWORK" | sed 's/[\[\.*^$()+{}|]/\\&/g')
local escaped_branch=$(printf '%s\n' "$CURRENT_BRANCH" | sed 's/[\[\.*^$()+{}|]/\\&/g')
# Build technology stack and recent change strings conditionally
local tech_stack
if [[ -n "$escaped_lang" && -n "$escaped_framework" ]]; then
tech_stack="- $escaped_lang + $escaped_framework ($escaped_branch)"
elif [[ -n "$escaped_lang" ]]; then
tech_stack="- $escaped_lang ($escaped_branch)"
elif [[ -n "$escaped_framework" ]]; then
tech_stack="- $escaped_framework ($escaped_branch)"
else
tech_stack="- ($escaped_branch)"
fi
local recent_change
if [[ -n "$escaped_lang" && -n "$escaped_framework" ]]; then
recent_change="- $escaped_branch: Added $escaped_lang + $escaped_framework"
elif [[ -n "$escaped_lang" ]]; then
recent_change="- $escaped_branch: Added $escaped_lang"
elif [[ -n "$escaped_framework" ]]; then
recent_change="- $escaped_branch: Added $escaped_framework"
else
recent_change="- $escaped_branch: Added"
fi
local substitutions=(
"s|\[PROJECT NAME\]|$project_name|"
"s|\[DATE\]|$current_date|"
"s|\[EXTRACTED FROM ALL PLAN.MD FILES\]|$tech_stack|"
"s|\[ACTUAL STRUCTURE FROM PLANS\]|$project_structure|g"
"s|\[ONLY COMMANDS FOR ACTIVE TECHNOLOGIES\]|$commands|"
"s|\[LANGUAGE-SPECIFIC, ONLY FOR LANGUAGES IN USE\]|$language_conventions|"
"s|\[LAST 3 FEATURES AND WHAT THEY ADDED\]|$recent_change|"
)
for substitution in "${substitutions[@]}"; do
if ! sed -i.bak -e "$substitution" "$temp_file"; then
log_error "Failed to perform substitution: $substitution"
rm -f "$temp_file" "$temp_file.bak"
return 1
fi
done
# Convert \n sequences to actual newlines
newline=$(printf '\n')
sed -i.bak2 "s/\\\\n/${newline}/g" "$temp_file"
# Clean up backup files
rm -f "$temp_file.bak" "$temp_file.bak2"
return 0
}
update_existing_agent_file() {
local target_file="$1"
local current_date="$2"
log_info "Updating existing agent context file..."
# Use a single temporary file for atomic update
local temp_file
temp_file=$(mktemp) || {
log_error "Failed to create temporary file"
return 1
}
# Process the file in one pass
local tech_stack=$(format_technology_stack "$NEW_LANG" "$NEW_FRAMEWORK")
local new_tech_entries=()
local new_change_entry=""
# Prepare new technology entries
if [[ -n "$tech_stack" ]] && ! grep -q "$tech_stack" "$target_file"; then
new_tech_entries+=("- $tech_stack ($CURRENT_BRANCH)")
fi
if [[ -n "$NEW_DB" ]] && [[ "$NEW_DB" != "N/A" ]] && [[ "$NEW_DB" != "NEEDS CLARIFICATION" ]] && ! grep -q "$NEW_DB" "$target_file"; then
new_tech_entries+=("- $NEW_DB ($CURRENT_BRANCH)")
fi
# Prepare new change entry
if [[ -n "$tech_stack" ]]; then
new_change_entry="- $CURRENT_BRANCH: Added $tech_stack"
elif [[ -n "$NEW_DB" ]] && [[ "$NEW_DB" != "N/A" ]] && [[ "$NEW_DB" != "NEEDS CLARIFICATION" ]]; then
new_change_entry="- $CURRENT_BRANCH: Added $NEW_DB"
fi
# Process file line by line
local in_tech_section=false
local in_changes_section=false
local tech_entries_added=false
local changes_entries_added=false
local existing_changes_count=0
while IFS= read -r line || [[ -n "$line" ]]; do
# Handle Active Technologies section
if [[ "$line" == "## Active Technologies" ]]; then
echo "$line" >> "$temp_file"
in_tech_section=true
continue
elif [[ $in_tech_section == true ]] && [[ "$line" =~ ^##[[:space:]] ]]; then
# Add new tech entries before closing the section
if [[ $tech_entries_added == false ]] && [[ ${#new_tech_entries[@]} -gt 0 ]]; then
printf '%s\n' "${new_tech_entries[@]}" >> "$temp_file"
tech_entries_added=true
fi
echo "$line" >> "$temp_file"
in_tech_section=false
continue
elif [[ $in_tech_section == true ]] && [[ -z "$line" ]]; then
# Add new tech entries before empty line in tech section
if [[ $tech_entries_added == false ]] && [[ ${#new_tech_entries[@]} -gt 0 ]]; then
printf '%s\n' "${new_tech_entries[@]}" >> "$temp_file"
tech_entries_added=true
fi
echo "$line" >> "$temp_file"
continue
fi
# Handle Recent Changes section
if [[ "$line" == "## Recent Changes" ]]; then
echo "$line" >> "$temp_file"
# Add new change entry right after the heading
if [[ -n "$new_change_entry" ]]; then
echo "$new_change_entry" >> "$temp_file"
fi
in_changes_section=true
changes_entries_added=true
continue
elif [[ $in_changes_section == true ]] && [[ "$line" =~ ^##[[:space:]] ]]; then
echo "$line" >> "$temp_file"
in_changes_section=false
continue
elif [[ $in_changes_section == true ]] && [[ "$line" == "- "* ]]; then
# Keep only first 2 existing changes
if [[ $existing_changes_count -lt 2 ]]; then
echo "$line" >> "$temp_file"
((existing_changes_count++))
fi
continue
fi
# Update timestamp
if [[ "$line" =~ \*\*Last\ updated\*\*:.*[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] ]]; then
echo "$line" | sed "s/[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]/$current_date/" >> "$temp_file"
else
echo "$line" >> "$temp_file"
fi
done < "$target_file"
# Post-loop check: if we're still in the Active Technologies section and haven't added new entries
if [[ $in_tech_section == true ]] && [[ $tech_entries_added == false ]] && [[ ${#new_tech_entries[@]} -gt 0 ]]; then
printf '%s\n' "${new_tech_entries[@]}" >> "$temp_file"
fi
# Move temp file to target atomically
if ! mv "$temp_file" "$target_file"; then
log_error "Failed to update target file"
rm -f "$temp_file"
return 1
fi
return 0
}
#==============================================================================
# Main Agent File Update Function
#==============================================================================
update_agent_file() {
local target_file="$1"
local agent_name="$2"
if [[ -z "$target_file" ]] || [[ -z "$agent_name" ]]; then
log_error "update_agent_file requires target_file and agent_name parameters"
return 1
fi
log_info "Updating $agent_name context file: $target_file"
local project_name
project_name=$(basename "$REPO_ROOT")
local current_date
current_date=$(date +%Y-%m-%d)
# Create directory if it doesn't exist
local target_dir
target_dir=$(dirname "$target_file")
if [[ ! -d "$target_dir" ]]; then
if ! mkdir -p "$target_dir"; then
log_error "Failed to create directory: $target_dir"
return 1
fi
fi
if [[ ! -f "$target_file" ]]; then
# Create new file from template
local temp_file
temp_file=$(mktemp) || {
log_error "Failed to create temporary file"
return 1
}
if create_new_agent_file "$target_file" "$temp_file" "$project_name" "$current_date"; then
if mv "$temp_file" "$target_file"; then
log_success "Created new $agent_name context file"
else
log_error "Failed to move temporary file to $target_file"
rm -f "$temp_file"
return 1
fi
else
log_error "Failed to create new agent file"
rm -f "$temp_file"
return 1
fi
else
# Update existing file
if [[ ! -r "$target_file" ]]; then
log_error "Cannot read existing file: $target_file"
return 1
fi
if [[ ! -w "$target_file" ]]; then
log_error "Cannot write to existing file: $target_file"
return 1
fi
if update_existing_agent_file "$target_file" "$current_date"; then
log_success "Updated existing $agent_name context file"
else
log_error "Failed to update existing agent file"
return 1
fi
fi
return 0
}
#==============================================================================
# Agent Selection and Processing
#==============================================================================
update_specific_agent() {
local agent_type="$1"
case "$agent_type" in
claude)
update_agent_file "$CLAUDE_FILE" "Claude Code"
;;
gemini)
update_agent_file "$GEMINI_FILE" "Gemini CLI"
;;
copilot)
update_agent_file "$COPILOT_FILE" "GitHub Copilot"
;;
cursor)
update_agent_file "$CURSOR_FILE" "Cursor IDE"
;;
qwen)
update_agent_file "$QWEN_FILE" "Qwen Code"
;;
opencode)
update_agent_file "$AGENTS_FILE" "opencode"
;;
codex)
update_agent_file "$AGENTS_FILE" "Codex CLI"
;;
windsurf)
update_agent_file "$WINDSURF_FILE" "Windsurf"
;;
kilocode)
update_agent_file "$KILOCODE_FILE" "Kilo Code"
;;
auggie)
update_agent_file "$AUGGIE_FILE" "Auggie CLI"
;;
roo)
update_agent_file "$ROO_FILE" "Roo Code"
;;
*)
log_error "Unknown agent type '$agent_type'"
log_error "Expected: claude|gemini|copilot|cursor|qwen|opencode|codex|windsurf|kilocode|auggie|roo"
exit 1
;;
esac
}
update_all_existing_agents() {
local found_agent=false
# Check each possible agent file and update if it exists
if [[ -f "$CLAUDE_FILE" ]]; then
update_agent_file "$CLAUDE_FILE" "Claude Code"
found_agent=true
fi
if [[ -f "$GEMINI_FILE" ]]; then
update_agent_file "$GEMINI_FILE" "Gemini CLI"
found_agent=true
fi
if [[ -f "$COPILOT_FILE" ]]; then
update_agent_file "$COPILOT_FILE" "GitHub Copilot"
found_agent=true
fi
if [[ -f "$CURSOR_FILE" ]]; then
update_agent_file "$CURSOR_FILE" "Cursor IDE"
found_agent=true
fi
if [[ -f "$QWEN_FILE" ]]; then
update_agent_file "$QWEN_FILE" "Qwen Code"
found_agent=true
fi
if [[ -f "$AGENTS_FILE" ]]; then
update_agent_file "$AGENTS_FILE" "Codex/opencode"
found_agent=true
fi
if [[ -f "$WINDSURF_FILE" ]]; then
update_agent_file "$WINDSURF_FILE" "Windsurf"
found_agent=true
fi
if [[ -f "$KILOCODE_FILE" ]]; then
update_agent_file "$KILOCODE_FILE" "Kilo Code"
found_agent=true
fi
if [[ -f "$AUGGIE_FILE" ]]; then
update_agent_file "$AUGGIE_FILE" "Auggie CLI"
found_agent=true
fi
if [[ -f "$ROO_FILE" ]]; then
update_agent_file "$ROO_FILE" "Roo Code"
found_agent=true
fi
# If no agent files exist, create a default Claude file
if [[ "$found_agent" == false ]]; then
log_info "No existing agent files found, creating default Claude file..."
update_agent_file "$CLAUDE_FILE" "Claude Code"
fi
}
print_summary() {
echo
log_info "Summary of changes:"
if [[ -n "$NEW_LANG" ]]; then
echo " - Added language: $NEW_LANG"
fi
if [[ -n "$NEW_FRAMEWORK" ]]; then
echo " - Added framework: $NEW_FRAMEWORK"
fi
if [[ -n "$NEW_DB" ]] && [[ "$NEW_DB" != "N/A" ]]; then
echo " - Added database: $NEW_DB"
fi
echo
log_info "Usage: $0 [claude|gemini|copilot|cursor|qwen|opencode|codex|windsurf|kilocode|auggie|roo]"
}
#==============================================================================
# Main Execution
#==============================================================================
main() {
# Validate environment before proceeding
validate_environment
log_info "=== Updating agent context files for feature $CURRENT_BRANCH ==="
# Parse the plan file to extract project information
if ! parse_plan_data "$NEW_PLAN"; then
log_error "Failed to parse plan data"
exit 1
fi
# Process based on agent type argument
local success=true
if [[ -z "$AGENT_TYPE" ]]; then
# No specific agent provided - update all existing agent files
log_info "No agent specified, updating all existing agent files..."
if ! update_all_existing_agents; then
success=false
fi
else
# Specific agent provided - update only that agent
log_info "Updating specific agent: $AGENT_TYPE"
if ! update_specific_agent "$AGENT_TYPE"; then
success=false
fi
fi
# Print summary
print_summary
if [[ "$success" == true ]]; then
log_success "Agent context update completed successfully"
exit 0
else
log_error "Agent context update completed with errors"
exit 1
fi
}
# Execute main function if script is run directly
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@"
fi
+23
View File
@@ -0,0 +1,23 @@
# [PROJECT NAME] Development Guidelines
Auto-generated from all feature plans. Last updated: [DATE]
## Active Technologies
[EXTRACTED FROM ALL PLAN.MD FILES]
## Project Structure
```
[ACTUAL STRUCTURE FROM PLANS]
```
## Commands
[ONLY COMMANDS FOR ACTIVE TECHNOLOGIES]
## Code Style
[LANGUAGE-SPECIFIC, ONLY FOR LANGUAGES IN USE]
## Recent Changes
[LAST 3 FEATURES AND WHAT THEY ADDED]
<!-- MANUAL ADDITIONS START -->
<!-- MANUAL ADDITIONS END -->
+219
View File
@@ -0,0 +1,219 @@
# Implementation Plan: [FEATURE]
**Branch**: `[###-feature-name]` | **Date**: [DATE] | **Spec**: [link]
**Input**: Feature specification from `/specs/[###-feature-name]/spec.md`
## Execution Flow (/plan command scope)
```
1. Load feature spec from Input path
→ If not found: ERROR "No feature spec at {path}"
2. Fill Technical Context (scan for NEEDS CLARIFICATION)
→ Detect Project Type from file system structure or context (web=frontend+backend, mobile=app+api)
→ Set Structure Decision based on project type
3. Fill the Constitution Check section based on the content of the constitution document.
4. Evaluate Constitution Check section below
→ If violations exist: Document in Complexity Tracking
→ If no justification possible: ERROR "Simplify approach first"
→ Update Progress Tracking: Initial Constitution Check
5. Execute Phase 0 → research.md
→ If NEEDS CLARIFICATION remain: ERROR "Resolve unknowns"
6. Execute Phase 1 → contracts, data-model.md, quickstart.md, agent-specific template file (e.g., `CLAUDE.md` for Claude Code, `.github/copilot-instructions.md` for GitHub Copilot, `GEMINI.md` for Gemini CLI, `QWEN.md` for Qwen Code or `AGENTS.md` for opencode).
7. Re-evaluate Constitution Check section
→ If new violations: Refactor design, return to Phase 1
→ Update Progress Tracking: Post-Design Constitution Check
8. Plan Phase 2 → Describe task generation approach (DO NOT create tasks.md)
9. STOP - Ready for /tasks command
```
**IMPORTANT**: The /plan command STOPS at step 7. Phases 2-4 are executed by other commands:
- Phase 2: /tasks command creates tasks.md
- Phase 3-4: Implementation execution (manual or via tools)
## Summary
[Extract from feature spec: primary requirement + technical approach from research]
## Technical Context
**Language/Version**: [e.g., Python 3.11, Swift 5.9, Rust 1.75 or NEEDS CLARIFICATION]
**Primary Dependencies**: [e.g., FastAPI, UIKit, LLVM or NEEDS CLARIFICATION]
**Storage**: [if applicable, e.g., PostgreSQL, CoreData, files or N/A]
**Testing**: [e.g., pytest, XCTest, cargo test or NEEDS CLARIFICATION]
**Target Platform**: [e.g., Linux server, iOS 15+, WASM or NEEDS CLARIFICATION]
**Project Type**: [single/web/mobile - determines source structure]
**Performance Goals**: [domain-specific, e.g., 1000 req/s, 10k lines/sec, 60 fps or NEEDS CLARIFICATION]
**Constraints**: [domain-specific, e.g., <200ms p95, <100MB memory, offline-capable or NEEDS CLARIFICATION]
**Scale/Scope**: [domain-specific, e.g., 10k users, 1M LOC, 50 screens or NEEDS CLARIFICATION]
## Constitution Check
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*
[Gates determined based on constitution file]
## Project Structure
### Documentation (this feature)
```
specs/[###-feature]/
├── plan.md # This file (/plan command output)
├── research.md # Phase 0 output (/plan command)
├── data-model.md # Phase 1 output (/plan command)
├── quickstart.md # Phase 1 output (/plan command)
├── contracts/ # Phase 1 output (/plan command)
└── tasks.md # Phase 2 output (/tasks command - NOT created by /plan)
```
### Source Code (repository root)
<!--
ACTION REQUIRED: Replace the placeholder tree below with the concrete layout
for this feature. Delete unused options and expand the chosen structure with
real paths (e.g., apps/admin, packages/something). The delivered plan must
not include Option labels.
-->
```
# [REMOVE IF UNUSED] Option 1: Single project (DEFAULT)
src/
├── models/
├── services/
├── cli/
└── lib/
tests/
├── contract/
├── integration/
└── unit/
# [REMOVE IF UNUSED] Option 2: Web application (when "frontend" + "backend" detected)
backend/
├── src/
│ ├── models/
│ ├── services/
│ └── api/
└── tests/
frontend/
├── src/
│ ├── components/
│ ├── pages/
│ └── services/
└── tests/
# [REMOVE IF UNUSED] Option 3: Mobile + API (when "iOS/Android" detected)
api/
└── [same as backend above]
ios/ or android/
└── [platform-specific structure: feature modules, UI flows, platform tests]
```
**Structure Decision**: [Document the selected structure and reference the real
directories captured above]
## Phase 0: Outline & Research
1. **Extract unknowns from Technical Context** above:
- For each NEEDS CLARIFICATION → research task
- For each dependency → best practices task
- For each integration → patterns task
2. **Generate and dispatch research agents**:
```
For each unknown in Technical Context:
Task: "Research {unknown} for {feature context}"
For each technology choice:
Task: "Find best practices for {tech} in {domain}"
```
3. **Consolidate findings** in `research.md` using format:
- Decision: [what was chosen]
- Rationale: [why chosen]
- Alternatives considered: [what else evaluated]
**Output**: research.md with all NEEDS CLARIFICATION resolved
## Phase 1: Design & Contracts
*Prerequisites: research.md complete*
1. **Extract entities from feature spec** → `data-model.md`:
- Entity name, fields, relationships
- Validation rules from requirements
- State transitions if applicable
2. **Generate API contracts** from functional requirements:
- For each user action → endpoint
- Use standard REST/GraphQL patterns
- Output OpenAPI/GraphQL schema to `/contracts/`
3. **Generate contract tests** from contracts:
- One test file per endpoint
- Assert request/response schemas
- Tests must fail (no implementation yet)
4. **Extract test scenarios** from user stories:
- Each story → integration test scenario
- Quickstart test = story validation steps
5. **Update agent file incrementally** (O(1) operation):
- Run `.specify/scripts/bash/update-agent-context.sh cursor`
**IMPORTANT**: Execute it exactly as specified above. Do not add or remove any arguments.
- If exists: Add only NEW tech from current plan
- Preserve manual additions between markers
- Update recent changes (keep last 3)
- Keep under 150 lines for token efficiency
- Output to repository root
**Output**: data-model.md, /contracts/*, failing tests, quickstart.md, agent-specific file
## Phase 2: Task Planning Approach
*This section describes what the /tasks command will do - DO NOT execute during /plan*
**Task Generation Strategy**:
- Load `.specify/templates/tasks-template.md` as base
- Generate tasks from Phase 1 design docs (contracts, data model, quickstart)
- Each contract → contract test task [P]
- Each entity → model creation task [P]
- Each user story → integration test task
- Implementation tasks to make tests pass
**Ordering Strategy**:
- TDD order: Tests before implementation
- Dependency order: Models before services before UI
- Mark [P] for parallel execution (independent files)
**Estimated Output**: 25-30 numbered, ordered tasks in tasks.md
**IMPORTANT**: This phase is executed by the /tasks command, NOT by /plan
## Phase 3+: Future Implementation
*These phases are beyond the scope of the /plan command*
**Phase 3**: Task execution (/tasks command creates tasks.md)
**Phase 4**: Implementation (execute tasks.md following constitutional principles)
**Phase 5**: Validation (run tests, execute quickstart.md, performance validation)
## Complexity Tracking
*Fill ONLY if Constitution Check has violations that must be justified*
| Violation | Why Needed | Simpler Alternative Rejected Because |
|-----------|------------|-------------------------------------|
| [e.g., 4th project] | [current need] | [why 3 projects insufficient] |
| [e.g., Repository pattern] | [specific problem] | [why direct DB access insufficient] |
## Progress Tracking
*This checklist is updated during execution flow*
**Phase Status**:
- [ ] Phase 0: Research complete (/plan command)
- [ ] Phase 1: Design complete (/plan command)
- [ ] Phase 2: Task planning complete (/plan command - describe approach only)
- [ ] Phase 3: Tasks generated (/tasks command)
- [ ] Phase 4: Implementation complete
- [ ] Phase 5: Validation passed
**Gate Status**:
- [ ] Initial Constitution Check: PASS
- [ ] Post-Design Constitution Check: PASS
- [ ] All NEEDS CLARIFICATION resolved
- [ ] Complexity deviations documented
---
*Based on Constitution v2.1.1 - See `/memory/constitution.md`*
+116
View File
@@ -0,0 +1,116 @@
# Feature Specification: [FEATURE NAME]
**Feature Branch**: `[###-feature-name]`
**Created**: [DATE]
**Status**: Draft
**Input**: User description: "$ARGUMENTS"
## Execution Flow (main)
```
1. Parse user description from Input
→ If empty: ERROR "No feature description provided"
2. Extract key concepts from description
→ Identify: actors, actions, data, constraints
3. For each unclear aspect:
→ Mark with [NEEDS CLARIFICATION: specific question]
4. Fill User Scenarios & Testing section
→ If no clear user flow: ERROR "Cannot determine user scenarios"
5. Generate Functional Requirements
→ Each requirement must be testable
→ Mark ambiguous requirements
6. Identify Key Entities (if data involved)
7. Run Review Checklist
→ If any [NEEDS CLARIFICATION]: WARN "Spec has uncertainties"
→ If implementation details found: ERROR "Remove tech details"
8. Return: SUCCESS (spec ready for planning)
```
---
## ⚡ Quick Guidelines
- ✅ Focus on WHAT users need and WHY
- ❌ Avoid HOW to implement (no tech stack, APIs, code structure)
- 👥 Written for business stakeholders, not developers
### Section Requirements
- **Mandatory sections**: Must be completed for every feature
- **Optional sections**: Include only when relevant to the feature
- When a section doesn't apply, remove it entirely (don't leave as "N/A")
### For AI Generation
When creating this spec from a user prompt:
1. **Mark all ambiguities**: Use [NEEDS CLARIFICATION: specific question] for any assumption you'd need to make
2. **Don't guess**: If the prompt doesn't specify something (e.g., "login system" without auth method), mark it
3. **Think like a tester**: Every vague requirement should fail the "testable and unambiguous" checklist item
4. **Common underspecified areas**:
- User types and permissions
- Data retention/deletion policies
- Performance targets and scale
- Error handling behaviors
- Integration requirements
- Security/compliance needs
---
## User Scenarios & Testing *(mandatory)*
### Primary User Story
[Describe the main user journey in plain language]
### Acceptance Scenarios
1. **Given** [initial state], **When** [action], **Then** [expected outcome]
2. **Given** [initial state], **When** [action], **Then** [expected outcome]
### Edge Cases
- What happens when [boundary condition]?
- How does system handle [error scenario]?
## Requirements *(mandatory)*
### Functional Requirements
- **FR-001**: System MUST [specific capability, e.g., "allow users to create accounts"]
- **FR-002**: System MUST [specific capability, e.g., "validate email addresses"]
- **FR-003**: Users MUST be able to [key interaction, e.g., "reset their password"]
- **FR-004**: System MUST [data requirement, e.g., "persist user preferences"]
- **FR-005**: System MUST [behavior, e.g., "log all security events"]
*Example of marking unclear requirements:*
- **FR-006**: System MUST authenticate users via [NEEDS CLARIFICATION: auth method not specified - email/password, SSO, OAuth?]
- **FR-007**: System MUST retain user data for [NEEDS CLARIFICATION: retention period not specified]
### Key Entities *(include if feature involves data)*
- **[Entity 1]**: [What it represents, key attributes without implementation]
- **[Entity 2]**: [What it represents, relationships to other entities]
---
## Review & Acceptance Checklist
*GATE: Automated checks run during main() execution*
### Content Quality
- [ ] No implementation details (languages, frameworks, APIs)
- [ ] Focused on user value and business needs
- [ ] Written for non-technical stakeholders
- [ ] All mandatory sections completed
### Requirement Completeness
- [ ] No [NEEDS CLARIFICATION] markers remain
- [ ] Requirements are testable and unambiguous
- [ ] Success criteria are measurable
- [ ] Scope is clearly bounded
- [ ] Dependencies and assumptions identified
---
## Execution Status
*Updated by main() during processing*
- [ ] User description parsed
- [ ] Key concepts extracted
- [ ] Ambiguities marked
- [ ] User scenarios defined
- [ ] Requirements generated
- [ ] Entities identified
- [ ] Review checklist passed
---
+127
View File
@@ -0,0 +1,127 @@
# Tasks: [FEATURE NAME]
**Input**: Design documents from `/specs/[###-feature-name]/`
**Prerequisites**: plan.md (required), research.md, data-model.md, contracts/
## Execution Flow (main)
```
1. Load plan.md from feature directory
→ If not found: ERROR "No implementation plan found"
→ Extract: tech stack, libraries, structure
2. Load optional design documents:
→ data-model.md: Extract entities → model tasks
→ contracts/: Each file → contract test task
→ research.md: Extract decisions → setup tasks
3. Generate tasks by category:
→ Setup: project init, dependencies, linting
→ Tests: contract tests, integration tests
→ Core: models, services, CLI commands
→ Integration: DB, middleware, logging
→ Polish: unit tests, performance, docs
4. Apply task rules:
→ Different files = mark [P] for parallel
→ Same file = sequential (no [P])
→ Tests before implementation (TDD)
5. Number tasks sequentially (T001, T002...)
6. Generate dependency graph
7. Create parallel execution examples
8. Validate task completeness:
→ All contracts have tests?
→ All entities have models?
→ All endpoints implemented?
9. Return: SUCCESS (tasks ready for execution)
```
## Format: `[ID] [P?] Description`
- **[P]**: Can run in parallel (different files, no dependencies)
- Include exact file paths in descriptions
## Path Conventions
- **Single project**: `src/`, `tests/` at repository root
- **Web app**: `backend/src/`, `frontend/src/`
- **Mobile**: `api/src/`, `ios/src/` or `android/src/`
- Paths shown below assume single project - adjust based on plan.md structure
## Phase 3.1: Setup
- [ ] T001 Create project structure per implementation plan
- [ ] T002 Initialize [language] project with [framework] dependencies
- [ ] T003 [P] Configure linting and formatting tools
## Phase 3.2: Tests First (TDD) ⚠️ MUST COMPLETE BEFORE 3.3
**CRITICAL: These tests MUST be written and MUST FAIL before ANY implementation**
- [ ] T004 [P] Contract test POST /api/users in tests/contract/test_users_post.py
- [ ] T005 [P] Contract test GET /api/users/{id} in tests/contract/test_users_get.py
- [ ] T006 [P] Integration test user registration in tests/integration/test_registration.py
- [ ] T007 [P] Integration test auth flow in tests/integration/test_auth.py
## Phase 3.3: Core Implementation (ONLY after tests are failing)
- [ ] T008 [P] User model in src/models/user.py
- [ ] T009 [P] UserService CRUD in src/services/user_service.py
- [ ] T010 [P] CLI --create-user in src/cli/user_commands.py
- [ ] T011 POST /api/users endpoint
- [ ] T012 GET /api/users/{id} endpoint
- [ ] T013 Input validation
- [ ] T014 Error handling and logging
## Phase 3.4: Integration
- [ ] T015 Connect UserService to DB
- [ ] T016 Auth middleware
- [ ] T017 Request/response logging
- [ ] T018 CORS and security headers
## Phase 3.5: Polish
- [ ] T019 [P] Unit tests for validation in tests/unit/test_validation.py
- [ ] T020 Performance tests (<200ms)
- [ ] T021 [P] Update docs/api.md
- [ ] T022 Remove duplication
- [ ] T023 Run manual-testing.md
## Dependencies
- Tests (T004-T007) before implementation (T008-T014)
- T008 blocks T009, T015
- T016 blocks T018
- Implementation before polish (T019-T023)
## Parallel Example
```
# Launch T004-T007 together:
Task: "Contract test POST /api/users in tests/contract/test_users_post.py"
Task: "Contract test GET /api/users/{id} in tests/contract/test_users_get.py"
Task: "Integration test registration in tests/integration/test_registration.py"
Task: "Integration test auth in tests/integration/test_auth.py"
```
## Notes
- [P] tasks = different files, no dependencies
- Verify tests fail before implementing
- Commit after each task
- Avoid: vague tasks, same file conflicts
## Task Generation Rules
*Applied during main() execution*
1. **From Contracts**:
- Each contract file → contract test task [P]
- Each endpoint → implementation task
2. **From Data Model**:
- Each entity → model creation task [P]
- Relationships → service layer tasks
3. **From User Stories**:
- Each story → integration test [P]
- Quickstart scenarios → validation tasks
4. **Ordering**:
- Setup → Tests → Models → Services → Endpoints → Polish
- Dependencies block parallel execution
## Validation Checklist
*GATE: Checked by main() before returning*
- [ ] All contracts have corresponding tests
- [ ] All entities have model tasks
- [ ] All tests come before implementation
- [ ] Parallel tasks truly independent
- [ ] Each task specifies exact file path
- [ ] No task modifies same file as another [P] task
+280
View File
@@ -0,0 +1,280 @@
# Karaoke Generator - Technical Architecture Overview
## Core Functionality
The Karaoke Generator is a comprehensive pipeline that transforms audio files (local files or YouTube URLs) into professional karaoke videos with synchronized lyrics. It handles the complete workflow from raw audio input to final deliverable files.
## Main Processing Pipeline
### 1. **Input Processing**
- **Input Sources**: Local audio files (FLAC, WAV, MP3) or YouTube URLs
- **Metadata**: Artist name and song title (can search YouTube if URL not provided)
- **File Handling**: Converts input media to WAV format for processing
### 2. **Parallel Processing Phase**
The tool runs two major operations concurrently:
#### **Audio Separation** (Compute-Intensive)
- **Models Used**: Multiple AI models for different separation tasks:
- `model_bs_roformer_ep_317_sdr_12.9755.ckpt` (clean instrumental)
- `htdemucs_6s.yaml` (6-stem separation)
- `mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt` (backing vocals)
- **Processing Options**:
- **Remote Processing**: When `AUDIO_SEPARATOR_API_URL` environment variable is set, uploads audio to remote API for GPU-accelerated separation
- **Local Processing**: Falls back to local separation using available hardware
- **Hardware Requirements**:
- **Remote**: Internet connection, minimal local resources
- **Local**: GPU acceleration preferred (uses Apple Silicon MPS, CUDA, or CPU fallback)
- Significant processing time (2-5 minutes remote, 12+ minutes local for a ~5-minute song)
- Large model files (requires dedicated model storage directory for local processing)
- **Output**: Multiple stems (vocals, instrumental, backing vocals, drums, bass, etc.)
#### **Lyrics Processing**
- **Lyrics Fetching**: Genius API integration for lyric retrieval
- **Transcription**: AudioShake API for timing synchronization
- **Correction**: AI-powered lyrics correction using reference sources
- **Processing Time**: ~5-6 minutes for transcription + correction
### 3. **Human Review Phase** (Interactive)
- **Web Interface**: React-based web UI launches in browser
- **Functionality**: Users review and correct automatically transcribed lyrics
- **Timing**: Allows fine-tuning of lyric timing and text accuracy
- **Critical Dependency**: Requires human interaction - cannot be fully automated
### 4. **Output Generation**
Creates multiple synchronized lyric formats:
- **LRC files** (timed lyrics for media players)
- **CDG files** (CD+Graphics karaoke format)
- **ASS/SSA files** (Advanced SubStation Alpha for video)
- **Plain text files** (reference versions)
- **Video files** with lyric overlays
### 5. **Video Production**
- **Title/End Screens**: Generated with custom branding and styling
- **Video Composition**: Combines title + karaoke content + end screen
- **Multiple Formats**:
- 4K lossless (PCM audio)
- 4K lossy (AAC audio)
- 720p compressed
- MKV with FLAC audio (YouTube optimized)
## External API Dependencies
### **Required APIs**
1. **AudioShake API**: Core dependency for lyrics transcription/timing
- Upload audio files (can be large - 280+ seconds in example)
- Wait for processing completion
- Retrieve timed transcription data
2. **Genius API**: Lyrics text retrieval
- Search by artist/title
- Fetch reference lyrics text
3. **YouTube Data API v3**: Video management
- Upload videos
- Set thumbnails
- Check for existing videos
### **Optional Integrations**
- **Audio Separator API**: Remote audio separation processing
- Offloads compute-intensive audio separation to remote GPU servers
- Activated by setting `AUDIO_SEPARATOR_API_URL` environment variable
- Supports multiple models in single upload for efficiency
- Graceful fallback to local processing if unavailable
- **Discord Webhooks**: Completion notifications
- **Email APIs**: Draft creation for delivery notifications
- **Rclone**: Cloud storage synchronization (Google Drive, Dropbox)
## User Interaction Points
### **Critical Interactive Elements**
1. **Instrumental Selection**:
- Terminal-based choice between separation models
- Presents numbered options (e.g., "Choose instrumental audio file: [1]/2")
- Requires user input to proceed
2. **Human Review Interface**:
- Launches React web application
- Browser-based editing of transcribed lyrics
- Users can modify text and timing
- Must submit reviewed data to continue processing
3. **Confirmation Prompts**:
- Feature confirmation before finalization
- Video quality check before proceeding
- Manual approval gates throughout process
## Computing Requirements
### **Hardware Needs**
- **GPU/Accelerated Processing**:
- NVIDIA CUDA (preferred)
- Apple Silicon MPS (Metal Performance Shaders)
- CPU fallback available but significantly slower
- **Storage**:
- Large model files (multiple GB)
- Temporary processing files during separation
- Final output files (videos can be several GB each)
- **Memory**: Significant RAM for audio processing (8GB+ recommended)
- **CPU**: Multi-core processing for parallel operations
### **Processing Time Estimates**
Based on a ~5-minute song:
- Audio separation: ~15 minutes (GPU) / 45+ minutes (CPU)
- Lyrics transcription: ~5 minutes (API dependent)
- Human review: ~5-15 minutes (user-dependent)
- Video encoding: ~7 minutes
- Upload/organization: ~5 minutes
- **Total**: 32-47 minutes per track
### **External Dependencies**
- **FFmpeg**: Video/audio processing and encoding
- **Python 3.10+**: Runtime environment
- **PyTorch**: AI model execution framework
- **Audio Processing Libraries**: librosa, soundfile, pydub
- **Web Framework**: For human review interface
- **Rclone**: Cloud storage synchronization (optional)
## File Input/Output Structure
### **Input Files**
- **Audio Sources**: Any FFmpeg-supported format (FLAC, WAV, MP3, etc.)
- **Configuration**:
- Style parameters JSON (branding, colors, fonts)
- YouTube credentials and templates
- Email templates
- **Assets**:
- Background images for title/end screens
- Custom fonts
- Branding elements
### **Working Directory Structure**
```
Artist - Song Title/
├── Artist - Song Title (Original).wav # Converted input
├── Artist - Song Title (Title).mov # Generated title screen
├── Artist - Song Title (End).mov # Generated end screen
├── Artist - Song Title (With Vocals).mkv # Karaoke video with vocals
├── Artist - Song Title (Karaoke).lrc # Timed lyrics
├── stems/ # Audio separation outputs
│ ├── Artist - Song Title (Vocals ...).flac
│ ├── Artist - Song Title (Drums ...).flac
│ └── ...
└── lyrics/ # Lyrics processing files
├── Artist - Song Title (Lyrics Genius).txt
├── Artist - Song Title (Lyrics Corrected).txt
├── Artist - Song Title (Karaoke).cdg
└── ...
```
### **Final Output Files**
- **Video Formats**:
- 4K lossless MP4 (PCM audio)
- 4K lossy MP4 (AAC audio)
- 720p MP4 (compressed for sharing)
- MKV with FLAC audio (YouTube optimized)
- **Karaoke Packages**:
- CDG+MP3 ZIP (CD+Graphics format)
- TXT+MP3 ZIP (text-based karaoke)
- **Individual Formats**: LRC, CDG, ASS subtitle files
### **Organization System**
- **Brand-coded directories**: `BRAND-####` sequence numbering
- **Automated file organization** to configured paths
- **Public sharing directory** with cloud synchronization
- **Multi-location backup** integration
## Current Architecture Limitations for Cloud Deployment
The tool currently assumes:
### **Local System Dependencies**
- Local file system access for model storage and temporary files
- Terminal-based user interaction for choices and confirmations
- Browser access on same machine for web UI components
- Local application launching (e.g., Audacity integration)
- Direct file system paths for organization and sharing
### **Interactive Elements**
- Terminal prompts requiring keyboard input
- Web browser launching on local machine
- File system browsing for path selection
- Manual approval gates that pause execution
### **Resource Management**
- Static model file paths
- Local GPU/hardware detection and usage
- Temporary file cleanup assumes local storage
- Process management tied to single-machine execution
## Cloud Deployment Challenges
Key architectural changes needed for cloud deployment:
1. **User Interface Migration**
- Replace terminal interactions with web-based interfaces
- Implement session management for multi-step workflows
- Handle asynchronous processing with status updates
2. **Resource Management**
- Dynamic GPU allocation and queuing
- Distributed model file storage and caching
- Scalable temporary storage management
- Container orchestration for processing jobs
3. **Interactive Workflow Adaptation**
- Web-based instrumental selection interface
- Embedded lyrics review interface
- Progress tracking and resumable workflows
- Real-time collaboration features
4. **File Management**
- Cloud storage integration for inputs/outputs
- Streaming upload/download for large files
- Multi-tenant file isolation
- Automated cleanup and retention policies
5. **API Integration Scaling**
- Rate limiting and quota management
- API key rotation and security
- Fallback providers for critical services
- Cost optimization for external API usage
This architecture provides a foundation for understanding the current system's capabilities and the considerations needed for cloud deployment transformation.
## Approach 1: The Managed Platform (Easier Start)
This approach uses "Platform as a Service" (PaaS) providers that specialize in running containerized applications and backend tasks, including those requiring GPUs. This abstracts away much of the server management.
A great fit for this would be Modal. It's designed almost exactly for your use case: turning Python scripts into serverless functions that can be called via an API and can have GPUs attached.
How it would work with Modal:
Refactor karaoke-gen: You'd wrap your core processing logic in functions within a Modal script. You would use decorators to specify requirements like the GPU type (@modal.function(gpu="any")), secrets (API keys), and shared storage for your models.
Web Frontend: You could build a simple web app using Flask or FastAPI that also runs on Modal. This app would serve your HTML/React interface.
Job Submission: When you hit "Generate" in the web app, it calls your Modal GPU function asynchronously (my_gpu_function.spawn(...)). This immediately returns a job ID.
State Management: The worker function updates its status in a shared dictionary or a simple database. The web app can have an endpoint that you poll from the frontend to check on the job's progress.
Lyric Review: When the job reaches the AWAITING_REVIEW state, it saves the transcribed lyrics to storage. The web app loads this data into your React editor. When you submit your corrections, it saves the updated data and triggers the next part of the Modal function to resume the job.
Technology Stack:
Backend/Worker: Python on Modal
Web Framework: Flask or FastAPI (also on Modal)
Frontend: Your existing React app, served by the web framework.
Storage: Modal's Network File System for models and temporary files.
Pros & Cons:
✅ Fastest to implement: Drastically reduces infrastructure setup.
✅ Cost-effective for sporadic use: You only pay for the GPU while it's actively processing a job.
❌ Less control: You're dependent on the Modal platform's features and pricing.
+467
View File
@@ -0,0 +1,467 @@
# Karaoke Generator Authentication Setup Guide
This guide explains how to set up and configure the authentication system for the Karaoke Generator web application.
## Overview
The authentication system supports four types of access:
1. **Admin Access** - Full system access with admin tools
2. **Unlimited Access** - Unlimited karaoke generation without admin tools
3. **Limited Access** - Fixed number of uses (e.g., 1, 5, 10 uses)
4. **Stripe Access** - Payment-validated access tokens
## Initial Setup
### 1. Configure Admin Tokens
Admin tokens are set via environment variables in your Modal deployment:
```bash
# Set one or more admin tokens (comma-separated)
modal secret create env-vars ADMIN_TOKENS="admin-master-key-2024,backup-admin-token"
# Set an auth secret for session security (optional but recommended)
modal secret create env-vars AUTH_SECRET="your-random-secret-string-here"
```
### 2. Deploy the Updated Application
Deploy your updated `app.py` with the authentication system:
```bash
modal deploy app.py
```
### 3. Access the Admin Interface
1. Go to your frontend URL: `https://gen.nomadkaraoke.com`
2. Enter one of your admin tokens when prompted
3. Click the **Admin** panel in the top-right corner
4. Click **🎫 Manage Tokens** to create access codes
## Creating Access Tokens
### Admin Interface
Once logged in as an admin, you can create tokens through the web interface:
1. Open the **Token Management** modal
2. Fill in the token creation form:
- **Type**: Choose the token type
- **Token**: Enter the token string (e.g., `SUMMER2024`, `PROMO-10-USES`)
- **Max Uses**: For limited tokens, specify the number of uses
- **Description**: Optional description for tracking
### API Creation (Advanced)
You can also create tokens via the API:
```bash
# Create unlimited access token
curl -X POST "https://your-modal-url/api/admin/tokens/create" \
-H "Authorization: Bearer your-admin-token" \
-H "Content-Type: application/json" \
-d '{
"token_type": "unlimited",
"token_value": "UNLIMITED-PROMO-2024",
"description": "Marketing campaign unlimited access"
}'
# Create limited access token
curl -X POST "https://your-modal-url/api/admin/tokens/create" \
-H "Authorization: Bearer your-admin-token" \
-H "Content-Type: application/json" \
-d '{
"token_type": "limited",
"token_value": "TRIAL-5-USES",
"max_uses": 5,
"description": "5-use trial token"
}'
```
## Token Examples
### Admin Tokens
```
admin-master-2024
nomad-admin-key
backup-admin-access
```
### Unlimited Promo Codes
```
UNLIMITED-BETA
NOMAD-VIP-2024
CREATOR-ACCESS
INFLUENCER-CODE
```
### Limited Use Codes
```
TRIAL-1-USE (1 use)
DEMO-5-VIDEOS (5 uses)
WORKSHOP-10-USES (10 uses)
CONFERENCE-PACK (20 uses)
```
### Stripe Payment Tokens
```
stripe_1234567890abcdef (Generated automatically)
payment_verified_xyz123 (Generated after payment)
```
## Token Management
### Viewing Token Usage
Admin users can see detailed usage statistics:
- Total uses per token
- Number of jobs created
- Last used timestamp
- Active/revoked status
### Revoking Tokens
Revoke compromised or expired tokens:
1. Go to **Token Management**
2. Find the token in the list
3. Click **Revoke** button
4. Confirm the action
### Usage Tracking
The system automatically tracks:
- When tokens are used
- Which jobs were created with each token
- Remaining uses for limited tokens
- Usage patterns and statistics
## Security Considerations
### Admin Token Security
- Use strong, unique admin tokens
- Store admin tokens securely
- Rotate admin tokens periodically
- Limit the number of admin tokens
### Access Token Best Practices
- Use descriptive token names
- Include purpose in token description
- Set appropriate use limits
- Monitor token usage regularly
- Revoke unused or suspicious tokens
### Environment Variables
Required environment variables:
```bash
ADMIN_TOKENS="token1,token2,token3" # Required
AUTH_SECRET="random-secret-string" # Recommended
```
## Stripe Integration (Future Implementation)
*Note: This section documents the planned Stripe payment integration for future development.*
### Overview
The authentication system is already prepared for Stripe integration with:
- `stripe` token type implemented
- Payment tracking infrastructure in place
- Webhook endpoint structure ready
- Token expiration and usage limits supported
### Implementation Steps
#### 1. Stripe Account Setup
```bash
# Required Stripe configuration
modal secret create env-vars STRIPE_SECRET_KEY="sk_live_..."
modal secret create env-vars STRIPE_PUBLISHABLE_KEY="pk_live_..."
modal secret create env-vars STRIPE_WEBHOOK_SECRET="whsec_..."
```
#### 2. Payment Products Configuration
Create Stripe products for different access levels:
```python
# Example product configurations
STRIPE_PRODUCTS = {
"single_video": {
"price_id": "price_1234567890",
"uses": 1,
"name": "Single Video Generation"
},
"video_pack_5": {
"price_id": "price_0987654321",
"uses": 5,
"name": "5-Video Pack"
},
"monthly_unlimited": {
"price_id": "price_monthly_unlimited",
"uses": -1, # unlimited
"expires_days": 30,
"name": "Monthly Unlimited Access"
}
}
```
#### 3. Frontend Payment Flow
Add to frontend (`app.js`):
```javascript
// Payment button integration
async function initiateStripePayment(productType) {
const response = await authenticatedFetch(`${API_BASE_URL}/stripe/create-checkout`, {
method: 'POST',
body: JSON.stringify({
product_type: productType,
success_url: window.location.origin + '/payment-success',
cancel_url: window.location.origin + '/payment-cancelled'
})
});
const { checkout_url } = await response.json();
window.location.href = checkout_url;
}
```
#### 4. Backend Payment Endpoints
Add to `app.py`:
```python
import stripe
@api_app.post("/api/stripe/create-checkout")
async def create_stripe_checkout(request: PaymentRequest):
"""Create Stripe checkout session."""
try:
stripe.api_key = os.environ.get("STRIPE_SECRET_KEY")
session = stripe.checkout.Session.create(
payment_method_types=['card'],
line_items=[{
'price': STRIPE_PRODUCTS[request.product_type]['price_id'],
'quantity': 1,
}],
mode='payment',
success_url=request.success_url + '?session_id={CHECKOUT_SESSION_ID}',
cancel_url=request.cancel_url,
metadata={'product_type': request.product_type}
)
return {"checkout_url": session.url}
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@api_app.post("/api/stripe/webhook")
async def stripe_webhook(request: Request):
"""Handle Stripe webhook events."""
payload = await request.body()
sig_header = request.headers.get('stripe-signature')
try:
event = stripe.Webhook.construct_event(
payload, sig_header, os.environ.get("STRIPE_WEBHOOK_SECRET")
)
except ValueError:
raise HTTPException(status_code=400, detail="Invalid payload")
except stripe.error.SignatureVerificationError:
raise HTTPException(status_code=400, detail="Invalid signature")
if event['type'] == 'checkout.session.completed':
session = event['data']['object']
await handle_successful_payment(session)
return {"status": "success"}
async def handle_successful_payment(session):
"""Generate access token after successful payment."""
product_type = session['metadata']['product_type']
product_config = STRIPE_PRODUCTS[product_type]
# Generate unique token
payment_token = f"stripe_{session['id']}"
# Create token in auth system
token_data = {
"type": "stripe",
"max_uses": product_config['uses'],
"description": f"Paid access: {product_config['name']}",
"created_at": time.time(),
"stripe_session_id": session['id'],
"customer_email": session.get('customer_details', {}).get('email'),
"active": True
}
# Add expiration for time-limited products
if 'expires_days' in product_config:
token_data["expires_at"] = time.time() + (product_config['expires_days'] * 24 * 60 * 60)
# Store token
stored_tokens = auth_tokens_dict.get("tokens", {})
stored_tokens[payment_token] = token_data
auth_tokens_dict["tokens"] = stored_tokens
# TODO: Send email with access token to customer
# send_access_token_email(session['customer_details']['email'], payment_token)
```
#### 5. Email Integration
For sending access tokens via email after payment:
```python
# Add email service (SendGrid, Mailgun, etc.)
async def send_access_token_email(email: str, token: str):
"""Send access token to customer via email."""
subject = "Your Nomad Karaoke Access Token"
body = f"""
Thank you for your purchase!
Your access token: {token}
To use your karaoke generator:
1. Go to https://gen.nomadkaraoke.com
2. Enter your access token: {token}
3. Start creating karaoke videos!
Questions? Contact support@nomadkaraoke.com
"""
# Send email implementation here
```
#### 6. Payment Success Page
Add payment success handling:
```javascript
// Handle successful payment redirect
async function handlePaymentSuccess() {
const urlParams = new URLSearchParams(window.location.search);
const sessionId = urlParams.get('session_id');
if (sessionId) {
// Show success message and instructions for token retrieval
showSuccess('Payment successful! Check your email for your access token.');
// Optional: Auto-retrieve token if customer is logged in
try {
const response = await fetch(`${API_BASE_URL}/stripe/get-token/${sessionId}`);
if (response.ok) {
const { token } = await response.json();
await login(token);
}
} catch (error) {
console.log('Auto-login failed, user will need to enter token manually');
}
}
}
```
#### 7. Testing Configuration
For testing with Stripe test keys:
```bash
# Test environment
modal secret create env-vars STRIPE_SECRET_KEY="sk_test_..."
modal secret create env-vars STRIPE_PUBLISHABLE_KEY="pk_test_..."
modal secret create env-vars STRIPE_WEBHOOK_SECRET="whsec_test_..."
```
#### 8. Security Considerations
- Validate all webhook signatures
- Store minimal payment data (just session IDs)
- Use HTTPS for all payment flows
- Implement rate limiting on payment endpoints
- Log all payment events for audit trail
- Never store credit card information
#### 9. Admin Monitoring
Add Stripe payment monitoring to admin panel:
```javascript
// Admin view of Stripe payments
async function showStripePayments() {
const response = await authenticatedFetch(`${API_BASE_URL}/admin/stripe/payments`);
const payments = await response.json();
// Display payment history, refunds, token generation stats
}
```
### Testing Workflow
1. Set up Stripe test environment
2. Create test products and prices
3. Test checkout flow with test cards
4. Verify webhook delivery and token generation
5. Test email delivery
6. Validate token usage and limits
### Production Checklist
- [ ] Live Stripe keys configured
- [ ] Webhook endpoints registered with Stripe
- [ ] SSL certificates valid
- [ ] Email service configured
- [ ] Payment success/cancel pages deployed
- [ ] Admin monitoring dashboard ready
- [ ] Customer support process documented
This foundation allows for rapid Stripe integration when you're ready to monetize the service.
## Troubleshooting
### Common Issues
1. **Authentication Failed**
- Check if token exists and is active
- Verify token spelling and case
- Ensure token hasn't been revoked
2. **Admin Access Denied**
- Verify admin token is in ADMIN_TOKENS environment variable
- Check Modal secrets are properly configured
- Redeploy if environment variables were changed
3. **No Uses Remaining**
- Check token usage in admin panel
- Create new token or increase limits
- Verify usage tracking is working correctly
### Debugging
Enable debug logging in the backend:
```python
logging.getLogger().setLevel(logging.DEBUG)
```
Check authentication status via API:
```bash
curl -X POST "https://your-modal-url/api/auth/validate" \
-H "Authorization: Bearer your-token"
```
## Support
For issues with the authentication system:
1. Check the admin panel for token status
2. Review Modal logs for authentication errors
3. Verify environment variables are set correctly
4. Contact system administrator if problems persist
## Example Deployment Workflow
1. **Development**: Use admin tokens for testing
2. **Staging**: Create test tokens for validation
3. **Production**:
- Set strong admin tokens
- Create marketing promo codes
- Set up Stripe integration
- Monitor usage and security
This authentication system provides flexible access control while maintaining security and usage tracking for your karaoke generation service.
+210
View File
@@ -0,0 +1,210 @@
# Karaoke Generator Finalization Setup Guide
This guide explains how to configure the Modal web application to work the same way as your local CLI workflow, including YouTube upload, Dropbox sync, Discord notifications, and file organization.
## Overview
The finalization system now supports all the features from your CLI workflow:
- **YouTube Upload**: Automatically upload final videos to YouTube
- **Dropbox Sync**: Organize files in Dropbox with brand codes (NOMAD-XXXX)
- **Discord Notifications**: Send Discord webhook notifications for new uploads
- **Email Drafts**: Create email drafts for client delivery
- **Public Share**: Copy files to public sharing directories
- **Cloud Sync**: Sync public files to Google Drive
## Step 1: Deploy Updated Modal App
First, deploy the updated Modal app with the new finalization features:
```bash
modal deploy app.py
```
## Step 2: Configure Secrets
Set up your Modal secrets with the required environment variables:
```bash
# Update your existing env-vars secret with Discord webhook
modal secret create env-vars \
ADMIN_TOKENS="your-admin-token-here" \
AUTH_SECRET="your-auth-secret" \
AUDIOSHAKE_API_TOKEN="your-audioshake-token" \
GENIUS_API_TOKEN="your-genius-token"
```
## Step 3: Upload Configuration Files
Use the admin API endpoints to upload your configuration files. You'll need your YouTube client secrets, video description template, and email template.
### Upload YouTube Client Secrets
```bash
curl -X POST "https://nomadkaraoke--karaoke-generator-webapp-api-endpoint.modal.run/api/admin/finalization/upload-config-file" \
-H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
-F "file_type=youtube_secrets" \
-F "config_file=@/path/to/your/youtube-client-secrets.json"
```
### Upload YouTube Description Template
```bash
curl -X POST "https://nomadkaraoke--karaoke-generator-webapp-api-endpoint.modal.run/api/admin/finalization/upload-config-file" \
-H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
-F "file_type=youtube_description" \
-F "config_file=@/path/to/your/youtube-description.txt"
```
### Upload Email Template
```bash
curl -X POST "https://nomadkaraoke--karaoke-generator-webapp-api-endpoint.modal.run/api/admin/finalization/upload-config-file" \
-H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
-F "file_type=email_template" \
-F "config_file=@/path/to/your/email-template.txt"
```
## Step 4: Configure rclone
Set up rclone configuration for Dropbox and Google Drive access. First, create your rclone.conf locally:
```bash
# Configure Dropbox remote
rclone config create andrewdropboxfull dropbox
# Configure Google Drive remote
rclone config create googledrive drive
```
Then upload the rclone configuration:
```bash
# Get your rclone config
cat ~/.config/rclone/rclone.conf
# Upload it via the API
curl -X POST "https://nomadkaraoke--karaoke-generator-webapp-api-endpoint.modal.run/api/admin/finalization/rclone-config" \
-H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
-F "rclone_conf=@~/.config/rclone/rclone.conf"
```
## Step 5: Configure Finalization Settings
Update the finalization configuration to match your CLI workflow:
```bash
curl -X POST "https://nomadkaraoke--karaoke-generator-webapp-api-endpoint.modal.run/api/admin/finalization/config" \
-H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"enable_youtube_upload": true,
"enable_discord_notifications": true,
"enable_folder_organisation": true,
"enable_public_share_copy": true,
"enable_rclone_sync": true,
"enable_email_drafts": true,
"brand_prefix": "NOMAD",
"organised_dir": "/output/organized",
"organised_dir_rclone_root": "andrewdropboxfull:Tracks-Organized",
"public_share_dir": "/output/public-share",
"rclone_destination": "googledrive:Nomad Karaoke",
"discord_webhook_url": "https://discord.com/api/webhooks/1313902611421724734/QcQXuvFpa5E3-PA8QXkeG-3mGJVHXXfbbVYWSmT9a7DoSnE-oOXeSWQpMntmIaw9yqPG"
}'
```
## Step 6: Test Configuration
Test that everything is configured correctly:
```bash
curl -X POST "https://nomadkaraoke--karaoke-generator-webapp-api-endpoint.modal.run/api/admin/finalization/test-config" \
-H "Authorization: Bearer YOUR_ADMIN_TOKEN"
```
This will return a detailed test report showing which features are working.
## Step 7: View Current Configuration
You can view your current configuration at any time:
```bash
curl -X GET "https://nomadkaraoke--karaoke-generator-webapp-api-endpoint.modal.run/api/admin/finalization/config" \
-H "Authorization: Bearer YOUR_ADMIN_TOKEN"
```
## How It Works
Once configured, when jobs reach the finalization phase (Phase 3), the system will:
1. **Generate Final Videos**: Create all video formats (lossless 4K, lossy 4K, 720p)
2. **Create CDG/TXT Packages**: Generate karaoke machine files
3. **Upload to YouTube**: Upload the lossless MKV with your title/thumbnail
4. **Organize Files**: Move files to Dropbox with brand code (e.g., NOMAD-0948)
5. **Copy to Public Share**: Copy files to public sharing structure
6. **Sync to Google Drive**: Sync public files to Google Drive
7. **Send Discord Notification**: Post notification with YouTube link
8. **Create Email Draft**: Generate email draft for client delivery
## Troubleshooting
### YouTube Upload Issues
- Verify your client secrets file is valid JSON
- Check that the Google Cloud project has YouTube API enabled
- Test authentication by checking if tokens exist in `/tmp/`
### rclone Issues
- Test rclone commands manually in Modal: `modal run app.py::test_rclone`
- Verify remote names match exactly (case-sensitive)
- Check OAuth tokens are still valid
### Discord Notifications
- Verify webhook URL format: `https://discord.com/api/webhooks/...`
- Test webhook manually with curl
### File Organization
- Check volume permissions and disk space
- Verify brand prefix format and existing sequence numbers
## API Endpoints Reference
All admin finalization endpoints require admin authentication:
- `GET /api/admin/finalization/config` - View current configuration
- `POST /api/admin/finalization/config` - Update configuration
- `POST /api/admin/finalization/rclone-config` - Update rclone config
- `POST /api/admin/finalization/upload-config-file` - Upload config files
- `POST /api/admin/finalization/test-config` - Test configuration
## Example Configuration Files
### YouTube Description Template
```
Karaoke version of {youtube_url}
📱 Download karaoke files: {dropbox_url}
🎤 More karaoke tracks: https://nomadkaraoke.com
```
### Email Template
```
Hi there!
Your karaoke track is ready!
🎵 YouTube: {youtube_url}
📁 Downloads: {dropbox_url}
Enjoy singing!
```
## Security Notes
- Configuration files are stored in Modal volumes and encrypted at rest
- rclone tokens are stored securely and not exposed in logs
- Admin endpoints require authentication tokens
- YouTube tokens are managed by Google's OAuth flow
## Next Steps
After setup is complete, your Modal karaoke generation will work exactly like your local CLI, automatically uploading to YouTube, organizing in Dropbox, and sending notifications.
+1 -1
View File
@@ -1,6 +1,6 @@
MIT License
Copyright (c) 2023 karaokenerds
Copyright (c) 2024 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
+147
View File
@@ -0,0 +1,147 @@
# Modal Karaoke Generator - Migration
## Overview
This document describes the completed migration of the `karaoke-gen` CLI tool to a scalable web application using Modal for serverless GPU processing and GitHub Pages for the frontend.
## Architecture Summary
### Current State: Separated Frontend/Backend Architecture
**Frontend (GitHub Pages):** https://gen.nomadkaraoke.com/
- Static HTML/CSS/JavaScript application
- Real-time job monitoring and admin dashboard
- Lyrics review interface
- Mobile-responsive design
- Deployed automatically via GitHub Actions
**Backend (Modal):** API-only endpoints with CORS support
- GPU-powered serverless functions for audio processing
- RESTful API at `/api/*` endpoints
- Persistent storage for models and job artifacts
- Auto-scaling with warm containers
## Completed Implementation
### Phase 1: Modal Setup ✅ COMPLETE
- ✅ Installed Modal client package
- ✅ Set up Modal authentication token
- ✅ Created `app.py` and `core.py` files
- ✅ Isolated core karaoke processing logic into `core.py`
- ✅ Created persistent volumes for models and output storage
### Phase 2: Modal Application Development ✅ COMPLETE
- ✅ Created Modal app with GPU-powered worker functions
- ✅ Implemented two-phase processing:
- Phase 1: Download audio, separate stems, transcribe lyrics
- Phase 2: Generate final video with corrected lyrics
- ✅ Built comprehensive REST API with the following endpoints:
- `POST /api/submit` - Submit new karaoke generation job
- `GET /api/jobs` - Get all job statuses
- `GET /api/jobs/{job_id}` - Get specific job details
- `GET /api/jobs/{job_id}/logs` - Get job logs
- `POST /api/jobs/{job_id}/lyrics` - Submit corrected lyrics
- `DELETE /api/jobs/{job_id}` - Delete job
- `POST /api/jobs/{job_id}/retry` - Retry failed job
- `GET /api/health` - Health check
- `GET /api/stats` - System statistics
- `POST /api/admin/clear-errors` - Clear error jobs
- `GET /api/admin/logs` - Export logs
- ✅ Added comprehensive error handling and logging system
- ✅ Implemented job state management with persistent storage
### Phase 3: Frontend Development ✅ COMPLETE
- ✅ Created complete static HTML/CSS/JavaScript application
- ✅ Built professional admin dashboard with:
- Real-time job monitoring with auto-refresh
- Statistics dashboard (total jobs, processing, awaiting review, complete, errors)
- Job management (delete, retry, view logs)
- Lyrics review interface
- Error handling and admin controls
- ✅ Mobile-responsive design with modern UI/UX
- ✅ CORS integration with Modal API backend
### Phase 4: Deployment & CI/CD ✅ COMPLETE
- ✅ Deployed Modal backend to production environment
- ✅ Set up GitHub Pages deployment for frontend
- ✅ Updated GitHub Actions workflow with:
- Automated testing
- PyPI publishing with version checking
- GitHub Pages deployment
- Proper permissions and environment protection
- ✅ Custom domain configuration at gen.nomadkaraoke.com
## Current File Structure
```
karaoke-gen/
├── app.py # Modal backend application (API-only)
├── core.py # Core karaoke processing logic
├── frontend/ # Static frontend for GitHub Pages
│ ├── index.html # Main application interface
│ ├── app.js # Frontend JavaScript logic
│ ├── styles.css # Modern responsive styling
│ └── CNAME # Custom domain configuration
├── .github/workflows/
│ └── test-and-publish.yml # CI/CD pipeline
└── ... (rest of original structure)
```
## Key Technical Achievements
1. **Serverless Architecture:** Transformed CLI tool to GPU-powered serverless functions
2. **Separated Concerns:** Clean frontend/backend separation enabling independent scaling
3. **Real-time Monitoring:** Live job status updates and comprehensive admin dashboard
4. **Persistent Storage:** Models and job artifacts stored in Modal volumes
5. **Custom Domain:** Free custom domain via GitHub Pages (gen.nomadkaraoke.com)
6. **CI/CD Pipeline:** Automated testing, publishing, and deployment
7. **Error Handling:** Comprehensive error handling and retry mechanisms
8. **Mobile Responsive:** Professional UI that works on all devices
## Current Issues & Next Steps
### Authentication & Security 🚨 HIGH PRIORITY
- **No Authentication:** Frontend currently has no user authentication
- **Open API:** Modal endpoints are publicly accessible without authorization
- **Admin Controls:** Admin functions (clear errors, delete jobs) need protection
### Backend Integration Issues
- **CORS Configuration:** May need fine-tuning for production
- **Error Handling:** Some backend integration points still broken
- **Job State Management:** Need to verify all job states are properly handled
### Recommended Next Steps
1. **Implement Authentication:**
- Add user authentication to frontend (consider OAuth with GitHub/Google)
- Implement API key or JWT-based authentication for Modal endpoints
- Protect admin functions behind authentication
2. **Fix Backend Integration:**
- Debug CORS issues between frontend and Modal API
- Ensure all API endpoints are working correctly
- Test complete job flow from submission to completion
3. **Add Rate Limiting:**
- Implement rate limiting on Modal endpoints
- Add job queue management to prevent abuse
4. **Enhanced Monitoring:**
- Add proper logging and monitoring for production
- Implement alerting for failed jobs
- Add performance metrics
## Deployment URLs
- **Frontend:** https://gen.nomadkaraoke.com/
- **Backend API:** `nomadkaraoke--karaoke-generator-webapp-api-endpoint.modal.run/api/`
- **Repository:** https://github.com/nomadkaraoke/karaoke-gen
## Modal Configuration
Since the frontend is now served statically from GitHub Pages, the Modal deployment should focus solely on the API endpoints and GPU processing functions.
---
*Last Updated: December 2024*
*Status: Backend functional, Frontend deployed, Authentication needed*
+120 -216
View File
@@ -1,256 +1,160 @@
# Karaoke Prep 🎶
# Karaoke Generator 🎶 🎥 🚀
[![PyPI version](https://badge.fury.io/py/karaoke-prep.svg)](https://badge.fury.io/py/karaoke-prep)
![PyPI - Version](https://img.shields.io/pypi/v/karaoke-gen)
![Python Version](https://img.shields.io/badge/python-3.10+-blue)
![Tests](https://github.com/nomadkaraoke/karaoke-gen/workflows/Test%20and%20Publish/badge.svg)
![Test Coverage](https://codecov.io/gh/nomadkaraoke/karaoke-gen/branch/main/graph/badge.svg)
Prepare for karaoke video creation, by downloading audio from YouTube and lyrics from Genius for a given song.
Generate karaoke videos with instrumental audio and synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens, uploading the resulting video to YouTube.
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.
## Overview
## Features
Karaoke Generator is a comprehensive tool for creating high-quality karaoke videos. It automates the entire workflow:
- 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.
- Easy Finalisation: After manually performing your sync (e.g. using [MidiCo](https://www.midicokaraoke.com)), run `karaoke-finalise` to remux and add your title screen!
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
## Installation 🛠️
## Installation
You can install Karaoke Prep using pip:
`pip install karaoke-prep`
If you aren't sure what `pip` is or how to use the command line, here are some YouTube tutorials which will probably help:
- Install Python on Windows: https://www.youtube.com/watch?v=YKSpANU8jPE
- Command Line basics Windows: https://www.youtube.com/watch?v=MBBWVgE0ewk
- Install Python on Mac: https://www.youtube.com/watch?v=3-sPfR4JEQ8
- Command Line basics Mac: https://www.youtube.com/watch?v=FfT8OfMpARM
## Karaoke production guide using karaoke-prep and MidiCo
- Run `karaoke-prep <Artist> <Title>` to fetch and prep the files above
- Wait for it to output at least the WAV file and lyrics (you can leave it running in the background while you sync)
- Open the WAV file in MidiCo: `(YouTube xxxxxxxxxxx).wav`
- Copy/paste the lyrics into MidiCo: `(Lyrics Processed).txt`
- Perform the lyrics sync (here's a [video](https://www.youtube.com/watch?v=63-Fk3mfZ7Q) showing me doing it) in MidiCo
- Render the video to 4k using the MidiCo "Export Movie" feature, saving it as `Artist - Title (Karaoke).mov` in the same folder
- Run `karaoke-finalise` to remux the instrumental audio and join the title clip to the start
- Upload the resulting `Artist - Title (Final Karaoke).mp4` video to YouTube!
Here's my [tutorial video with verbal explanation](https://www.youtube.com/watch?v=ZsROHgqAVHs) of the whole process, and here's a [normal speed demo](https://www.youtube.com/watch?v=63-Fk3mfZ7Q) of me doing it (8 minutes total for a single track).
## Usage 🚀
### 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
--intro_background_color INTRO_BACKGROUND_COLOR Optional: Background color for intro video (default: black). Example: --intro_background_color=#123456
--intro_background_image INTRO_BACKGROUND_IMAGE Optional: Path to background image for intro video. Overrides background color if provided. Example: --intro_background_image=path/to/image.jpg
--intro_font INTRO_FONT Optional: Font file for intro video (default: Avenir-Next-Bold). Example: --intro_font=AvenirNext-Bold.ttf
--intro_artist_color INTRO_ARTIST_COLOR Optional: Font color for intro video artist text (default: #ff7acc). Example: --intro_artist_color=#123456
--intro_title_color INTRO_TITLE_COLOR Optional: Font color for intro video title text (default: #ffdf6b). Example: --intro_title_color=#123456
```
### ⭐ YouTube URL with Artist and Title
For the most consistent results, provide a specific YouTube URL along with the artist and title like so:
```
karaoke-prep "https://www.youtube.com/watch?v=YOUR_VIDEO_ID" "The Fray" "Never Say Never"
```bash
pip install karaoke-gen
```
### Artist and Title Only
## Remote Audio Separation 🌐
If you don't have a specific YouTube URL, just provide the artist and title. Karaoke Prep will search for and download the top YouTube result.
Karaoke Generator now supports remote audio separation using the Audio Separator API. This allows you to offload the compute-intensive audio separation to a remote GPU server while keeping the rest of the workflow local.
```
karaoke-prep "The Fray" "Never Say Never"
### Benefits of Remote Processing
- **Save Local Resources**: No more laptop CPU/GPU consumption during separation
- **Faster Processing**: GPU-accelerated separation on dedicated hardware
- **Cost Effective**: ~$0.019 per separation job on Modal.com (with $30/month free credits)
- **Multiple Models**: Process with multiple separation models efficiently
### Setup Remote Processing
1. **Deploy Audio Separator API** (using Modal.com):
```bash
pip install modal
modal setup
modal deploy audio_separator/remote/deploy_modal.py
```
2. **Set Environment Variable**:
```bash
export AUDIO_SEPARATOR_API_URL="https://USERNAME--audio-separator-api.modal.run"
```
3. **Run Karaoke Generator Normally**:
```bash
karaoke-gen "Rick Astley" "Never Gonna Give You Up"
```
The tool will automatically detect the `AUDIO_SEPARATOR_API_URL` environment variable and use remote processing instead of local separation. If the remote API is unavailable, it will gracefully fall back to local processing.
### Remote vs Local Processing
| Aspect | Remote Processing | Local Processing |
|--------|------------------|------------------|
| **Resource Usage** | Minimal local CPU/GPU | High local CPU/GPU |
| **Processing Time** | ~2-5 minutes | ~15-45 minutes |
| **Cost** | ~$0.019 per job | Free (but uses local resources) |
| **Requirements** | Internet connection | Local GPU recommended |
| **Setup** | One-time API deployment | Audio separator models download |
## Quick Start
```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"
# Or let it search YouTube for you
karaoke-gen "Rick Astley" "Never Gonna Give You Up"
```
### Only YouTube URL
## Workflow Options
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 Gen supports different workflow options to fit your needs:
```
karaoke-prep "https://www.youtube.com/watch?v=YOUR_VIDEO_ID"
```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"
```
## Files produced by karaoke-prep and what to do with them
### Lyrics Handling
After running `karaoke-prep` you should have the following 11 files, grouped into folder(s) for each track:
```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"
- `Artist - Title (YouTube xxxxxxxxxxx).webm`
- Original unmodified video, fetched from YouTube in the highest quality available (may not always be WebM)
- You probably don't need this unless you're creating a custom request
- `Artist - Title (YouTube xxxxxxxxxxx).png`
- A still image taken from 30 seconds into the video, in case that's useful for a custom background
- You probably don't need this unless you're creating a custom request
- `Artist - Title (YouTube xxxxxxxxxxx).wav`
- Unmodified audio from the YouTube video, converted to WAV format for compatibility
- You should open this in MidiCo to begin syncing lyrics to make your karaoke video.
- `Artist - Title (Lyrics).txt`
- Unmodified lyrics fetched from genius.com based on the artist/title provided
- Depending on the song, may have lines which are too long for one karaoke screen
- `Artist - Title (Lyrics Processed).txt`
- Lyrics from genius, split into lines no longer than 40 characters
- You should open this and copy/paste the text into the MidiCo lyrics editor
- `Artist - Title (Vocals UVR-MDX-NET-Inst_HQ_3).mp3`
- Vocal track from the audio, separated using the UVR Inst_HQ_3 model.
- You probably don't need this unless you're trying to tweak the backing track
- `Artist - Title (Vocals UVR_MDXNET_KARA_2).mp3`
- Vocal track from the audio, separated using the UVR KARA_2 model.
- You probably don't need this unless you're trying to tweak the backing track
- `Artist - Title (Instrumental UVR-MDX-NET-Inst_HQ_3).mp3`
- Instrumental track from the audio, separated using the UVR Inst_HQ_3 model.
- This is typically a safe bet for the instrumental track but will not include any backing vocals.
- `Artist - Title (Instrumental UVR_MDXNET_KARA_2).mp3`
- Instrumental track from the audio, separated using the UVR KARA_2 model.
- This is the default choice for the finalisation step below as it usually does a good job of keeping backing vocals. However for some songs it includes far too much or is kinda glitchy, so you should check it before finalising and make a judgement call about using this vs. the Inst_HQ_3 one.
- `Artist - Title (Title).png`
- Title screen static image; if you specify your own background image, font, color etc. this should give you a convenient way to add a title screen to the start of your video.
- `Artist - Title (Title).mov`
- 5 second video clip version of the title screen image, ready to be joined by the finalisation step.
## Finalisation 🎥
After completing your manual sync process and rendering your `Artist - Title (Karaoke).mov` file (still using the original audio!) into the same folder, you can now run `karaoke-finalise`.
This will output some additional files:
- `Artist - Title (Karaoke).mov`
- Karaoke video without title screen, remuxed to use the instrumental audio
- `Artist - Title (With Vocals).mov`
- Karaoke video without title screen, using the original audio (useful for practicing!)
- `Artist - Title (Final Karaoke).mp4`
- Final karaoke video with 5 second title screen intro, instrumental audio and converted to MP4 for compatibility and reduced file size. Upload this to YouTube!
## Requirements 📋
Python >= 3.9
Libraries: onnx, onnxruntime, numpy, soundfile, librosa, torch, wget, six
## Developing Locally
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
# Adjust subtitle timing
karaoke-gen --subtitle_offset_ms=500 "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.
### Finalisation Options
### Install Dependencies
```bash
# Enable CDG ZIP generation
karaoke-gen --enable_cdg --style_params_json="path/to/style.json" "Rick Astley" "Never Gonna Give You Up"
Run the following command to install the project dependencies:
# Enable TXT ZIP generation
karaoke-gen --enable_txt "Rick Astley" "Never Gonna Give You Up"
```
poetry install
# 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"
# Organize files with brand code
karaoke-gen --brand_prefix="BRAND" --organised_dir="path/to/Tracks-Organized" "Rick Astley" "Never Gonna Give You Up"
```
### Activate the Virtual Environment
## Full Command Reference
To activate the virtual environment, use the following command:
For a complete list of options:
```
poetry shell
```bash
karaoke-gen --help
```
### Running the Command-Line Interface Locally
## Development
You can run the CLI command directly within the virtual environment. For example:
### Running Tests
```
karaoke-prep 1
The project uses pytest for testing with unit and integration tests:
```bash
# Run all tests (unit tests first, then integration tests)
pytest
# Run only unit tests (fast feedback during development)
pytest -m "not integration"
# Run only integration tests (comprehensive end-to-end testing)
pytest -m integration
```
### Deactivate the Virtual Environment
Unit tests run quickly and provide fast feedback, while integration tests are slower but test the full workflow end-to-end.
Once you are done with your development work, you can exit the virtual environment by simply typing:
## License
```
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
+7182
View File
File diff suppressed because it is too large. Load diff
+984
View File
@@ -0,0 +1,984 @@
"""
Core processing functions for karaoke generation.
This module contains a wrapper around the existing KaraokePrep functionality
for serverless execution on Modal.
"""
import os
import sys
import json
import logging
import tempfile
import shutil
import asyncio
import zipfile
from pathlib import Path
from typing import Dict, Any, Optional, Tuple, List
# Import the existing KaraokePrep class that the CLI uses
from karaoke_gen import KaraokePrep
def setup_logger(log_level=logging.INFO) -> logging.Logger:
"""Set up a basic logger for core processing functions."""
logger = logging.getLogger(__name__)
logger.setLevel(log_level)
if not logger.handlers:
handler = logging.StreamHandler()
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(module)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
return logger
class ServerlessKaraokeProcessor:
"""
Serverless wrapper around the existing KaraokePrep functionality.
Uses the same code path as the CLI for consistency.
"""
def __init__(self, model_dir: str = "/models", output_dir: str = "/output"):
self.model_dir = model_dir
self.output_dir = output_dir
# Use the logger from this module - job-specific logging will be set up externally
self.logger = logging.getLogger(__name__)
async def process_uploaded_file(self, job_id: str, audio_file_path: str, artist: str, title: str, styles_file_path: Optional[str] = None, styles_archive_path: Optional[str] = None) -> Dict[str, Any]:
"""
Process uploaded audio file through the complete karaoke generation pipeline.
Uses the same KaraokePrep workflow as the CLI.
Args:
job_id: Unique identifier for this job
audio_file_path: Path to uploaded audio file
artist: Artist name
title: Song title
styles_file_path: Optional path to uploaded styles JSON file
styles_archive_path: Optional path to uploaded styles archive file
Returns:
Dictionary with processing results and output file paths
"""
try:
job_output_dir = Path(self.output_dir) / job_id
job_output_dir.mkdir(parents=True, exist_ok=True)
self.logger.info(f"Processing uploaded file: {audio_file_path}")
self.logger.info(f"Artist: {artist}, Title: {title}")
if styles_file_path:
self.logger.info(f"Using custom styles: {styles_file_path}")
# Handle styles archive extraction
if styles_archive_path:
self.logger.info(f"Using styles archive: {styles_archive_path}")
# Extract archive to the job output directory instead of /tmp
styles_assets_dir = job_output_dir / "styles_assets"
styles_assets_dir.mkdir(exist_ok=True)
with zipfile.ZipFile(styles_archive_path, 'r') as zip_ref:
zip_ref.extractall(styles_assets_dir)
self.logger.info(f"Extracted styles archive to {styles_assets_dir}")
# List extracted files for debugging
extracted_files = []
for root, dirs, files in os.walk(styles_assets_dir):
for file in files:
file_path = os.path.join(root, file)
extracted_files.append(file_path)
# Check if file is readable
try:
file_stat = os.stat(file_path)
self.logger.info(f"Extracted file: {file_path} (size: {file_stat.st_size} bytes)")
except Exception as e:
self.logger.warning(f"Could not stat file {file_path}: {e}")
# Update styles JSON to use the extracted files
if styles_file_path:
updated_styles_path = job_output_dir / "styles_updated.json"
self._update_styles_paths(styles_file_path, str(updated_styles_path), str(styles_assets_dir))
styles_file_path = str(updated_styles_path)
self.logger.info(f"Updated styles file paths: {styles_file_path}")
# Validate that style-referenced files exist (do this after archive extraction)
if styles_file_path:
self.logger.info("Starting styles file validation...")
missing_files = self._validate_styles_files(styles_file_path)
if missing_files:
self.logger.error(f"Validation failed. Missing files: {missing_files}")
raise Exception(f"Missing style files - please ensure these files are included in the styles archive: {', '.join(missing_files)}")
else:
self.logger.info("Styles file validation passed - all files found")
# Set up KaraokePrep with the same formatter used by the CLI
log_formatter = logging.Formatter(
fmt="%(asctime)s.%(msecs)03d - %(levelname)s - %(module)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
)
# Create KaraokePrep instance using the same configuration as CLI
kprep = KaraokePrep(
input_media=audio_file_path,
artist=artist,
title=title,
filename_pattern=None,
dry_run=False,
log_formatter=log_formatter,
log_level=logging.INFO,
render_bounding_boxes=False,
output_dir=str(job_output_dir),
create_track_subfolders=False, # Don't create subfolders in serverless
lossless_output_format="FLAC",
output_png=True,
output_jpg=True,
clean_instrumental_model="model_bs_roformer_ep_317_sdr_12.9755.ckpt",
backing_vocals_models=["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"],
other_stems_models=["htdemucs_6s.yaml"],
model_file_dir=self.model_dir,
existing_instrumental=None,
skip_separation=False,
lyrics_artist=artist,
lyrics_title=title,
lyrics_file=None,
skip_lyrics=False,
skip_transcription=False,
skip_transcription_review=False, # Enable review step - will be intercepted for web interface
subtitle_offset_ms=0,
style_params_json=styles_file_path, # Use uploaded styles file if provided
)
# Process the track using the full KaraokePrep workflow
self.logger.info("Starting KaraokePrep processing...")
tracks = await kprep.process()
if not tracks:
raise Exception("No tracks were processed")
track = tracks[0] # We're processing a single track
self.logger.info(f"Successfully processed track: {track['artist']} - {track['title']}")
# Check if correction data was generated (indicating lyrics transcription occurred)
track_output_dir = track.get("track_output_dir", str(job_output_dir))
lyrics_dir = Path(track_output_dir) / "lyrics"
corrections_file = lyrics_dir / f"{artist} - {title} (Lyrics Corrections).json"
if corrections_file.exists():
self.logger.info(f"Found lyrics correction data at {corrections_file}, setting status to awaiting_review")
return {
"job_id": job_id,
"status": "awaiting_review",
"track_data": track,
"track_output_dir": track_output_dir,
"corrections_file": str(corrections_file),
"styles_file_path": styles_file_path, # Return the updated styles file path
}
else:
self.logger.info("No lyrics correction data found, job completed successfully")
return {
"job_id": job_id,
"status": "complete",
"track_data": track,
"track_output_dir": track_output_dir,
"styles_file_path": styles_file_path, # Return the updated styles file path
}
except Exception as e:
self.logger.error(f"Error processing uploaded file {job_id}: {str(e)}")
raise
async def process_url(self, job_id: str, url: str, stored_cookies: Optional[str] = None, override_artist: Optional[str] = None, override_title: Optional[str] = None, styles_file_path: Optional[str] = None, styles_archive_path: Optional[str] = None) -> Dict[str, Any]:
"""
Process a URL through the complete karaoke generation pipeline.
Uses the same KaraokePrep workflow as the CLI.
Args:
job_id: Unique identifier for this job
url: YouTube or other media URL
stored_cookies: Optional stored browser cookies to help bypass bot detection
Returns:
Dictionary with processing results and output file paths
"""
try:
job_output_dir = Path(self.output_dir) / job_id
job_output_dir.mkdir(parents=True, exist_ok=True)
self.logger.info(f"Processing URL: {url}")
if override_artist:
self.logger.info(f"Artist override: {override_artist}")
if override_title:
self.logger.info(f"Title override: {override_title}")
# Handle styles files the same way as uploaded files
if styles_file_path:
self.logger.info(f"Using custom styles: {styles_file_path}")
# Handle styles archive extraction
if styles_archive_path:
self.logger.info(f"Using styles archive: {styles_archive_path}")
# Extract archive to the job output directory
styles_assets_dir = job_output_dir / "styles_assets"
styles_assets_dir.mkdir(exist_ok=True)
with zipfile.ZipFile(styles_archive_path, 'r') as zip_ref:
zip_ref.extractall(styles_assets_dir)
self.logger.info(f"Extracted styles archive to {styles_assets_dir}")
# List extracted files for debugging
extracted_files = []
for root, dirs, files in os.walk(styles_assets_dir):
for file in files:
file_path = os.path.join(root, file)
extracted_files.append(file_path)
# Check if file is readable
try:
file_stat = os.stat(file_path)
self.logger.info(f"Extracted file: {file_path} (size: {file_stat.st_size} bytes)")
except Exception as e:
self.logger.warning(f"Could not stat file {file_path}: {e}")
# Update styles JSON to use the extracted files
if styles_file_path:
updated_styles_path = job_output_dir / "styles_updated.json"
self._update_styles_paths(styles_file_path, str(updated_styles_path), str(styles_assets_dir))
styles_file_path = str(updated_styles_path)
self.logger.info(f"Updated styles file paths: {styles_file_path}")
# Ensure styles file was provided - frontend should always upload one
if not styles_file_path:
raise Exception("No styles file provided. The frontend should upload default styles for all jobs.")
# Validate that style-referenced files exist (do this after archive extraction)
if styles_file_path:
self.logger.info("Starting styles file validation...")
missing_files = self._validate_styles_files(styles_file_path)
if missing_files:
self.logger.error(f"Validation failed. Missing files: {missing_files}")
raise Exception(f"Missing style files - please ensure these files are included in the styles archive: {', '.join(missing_files)}")
else:
self.logger.info("Styles file validation passed - all files found")
if stored_cookies:
self.logger.info("Using stored admin cookies for enhanced access")
else:
self.logger.info("No stored cookies available - attempting server-side extraction with anti-detection measures")
# Set up enhanced yt-dlp options
ytdlp_options = self.get_ytdlp_options(stored_cookies)
# Override the extraction options in the environment
# This is a bit hacky but necessary since KaraokePrep doesn't expose yt-dlp options directly
cookies_file_path = None
try:
if stored_cookies:
# Save stored cookies to a file and set environment variable
import tempfile
cookies_file = tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False)
cookies_file.write(stored_cookies)
cookies_file.close()
cookies_file_path = cookies_file.name
os.environ['YT_DLP_COOKIEFILE'] = cookies_file_path
self.logger.debug(f"Stored cookies saved to: {cookies_file_path}")
# Set additional yt-dlp options via environment
os.environ['YT_DLP_USER_AGENT'] = ytdlp_options['user_agent']
os.environ['YT_DLP_REFERER'] = ytdlp_options['referer']
# Set up KaraokePrep with the same formatter used by the CLI
log_formatter = logging.Formatter(
fmt="%(asctime)s.%(msecs)03d - %(levelname)s - %(module)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
)
# Create KaraokePrep instance using the same configuration as CLI
kprep = KaraokePrep(
input_media=url,
artist=override_artist, # User-provided override or None
title=override_title, # User-provided override or None
filename_pattern=None,
dry_run=False,
log_formatter=log_formatter,
log_level=logging.INFO,
render_bounding_boxes=False,
output_dir=str(job_output_dir),
create_track_subfolders=False, # Don't create subfolders in serverless
lossless_output_format="FLAC",
output_png=True,
output_jpg=True,
clean_instrumental_model="model_bs_roformer_ep_317_sdr_12.9755.ckpt",
backing_vocals_models=["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"],
other_stems_models=["htdemucs_6s.yaml"],
model_file_dir=self.model_dir,
existing_instrumental=None,
skip_separation=False,
lyrics_artist=None,
lyrics_title=None,
lyrics_file=None,
skip_lyrics=False,
skip_transcription=False,
skip_transcription_review=False, # Enable review step - will be intercepted for web interface
subtitle_offset_ms=0,
style_params_json=styles_file_path, # Use processed styles file (default or custom)
cookies_str=stored_cookies, # Pass stored admin cookies
)
# Process the track using the full KaraokePrep workflow
self.logger.info("Starting KaraokePrep processing...")
tracks = await kprep.process()
if not tracks:
raise Exception("No tracks were processed")
track = tracks[0] # We're processing a single track
self.logger.info(f"Successfully processed track: {track['artist']} - {track['title']}")
# Check if correction data was generated (indicating lyrics transcription occurred)
track_output_dir = track.get("track_output_dir", str(job_output_dir))
lyrics_dir = Path(track_output_dir) / "lyrics"
artist = track.get("artist", "Unknown")
title = track.get("title", "Unknown")
corrections_file = lyrics_dir / f"{artist} - {title} (Lyrics Corrections).json"
if corrections_file.exists():
self.logger.info(f"Found lyrics correction data at {corrections_file}, setting status to awaiting_review")
return {
"job_id": job_id,
"status": "awaiting_review",
"track_data": track,
"track_output_dir": track_output_dir,
"corrections_file": str(corrections_file),
"styles_file_path": styles_file_path, # Return the processed styles file path
}
else:
self.logger.info("No lyrics correction data found, job completed successfully")
return {
"job_id": job_id,
"status": "complete",
"track_data": track,
"track_output_dir": track_output_dir,
"styles_file_path": styles_file_path, # Return the processed styles file path
}
finally:
# Clean up cookies file and environment variables
if cookies_file_path:
try:
os.unlink(cookies_file_path)
except:
pass
for env_var in ['YT_DLP_COOKIEFILE', 'YT_DLP_USER_AGENT', 'YT_DLP_REFERER']:
if env_var in os.environ:
del os.environ[env_var]
except Exception as e:
error_msg = str(e)
self.logger.error(f"Error processing URL {job_id}: {error_msg}")
# Check if this looks like a bot detection error
if any(keyword in error_msg.lower() for keyword in ['sign in', 'bot', 'automated', '403', 'forbidden', 'captcha']):
# This suggests YouTube bot detection - provide helpful error message
raise Exception(
f"YouTube access blocked (bot detection): {error_msg}. "
f"This usually means YouTube is blocking server requests. "
f"Try providing browser cookies to help bypass this restriction."
)
else:
raise
def get_review_data(self, job_id: str, track_data: Dict[str, Any]) -> Dict[str, Any]:
"""
Extract review data from processed track for frontend review interface.
"""
try:
track_dir = Path(track_data.get("track_output_dir", f"{self.output_dir}/{job_id}"))
# Look for transcription results
transcription_files = {
"lrc_file": None,
"corrected_lyrics": None,
"original_lyrics": None,
"vocals_audio": None
}
# Find LRC file
lrc_files = list(track_dir.glob("**/*.lrc"))
if lrc_files:
transcription_files["lrc_file"] = str(lrc_files[0])
# Find corrected lyrics text file
corrected_files = list(track_dir.glob("**/*Corrected*.txt"))
if corrected_files:
with open(corrected_files[0], 'r') as f:
transcription_files["corrected_lyrics"] = f.read()
# Find original/uncorrected lyrics
original_files = list(track_dir.glob("**/*Uncorrected*.txt"))
if original_files:
with open(original_files[0], 'r') as f:
transcription_files["original_lyrics"] = f.read()
# Find vocals audio file
vocals_files = list(track_dir.glob("**/*Vocals*.flac")) + list(track_dir.glob("**/*Vocals*.FLAC"))
if vocals_files:
transcription_files["vocals_audio"] = str(vocals_files[0])
return {
"job_id": job_id,
"artist": track_data.get("artist", "Unknown"),
"title": track_data.get("title", "Unknown"),
"transcription_files": transcription_files,
"track_data": track_data
}
except Exception as e:
self.logger.error(f"Error getting review data for {job_id}: {str(e)}")
return {
"job_id": job_id,
"error": str(e)
}
def get_ytdlp_options(self, stored_cookies: Optional[str] = None):
"""Get yt-dlp options with enhanced anti-detection."""
options = {
# Basic extraction options
'format': 'bestaudio[ext=webm]/bestaudio[ext=m4a]/bestaudio',
'extractaudio': True,
'audioformat': 'flac',
'outtmpl': '%(title)s.%(ext)s',
# Anti-detection options
'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'referer': 'https://www.youtube.com/',
'sleep_interval': 1,
'max_sleep_interval': 3,
'fragment_retries': 3,
'extractor_retries': 3,
'retries': 3,
# Headers to appear more human
'http_headers': {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-us,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'DNT': '1',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
},
# Avoid bot-like behavior
'no_check_certificate': False,
'prefer_insecure': False,
'call_home': False,
}
# Add stored cookies if available
if stored_cookies:
# Save stored cookies to a temporary file
import tempfile
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
f.write(stored_cookies)
options['cookiefile'] = f.name
return options
def _validate_styles_files(self, styles_file_path: str) -> List[str]:
"""
Validate that all files referenced in the styles JSON exist.
Returns a list of missing file paths.
"""
missing_files = []
try:
with open(styles_file_path, 'r') as f:
styles_data = json.load(f)
# Common keys that reference files
file_keys = [
'background_image', 'existing_image', 'font', 'font_path',
'instrumental_background', 'title_screen_background', 'outro_background'
]
def check_section(section_data, section_name):
if isinstance(section_data, dict):
for key, value in section_data.items():
if key in file_keys and value:
# Convert to string and check if it's a file path
file_path = str(value)
if file_path.startswith('/') and not Path(file_path).exists():
missing_files.append(file_path)
elif isinstance(value, dict):
check_section(value, f"{section_name}.{key}")
# Check all sections
check_section(styles_data, "styles")
return missing_files
except Exception as e:
self.logger.warning(f"Could not validate styles file: {str(e)}")
return [] # Don't block processing for validation errors
def _update_styles_paths(self, input_styles_path: str, output_styles_path: str, assets_dir: str) -> None:
"""
Update file paths in styles JSON to point to the extracted assets directory.
Also install any font files system-wide so they can be referenced by name.
"""
try:
with open(input_styles_path, 'r') as f:
styles_data = json.load(f)
# Build a map of all files in the assets directory for quick lookup
assets_path = Path(assets_dir)
file_map = {}
font_files = [] # Track font files for installation
self.logger.info(f"Building file map from assets directory: {assets_dir}")
for root, dirs, files in os.walk(assets_dir):
for file in files:
file_path = os.path.join(root, file)
filename = file.lower() # Use lowercase for case-insensitive matching
file_map[filename] = file_path
# Check if this is a font file
if filename.endswith(('.ttf', '.otf', '.woff', '.woff2')):
font_files.append(file_path)
self.logger.info(f"Found font file for installation: {file_path}")
self.logger.debug(f"Found asset file: {filename} -> {file_path}")
self.logger.info(f"Found {len(file_map)} files in assets directory, {len(font_files)} fonts")
# Install font files system-wide
if font_files:
self._install_fonts(font_files)
# Common keys that reference files
file_keys = [
'background_image', 'existing_image', 'font', 'font_path',
'instrumental_background', 'title_screen_background', 'outro_background'
]
paths_updated = 0
paths_failed = 0
def update_section(section_data, section_path=""):
nonlocal paths_updated, paths_failed
if isinstance(section_data, dict):
for key, value in section_data.items():
current_path = f"{section_path}.{key}" if section_path else key
if key in file_keys and value:
file_path = str(value).strip()
# Check if this is an absolute path that needs updating
if file_path.startswith('/'):
self.logger.info(f"Processing file path at {current_path}: {file_path}")
# Extract just the filename
original_filename = Path(file_path).name
filename_lower = original_filename.lower()
# Look for the file in our assets map
if filename_lower in file_map:
new_path = file_map[filename_lower]
section_data[key] = new_path
paths_updated += 1
self.logger.info(f"✓ Updated path at {current_path}: {file_path} -> {new_path}")
# Verify the new path exists
if not Path(new_path).exists():
self.logger.warning(f"WARNING: Updated path does not exist: {new_path}")
paths_failed += 1
else:
self.logger.error(f"✗ Could not find file '{original_filename}' in assets directory for path at {current_path}")
self.logger.error(f"Available files: {list(file_map.keys())}")
paths_failed += 1
else:
self.logger.debug(f"Skipping relative path at {current_path}: {file_path}")
elif isinstance(value, dict):
update_section(value, current_path)
elif isinstance(value, list):
# Handle arrays that might contain file paths
for i, item in enumerate(value):
if isinstance(item, dict):
update_section(item, f"{current_path}[{i}]")
self.logger.info("Starting styles path updates...")
update_section(styles_data)
self.logger.info(f"Path update summary: {paths_updated} updated, {paths_failed} failed")
# Write updated styles file
with open(output_styles_path, 'w') as f:
json.dump(styles_data, f, indent=2)
self.logger.info(f"Updated styles file written to: {output_styles_path}")
# Now update font names with correct names that FFmpeg recognizes
if font_files:
self._fix_font_names_in_styles(output_styles_path, font_files)
# Log the content of the updated file for debugging
self.logger.debug("Updated styles file content:")
with open(output_styles_path, 'r') as f:
content = f.read()
# Only log first 1000 chars to avoid spam
self.logger.debug(content[:1000] + ("..." if len(content) > 1000 else ""))
except Exception as e:
self.logger.error(f"Could not update styles paths: {str(e)}")
import traceback
self.logger.error(f"Traceback: {traceback.format_exc()}")
raise
def _install_fonts(self, font_files: List[str]) -> None:
"""
Install font files system-wide so they can be referenced by name in FFmpeg.
"""
import subprocess
try:
# Try to install fonts in multiple directories for maximum compatibility
font_dirs = [
Path.home() / '.fonts',
Path('/usr/share/fonts/truetype/custom'),
Path('/usr/local/share/fonts'),
Path('/tmp/fonts')
]
installed_fonts = []
# Install fonts in all accessible directories
for fonts_dir in font_dirs:
try:
fonts_dir.mkdir(parents=True, exist_ok=True)
self.logger.info(f"Installing fonts in: {fonts_dir}")
for font_file in font_files:
try:
source_path = Path(font_file)
dest_path = fonts_dir / source_path.name
# Copy the font file
shutil.copy2(source_path, dest_path)
if str(dest_path) not in installed_fonts:
installed_fonts.append(str(dest_path))
self.logger.info(f"✓ Installed font: {source_path.name} -> {dest_path}")
except Exception as e:
self.logger.warning(f"Failed to install font {font_file} to {fonts_dir}: {str(e)}")
except PermissionError:
self.logger.info(f"Cannot write to fonts directory: {fonts_dir}")
except Exception as e:
self.logger.warning(f"Error setting up fonts directory {fonts_dir}: {str(e)}")
if installed_fonts:
# Set up environment variables for font discovery
import os
font_paths = [str(Path(f).parent) for f in installed_fonts]
font_paths = list(set(font_paths)) # Remove duplicates
if font_paths:
# Set FONTCONFIG_PATH to help with font discovery
current_fontconfig = os.environ.get('FONTCONFIG_PATH', '')
new_fontconfig = ':'.join(font_paths)
if current_fontconfig:
new_fontconfig = f"{current_fontconfig}:{new_fontconfig}"
os.environ['FONTCONFIG_PATH'] = new_fontconfig
self.logger.info(f"Set FONTCONFIG_PATH to: {new_fontconfig}")
# Refresh the font cache
try:
# Try to run fc-cache to refresh font cache
result = subprocess.run(['fc-cache', '-f'],
capture_output=True, text=True, timeout=30)
if result.returncode == 0:
self.logger.info("✓ Font cache refreshed successfully")
else:
self.logger.warning(f"Font cache refresh had warnings: {result.stderr}")
# List installed fonts for verification
try:
result = subprocess.run(['fc-list'],
capture_output=True, text=True, timeout=10)
if result.returncode == 0:
font_list = result.stdout
for font_file in installed_fonts:
font_name = Path(font_file).stem
if font_name.lower() in font_list.lower():
self.logger.info(f"✓ Verified font is available: {font_name}")
else:
self.logger.warning(f"⚠ Font may not be properly installed: {font_name}")
except Exception as e:
self.logger.debug(f"Could not verify font installation: {str(e)}")
# Additional debugging: Check what FFmpeg sees
try:
self.logger.info("=== FFmpeg Font Debugging ===")
# Test if FFmpeg can find the font by name
ffmpeg_result = subprocess.run([
'ffmpeg', '-hide_banner', '-f', 'lavfi', '-i', 'color=black:size=100x100:duration=1',
'-vf', 'drawtext=text=TEST:fontfile=/root/.fonts/AvenirNext-Bold.ttf:fontsize=24:fontcolor=white',
'-frames:v', '1', '-f', 'null', '-'
], capture_output=True, text=True, timeout=10)
if ffmpeg_result.returncode == 0:
self.logger.info("✓ FFmpeg can access font by file path")
else:
self.logger.warning(f"✗ FFmpeg cannot access font by file path: {ffmpeg_result.stderr}")
# Test if FFmpeg can find the font by name
ffmpeg_result = subprocess.run([
'ffmpeg', '-hide_banner', '-f', 'lavfi', '-i', 'color=black:size=100x100:duration=1',
'-vf', 'drawtext=text=TEST:font=AvenirNext-Bold:fontsize=24:fontcolor=white',
'-frames:v', '1', '-f', 'null', '-'
], capture_output=True, text=True, timeout=10)
if ffmpeg_result.returncode == 0:
self.logger.info("✓ FFmpeg can access font by name")
else:
self.logger.warning(f"✗ FFmpeg cannot access font by name: {ffmpeg_result.stderr}")
# Get actual font name from fc-query
fc_query_result = subprocess.run([
'fc-query', '--format=%{family}\\n', '/root/.fonts/AvenirNext-Bold.ttf'
], capture_output=True, text=True, timeout=10)
if fc_query_result.returncode == 0:
actual_font_name = fc_query_result.stdout.strip()
self.logger.info(f"✓ Actual font family name: '{actual_font_name}'")
# Test with the actual font name
if actual_font_name and actual_font_name != "AvenirNext-Bold":
ffmpeg_result = subprocess.run([
'ffmpeg', '-hide_banner', '-f', 'lavfi', '-i', 'color=black:size=100x100:duration=1',
'-vf', f'drawtext=text=TEST:font={actual_font_name}:fontsize=24:fontcolor=white',
'-frames:v', '1', '-f', 'null', '-'
], capture_output=True, text=True, timeout=10)
if ffmpeg_result.returncode == 0:
self.logger.info(f"✓ FFmpeg can access font by actual name: '{actual_font_name}'")
else:
self.logger.warning(f"✗ FFmpeg cannot access font by actual name '{actual_font_name}': {ffmpeg_result.stderr}")
else:
self.logger.warning(f"Could not query font name: {fc_query_result.stderr}")
# List all fonts that FFmpeg can see
try:
# This uses a trick to get FFmpeg to list all available fonts
ffmpeg_list_result = subprocess.run([
'ffmpeg', '-hide_banner', '-f', 'lavfi', '-i', 'color=black:size=100x100:duration=0.1',
'-vf', 'drawtext=text=:font=ThisFontDoesNotExist:fontsize=1',
'-f', 'null', '-'
], capture_output=True, text=True, timeout=10)
# FFmpeg will error but should list available fonts in stderr
if "unable to find a suitable font" in ffmpeg_list_result.stderr.lower():
self.logger.info("FFmpeg font listing (available fonts mentioned in error):")
# Extract font info from error message
lines = ffmpeg_list_result.stderr.split('\n')
for line in lines:
if 'font' in line.lower() and ('available' in line.lower() or 'found' in line.lower()):
self.logger.info(f" {line.strip()}")
except Exception as e:
self.logger.debug(f"Could not list FFmpeg fonts: {str(e)}")
self.logger.info("=== End FFmpeg Font Debugging ===")
except Exception as e:
self.logger.warning(f"Font debugging failed: {str(e)}")
except subprocess.TimeoutExpired:
self.logger.warning("Font cache refresh timed out")
except FileNotFoundError:
self.logger.warning("fc-cache not found, fonts may not be properly cached")
except Exception as e:
self.logger.warning(f"Error refreshing font cache: {str(e)}")
self.logger.info(f"Successfully installed {len(installed_fonts)} fonts")
else:
self.logger.warning("No fonts were successfully installed")
except Exception as e:
self.logger.error(f"Error installing fonts: {str(e)}")
import traceback
self.logger.error(f"Traceback: {traceback.format_exc()}")
# Don't raise - font installation failure shouldn't stop the job
def _fix_font_names_in_styles(self, styles_file_path: str, installed_font_files: List[str]) -> None:
"""
Update font names in styles JSON to use the actual font names that FFmpeg recognizes.
This is necessary because FFmpeg's font rendering can be sensitive to font names.
"""
import subprocess
try:
with open(styles_file_path, 'r') as f:
styles_data = json.load(f)
# Build a map of font file paths to their actual family names
font_name_map = {}
for font_file in installed_font_files:
try:
result = subprocess.run([
'fc-query', '--format=%{family}\\n', font_file
], capture_output=True, text=True, timeout=10)
if result.returncode == 0:
actual_font_name = result.stdout.strip()
font_name_map[font_file] = actual_font_name
self.logger.info(f"Font file {font_file} -> Font name '{actual_font_name}'")
else:
self.logger.warning(f"fc-query failed for {font_file}: {result.stderr}")
except Exception as e:
self.logger.warning(f"Could not resolve font name for {font_file}: {str(e)}")
fonts_updated = 0
def update_section(section_data, section_path=""):
nonlocal fonts_updated
if isinstance(section_data, dict):
for key, value in section_data.items():
current_path = f"{section_path}.{key}" if section_path else key
# Look for font name fields (not file paths)
if key == 'font' and isinstance(value, str) and value:
# This is a font name field - check if we have a corresponding font_path
font_path_key = 'font_path'
if font_path_key in section_data and section_data[font_path_key]:
font_path = str(section_data[font_path_key]).strip()
# Find matching font in our installed fonts
for font_file, actual_name in font_name_map.items():
if font_path.endswith(Path(font_file).name) or font_file == font_path:
old_name = value
section_data[key] = actual_name
fonts_updated += 1
self.logger.info(f"✓ Updated font name at {current_path}: '{old_name}' -> '{actual_name}'")
break
else:
self.logger.warning(f"Could not find matching font file for {current_path} with path {font_path}")
else:
self.logger.debug(f"No font_path found for font name at {current_path}")
elif isinstance(value, dict):
update_section(value, current_path)
elif isinstance(value, list):
for i, item in enumerate(value):
if isinstance(item, dict):
update_section(item, f"{current_path}[{i}]")
self.logger.info("Starting font name correction in styles...")
update_section(styles_data)
self.logger.info(f"Font name update summary: {fonts_updated} font names updated")
# Write updated styles file
with open(styles_file_path, 'w') as f:
json.dump(styles_data, f, indent=2)
self.logger.info(f"Updated styles file written to: {styles_file_path}")
except Exception as e:
self.logger.error(f"Could not update font names in styles: {str(e)}")
import traceback
self.logger.error(f"Traceback: {traceback.format_exc()}")
# Don't raise - this shouldn't stop the job
def ensure_fonts_available(self, styles_file_path: str) -> None:
"""
Ensure fonts are available in the current environment by re-installing them if needed.
This is useful when ASS generation happens in a different process/context.
"""
try:
if not Path(styles_file_path).exists():
self.logger.warning(f"Styles file not found: {styles_file_path}")
return
self.logger.info("=== Ensuring Fonts Available ===")
# Load styles to find font files
with open(styles_file_path, 'r') as f:
styles_data = json.load(f)
# Find font files referenced in styles
font_files = []
def find_fonts(section_data):
if isinstance(section_data, dict):
for key, value in section_data.items():
if key == 'font_path' and value and str(value).endswith('.ttf'):
font_files.append(str(value))
elif isinstance(value, dict):
find_fonts(value)
find_fonts(styles_data)
if font_files:
self.logger.info(f"Found {len(font_files)} font files to ensure: {font_files}")
# Check if fonts are already available
import subprocess
fonts_need_install = []
for font_file in font_files:
if Path(font_file).exists():
try:
# Check if font is in fc-list
result = subprocess.run(['fc-query', '--format=%{family}\\n', font_file],
capture_output=True, text=True, timeout=5)
if result.returncode == 0:
font_name = result.stdout.strip()
# Check if FFmpeg can access it
ffmpeg_result = subprocess.run([
'ffmpeg', '-hide_banner', '-f', 'lavfi', '-i', 'color=black:size=100x100:duration=0.1',
'-vf', f'drawtext=text=TEST:font={font_name}:fontsize=12',
'-frames:v', '1', '-f', 'null', '-'
], capture_output=True, text=True, timeout=5)
if ffmpeg_result.returncode == 0:
self.logger.info(f"✓ Font available: {font_name} ({Path(font_file).name})")
else:
self.logger.warning(f"⚠ Font not accessible to FFmpeg: {font_name}")
fonts_need_install.append(font_file)
else:
self.logger.warning(f"⚠ Font not in fc-list: {font_file}")
fonts_need_install.append(font_file)
except Exception as e:
self.logger.warning(f"Error checking font {font_file}: {str(e)}")
fonts_need_install.append(font_file)
else:
self.logger.error(f"✗ Font file missing: {font_file}")
# Re-install fonts if needed
if fonts_need_install:
self.logger.info(f"Re-installing {len(fonts_need_install)} fonts")
self._install_fonts(fonts_need_install)
else:
self.logger.info("All fonts are already available")
else:
self.logger.info("No font files found in styles")
self.logger.info("=== Font Availability Check Complete ===")
except Exception as e:
self.logger.error(f"Error ensuring fonts available: {str(e)}")
+250
View File
@@ -0,0 +1,250 @@
# Countdown Padding Implementation - Summary
## Overview
Successfully integrated countdown padding support from the `lyrics-transcriber` library into the karaoke-gen codebase. This ensures that when vocals are padded with a countdown (for songs that start too quickly), all instrumental audio files are automatically synchronized with the same padding.
## Changes Implemented
### 1. LyricsProcessor (`karaoke_gen/lyrics_processor.py`)
**Changes Made:**
- Modified `transcribe_lyrics()` method to capture countdown padding information from `LyricsControllerResult`
- Added three new fields to the return dictionary:
- `countdown_padding_added` (bool): Whether padding was applied
- `countdown_padding_seconds` (float): Amount of padding (typically 3.0 seconds)
- `padded_audio_filepath` (str): Path to the padded vocal audio file
**Implementation Details:**
```python
# Lines 289-298
transcriber_outputs["countdown_padding_added"] = getattr(results, "countdown_padding_added", False)
transcriber_outputs["countdown_padding_seconds"] = getattr(results, "countdown_padding_seconds", 0.0)
transcriber_outputs["padded_audio_filepath"] = getattr(results, "padded_audio_filepath", None)
if transcriber_outputs["countdown_padding_added"]:
self.logger.info(
f"Countdown padding detected: {transcriber_outputs['countdown_padding_seconds']}s added to vocals. "
f"Instrumental audio will need to be padded accordingly."
)
```
**Why getattr():** Uses `getattr()` with defaults to maintain backward compatibility with older versions of lyrics-transcriber that don't have these fields.
### 2. AudioProcessor (`karaoke_gen/audio_processor.py`)
**New Methods Added:**
#### `pad_audio_file(input_audio, output_audio, padding_seconds)`
- **Purpose:** Pads an audio file with silence at the start using ffmpeg
- **Implementation:** Uses the exact same ffmpeg approach as lyrics-transcriber
- **Error Handling:** Handles subprocess errors and timeouts gracefully
- **Lines:** 55-107
**Key Features:**
- Uses `anullsrc` to generate silence
- Uses `concat` filter to prepend silence to audio
- Preserves audio quality with lossless format
- 5-minute timeout for safety
- Comprehensive error logging
#### `apply_countdown_padding_to_instrumentals(separation_result, padding_seconds, artist_title, track_output_dir)`
- **Purpose:** Applies padding to all instrumental files in a separation result
- **Implementation:** Pads clean instrumental and all combined instrumentals
- **Lines:** 775-838
**What Gets Padded:**
1. Clean instrumental track
2. All combined instrumentals (instrumental + backing vocals for each model)
**What Doesn't Get Padded:**
- Backing vocals (not used in final output)
- Other stems (drums, bass, etc. - not used in final output)
- Vocal tracks (already padded by lyrics-transcriber)
**Naming Convention:**
- Padded files are named with "(Padded)" inserted before the file extension
- Example: `Artist - Song (Instrumental model.ckpt).flac` → `Artist - Song (Instrumental model.ckpt) (Padded).flac`
### 3. KaraokeGen (`karaoke_gen/karaoke_gen.py`)
**Changes Made:**
#### Transcription Result Handling (Lines 487-499)
- Captures countdown padding information from transcription results
- Stores padding info in `processed_track` dictionary
- Logs clear warning when countdown padding is detected
#### Skip Lyrics Edge Case (Lines 395-398)
- Initializes padding fields to False/0.0 when lyrics are skipped
- Prevents errors in downstream code
#### Existing Instrumental Handling (Lines 604-619)
- When a custom instrumental is provided AND countdown padding was detected:
- Pads the custom instrumental with the same padding_seconds
- Updates the path to use the padded version
- Ensures synchronization with vocals
#### Post-Separation Padding (Lines 614-637)
- After audio separation completes, checks if countdown padding was added
- If padding was detected:
- Calls `apply_countdown_padding_to_instrumentals()`
- Updates `processed_track["separated_audio"]` with padded file paths
- Ensures all downstream code uses the padded files
## Testing
### Test Coverage
Created comprehensive unit tests in `tests/unit/test_countdown_padding.py`:
**13 tests total, all passing:**
1. **TestPadAudioFile** (3 tests)
- `test_pad_audio_file_success`: Verifies ffmpeg is called correctly
- `test_pad_audio_file_failure`: Tests error handling
- `test_pad_audio_file_timeout`: Tests timeout handling
2. **TestApplyCountdownPaddingToInstrumentals** (4 tests)
- `test_apply_padding_to_clean_instrumental`: Verifies clean instrumental padding
- `test_apply_padding_to_combined_instrumentals`: Verifies all combined instrumentals are padded
- `test_skip_padding_if_file_exists`: Verifies idempotency (skips if already padded)
- `test_preserve_structure_with_empty_separation`: Tests edge case with no files
3. **TestLyricsProcessorIntegration** (2 tests)
- `test_lyrics_processor_captures_padding_info`: Verifies padding info capture
- `test_lyrics_processor_handles_no_padding`: Tests backward compatibility
4. **TestKaraokeGenIntegration** (3 tests)
- `test_karaoke_gen_applies_padding_when_detected`: End-to-end padding application
- `test_karaoke_gen_skips_padding_when_not_needed`: Verifies no unnecessary padding
- `test_skip_lyrics_initializes_padding_fields`: Tests edge case
5. **TestExistingInstrumentalPadding** (1 test)
- `test_custom_instrumental_padding_logic`: Tests custom instrumental padding
### Running Tests
```bash
cd /Users/andrew/Projects/karaoke-gen
python -m pytest tests/unit/test_countdown_padding.py -v
```
## Workflow
### Normal Flow (No Countdown Padding)
1. Transcribe lyrics → No padding detected
2. Separate audio → Original instrumental files created
3. Use original files in final output
### With Countdown Padding
1. Transcribe lyrics → Countdown padding detected (3 seconds added to vocals)
2. Separate audio → Original instrumental files created
3. **Apply padding** → Create padded versions of all instrumentals
4. Update file paths → Point to padded versions
5. Use padded files in final output → Everything stays synchronized
### Edge Cases Handled
1. **Lyrics Skipped:** Padding fields initialized to False/0.0
2. **Custom Instrumental:** Padded along with vocals
3. **Files Already Exist:** Skips re-padding (idempotent)
4. **Backward Compatibility:** Works with old lyrics-transcriber versions
## File Naming
### Before Padding
```
Artist - Song (Instrumental model.ckpt).flac
Artist - Song (Instrumental +BV model.ckpt).flac
```
### After Padding
```
Artist - Song (Instrumental model.ckpt) (Padded).flac
Artist - Song (Instrumental +BV model.ckpt) (Padded).flac
```
**Original files are preserved** - padded versions are created as new files.
## Benefits
1. **Automatic Synchronization:** No manual intervention needed
2. **Audio Quality Preservation:** Uses lossless formats throughout
3. **Comprehensive:** Pads all instrumental variants
4. **Idempotent:** Safe to run multiple times
5. **Backward Compatible:** Works with old lyrics-transcriber versions
6. **Well Tested:** 13 comprehensive unit tests
7. **Well Logged:** Clear logging at every step
## Integration with Downstream Tools
### KaraokeFinalise
The `remux_with_instrumental()` method in `karaoke_finalise.py` will automatically use the padded instrumental files when they exist, since the paths in `processed_track["separated_audio"]` are updated to point to the padded versions.
### Manual Usage
Users can also manually select the padded instrumental files (identifiable by "(Padded)" in the filename) when creating final videos.
## Troubleshooting
### Issue: Countdown in video but instrumental out of sync
**Solution:** Verify that padded instrumental files were created. Check logs for:
```
=== COUNTDOWN PADDING DETECTED ===
Applying Xs padding to all instrumental files
```
### Issue: Padding applied when it shouldn't be
**Solution:** Check that `countdown_padding_added` is being set correctly by lyrics-transcriber. This is a boolean flag that should only be True when vocals actually start within 3 seconds.
### Issue: Padded files not being used
**Solution:** Verify that the `processed_track["separated_audio"]` dictionary contains paths with "(Padded)" in them after the padding step runs.
## Code Quality
### SOLID Principles Applied
1. **Single Responsibility Principle (SRP)**
- `pad_audio_file()`: Only handles audio padding
- `apply_countdown_padding_to_instrumentals()`: Only orchestrates padding application
- Each method has a clear, single purpose
2. **Open/Closed Principle (OCP)**
- New functionality added without modifying existing separation logic
- Padding is applied as a post-processing step
- Existing code works unchanged if padding is not needed
3. **Liskov Substitution Principle (LSP)**
- Padded audio files are drop-in replacements for original files
- Same format, same structure, just with added silence at start
4. **Interface Segregation Principle (ISP)**
- Each method has a focused interface with only necessary parameters
- Callers don't need to know about internal padding implementation
5. **Dependency Inversion Principle (DIP)**
- Uses ffmpeg abstraction (subprocess) rather than direct file manipulation
- AudioProcessor methods can be mocked/stubbed for testing
### Best Practices
- **Error Handling:** Comprehensive try/catch blocks with clear error messages
- **Logging:** Detailed logging at INFO level for user visibility
- **Type Safety:** Clear parameter types in docstrings
- **Idempotency:** Safe to run multiple times (checks for existing files)
- **Testability:** All methods are easily testable with mocks
- **Documentation:** Clear docstrings explaining purpose and behavior
## Future Enhancements (Optional)
1. **Configurable Padding Amount:** Allow users to specify padding amount
2. **Padding Other Stems:** Option to pad backing vocals, drums, bass, etc.
3. **Padding Verification:** Automated check that padded files have correct duration
4. **Padding Metadata:** Store padding info in a metadata file for reference
## References
- Implementation guide: `COUNTDOWN_INTEGRATION_EXAMPLE.md`
- Test file: `tests/unit/test_countdown_padding.py`
- Modified files:
- `karaoke_gen/lyrics_processor.py`
- `karaoke_gen/audio_processor.py`
- `karaoke_gen/karaoke_gen.py`
+220
View File
@@ -0,0 +1,220 @@
# Countdown Padding Integration - Quick Start Guide
## What Was Implemented
The karaoke-gen system now automatically synchronizes instrumental audio with vocals when the `lyrics-transcriber` library adds countdown padding (3 seconds of silence for songs that start too quickly).
## Key Features
✅ **Automatic Detection** - Detects when countdown padding has been applied to vocals
✅ **Automatic Synchronization** - Pads all instrumental tracks by the same amount
✅ **Multiple File Support** - Handles clean instrumental + all combined instrumental variants
✅ **Custom Instrumental Support** - Works with user-provided instrumental files
✅ **Idempotent** - Safe to run multiple times (won't re-pad existing padded files)
✅ **Backward Compatible** - Works with old versions of lyrics-transcriber
✅ **Well Tested** - 13 comprehensive unit tests, all passing
✅ **SOLID Principles** - Clean, maintainable code following best practices
## How It Works
### Normal Song (No Padding Needed)
```
1. Transcribe vocals → No padding applied
2. Separate audio → Create instrumental files
3. Generate karaoke → Use original files ✓
```
### Song Starting Too Quickly (Padding Applied)
```
1. Transcribe vocals → 3s countdown added to vocals
2. Separate audio → Create instrumental files
3. Apply padding → Create padded instrumental files (+3s silence)
4. Generate karaoke → Use padded files ✓
→ Vocals and instrumental stay synchronized!
```
## Files Modified
### Core Implementation
- `karaoke_gen/lyrics_processor.py` - Captures padding info from lyrics-transcriber
- `karaoke_gen/audio_processor.py` - New methods for audio padding
- `karaoke_gen/karaoke_gen.py` - Orchestrates padding application
### Tests
- `tests/unit/test_countdown_padding.py` - 13 comprehensive unit tests
### Documentation
- `COUNTDOWN_INTEGRATION_EXAMPLE.md` - Original reference implementation
- `COUNTDOWN_PADDING_IMPLEMENTATION.md` - Detailed implementation notes
- `COUNTDOWN_PADDING_QUICKSTART.md` - This file
## What Gets Padded
✅ **Clean Instrumental** - The main instrumental track
✅ **Combined Instrumentals** - Instrumental + backing vocals variants
❌ Backing vocals alone (not used in final output)
❌ Other stems like drums, bass (not used in final output)
❌ Vocals (already padded by lyrics-transcriber)
## File Naming Convention
### Before Padding
```
Artist - Song (Instrumental model.ckpt).flac
Artist - Song (Instrumental +BV model.ckpt).flac
```
### After Padding
```
Artist - Song (Instrumental model.ckpt) (Padded).flac ← New file created
Artist - Song (Instrumental +BV model.ckpt) (Padded).flac ← New file created
```
**Note:** Original files are preserved. Padded versions are created as new files.
## Logging Output
When countdown padding is detected, you'll see:
```
=== COUNTDOWN PADDING DETECTED ===
Vocals have been padded with 3.0s of silence. Instrumental tracks will be padded after separation to maintain synchronization.
=== APPLYING COUNTDOWN PADDING TO INSTRUMENTALS ===
Applying 3.0s padding to all instrumental files to sync with vocal countdown
Padding audio file with 3.0s of silence: /path/to/instrumental.flac
Successfully padded audio file: /path/to/instrumental_padded.flac
✓ Countdown padding applied to 2 instrumental file(s)
✓ All instrumental files have been padded and are now synchronized with vocals
```
## Testing
### Run All Countdown Padding Tests
```bash
cd /Users/andrew/Projects/karaoke-gen
python -m pytest tests/unit/test_countdown_padding.py -v
```
### Expected Output
```
13 passed in 0.6s
```
## Usage Examples
### Scenario 1: Normal Workflow
```python
from karaoke_gen import KaraokePrep
prep = KaraokePrep(
input_media="song.mp3",
artist="Artist Name",
title="Song Title",
)
result = await prep.prep_single_track()
# If countdown padding was added:
if result["countdown_padding_added"]:
print(f"Countdown padding: {result['countdown_padding_seconds']}s")
print(f"Padded vocal file: {result['padded_vocals_audio']}")
print(f"Padded instrumental: {result['separated_audio']['clean_instrumental']['instrumental']}")
# The padded instrumental path will contain "(Padded)" in the filename
```
### Scenario 2: With Custom Instrumental
```python
prep = KaraokePrep(
input_media="song.mp3",
artist="Artist Name",
title="Song Title",
existing_instrumental="my_custom_instrumental.flac", # Your custom file
)
result = await prep.prep_single_track()
# Your custom instrumental will be automatically padded if countdown was added
# Result will contain the padded custom instrumental path
```
## Troubleshooting
### Issue: Countdown appears in video but instrumental is out of sync
**Check:**
1. Look for `=== COUNTDOWN PADDING DETECTED ===` in logs
2. Verify padded instrumental files were created (check for "(Padded)" in filenames)
3. Verify the padded files are being used in final output
**Solution:** If padded files exist but aren't being used, check that `processed_track["separated_audio"]` contains the padded paths.
### Issue: Padding applied when it shouldn't be
**Check:** Look at the `countdown_padding_added` flag in the result.
**Solution:** This flag comes from lyrics-transcriber. If it's incorrectly set to True, that's an upstream issue in the lyrics-transcriber library.
### Issue: Custom instrumental not getting padded
**Check:** Make sure you're providing `existing_instrumental` parameter AND countdown padding is detected.
**Solution:** The code automatically handles this case. If it's not working, check the logs for errors during the padding step.
## Technical Details
### FFmpeg Command Used
```bash
ffmpeg -y -hide_banner -loglevel error \
-f lavfi -t 3.0 -i anullsrc=channel_layout=stereo:sample_rate=44100 \
-i input_audio.flac \
-filter_complex "[0:a][1:a]concat=n=2:v=0:a=1[out]" \
-map "[out]" \
-c:a flac \
output_padded.flac
```
This prepends 3 seconds of silence to the input audio while preserving quality.
### Data Flow
```
LyricsTranscriber.process()
↓ (returns LyricsControllerResult with padding info)
LyricsProcessor.transcribe_lyrics()
↓ (captures padding info)
KaraokeGen.prep_single_track()
↓ (detects padding)
AudioProcessor.apply_countdown_padding_to_instrumentals()
↓ (pads all instrumentals)
Final Output (synchronized audio!)
```
## Code Quality Highlights
✅ **Single Responsibility** - Each function does one thing well
✅ **Error Handling** - Comprehensive error handling with clear messages
✅ **Logging** - Detailed logging for debugging and monitoring
✅ **Testing** - 13 unit tests covering all scenarios
✅ **Documentation** - Clear docstrings and inline comments
✅ **Backward Compatibility** - Works with old lyrics-transcriber versions
✅ **Idempotency** - Safe to run multiple times
## Next Steps
1. **Test with Real Songs**: Try with a song that starts cold (vocals within first 3 seconds)
2. **Verify Synchronization**: Check that countdown appears and audio is synchronized
3. **Monitor Logs**: Watch for padding detection and application messages
4. **Report Issues**: If anything doesn't work as expected, check logs first
## Need More Details?
- **Full Implementation Details**: See `COUNTDOWN_PADDING_IMPLEMENTATION.md`
- **Reference Implementation**: See `COUNTDOWN_INTEGRATION_EXAMPLE.md`
- **Test Code**: See `tests/unit/test_countdown_padding.py`
## Summary
The countdown padding integration is complete, tested, and ready to use. It automatically handles synchronization between vocals and instrumentals when countdown padding is applied, requiring no manual intervention from users.
**Status: ✅ Complete and Production-Ready**
+7
View File
@@ -0,0 +1,7 @@
# Playwright
node_modules/
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/
+1
View File
@@ -0,0 +1 @@
gen.nomadkaraoke.com
+141
View File
@@ -0,0 +1,141 @@
# Karaoke Generator Frontend
This is the static frontend for the Karaoke Generator web application. It's designed to be deployed on GitHub Pages with a custom domain.
## Architecture
- **Frontend**: Static HTML/CSS/JS hosted on GitHub Pages → `gen.nomadkaraoke.com`
- **Backend**: Modal API endpoints → `nomadkaraoke--karaoke-generator-webapp-api-endpoint.modal.run/api`
## Files
- `index.html` - Main application page
- `styles.css` - All CSS styles and responsive design
- `app.js` - JavaScript application logic and API communication
- `README.md` - This file
## Features
- 🎵 YouTube URL submission for karaoke generation
- 📊 Real-time job monitoring with progress bars
- 📋 Comprehensive logging and admin controls
- 📝 Lyrics review interface
- 📥 Video download functionality
- 🔧 Admin panel for job management
- 📱 Responsive mobile design
## Deployment to GitHub Pages
### 1. Create GitHub Repository
```bash
# Initialize git repository
cd frontend
git init
git add .
git commit -m "Initial frontend setup"
# Create GitHub repository and push
git remote add origin https://github.com/YOUR_USERNAME/karaoke-gen-frontend.git
git branch -M main
git push -u origin main
```
### 2. Enable GitHub Pages
1. Go to your repository on GitHub
2. Click **Settings** tab
3. Scroll to **Pages** section
4. Under **Source**, select **Deploy from a branch**
5. Choose **main** branch and **/ (root)** folder
6. Click **Save**
### 3. Configure Custom Domain
1. In the **Pages** section, add your custom domain: `gen.nomadkaraoke.com`
2. Enable **Enforce HTTPS**
### 4. DNS Configuration (Cloudflare)
Add a CNAME record in your Cloudflare DNS:
```
Type: CNAME
Name: gen
Target: YOUR_USERNAME.github.io
Proxy status: Proxied (orange cloud)
```
## Development
### Local Testing
You can test the frontend locally using Python's built-in server:
```bash
cd frontend
python -m http.server 8000
```
Then visit `http://localhost:8000`
### API Configuration
The API endpoint is configured in `app.js`:
```javascript
const API_BASE_URL = 'https://nomadkaraoke--karaoke-generator-webapp-api-endpoint.modal.run/api';
```
Update this URL if your Modal deployment changes.
## Features Overview
### Job Management
- Submit YouTube URLs for processing
- Monitor job progress in real-time
- View detailed logs for each job
- Delete, retry, or download completed jobs
### Admin Controls
- Clear error jobs in bulk
- Export all logs as JSON
- Real-time statistics dashboard
- Auto-refresh functionality
### Responsive Design
- Mobile-friendly interface
- Progressive enhancement
- Modern CSS with gradients and animations
- Accessible design patterns
## Browser Support
- Chrome/Chromium 80+
- Firefox 75+
- Safari 13+
- Edge 80+
## Security Notes
- CORS is configured on the backend to allow requests from your domain
- All API communication uses HTTPS
- No sensitive data is stored in the frontend
- GitHub Pages provides automatic HTTPS with custom domains
## Troubleshooting
### API Connection Issues
1. Check that the Modal backend is running
2. Verify the API_BASE_URL in app.js
3. Check browser console for CORS errors
### GitHub Pages Not Updating
1. Check the Actions tab for deployment status
2. Ensure all files are committed and pushed
3. Wait 5-10 minutes for propagation
### Custom Domain Issues
1. Verify DNS settings in Cloudflare
2. Ensure CNAME record points to YOUR_USERNAME.github.io
3. Enable HTTPS enforcement in GitHub Pages settings
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

+7817
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 604 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

+555
View File
@@ -0,0 +1,555 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Nomad Karaoke Generator</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<!-- Authentication Section (shown when not authenticated) -->
<section id="auth-section" class="auth-section" style="display: none;">
<div class="auth-container">
<header class="auth-header">
<h1>🎤 Karaoke Generator</h1>
<p>Enter your access token to get started</p>
</header>
<div class="auth-form-container">
<form id="auth-form" class="auth-form">
<div class="form-group">
<label for="access-token">Access Token</label>
<input type="text" id="access-token" class="form-control" placeholder="Enter your access token" required>
<small class="help-text">If you don't have an access token, contact support or check your purchase confirmation.</small>
</div>
<button type="submit" class="auth-btn">
🔓 Access Karaoke Generator
</button>
</form>
<div class="auth-help">
<h3>Need an access token?</h3>
<p>Access tokens are provided when you:</p>
<ul>
<li>Purchase access through our payment portal</li>
<li>Receive a promo code from Nomad Karaoke</li>
<li>Are granted admin access</li>
</ul>
<p>Contact <a href="mailto:support@nomadkaraoke.com">support@nomadkaraoke.com</a> if you need help.</p>
</div>
</div>
</div>
</section>
<!-- Main Application (shown when authenticated) -->
<div id="main-app" style="display: none;">
<!-- User Status Bar -->
<div class="user-status-bar">
<div class="user-info">
<span class="user-type" id="user-type-display"></span>
<span class="user-remaining" id="user-remaining-display"></span>
</div>
<div class="user-actions">
<button onclick="showUserInfo()" class="btn btn-link">ℹ️ Account Info</button>
<button onclick="logout()" class="btn btn-secondary">🚪 Logout</button>
</div>
</div>
<!-- Header -->
<header class="header">
<div class="header-content">
<img src="nomad-karaoke-logo.png" alt="Nomad Karaoke Logo" class="header-logo">
<div class="header-text">
<h1>Karaoke Generator</h1>
<p>Transform audio files into professional karaoke videos with synchronized lyrics!</p>
</div>
</div>
</header>
<!-- Submit New Job Section -->
<section class="submit-section">
<h2>🎵 Submit a New Job</h2>
<form id="job-form" class="job-form">
<!-- Input Mode Selection -->
<div class="input-mode-selection">
<div class="input-mode-tabs">
<button type="button" id="file-mode-tab" class="input-mode-tab active" onclick="switchInputMode('file')">
📁 Upload File
</button>
<button type="button" id="youtube-mode-tab" class="input-mode-tab" onclick="switchInputMode('youtube')">
📺 YouTube URL
</button>
</div>
</div>
<!-- File Upload Mode -->
<div id="file-upload-mode" class="input-mode-section active">
<div class="primary-fields">
<div class="name-fields-row">
<div class="form-group">
<label for="artist">Artist Name</label>
<input type="text" id="artist" class="form-control" placeholder="Enter artist name" required>
</div>
<div class="form-group">
<label for="title">Song Title</label>
<input type="text" id="title" class="form-control" placeholder="Enter song title" required>
</div>
<div class="form-group">
<label for="loadexample">Load Example</label>
<button id="loadexample" type="button" onclick="loadExampleData()" class="example-btn">
🎵 ABBA - Waterloo<br><small>(30 second clip)</small></small>
</button>
</div>
</div>
<div class="file-upload">
<label for="audio-file">Audio File (MP3, WAV, FLAC, etc.)</label>
<input type="file" id="audio-file" accept="audio/*" required>
<small>Upload the original audio file you want to convert to karaoke, in the highest quality possible (ideally lossless 24bit FLAC)</small>
</div>
</div>
</div>
<!-- YouTube URL Mode -->
<div id="youtube-url-mode" class="input-mode-section">
<div class="primary-fields">
<div class="url-input-section">
<div class="form-group">
<label for="youtube-url">YouTube URL</label>
<input type="url" id="youtube-url" class="form-control" placeholder="https://www.youtube.com/watch?v=..." oninput="handleYouTubeUrlChange()">
<small>Enter a YouTube URL and we'll automatically extract the artist and title</small>
</div>
</div>
<div class="name-fields-row">
<div class="form-group">
<label for="youtube-artist">Artist Name</label>
<input type="text" id="youtube-artist" class="form-control" placeholder="Will be auto-populated from URL">
<small>Auto-extracted from YouTube - edit if needed</small>
</div>
<div class="form-group">
<label for="youtube-title">Song Title</label>
<input type="text" id="youtube-title" class="form-control" placeholder="Will be auto-populated from URL">
<small>Auto-extracted from YouTube - edit if needed</small>
</div>
<div class="loading-status">
<div id="metadata-loading" class="metadata-loading" style="display: none;">
🔄 Extracting metadata...
</div>
<div id="metadata-status" class="metadata-status"></div>
</div>
</div>
</div>
</div>
<!-- Styles Configuration -->
<div class="styles-section">
<div class="styles-header">
<div class="styles-info">
<h3>🎨 Styling</h3>
<p>Using Nomad Default Styles for professional karaoke appearance</p>
</div>
<button type="button" id="customize-styles-btn" onclick="toggleCustomStyles()" class="btn btn-secondary">
🎛️ Customize Styles
</button>
</div>
<div id="custom-styles-section" class="custom-styles-section" style="display: none;">
<div class="file-upload">
<label for="styles-file">Styles JSON File (optional)</label>
<input type="file" id="styles-file" name="styles-file" accept=".json" class="form-control">
<div class="form-actions">
<button type="button" class="btn btn-link" onclick="loadDefaultStyles()">
📁 Load Nomad Default Styles
</button>
</div>
</div>
<div class="form-group">
<label for="styles-archive">Styles Assets Archive (optional)</label>
<input type="file" id="styles-archive" name="styles-archive" accept=".zip" class="form-control">
<small class="help-text">Upload a ZIP file containing fonts, images, and other assets referenced in the styles JSON</small>
</div>
</div>
</div>
<button type="submit" class="submit-btn">
🎤 Generate Karaoke
</button>
</form>
</section>
<!-- Statistics Cards -->
<section class="stats-section">
<div class="stats-grid">
<div class="stat-card">
<div class="stat-number" id="stat-total">0</div>
<div class="stat-label">Total Jobs</div>
</div>
<div class="stat-card">
<div class="stat-number" id="stat-processing">0</div>
<div class="stat-label">Processing</div>
</div>
<div class="stat-card">
<div class="stat-number" id="stat-awaiting-review">0</div>
<div class="stat-label">Awaiting Review</div>
</div>
<div class="stat-card">
<div class="stat-number" id="stat-complete">0</div>
<div class="stat-label">Complete</div>
</div>
<div class="stat-card">
<div class="stat-number" id="stat-errors">0</div>
<div class="stat-label">Errors</div>
</div>
</div>
</section>
<!-- Jobs -->
<section class="jobs-section">
<div class="section-header">
<h2>Jobs</h2>
<div class="auto-refresh-control">
<label>
<input type="checkbox" id="auto-refresh" checked>
Auto-refresh (5s)
</label>
</div>
</div>
<div id="jobs-list" class="jobs-list">
<div class="loading">Loading jobs...</div>
</div>
</section>
<!-- Admin Panel (Floating) - Only shown for admin users -->
<div class="admin-panel" id="admin-panel" style="display: none;">
<button class="admin-toggle" onclick="toggleAdminPanel()">
⚙️ Admin
</button>
<div class="admin-content">
<h3>🔧 Admin Controls</h3>
<div class="admin-buttons">
<button onclick="showTokenManagement()" class="btn btn-primary">
🎫 Manage Tokens
</button>
<button onclick="showCookieManagement()" class="btn btn-primary">
🍪 Manage YouTube Cookies
</button>
<button onclick="showDeliveryMessageTemplate()" class="btn btn-primary">
📧 Delivery Message Template
</button>
<button onclick="showLogLevelSettings()" class="btn btn-primary">
🔍 Log Level Settings
</button>
<button onclick="showManualStatusUpdate()" class="btn btn-primary">
⚙️ Manual Status Update
</button>
<button onclick="refreshData()" class="btn btn-primary">
🔄 Refresh Data
</button>
<button onclick="viewCacheStats()" class="btn btn-info">
💾 Cache Stats
</button>
<button onclick="clearErrorJobs()" class="btn btn-danger">
🗑️ Clear Error Jobs
</button>
<button onclick="exportLogs()" class="btn btn-secondary">
📤 Export Logs
</button>
</div>
</div>
</div>
<!-- Footer -->
<footer class="footer">
<p>Made with ❤️ by <a href="https://nomadkaraoke.com" target="_blank">Nomad Karaoke</a></p>
</footer>
</div>
</div>
<!-- User Info Modal -->
<div id="user-info-modal" class="modal">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title">👤 Account Information</h3>
<div class="modal-controls">
<button onclick="closeUserInfoModal()" class="modal-close">✕</button>
</div>
</div>
<div class="modal-body">
<div id="user-info-content" class="user-info-content">
<!-- User info will be populated here -->
</div>
</div>
</div>
</div>
<!-- Token Management Modal (Admin Only) -->
<div id="token-management-modal" class="modal">
<div class="modal-content token-modal-content">
<div class="modal-header">
<h3 class="modal-title">🎫 Token Management</h3>
<div class="modal-controls">
<button onclick="closeTokenManagementModal()" class="modal-close">✕</button>
</div>
</div>
<div class="modal-body">
<div id="token-management-content" class="token-management-content">
<div class="token-loading">Loading tokens...</div>
</div>
</div>
</div>
</div>
<!-- Cookie Management Modal (Admin Only) -->
<div id="cookie-management-modal" class="modal">
<div class="modal-content cookie-modal-content">
<div class="modal-header">
<h3 class="modal-title">🍪 YouTube Cookie Management</h3>
<div class="modal-controls">
<button onclick="closeCookieManagementModal()" class="modal-close">✕</button>
</div>
</div>
<div class="modal-body">
<div id="cookie-management-content" class="cookie-management-content">
<div class="cookie-loading">Loading cookie settings...</div>
</div>
</div>
</div>
</div>
<!-- Delivery Message Template Modal (Admin Only) -->
<div id="delivery-message-template-modal" class="modal">
<div class="modal-content delivery-template-modal-content">
<div class="modal-header">
<h3 class="modal-title">📧 Delivery Message Template</h3>
<div class="modal-controls">
<button onclick="closeDeliveryMessageTemplateModal()" class="modal-close">✕</button>
</div>
</div>
<div class="modal-body">
<div id="delivery-message-template-content" class="delivery-template-content">
<div class="delivery-template-loading">Loading template...</div>
</div>
</div>
</div>
</div>
<!-- Manual Status Update Modal (Admin Only) -->
<div id="manual-status-update-modal" class="modal">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title">⚙️ Manual Status Update</h3>
<div class="modal-controls">
<button onclick="closeManualStatusUpdateModal()" class="modal-close">✕</button>
</div>
</div>
<div class="modal-body">
<form id="manual-status-update-form" class="manual-status-update-form">
<div class="form-group">
<label for="status-update-job-id">Job ID</label>
<input type="text" id="status-update-job-id" class="form-control" placeholder="Enter job ID (e.g., 12345678)" required>
<small class="help-text">The 8-character job ID you want to update</small>
</div>
<!-- Preset Scenarios -->
<div class="form-group">
<label>Quick Presets</label>
<div class="preset-buttons">
<button type="button" class="btn btn-small btn-warning" onclick="setStatusPreset('phase1_timeout')">
<i class="fas fa-clock"></i> Phase 1 Timeout
</button>
<button type="button" class="btn btn-small btn-warning" onclick="setStatusPreset('phase2_timeout')">
<i class="fas fa-clock"></i> Phase 2 Timeout
</button>
<button type="button" class="btn btn-small btn-warning" onclick="setStatusPreset('phase3_timeout')">
<i class="fas fa-clock"></i> Phase 3 Timeout
</button>
<button type="button" class="btn btn-small btn-danger" onclick="setStatusPreset('processing_error')">
<i class="fas fa-exclamation-triangle"></i> Processing Error
</button>
<button type="button" class="btn btn-small btn-success" onclick="setStatusPreset('force_complete')">
<i class="fas fa-check"></i> Force Complete
</button>
<button type="button" class="btn btn-small btn-info" onclick="setStatusPreset('reset_queued')">
<i class="fas fa-undo"></i> Reset to Queued
</button>
<button type="button" class="btn btn-small btn-info" onclick="setStatusPreset('await_review')">
<i class="fas fa-eye"></i> Set Awaiting Review
</button>
<button type="button" class="btn btn-small btn-info" onclick="setStatusPreset('ready_final')">
<i class="fas fa-video"></i> Ready for Final
</button>
</div>
<small class="help-text">Click a preset to auto-fill the form with realistic values for common scenarios</small>
</div>
<div class="form-group">
<label for="status-update-new-status">New Status</label>
<select id="status-update-new-status" class="form-control" required>
<option value="">Select new status...</option>
<option value="queued">⏳ Queued</option>
<option value="processing">⚙️ Processing</option>
<option value="awaiting_review">👀 Awaiting Review</option>
<option value="reviewing">✏️ Reviewing</option>
<option value="ready_for_finalization">🎬 Ready for Finalization</option>
<option value="rendering">🎨 Rendering</option>
<option value="finalizing">🎯 Finalizing</option>
<option value="complete">✅ Complete</option>
<option value="error">❌ Error</option>
<option value="timeout">⏰ Timeout</option>
<option value="cancelled">🚫 Cancelled</option>
</select>
<small class="help-text">Choose the status you want to set for this job</small>
</div>
<div class="form-group">
<label for="status-update-progress">Progress (0-100)</label>
<input type="number" id="status-update-progress" class="form-control" min="0" max="100" placeholder="Optional progress percentage">
<small class="help-text">Optional: Set a progress percentage (0-100)</small>
</div>
<div class="form-group">
<label for="status-update-additional-data">Additional Data (JSON)</label>
<textarea id="status-update-additional-data" class="form-control" rows="4" placeholder='{"error": "Custom error message", "custom_field": "value"}'></textarea>
<small class="help-text">Optional: JSON object with additional fields to set on the job</small>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">
🔄 Update Job Status
</button>
<button type="button" onclick="closeManualStatusUpdateModal()" class="btn btn-secondary">
Cancel
</button>
</div>
<div class="status-update-result" id="status-update-result" style="display: none;">
<!-- Result will be displayed here -->
</div>
</form>
</div>
</div>
</div>
<!-- Log Tail Modal -->
<div id="log-tail-modal" class="modal">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title">Log Tail - Job <span id="modal-job-id"></span></h3>
<div class="modal-controls">
<button onclick="decreaseFontSize()" class="modal-control-btn" title="Decrease font size">A-</button>
<button onclick="increaseFontSize()" class="modal-control-btn" title="Increase font size">A+</button>
<button onclick="scrollToBottom()" class="modal-control-btn secondary" title="Scroll to bottom">⬇️</button>
<button onclick="copyLogsToClipboard()" class="modal-control-btn secondary" title="Copy all logs to clipboard">📋 Copy</button>
<button onclick="toggleAutoScroll()" class="modal-control-btn toggle-active" id="auto-scroll-btn" title="Toggle auto-scroll">🔄 Auto</button>
<button onclick="toggleLogAutoRefresh()" class="modal-control-btn toggle-active" id="log-auto-refresh-btn" title="Toggle automatic log refresh">🔄 Refresh</button>
<button onclick="closeLogTailModal()" class="modal-close">✕</button>
</div>
</div>
<!-- Log Filter Bar (Server-side Filtering) -->
<div class="log-filter-bar">
<div class="filter-row">
<div class="filter-group">
<label class="filter-label">🔍 Include:</label>
<input type="text" id="log-include-filter" class="filter-input" placeholder="Include logs containing..." oninput="applyLogFilters()">
</div>
<div class="filter-group">
<label class="filter-label">🚫 Exclude:</label>
<input type="text" id="log-exclude-filter" class="filter-input" placeholder="Exclude logs containing..." oninput="applyLogFilters()">
</div>
<div class="filter-group">
<label class="filter-label">📊 Level:</label>
<select id="log-level-filter" onchange="applyLogFilters()" class="filter-level-select">
<option value="">All Levels</option>
<option value="DEBUG">DEBUG+ (all levels)</option>
<option value="INFO">INFO+ (info, warning, error, critical)</option>
<option value="WARNING">WARNING+ (warning, error, critical)</option>
<option value="ERROR">ERROR+ (error, critical)</option>
<option value="CRITICAL">CRITICAL only</option>
</select>
</div>
<div class="filter-group">
<label class="filter-label">📄 Limit:</label>
<input type="number" id="log-limit-input" class="filter-limit-input" value="1000" min="10" max="10000" step="100" onchange="applyLogFilters()" title="Maximum number of logs to show">
<div class="limit-presets">
<button onclick="setLogLimit(100)" class="limit-preset-btn">100</button>
<button onclick="setLogLimit(1000)" class="limit-preset-btn">1K</button>
<button onclick="setLogLimit(5000)" class="limit-preset-btn">5K</button>
</div>
</div>
<div class="filter-actions">
<button onclick="toggleRegexMode()" class="filter-regex-btn" id="regex-mode-btn" title="Toggle regex mode">.*</button>
<button onclick="refreshLogs()" class="filter-refresh-btn" title="Refresh logs">🔄</button>
<button onclick="clearAllFilters()" class="filter-clear-btn" title="Clear all filters">🗑️</button>
</div>
</div>
<div class="filter-stats-row">
<span class="filter-stats" id="filter-stats">Loading...</span>
</div>
</div>
<div class="modal-body">
<div id="modal-logs" class="modal-logs font-md">
<div class="logs-loading">Starting log tail...</div>
</div>
</div>
</div>
</div>
<!-- Cache Stats Modal -->
<div id="cache-stats-modal" class="modal">
<div class="modal-content cache-modal-content">
<div class="modal-header">
<h3 class="modal-title">💾 Cache Statistics & Management</h3>
<div class="modal-controls">
<button onclick="closeCacheStatsModal()" class="modal-close">✕</button>
</div>
</div>
<div class="modal-body">
<div id="cache-stats-content" class="cache-stats-content">
<div class="cache-loading">Loading cache statistics...</div>
</div>
</div>
</div>
</div>
<!-- Instrumental Selection Modal -->
<div id="instrumental-selection-modal" class="modal">
<div class="modal-content instrumental-modal-content">
<div class="modal-header">
<h3 class="modal-title">🎵 Choose Instrumental Track</h3>
<div class="instrumental-selection-subtitle">
<p class="subtitle">Preview and select your preferred instrumental track</p>
</div>
<div class="modal-controls">
<button onclick="closeInstrumentalSelectionModal()" class="modal-close">✕</button>
</div>
</div>
<div class="modal-body">
<div id="instrumental-selection-content" class="instrumental-selection-content">
<div class="instrumental-loading">Loading instrumental options...</div>
</div>
<div class="instrumental-selection-actions">
<button id="confirm-instrumental-btn" onclick="confirmInstrumentalSelection()" class="btn btn-primary" disabled>
🎵 Continue with Selected Track
</button>
<button onclick="closeInstrumentalSelectionModal()" class="btn btn-secondary">
Cancel
</button>
</div>
</div>
</div>
</div>
<!-- Notification Container -->
<div id="notifications" class="notifications"></div>
<script src="app.js"></script>
</body>
</html>
+121
View File
@@ -0,0 +1,121 @@
{
"intro": {
"video_duration": 5,
"existing_image": null,
"background_color": "#000000",
"background_image": "/tmp/karaoke-title-screen-background-nomad-4k.png",
"font": "/tmp/AvenirNext-Bold.ttf",
"artist_color": "#ffdf6b",
"artist_text_transform": "uppercase",
"title_color": "#ffffff",
"title_gradient": null,
"title_text_transform": "uppercase",
"title_region": "370,980,3100,350",
"artist_region": "370,1400,3100,450",
"artist_gradient": null,
"extra_text": null,
"extra_text_color": "#ffffff",
"extra_text_gradient": null,
"extra_text_region": null,
"extra_text_text_transform": "uppercase"
},
"karaoke": {
"background_image": "/tmp/karaoke-background-image-nomad-4k.png",
"background_color": "#000000",
"font_path": "/tmp/AvenirNext-Bold.ttf",
"font": "Avenir Next",
"ass_name": "Nomad",
"primary_color": "112, 112, 247, 255",
"secondary_color": "255, 255, 255, 255",
"outline_color": "26, 58, 235, 255",
"back_color": "0, 255, 0, 255",
"bold": false,
"italic": false,
"underline": false,
"strike_out": false,
"scale_x": 100,
"scale_y": 100,
"spacing": 0,
"angle": 0.0,
"border_style": 1,
"outline": 1,
"shadow": 0,
"margin_l": 0,
"margin_r": 0,
"margin_v": 0,
"encoding": 0
},
"end": {
"video_duration": 5,
"existing_image": null,
"background_color": "#000000",
"background_image": "/tmp/karaoke-background-image-nomad-4k.png",
"font": "/tmp/AvenirNext-Bold.ttf",
"artist_color": "#ffdf6b",
"artist_text_transform": "uppercase",
"title_color": "#ffffff",
"title_gradient": null,
"title_text_transform": "uppercase",
"title_region": "370,900,3100,350",
"artist_region": "370,1450,3100,200",
"artist_gradient": null,
"extra_text": "THANK YOU FOR SINGING!",
"extra_text_color": "#ff7acc",
"extra_text_region": "370,400,3100,400",
"extra_text_text_transform": "uppercase",
"extra_text_gradient": null
},
"cdg": {
"//sync": "Display timing and sync",
"clear_mode": "eager",
"sync_offset": 0,
"lead_in_threshold": 300,
"lead_in_duration": 30,
"lead_in_total": 200,
"lead_in_symbols": ["/>", ">", ">", ">"],
"//layout": "Layout and dimensions",
"row": 4,
"line_tile_height": 3,
"lines_per_page": 4,
"//colors": "Colors",
"title_color": "#ffffff",
"artist_color": "#ffdf6b",
"background_color": "#111427",
"border_color": "#111427",
"active_fill": "#7070F7",
"active_stroke": "#000000",
"inactive_fill": "#ff7acc",
"inactive_stroke": "#000000",
"instrumental_font_color": "#ffdf6b",
"//font": "Font settings",
"font_path": "/tmp/AvenirNext-Bold.ttf",
"font_size": 18,
"stroke_width": 0,
"stroke_style": "octagon",
"//instrumental": "Instrumental section settings",
"instrumental_gap_threshold": 1500,
"instrumental_text": "INSTRUMENTAL",
"instrumental_background": "/tmp/cdg-instrumental-background-nomad-notes.png",
"instrumental_transition": "topleftmusicalnotes",
"//title": "Title screen settings",
"title_screen_background": "/tmp/cdg-title-screen-background-nomad-simple.png",
"title_screen_transition": "largecentertexttoplogo",
"title_artist_gap": 10,
"intro_duration_seconds": 5.0,
"first_syllable_buffer_seconds": 3.0,
"//outro": "Outro screen settings",
"outro_background": "/tmp/cdg-title-screen-background-nomad-simple.png",
"outro_transition": "largecentertexttoplogo",
"outro_text_line1": "THANK YOU FOR SINGING!",
"outro_text_line2": "nomadkaraoke.com",
"outro_line1_color": "#ffffff",
"outro_line2_color": "#ffdf6b",
"outro_line1_line2_gap": 30
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 208 KiB

Binary file not shown.
+97
View File
@@ -0,0 +1,97 @@
{
"name": "frontend",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "frontend",
"version": "1.0.0",
"license": "ISC",
"devDependencies": {
"@playwright/test": "^1.53.2",
"@types/node": "^24.0.10"
}
},
"node_modules/@playwright/test": {
"version": "1.53.2",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.53.2.tgz",
"integrity": "sha512-tEB2U5z74ebBeyfGNZ3Jfg29AnW+5HlWhvHtb/Mqco9pFdZU1ZLNdVb2UtB5CvmiilNr2ZfVH/qMmAROG/XTzw==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright": "1.53.2"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/@types/node": {
"version": "24.0.10",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.0.10.tgz",
"integrity": "sha512-ENHwaH+JIRTDIEEbDK6QSQntAYGtbvdDXnMXnZaZ6k13Du1dPMmprkEHIL7ok2Wl2aZevetwTAb5S+7yIF+enA==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~7.8.0"
}
},
"node_modules/fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/playwright": {
"version": "1.53.2",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.53.2.tgz",
"integrity": "sha512-6K/qQxVFuVQhRQhFsVZ9fGeatxirtrpPgxzBYWyZLEXJzqYwuL4fuNmfOfD5et1tJE4GScKyPNeLhZeRwuTU3A==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.53.2"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"fsevents": "2.3.2"
}
},
"node_modules/playwright-core": {
"version": "1.53.2",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.53.2.tgz",
"integrity": "sha512-ox/OytMy+2w1jcYEYlOo1Hhp8hZkLCximMTUTMBXjGUA1KoFfiSZ+DU+3a739jsPY0yoKH2TFy9S2fsJas8yAw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/undici-types": {
"version": "7.8.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.8.0.tgz",
"integrity": "sha512-9UJ2xGDvQ43tYyVMpuHlsgApydB8ZKfVYTsLDhXkFL/6gfkp+U8xTGdh8pMJv1SpZna0zxG1DwsKZsreLbXBxw==",
"dev": true,
"license": "MIT"
}
}
}
+15
View File
@@ -0,0 +1,15 @@
{
"name": "frontend",
"version": "1.0.0",
"description": "This is the static frontend for the Karaoke Generator web application. It's designed to be deployed on GitHub Pages with a custom domain.",
"main": "app.js",
"scripts": {},
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs",
"devDependencies": {
"@playwright/test": "^1.53.2",
"@types/node": "^24.0.10"
}
}
+79
View File
@@ -0,0 +1,79 @@
import { defineConfig, devices } from '@playwright/test';
/**
* Read environment variables from file.
* https://github.com/motdotla/dotenv
*/
// import dotenv from 'dotenv';
// import path from 'path';
// dotenv.config({ path: path.resolve(__dirname, '.env') });
/**
* See https://playwright.dev/docs/test-configuration.
*/
export default defineConfig({
testDir: './tests',
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: process.env.CI ? 2 : 0,
/* Opt out of parallel tests on CI. */
workers: process.env.CI ? 1 : undefined,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: 'html',
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Base URL to use in actions like `await page.goto('/')`. */
// baseURL: 'http://localhost:3000',
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: 'on-first-retry',
},
/* Configure projects for major browsers */
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
},
/* Test against mobile viewports. */
// {
// name: 'Mobile Chrome',
// use: { ...devices['Pixel 5'] },
// },
// {
// name: 'Mobile Safari',
// use: { ...devices['iPhone 12'] },
// },
/* Test against branded browsers. */
// {
// name: 'Microsoft Edge',
// use: { ...devices['Desktop Edge'], channel: 'msedge' },
// },
// {
// name: 'Google Chrome',
// use: { ...devices['Desktop Chrome'], channel: 'chrome' },
// },
],
/* Run your local dev server before starting the tests */
// webServer: {
// command: 'npm run start',
// url: 'http://localhost:3000',
// reuseExistingServer: !process.env.CI,
// },
});
+1
View File
@@ -0,0 +1 @@
{"name":"","short_name":"","icons":[{"src":"/android-chrome-192x192.png","sizes":"192x192","type":"image/png"},{"src":"/android-chrome-512x512.png","sizes":"512x512","type":"image/png"}],"theme_color":"#ffffff","background_color":"#ffffff","display":"standalone"}
+5998
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,437 @@
import { test, expect, type Page } from '@playwright/test';
test.beforeEach(async ({ page }) => {
await page.goto('https://demo.playwright.dev/todomvc');
});
const TODO_ITEMS = [
'buy some cheese',
'feed the cat',
'book a doctors appointment'
] as const;
test.describe('New Todo', () => {
test('should allow me to add todo items', async ({ page }) => {
// create a new todo locator
const newTodo = page.getByPlaceholder('What needs to be done?');
// Create 1st todo.
await newTodo.fill(TODO_ITEMS[0]);
await newTodo.press('Enter');
// Make sure the list only has one todo item.
await expect(page.getByTestId('todo-title')).toHaveText([
TODO_ITEMS[0]
]);
// Create 2nd todo.
await newTodo.fill(TODO_ITEMS[1]);
await newTodo.press('Enter');
// Make sure the list now has two todo items.
await expect(page.getByTestId('todo-title')).toHaveText([
TODO_ITEMS[0],
TODO_ITEMS[1]
]);
await checkNumberOfTodosInLocalStorage(page, 2);
});
test('should clear text input field when an item is added', async ({ page }) => {
// create a new todo locator
const newTodo = page.getByPlaceholder('What needs to be done?');
// Create one todo item.
await newTodo.fill(TODO_ITEMS[0]);
await newTodo.press('Enter');
// Check that input is empty.
await expect(newTodo).toBeEmpty();
await checkNumberOfTodosInLocalStorage(page, 1);
});
test('should append new items to the bottom of the list', async ({ page }) => {
// Create 3 items.
await createDefaultTodos(page);
// create a todo count locator
const todoCount = page.getByTestId('todo-count')
// Check test using different methods.
await expect(page.getByText('3 items left')).toBeVisible();
await expect(todoCount).toHaveText('3 items left');
await expect(todoCount).toContainText('3');
await expect(todoCount).toHaveText(/3/);
// Check all items in one call.
await expect(page.getByTestId('todo-title')).toHaveText(TODO_ITEMS);
await checkNumberOfTodosInLocalStorage(page, 3);
});
});
test.describe('Mark all as completed', () => {
test.beforeEach(async ({ page }) => {
await createDefaultTodos(page);
await checkNumberOfTodosInLocalStorage(page, 3);
});
test.afterEach(async ({ page }) => {
await checkNumberOfTodosInLocalStorage(page, 3);
});
test('should allow me to mark all items as completed', async ({ page }) => {
// Complete all todos.
await page.getByLabel('Mark all as complete').check();
// Ensure all todos have 'completed' class.
await expect(page.getByTestId('todo-item')).toHaveClass(['completed', 'completed', 'completed']);
await checkNumberOfCompletedTodosInLocalStorage(page, 3);
});
test('should allow me to clear the complete state of all items', async ({ page }) => {
const toggleAll = page.getByLabel('Mark all as complete');
// Check and then immediately uncheck.
await toggleAll.check();
await toggleAll.uncheck();
// Should be no completed classes.
await expect(page.getByTestId('todo-item')).toHaveClass(['', '', '']);
});
test('complete all checkbox should update state when items are completed / cleared', async ({ page }) => {
const toggleAll = page.getByLabel('Mark all as complete');
await toggleAll.check();
await expect(toggleAll).toBeChecked();
await checkNumberOfCompletedTodosInLocalStorage(page, 3);
// Uncheck first todo.
const firstTodo = page.getByTestId('todo-item').nth(0);
await firstTodo.getByRole('checkbox').uncheck();
// Reuse toggleAll locator and make sure its not checked.
await expect(toggleAll).not.toBeChecked();
await firstTodo.getByRole('checkbox').check();
await checkNumberOfCompletedTodosInLocalStorage(page, 3);
// Assert the toggle all is checked again.
await expect(toggleAll).toBeChecked();
});
});
test.describe('Item', () => {
test('should allow me to mark items as complete', async ({ page }) => {
// create a new todo locator
const newTodo = page.getByPlaceholder('What needs to be done?');
// Create two items.
for (const item of TODO_ITEMS.slice(0, 2)) {
await newTodo.fill(item);
await newTodo.press('Enter');
}
// Check first item.
const firstTodo = page.getByTestId('todo-item').nth(0);
await firstTodo.getByRole('checkbox').check();
await expect(firstTodo).toHaveClass('completed');
// Check second item.
const secondTodo = page.getByTestId('todo-item').nth(1);
await expect(secondTodo).not.toHaveClass('completed');
await secondTodo.getByRole('checkbox').check();
// Assert completed class.
await expect(firstTodo).toHaveClass('completed');
await expect(secondTodo).toHaveClass('completed');
});
test('should allow me to un-mark items as complete', async ({ page }) => {
// create a new todo locator
const newTodo = page.getByPlaceholder('What needs to be done?');
// Create two items.
for (const item of TODO_ITEMS.slice(0, 2)) {
await newTodo.fill(item);
await newTodo.press('Enter');
}
const firstTodo = page.getByTestId('todo-item').nth(0);
const secondTodo = page.getByTestId('todo-item').nth(1);
const firstTodoCheckbox = firstTodo.getByRole('checkbox');
await firstTodoCheckbox.check();
await expect(firstTodo).toHaveClass('completed');
await expect(secondTodo).not.toHaveClass('completed');
await checkNumberOfCompletedTodosInLocalStorage(page, 1);
await firstTodoCheckbox.uncheck();
await expect(firstTodo).not.toHaveClass('completed');
await expect(secondTodo).not.toHaveClass('completed');
await checkNumberOfCompletedTodosInLocalStorage(page, 0);
});
test('should allow me to edit an item', async ({ page }) => {
await createDefaultTodos(page);
const todoItems = page.getByTestId('todo-item');
const secondTodo = todoItems.nth(1);
await secondTodo.dblclick();
await expect(secondTodo.getByRole('textbox', { name: 'Edit' })).toHaveValue(TODO_ITEMS[1]);
await secondTodo.getByRole('textbox', { name: 'Edit' }).fill('buy some sausages');
await secondTodo.getByRole('textbox', { name: 'Edit' }).press('Enter');
// Explicitly assert the new text value.
await expect(todoItems).toHaveText([
TODO_ITEMS[0],
'buy some sausages',
TODO_ITEMS[2]
]);
await checkTodosInLocalStorage(page, 'buy some sausages');
});
});
test.describe('Editing', () => {
test.beforeEach(async ({ page }) => {
await createDefaultTodos(page);
await checkNumberOfTodosInLocalStorage(page, 3);
});
test('should hide other controls when editing', async ({ page }) => {
const todoItem = page.getByTestId('todo-item').nth(1);
await todoItem.dblclick();
await expect(todoItem.getByRole('checkbox')).not.toBeVisible();
await expect(todoItem.locator('label', {
hasText: TODO_ITEMS[1],
})).not.toBeVisible();
await checkNumberOfTodosInLocalStorage(page, 3);
});
test('should save edits on blur', async ({ page }) => {
const todoItems = page.getByTestId('todo-item');
await todoItems.nth(1).dblclick();
await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).fill('buy some sausages');
await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).dispatchEvent('blur');
await expect(todoItems).toHaveText([
TODO_ITEMS[0],
'buy some sausages',
TODO_ITEMS[2],
]);
await checkTodosInLocalStorage(page, 'buy some sausages');
});
test('should trim entered text', async ({ page }) => {
const todoItems = page.getByTestId('todo-item');
await todoItems.nth(1).dblclick();
await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).fill(' buy some sausages ');
await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).press('Enter');
await expect(todoItems).toHaveText([
TODO_ITEMS[0],
'buy some sausages',
TODO_ITEMS[2],
]);
await checkTodosInLocalStorage(page, 'buy some sausages');
});
test('should remove the item if an empty text string was entered', async ({ page }) => {
const todoItems = page.getByTestId('todo-item');
await todoItems.nth(1).dblclick();
await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).fill('');
await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).press('Enter');
await expect(todoItems).toHaveText([
TODO_ITEMS[0],
TODO_ITEMS[2],
]);
});
test('should cancel edits on escape', async ({ page }) => {
const todoItems = page.getByTestId('todo-item');
await todoItems.nth(1).dblclick();
await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).fill('buy some sausages');
await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).press('Escape');
await expect(todoItems).toHaveText(TODO_ITEMS);
});
});
test.describe('Counter', () => {
test('should display the current number of todo items', async ({ page }) => {
// create a new todo locator
const newTodo = page.getByPlaceholder('What needs to be done?');
// create a todo count locator
const todoCount = page.getByTestId('todo-count')
await newTodo.fill(TODO_ITEMS[0]);
await newTodo.press('Enter');
await expect(todoCount).toContainText('1');
await newTodo.fill(TODO_ITEMS[1]);
await newTodo.press('Enter');
await expect(todoCount).toContainText('2');
await checkNumberOfTodosInLocalStorage(page, 2);
});
});
test.describe('Clear completed button', () => {
test.beforeEach(async ({ page }) => {
await createDefaultTodos(page);
});
test('should display the correct text', async ({ page }) => {
await page.locator('.todo-list li .toggle').first().check();
await expect(page.getByRole('button', { name: 'Clear completed' })).toBeVisible();
});
test('should remove completed items when clicked', async ({ page }) => {
const todoItems = page.getByTestId('todo-item');
await todoItems.nth(1).getByRole('checkbox').check();
await page.getByRole('button', { name: 'Clear completed' }).click();
await expect(todoItems).toHaveCount(2);
await expect(todoItems).toHaveText([TODO_ITEMS[0], TODO_ITEMS[2]]);
});
test('should be hidden when there are no items that are completed', async ({ page }) => {
await page.locator('.todo-list li .toggle').first().check();
await page.getByRole('button', { name: 'Clear completed' }).click();
await expect(page.getByRole('button', { name: 'Clear completed' })).toBeHidden();
});
});
test.describe('Persistence', () => {
test('should persist its data', async ({ page }) => {
// create a new todo locator
const newTodo = page.getByPlaceholder('What needs to be done?');
for (const item of TODO_ITEMS.slice(0, 2)) {
await newTodo.fill(item);
await newTodo.press('Enter');
}
const todoItems = page.getByTestId('todo-item');
const firstTodoCheck = todoItems.nth(0).getByRole('checkbox');
await firstTodoCheck.check();
await expect(todoItems).toHaveText([TODO_ITEMS[0], TODO_ITEMS[1]]);
await expect(firstTodoCheck).toBeChecked();
await expect(todoItems).toHaveClass(['completed', '']);
// Ensure there is 1 completed item.
await checkNumberOfCompletedTodosInLocalStorage(page, 1);
// Now reload.
await page.reload();
await expect(todoItems).toHaveText([TODO_ITEMS[0], TODO_ITEMS[1]]);
await expect(firstTodoCheck).toBeChecked();
await expect(todoItems).toHaveClass(['completed', '']);
});
});
test.describe('Routing', () => {
test.beforeEach(async ({ page }) => {
await createDefaultTodos(page);
// make sure the app had a chance to save updated todos in storage
// before navigating to a new view, otherwise the items can get lost :(
// in some frameworks like Durandal
await checkTodosInLocalStorage(page, TODO_ITEMS[0]);
});
test('should allow me to display active items', async ({ page }) => {
const todoItem = page.getByTestId('todo-item');
await page.getByTestId('todo-item').nth(1).getByRole('checkbox').check();
await checkNumberOfCompletedTodosInLocalStorage(page, 1);
await page.getByRole('link', { name: 'Active' }).click();
await expect(todoItem).toHaveCount(2);
await expect(todoItem).toHaveText([TODO_ITEMS[0], TODO_ITEMS[2]]);
});
test('should respect the back button', async ({ page }) => {
const todoItem = page.getByTestId('todo-item');
await page.getByTestId('todo-item').nth(1).getByRole('checkbox').check();
await checkNumberOfCompletedTodosInLocalStorage(page, 1);
await test.step('Showing all items', async () => {
await page.getByRole('link', { name: 'All' }).click();
await expect(todoItem).toHaveCount(3);
});
await test.step('Showing active items', async () => {
await page.getByRole('link', { name: 'Active' }).click();
});
await test.step('Showing completed items', async () => {
await page.getByRole('link', { name: 'Completed' }).click();
});
await expect(todoItem).toHaveCount(1);
await page.goBack();
await expect(todoItem).toHaveCount(2);
await page.goBack();
await expect(todoItem).toHaveCount(3);
});
test('should allow me to display completed items', async ({ page }) => {
await page.getByTestId('todo-item').nth(1).getByRole('checkbox').check();
await checkNumberOfCompletedTodosInLocalStorage(page, 1);
await page.getByRole('link', { name: 'Completed' }).click();
await expect(page.getByTestId('todo-item')).toHaveCount(1);
});
test('should allow me to display all items', async ({ page }) => {
await page.getByTestId('todo-item').nth(1).getByRole('checkbox').check();
await checkNumberOfCompletedTodosInLocalStorage(page, 1);
await page.getByRole('link', { name: 'Active' }).click();
await page.getByRole('link', { name: 'Completed' }).click();
await page.getByRole('link', { name: 'All' }).click();
await expect(page.getByTestId('todo-item')).toHaveCount(3);
});
test('should highlight the currently applied filter', async ({ page }) => {
await expect(page.getByRole('link', { name: 'All' })).toHaveClass('selected');
//create locators for active and completed links
const activeLink = page.getByRole('link', { name: 'Active' });
const completedLink = page.getByRole('link', { name: 'Completed' });
await activeLink.click();
// Page change - active items.
await expect(activeLink).toHaveClass('selected');
await completedLink.click();
// Page change - completed items.
await expect(completedLink).toHaveClass('selected');
});
});
async function createDefaultTodos(page: Page) {
// create a new todo locator
const newTodo = page.getByPlaceholder('What needs to be done?');
for (const item of TODO_ITEMS) {
await newTodo.fill(item);
await newTodo.press('Enter');
}
}
async function checkNumberOfTodosInLocalStorage(page: Page, expected: number) {
return await page.waitForFunction(e => {
return JSON.parse(localStorage['react-todos']).length === e;
}, expected);
}
async function checkNumberOfCompletedTodosInLocalStorage(page: Page, expected: number) {
return await page.waitForFunction(e => {
return JSON.parse(localStorage['react-todos']).filter((todo: any) => todo.completed).length === e;
}, expected);
}
async function checkTodosInLocalStorage(page: Page, title: string) {
return await page.waitForFunction(t => {
return JSON.parse(localStorage['react-todos']).map((todo: any) => todo.title).includes(t);
}, title);
}
+18
View File
@@ -0,0 +1,18 @@
import { test, expect } from '@playwright/test';
test('has title', async ({ page }) => {
await page.goto('https://playwright.dev/');
// Expect a title "to contain" a substring.
await expect(page).toHaveTitle(/Playwright/);
});
test('get started link', async ({ page }) => {
await page.goto('https://playwright.dev/');
// Click the get started link.
await page.getByRole('link', { name: 'Get started' }).click();
// Expects page to have a heading with the name of Installation.
await expect(page.getByRole('heading', { name: 'Installation' })).toBeVisible();
});
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
import warnings
# Suppress specific SyntaxWarnings from third-party packages
warnings.filterwarnings("ignore", category=SyntaxWarning, module="pydub.*")
warnings.filterwarnings("ignore", category=SyntaxWarning, module="syrics.*")
from .karaoke_gen import KaraokePrep
+838
View File
@@ -0,0 +1,838 @@
import os
import sys
import json
import logging
import glob
import shutil
import tempfile
import time
import fcntl
import errno
import psutil
from datetime import datetime
from pydub import AudioSegment
# Try to import the remote API client if available
try:
from audio_separator.remote import AudioSeparatorAPIClient
REMOTE_API_AVAILABLE = True
except ImportError:
REMOTE_API_AVAILABLE = False
AudioSeparatorAPIClient = None
# Placeholder class or functions for audio processing
class AudioProcessor:
def __init__(
self,
logger,
log_level,
log_formatter,
model_file_dir,
lossless_output_format,
clean_instrumental_model,
backing_vocals_models,
other_stems_models,
ffmpeg_base_command,
):
self.logger = logger
self.log_level = log_level
self.log_formatter = log_formatter
self.model_file_dir = model_file_dir
self.lossless_output_format = lossless_output_format
self.clean_instrumental_model = clean_instrumental_model
self.backing_vocals_models = backing_vocals_models
self.other_stems_models = other_stems_models
self.ffmpeg_base_command = ffmpeg_base_command # Needed for combined instrumentals
def _file_exists(self, file_path):
"""Check if a file exists and log the result."""
exists = os.path.isfile(file_path)
if exists:
self.logger.info(f"File already exists, skipping creation: {file_path}")
return exists
def pad_audio_file(self, input_audio, output_audio, padding_seconds):
"""
Add silence to the start of an audio file using ffmpeg.
This ensures the instrumental tracks are synchronized with vocals when
countdown padding has been applied by the LyricsTranscriber.
Args:
input_audio: Path to input audio file
output_audio: Path for output padded audio file
padding_seconds: Amount of silence to add in seconds (e.g., 3.0)
Raises:
Exception: If ffmpeg command fails
"""
self.logger.info(f"Padding audio file with {padding_seconds}s of silence: {input_audio}")
# Use ffmpeg to prepend silence to the audio file
# This matches the approach used in LyricsTranscriber for vocal padding
cmd = [
"ffmpeg",
"-y", # Overwrite output file
"-hide_banner",
"-loglevel", "error",
"-f", "lavfi",
"-t", str(padding_seconds),
"-i", f"anullsrc=channel_layout=stereo:sample_rate=44100",
"-i", input_audio,
"-filter_complex", "[0:a][1:a]concat=n=2:v=0:a=1[out]",
"-map", "[out]",
"-c:a", self.lossless_output_format.lower(),
output_audio,
]
try:
import subprocess
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=300, # 5 minute timeout
check=True
)
self.logger.info(f"Successfully padded audio file: {output_audio}")
except subprocess.CalledProcessError as e:
error_msg = f"Failed to pad audio file {input_audio}: {e.stderr}"
self.logger.error(error_msg)
raise Exception(error_msg)
except subprocess.TimeoutExpired:
error_msg = f"Timeout while padding audio file {input_audio}"
self.logger.error(error_msg)
raise Exception(error_msg)
def separate_audio(self, audio_file, model_name, artist_title, track_output_dir, 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.info(
f"instantiating Separator with model_file_dir: {self.model_file_dir}, model_filename: {model_name} output_format: {self.lossless_output_format}"
)
from audio_separator.separator import Separator
separator = Separator(
log_level=self.log_level,
log_formatter=self.log_formatter,
model_file_dir=self.model_file_dir,
output_format=self.lossless_output_format,
)
separator.load_model(model_filename=model_name)
output_files = separator.separate(audio_file)
self.logger.debug(f"Separator output files: {output_files}")
model_name_no_extension = os.path.splitext(model_name)[0]
for file in output_files:
if "(Vocals)" in file:
self.logger.info(f"Moving Vocals file {file} to {vocals_path}")
shutil.move(file, vocals_path)
elif "(Instrumental)" in file:
self.logger.info(f"Moving Instrumental file {file} to {instrumental_path}")
shutil.move(file, instrumental_path)
elif model_name in file:
# Example filename 1: "Freddie Jackson - All I'll Ever Ask (feat. Najee) (Local)_(Piano)_htdemucs_6s.flac"
# Example filename 2: "Freddie Jackson - All I'll Ever Ask (feat. Najee) (Local)_(Guitar)_htdemucs_6s.flac"
# The stem name in these examples would be "Piano" or "Guitar"
# Extract stem_name from the filename
stem_name = file.split(f"_{model_name}")[0].split("_")[-1]
stem_name = stem_name.strip("()") # Remove parentheses if present
other_stem_path = os.path.join(track_output_dir, f"{artist_title} ({stem_name} {model_name}).{self.lossless_output_format}")
self.logger.info(f"Moving other stem file {file} to {other_stem_path}")
shutil.move(file, other_stem_path)
elif model_name_no_extension in file:
# Example filename 1: "Freddie Jackson - All I'll Ever Ask (feat. Najee) (Local)_(Piano)_htdemucs_6s.flac"
# Example filename 2: "Freddie Jackson - All I'll Ever Ask (feat. Najee) (Local)_(Guitar)_htdemucs_6s.flac"
# The stem name in these examples would be "Piano" or "Guitar"
# Extract stem_name from the filename
stem_name = file.split(f"_{model_name_no_extension}")[0].split("_")[-1]
stem_name = stem_name.strip("()") # Remove parentheses if present
other_stem_path = os.path.join(track_output_dir, f"{artist_title} ({stem_name} {model_name}).{self.lossless_output_format}")
self.logger.info(f"Moving other stem file {file} to {other_stem_path}")
shutil.move(file, other_stem_path)
self.logger.info(f"Separation complete! Output file(s): {vocals_path} {instrumental_path}")
def process_audio_separation(self, audio_file, artist_title, track_output_dir):
# Check if we should use remote API
remote_api_url = os.environ.get("AUDIO_SEPARATOR_API_URL")
if remote_api_url:
if not REMOTE_API_AVAILABLE:
self.logger.warning("AUDIO_SEPARATOR_API_URL is set but remote API client is not available. "
"Please ensure audio-separator is updated to a version that includes remote API support. "
"Falling back to local processing.")
else:
self.logger.info(f"Using remote audio separator API at: {remote_api_url}")
try:
return self._process_audio_separation_remote(audio_file, artist_title, track_output_dir, remote_api_url)
except Exception as e:
error_str = str(e)
# Don't fall back for download failures - these indicate API issues that should be fixed
if ("no files were downloaded" in error_str or
"failed to produce essential" in error_str):
self.logger.error(f"Remote API processing failed with download/file organization issue: {error_str}")
self.logger.error("This indicates an audio-separator API issue that should be fixed. Not falling back to local processing.")
raise e
else:
# Fall back for other types of errors (network issues, etc.)
self.logger.error(f"Remote API processing failed: {error_str}")
self.logger.info("Falling back to local audio separation")
else:
self.logger.info("AUDIO_SEPARATOR_API_URL not set, using local audio separation. "
"Set this environment variable to use remote GPU processing.")
from audio_separator.separator import Separator
self.logger.info(f"Starting local audio separation process for {artist_title}")
# Define lock file path in system temp directory
lock_file_path = os.path.join(tempfile.gettempdir(), "audio_separator.lock")
# Try to acquire lock
while True:
try:
# First check if there's a stale lock
if os.path.exists(lock_file_path):
try:
with open(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 process is still running
if not psutil.pid_exists(pid):
self.logger.warning(f"Found stale lock from dead process {pid}, removing...")
os.remove(lock_file_path)
else:
# Calculate runtime
runtime = datetime.now() - start_time
runtime_mins = runtime.total_seconds() / 60
# Get process command line
try:
proc = psutil.Process(pid)
cmdline_args = proc.cmdline()
# Handle potential bytes in cmdline args (cross-platform compatibility)
cmd = " ".join(arg.decode('utf-8', errors='replace') if isinstance(arg, bytes) else arg for arg in cmdline_args)
except (psutil.AccessDenied, psutil.NoSuchProcess):
cmd = "<command unavailable>"
self.logger.info(
f"Waiting for other audio separation process to complete before starting separation for {artist_title}...\n"
f"Currently running process details:\n"
f" Track: {running_track}\n"
f" PID: {pid}\n"
f" Running time: {runtime_mins:.1f} minutes\n"
f" Command: {cmd}\n"
f"To force clear the lock and kill the process, run:\n"
f" kill {pid} && rm {lock_file_path}"
)
except (json.JSONDecodeError, KeyError, ValueError) as e:
self.logger.warning(f"Found invalid lock file, removing: {e}")
os.remove(lock_file_path)
# Try to acquire lock
lock_file = open(lock_file_path, "w")
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
# Write metadata to lock file
lock_data = {
"pid": os.getpid(),
"start_time": datetime.now().isoformat(),
"track": f"{artist_title}",
}
json.dump(lock_data, lock_file)
lock_file.flush()
break
except IOError as e:
if e.errno != errno.EAGAIN:
raise
# Lock is held by another process
time.sleep(30) # Wait 30 seconds before trying again
continue
try:
separator = Separator(
log_level=self.log_level,
log_formatter=self.log_formatter,
model_file_dir=self.model_file_dir,
output_format=self.lossless_output_format,
)
stems_dir = self._create_stems_directory(track_output_dir)
result = {"clean_instrumental": {}, "other_stems": {}, "backing_vocals": {}, "combined_instrumentals": {}}
if os.environ.get("KARAOKE_GEN_SKIP_AUDIO_SEPARATION"):
return result
result["clean_instrumental"] = self._separate_clean_instrumental(
separator, audio_file, artist_title, track_output_dir, stems_dir
)
result["other_stems"] = self._separate_other_stems(separator, audio_file, artist_title, stems_dir)
result["backing_vocals"] = self._separate_backing_vocals(
separator, result["clean_instrumental"]["vocals"], artist_title, stems_dir
)
result["combined_instrumentals"] = self._generate_combined_instrumentals(
result["clean_instrumental"]["instrumental"], result["backing_vocals"], artist_title, track_output_dir
)
self._normalize_audio_files(result, artist_title, track_output_dir)
# Create Audacity LOF file
if result["backing_vocals"]:
lof_path = os.path.join(stems_dir, f"{artist_title} (Audacity).lof")
first_model = list(result["backing_vocals"].keys())[0]
files_to_include = [
audio_file, # Original audio
result["clean_instrumental"]["instrumental"], # Clean instrumental
result["backing_vocals"][first_model]["backing_vocals"], # Backing vocals
result["combined_instrumentals"][first_model], # Combined instrumental+BV
]
# Convert to absolute paths
files_to_include = [os.path.abspath(f) for f in files_to_include]
with open(lof_path, "w") as lof:
for file_path in files_to_include:
lof.write(f'file "{file_path}"\n')
self.logger.info(f"Created Audacity LOF file: {lof_path}")
result["audacity_lof"] = lof_path
# Launch Audacity with multiple tracks
if sys.platform == "darwin": # Check if we're on macOS
if lof_path and os.path.exists(lof_path):
self.logger.info(f"Launching Audacity with LOF file: {lof_path}")
os.system(f'open -a Audacity "{lof_path}"')
else:
self.logger.debug("Audacity LOF file not available or not found")
self.logger.info("Audio separation, combination, and normalization process completed")
return result
finally:
# Release lock
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
lock_file.close()
try:
os.remove(lock_file_path)
except OSError:
pass
def _process_audio_separation_remote(self, audio_file, artist_title, track_output_dir, remote_api_url):
"""Process audio separation using remote API with proper two-stage workflow."""
self.logger.info(f"Starting remote audio separation process for {artist_title}")
# Initialize the API client
api_client = AudioSeparatorAPIClient(remote_api_url, self.logger)
stems_dir = self._create_stems_directory(track_output_dir)
result = {"clean_instrumental": {}, "other_stems": {}, "backing_vocals": {}, "combined_instrumentals": {}}
if os.environ.get("KARAOKE_GEN_SKIP_AUDIO_SEPARATION"):
return result
try:
# Stage 1: Process original song with clean instrumental model + other stems models
stage1_models = []
if self.clean_instrumental_model:
stage1_models.append(self.clean_instrumental_model)
stage1_models.extend(self.other_stems_models)
self.logger.info(f"Stage 1: Submitting audio separation job with models: {stage1_models}")
# Submit the first stage job
stage1_result = api_client.separate_audio_and_wait(
audio_file,
models=stage1_models,
timeout=1800, # 30 minutes timeout
poll_interval=15, # Check every 15 seconds
download=True,
output_dir=stems_dir,
output_format=self.lossless_output_format.lower()
)
if stage1_result["status"] != "completed":
raise Exception(f"Stage 1 remote audio separation failed: {stage1_result.get('error', 'Unknown error')}")
self.logger.info(f"Stage 1 completed. Downloaded {len(stage1_result['downloaded_files'])} files")
# Check if we actually got the expected files for Stage 1
if len(stage1_result["downloaded_files"]) == 0:
error_msg = ("Stage 1 audio separation completed successfully but no files were downloaded. "
"This indicates a filename encoding or API issue in the audio-separator remote service. "
f"Expected files for models {stage1_models} but got 0.")
self.logger.error(error_msg)
raise Exception(error_msg)
# Organize the stage 1 results
result = self._organize_stage1_remote_results(
stage1_result["downloaded_files"], artist_title, track_output_dir, stems_dir
)
# Validate that we got the essential clean instrumental outputs
if not result["clean_instrumental"].get("vocals") or not result["clean_instrumental"].get("instrumental"):
missing = []
if not result["clean_instrumental"].get("vocals"):
missing.append("clean vocals")
if not result["clean_instrumental"].get("instrumental"):
missing.append("clean instrumental")
error_msg = (f"Stage 1 completed but failed to produce essential clean instrumental outputs: {', '.join(missing)}. "
"This may indicate a model naming or file organization issue in the remote API.")
self.logger.error(error_msg)
raise Exception(error_msg)
# Stage 2: Process clean vocals with backing vocals models (if we have both)
if result["clean_instrumental"].get("vocals") and self.backing_vocals_models:
self.logger.info(f"Stage 2: Processing clean vocals for backing vocals separation...")
vocals_path = result["clean_instrumental"]["vocals"]
stage2_result = api_client.separate_audio_and_wait(
vocals_path,
models=self.backing_vocals_models,
timeout=900, # 15 minutes timeout for backing vocals
poll_interval=10,
download=True,
output_dir=stems_dir,
output_format=self.lossless_output_format.lower()
)
if stage2_result["status"] == "completed":
self.logger.info(f"Stage 2 completed. Downloaded {len(stage2_result['downloaded_files'])} files")
# Check if we actually got the expected files
if len(stage2_result["downloaded_files"]) == 0:
error_msg = ("Stage 2 backing vocals separation completed successfully but no files were downloaded. "
"This indicates a filename encoding or API issue in the audio-separator remote service. "
"Expected 2 files (lead vocals + backing vocals) but got 0.")
self.logger.error(error_msg)
raise Exception(error_msg)
# Organize the stage 2 results (backing vocals)
backing_vocals_result = self._organize_stage2_remote_results(
stage2_result["downloaded_files"], artist_title, stems_dir
)
result["backing_vocals"] = backing_vocals_result
else:
error_msg = f"Stage 2 backing vocals separation failed: {stage2_result.get('error', 'Unknown error')}"
self.logger.error(error_msg)
raise Exception(error_msg)
else:
result["backing_vocals"] = {}
# Generate combined instrumentals
if result["clean_instrumental"].get("instrumental") and result["backing_vocals"]:
result["combined_instrumentals"] = self._generate_combined_instrumentals(
result["clean_instrumental"]["instrumental"], result["backing_vocals"], artist_title, track_output_dir
)
else:
result["combined_instrumentals"] = {}
# Normalize audio files
self._normalize_audio_files(result, artist_title, track_output_dir)
# Create Audacity LOF file
if result["backing_vocals"]:
lof_path = os.path.join(stems_dir, f"{artist_title} (Audacity).lof")
first_model = list(result["backing_vocals"].keys())[0]
files_to_include = [
audio_file, # Original audio
result["clean_instrumental"]["instrumental"], # Clean instrumental
result["backing_vocals"][first_model]["backing_vocals"], # Backing vocals
result["combined_instrumentals"][first_model], # Combined instrumental+BV
]
# Convert to absolute paths
files_to_include = [os.path.abspath(f) for f in files_to_include]
with open(lof_path, "w") as lof:
for file_path in files_to_include:
lof.write(f'file "{file_path}"\n')
self.logger.info(f"Created Audacity LOF file: {lof_path}")
result["audacity_lof"] = lof_path
# Launch Audacity with multiple tracks
if sys.platform == "darwin": # Check if we're on macOS
if lof_path and os.path.exists(lof_path):
self.logger.info(f"Launching Audacity with LOF file: {lof_path}")
os.system(f'open -a Audacity "{lof_path}"')
else:
self.logger.debug("Audacity LOF file not available or not found")
self.logger.info("Remote audio separation, combination, and normalization process completed")
return result
except Exception as e:
self.logger.error(f"Error during remote audio separation: {str(e)}")
raise e
def _organize_stage1_remote_results(self, downloaded_files, artist_title, track_output_dir, stems_dir):
"""Organize stage 1 separation results (clean instrumental + other stems)."""
result = {"clean_instrumental": {}, "other_stems": {}}
for file_path in downloaded_files:
filename = os.path.basename(file_path)
self.logger.debug(f"Stage 1 - Processing downloaded file: {filename}")
# Determine which model and stem type this file represents
model_name = None
stem_type = None
# Extract model name and stem type from filename
# Expected format: "audio_(StemType)_modelname.ext"
if "_(Vocals)_" in filename:
stem_type = "Vocals"
model_name = filename.split("_(Vocals)_")[1].split(".")[0]
elif "_(Instrumental)_" in filename:
stem_type = "Instrumental"
model_name = filename.split("_(Instrumental)_")[1].split(".")[0]
elif "_(Drums)_" in filename:
stem_type = "Drums"
model_name = filename.split("_(Drums)_")[1].split(".")[0]
elif "_(Bass)_" in filename:
stem_type = "Bass"
model_name = filename.split("_(Bass)_")[1].split(".")[0]
elif "_(Other)_" in filename:
stem_type = "Other"
model_name = filename.split("_(Other)_")[1].split(".")[0]
elif "_(Guitar)_" in filename:
stem_type = "Guitar"
model_name = filename.split("_(Guitar)_")[1].split(".")[0]
elif "_(Piano)_" in filename:
stem_type = "Piano"
model_name = filename.split("_(Piano)_")[1].split(".")[0]
else:
# Try to extract stem type from parentheses
import re
match = re.search(r'_\(([^)]+)\)_([^.]+)', filename)
if match:
stem_type = match.group(1)
model_name = match.group(2)
else:
self.logger.warning(f"Could not parse stem type and model from filename: {filename}")
continue
# Check if this model name matches the clean instrumental model
is_clean_instrumental_model = (
model_name == self.clean_instrumental_model or
self.clean_instrumental_model.startswith(model_name) or
model_name.startswith(self.clean_instrumental_model.split('.')[0])
)
if is_clean_instrumental_model:
if stem_type == "Vocals":
target_path = os.path.join(stems_dir, f"{artist_title} (Vocals {self.clean_instrumental_model}).{self.lossless_output_format}")
shutil.move(file_path, target_path)
result["clean_instrumental"]["vocals"] = target_path
elif stem_type == "Instrumental":
target_path = os.path.join(track_output_dir, f"{artist_title} (Instrumental {self.clean_instrumental_model}).{self.lossless_output_format}")
shutil.move(file_path, target_path)
result["clean_instrumental"]["instrumental"] = target_path
elif any(model_name == os_model or os_model.startswith(model_name) or model_name.startswith(os_model.split('.')[0]) for os_model in self.other_stems_models):
# Find the matching other stems model
matching_os_model = None
for os_model in self.other_stems_models:
if model_name == os_model or os_model.startswith(model_name) or model_name.startswith(os_model.split('.')[0]):
matching_os_model = os_model
break
if matching_os_model:
if matching_os_model not in result["other_stems"]:
result["other_stems"][matching_os_model] = {}
target_path = os.path.join(stems_dir, f"{artist_title} ({stem_type} {matching_os_model}).{self.lossless_output_format}")
shutil.move(file_path, target_path)
result["other_stems"][matching_os_model][stem_type] = target_path
return result
def _organize_stage2_remote_results(self, downloaded_files, artist_title, stems_dir):
"""Organize stage 2 separation results (backing vocals)."""
result = {}
for file_path in downloaded_files:
filename = os.path.basename(file_path)
self.logger.debug(f"Stage 2 - Processing downloaded file: {filename}")
# Determine which model and stem type this file represents
model_name = None
stem_type = None
# Extract model name and stem type from filename
if "_(Vocals)_" in filename:
stem_type = "Vocals"
model_name = filename.split("_(Vocals)_")[1].split(".")[0]
elif "_(Instrumental)_" in filename:
stem_type = "Instrumental"
model_name = filename.split("_(Instrumental)_")[1].split(".")[0]
else:
# Try to extract stem type from parentheses
import re
match = re.search(r'_\(([^)]+)\)_([^.]+)', filename)
if match:
stem_type = match.group(1)
model_name = match.group(2)
else:
self.logger.warning(f"Could not parse stem type and model from filename: {filename}")
continue
# Find the matching backing vocals model
matching_bv_model = None
for bv_model in self.backing_vocals_models:
if model_name == bv_model or bv_model.startswith(model_name) or model_name.startswith(bv_model.split('.')[0]):
matching_bv_model = bv_model
break
if matching_bv_model:
if matching_bv_model not in result:
result[matching_bv_model] = {}
if stem_type == "Vocals":
target_path = os.path.join(stems_dir, f"{artist_title} (Lead Vocals {matching_bv_model}).{self.lossless_output_format}")
shutil.move(file_path, target_path)
result[matching_bv_model]["lead_vocals"] = target_path
elif stem_type == "Instrumental":
target_path = os.path.join(stems_dir, f"{artist_title} (Backing Vocals {matching_bv_model}).{self.lossless_output_format}")
shutil.move(file_path, target_path)
result[matching_bv_model]["backing_vocals"] = target_path
return result
def _create_stems_directory(self, track_output_dir):
stems_dir = os.path.join(track_output_dir, "stems")
os.makedirs(stems_dir, exist_ok=True)
self.logger.info(f"Created stems directory: {stems_dir}")
return stems_dir
def _separate_clean_instrumental(self, separator, audio_file, artist_title, track_output_dir, stems_dir):
self.logger.info(f"Separating using clean instrumental model: {self.clean_instrumental_model}")
instrumental_path = os.path.join(
track_output_dir, f"{artist_title} (Instrumental {self.clean_instrumental_model}).{self.lossless_output_format}"
)
vocals_path = os.path.join(stems_dir, f"{artist_title} (Vocals {self.clean_instrumental_model}).{self.lossless_output_format}")
result = {}
if not self._file_exists(instrumental_path) or not self._file_exists(vocals_path):
separator.load_model(model_filename=self.clean_instrumental_model)
clean_output_files = separator.separate(audio_file)
for file in clean_output_files:
if "(Vocals)" in file and not self._file_exists(vocals_path):
shutil.move(file, vocals_path)
result["vocals"] = vocals_path
elif "(Instrumental)" in file and not self._file_exists(instrumental_path):
shutil.move(file, instrumental_path)
result["instrumental"] = instrumental_path
else:
result["vocals"] = vocals_path
result["instrumental"] = instrumental_path
return result
def _separate_other_stems(self, separator, audio_file, artist_title, stems_dir):
self.logger.info(f"Separating using other stems models: {self.other_stems_models}")
result = {}
for model in self.other_stems_models:
self.logger.info(f"Processing with model: {model}")
result[model] = {}
# Check if any stem files for this model already exist
existing_stems = glob.glob(os.path.join(stems_dir, f"{artist_title} (*{model}).{self.lossless_output_format}"))
if existing_stems:
self.logger.info(f"Found existing stem files for model {model}, skipping separation")
for stem_file in existing_stems:
stem_name = os.path.basename(stem_file).split("(")[1].split(")")[0].strip()
result[model][stem_name] = stem_file
else:
separator.load_model(model_filename=model)
other_stems_output = separator.separate(audio_file)
for file in other_stems_output:
file_name = os.path.basename(file)
stem_name = file_name[file_name.rfind("_(") + 2 : file_name.rfind(")_")]
new_filename = f"{artist_title} ({stem_name} {model}).{self.lossless_output_format}"
other_stem_path = os.path.join(stems_dir, new_filename)
if not self._file_exists(other_stem_path):
shutil.move(file, other_stem_path)
result[model][stem_name] = other_stem_path
return result
def _separate_backing_vocals(self, separator, vocals_path, artist_title, stems_dir):
self.logger.info(f"Separating clean vocals using backing vocals models: {self.backing_vocals_models}")
result = {}
for model in self.backing_vocals_models:
self.logger.info(f"Processing with model: {model}")
result[model] = {}
lead_vocals_path = os.path.join(stems_dir, f"{artist_title} (Lead Vocals {model}).{self.lossless_output_format}")
backing_vocals_path = os.path.join(stems_dir, f"{artist_title} (Backing Vocals {model}).{self.lossless_output_format}")
if not self._file_exists(lead_vocals_path) or not self._file_exists(backing_vocals_path):
separator.load_model(model_filename=model)
backing_vocals_output = separator.separate(vocals_path)
for file in backing_vocals_output:
if "(Vocals)" in file and not self._file_exists(lead_vocals_path):
shutil.move(file, lead_vocals_path)
result[model]["lead_vocals"] = lead_vocals_path
elif "(Instrumental)" in file and not self._file_exists(backing_vocals_path):
shutil.move(file, backing_vocals_path)
result[model]["backing_vocals"] = backing_vocals_path
else:
result[model]["lead_vocals"] = lead_vocals_path
result[model]["backing_vocals"] = backing_vocals_path
return result
def _generate_combined_instrumentals(self, instrumental_path, backing_vocals_result, artist_title, track_output_dir):
self.logger.info("Generating combined instrumental tracks with backing vocals")
result = {}
for model, paths in backing_vocals_result.items():
backing_vocals_path = paths["backing_vocals"]
combined_path = os.path.join(track_output_dir, f"{artist_title} (Instrumental +BV {model}).{self.lossless_output_format}")
if not self._file_exists(combined_path):
ffmpeg_command = (
f'{self.ffmpeg_base_command} -i "{instrumental_path}" -i "{backing_vocals_path}" '
f'-filter_complex "[0:a][1:a]amix=inputs=2:duration=longest:weights=1 1" '
f'-c:a {self.lossless_output_format.lower()} "{combined_path}"'
)
self.logger.debug(f"Running command: {ffmpeg_command}")
os.system(ffmpeg_command)
result[model] = combined_path
return result
def _normalize_audio_files(self, separation_result, artist_title, track_output_dir):
self.logger.info("Normalizing clean instrumental and combined instrumentals")
files_to_normalize = [
("clean_instrumental", separation_result["clean_instrumental"]["instrumental"]),
] + [("combined_instrumentals", path) for path in separation_result["combined_instrumentals"].values()]
for key, file_path in files_to_normalize:
if self._file_exists(file_path):
try:
self._normalize_audio(file_path, file_path) # Normalize in-place
# Verify the normalized file
if os.path.getsize(file_path) > 0:
self.logger.info(f"Successfully normalized: {file_path}")
else:
raise Exception("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")
def _normalize_audio(self, input_path, output_path, target_level=0.0):
self.logger.info(f"Normalizing audio file: {input_path}")
# Load audio file
audio = AudioSegment.from_file(input_path, format=self.lossless_output_format.lower())
# 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, overwriting the original file
normalized_audio.export(output_path, format=self.lossless_output_format.lower())
self.logger.info(f"Normalized audio saved, replacing: {output_path}")
self.logger.debug(f"Original peak: {peak_amplitude} dB, Applied gain: {gain_db} dB")
def apply_countdown_padding_to_instrumentals(self, separation_result, padding_seconds, artist_title, track_output_dir):
"""
Apply countdown padding to all instrumental audio files.
When LyricsTranscriber adds countdown padding to vocals, this method ensures
all instrumental tracks are padded by the same amount to maintain synchronization.
Args:
separation_result: Dictionary containing paths to separated audio files
padding_seconds: Amount of padding to apply (e.g., 3.0)
artist_title: Artist and title string for naming padded files
track_output_dir: Output directory for padded files
Returns:
Dictionary with updated paths to padded instrumental files
"""
self.logger.info(
f"Applying {padding_seconds}s countdown padding to all instrumental files to match vocal padding"
)
padded_result = {
"clean_instrumental": {},
"other_stems": {},
"backing_vocals": {},
"combined_instrumentals": {},
}
# Pad clean instrumental
if "clean_instrumental" in separation_result and separation_result["clean_instrumental"].get("instrumental"):
original_instrumental = separation_result["clean_instrumental"]["instrumental"]
# Insert "Padded" before the file extension
base, ext = os.path.splitext(original_instrumental)
padded_instrumental = f"{base} (Padded){ext}"
if not self._file_exists(padded_instrumental):
self.logger.info(f"Padding clean instrumental: {original_instrumental}")
self.pad_audio_file(original_instrumental, padded_instrumental, padding_seconds)
padded_result["clean_instrumental"]["instrumental"] = padded_instrumental
padded_result["clean_instrumental"]["vocals"] = separation_result["clean_instrumental"].get("vocals")
# Pad combined instrumentals (instrumental + backing vocals)
if "combined_instrumentals" in separation_result:
for model, combined_path in separation_result["combined_instrumentals"].items():
base, ext = os.path.splitext(combined_path)
padded_combined = f"{base} (Padded){ext}"
if not self._file_exists(padded_combined):
self.logger.info(f"Padding combined instrumental ({model}): {combined_path}")
self.pad_audio_file(combined_path, padded_combined, padding_seconds)
padded_result["combined_instrumentals"][model] = padded_combined
# Copy over other stems and backing vocals without padding
# (these are typically not used in final output, but preserve the structure)
padded_result["other_stems"] = separation_result.get("other_stems", {})
padded_result["backing_vocals"] = separation_result.get("backing_vocals", {})
self.logger.info(
f"✓ Countdown padding applied to {len(padded_result['combined_instrumentals']) + 1} instrumental file(s)"
)
return padded_result
+167
View File
@@ -0,0 +1,167 @@
import os
import sys
import json
import logging
# Default style parameters if no JSON file is provided or if it's invalid
DEFAULT_STYLE_PARAMS = {
"intro": {
"video_duration": 5,
"existing_image": None,
"background_color": "#000000",
"background_image": None,
"font": "Montserrat-Bold.ttf",
"artist_color": "#ffdf6b",
"artist_gradient": None,
"title_color": "#ffffff",
"title_gradient": None,
"title_region": "370, 200, 3100, 480",
"artist_region": "370, 700, 3100, 480",
"extra_text": None,
"extra_text_color": "#ffffff",
"extra_text_gradient": None,
"extra_text_region": "370, 1200, 3100, 480",
"title_text_transform": None, # none, uppercase, lowercase, propercase
"artist_text_transform": None, # none, uppercase, lowercase, propercase
},
"end": {
"video_duration": 5,
"existing_image": None,
"background_color": "#000000",
"background_image": None,
"font": "Montserrat-Bold.ttf",
"artist_color": "#ffdf6b",
"artist_gradient": None,
"title_color": "#ffffff",
"title_gradient": None,
"title_region": None,
"artist_region": None,
"extra_text": "THANK YOU FOR SINGING!",
"extra_text_color": "#ff7acc",
"extra_text_gradient": None,
"extra_text_region": None,
"title_text_transform": None, # none, uppercase, lowercase, propercase
"artist_text_transform": None, # none, uppercase, lowercase, propercase
},
}
def apply_style_overrides(style_params, overrides, logger):
"""Recursively applies overrides to the style parameters."""
for key, value in overrides.items():
keys = key.split('.')
current_level = style_params
for i, k in enumerate(keys):
if i == len(keys) - 1:
if k in current_level:
# Attempt to cast the value to the type of the existing value
try:
original_type = type(current_level[k])
if original_type == bool:
# Handle boolean conversion
value = value.lower() in ('true', '1', 't', 'y', 'yes')
else:
value = original_type(value)
except (ValueError, TypeError) as e:
logger.warning(f"Could not cast override value '{value}' for key '{key}' to original type. Using as string. Error: {e}")
current_level[k] = value
logger.info(f"Overrode style: {key} = {value}")
else:
logger.warning(f"Override key '{key}' not found in style parameters.")
elif k in current_level and isinstance(current_level[k], dict):
current_level = current_level[k]
else:
logger.warning(f"Override key part '{k}' not found or not a dictionary for key '{key}'.")
break
def load_style_params(style_params_json, style_overrides, logger):
"""Loads style parameters from a JSON file or uses defaults."""
style_params = {}
if style_params_json:
try:
with open(style_params_json, "r") as f:
style_params = json.loads(f.read())
logger.info(f"Loaded style parameters from {style_params_json}")
except FileNotFoundError:
logger.error(f"Style parameters configuration file not found: {style_params_json}")
sys.exit(1)
except json.JSONDecodeError as e:
logger.error(f"Invalid JSON in style parameters configuration file: {e}")
sys.exit(1)
except Exception as e:
logger.error(f"Error loading style parameters file {style_params_json}: {e}")
sys.exit(1)
else:
logger.info("No style parameters JSON file provided. Using default styles.")
style_params = DEFAULT_STYLE_PARAMS
if style_overrides:
apply_style_overrides(style_params, style_overrides, logger)
return style_params
def setup_title_format(style_params):
"""Sets up the title format dictionary from style parameters."""
intro_params = style_params.get("intro", DEFAULT_STYLE_PARAMS["intro"])
return {
"background_color": intro_params.get("background_color", DEFAULT_STYLE_PARAMS["intro"]["background_color"]),
"background_image": intro_params.get("background_image"),
"font": intro_params.get("font", DEFAULT_STYLE_PARAMS["intro"]["font"]),
"artist_color": intro_params.get("artist_color", DEFAULT_STYLE_PARAMS["intro"]["artist_color"]),
"artist_gradient": intro_params.get("artist_gradient"),
"title_color": intro_params.get("title_color", DEFAULT_STYLE_PARAMS["intro"]["title_color"]),
"title_gradient": intro_params.get("title_gradient"),
"extra_text": intro_params.get("extra_text"),
"extra_text_color": intro_params.get("extra_text_color", DEFAULT_STYLE_PARAMS["intro"]["extra_text_color"]),
"extra_text_gradient": intro_params.get("extra_text_gradient"),
"extra_text_region": intro_params.get("extra_text_region", DEFAULT_STYLE_PARAMS["intro"]["extra_text_region"]),
"title_region": intro_params.get("title_region", DEFAULT_STYLE_PARAMS["intro"]["title_region"]),
"artist_region": intro_params.get("artist_region", DEFAULT_STYLE_PARAMS["intro"]["artist_region"]),
"title_text_transform": intro_params.get("title_text_transform"),
"artist_text_transform": intro_params.get("artist_text_transform"),
}
def setup_end_format(style_params):
"""Sets up the end format dictionary from style parameters."""
end_params = style_params.get("end", DEFAULT_STYLE_PARAMS["end"])
return {
"background_color": end_params.get("background_color", DEFAULT_STYLE_PARAMS["end"]["background_color"]),
"background_image": end_params.get("background_image"),
"font": end_params.get("font", DEFAULT_STYLE_PARAMS["end"]["font"]),
"artist_color": end_params.get("artist_color", DEFAULT_STYLE_PARAMS["end"]["artist_color"]),
"artist_gradient": end_params.get("artist_gradient"),
"title_color": end_params.get("title_color", DEFAULT_STYLE_PARAMS["end"]["title_color"]),
"title_gradient": end_params.get("title_gradient"),
"extra_text": end_params.get("extra_text", DEFAULT_STYLE_PARAMS["end"]["extra_text"]),
"extra_text_color": end_params.get("extra_text_color", DEFAULT_STYLE_PARAMS["end"]["extra_text_color"]),
"extra_text_gradient": end_params.get("extra_text_gradient"),
"extra_text_region": end_params.get("extra_text_region"),
"title_region": end_params.get("title_region"),
"artist_region": end_params.get("artist_region"),
"title_text_transform": end_params.get("title_text_transform"),
"artist_text_transform": end_params.get("artist_text_transform"),
}
def get_video_durations(style_params):
"""Gets intro and end video durations from style parameters."""
intro_duration = style_params.get("intro", {}).get("video_duration", DEFAULT_STYLE_PARAMS["intro"]["video_duration"])
end_duration = style_params.get("end", {}).get("video_duration", DEFAULT_STYLE_PARAMS["end"]["video_duration"])
return intro_duration, end_duration
def get_existing_images(style_params):
"""Gets existing title and end images from style parameters."""
existing_title_image = style_params.get("intro", {}).get("existing_image")
existing_end_image = style_params.get("end", {}).get("existing_image")
return existing_title_image, existing_end_image
def setup_ffmpeg_command(log_level):
"""Sets up the base ffmpeg command string based on log level."""
# Path to the Windows PyInstaller frozen bundled ffmpeg.exe, or the system-installed FFmpeg binary on Mac/Linux
ffmpeg_path = os.path.join(sys._MEIPASS, "ffmpeg.exe") if getattr(sys, "frozen", False) else "ffmpeg"
ffmpeg_base_command = f"{ffmpeg_path} -hide_banner -nostats"
if log_level == logging.DEBUG:
ffmpeg_base_command += " -loglevel verbose"
else:
ffmpeg_base_command += " -loglevel fatal"
return ffmpeg_base_command
+222
View File
@@ -0,0 +1,222 @@
import os
import glob
import logging
import shutil
import tempfile
import yt_dlp.YoutubeDL as ydl
from .utils import sanitize_filename
# Placeholder class or functions for file handling
class FileHandler:
def __init__(self, logger, ffmpeg_base_command, create_track_subfolders, dry_run):
self.logger = logger
self.ffmpeg_base_command = ffmpeg_base_command
self.create_track_subfolders = create_track_subfolders
self.dry_run = dry_run
def _file_exists(self, file_path):
"""Check if a file exists and log the result."""
exists = os.path.isfile(file_path)
if exists:
self.logger.info(f"File already exists, skipping creation: {file_path}")
return exists
# Placeholder methods - to be filled by user moving code
def copy_input_media(self, input_media, output_filename_no_extension):
self.logger.debug(f"Copying media from local path {input_media} to filename {output_filename_no_extension} + existing extension")
copied_file_name = output_filename_no_extension + os.path.splitext(input_media)[1]
self.logger.debug(f"Target filename: {copied_file_name}")
# Check if source and destination are the same
if os.path.abspath(input_media) == os.path.abspath(copied_file_name):
self.logger.info("Source and destination are the same file, skipping copy")
return input_media
self.logger.debug(f"Copying {input_media} to {copied_file_name}")
shutil.copy2(input_media, copied_file_name)
return copied_file_name
def download_video(self, url, output_filename_no_extension, cookies_str=None):
self.logger.debug(f"Downloading media from URL {url} to filename {output_filename_no_extension} + (as yet) unknown extension")
ydl_opts = {
"quiet": True,
"format": "bv*+ba/b", # if a combined video + audio format is better than the best video-only format use the combined format
"outtmpl": f"{output_filename_no_extension}.%(ext)s",
# Enhanced anti-detection options
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"referer": "https://www.youtube.com/",
"sleep_interval": 1,
"max_sleep_interval": 3,
"fragment_retries": 3,
"extractor_retries": 3,
"retries": 3,
# Headers to appear more human
"http_headers": {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-us,en;q=0.5",
"Accept-Encoding": "gzip, deflate",
"DNT": "1",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1",
},
}
# Add cookies if provided
if cookies_str:
self.logger.info("Using provided cookies for enhanced YouTube download access")
# Save cookies to a temporary file
import tempfile
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
f.write(cookies_str)
ydl_opts['cookiefile'] = f.name
else:
self.logger.info("No cookies provided for download - attempting standard download")
try:
with ydl(ydl_opts) as ydl_instance:
ydl_instance.download([url])
# Search for the file with any extension
downloaded_files = glob.glob(f"{output_filename_no_extension}.*")
if downloaded_files:
downloaded_file_name = downloaded_files[0] # Assume the first match is the correct one
self.logger.info(f"Download finished, returning downloaded filename: {downloaded_file_name}")
return downloaded_file_name
else:
self.logger.error("No files found matching the download pattern.")
return None
finally:
# Clean up temporary cookie file if it was created
if cookies_str and 'cookiefile' in ydl_opts:
try:
import os
os.unlink(ydl_opts['cookiefile'])
except:
pass
def extract_still_image_from_video(self, input_filename, output_filename_no_extension):
output_filename = output_filename_no_extension + ".png"
self.logger.info(f"Extracting still image from position 30s input media")
ffmpeg_command = f'{self.ffmpeg_base_command} -i "{input_filename}" -ss 00:00:30 -vframes 1 "{output_filename}"'
self.logger.debug(f"Running command: {ffmpeg_command}")
os.system(ffmpeg_command)
return output_filename
def convert_to_wav(self, input_filename, output_filename_no_extension):
"""Convert input audio to WAV format, with input validation."""
# Validate input file exists and is readable
if not os.path.isfile(input_filename):
raise Exception(f"Input audio file not found: {input_filename}")
if os.path.getsize(input_filename) == 0:
raise Exception(f"Input audio file is empty: {input_filename}")
# Validate input file format using ffprobe
probe_command = f'ffprobe -v error -show_entries stream=codec_type -of default=noprint_wrappers=1 "{input_filename}"'
probe_output = os.popen(probe_command).read()
if "codec_type=audio" not in probe_output:
raise Exception(f"No valid audio stream found in file: {input_filename}")
output_filename = output_filename_no_extension + ".wav"
self.logger.info(f"Converting input media to audio WAV file")
ffmpeg_command = f'{self.ffmpeg_base_command} -n -i "{input_filename}" "{output_filename}"'
self.logger.debug(f"Running command: {ffmpeg_command}")
if not self.dry_run:
os.system(ffmpeg_command)
return output_filename
def setup_output_paths(self, output_dir, artist, title):
if title is None and artist is None:
raise ValueError("Error: At least title or artist must be provided")
# If only title is provided, use it for both artist and title portions of paths
if artist is None:
sanitized_title = sanitize_filename(title)
artist_title = sanitized_title
else:
sanitized_artist = sanitize_filename(artist)
sanitized_title = sanitize_filename(title)
artist_title = f"{sanitized_artist} - {sanitized_title}"
track_output_dir = output_dir
if self.create_track_subfolders:
track_output_dir = os.path.join(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 backup_existing_outputs(self, track_output_dir, artist, title):
"""
Backup existing outputs to a versioned folder.
Args:
track_output_dir: The directory containing the track outputs
artist: The artist name
title: The track title
Returns:
The path to the original input audio file
"""
self.logger.info(f"Backing up existing outputs for {artist} - {title}")
# Sanitize artist and title for filenames
sanitized_artist = sanitize_filename(artist)
sanitized_title = sanitize_filename(title)
base_name = f"{sanitized_artist} - {sanitized_title}"
# Find the next available version number
version_num = 1
while os.path.exists(os.path.join(track_output_dir, f"version-{version_num}")):
version_num += 1
version_dir = os.path.join(track_output_dir, f"version-{version_num}")
self.logger.info(f"Creating backup directory: {version_dir}")
os.makedirs(version_dir, exist_ok=True)
# Find the input audio file (we'll need this for re-running the transcription)
input_audio_wav = os.path.join(track_output_dir, f"{base_name}.wav")
if not os.path.exists(input_audio_wav):
self.logger.warning(f"Input audio file not found: {input_audio_wav}")
# Try to find any WAV file
wav_files = glob.glob(os.path.join(track_output_dir, "*.wav"))
if wav_files:
input_audio_wav = wav_files[0]
self.logger.info(f"Using alternative input audio file: {input_audio_wav}")
else:
raise Exception(f"No input audio file found in {track_output_dir}")
# List of file patterns to move
file_patterns = [
f"{base_name} (With Vocals).*",
f"{base_name} (Karaoke).*",
f"{base_name} (Final Karaoke*).*",
]
# Move files matching patterns to version directory
for pattern in file_patterns:
for file_path in glob.glob(os.path.join(track_output_dir, pattern)):
if os.path.isfile(file_path):
dest_path = os.path.join(version_dir, os.path.basename(file_path))
self.logger.info(f"Moving {file_path} to {dest_path}")
if not self.dry_run:
shutil.move(file_path, dest_path)
# Also backup the lyrics directory
lyrics_dir = os.path.join(track_output_dir, "lyrics")
if os.path.exists(lyrics_dir):
lyrics_backup_dir = os.path.join(version_dir, "lyrics")
self.logger.info(f"Backing up lyrics directory to {lyrics_backup_dir}")
if not self.dry_run:
shutil.copytree(lyrics_dir, lyrics_backup_dir)
# Remove the original lyrics directory
shutil.rmtree(lyrics_dir)
return input_audio_wav
File diff suppressed because it is too large. Load diff
+780
View File
@@ -0,0 +1,780 @@
import os
import sys
import re
import glob
import logging
import tempfile
import shutil
import asyncio
import signal
import time
import fcntl
import errno
import psutil
from datetime import datetime
import importlib.resources as pkg_resources
import json
from dotenv import load_dotenv
from .config import (
load_style_params,
setup_title_format,
setup_end_format,
get_video_durations,
get_existing_images,
setup_ffmpeg_command,
)
from .metadata import extract_info_for_online_media, parse_track_metadata
from .file_handler import FileHandler
from .audio_processor import AudioProcessor
from .lyrics_processor import LyricsProcessor
from .video_generator import VideoGenerator
class KaraokePrep:
def __init__(
self,
# Basic inputs
input_media=None,
artist=None,
title=None,
filename_pattern=None,
# Logging & Debugging
dry_run=False,
logger=None,
log_level=logging.DEBUG,
log_formatter=None,
render_bounding_boxes=False,
# Input/Output Configuration
output_dir=".",
create_track_subfolders=False,
lossless_output_format="FLAC",
output_png=True,
output_jpg=True,
# Audio Processing Configuration
clean_instrumental_model="model_bs_roformer_ep_317_sdr_12.9755.ckpt",
backing_vocals_models=["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"],
other_stems_models=["htdemucs_6s.yaml"],
model_file_dir=os.path.join(tempfile.gettempdir(), "audio-separator-models"),
existing_instrumental=None,
# Lyrics Configuration
lyrics_artist=None,
lyrics_title=None,
lyrics_file=None,
skip_lyrics=False,
skip_transcription=False,
skip_transcription_review=False,
render_video=True,
subtitle_offset_ms=0,
# Style Configuration
style_params_json=None,
style_overrides=None,
# Add the new parameter
skip_separation=False,
# YouTube/Online Configuration
cookies_str=None,
):
self.log_level = log_level
self.log_formatter = log_formatter
if logger is None:
self.logger = logging.getLogger(__name__)
self.logger.setLevel(log_level)
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)
else:
self.logger = logger
self.logger.debug(f"KaraokePrep instantiating with input_media: {input_media} artist: {artist} title: {title}")
self.dry_run = dry_run
self.extractor = None # Will be set later based on source (Original or yt-dlp extractor)
self.media_id = None # Will be set by parse_track_metadata if applicable
self.url = None # Will be set by parse_track_metadata if applicable
self.input_media = input_media
self.artist = artist
self.title = title
self.filename_pattern = filename_pattern
# Input/Output - Keep these as they might be needed for logic outside handlers or passed to multiple handlers
self.output_dir = output_dir
self.lossless_output_format = lossless_output_format.lower()
self.create_track_subfolders = create_track_subfolders
self.output_png = output_png
self.output_jpg = output_jpg
# Lyrics Config - Keep needed ones
self.lyrics_artist = lyrics_artist
self.lyrics_title = lyrics_title
self.lyrics_file = lyrics_file # Passed to LyricsProcessor
self.skip_lyrics = skip_lyrics # Used in prep_single_track logic
self.skip_transcription = skip_transcription # Passed to LyricsProcessor
self.skip_transcription_review = skip_transcription_review # Passed to LyricsProcessor
self.render_video = render_video # Passed to LyricsProcessor
self.subtitle_offset_ms = subtitle_offset_ms # Passed to LyricsProcessor
# Audio Config - Keep needed ones
self.existing_instrumental = existing_instrumental # Used in prep_single_track logic
self.skip_separation = skip_separation # Used in prep_single_track logic
self.model_file_dir = model_file_dir # Passed to AudioProcessor
# Style Config - Keep needed ones
self.render_bounding_boxes = render_bounding_boxes # Passed to VideoGenerator
self.style_params_json = style_params_json
self.style_overrides = style_overrides
self.temp_style_file = None
# YouTube/Online Config
self.cookies_str = cookies_str # Passed to metadata extraction and file download
# Load style parameters using the config module
self.style_params = load_style_params(self.style_params_json, self.style_overrides, self.logger)
# If overrides were applied, write to a temp file and update the path
if self.style_overrides:
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".json") as temp_file:
json.dump(self.style_params, temp_file, indent=2)
self.temp_style_file = temp_file.name
self.style_params_json = self.temp_style_file
self.logger.info(f"Style overrides applied. Using temporary style file: {self.temp_style_file}")
# Set up title and end formats using the config module
self.title_format = setup_title_format(self.style_params)
self.end_format = setup_end_format(self.style_params)
# Get video durations and existing images using the config module
self.intro_video_duration, self.end_video_duration = get_video_durations(self.style_params)
self.existing_title_image, self.existing_end_image = get_existing_images(self.style_params)
# Set up ffmpeg command using the config module
self.ffmpeg_base_command = setup_ffmpeg_command(self.log_level)
# Instantiate Handlers
self.file_handler = FileHandler(
logger=self.logger,
ffmpeg_base_command=self.ffmpeg_base_command,
create_track_subfolders=self.create_track_subfolders,
dry_run=self.dry_run,
)
self.audio_processor = AudioProcessor(
logger=self.logger,
log_level=self.log_level,
log_formatter=self.log_formatter,
model_file_dir=self.model_file_dir,
lossless_output_format=self.lossless_output_format,
clean_instrumental_model=clean_instrumental_model, # Passed directly from args
backing_vocals_models=backing_vocals_models, # Passed directly from args
other_stems_models=other_stems_models, # Passed directly from args
ffmpeg_base_command=self.ffmpeg_base_command,
)
self.lyrics_processor = LyricsProcessor(
logger=self.logger,
style_params_json=self.style_params_json,
lyrics_file=self.lyrics_file,
skip_transcription=self.skip_transcription,
skip_transcription_review=self.skip_transcription_review,
render_video=self.render_video,
subtitle_offset_ms=self.subtitle_offset_ms,
)
self.video_generator = VideoGenerator(
logger=self.logger,
ffmpeg_base_command=self.ffmpeg_base_command,
render_bounding_boxes=self.render_bounding_boxes,
output_png=self.output_png,
output_jpg=self.output_jpg,
)
self.logger.debug(f"Initialized title_format with extra_text: {self.title_format['extra_text']}")
self.logger.debug(f"Initialized title_format with extra_text_region: {self.title_format['extra_text_region']}")
self.logger.debug(f"Initialized end_format with extra_text: {self.end_format['extra_text']}")
self.logger.debug(f"Initialized end_format with extra_text_region: {self.end_format['extra_text_region']}")
self.extracted_info = None # Will be populated by extract_info_for_online_media if needed
self.persistent_artist = None # Used for playlists
self.logger.debug(f"KaraokePrep lossless_output_format: {self.lossless_output_format}")
# Use FileHandler method to check/create output dir
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 __del__(self):
# Cleanup the temporary style file if it was created
if self.temp_style_file and os.path.exists(self.temp_style_file):
try:
os.remove(self.temp_style_file)
self.logger.debug(f"Removed temporary style file: {self.temp_style_file}")
except OSError as e:
self.logger.warning(f"Error removing temporary style file {self.temp_style_file}: {e}")
# Compatibility methods for tests - these call the new functions in metadata.py
def extract_info_for_online_media(self, input_url=None, input_artist=None, input_title=None):
"""Compatibility method that calls the function in metadata.py"""
self.extracted_info = extract_info_for_online_media(input_url, input_artist, input_title, self.logger, self.cookies_str)
return self.extracted_info
def parse_single_track_metadata(self, input_artist, input_title):
"""Compatibility method that calls the function in metadata.py"""
metadata_result = parse_track_metadata(self.extracted_info, input_artist, input_title, self.persistent_artist, self.logger)
self.url = metadata_result["url"]
self.extractor = metadata_result["extractor"]
self.media_id = metadata_result["media_id"]
self.artist = metadata_result["artist"]
self.title = metadata_result["title"]
async def prep_single_track(self):
# Add signal handler at the start
loop = asyncio.get_running_loop()
for sig in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(sig, lambda s=sig: asyncio.create_task(self.shutdown(s)))
try:
self.logger.info(f"Preparing single track: {self.artist} - {self.title}")
# Determine extractor early based on input type
# Assume self.extractor, self.url, self.media_id etc. are set by process() before calling this
if self.input_media and os.path.isfile(self.input_media):
if not self.extractor: # If extractor wasn't somehow set before (e.g., direct call)
self.extractor = "Original"
elif self.url: # If it's a URL (set by process)
if not self.extractor: # Should have been set by parse_track_metadata in process()
self.logger.warning("Extractor not set before prep_single_track for URL, attempting fallback logic.")
# Fallback logic (less ideal, relies on potentially missing info)
if self.extracted_info and self.extracted_info.get('extractor'):
self.extractor = self.extracted_info['extractor']
elif self.media_id: # Try to guess based on ID format
# Basic youtube id check
if re.match(r'^[a-zA-Z0-9_-]{11}$', self.media_id):
self.extractor = "youtube"
else:
self.extractor = "UnknownSource" # Fallback if ID doesn't look like youtube
else:
self.extractor = "UnknownSource" # Final fallback
self.logger.info(f"Fallback extractor set to: {self.extractor}")
elif self.input_media: # Not a file, not a URL -> maybe a direct URL string?
self.logger.warning(f"Input media '{self.input_media}' is not a file and self.url was not set. Attempting to treat as URL.")
# This path requires calling extract/parse again, less efficient
try:
extracted = extract_info_for_online_media(self.input_media, self.artist, self.title, self.logger, self.cookies_str)
if extracted:
metadata_result = parse_track_metadata(
extracted, self.artist, self.title, self.persistent_artist, self.logger
)
self.url = metadata_result["url"]
self.extractor = metadata_result["extractor"]
self.media_id = metadata_result["media_id"]
self.artist = metadata_result["artist"]
self.title = metadata_result["title"]
self.logger.info(f"Successfully extracted metadata within prep_single_track for {self.input_media}")
else:
self.logger.error(f"Could not extract info for {self.input_media} within prep_single_track.")
self.extractor = "ErrorExtracting"
return None # Cannot proceed without metadata
except Exception as meta_exc:
self.logger.error(f"Error during metadata extraction/parsing within prep_single_track: {meta_exc}")
self.extractor = "ErrorParsing"
return None # Cannot proceed
else:
# If it's neither file nor URL, and input_media is None, check for existing files
# This path is mainly for the case where files exist from previous run
# We still need artist/title for filename generation
if not self.artist or not self.title:
self.logger.error("Cannot determine output path without artist/title when input_media is None and not a URL.")
return None
self.logger.info("Input media is None, assuming check for existing files based on artist/title.")
# We need a nominal extractor for filename matching if files exist
# Let's default to 'UnknownExisting' or try to infer if possible later
if not self.extractor:
self.extractor = "UnknownExisting"
if not self.extractor:
self.logger.error("Could not determine extractor for the track.")
return None
# Now self.extractor should be set correctly for path generation etc.
self.logger.info(f"Preparing output path for track: {self.title} by {self.artist} (Extractor: {self.extractor})")
if self.dry_run:
return None
# Delegate to FileHandler
track_output_dir, artist_title = self.file_handler.setup_output_paths(self.output_dir, self.artist, self.title)
processed_track = {
"track_output_dir": track_output_dir,
"artist": self.artist,
"title": self.title,
"extractor": self.extractor,
"extracted_info": self.extracted_info,
"lyrics": None,
"processed_lyrics": None,
"separated_audio": {},
}
processed_track["input_media"] = None
processed_track["input_still_image"] = None
processed_track["input_audio_wav"] = None
if self.input_media and os.path.isfile(self.input_media):
# --- Local File Input Handling ---
input_wav_filename_pattern = os.path.join(track_output_dir, f"{artist_title} ({self.extractor}*).wav")
input_wav_glob = glob.glob(input_wav_filename_pattern)
if input_wav_glob:
processed_track["input_audio_wav"] = input_wav_glob[0]
self.logger.info(f"Input media WAV file already exists, skipping conversion: {processed_track['input_audio_wav']}")
else:
output_filename_no_extension = os.path.join(track_output_dir, f"{artist_title} ({self.extractor})")
self.logger.info(f"Copying input media from {self.input_media} to new directory...")
# Delegate to FileHandler
processed_track["input_media"] = self.file_handler.copy_input_media(self.input_media, output_filename_no_extension)
self.logger.info("Converting input media to WAV for audio processing...")
# Delegate to FileHandler
processed_track["input_audio_wav"] = self.file_handler.convert_to_wav(processed_track["input_media"], output_filename_no_extension)
else:
# --- URL or Existing Files Handling ---
# Construct patterns using the determined extractor
base_pattern = os.path.join(track_output_dir, f"{artist_title} ({self.extractor}*)")
input_media_glob = glob.glob(f"{base_pattern}.*webm") + glob.glob(f"{base_pattern}.*mp4") # Add other common formats if needed
input_png_glob = glob.glob(f"{base_pattern}.png")
input_wav_glob = glob.glob(f"{base_pattern}.wav")
if input_media_glob and input_png_glob and input_wav_glob:
# Existing files found
processed_track["input_media"] = input_media_glob[0]
processed_track["input_still_image"] = input_png_glob[0]
processed_track["input_audio_wav"] = input_wav_glob[0]
self.logger.info(f"Found existing media files matching extractor '{self.extractor}', skipping download/conversion.")
# Ensure self.extractor reflects the found files if it was a fallback
# Extract the actual extractor string from the filename if needed, though it should match
elif self.url: # URL provided and files not found, proceed with download
# Use media_id if available for better uniqueness
filename_suffix = f"{self.extractor} {self.media_id}" if self.media_id else self.extractor
output_filename_no_extension = os.path.join(track_output_dir, f"{artist_title} ({filename_suffix})")
self.logger.info(f"Downloading input media from {self.url}...")
# Delegate to FileHandler
processed_track["input_media"] = self.file_handler.download_video(self.url, output_filename_no_extension, self.cookies_str)
self.logger.info("Extracting still image from downloaded media (if input is video)...")
# Delegate to FileHandler
processed_track["input_still_image"] = self.file_handler.extract_still_image_from_video(
processed_track["input_media"], output_filename_no_extension
)
self.logger.info("Converting downloaded video to WAV for audio processing...")
# Delegate to FileHandler
processed_track["input_audio_wav"] = self.file_handler.convert_to_wav(
processed_track["input_media"], output_filename_no_extension
)
else:
# This case means input_media was None, not a URL, and no existing files found
self.logger.error(f"Cannot proceed: No input file, no URL, and no existing files found for {artist_title}.")
return None
if self.skip_lyrics:
self.logger.info("Skipping lyrics fetch as requested.")
processed_track["lyrics"] = None
processed_track["processed_lyrics"] = None
# No countdown padding when lyrics are skipped
processed_track["countdown_padding_added"] = False
processed_track["countdown_padding_seconds"] = 0.0
processed_track["padded_vocals_audio"] = None
else:
lyrics_artist = self.lyrics_artist or self.artist
lyrics_title = self.lyrics_title or self.title
# Create futures for both operations
transcription_future = None
separation_future = None
self.logger.info("=== Starting Parallel Processing ===")
if not self.skip_lyrics:
self.logger.info("Creating transcription future...")
# Run transcription in a separate thread
transcription_future = asyncio.create_task(
asyncio.to_thread(
# Delegate to LyricsProcessor - pass original artist/title for filenames, lyrics_artist/lyrics_title for processing
self.lyrics_processor.transcribe_lyrics,
processed_track["input_audio_wav"],
self.artist, # Original artist for filename generation
self.title, # Original title for filename generation
track_output_dir,
lyrics_artist, # Lyrics artist for processing
lyrics_title # Lyrics title for processing
)
)
self.logger.info(f"Transcription future created, type: {type(transcription_future)}")
# Default to a placeholder task if separation won't run
separation_future = asyncio.create_task(asyncio.sleep(0))
# Only create real separation future if not skipping AND no existing instrumental provided
if not self.skip_separation and not self.existing_instrumental:
self.logger.info("Creating separation future (not skipping and no existing instrumental)...")
# Run separation in a separate thread
separation_future = asyncio.create_task(
asyncio.to_thread(
# Delegate to AudioProcessor
self.audio_processor.process_audio_separation,
audio_file=processed_track["input_audio_wav"],
artist_title=artist_title,
track_output_dir=track_output_dir,
)
)
self.logger.info(f"Separation future created, type: {type(separation_future)}")
elif self.existing_instrumental:
self.logger.info(f"Skipping separation future creation because existing instrumental was provided: {self.existing_instrumental}")
elif self.skip_separation: # Check this condition explicitly for clarity
self.logger.info("Skipping separation future creation because skip_separation is True.")
self.logger.info("About to await both operations with asyncio.gather...")
# Wait for both operations to complete
try:
results = await asyncio.gather(
transcription_future if transcription_future else asyncio.sleep(0), # Use placeholder if None
separation_future, # Already defaults to placeholder if not created
return_exceptions=True,
)
except asyncio.CancelledError:
self.logger.info("Received cancellation request, cleaning up...")
# Cancel any running futures
if transcription_future and not transcription_future.done():
transcription_future.cancel()
if separation_future and not separation_future.done() and not isinstance(separation_future, asyncio.Task): # Check if it's a real task
# Don't try to cancel the asyncio.sleep(0) placeholder
separation_future.cancel()
# Wait for futures to complete cancellation
await asyncio.gather(
transcription_future if transcription_future else asyncio.sleep(0),
separation_future if separation_future else asyncio.sleep(0), # Use placeholder if None/Placeholder
return_exceptions=True,
)
raise
# Handle transcription results
if transcription_future:
self.logger.info("Processing transcription results...")
try:
# Index 0 corresponds to transcription_future in gather
transcriber_outputs = results[0]
# Check if the result is an exception or the actual output
if isinstance(transcriber_outputs, Exception):
self.logger.error(f"Error during lyrics transcription: {transcriber_outputs}")
# Optionally log traceback: self.logger.exception("Transcription error:")
raise transcriber_outputs # Re-raise the exception
elif transcriber_outputs is not None and not isinstance(transcriber_outputs, asyncio.futures.Future): # Ensure it's not the placeholder future
self.logger.info(f"Successfully received transcription outputs: {type(transcriber_outputs)}")
# Ensure transcriber_outputs is a dictionary before calling .get()
if isinstance(transcriber_outputs, dict):
self.lyrics = transcriber_outputs.get("corrected_lyrics_text")
processed_track["lyrics"] = transcriber_outputs.get("corrected_lyrics_text_filepath")
# Capture countdown padding information
processed_track["countdown_padding_added"] = transcriber_outputs.get("countdown_padding_added", False)
processed_track["countdown_padding_seconds"] = transcriber_outputs.get("countdown_padding_seconds", 0.0)
processed_track["padded_vocals_audio"] = transcriber_outputs.get("padded_audio_filepath")
if processed_track["countdown_padding_added"]:
self.logger.info(
f"=== COUNTDOWN PADDING DETECTED ==="
)
self.logger.info(
f"Vocals have been padded with {processed_track['countdown_padding_seconds']}s of silence. "
f"Instrumental tracks will be padded after separation to maintain synchronization."
)
else:
self.logger.warning(f"Unexpected type for transcriber_outputs: {type(transcriber_outputs)}, value: {transcriber_outputs}")
else:
self.logger.info("Transcription task did not return results (possibly skipped or placeholder).")
except Exception as e:
self.logger.error(f"Error processing transcription results: {e}")
self.logger.exception("Full traceback:")
raise # Re-raise the exception
# Handle separation results only if a real future was created and ran
# Check if separation_future was the placeholder or a real task
# The result index in `results` depends on whether transcription_future existed
separation_result_index = 1 if transcription_future else 0
if separation_future is not None and isinstance(separation_future, asyncio.Task) and len(results) > separation_result_index:
self.logger.info("Processing separation results...")
try:
separation_results = results[separation_result_index]
# Check if the result is an exception or the actual output
if isinstance(separation_results, Exception):
self.logger.error(f"Error during audio separation: {separation_results}")
# Optionally log traceback: self.logger.exception("Separation error:")
# Decide if you want to raise here or just log
elif separation_results is not None and not isinstance(separation_results, asyncio.futures.Future): # Ensure it's not the placeholder future
self.logger.info(f"Successfully received separation results: {type(separation_results)}")
if isinstance(separation_results, dict):
processed_track["separated_audio"] = separation_results
else:
self.logger.warning(f"Unexpected type for separation_results: {type(separation_results)}, value: {separation_results}")
else:
self.logger.info("Separation task did not return results (possibly skipped or placeholder).")
except Exception as e:
self.logger.error(f"Error processing separation results: {e}")
self.logger.exception("Full traceback:")
# Decide if you want to raise here or just log
elif not self.skip_separation and not self.existing_instrumental:
# This case means separation was supposed to run but didn't return results properly
self.logger.warning("Separation task was expected but did not yield results or resulted in an error captured earlier.")
else:
# This case means separation was intentionally skipped
self.logger.info("Skipping processing of separation results as separation was not run.")
self.logger.info("=== Parallel Processing Complete ===")
output_image_filepath_noext = os.path.join(track_output_dir, f"{artist_title} (Title)")
processed_track["title_image_png"] = f"{output_image_filepath_noext}.png"
processed_track["title_image_jpg"] = f"{output_image_filepath_noext}.jpg"
processed_track["title_video"] = os.path.join(track_output_dir, f"{artist_title} (Title).mov")
# Use FileHandler._file_exists
if not self.file_handler._file_exists(processed_track["title_video"]) and not os.environ.get("KARAOKE_GEN_SKIP_TITLE_END_SCREENS"):
self.logger.info(f"Creating title video...")
# Delegate to VideoGenerator
self.video_generator.create_title_video(
artist=self.artist,
title=self.title,
format=self.title_format,
output_image_filepath_noext=output_image_filepath_noext,
output_video_filepath=processed_track["title_video"],
existing_title_image=self.existing_title_image,
intro_video_duration=self.intro_video_duration,
)
output_image_filepath_noext = os.path.join(track_output_dir, f"{artist_title} (End)")
processed_track["end_image_png"] = f"{output_image_filepath_noext}.png"
processed_track["end_image_jpg"] = f"{output_image_filepath_noext}.jpg"
processed_track["end_video"] = os.path.join(track_output_dir, f"{artist_title} (End).mov")
# Use FileHandler._file_exists
if not self.file_handler._file_exists(processed_track["end_video"]) and not os.environ.get("KARAOKE_GEN_SKIP_TITLE_END_SCREENS"):
self.logger.info(f"Creating end screen video...")
# Delegate to VideoGenerator
self.video_generator.create_end_video(
artist=self.artist,
title=self.title,
format=self.end_format,
output_image_filepath_noext=output_image_filepath_noext,
output_video_filepath=processed_track["end_video"],
existing_end_image=self.existing_end_image,
end_video_duration=self.end_video_duration,
)
if self.skip_separation:
self.logger.info("Skipping audio separation as requested.")
processed_track["separated_audio"] = {
"clean_instrumental": {},
"backing_vocals": {},
"other_stems": {},
"combined_instrumentals": {},
}
elif self.existing_instrumental:
self.logger.info(f"Using existing instrumental file: {self.existing_instrumental}")
existing_instrumental_extension = os.path.splitext(self.existing_instrumental)[1]
instrumental_path = os.path.join(track_output_dir, f"{artist_title} (Instrumental Custom){existing_instrumental_extension}")
# Use FileHandler._file_exists
if not self.file_handler._file_exists(instrumental_path):
shutil.copy2(self.existing_instrumental, instrumental_path)
processed_track["separated_audio"]["Custom"] = {
"instrumental": instrumental_path,
"vocals": None,
}
# If countdown padding was added to vocals, pad the custom instrumental too
if processed_track.get("countdown_padding_added", False):
padding_seconds = processed_track["countdown_padding_seconds"]
self.logger.info(
f"Countdown padding detected - applying {padding_seconds}s padding to custom instrumental"
)
base, ext = os.path.splitext(instrumental_path)
padded_instrumental_path = f"{base} (Padded){ext}"
if not self.file_handler._file_exists(padded_instrumental_path):
self.audio_processor.pad_audio_file(instrumental_path, padded_instrumental_path, padding_seconds)
# Update the path to use the padded version
processed_track["separated_audio"]["Custom"]["instrumental"] = padded_instrumental_path
self.logger.info(f"✓ Custom instrumental has been padded and synchronized with vocals")
elif "separated_audio" not in processed_track or not processed_track["separated_audio"]:
# Only run separation if it wasn't already done in parallel processing
self.logger.info(f"Separation was not completed in parallel processing, running separation for track: {self.title} by {self.artist}")
# Delegate to AudioProcessor (called directly, not in thread here)
separation_results = self.audio_processor.process_audio_separation(
audio_file=processed_track["input_audio_wav"], artist_title=artist_title, track_output_dir=track_output_dir
)
processed_track["separated_audio"] = separation_results
else:
self.logger.info("Audio separation was already completed in parallel processing, skipping duplicate separation.")
# Apply countdown padding to instrumental files if needed
if processed_track.get("countdown_padding_added", False):
padding_seconds = processed_track["countdown_padding_seconds"]
self.logger.info(
f"=== APPLYING COUNTDOWN PADDING TO INSTRUMENTALS ==="
)
self.logger.info(
f"Applying {padding_seconds}s padding to all instrumental files to sync with vocal countdown"
)
# Apply padding using AudioProcessor
padded_separation_result = self.audio_processor.apply_countdown_padding_to_instrumentals(
separation_result=processed_track["separated_audio"],
padding_seconds=padding_seconds,
artist_title=artist_title,
track_output_dir=track_output_dir,
)
# Update processed_track with padded file paths
processed_track["separated_audio"] = padded_separation_result
self.logger.info(
f"✓ All instrumental files have been padded and are now synchronized with vocals"
)
self.logger.info("Script finished, audio downloaded, lyrics fetched and audio separated!")
return processed_track
except Exception as e:
self.logger.error(f"Error in prep_single_track: {e}")
raise
finally:
# Remove signal handlers
for sig in (signal.SIGINT, signal.SIGTERM):
loop.remove_signal_handler(sig)
async def shutdown(self, signal):
"""Handle shutdown signals gracefully."""
self.logger.info(f"Received exit signal {signal.name}...")
# Get all running tasks
tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]
if tasks:
self.logger.info(f"Cancelling {len(tasks)} outstanding tasks")
# Cancel all running tasks
for task in tasks:
task.cancel()
self.logger.info("Received cancellation request, cleaning up...")
# Wait for all tasks to complete with cancellation
try:
await asyncio.gather(*tasks, return_exceptions=True)
except asyncio.CancelledError:
pass
# Force exit after cleanup
self.logger.info("Cleanup complete, exiting...")
sys.exit(0) # Add this line to force exit
async def process_playlist(self):
if self.artist is None or self.title is None:
raise Exception("Error: Artist and Title are required for processing a local file.")
if "entries" in self.extracted_info:
track_results = []
self.logger.info(f"Found {len(self.extracted_info['entries'])} entries in playlist, processing each invididually...")
for entry in self.extracted_info["entries"]:
self.extracted_info = entry
self.logger.info(f"Processing playlist entry with title: {self.extracted_info['title']}")
if not self.dry_run:
track_results.append(await self.prep_single_track())
self.artist = self.persistent_artist
self.title = None
return track_results
else:
raise Exception(f"Failed to find 'entries' in playlist, cannot process")
async def process_folder(self):
if self.filename_pattern is None or self.artist is None:
raise Exception("Error: Filename pattern and artist are required for processing a folder.")
folder_path = self.input_media
output_folder_path = os.path.join(os.getcwd(), os.path.basename(folder_path))
if not os.path.exists(output_folder_path):
if not self.dry_run:
self.logger.info(f"DRY RUN: Would create output folder: {output_folder_path}")
os.makedirs(output_folder_path)
else:
self.logger.info(f"Output folder already exists: {output_folder_path}")
pattern = re.compile(self.filename_pattern)
tracks = []
for filename in sorted(os.listdir(folder_path)):
match = pattern.match(filename)
if match:
title = match.group("title")
file_path = os.path.join(folder_path, filename)
self.input_media = file_path
self.title = title
track_index = match.group("index") if "index" in match.groupdict() else None
self.logger.info(f"Processing track: {track_index} with title: {title} from file: {filename}")
track_output_dir = os.path.join(output_folder_path, f"{track_index} - {self.artist} - {title}")
if not self.dry_run:
track = await self.prep_single_track()
tracks.append(track)
# Move the track folder to the output folder
track_folder = track["track_output_dir"]
shutil.move(track_folder, track_output_dir)
else:
self.logger.info(f"DRY RUN: Would move track folder to: {os.path.basename(track_output_dir)}")
return tracks
async def process(self):
if self.input_media is not None and os.path.isdir(self.input_media):
self.logger.info(f"Input media {self.input_media} is a local folder, processing each file individually...")
return await self.process_folder()
elif self.input_media is not None and os.path.isfile(self.input_media):
self.logger.info(f"Input media {self.input_media} is a local file, youtube logic will be skipped")
return [await self.prep_single_track()]
else:
self.url = self.input_media
# Use the imported extract_info_for_online_media function
self.extracted_info = extract_info_for_online_media(
input_url=self.url, input_artist=self.artist, input_title=self.title, logger=self.logger, cookies_str=self.cookies_str
)
if self.extracted_info and "playlist_count" in self.extracted_info:
self.persistent_artist = self.artist
self.logger.info(f"Input URL is a playlist, beginning batch operation with persistent artist: {self.persistent_artist}")
return await self.process_playlist()
else:
self.logger.info(f"Input URL is not a playlist, processing single track")
# Parse metadata to extract artist and title before processing
self.parse_single_track_metadata(self.artist, self.title)
return [await self.prep_single_track()]
+306
View File
@@ -0,0 +1,306 @@
import os
import re
import logging
import shutil
import json
from lyrics_transcriber import LyricsTranscriber, OutputConfig, TranscriberConfig, LyricsConfig
from lyrics_transcriber.core.controller import LyricsControllerResult
from dotenv import load_dotenv
from .utils import sanitize_filename
# Placeholder class or functions for lyrics processing
class LyricsProcessor:
def __init__(
self, logger, style_params_json, lyrics_file, skip_transcription, skip_transcription_review, render_video, subtitle_offset_ms
):
self.logger = logger
self.style_params_json = style_params_json
self.lyrics_file = lyrics_file
self.skip_transcription = skip_transcription
self.skip_transcription_review = skip_transcription_review
self.render_video = render_video
self.subtitle_offset_ms = subtitle_offset_ms
def find_best_split_point(self, line):
"""
Find the best split point in a line based on the specified criteria.
"""
self.logger.debug(f"Finding best_split_point for line: {line}")
words = line.split()
mid_word_index = len(words) // 2
self.logger.debug(f"words: {words} mid_word_index: {mid_word_index}")
# Check for a comma within one or two words of the middle word
if "," in line:
mid_point = len(" ".join(words[:mid_word_index]))
comma_indices = [i for i, char in enumerate(line) if char == ","]
for index in comma_indices:
if abs(mid_point - index) < 20 and len(line[: index + 1].strip()) <= 36:
self.logger.debug(
f"Found comma at index {index} which is within 20 characters of mid_point {mid_point} and results in a suitable line length, accepting as split point"
)
return index + 1 # Include the comma in the first line
# Check for 'and'
if " and " in line:
mid_point = len(line) // 2
and_indices = [m.start() for m in re.finditer(" and ", line)]
for index in sorted(and_indices, key=lambda x: abs(x - mid_point)):
if len(line[: index + len(" and ")].strip()) <= 36:
self.logger.debug(f"Found 'and' at index {index} which results in a suitable line length, accepting as split point")
return index + len(" and ")
# If no better split point is found, try splitting at the middle word
if len(words) > 2 and mid_word_index > 0:
split_at_middle = len(" ".join(words[:mid_word_index]))
if split_at_middle <= 36:
self.logger.debug(f"Splitting at middle word index: {mid_word_index}")
return split_at_middle
# If the line is still too long, forcibly split at the maximum length
forced_split_point = 36
if len(line) > forced_split_point:
self.logger.debug(f"Line is still too long, forcibly splitting at position {forced_split_point}")
return forced_split_point
def process_line(self, line):
"""
Process a single line to ensure it's within the maximum length,
and handle parentheses.
"""
processed_lines = []
iteration_count = 0
max_iterations = 100 # Failsafe limit
while len(line) > 36:
if iteration_count > max_iterations:
self.logger.error(f"Maximum iterations exceeded in process_line for line: {line}")
break
# Check if the line contains parentheses
if "(" in line and ")" in line:
start_paren = line.find("(")
end_paren = line.find(")") + 1
if end_paren < len(line) and line[end_paren] == ",":
end_paren += 1
if start_paren > 0:
processed_lines.append(line[:start_paren].strip())
processed_lines.append(line[start_paren:end_paren].strip())
line = line[end_paren:].strip()
else:
split_point = self.find_best_split_point(line)
processed_lines.append(line[:split_point].strip())
line = line[split_point:].strip()
iteration_count += 1
if line: # Add the remaining part if not empty
processed_lines.append(line)
return processed_lines
def transcribe_lyrics(self, input_audio_wav, artist, title, track_output_dir, lyrics_artist=None, lyrics_title=None):
"""
Transcribe lyrics for a track.
Args:
input_audio_wav: Path to the audio file
artist: Original artist name (used for filename generation)
title: Original title (used for filename generation)
track_output_dir: Output directory path
lyrics_artist: Artist name for lyrics processing (defaults to artist if None)
lyrics_title: Title for lyrics processing (defaults to title if None)
"""
# Use original artist/title for filename generation
filename_artist = artist
filename_title = title
# Use lyrics_artist/lyrics_title for actual lyrics processing, fall back to originals if not provided
processing_artist = lyrics_artist or artist
processing_title = lyrics_title or title
self.logger.info(
f"Transcribing lyrics for track {processing_artist} - {processing_title} from audio file: {input_audio_wav} with output directory: {track_output_dir}"
)
# Check for existing files first using sanitized names from ORIGINAL artist/title for consistency
sanitized_artist = sanitize_filename(filename_artist)
sanitized_title = sanitize_filename(filename_title)
parent_video_path = os.path.join(track_output_dir, f"{sanitized_artist} - {sanitized_title} (With Vocals).mkv")
parent_lrc_path = os.path.join(track_output_dir, f"{sanitized_artist} - {sanitized_title} (Karaoke).lrc")
# Check lyrics directory for existing files
lyrics_dir = os.path.join(track_output_dir, "lyrics")
lyrics_video_path = os.path.join(lyrics_dir, f"{sanitized_artist} - {sanitized_title} (With Vocals).mkv")
lyrics_lrc_path = os.path.join(lyrics_dir, f"{sanitized_artist} - {sanitized_title} (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")
return {
"lrc_filepath": parent_lrc_path,
"ass_filepath": parent_video_path,
}
# 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_output_dir, exist_ok=True)
shutil.copy2(lyrics_video_path, parent_video_path)
shutil.copy2(lyrics_lrc_path, parent_lrc_path)
return {
"lrc_filepath": parent_lrc_path,
"ass_filepath": parent_video_path,
}
# Create lyrics directory if it doesn't exist
os.makedirs(lyrics_dir, exist_ok=True)
self.logger.info(f"Created lyrics directory: {lyrics_dir}")
# Set render_video to False if explicitly disabled
render_video = self.render_video
if not render_video:
self.logger.info("Video rendering disabled, skipping video output")
# 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"),
"rapidapi_key": os.getenv("RAPIDAPI_KEY"), # Add missing RAPIDAPI_KEY
}
# Create config objects for LyricsTranscriber
transcriber_config = TranscriberConfig(
audioshake_api_token=env_config.get("audioshake_api_token"),
)
lyrics_config = LyricsConfig(
genius_api_token=env_config.get("genius_api_token"),
spotify_cookie=env_config.get("spotify_cookie"),
rapidapi_key=env_config.get("rapidapi_key"),
lyrics_file=self.lyrics_file,
)
# Debug logging for lyrics_config
self.logger.info(f"LyricsConfig created with:")
self.logger.info(f" genius_api_token: {env_config.get('genius_api_token')[:3] + '...' if env_config.get('genius_api_token') else 'None'}")
self.logger.info(f" spotify_cookie: {env_config.get('spotify_cookie')[:3] + '...' if env_config.get('spotify_cookie') else 'None'}")
self.logger.info(f" rapidapi_key: {env_config.get('rapidapi_key')[:3] + '...' if env_config.get('rapidapi_key') else 'None'}")
self.logger.info(f" lyrics_file: {self.lyrics_file}")
# Detect if we're running in a serverless environment (Modal)
# Modal sets specific environment variables we can check for
is_serverless = (
os.getenv("MODAL_TASK_ID") is not None or
os.getenv("MODAL_FUNCTION_NAME") is not None or
os.path.exists("/.modal") # Modal creates this directory in containers
)
# In serverless environment, disable interactive review even if skip_transcription_review=False
# This preserves CLI behavior while fixing serverless hanging
enable_review_setting = not self.skip_transcription_review and not is_serverless
if is_serverless and not self.skip_transcription_review:
self.logger.info("Detected serverless environment - disabling interactive review to prevent hanging")
# In serverless environment, disable video generation during Phase 1 to save compute
# Video will be generated in Phase 2 after human review
serverless_render_video = render_video and not is_serverless
if is_serverless and render_video:
self.logger.info("Detected serverless environment - deferring video generation until after review")
output_config = OutputConfig(
output_styles_json=self.style_params_json,
output_dir=lyrics_dir,
render_video=serverless_render_video, # Disable video in serverless Phase 1
fetch_lyrics=True,
run_transcription=not self.skip_transcription,
run_correction=True,
generate_plain_text=True,
generate_lrc=True,
generate_cdg=False, # Also defer CDG generation to Phase 2
video_resolution="4k",
enable_review=enable_review_setting,
subtitle_offset_ms=self.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 - use PROCESSING artist/title for lyrics work
transcriber = LyricsTranscriber(
audio_filepath=input_audio_wav,
artist=processing_artist, # Use lyrics_artist for processing
title=processing_title, # Use lyrics_title for processing
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.ass_filepath:
transcriber_outputs["ass_filepath"] = results.ass_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.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
# Save correction data to JSON file for review interface
# Use the expected filename format: "{artist} - {title} (Lyrics Corrections).json"
# Use sanitized names to be consistent with all other files created by lyrics_transcriber
corrections_filename = f"{sanitized_artist} - {sanitized_title} (Lyrics Corrections).json"
corrections_filepath = os.path.join(lyrics_dir, corrections_filename)
# Use the CorrectionResult's to_dict() method to serialize
correction_data = results.transcription_corrected.to_dict()
with open(corrections_filepath, 'w') as f:
json.dump(correction_data, f, indent=2)
self.logger.info(f"Saved correction data to {corrections_filepath}")
# Capture countdown padding information for syncing with instrumental audio
transcriber_outputs["countdown_padding_added"] = getattr(results, "countdown_padding_added", False)
transcriber_outputs["countdown_padding_seconds"] = getattr(results, "countdown_padding_seconds", 0.0)
transcriber_outputs["padded_audio_filepath"] = getattr(results, "padded_audio_filepath", None)
if transcriber_outputs["countdown_padding_added"]:
self.logger.info(
f"Countdown padding detected: {transcriber_outputs['countdown_padding_seconds']}s added to vocals. "
f"Instrumental audio will need to be padded accordingly."
)
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}")
return transcriber_outputs
+155
View File
@@ -0,0 +1,155 @@
import logging
import yt_dlp.YoutubeDL as ydl
def extract_info_for_online_media(input_url, input_artist, input_title, logger, cookies_str=None):
"""Extracts metadata using yt-dlp, either from a URL or via search."""
logger.info(f"Extracting info for input_url: {input_url} input_artist: {input_artist} input_title: {input_title}")
# Set up yt-dlp options with enhanced anti-detection
base_opts = {
"quiet": True,
# Anti-detection options
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"referer": "https://www.youtube.com/",
"sleep_interval": 1,
"max_sleep_interval": 3,
"fragment_retries": 3,
"extractor_retries": 3,
"retries": 3,
# Headers to appear more human
"http_headers": {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-us,en;q=0.5",
"Accept-Encoding": "gzip, deflate",
"DNT": "1",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1",
},
}
# Add cookies if provided
if cookies_str:
logger.info("Using provided cookies for enhanced YouTube access")
# Save cookies to a temporary file
import tempfile
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
f.write(cookies_str)
base_opts['cookiefile'] = f.name
else:
logger.info("No cookies provided - attempting standard extraction")
extracted_info = None
try:
if input_url is not None:
# If a URL is provided, use it to extract the metadata
with ydl(base_opts) as ydl_instance:
extracted_info = ydl_instance.extract_info(input_url, download=False)
else:
# If no URL is provided, use the query to search for the top result
search_opts = base_opts.copy()
search_opts.update({
"format": "bestaudio",
"noplaylist": "True",
"extract_flat": True
})
with ydl(search_opts) as ydl_instance:
query = f"{input_artist} {input_title}"
search_results = ydl_instance.extract_info(f"ytsearch1:{query}", download=False)
if search_results and "entries" in search_results and search_results["entries"]:
extracted_info = search_results["entries"][0]
else:
# Raise IndexError to match the expected exception in tests
raise IndexError(f"No search results found on YouTube for query: {input_artist} {input_title}")
if not extracted_info:
raise Exception(f"Failed to extract info for query: {input_artist} {input_title} or URL: {input_url}")
return extracted_info
finally:
# Clean up temporary cookie file if it was created
if cookies_str and 'cookiefile' in base_opts:
try:
import os
os.unlink(base_opts['cookiefile'])
except:
pass
def parse_track_metadata(extracted_info, current_artist, current_title, persistent_artist, logger):
"""
Parses extracted_info to determine URL, extractor, ID, artist, and title.
Returns a dictionary with the parsed values.
"""
parsed_data = {
"url": None,
"extractor": None,
"media_id": None,
"artist": current_artist,
"title": current_title,
}
metadata_artist = ""
metadata_title = ""
if "url" in extracted_info:
parsed_data["url"] = extracted_info["url"]
elif "webpage_url" in extracted_info:
parsed_data["url"] = extracted_info["webpage_url"]
else:
raise Exception(f"Failed to extract URL from input media metadata: {extracted_info}")
if "extractor_key" in extracted_info:
parsed_data["extractor"] = extracted_info["extractor_key"]
elif "ie_key" in extracted_info:
parsed_data["extractor"] = extracted_info["ie_key"]
else:
raise Exception(f"Failed to find extractor name from input media metadata: {extracted_info}")
if "id" in extracted_info:
parsed_data["media_id"] = extracted_info["id"]
# Example: "Artist - Title"
if "title" in extracted_info and "-" in extracted_info["title"]:
try:
metadata_artist, metadata_title = extracted_info["title"].split("-", 1)
metadata_artist = metadata_artist.strip()
metadata_title = metadata_title.strip()
except ValueError:
logger.warning(f"Could not split title '{extracted_info['title']}' on '-', using full title.")
metadata_title = extracted_info["title"].strip()
if "uploader" in extracted_info:
metadata_artist = extracted_info["uploader"]
elif "uploader" in extracted_info:
# Fallback to uploader as artist if title parsing fails
metadata_artist = extracted_info["uploader"]
if "title" in extracted_info:
metadata_title = extracted_info["title"].strip()
# If unable to parse, log an appropriate message
if not metadata_artist or not metadata_title:
logger.warning("Could not parse artist and title from the input media metadata.")
if not parsed_data["artist"] and metadata_artist:
logger.warning(f"Artist not provided as input, setting to {metadata_artist} from input media metadata...")
parsed_data["artist"] = metadata_artist
if not parsed_data["title"] and metadata_title:
logger.warning(f"Title not provided as input, setting to {metadata_title} from input media metadata...")
parsed_data["title"] = metadata_title
if persistent_artist:
logger.debug(
f"Resetting artist from {parsed_data['artist']} to persistent artist: {persistent_artist} for consistency while processing playlist..."
)
parsed_data["artist"] = persistent_artist
if parsed_data["artist"] and parsed_data["title"]:
logger.info(f"Extracted url: {parsed_data['url']}, artist: {parsed_data['artist']}, title: {parsed_data['title']}")
else:
logger.debug(extracted_info)
raise Exception("Failed to extract artist and title from the input media metadata.")
return parsed_data
Binary file not shown.
Binary file not shown.
Binary file not shown.
+18
View File
@@ -0,0 +1,18 @@
import re
def sanitize_filename(filename):
"""Replace or remove characters that are unsafe for filenames."""
if filename is None:
return None
# Replace problematic characters with underscores
for char in ["\\", "/", ":", "*", "?", '"', "<", ">", "|"]:
filename = filename.replace(char, "_")
# Remove any trailing periods or spaces
filename = filename.rstrip(". ") # Added period here as well
# Remove any leading periods or spaces
filename = filename.lstrip(". ")
# Replace multiple underscores with a single one
filename = re.sub(r'_+', '_', filename)
# Replace multiple spaces with a single one
filename = re.sub(r' +', ' ', filename)
return filename
+483
View File
@@ -0,0 +1,483 @@
#!/usr/bin/env python
import argparse
import logging
import pkg_resources
import os
import csv
import asyncio
import json
import sys
from karaoke_gen import KaraokePrep
from karaoke_gen.karaoke_finalise import KaraokeFinalise
# Global logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO) # Set initial log level
async def process_track_prep(row, args, logger, log_formatter):
"""First phase: Process a track through prep stage only, without video rendering"""
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}")
kprep = KaraokePrep(
artist=artist,
title=title,
input_media=guide_file,
existing_instrumental=instrumental_file,
style_params_json=args.style_params_json,
logger=logger,
log_level=args.log_level,
dry_run=args.dry_run,
render_video=False, # First phase: no video rendering
create_track_subfolders=True,
)
tracks = await kprep.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, args, logger, log_formatter):
"""Phase 2: Process a track through karaoke-finalise."""
# First, load CDG styles if CDG generation is enabled
cdg_styles = None
if args.enable_cdg:
if not args.style_params_json:
# Raise ValueError instead of sys.exit
raise ValueError("CDG styles JSON file path (--style_params_json) is required when --enable_cdg is used")
try:
with open(args.style_params_json, "r") as f:
style_params = json.load(f) # Use json.load directly with file object
# Check if 'cdg' key exists
if "cdg" not in style_params:
raise ValueError(f"'cdg' key not found in style parameters file: {args.style_params_json}")
cdg_styles = style_params["cdg"]
except FileNotFoundError:
# Re-raise FileNotFoundError
raise FileNotFoundError(f"CDG styles configuration file not found: {args.style_params_json}")
except json.JSONDecodeError as e:
# Raise ValueError for invalid JSON
raise ValueError(f"Invalid JSON in CDG styles configuration file: {str(e)}")
original_dir = os.getcwd()
artist = row["Artist"].strip()
title = row["Title"].strip()
guide_file = row["Mixed Audio Filename"].strip()
instrumental_file = row["Instrumental Audio Filename"].strip()
try:
# Initialize KaraokeFinalise first (needed for test assertions)
kfinalise = KaraokeFinalise(
log_formatter=log_formatter,
log_level=args.log_level,
dry_run=args.dry_run,
enable_cdg=args.enable_cdg,
enable_txt=args.enable_txt,
cdg_styles=cdg_styles,
non_interactive=True
)
# Try to find the track directory
track_dir_found = False
# Try several directory naming patterns
possible_dirs = [
os.path.join(args.output_dir, f"{artist} - {title}"),
os.path.join(args.output_dir, f"{artist} - {title}"), # Original artist/title from row
os.path.join(args.output_dir, f"{artist} - {title}") # With space replace (same here)
]
for track_dir in possible_dirs:
if os.path.exists(track_dir):
track_dir_found = True
break
if not track_dir_found:
logger.error(f"Track directory not found. Tried: {', '.join(possible_dirs)}")
return True # Return True to continue with other tracks
# First run KaraokePrep with video rendering enabled
# This is so the human can review all of the lyrics for the entire batch fairly quickly,
# then leave the script running to render the videos for all of them.
logger.info(f"Video rendering for track: {artist} - {title}")
kprep = KaraokePrep(
artist=artist,
title=title,
input_media=guide_file,
existing_instrumental=instrumental_file,
style_params_json=args.style_params_json,
logger=logger,
log_level=args.log_level,
dry_run=args.dry_run,
render_video=True, # Second phase: with video rendering
create_track_subfolders=True,
skip_transcription_review=True,
)
tracks = await kprep.process()
# Process with KaraokeFinalise in the track directory
for track_dir in possible_dirs:
if os.path.exists(track_dir):
try:
os.chdir(track_dir)
# Process with KaraokeFinalise
kfinalise.process()
return True
except Exception as e:
logger.error(f"Error during finalisation: {str(e)}")
raise # Re-raise to be caught by outer try/except
finally:
# Always go back to original directory
os.chdir(original_dir)
except Exception as e:
logger.error(f"Failed render/finalise for {artist} - {title}: {str(e)}")
os.chdir(original_dir) # Make sure we go back to original directory
return False
def update_csv_status(csv_path, row_index, new_status, dry_run=False):
"""Update the status of a processed row in the CSV file.
Args:
csv_path (str): Path to the CSV file
row_index (int): Index of the row to update
new_status (str): New status to set
dry_run (bool): If True, log the update but don't modify the file
Returns:
bool: True if updated, False if in dry run mode or error occurred
"""
if dry_run:
logger.info(f"DRY RUN: Would update row {row_index} in {csv_path} to status '{new_status}'")
return False
try:
# Read all rows
with open(csv_path, "r") as f:
reader = csv.DictReader(f)
rows = list(reader)
# Check if CSV has any rows
if not rows:
logger.error(f"CSV file {csv_path} is empty or has no data rows")
return False
# Update status for the processed row
if row_index < 0 or row_index >= len(rows):
logger.error(f"Row index {row_index} is out of range for CSV with {len(rows)} rows")
return False
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)
return True
except Exception as e:
logger.error(f"Error updating CSV status: {str(e)}")
return False
def parse_arguments():
"""Parse command line arguments"""
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",
)
# 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 early
args.input_csv = os.path.abspath(args.input_csv)
# Validate and convert log level
if isinstance(args.log_level, str):
try:
log_level_int = getattr(logging, args.log_level.upper())
args.log_level = log_level_int # Store the numeric log level back in args
except AttributeError:
# Raise ValueError for invalid log level string
raise ValueError(f"Invalid log level string: {args.log_level}")
elif not isinstance(args.log_level, int):
# If it's neither string nor int, raise error
raise ValueError(f"Invalid log level type: {type(args.log_level)}")
return args
def _parse_and_validate_args():
"""Parses arguments and performs initial validation."""
args = parse_arguments() # Calls the modified parse_arguments
# Validate input CSV existence (raises FileNotFoundError if invalid)
if not validate_input_csv(args.input_csv):
raise FileNotFoundError(f"Input CSV file not found: {args.input_csv}")
# Validate style params JSON existence if CDG is enabled
if args.enable_cdg:
if not args.style_params_json:
raise ValueError("CDG styles JSON file path (--style_params_json) is required when --enable_cdg is used")
if not os.path.isfile(args.style_params_json):
raise FileNotFoundError(f"CDG styles configuration file not found: {args.style_params_json}")
# Basic JSON validation can also happen here if desired, or deferred to process_track_render
try:
with open(args.style_params_json, 'r') as f:
json.load(f)
except json.JSONDecodeError as e:
raise ValueError(f"Invalid JSON in CDG styles configuration file: {args.style_params_json} - {e}")
except FileNotFoundError: # Should be caught above, but belt-and-suspenders
raise FileNotFoundError(f"CDG styles configuration file not found: {args.style_params_json}")
return args
def validate_input_csv(csv_path):
"""Validate that the input CSV file exists.
Args:
csv_path (str): Path to the CSV file
Returns:
bool: True if the file exists, False otherwise
"""
if not os.path.isfile(csv_path):
logger.error(f"Input CSV file not found: {csv_path}")
return False
return True
def _read_csv_file(csv_path):
"""Reads the CSV file and returns rows as a list of dictionaries."""
try:
with open(csv_path, "r", newline='') as f: # Added newline=''
reader = csv.DictReader(f)
# Check for required columns before reading all rows
required_columns = {"Artist", "Title", "Mixed Audio Filename", "Instrumental Audio Filename", "Status"}
if not required_columns.issubset(reader.fieldnames):
missing = required_columns - set(reader.fieldnames)
raise ValueError(f"CSV file missing required columns: {', '.join(missing)}")
rows = list(reader)
if not rows:
logger.warning(f"CSV file {csv_path} is empty or contains only headers.")
return rows
except FileNotFoundError:
# This should ideally be caught earlier by validate_input_csv, but handle defensively
logger.error(f"CSV file not found during read: {csv_path}")
raise # Re-raise the exception
except Exception as e:
logger.error(f"Error reading CSV file {csv_path}: {e}")
raise # Re-raise other read errors
async def process_csv_rows(csv_path, rows, args, logger, log_formatter):
"""Process all rows in a CSV file.
Args:
csv_path (str): Path to the CSV file
rows (list): List of CSV rows as dictionaries
args (argparse.Namespace): Command line arguments
logger (logging.Logger): Logger instance
log_formatter (logging.Formatter): Log formatter
Returns:
dict: A summary of the processing results
"""
results = {
"prep_success": 0,
"prep_failed": 0,
"render_success": 0,
"render_failed": 0,
"skipped": 0
}
# Phase 1: Initial prep for all tracks
logger.info("Starting Phase 1: Initial prep for all tracks")
for i, row in enumerate(rows):
status = row["Status"].lower() if "Status" in row else ""
if status != "uploaded":
logger.info(f"Skipping {row.get('Artist', 'Unknown')} - {row.get('Title', 'Unknown')} (Status: {row.get('Status', 'Unknown')})")
results["skipped"] += 1
continue
success = await process_track_prep(row, args, logger, log_formatter)
if success:
results["prep_success"] += 1
if not args.dry_run:
update_csv_status(csv_path, i, "Prep_Complete", args.dry_run)
else:
results["prep_failed"] += 1
if not args.dry_run:
update_csv_status(csv_path, i, "Prep_Failed", args.dry_run)
# Phase 2: Render and finalise all tracks
logger.info("Starting Phase 2: Render and finalise for all tracks")
for i, row in enumerate(rows):
status = row["Status"].lower() if "Status" in row else ""
if status not in ["prep_complete", "uploaded"]:
logger.info(f"Skipping {row.get('Artist', 'Unknown')} - {row.get('Title', 'Unknown')} (Status: {row.get('Status', 'Unknown')})")
continue
success = await process_track_render(row, args, logger, log_formatter)
if success:
results["render_success"] += 1
if not args.dry_run:
update_csv_status(csv_path, i, "Completed", args.dry_run)
else:
results["render_failed"] += 1
if not args.dry_run:
update_csv_status(csv_path, i, "Render_Failed", args.dry_run)
return results
async def async_main():
"""Main async function to process bulk tracks from CSV"""
# Parse and validate arguments first (raises exceptions on failure)
args = _parse_and_validate_args()
# Set log level based on validated args (logger should already be partially set up by main)
logger.setLevel(args.log_level)
logger.info(f"Log level set to {logging.getLevelName(args.log_level)}")
if args.dry_run:
logger.info("Dry run mode enabled. No changes will be made.")
logger.info(f"Starting bulk processing with input CSV: {args.input_csv}")
# Read CSV (raises exceptions on failure)
rows = _read_csv_file(args.input_csv)
# Check if log_formatter is available (should be set by main)
global log_formatter
if log_formatter is None:
# This case should ideally not happen if main() calls setup_logging correctly
logger.warning("Log formatter not found, setting up default.")
log_formatter = setup_logging(args.log_level)
# Process the CSV rows
results = await process_csv_rows(args.input_csv, rows, args, logger, log_formatter)
# Log summary
logger.info(f"Processing complete. Summary: {results}")
return results
def setup_logging(log_level=logging.INFO):
"""Set up logging with the given log level.
Args:
log_level (int): Logging level (e.g., logging.INFO, logging.DEBUG)
Returns:
logging.Formatter: The log formatter for use by other functions
"""
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)
logger.setLevel(log_level)
return log_formatter
def main():
"""Main entry point for the CLI."""
log_formatter = None # Initialize log_formatter
try:
# Set up logging early to capture potential errors during setup/parsing
# Get initial args just for log level if provided, otherwise default
temp_args, _ = argparse.ArgumentParser(add_help=False).parse_known_args()
initial_log_level_str = getattr(temp_args, 'log_level', 'info')
try:
initial_log_level = getattr(logging, initial_log_level_str.upper())
except AttributeError:
initial_log_level = logging.INFO
print(f"Warning: Invalid initial log level '{initial_log_level_str}'. Using INFO.", file=sys.stderr)
log_formatter = setup_logging(initial_log_level)
# Run the async main function using asyncio
asyncio.run(async_main())
logger.info("Bulk processing finished successfully.")
sys.exit(0)
except (FileNotFoundError, ValueError, argparse.ArgumentError) as e:
# Log specific configuration/setup errors before exiting
if logger.handlers: # Check if logger was set up
logger.error(f"Configuration error: {str(e)}")
else: # Fallback if logging setup failed
print(f"Error: {str(e)}", file=sys.stderr)
sys.exit(1)
except Exception as e:
# Catch any other unexpected errors during processing
if logger.handlers:
logger.exception(f"An unexpected error occurred during bulk processing: {str(e)}") # Use exception for traceback
else:
print(f"An unexpected error occurred: {str(e)}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
+829
View File
@@ -0,0 +1,829 @@
#!/usr/bin/env python
import argparse
import logging
from importlib import metadata
import tempfile
import os
import sys
import json
import asyncio
import time
import pyperclip
from karaoke_gen import KaraokePrep
from karaoke_gen.karaoke_finalise import KaraokeFinalise
def is_url(string):
"""Simple check to determine if a string is a URL."""
return string.startswith("http://") or string.startswith("https://")
def is_file(string):
"""Check if a string is a valid file."""
return os.path.isfile(string)
async def async_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="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.",
)
# Get version using importlib.metadata
try:
package_version = metadata.version("karaoke-gen")
except metadata.PackageNotFoundError:
package_version = "unknown"
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(
"--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'",
)
style_group.add_argument(
"--style_override",
action="append",
help="Optional: Override a style parameter. Can be used multiple times. Example: --style_override 'intro.background_image=/path/to/new_image.png'",
)
# 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",
)
args = parser.parse_args()
# Process style overrides
style_overrides = {}
if args.style_override:
for override in args.style_override:
try:
key, value = override.split("=", 1)
style_overrides[key] = value
except ValueError:
logger.error(f"Invalid style override format: {override}. Must be in 'key=value' format.")
sys.exit(1)
# Handle test email template case first
if args.test_email_template:
log_level = getattr(logging, args.log_level.upper())
logger.setLevel(log_level)
logger.info("Testing email template functionality...")
kfinalise = KaraokeFinalise(
log_formatter=log_formatter,
log_level=log_level,
email_template_file=args.email_template_file,
)
kfinalise.test_email_template()
return
# Handle edit-lyrics mode
if args.edit_lyrics:
log_level = getattr(logging, args.log_level.upper())
logger.setLevel(log_level)
logger.info("Running in edit-lyrics mode...")
# Get the current directory name to extract artist and title
current_dir = os.path.basename(os.getcwd())
logger.info(f"Current directory: {current_dir}")
# Extract artist and title from directory name
# Format could be either "Artist - Title" or "BRAND-XXXX - Artist - Title"
if " - " not in current_dir:
logger.error("Current directory name does not contain ' - ' separator. Cannot extract artist and title.")
sys.exit(1)
return # Explicit return for testing
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:
logger.error(f"Could not parse artist and title from directory name: {current_dir}")
sys.exit(1)
return # Explicit return for testing
logger.info(f"Extracted artist: {artist}, title: {title}")
# Initialize KaraokePrep
kprep_coroutine = KaraokePrep(
artist=artist,
title=title,
input_media=None, # Will be set by backup_existing_outputs
dry_run=args.dry_run,
log_formatter=log_formatter,
log_level=log_level,
render_bounding_boxes=args.render_bounding_boxes,
output_dir=".", # We're already in the track directory
create_track_subfolders=False, # Don't create subfolders, we're already in one
lossless_output_format=args.lossless_output_format,
output_png=args.output_png,
output_jpg=args.output_jpg,
clean_instrumental_model=args.clean_instrumental_model,
backing_vocals_models=args.backing_vocals_models,
other_stems_models=args.other_stems_models,
model_file_dir=args.model_file_dir,
skip_separation=True, # Skip separation as we already have the audio files
lyrics_artist=args.lyrics_artist or artist,
lyrics_title=args.lyrics_title or title,
lyrics_file=args.lyrics_file,
skip_lyrics=False, # We want to process lyrics
skip_transcription=False, # We want to transcribe
skip_transcription_review=args.skip_transcription_review,
subtitle_offset_ms=args.subtitle_offset_ms,
style_params_json=args.style_params_json,
style_overrides=style_overrides,
)
# No await needed for constructor
kprep = kprep_coroutine
# Backup existing outputs and get the input audio file
track_output_dir = os.getcwd()
input_audio_wav = kprep.file_handler.backup_existing_outputs(track_output_dir, artist, title)
kprep.input_media = input_audio_wav
# Run KaraokePrep
tracks = await kprep.process()
# Load CDG styles if CDG generation is enabled
cdg_styles = None
if args.enable_cdg:
if not args.style_params_json:
logger.error("CDG styles JSON file path (--style_params_json) is required when --enable_cdg is used")
sys.exit(1)
return # Explicit return for testing
try:
with open(args.style_params_json, "r") as f:
style_params = json.loads(f.read())
cdg_styles = style_params["cdg"]
except FileNotFoundError:
logger.error(f"CDG styles configuration file not found: {args.style_params_json}")
sys.exit(1)
return # Explicit return for testing
except json.JSONDecodeError as e:
logger.error(f"Invalid JSON in CDG styles configuration file: {e}")
sys.exit(1)
return # Explicit return for testing
except KeyError:
logger.error(f"'cdg' key not found in style parameters file: {args.style_params_json}")
sys.exit(1)
return # Explicit return for testing
# Run KaraokeFinalise with keep_brand_code=True and replace_existing=True
kfinalise = KaraokeFinalise(
log_formatter=log_formatter,
log_level=log_level,
dry_run=args.dry_run,
instrumental_format=args.instrumental_format,
enable_cdg=args.enable_cdg,
enable_txt=args.enable_txt,
brand_prefix=args.brand_prefix,
organised_dir=args.organised_dir,
organised_dir_rclone_root=args.organised_dir_rclone_root,
public_share_dir=args.public_share_dir,
youtube_client_secrets_file=args.youtube_client_secrets_file,
youtube_description_file=args.youtube_description_file,
rclone_destination=args.rclone_destination,
discord_webhook_url=args.discord_webhook_url,
email_template_file=args.email_template_file,
cdg_styles=cdg_styles,
keep_brand_code=True, # Always keep brand code in edit mode
non_interactive=args.yes,
)
try:
final_track = kfinalise.process(replace_existing=True) # Replace existing YouTube video
logger.info(f"Successfully completed editing lyrics for: {artist} - {title}")
# Display summary of outputs
logger.info(f"Karaoke lyrics edit complete! Output files:")
logger.info(f"")
logger.info(f"Track: {final_track['artist']} - {final_track['title']}")
logger.info(f"")
logger.info(f"Working Files:")
logger.info(f" Video With Vocals: {final_track['video_with_vocals']}")
logger.info(f" Video With Instrumental: {final_track['video_with_instrumental']}")
logger.info(f"")
logger.info(f"Final Videos:")
logger.info(f" Lossless 4K MP4 (PCM): {final_track['final_video']}")
logger.info(f" Lossless 4K MKV (FLAC): {final_track['final_video_mkv']}")
logger.info(f" Lossy 4K MP4 (AAC): {final_track['final_video_lossy']}")
logger.info(f" Lossy 720p MP4 (AAC): {final_track['final_video_720p']}")
if "final_karaoke_cdg_zip" in final_track or "final_karaoke_txt_zip" in final_track:
logger.info(f"")
logger.info(f"Karaoke Files:")
if "final_karaoke_cdg_zip" in final_track:
logger.info(f" CDG+MP3 ZIP: {final_track['final_karaoke_cdg_zip']}")
if "final_karaoke_txt_zip" in final_track:
logger.info(f" TXT+MP3 ZIP: {final_track['final_karaoke_txt_zip']}")
if final_track["brand_code"]:
logger.info(f"")
logger.info(f"Organization:")
logger.info(f" Brand Code: {final_track['brand_code']}")
logger.info(f" Directory: {final_track['new_brand_code_dir_path']}")
if final_track["youtube_url"] or final_track["brand_code_dir_sharing_link"]:
logger.info(f"")
logger.info(f"Sharing:")
if final_track["brand_code_dir_sharing_link"]:
logger.info(f" Folder Link: {final_track['brand_code_dir_sharing_link']}")
try:
time.sleep(1) # Brief pause between clipboard operations
pyperclip.copy(final_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 final_track["youtube_url"]:
logger.info(f" YouTube URL: {final_track['youtube_url']}")
try:
pyperclip.copy(final_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)}")
except Exception as e:
logger.error(f"Error during finalisation: {str(e)}")
raise e
return
# Handle finalise-only mode
if args.finalise_only:
log_level = getattr(logging, args.log_level.upper())
logger.setLevel(log_level)
logger.info("Running in finalise-only mode...")
# Load CDG styles if CDG generation is enabled
cdg_styles = None
if args.enable_cdg:
if not args.style_params_json:
logger.error("CDG styles JSON file path (--style_params_json) is required when --enable_cdg is used")
sys.exit(1)
return # Explicit return for testing
try:
with open(args.style_params_json, "r") as f:
style_params = json.loads(f.read())
cdg_styles = style_params["cdg"]
except FileNotFoundError:
logger.error(f"CDG styles configuration file not found: {args.style_params_json}")
sys.exit(1)
return # Explicit return for testing
except json.JSONDecodeError as e:
logger.error(f"Invalid JSON in CDG styles configuration file: {e}")
sys.exit(1)
return # Explicit return for testing
except KeyError:
logger.error(f"'cdg' key not found in style parameters file: {args.style_params_json}")
sys.exit(1)
return # Explicit return for testing
kfinalise = KaraokeFinalise(
log_formatter=log_formatter,
log_level=log_level,
dry_run=args.dry_run,
instrumental_format=args.instrumental_format,
enable_cdg=args.enable_cdg,
enable_txt=args.enable_txt,
brand_prefix=args.brand_prefix,
organised_dir=args.organised_dir,
organised_dir_rclone_root=args.organised_dir_rclone_root,
public_share_dir=args.public_share_dir,
youtube_client_secrets_file=args.youtube_client_secrets_file,
youtube_description_file=args.youtube_description_file,
rclone_destination=args.rclone_destination,
discord_webhook_url=args.discord_webhook_url,
email_template_file=args.email_template_file,
cdg_styles=cdg_styles,
keep_brand_code=getattr(args, 'keep_brand_code', False),
non_interactive=args.yes,
)
try:
track = kfinalise.process()
logger.info(f"Successfully completed finalisation for: {track['artist']} - {track['title']}")
# Display summary of outputs
logger.info(f"Karaoke finalisation 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 "final_karaoke_cdg_zip" in track or "final_karaoke_txt_zip" in track:
logger.info(f"")
logger.info(f"Karaoke Files:")
if "final_karaoke_cdg_zip" in track:
logger.info(f" CDG+MP3 ZIP: {track['final_karaoke_cdg_zip']}")
if "final_karaoke_txt_zip" in track:
logger.info(f" TXT+MP3 ZIP: {track['final_karaoke_txt_zip']}")
if track["brand_code"]:
logger.info(f"")
logger.info(f"Organization:")
logger.info(f" Brand Code: {track['brand_code']}")
logger.info(f" Directory: {track['new_brand_code_dir_path']}")
if track["youtube_url"] or track["brand_code_dir_sharing_link"]:
logger.info(f"")
logger.info(f"Sharing:")
if 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 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)}")
except Exception as e:
logger.error(f"An error occurred during finalisation, see stack trace below: {str(e)}")
raise e
return
# For prep or full workflow, parse input arguments
input_media, artist, title, filename_pattern = None, None, None, None
if not args.args:
parser.print_help()
sys.exit(1)
return # Explicit return for testing
# 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 (is_url(args.args[0]) or is_file(args.args[0])):
input_media = args.args[0]
if len(args.args) > 2:
artist = args.args[1]
title = args.args[2]
elif len(args.args) > 1:
artist = args.args[1]
else:
logger.warning("Input media provided without Artist and Title, both will be guessed from title")
elif os.path.isdir(args.args[0]):
if not args.filename_pattern:
logger.error("Filename pattern is required when processing a folder.")
sys.exit(1)
return # Explicit return for testing
if len(args.args) <= 1:
logger.error("Second parameter provided must be Artist name; Artist is required when processing a folder.")
sys.exit(1)
return # Explicit return for testing
input_media = args.args[0]
artist = args.args[1]
filename_pattern = args.filename_pattern
elif len(args.args) > 1:
artist = args.args[0]
title = args.args[1]
logger.warning(f"No input media provided, the top YouTube search result for {artist} - {title} will be used.")
else:
parser.print_help()
sys.exit(1)
return # Explicit return for testing
log_level = getattr(logging, args.log_level.upper())
logger.setLevel(log_level)
# Set up environment variables for lyrics-only mode
if args.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")
# Step 1: Run KaraokePrep
kprep_coroutine = KaraokePrep(
input_media=input_media,
artist=artist,
title=title,
filename_pattern=filename_pattern,
dry_run=args.dry_run,
log_formatter=log_formatter,
log_level=log_level,
render_bounding_boxes=args.render_bounding_boxes,
output_dir=args.output_dir,
create_track_subfolders=args.no_track_subfolders,
lossless_output_format=args.lossless_output_format,
output_png=args.output_png,
output_jpg=args.output_jpg,
clean_instrumental_model=args.clean_instrumental_model,
backing_vocals_models=args.backing_vocals_models,
other_stems_models=args.other_stems_models,
model_file_dir=args.model_file_dir,
existing_instrumental=args.existing_instrumental,
skip_separation=args.skip_separation,
lyrics_artist=args.lyrics_artist,
lyrics_title=args.lyrics_title,
lyrics_file=args.lyrics_file,
skip_lyrics=args.skip_lyrics,
skip_transcription=args.skip_transcription,
skip_transcription_review=args.skip_transcription_review,
subtitle_offset_ms=args.subtitle_offset_ms,
style_params_json=args.style_params_json,
style_overrides=style_overrides,
)
# No await needed for constructor
kprep = kprep_coroutine
# Create final tracks data structure
tracks = await kprep.process()
# If prep-only mode, we're done
if args.prep_only:
logger.info("Prep-only mode: skipping finalisation phase")
return
# Step 2: For each track, run KaraokeFinalise
for track in tracks:
logger.info(f"Starting finalisation phase for {track['artist']} - {track['title']}...")
# Use the track directory that was actually created by KaraokePrep
track_dir = track["track_output_dir"]
if not os.path.exists(track_dir):
logger.error(f"Track directory not found: {track_dir}")
continue
logger.info(f"Changing to directory: {track_dir}")
os.chdir(track_dir)
# Load CDG styles if CDG generation is enabled
cdg_styles = None
if args.enable_cdg:
if not args.style_params_json:
logger.error("CDG styles JSON file path (--style_params_json) is required when --enable_cdg is used")
sys.exit(1)
return # Explicit return for testing
try:
with open(args.style_params_json, "r") as f:
style_params = json.loads(f.read())
cdg_styles = style_params["cdg"]
except FileNotFoundError:
logger.error(f"CDG styles configuration file not found: {args.style_params_json}")
sys.exit(1)
return # Explicit return for testing
except json.JSONDecodeError as e:
logger.error(f"Invalid JSON in CDG styles configuration file: {e}")
sys.exit(1)
return # Explicit return for testing
except KeyError:
logger.error(f"'cdg' key not found in style parameters file: {args.style_params_json}")
sys.exit(1)
return # Explicit return for testing
kfinalise = KaraokeFinalise(
log_formatter=log_formatter,
log_level=log_level,
dry_run=args.dry_run,
instrumental_format=args.instrumental_format,
enable_cdg=args.enable_cdg,
enable_txt=args.enable_txt,
brand_prefix=args.brand_prefix,
organised_dir=args.organised_dir,
organised_dir_rclone_root=args.organised_dir_rclone_root,
public_share_dir=args.public_share_dir,
youtube_client_secrets_file=args.youtube_client_secrets_file,
youtube_description_file=args.youtube_description_file,
rclone_destination=args.rclone_destination,
discord_webhook_url=args.discord_webhook_url,
email_template_file=args.email_template_file,
cdg_styles=cdg_styles,
keep_brand_code=getattr(args, 'keep_brand_code', False),
non_interactive=args.yes,
)
try:
final_track = kfinalise.process()
logger.info(f"Successfully completed processing: {final_track['artist']} - {final_track['title']}")
# Display summary of outputs
logger.info(f"Karaoke generation complete! Output files:")
logger.info(f"")
logger.info(f"Track: {final_track['artist']} - {final_track['title']}")
logger.info(f"")
logger.info(f"Working Files:")
logger.info(f" Video With Vocals: {final_track['video_with_vocals']}")
logger.info(f" Video With Instrumental: {final_track['video_with_instrumental']}")
logger.info(f"")
logger.info(f"Final Videos:")
logger.info(f" Lossless 4K MP4 (PCM): {final_track['final_video']}")
logger.info(f" Lossless 4K MKV (FLAC): {final_track['final_video_mkv']}")
logger.info(f" Lossy 4K MP4 (AAC): {final_track['final_video_lossy']}")
logger.info(f" Lossy 720p MP4 (AAC): {final_track['final_video_720p']}")
if "final_karaoke_cdg_zip" in final_track or "final_karaoke_txt_zip" in final_track:
logger.info(f"")
logger.info(f"Karaoke Files:")
if "final_karaoke_cdg_zip" in final_track:
logger.info(f" CDG+MP3 ZIP: {final_track['final_karaoke_cdg_zip']}")
if "final_karaoke_txt_zip" in final_track:
logger.info(f" TXT+MP3 ZIP: {final_track['final_karaoke_txt_zip']}")
if final_track["brand_code"]:
logger.info(f"")
logger.info(f"Organization:")
logger.info(f" Brand Code: {final_track['brand_code']}")
logger.info(f" Directory: {final_track['new_brand_code_dir_path']}")
if final_track["youtube_url"] or final_track["brand_code_dir_sharing_link"]:
logger.info(f"")
logger.info(f"Sharing:")
if final_track["brand_code_dir_sharing_link"]:
logger.info(f" Folder Link: {final_track['brand_code_dir_sharing_link']}")
try:
time.sleep(1) # Brief pause between clipboard operations
pyperclip.copy(final_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 final_track["youtube_url"]:
logger.info(f" YouTube URL: {final_track['youtube_url']}")
try:
pyperclip.copy(final_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)}")
except Exception as e:
logger.error(f"An error occurred during finalisation, see stack trace below: {str(e)}")
raise e
return
def main():
asyncio.run(async_main())
if __name__ == "__main__":
main()
+424
View File
@@ -0,0 +1,424 @@
import os
import logging
import importlib.resources as pkg_resources
import shutil
from PIL import Image, ImageDraw, ImageFont
# Placeholder class or functions for video/image generation
class VideoGenerator:
def __init__(self, logger, ffmpeg_base_command, render_bounding_boxes, output_png, output_jpg):
self.logger = logger
self.ffmpeg_base_command = ffmpeg_base_command
self.render_bounding_boxes = render_bounding_boxes
self.output_png = output_png
self.output_jpg = output_jpg
def parse_region(self, region_str):
if region_str:
try:
parts = region_str.split(",")
if len(parts) != 4:
raise ValueError(f"Invalid region format: {region_str}. Expected 4 elements: 'x,y,width,height'")
return tuple(map(int, parts))
except ValueError as e:
# Re-raise specific format errors or general ValueError for int conversion issues
if "Expected 4 elements" in str(e):
raise e
raise ValueError(f"Invalid region format: {region_str}. Could not convert to integers. Expected format: 'x,y,width,height'") from e
return None
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))
# Placeholder methods - to be filled by user moving code
def create_video(
self,
extra_text,
title_text,
artist_text,
format,
output_image_filepath_noext,
output_video_filepath,
existing_image=None,
duration=5,
):
"""Create a video with title, artist, and optional extra text."""
self.logger.debug(f"Creating video with extra_text: '{extra_text}'")
self.logger.debug(f"Format settings: {format}")
resolution = (3840, 2160) # 4K resolution
self.logger.info(f"Creating video with format: {format}")
self.logger.info(f"extra_text: {extra_text}, artist_text: {artist_text}, title_text: {title_text}")
if existing_image:
return self._handle_existing_image(existing_image, output_image_filepath_noext, output_video_filepath, duration)
# Create or load background
background = self._create_background(format, resolution)
draw = ImageDraw.Draw(background)
if format["font"] is not None:
self.logger.info(f"Using font: {format['font']}")
# Check if the font path is absolute
if os.path.isabs(format["font"]):
font_path = format["font"]
if not os.path.exists(font_path):
self.logger.warning(f"Font file not found at {font_path}, falling back to default font")
font_path = None
else:
# Try to load from package resources
try:
with pkg_resources.path("karaoke_gen.resources", format["font"]) as font_path:
font_path = str(font_path)
except Exception as e:
self.logger.warning(f"Could not load font from resources: {e}, falling back to default font")
font_path = None
# Render all text elements
self._render_all_text(
draw,
font_path,
title_text,
artist_text,
format,
self.render_bounding_boxes,
)
else:
self.logger.info("No font specified, skipping text rendering")
# Save images and create video
self._save_output_files(
background, output_image_filepath_noext, output_video_filepath, duration, resolution
)
def calculate_text_size_to_fit(self, draw, text, font_path, region):
font_size = 500 # Start with a large font size
font = ImageFont.truetype(font_path, size=font_size) if font_path and os.path.exists(font_path) else ImageFont.load_default()
def get_text_size(text, font):
bbox = draw.textbbox((0, 0), text, font=font)
# Use the actual text height without the font's internal padding
return bbox[2], bbox[3] - bbox[1]
text_width, text_height = get_text_size(text, font)
target_height = region[3] # Use full region height as target
while text_width > region[2] or text_height > target_height:
font_size -= 10
if font_size <= 150:
# Split the text into two lines
words = text.split()
mid = len(words) // 2
line1 = " ".join(words[:mid])
line2 = " ".join(words[mid:])
# Reset font size for two-line layout
font_size = 500
font = ImageFont.truetype(font_path, size=font_size) if font_path and os.path.exists(font_path) else ImageFont.load_default()
while True:
text_width1, text_height1 = get_text_size(line1, font)
text_width2, text_height2 = get_text_size(line2, font)
total_height = text_height1 + text_height2
# Add a small gap between lines (10% of line height)
line_gap = text_height1 * 0.1
total_height_with_gap = total_height + line_gap
if max(text_width1, text_width2) <= region[2] and total_height_with_gap <= target_height:
return font, (line1, line2)
font_size -= 10
if font_size <= 0:
raise ValueError("Cannot fit text within the defined region.")
font = ImageFont.truetype(font_path, size=font_size) if font_path and os.path.exists(font_path) else ImageFont.load_default()
font = ImageFont.truetype(font_path, size=font_size) if font_path and os.path.exists(font_path) else ImageFont.load_default()
text_width, text_height = get_text_size(text, font)
return font, text
def _render_text_in_region(self, draw, text, font_path, region, color, gradient=None, font=None):
"""Helper method to render text within a specified region."""
self.logger.debug(f"Rendering text: '{text}' in region: {region} with color: {color} gradient: {gradient}")
if text is None:
self.logger.debug("Text is None, skipping rendering")
return region
if region is None:
self.logger.debug("Region is None, skipping rendering")
return region
if font is None:
font, text_lines = self.calculate_text_size_to_fit(draw, text, font_path, region)
else:
text_lines = text
self.logger.debug(f"Using text_lines: {text_lines}")
x, y, width, height = region
# Get font metrics
ascent, descent = font.getmetrics()
font_height = ascent + descent
def render_text_with_gradient(text, position, bbox):
# Convert position coordinates to integers
position = (int(position[0]), int(position[1]))
if gradient is None:
draw.text(position, text, fill=color, font=font)
else:
# Create a temporary image for this text
text_layer = Image.new("RGBA", (bbox[2], bbox[3]), (0, 0, 0, 0))
text_draw = ImageDraw.Draw(text_layer)
# Draw text in first color
text_draw.text((0, 0), text, fill=gradient["color1"], font=font)
# Create and apply gradient mask
mask = self._create_gradient_mask((bbox[2], bbox[3]), gradient)
# Create second color layer
color2_layer = Image.new("RGBA", (bbox[2], bbox[3]), (0, 0, 0, 0))
color2_draw = ImageDraw.Draw(color2_layer)
color2_draw.text((0, 0), text, fill=gradient["color2"], font=font)
# Composite using gradient mask
text_layer.paste(color2_layer, mask=mask)
# Paste onto main image
draw._image.paste(text_layer, position, text_layer)
if isinstance(text_lines, tuple): # Two lines
line1, line2 = text_lines
bbox1 = draw.textbbox((0, 0), line1, font=font)
bbox2 = draw.textbbox((0, 0), line2, font=font)
# Calculate line heights using bounding boxes
line1_height = bbox1[3] - bbox1[1]
line2_height = bbox2[3] - bbox2[1]
# Use a small gap between lines (20% of average line height)
line_gap = int((line1_height + line2_height) * 0.1)
# Calculate total height needed
total_height = line1_height + line_gap + line2_height
# Center the entire text block vertically in the region
y_start = y + (height - total_height) // 2
# Draw first line
pos1 = (x + (width - bbox1[2]) // 2, y_start)
render_text_with_gradient(line1, pos1, bbox1)
# Draw second line
pos2 = (x + (width - bbox2[2]) // 2, y_start + line1_height + line_gap)
render_text_with_gradient(line2, pos2, bbox2)
else:
# Single line
bbox = draw.textbbox((0, 0), text_lines, font=font)
# Center text vertically using font metrics
y_pos = y + (height - font_height) // 2
position = (x + (width - bbox[2]) // 2, y_pos)
render_text_with_gradient(text_lines, position, bbox)
return region
def _draw_bounding_box(self, draw, region, color):
"""Helper method to draw a bounding box around a region."""
if region is None:
self.logger.debug("Region is None, skipping drawing bounding box")
return
x, y, width, height = region
draw.rectangle([x, y, x + width, y + height], outline=color, width=2)
def _create_gradient_mask(self, size, gradient_config):
"""Create a gradient mask for text coloring.
Args:
size (tuple): (width, height) of the mask
gradient_config (dict): Configuration with keys:
- color1: First color (hex)
- color2: Second color (hex)
- direction: 'horizontal' or 'vertical'
- start: Start point of gradient transition (0-1)
- stop: Stop point of gradient transition (0-1)
"""
mask = Image.new("L", size)
draw = ImageDraw.Draw(mask)
width, height = size
start = gradient_config["start"]
stop = gradient_config["stop"]
if gradient_config["direction"] == "horizontal":
for x in range(width):
# Calculate position in gradient (0 to 1)
pos = x / width
# Calculate color intensity
if pos < start:
intensity = 0
elif pos > stop:
intensity = 255
else:
# Linear interpolation between start and stop
intensity = int(255 * (pos - start) / (stop - start))
draw.line([(x, 0), (x, height)], fill=intensity)
else: # vertical
for y in range(height):
pos = y / height
if pos < start:
intensity = 0
elif pos > stop:
intensity = 255
else:
intensity = int(255 * (pos - start) / (stop - start))
draw.line([(0, y), (width, y)], fill=intensity)
return mask
def _handle_existing_image(self, existing_image, output_image_filepath_noext, output_video_filepath, duration):
"""Handle case where an existing image is provided."""
self.logger.info(f"Using existing image file: {existing_image}")
existing_extension = os.path.splitext(existing_image)[1]
if existing_extension == ".png":
self.logger.info(f"Copying existing PNG image file: {existing_image}")
shutil.copy2(existing_image, output_image_filepath_noext + existing_extension)
else:
self.logger.info(f"Converting existing image to PNG")
existing_image_obj = Image.open(existing_image)
existing_image_obj.save(output_image_filepath_noext + ".png")
if existing_extension != ".jpg":
self.logger.info(f"Converting existing image to JPG")
existing_image_obj = Image.open(existing_image)
if existing_image_obj.mode == "RGBA":
existing_image_obj = existing_image_obj.convert("RGB")
existing_image_obj.save(output_image_filepath_noext + ".jpg", quality=95)
if duration > 0:
self._create_video_from_image(output_image_filepath_noext + ".png", output_video_filepath, duration)
def _create_background(self, format, resolution):
"""Create or load the background image."""
if format["background_image"] and os.path.exists(format["background_image"]):
self.logger.info(f"Using background image file: {format['background_image']}")
background = Image.open(format["background_image"])
else:
self.logger.info(f"Using background color: {format['background_color']}")
background = Image.new("RGB", resolution, color=self.hex_to_rgb(format["background_color"]))
return background.resize(resolution)
def _render_all_text(self, draw, font_path, title_text, artist_text, format, render_bounding_boxes):
"""Render all text elements on the image."""
# Render title
if format["title_region"]:
region_parsed = self.parse_region(format["title_region"])
region = self._render_text_in_region(
draw, title_text, font_path, region_parsed, format["title_color"], gradient=format.get("title_gradient")
)
if render_bounding_boxes:
self._draw_bounding_box(draw, region, format["title_color"])
# Render artist
if format["artist_region"]:
region_parsed = self.parse_region(format["artist_region"])
region = self._render_text_in_region(
draw, artist_text, font_path, region_parsed, format["artist_color"], gradient=format.get("artist_gradient")
)
if render_bounding_boxes:
self._draw_bounding_box(draw, region, format["artist_color"])
# Render extra text if provided
if format["extra_text"]:
region_parsed = self.parse_region(format["extra_text_region"])
region = self._render_text_in_region(
draw, format["extra_text"], font_path, region_parsed, format["extra_text_color"], gradient=format.get("extra_text_gradient")
)
if render_bounding_boxes:
self._draw_bounding_box(draw, region, format["extra_text_color"])
def _save_output_files(
self, background, output_image_filepath_noext, output_video_filepath, duration, resolution
):
"""Save the output image files and create video if needed."""
# Save static background image
if self.output_png:
background.save(f"{output_image_filepath_noext}.png")
if self.output_jpg:
# Save static background image as JPG for smaller filesize
background_rgb = background.convert("RGB")
background_rgb.save(f"{output_image_filepath_noext}.jpg", quality=95)
if duration > 0:
self._create_video_from_image(f"{output_image_filepath_noext}.png", output_video_filepath, duration, resolution)
def _create_video_from_image(self, image_path, video_path, duration, resolution=(3840, 2160)):
"""Create a video from a static image."""
ffmpeg_command = (
f'{self.ffmpeg_base_command} -y -loop 1 -framerate 30 -i "{image_path}" '
f"-f lavfi -i anullsrc -c:v libx264 -r 30 -t {duration} -pix_fmt yuv420p "
f'-vf scale={resolution[0]}:{resolution[1]} -c:a aac -shortest "{video_path}"'
)
self.logger.info("Generating video...")
self.logger.debug(f"Running command: {ffmpeg_command}")
os.system(ffmpeg_command)
def _transform_text(self, text, transform_type):
"""Helper method to transform text based on specified type."""
if text is None:
return None # Return None if input is None
if transform_type == "uppercase":
return text.upper()
elif transform_type == "lowercase":
return text.lower()
elif transform_type == "propercase":
return text.title()
return text # "none" or any other value returns original text
def create_title_video(
self, artist, title, format, output_image_filepath_noext, output_video_filepath, existing_title_image, intro_video_duration
):
title_text = self._transform_text(title, format["title_text_transform"])
artist_text = self._transform_text(artist, format["artist_text_transform"])
self.create_video(
title_text=title_text,
artist_text=artist_text,
extra_text=format["extra_text"],
format=format,
output_image_filepath_noext=output_image_filepath_noext,
output_video_filepath=output_video_filepath,
existing_image=existing_title_image,
duration=intro_video_duration,
)
def create_end_video(
self, artist, title, format, output_image_filepath_noext, output_video_filepath, existing_end_image, end_video_duration
):
title_text = self._transform_text(title, format["title_text_transform"])
artist_text = self._transform_text(artist, format["artist_text_transform"])
self.create_video(
title_text=title_text,
artist_text=artist_text,
extra_text=format["extra_text"],
format=format,
output_image_filepath_noext=output_image_filepath_noext,
output_video_filepath=output_video_filepath,
existing_image=existing_end_image,
duration=end_video_duration,
)
-1
View File
@@ -1 +0,0 @@
from .karaoke_prep import KaraokePrep
@@ -1,89 +0,0 @@
import os
import subprocess
import tempfile
import logging
class KaraokeFinalise:
def __init__(
self,
log_level=logging.DEBUG,
log_formatter=None,
model_name="UVR_MDXNET_KARA_2",
):
self.logger = logging.getLogger(__name__)
self.logger.setLevel(log_level)
self.log_level = log_level
self.log_formatter = log_formatter
self.log_handler = logging.StreamHandler()
if self.log_formatter is None:
self.log_formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(module)s - %(message)s")
self.log_handler.setFormatter(self.log_formatter)
self.logger.addHandler(self.log_handler)
self.logger.debug(f"KaraokeFinalise instantiating")
self.ffmpeg_base_command = "ffmpeg -hide_banner -nostats"
if self.log_level == logging.DEBUG:
self.ffmpeg_base_command += " -loglevel verbose"
else:
self.ffmpeg_base_command += " -loglevel fatal"
self.model_name = model_name
def process(self):
tracks = []
self.logger.info(f"Searching for files in current directory ending with (Karaoke).mov")
for karaoke_file in filter(lambda f: " (Karaoke).mov" in f, os.listdir(".")):
base_name = karaoke_file.replace(" (Karaoke).mov", "")
artist = base_name.split(" - ")[0]
title = base_name.split(" - ")[1]
with_vocals_file = f"{base_name} (With Vocals).mov"
title_file = f"{base_name} (Title).mov"
instrumental_file = f"{base_name} (Instrumental {self.model_name}).mp3"
final_mp4_file = f"{base_name} (Final Karaoke).mp4"
track = {
"artist": artist,
"title": title,
"video_with_vocals": with_vocals_file,
"video_with_instrumental": karaoke_file,
"final_video": final_mp4_file,
}
if os.path.isfile(title_file) and os.path.isfile(karaoke_file) and os.path.isfile(instrumental_file):
self.logger.info(f"All 3 input files found for {base_name}, beginning finalisation")
self.logger.info(f"Output [With Vocals]: renaming synced video to: {with_vocals_file}")
os.rename(karaoke_file, with_vocals_file)
self.logger.info(f"Output [With Instrumental]: remuxing synced video with instrumental audio to: {karaoke_file}")
ffmpeg_command = f'{self.ffmpeg_base_command} -an -i "{with_vocals_file}" -vn -i "{instrumental_file}" -c:v copy -c:a aac "{karaoke_file}"'
self.logger.debug(f"Running command: {ffmpeg_command}")
os.system(ffmpeg_command)
self.logger.info(f"Output [Final Karaoke]: joining title video and instrumental video to produce: {final_mp4_file}")
with tempfile.NamedTemporaryFile(mode="w+", delete=False, dir="/tmp", suffix=".txt") as tmp_file_list:
tmp_file_list.write(f"file '{os.path.abspath(title_file)}'\n")
tmp_file_list.write(f"file '{os.path.abspath(karaoke_file)}'\n")
ffmpeg_command = f'{self.ffmpeg_base_command} -f concat -safe 0 -i "{tmp_file_list.name}" -vf settb=AVTB,setpts=N/30/TB,fps=30 "{final_mp4_file}"'
self.logger.debug(f"Running command: {ffmpeg_command}")
os.system(ffmpeg_command)
os.remove(tmp_file_list.name)
else:
self.logger.error(f"Unable to find all 3 required input files:\n {title_file}\n {karaoke_file}\n {instrumental_file}")
tracks.append(track)
return tracks
-580
View File
@@ -1,580 +0,0 @@
import os
import re
import glob
import yt_dlp
import logging
import lyricsgenius
import tempfile
import importlib.resources as pkg_resources
from PIL import Image, ImageDraw, ImageFont
class KaraokePrep:
def __init__(
self,
url=None,
artist=None,
title=None,
log_level=logging.DEBUG,
log_formatter=None,
model_name="UVR_MDXNET_KARA_2",
model_name_2="UVR-MDX-NET-Inst_HQ_3",
model_file_dir=os.path.join(tempfile.gettempdir(), "audio-separator-models"),
output_dir=".",
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="Montserrat-Bold.ttf",
intro_artist_color="#ffffff",
intro_title_color="#ff7acc",
):
self.logger = logging.getLogger(__name__)
self.logger.setLevel(log_level)
self.log_level = log_level
self.log_formatter = log_formatter
self.log_handler = logging.StreamHandler()
if self.log_formatter is None:
self.log_formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(module)s - %(message)s")
self.log_handler.setFormatter(self.log_formatter)
self.logger.addHandler(self.log_handler)
self.logger.debug(f"KaraokePrep instantiating with url: {url} artist: {artist} title: {title}")
self.url = url
self.artist = artist
self.title = title
self.model_name = model_name
self.model_name_2 = model_name_2
self.model_file_dir = model_file_dir
self.output_dir = output_dir
self.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.ffmpeg_base_command = "ffmpeg -hide_banner -nostats"
if self.log_level == logging.DEBUG:
self.ffmpeg_base_command += " -loglevel verbose"
else:
self.ffmpeg_base_command += " -loglevel fatal"
self.title_format = {
"background_color": intro_background_color,
"background_image": intro_background_image,
"intro_font": intro_font,
"artist_color": intro_artist_color,
"title_color": intro_title_color,
}
self.persistent_artist = None
self.logger.debug(f"KaraokePrep 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.persistent_artist:
self.artist = self.persistent_artist
if self.artist and self.title:
self.logger.info(f"Extracted artist: {self.artist}, title: {self.title}")
else:
self.logger.error("Failed to extract artist and title from the YouTube URL.")
def parse_metadata(self, info):
"""
Parses the metadata to extract artist and title.
:param info: The metadata information extracted from yt_dlp.
:return: A tuple containing the artist and title.
"""
# Default values if parsing fails
artist = ""
title = ""
# Example: "Artist - Title"
if "title" in info and "-" in info["title"]:
artist, title = info["title"].split("-", 1)
artist = artist.strip()
title = title.strip()
elif "uploader" in info:
# Fallback to uploader as artist if title parsing fails
artist = info["uploader"]
if "title" in info:
title = info["title"].strip()
# If unable to parse, log an appropriate message
if not artist or not title:
self.logger.warning("Could not parse artist and title from the video metadata.")
return artist, title
def get_youtube_id_for_top_search_result(self, query):
ydl_opts = {"quiet": "True", "format": "bestaudio", "noplaylist": "True", "extract_flat": True}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
video = ydl.extract_info(f"ytsearch1:{query}", download=False)["entries"][0]
if video:
youtube_id = video.get("id")
return youtube_id
else:
self.logger.warning(f"No YouTube results found for query: {query}")
return None
def download_video(self, youtube_id, output_filename_no_extension):
self.logger.debug(f"Downloading YouTube video {youtube_id} to filename {output_filename_no_extension} + (as yet) unknown extension")
downloaded_file_name = output_filename_no_extension
actual_file_extension = None
def ydl_progress_hook(d):
nonlocal actual_file_extension
if d["status"] == "finished":
actual_file_extension = d["filename"].split(".")[-1]
ydl_opts = {
"quiet": True,
"format": "bv*+ba/b", # if a combined video + audio format is better than the best video-only format use the combined format
"outtmpl": f"{output_filename_no_extension}",
"progress_hooks": [ydl_progress_hook],
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",
}
with yt_dlp.YoutubeDL(ydl_opts) as youtube_dl_instance:
youtube_dl_instance.download([f"https://www.youtube.com/watch?v={youtube_id}"])
downloaded_file_name += f".{actual_file_extension}"
self.logger.info(f"Download finished, returning downloaded filename: {downloaded_file_name}")
return downloaded_file_name
def extract_still_image_from_video(self, input_filename, output_filename_no_extension):
output_filename = output_filename_no_extension + ".png"
self.logger.info(f"Extracting still image from position 30s YouTube video")
ffmpeg_command = f'{self.ffmpeg_base_command} -i "{input_filename}" -ss 00:00:30 -vframes 1 "{output_filename}"'
self.logger.debug(f"Running command: {ffmpeg_command}")
os.system(ffmpeg_command)
return output_filename
def convert_to_wav(self, input_filename, output_filename_no_extension):
output_filename = output_filename_no_extension + ".wav"
self.logger.info(f"Converting input video to audio WAV file")
ffmpeg_command = f'{self.ffmpeg_base_command} -i "{input_filename}" "{output_filename}"'
self.logger.debug(f"Running command: {ffmpeg_command}")
os.system(ffmpeg_command)
return output_filename
def write_lyrics_from_genius(self, artist, title, filename):
genius = lyricsgenius.Genius(access_token=os.environ["GENIUS_API_TOKEN"], verbose=False, remove_section_headers=True)
song = genius.search_song(title, artist)
if song:
lyrics = self.clean_genius_lyrics(song.lyrics)
with open(filename, "w") as f:
f.write(lyrics)
self.logger.info("Lyrics for %s by %s fetched successfully", title, artist)
return lyrics.split("\n")
else:
self.logger.warning("Could not find lyrics for %s by %s", title, artist)
def clean_genius_lyrics(self, lyrics):
lyrics = lyrics.replace("\\n", "\n")
lyrics = re.sub(r"You might also like", "", lyrics)
lyrics = re.sub(
r".*?Lyrics([A-Z])", r"\1", lyrics
) # Remove the song name and word "Lyrics" if this has a non-newline char at the start
lyrics = re.sub(r"^[0-9]* Contributors.*Lyrics", "", lyrics) # Remove this example: 27 ContributorsSex Bomb Lyrics
lyrics = re.sub(
r"See.*Live.*Get tickets as low as \$[0-9]+", "", lyrics
) # Remove this example: See Tom Jones LiveGet tickets as low as $71
lyrics = re.sub(r"[0-9]+Embed$", "", lyrics) # Remove the word "Embed" at end of line with preceding numbers if found
lyrics = re.sub(r"(\S)Embed$", r"\1", lyrics) # Remove the word "Embed" if it has been tacked onto a word at the end of a line
lyrics = re.sub(r"^Embed$", r"", lyrics) # Remove the word "Embed" if it has been tacked onto a word at the end of a line
lyrics = re.sub(r".*?\[.*?\].*?", "", lyrics) # Remove lines containing square brackets
# add any additional cleaning rules here
return lyrics
def find_best_split_point(self, line):
"""
Find the best split point in a line based on the specified criteria.
"""
self.logger.debug(f"Finding best_split_point for line: {line}")
words = line.split()
mid_word_index = len(words) // 2
# Check for a comma within one or two words of the middle word
if "," in line:
mid_point = len(" ".join(words[:mid_word_index]))
comma_indices = [i for i, char in enumerate(line) if char == ","]
for index in comma_indices:
if abs(mid_point - index) < 20: # Roughly the length of two average words
self.logger.debug(
f"Found comma at index {index} which is within 20 characters of mid_point {mid_point}, accepting as split point"
)
return index + 1 # Include the comma in the first line
# Check for 'and'
if " and " in line:
mid_point = len(line) // 2
and_indices = [m.start() for m in re.finditer(" and ", line)]
split_point = min(and_indices, key=lambda x: abs(x - mid_point))
self.logger.debug(f"Found 'and' at index {split_point} which is close to mid_point {mid_point}, accepting as split point")
return split_point + len(" and ") # Include 'and' in the first line
# Split at the middle word
self.logger.debug(f"No comma or suitable 'and' found, using middle word as split point")
return len(" ".join(words[:mid_word_index]))
def process_line(self, line):
"""
Process a single line to ensure it's within the maximum length,
and handle parentheses.
"""
processed_lines = []
while len(line) > 36:
# Check if the line contains parentheses
if "(" in line and ")" in line:
start_paren = line.find("(")
end_paren = line.find(")") + 1
if end_paren < len(line) and line[end_paren] == ",":
end_paren += 1
if start_paren > 0:
processed_lines.append(line[:start_paren].strip())
processed_lines.append(line[start_paren:end_paren].strip())
line = line[end_paren:].strip()
else:
split_point = self.find_best_split_point(line)
processed_lines.append(line[:split_point].strip())
line = line[split_point:].strip()
if line: # Add the remaining part if not empty
processed_lines.append(line)
return processed_lines
def write_processed_lyrics(self, lyrics, processed_lyrics_file):
self.logger.debug(f"Writing processed lyrics to {processed_lyrics_file}")
with open(processed_lyrics_file, "w") as outfile:
all_processed = False
while not all_processed:
all_processed = True
new_lyrics = []
for line in lyrics:
line = line.strip()
processed = self.process_line(line)
new_lyrics.extend(processed)
if any(len(l) > 36 for l in processed):
all_processed = False
lyrics = new_lyrics
# Write the processed lyrics to file
for line in lyrics:
outfile.write(line + "\n")
def sanitize_filename(self, filename):
"""Replace or remove characters that are unsafe for filenames."""
# Replace problematic characters with underscores
for char in ["\\", "/", ":", "*", "?", '"', "<", ">", "|"]:
filename = filename.replace(char, "_")
# Remove any trailing periods or spaces
filename = filename.rstrip(". ")
return filename
def separate_audio(self, audio_file, model_name, instrumental_path, vocals_path):
if audio_file is None or not os.path.isfile(audio_file):
raise Exception("Error: Invalid audio source provided.")
self.logger.debug(f"audio_file is valid file: {audio_file}")
self.logger.debug(
f"instantiating Separator with model_name: {model_name} instrumental_path: {instrumental_path} and 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 calculate_text_size_and_position(self, draw, text, font_path, start_size, resolution, padding):
font_size = start_size
font = ImageFont.truetype(font_path, size=font_size) if os.path.exists(font_path) else ImageFont.load_default()
# Initial position for calculating the text bounding box
temp_position = (padding, padding)
bbox = draw.textbbox(temp_position, text, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
while text_width + 2 * padding > resolution[0] or text_height + 2 * padding > resolution[1]:
font_size -= 10
if font_size <= 0:
raise ValueError("Cannot fit text within screen bounds.")
font = ImageFont.truetype(font_path, size=font_size) if os.path.exists(font_path) else ImageFont.load_default()
bbox = draw.textbbox(temp_position, text, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
text_position = ((resolution[0] - text_width) // 2, (resolution[1] - text_height) // 2)
return font, text_position
def calculate_text_position(self, draw, text, font, resolution, vertical_offset):
bbox = draw.textbbox((0, 0), text, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
text_x = (resolution[0] - text_width) // 2
text_y = vertical_offset
return (text_x, text_y), text_height
def create_title_video(self, artist, title, format, output_image_filepath, output_video_filepath):
duration = 5 # Duration in seconds
resolution = (3840, 2160) # 4K resolution
# Load or create background image
if format["background_image"] and os.path.exists(format["background_image"]):
self.logger.info(f"Using title screen background image file: {format['background_image']}")
background = Image.open(format["background_image"])
else:
self.logger.info(f"Using title screen background color: {format['background_color']}")
background = Image.new("RGB", resolution, color=self.hex_to_rgb(format["background_color"]))
# Resize background to match resolution
background = background.resize(resolution)
title = title.upper()
artist = artist.upper()
initial_font_size = 500
top_padding = 950
title_padding = 400
artist_padding = 700
fixed_gap = 150
draw = ImageDraw.Draw(background)
# Accessing the font file from the package resources
with pkg_resources.path('karaoke_prep.resources', format['intro_font']) as font_path:
# Calculate positions and sizes for title and artist
title_font, _ = self.calculate_text_size_and_position(
draw, title, str(font_path), initial_font_size, resolution, title_padding
)
artist_font, _ = self.calculate_text_size_and_position(
draw, artist, str(font_path), initial_font_size, resolution, artist_padding
)
# Calculate vertical positions with consistent gap
title_text_position, title_height = self.calculate_text_position(draw, title, title_font, resolution, top_padding)
artist_text_position, _ = self.calculate_text_position(
draw, artist, artist_font, resolution, title_text_position[1] + title_height + fixed_gap
)
draw.text(title_text_position, title, fill=format["title_color"], font=title_font)
draw.text(artist_text_position, artist, fill=format["artist_color"], font=artist_font)
# Save static background image
background.save(output_image_filepath)
# Use ffmpeg to create video
ffmpeg_command = f'{self.ffmpeg_base_command} -y -loop 1 -framerate 30 -i "{output_image_filepath}" -f lavfi -i anullsrc '
ffmpeg_command += f'-c:v libx264 -r 30 -t {duration} -pix_fmt yuv420p -vf scale={resolution[0]}:{resolution[1]} -c:a aac -shortest "{output_video_filepath}"'
self.logger.info("Generating title video...")
self.logger.debug(f"Running command: {ffmpeg_command}")
os.system(ffmpeg_command)
def hex_to_rgb(self, hex_color):
"""Convert hex color to RGB tuple."""
hex_color = hex_color.lstrip("#")
return tuple(int(hex_color[i : i + 2], 16) for i in (0, 2, 4))
def prep_single_track(self):
if self.artist is None or self.title is None:
self.logger.warn(f"Artist or Title nor specified manually, guessing from YouTube metadata...")
self.extract_metadata_from_url()
artist = self.artist
title = self.title
self.logger.info(f"Preparing output path for track: {title} by {artist}")
track_output_dir, artist_title = self.setup_output_paths(artist, title)
processed_track = {
"track_output_dir": track_output_dir,
"artist": artist,
"title": title,
}
self.logger.info(f"Creating title video...")
processed_track["title_image"] = os.path.join(track_output_dir, f"{artist_title} (Title).png")
processed_track["title_video"] = os.path.join(track_output_dir, f"{artist_title} (Title).mov")
self.create_title_video(artist, title, self.title_format, processed_track["title_image"], processed_track["title_video"])
lyrics_file = os.path.join(track_output_dir, f"{artist_title} (Lyrics).txt")
processed_lyrics_file = os.path.join(track_output_dir, f"{artist_title} (Lyrics Processed).txt")
if os.path.exists(lyrics_file):
self.logger.debug(f"Lyrics file already exists, skipping fetch: {lyrics_file}")
else:
self.logger.info("Fetching lyrics from Genius...")
lyrics = self.write_lyrics_from_genius(artist, title, lyrics_file)
self.write_processed_lyrics(lyrics, processed_lyrics_file)
processed_track["lyrics"] = lyrics_file
processed_track["processed_lyrics"] = processed_lyrics_file
# WebM may not always be the output format from YouTubeDL, but it's the most common and this is just a convenience cache
yt_webm_filename_pattern = os.path.join(track_output_dir, f"{artist_title} (YouTube *.webm")
yt_webm_glob = glob.glob(yt_webm_filename_pattern)
yt_png_filename_pattern = os.path.join(track_output_dir, f"{artist_title} (YouTube *.png")
yt_png_glob = glob.glob(yt_png_filename_pattern)
yt_wav_filename_pattern = os.path.join(track_output_dir, f"{artist_title} (YouTube *.wav")
yt_wav_glob = glob.glob(yt_wav_filename_pattern)
processed_track["youtube_video"] = None
processed_track["youtube_still_image"] = None
processed_track["youtube_audio"] = None
if yt_webm_glob and yt_png_glob and yt_wav_glob:
processed_track["youtube_video"] = yt_webm_glob[0]
processed_track["youtube_still_image"] = yt_png_glob[0]
processed_track["youtube_audio"] = yt_wav_glob[0]
self.logger.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.")
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(f"Querying playlist metadata from YouTube, assuming consistent artist {self.artist}...")
with yt_dlp.YoutubeDL({"quiet": True}) as ydl:
result = ydl.extract_info(self.url, download=False)
if "entries" in result:
track_results = []
self.logger.info(f"Found {len(result['entries'])} videos in playlist, processing each invididually...")
for video in result["entries"]:
video_url = f"https://www.youtube.com/watch?v={video['id']}"
self.logger.info(f"Processing video: {video_url}")
self.url = video_url
track_results.append(self.prep_single_track())
self.artist = self.persistent_artist
self.title = None
return track_results
def process(self):
if self.is_playlist_url():
self.persistent_artist = self.artist
self.logger.info(
f"Provided YouTube URL is a playlist, beginning batch operation with persistent artist: {self.persistent_artist}"
)
return self.process_playlist()
else:
self.logger.info(f"Provided YouTube URL is NOT a playlist, processing single track")
return [self.prep_single_track()]
-64
View File
@@ -1,64 +0,0 @@
#!/usr/bin/env python
import argparse
import logging
import pkg_resources
from karaoke_prep.karaoke_finalise import KaraokeFinalise
def main():
logger = logging.getLogger(__name__)
log_handler = logging.StreamHandler()
log_formatter = logging.Formatter(fmt="%(asctime)s.%(msecs)03d - %(levelname)s - %(module)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log_handler.setFormatter(log_formatter)
logger.addHandler(log_handler)
parser = argparse.ArgumentParser(
description="Render, remux and join intermediate files to create final karaoke video, as the third stage after using karaoke-prep. Processes all (Karaoke).mov files in current directory.",
formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=54),
)
package_version = pkg_resources.get_distribution("karaoke-prep").version
parser.add_argument("-v", "--version", action="version", version=f"%(prog)s {package_version}")
parser.add_argument(
"--log_level",
default="info",
help="Optional: logging level, e.g. info, debug, warning (default: %(default)s). Example: --log_level=debug",
)
parser.add_argument(
"--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",
)
args = parser.parse_args()
log_level = getattr(logging, args.log_level.upper())
logger.setLevel(log_level)
logger.info(f"KaraokeFinalise beginning with model_name: {args.model_name}")
kfinalise = KaraokeFinalise(
log_formatter=log_formatter,
log_level=log_level,
model_name=args.model_name,
)
tracks = kfinalise.process()
if len(tracks) == 0:
logger.error(f"No tracks found to process.")
return
logger.info(f"Karaoke finalisation processing complete! Output files:")
for track in tracks:
logger.info(f"")
logger.info(f"Track: {track['artist']} - {track['title']}")
logger.info(f" Video With Vocals: {track['video_with_vocals']}")
logger.info(f" Video With Instrumental: {track['video_with_instrumental']}")
logger.info(f" Final Video with Title: {track['final_video']}")
if __name__ == "__main__":
main()
-199
View File
@@ -1,199 +0,0 @@
#!/usr/bin/env python
import argparse
import logging
import pkg_resources
import tempfile
import os
from karaoke_prep import KaraokePrep
def is_url(string):
"""Simple check to determine if a string is a URL."""
return string.startswith("http://") or string.startswith("https://")
def main():
logger = logging.getLogger(__name__)
log_handler = logging.StreamHandler()
log_formatter = logging.Formatter(fmt="%(asctime)s.%(msecs)03d - %(levelname)s - %(module)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log_handler.setFormatter(log_formatter)
logger.addHandler(log_handler)
parser = argparse.ArgumentParser(
description="Fetch audio and lyrics for a specified song, to prepare karaoke video creation.",
formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=54),
)
parser.add_argument(
"args",
nargs="*",
help="[YouTube video or playlist URL] [Artist] [Title] of song to prep. If URL is provided, Artist and Title are optional but increase chance of fetching the correct lyrics. If Artist and Title are provided with no URL, the top YouTube search result will be fetched.",
)
package_version = pkg_resources.get_distribution("karaoke-prep").version
parser.add_argument("-v", "--version", action="version", version=f"%(prog)s {package_version}")
parser.add_argument(
"--log_level",
default="info",
help="Optional: logging level, e.g. info, debug, warning (default: %(default)s). Example: --log_level=debug",
)
parser.add_argument(
"--model_name",
default="UVR_MDXNET_KARA_2",
help="Optional: model name to be used for separation (default: %(default)s). Example: --model_name=UVR-MDX-NET-Inst_HQ_3",
)
# Use tempfile to get the platform-independent temp directory
default_model_dir = os.path.join(tempfile.gettempdir(), "audio-separator-models")
parser.add_argument(
"--model_file_dir",
default=default_model_dir,
help="Optional: model files directory (default: %(default)s). Example: --model_file_dir=/app/models",
)
parser.add_argument(
"--output_dir",
default=".",
help="Optional: directory to write output files (default: <current dir>). Example: --output_dir=/app/karaoke",
)
parser.add_argument(
"--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="#000000",
help="Optional: Background color for intro video (default: black). Example: --intro_background_color=#123456",
)
parser.add_argument(
"--intro_background_image",
help="Optional: Path to background image for intro video. Overrides background color if provided. Example: --intro_background_image=path/to/image.jpg",
)
parser.add_argument(
"--intro_font",
default="Montserrat-Bold.ttf",
help="Optional: Font file for intro video (default: Montserrat-Bold.ttf). Example: --intro_font=AvenirNext-Bold.ttf",
)
parser.add_argument(
"--intro_artist_color",
default="#ffdf6b",
help="Optional: Font color for intro video artist text (default: #ffdf6b). Example: --intro_artist_color=#123456",
)
parser.add_argument(
"--intro_title_color",
default="#ffffff",
help="Optional: Font color for intro video title text (default: #ffffff). Example: --intro_title_color=#123456",
)
args = parser.parse_args()
url, artist, title = None, None, None
# Allow 3 forms of positional arguments:
# 1. URL only (may be single track URL or playlist URL)
# 2. Artist and Title only
# 3. URL, Artist, and Title
if args.args and is_url(args.args[0]):
url = args.args[0]
if len(args.args) > 2:
artist = args.args[1]
title = args.args[2]
elif len(args.args) > 1:
artist = args.args[1]
else:
logger.warn("URL provided without Artist and Title, both will be guessed from YouTube Title")
elif len(args.args) > 1:
artist = args.args[0]
title = args.args[1]
logger.warn(f"No URL provided, the top YouTube search result for {artist} - {title} will be used.")
else:
parser.print_help()
exit(1)
log_level = getattr(logging, args.log_level.upper())
logger.setLevel(log_level)
logger.info(f"KaraokePrep beginning with url: {url} artist: {artist} and title: {title}")
kprep = KaraokePrep(
artist=artist,
title=title,
url=url,
log_formatter=log_formatter,
log_level=log_level,
model_name=args.model_name,
model_file_dir=args.model_file_dir,
output_dir=args.output_dir,
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" Processed Lyrics: {track['processed_lyrics']}")
logger.info(f" Instrumental: {track['instrumental_audio']}")
logger.info(f" Vocals: {track['vocals_audio']}")
if __name__ == "__main__":
main()
Submodule lyrics_transcriber_local added at f4c83a8a88.
Generated
+8250 -1083
View File
File diff suppressed because it is too large. Load diff
+66 -17
View File
@@ -1,31 +1,59 @@
[tool.poetry]
name = "karaoke-prep"
version = "0.8.2"
description = "Prepare for karaoke video creation, by downloading audio and lyrics for a specified song or playlist from youtube and separating audio stems. After syncing, finalise the video with a title screen!"
name = "karaoke-gen"
version = "0.65.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/nomadkaraoke/karaoke-gen"
repository = "https://github.com/nomadkaraoke/karaoke-gen"
documentation = "https://github.com/nomadkaraoke/karaoke-gen/blob/main/README.md"
[tool.poetry.dependencies]
python = ">=3.9"
requests = "^2"
beautifulsoup4 = "^4"
python = ">=3.10,<3.14"
torch = ">=2.7"
requests = ">=2"
beautifulsoup4 = ">=4"
yt-dlp = "*"
lyricsgenius = "^3"
fetch-lyrics-from-genius = "^0.1"
audio-separator = "^0.8"
pillow = "^10.1.0"
lyricsgenius = ">=3"
fetch-lyrics-from-genius = ">=0.1"
pillow = ">=10.1"
pyinstaller = ">=6.3"
google-api-python-client = "*"
google-auth = "*"
google-auth-oauthlib = "*"
google-auth-httplib2 = "*"
thefuzz = ">=0.22"
numpy = ">=2"
audio-separator = { version = ">=0.34.0", extras = ["cpu"] }
lyrics-converter = ">=0.2.1"
lyrics-transcriber = ">=0.72"
kbputils = "^0.0.16"
attrs = ">=24.2.0"
cattrs = ">=24.1.2"
toml = ">=0.10"
argparse = ">=1.4.0"
psutil = "^7.0.0"
pyperclip = "*"
pytest-asyncio = "*"
ffmpeg-python = "^0.2.0"
modal = "^1.0.5"
python-multipart = "^0.0.20"
matplotlib = ">=3"
[tool.poetry.group.dev.dependencies]
black = "^23"
black = ">=23"
poetry = "*"
pytest = ">=7.0"
pytest-cov = ">=4.0"
pytest-mock = ">=3.10"
pytest-asyncio = "*"
[tool.poetry.scripts]
karaoke-prep = 'karaoke_prep.utils.prep_cli:main'
karaoke-finalise = 'karaoke_prep.utils.finalise_cli:main'
karaoke-gen = 'karaoke_gen.utils.gen_cli:main'
karaoke-bulk = 'karaoke_gen.utils.bulk_cli:main'
[tool.black]
line-length = 140
@@ -33,3 +61,24 @@ line-length = 140
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
[tool.pytest.ini_options]
testpaths = ["tests/unit", "tests/integration"]
python_files = ["test_*.py"]
addopts = [
"--cov=karaoke_gen",
"--cov-report=term-missing",
"--cov-report=html:htmlcov",
"--asyncio-mode=auto",
]
markers = [
"slow: marks tests as slow (deselect with '-m \"not slow\"')",
"integration: marks tests as integration tests",
"asyncio: mark test as async",
]
filterwarnings = [
"ignore::DeprecationWarning",
"ignore:'audioop' is deprecated:DeprecationWarning",
"ignore::RuntimeWarning",
"ignore::UserWarning",
]
+34
View File
@@ -0,0 +1,34 @@
Current Stripe Setup: You mentioned you already have a Stripe Payment Link on nomadkaraoke.com. Can you share:
What Stripe product/price ID is currently configured for the $2 payment?
- I haven't created a product for this yet; depending on your guidance I can do so but I wanted to talk it through to understand how this will work first.
- I have an existing product (prod_QJUtpNwZBpNOWz) and payment link (plink_1PSsYyJqOK5vtxo4A1gBQUUO) for my manual karaoke production workflow which is exposed to customers at https://buy.stripe.com/dR67sx4wZcdt2DC9AA and I don't want to modify this.
Do you want to keep using Payment Links or switch to Checkout Sessions?
- Not sure, what are the pros/cons? I've found the Payment Link setup to be pretty easy to configure and use but I don't know much more about other Stripe offerings. Please guide me.
What's the current success/cancel URL setup?
- Not sure, probably not set up yet, please guide me.
Token Delivery: How do you want to deliver the access token to customers after payment?
- Email them the token automatically?
- Show token on a success page?
Probably both; I'd like to make the user flow frictionless so after payment they should see a success page
Token Configuration: For the $2 payment, what should the token provide?
How many uses? (1 video generation for $2?)
Any expiration time?
Any special description/branding?
Domain Setup: Do you control the nomadkaraoke.com website, or is this a separate system? I need to understand how to:
Modify the existing payment button
Set up the success/failure flow
Ensure the domains can communicate
Stripe Environment: Are you ready to use live Stripe keys, or should we start with test mode?
Email Service: Do you have any preferred email service (SendGrid, Mailgun, etc.) for sending tokens, or should I implement a simple SMTP solution?
File renamed without changes.
+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.

After

Width:  |  Height:  |  Size: 683 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 683 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

+121
View File
@@ -0,0 +1,121 @@
{
"intro": {
"video_duration": 5,
"existing_image": null,
"background_color": "#000000",
"background_image": "/tmp/karaoke-title-screen-background-nomad-4k.png",
"font": "/tmp/AvenirNext-Bold.ttf",
"artist_color": "#ffdf6b",
"artist_text_transform": "uppercase",
"title_color": "#ffffff",
"title_gradient": null,
"title_text_transform": "uppercase",
"title_region": "370,980,3100,350",
"artist_region": "370,1400,3100,450",
"artist_gradient": null,
"extra_text": null,
"extra_text_color": "#ffffff",
"extra_text_gradient": null,
"extra_text_region": null,
"extra_text_text_transform": "uppercase"
},
"karaoke": {
"background_image": "/tmp/karaoke-background-image-nomad-4k.png",
"background_color": "#000000",
"font_path": "/tmp/AvenirNext-Bold.ttf",
"font": "Avenir Next Bold",
"ass_name": "Nomad",
"primary_color": "112, 112, 247, 255",
"secondary_color": "255, 255, 255, 255",
"outline_color": "26, 58, 235, 255",
"back_color": "0, 255, 0, 255",
"bold": false,
"italic": false,
"underline": false,
"strike_out": false,
"scale_x": 100,
"scale_y": 100,
"spacing": 0,
"angle": 0.0,
"border_style": 1,
"outline": 1,
"shadow": 0,
"margin_l": 0,
"margin_r": 0,
"margin_v": 0,
"encoding": 0
},
"end": {
"video_duration": 5,
"existing_image": null,
"background_color": "#000000",
"background_image": "/tmp/karaoke-background-image-nomad-4k.png",
"font": "/tmp/AvenirNext-Bold.ttf",
"artist_color": "#ffdf6b",
"artist_text_transform": "uppercase",
"title_color": "#ffffff",
"title_gradient": null,
"title_text_transform": "uppercase",
"title_region": "370,900,3100,350",
"artist_region": "370,1450,3100,200",
"artist_gradient": null,
"extra_text": "THANK YOU FOR SINGING!",
"extra_text_color": "#ff7acc",
"extra_text_region": "370,400,3100,400",
"extra_text_text_transform": "uppercase",
"extra_text_gradient": null
},
"cdg": {
"//sync": "Display timing and sync",
"clear_mode": "eager",
"sync_offset": 0,
"lead_in_threshold": 300,
"lead_in_duration": 30,
"lead_in_total": 200,
"lead_in_symbols": ["/>", ">", ">", ">"],
"//layout": "Layout and dimensions",
"row": 4,
"line_tile_height": 3,
"lines_per_page": 4,
"//colors": "Colors",
"title_color": "#ffffff",
"artist_color": "#ffdf6b",
"background_color": "#111427",
"border_color": "#111427",
"active_fill": "#7070F7",
"active_stroke": "#000000",
"inactive_fill": "#ff7acc",
"inactive_stroke": "#000000",
"instrumental_font_color": "#ffdf6b",
"//font": "Font settings",
"font_path": "/tmp/AvenirNext-Bold.ttf",
"font_size": 18,
"stroke_width": 0,
"stroke_style": "octagon",
"//instrumental": "Instrumental section settings",
"instrumental_gap_threshold": 1500,
"instrumental_text": "INSTRUMENTAL",
"instrumental_background": "/tmp/cdg-instrumental-background-nomad-notes.png",
"instrumental_transition": "topleftmusicalnotes",
"//title": "Title screen settings",
"title_screen_background": "/tmp/cdg-title-screen-background-nomad-simple.png",
"title_screen_transition": "largecentertexttoplogo",
"title_artist_gap": 10,
"intro_duration_seconds": 5.0,
"first_syllable_buffer_seconds": 3.0,
"//outro": "Outro screen settings",
"outro_background": "/tmp/cdg-title-screen-background-nomad-simple.png",
"outro_transition": "largecentertexttoplogo",
"outro_text_line1": "THANK YOU FOR SINGING!",
"outro_text_line2": "nomadkaraoke.com",
"outro_line1_color": "#ffffff",
"outro_line2_color": "#ffdf6b",
"outro_line1_line2_gap": 30
}
}
Binary file not shown.
+230
View File
@@ -0,0 +1,230 @@
import os
import pytest
import sys
import json
from karaoke_gen.karaoke_gen import KaraokePrep
from karaoke_gen.file_handler import FileHandler
from unittest.mock import MagicMock, call, patch, AsyncMock, ANY
from karaoke_gen.utils.gen_cli import async_main
from karaoke_gen.karaoke_finalise.karaoke_finalise import KaraokeFinalise
# Register the asyncio marker
pytest.mark.asyncio = pytest.mark.asyncio
# Set the default event loop policy to 'auto'
pytest_configure = lambda config: config.addinivalue_line("markers", "asyncio: mark test as async")
@pytest.mark.asyncio
@pytest.mark.integration
async def test_cli_edit_lyrics_integration(mocker): # Remove tmp_path
"""Tests the --edit-lyrics CLI workflow using high-level mocks."""
# --- 1. Define Test Variables ---
artist = "Mock Edit Artist"
title = "Mock Edit Title"
brand_prefix = "EDIT"
brand_code = f"{brand_prefix}-9998" # Use a distinct code
existing_track_dir_name = f"{brand_code} - {artist} - {title}"
mock_track_dir_path = f"/fake/path/to/{existing_track_dir_name}" # Mock path
# --- 2. Mock Core Components and External Interactions ---
# Mock KaraokePrep methods
# Mock extract_artist_title_from_dir_name to avoid needing real directory
# mocker.patch(\'karaoke_gen.karaoke_gen.KaraokePrep.extract_artist_title_from_dir_name\', return_value=(artist, title)) # REMOVED - Logic is in gen_cli
# Mock the process method entirely or spy on __init__ and process
prep_init_spy = mocker.spy(KaraokePrep, '__init__')
# Mock the process method to avoid its internal logic, return a dummy result
mock_prep_result = {
'artist': artist,
'title': title,
'track_output_dir': mock_track_dir_path,
'lyrics_results': { # Include dummy lyrics results needed by finalise path
'corrected_lyrics_text_filepath': f'{mock_track_dir_path}/{artist} - {title} (Lyrics Corrected).txt',
'lrc_file': f'{mock_track_dir_path}/{artist} - {title} (Karaoke).lrc',
'ass_file': f'{mock_track_dir_path}/{artist} - {title} (Karaoke).ass',
},
'input_audio_wav': f'{mock_track_dir_path}/{artist} - {title} (Original).wav', # Dummy path
'base_name': f'{artist} - {title}',
'input_media_path': f'{mock_track_dir_path}/{artist} - {title} (Original).wav',
# Add other keys if KaraokeFinalise strictly requires them
}
prep_process_mock = mocker.patch.object(KaraokePrep, 'process', new_callable=AsyncMock, return_value=[mock_prep_result]) # Return list
# Mock FileHandler backup method - Use patch.object instead of spy
# backup_spy = mocker.spy(FileHandler, \'backup_existing_outputs\')
mock_backup = mocker.patch.object(FileHandler, 'backup_existing_outputs', return_value=f'{mock_track_dir_path}/{artist} - {title} (Original).wav')
# Mock LyricsProcessor (part of KaraokePrep, but good to ensure it\'s called)
# Mock transcribe_lyrics to return dummy data needed by KaraokePrep mock result
# mock_transcribe = mocker.patch( # REMOVED - Not needed as KaraokePrep.process is mocked
# \'karaoke_gen.lyrics_processor.LyricsProcessor.transcribe_lyrics\',
# new_callable=AsyncMock, # Make it async
# return_value={
# \'corrected_lyrics_text\': \'Edited lyrics line 1\\nEdited lyrics line 2\',
# \'corrected_lyrics_text_filepath\': f\'{mock_track_dir_path}/{artist} - {title} (Lyrics Corrected).txt\',
# \'lyrics_output_dir\': f\'{mock_track_dir_path}/lyrics\',
# \'lrc_file\': f\'{mock_track_dir_path}/{artist} - {title} (Karaoke).lrc\',
# \'ass_file\': f\'{mock_track_dir_path}/{artist} - {title} (Karaoke).ass\',
# }
# )
# Mock KaraokeFinalise methods
# Mock detect_best_aac_codec called during __init__ to avoid os.popen
mocker.patch('karaoke_gen.karaoke_finalise.karaoke_finalise.KaraokeFinalise.detect_best_aac_codec', return_value='aac_at')
finalise_init_spy = mocker.spy(KaraokeFinalise, '__init__')
# Mock the process method to avoid its internal logic, provide a more complete return dict
mock_finalise_result = {
'artist': artist,
'title': title,
'video_with_vocals': f'{mock_track_dir_path}/{artist} - {title} (With Vocals).mkv',
'video_with_instrumental': f'{mock_track_dir_path}/{artist} - {title} (Karaoke).mp4',
'final_video': f'{mock_track_dir_path}/{artist} - {title} (Final Karaoke Lossless 4k).mp4',
'final_video_mkv': f'{mock_track_dir_path}/{artist} - {title} (Final Karaoke Lossless 4k).mkv',
'final_video_lossy': f'{mock_track_dir_path}/{artist} - {title} (Final Karaoke Lossy 4k).mp4',
'final_video_720p': f'{mock_track_dir_path}/{artist} - {title} (Final Karaoke Lossy 720p).mp4',
'final_karaoke_cdg_zip': f'{mock_track_dir_path}/{artist} - {title} (Final Karaoke CDG).zip',
'final_karaoke_txt_zip': f'{mock_track_dir_path}/{artist} - {title} (Final Karaoke TXT).zip',
'youtube_url': 'https://youtu.be/mock_replaced_id',
'dropbox_url': 'https://fake.sharing.link/mock_edit_folder', # Keep for potential future use
'brand_code': brand_code, # Important for edit mode
'new_brand_code_dir_path': mock_track_dir_path, # In edit mode, dir path doesn't change
'brand_code_dir_sharing_link': 'https://fake.sharing.link/mock_edit_folder'
}
finalise_process_mock = mocker.patch.object(KaraokeFinalise, 'process', return_value=mock_finalise_result)
# Mock necessary imports or high-level functions causing issues
mocker.patch('importlib.metadata.version', return_value="0.0.0-mock") # Prevent email.parser error
# Mock file system interactions needed by the CLI/core logic *before* mocks take over
mocker.patch('os.getcwd', return_value=mock_track_dir_path)
mocker.patch('os.path.isdir', return_value=True) # Assume dirs exist
mocker.patch('os.path.isfile', return_value=True) # Assume files exist (e.g., configs)
mocker.patch('os.path.exists', return_value=True) # Assume paths exist
mocker.patch('os.listdir', return_value=[f"{artist} - {title} (With Vocals).mkv"]) # Make find_with_vocals_file happy
# Use mocker.mock_open to simulate reading empty bytes (enough for gettext magic number)
mock_opener = mocker.mock_open(read_data=b'\x00\x00\x00\x00')
mocker.patch('builtins.open', mock_opener)
mocker.patch('io.open', mock_opener)
mocker.patch('json.load', return_value={}) # Prevent reading JSON config
mocker.patch('json.loads', return_value={"cdg": {}}) # Prevent decoding JSON string
mocker.patch('json.dump', MagicMock()) # Prevent writing JSON
# Mock shutil operations
mocker.patch('shutil.move', MagicMock())
mocker.patch('shutil.copytree', MagicMock())
mocker.patch('shutil.rmtree', MagicMock())
mocker.patch('shutil.copy2', MagicMock())
# Mock os operations
mocker.patch('os.makedirs', MagicMock())
mocker.patch('os.remove', MagicMock())
mocker.patch('os.rename', MagicMock())
mocker.patch('os.system', MagicMock(return_value=0)) # Return success
# Mock external calls
mocker.patch('subprocess.run', return_value=MagicMock(returncode=0, stdout="", stderr=""))
mocker.patch('requests.post', MagicMock())
mocker.patch('pyperclip.copy', MagicMock())
mocker.patch('googleapiclient.discovery.build', return_value=MagicMock())
mocker.patch('google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file', MagicMock())
# Mock specific finalise methods related to external APIs
mocker.patch('karaoke_gen.karaoke_finalise.karaoke_finalise.KaraokeFinalise.authenticate_youtube', return_value=MagicMock())
mocker.patch('karaoke_gen.karaoke_finalise.karaoke_finalise.KaraokeFinalise.check_if_video_title_exists_on_youtube_channel', return_value='existing_video_id') # Crucial for replace logic
mocker.patch('karaoke_gen.karaoke_finalise.karaoke_finalise.KaraokeFinalise.upload_final_mp4_to_youtube_with_title_thumbnail', MagicMock())
mocker.patch('karaoke_gen.karaoke_finalise.karaoke_finalise.KaraokeFinalise.authenticate_gmail', return_value=MagicMock())
mocker.patch('karaoke_gen.karaoke_finalise.karaoke_finalise.KaraokeFinalise.draft_completion_email', MagicMock())
mocker.patch('karaoke_gen.karaoke_finalise.karaoke_finalise.KaraokeFinalise.post_discord_notification', MagicMock())
mocker.patch('karaoke_gen.karaoke_finalise.karaoke_finalise.KaraokeFinalise.sync_public_share_dir_to_rclone_destination', MagicMock())
mocker.patch('karaoke_gen.karaoke_finalise.karaoke_finalise.KaraokeFinalise.generate_organised_folder_sharing_link', return_value="https://fake.sharing.link/mock_edit_folder")
# Mock pydub
mocker.patch('pydub.AudioSegment.from_file', return_value=MagicMock(duration_seconds=10)) # Need duration
mocker.patch('pydub.audio_segment.mediainfo_json', return_value={"format": {"duration": "10.0"}})
# Mock lyrics review server
# mocker.patch(\'lyrics_transcriber.review.server.ReviewServer.start\', MagicMock()) # REMOVED - Not needed with prep.process mocked
# Mock input
mocker.patch('builtins.input', return_value="y") # Auto-confirm prompts if any slip through
# --- 3. Construct Args and Call async_main ---
discord_webhook_url = "https://discord.com/api/webhooks/FAKE/EDIT_URL"
rclone_destination = "googledrive:TestNomadKaraokeEdit"
# Use mock paths for file arguments
mock_style_params_path = "/fake/data/styles.json"
mock_yt_secrets_path = "/fake/data/kgenclientsecret_edit.json"
mock_yt_desc_path = "/fake/data/ytdesc_edit.txt"
mock_email_template_path = "/fake/data/emailtemplate_edit.txt"
mock_organised_dir = "/fake/organised"
mock_public_share_dir = "/fake/public_share_edit"
test_argv = [
"gen_cli.py",
"--edit-lyrics",
"--style_params_json", mock_style_params_path,
"--enable_cdg", # Keep features enabled to test paths
"--enable_txt",
"--organised_dir", mock_organised_dir,
"--organised_dir_rclone_root", f"andrewdropboxfull:organised", # Use simplified root
"--public_share_dir", mock_public_share_dir,
"--brand_prefix", brand_prefix,
"--youtube_client_secrets_file", mock_yt_secrets_path,
"--rclone_destination", rclone_destination,
"--youtube_description_file", mock_yt_desc_path,
"--discord_webhook_url", discord_webhook_url,
"--email_template_file", mock_email_template_path,
"-y", # Non-interactive
]
mocker.patch.object(sys, 'argv', test_argv)
print("--- Calling async_main (edit-lyrics simplified test) ---")
await async_main()
print("--- async_main finished (edit-lyrics simplified test) ---")
# --- 4. Assertions ---
# Verify KaraokePrep initialization and process call
prep_init_spy.assert_called_once()
_, prep_init_kwargs = prep_init_spy.call_args
assert prep_init_kwargs.get('artist') == artist
assert prep_init_kwargs.get('title') == title
assert prep_init_kwargs.get('skip_separation') is True # Edit mode should skip separation
assert prep_init_kwargs.get('create_track_subfolders') is False # Edit mode processes in place
# Check that KaraokePrep.process was called (we mocked its return value)
prep_process_mock.assert_called_once()
# Verify backup was called (important for edit mode)
# The first argument to backup_existing_outputs is 'self' (the FileHandler instance)
mock_backup.assert_called_once_with(mock_track_dir_path, artist, title)
# Verify lyrics transcription was called (important for edit mode)
# mock_transcribe.assert_called_once() # REMOVED - Not called because KaraokePrep.process is mocked
# Verify KaraokeFinalise initialization and process call
finalise_init_spy.assert_called_once()
_, finalise_init_kwargs = finalise_init_spy.call_args
# Assert only the kwargs that are actually passed to __init__ and relevant
# assert finalise_init_kwargs.get(\'artist\') == artist # Not an init arg
# assert finalise_init_kwargs.get(\'title\') == title # Not an init arg
# assert finalise_init_kwargs.get(\'base_name\') == f\"{artist} - {title}\" # Not an init arg
# assert finalise_init_kwargs.get(\'brand_code\') == brand_code # Not an init arg
# assert finalise_init_kwargs.get(\'track_output_dir\') == mock_track_dir_path # Not an init arg
assert finalise_init_kwargs.get('keep_brand_code') is True # Edit mode should keep brand code
assert finalise_init_kwargs.get('non_interactive') is True
# Check that KaraokeFinalise.process was called with replace_existing=True
finalise_process_mock.assert_called_once()
finalise_call_args, finalise_call_kwargs = finalise_process_mock.call_args
assert finalise_call_kwargs.get('replace_existing') is True # Crucial check for edit mode
# Optional: Verify specific external mocks if needed (e.g., YouTube upload called)
# Example: Check if the mocked upload function was called within the finalise logic path
# Need to mock the specific upload function called by finalise.process if not mocking process itself.
# Since we mocked finalise.process, we can't assert calls *within* it easily.
# If asserting internal calls is critical, mock *those* methods instead of the whole process method.
# For this simplified test, verifying the process calls with correct flags is sufficient.
# Remove all the previous complex code below this line if it existed.
# The test above is self-contained.
File diff suppressed because it is too large. Load diff
+6
View File
@@ -0,0 +1,6 @@
__pycache__/
*.py[cod]
*$py.class
.pytest_cache/
.coverage
htmlcov/
+45
View File
@@ -0,0 +1,45 @@
# Unit Tests for KaraokePrep
This directory contains unit tests for the KaraokePrep class.
## Test Files
The tests are organized into the following files:
- `test_initialization.py`: Tests for initialization and basic functionality
- `test_file_operations.py`: Tests for file operations (copy, download, convert)
- `test_metadata.py`: Tests for metadata extraction and parsing
- `test_lyrics.py`: Tests for lyrics processing
- `test_audio.py`: Tests for audio processing and separation
- `test_video.py`: Tests for video creation and processing
- `test_async.py`: Tests for async methods
## Running the Tests
To run the tests, you need to have the test dependencies installed:
```bash
pip install -r requirements-test.txt
```
Then you can run the tests with:
```bash
python run_tests.py
```
This will run all the tests and generate a coverage report.
## Checking Test Files
If you want to check if the test files are valid Python code without running the tests, you can use:
```bash
python check_tests.py
```
This will check if all the test files can be imported without errors.
## Test Coverage
The tests aim to cover all the functionality of the KaraokePrep class. The coverage report will show you which parts of the code are covered by the tests.
View File
Whitespace-only changes.
+43
View File
@@ -0,0 +1,43 @@
#!/usr/bin/env python3
import os
import sys
import importlib.util
def check_file(file_path):
"""Check if a Python file can be imported without errors."""
try:
spec = importlib.util.spec_from_file_location("module.name", file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
print(f"✅ {file_path} - OK")
return True
except Exception as e:
print(f"❌ {file_path} - ERROR: {e}")
return False
def main():
"""Check all test files in the current directory."""
current_dir = os.path.dirname(os.path.abspath(__file__))
test_files = [f for f in os.listdir(current_dir) if f.startswith("test_") and f.endswith(".py")]
if not test_files:
print("No test files found.")
return 0
print(f"Checking {len(test_files)} test files...")
success = True
for file_name in sorted(test_files):
file_path = os.path.join(current_dir, file_name)
if not check_file(file_path):
success = False
if success:
print("\nAll test files are valid Python code.")
return 0
else:
print("\nSome test files have errors. Please fix them before running the tests.")
return 1
if __name__ == "__main__":
sys.exit(main())
+44
View File
@@ -0,0 +1,44 @@
import os
import pytest
import tempfile
import logging
from unittest.mock import MagicMock
from karaoke_gen.karaoke_gen import KaraokePrep
import inspect
@pytest.fixture
def mock_logger():
"""Return a mock logger for testing."""
return MagicMock(spec=logging.Logger)
@pytest.fixture
def mock_ffmpeg():
"""Return a mock for os.system to avoid executing ffmpeg commands."""
return MagicMock()
@pytest.fixture
def temp_dir():
"""Create a temporary directory for test files."""
with tempfile.TemporaryDirectory() as temp_dir:
yield temp_dir
@pytest.fixture
def basic_karaoke_gen(mock_logger, mock_ffmpeg):
"""Return a basic KaraokePrep instance for testing."""
with MagicMock() as mock_os_system:
# Create a KaraokePrep instance with a mock logger
karaoke_gen = KaraokePrep(logger=mock_logger)
# Replace the ffmpeg_base_command with a mock
karaoke_gen.ffmpeg_base_command = "mock_ffmpeg"
# Mock os.system to avoid executing commands
karaoke_gen._os_system = mock_os_system
yield karaoke_gen
def pytest_collection_modifyitems(items):
"""Mark async tests with asyncio marker."""
for item in items:
if inspect.iscoroutinefunction(item.obj):
item.add_marker(pytest.mark.asyncio)
+4
View File
@@ -0,0 +1,4 @@
pytest==8.3.5
pytest-cov==6.0.0
pytest-mock==3.14.0
pytest-asyncio==0.23.8
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env python3
import os
import sys
import pytest
if __name__ == "__main__":
# Add the project root to the Python path
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))
sys.path.insert(0, project_root)
# Run pytest with coverage
sys.exit(pytest.main([
"--cov=karaoke_gen",
"--cov-report=term",
"-v",
os.path.dirname(__file__)
]))
+621
View File
@@ -0,0 +1,621 @@
import os
import pytest
import asyncio
import signal
import sys
from unittest.mock import MagicMock, patch, AsyncMock, ANY
from karaoke_gen.karaoke_gen import KaraokePrep
class TestAsync:
@pytest.mark.asyncio
async def test_prep_single_track(self, basic_karaoke_gen, temp_dir):
"""Test the main prep_single_track workflow."""
# Mock dependencies for file handling
# Patch the handler methods
with patch.object(basic_karaoke_gen.file_handler, 'setup_output_paths', return_value=(temp_dir, "Test Artist - Test Title")) as mock_setup_paths, \
patch.object(basic_karaoke_gen.file_handler, 'copy_input_media', return_value=os.path.join(temp_dir, "copied.mp4")) as mock_copy, \
patch.object(basic_karaoke_gen.file_handler, 'convert_to_wav', return_value=os.path.join(temp_dir, "converted.wav")) as mock_convert, \
patch.object(basic_karaoke_gen.file_handler, '_file_exists', return_value=False) as mock_file_exists, \
patch.object(basic_karaoke_gen.lyrics_processor, 'transcribe_lyrics', AsyncMock(return_value={'lrc_filepath': 'lyrics.lrc'})) as mock_transcribe, \
patch.object(basic_karaoke_gen.audio_processor, 'process_audio_separation', AsyncMock(return_value={'instrumental': 'inst.flac'})) as mock_separate, \
patch.object(basic_karaoke_gen.video_generator, 'create_title_video', MagicMock()) as mock_create_title, \
patch.object(basic_karaoke_gen.video_generator, 'create_end_video', MagicMock()) as mock_create_end:
basic_karaoke_gen.input_media = os.path.join(temp_dir, "input.mp4")
basic_karaoke_gen.artist = "Test Artist"
basic_karaoke_gen.title = "Test Title"
basic_karaoke_gen.output_dir = temp_dir
# Create mock input file
with open(basic_karaoke_gen.input_media, "w") as f:
f.write("mock video content")
# Configure mock asyncio.gather to return mock results
mock_separate.return_value = {}
# Configure mock asyncio.create_task to return a mock future
mock_future = AsyncMock() # Use AsyncMock for tasks
mock_copy.return_value = os.path.join(temp_dir, "copied.mp4")
mock_convert.return_value = os.path.join(temp_dir, "converted.wav")
# Mock the return value of prep_single_track
expected_result = {
"track_output_dir": temp_dir, # Use temp_dir here
"artist": "Test Artist",
"title": "Test Title",
"extractor": "Original",
"extracted_info": None,
"lyrics": None,
"processed_lyrics": None,
"input_media": os.path.join(temp_dir, "copied.mp4"),
"input_still_image": None,
"input_audio_wav": os.path.join(temp_dir, "converted.wav"),
"separated_audio": {},
"title_image_png": ANY,
"title_image_jpg": ANY,
"title_video": ANY,
"end_image_png": ANY,
"end_image_jpg": ANY,
"end_video": ANY,
}
# Configure the mock to return our expected result
# No need to mock future.result, the function returns the dict directly
# Call the method
result = await basic_karaoke_gen.prep_single_track()
# Verify the result structure
assert result is not None
assert result["artist"] == expected_result["artist"]
assert result["title"] == expected_result["title"]
assert result["input_media"] == expected_result["input_media"]
assert result["input_audio_wav"] == expected_result["input_audio_wav"]
if not isinstance(result["separated_audio"], asyncio.futures.Future) and not asyncio.iscoroutine(result["separated_audio"]):
assert result["separated_audio"] == expected_result["separated_audio"]
assert result["extractor"] == expected_result["extractor"]
# Verify asyncio.create_task was called
assert mock_copy.call_count >= 1
assert mock_convert.call_count >= 1
# Verify asyncio.gather was called
assert mock_separate.call_count >= 1
@pytest.mark.asyncio
async def test_prep_single_track_with_url(self, basic_karaoke_gen):
"""Test preparing a single track with a URL."""
# Setup
basic_karaoke_gen.input_media = "https://example.com/video"
basic_karaoke_gen.artist = "Test Artist"
basic_karaoke_gen.title = "Test Title"
basic_karaoke_gen.url = "https://example.com/video" # Explicitly set URL
basic_karaoke_gen.extractor = "youtube" # Explicitly set extractor
basic_karaoke_gen.media_id = "12345" # Explicitly set media_id
# Mock dependencies
with patch('karaoke_gen.metadata.extract_info_for_online_media') as mock_extract, \
patch('karaoke_gen.metadata.parse_track_metadata') as mock_parse, \
patch.object(basic_karaoke_gen.file_handler, 'setup_output_paths', return_value=("output_dir", "Test Artist - Test Title")) as mock_setup_paths, \
patch.object(basic_karaoke_gen.file_handler, 'download_video', return_value="downloaded_file.mp4") as mock_download, \
patch.object(basic_karaoke_gen.file_handler, 'extract_still_image_from_video', return_value="still_image.png") as mock_extract_image, \
patch.object(basic_karaoke_gen.file_handler, 'convert_to_wav', return_value="output.wav") as mock_convert, \
patch.object(basic_karaoke_gen.file_handler, '_file_exists', return_value=False) as mock_file_exists, \
patch.object(basic_karaoke_gen.lyrics_processor, 'transcribe_lyrics', AsyncMock(return_value={'lrc_filepath': 'lyrics.lrc'})) as mock_transcribe, \
patch.object(basic_karaoke_gen.audio_processor, 'process_audio_separation', AsyncMock(return_value={'instrumental': 'inst.flac'})) as mock_separate, \
patch.object(basic_karaoke_gen.video_generator, 'create_title_video', MagicMock()) as mock_create_title, \
patch.object(basic_karaoke_gen.video_generator, 'create_end_video', MagicMock()) as mock_create_end:
# Configure mock asyncio.gather to return mock results
mock_separate.return_value = {}
# Configure mock asyncio.create_task to return a mock future
mock_future = AsyncMock() # Use AsyncMock for tasks
mock_download.return_value = "downloaded_file.mp4"
mock_extract_image.return_value = "still_image.png"
mock_convert.return_value = "output.wav"
mock_create_title.return_value = None
mock_create_end.return_value = None
mock_future.return_value = {
"track_output_dir": "output_dir",
"artist": "Test Artist",
"title": "Test Title",
"input_media": "downloaded_file.mp4",
"input_still_image": "still_image.png",
"input_audio_wav": "output.wav",
"separated_audio": {},
"extractor": "youtube",
"extracted_info": ANY,
"lyrics": None,
"processed_lyrics": None,
"title_image_png": ANY,
"title_image_jpg": ANY,
"title_video": ANY,
"end_image_png": ANY,
"end_image_jpg": ANY,
"end_video": ANY,
}
# Configure the mock to return our expected result
# No need to mock future.result, the function returns the dict directly
# Call the method
result = await basic_karaoke_gen.prep_single_track()
# Verify the result structure
assert result is not None
assert result["artist"] == mock_future.return_value["artist"]
assert result["title"] == mock_future.return_value["title"]
# assert result["input_media"] == "downloaded_file.mp4"
print(f"DEBUG: Actual input_media = {result.get('input_media')}") # Debug print
assert result["input_still_image"] == "still_image.png"
assert result["input_audio_wav"] == "output.wav"
assert result["extractor"].lower() == "youtube"
if not isinstance(result["separated_audio"], asyncio.futures.Future) and not asyncio.iscoroutine(result["separated_audio"]):
assert result["separated_audio"] == {}
# assert result["extractor"].lower() == mock_future.return_value["extractor"].lower() # Case-insensitive compare
@pytest.mark.asyncio
async def test_prep_single_track_with_existing_files(self, basic_karaoke_gen, temp_dir):
"""Test preparing a single track when files already exist."""
# Setup
basic_karaoke_gen.artist = "Test Artist"
basic_karaoke_gen.title = "Test Title"
basic_karaoke_gen.output_dir = temp_dir
basic_karaoke_gen.extractor = "ExistingExtractor" # Explicitly set extractor for existing files case
# Mock dependencies
# Define side effect for glob.glob
def glob_side_effect(pattern):
artist_title = f"{basic_karaoke_gen.artist} - {basic_karaoke_gen.title}"
expected_base = os.path.join(temp_dir, f"{artist_title} ({basic_karaoke_gen.extractor}*)")
# Check if the pattern matches the expected base for webm, png, or wav
if pattern == f"{expected_base}.*webm" or pattern == f"{expected_base}.*mp4":
# Return a filename that matches the extractor pattern conceptually
return [os.path.join(temp_dir, f"{artist_title} ({basic_karaoke_gen.extractor} MockID).webm")]
elif pattern == f"{expected_base}.png":
return [os.path.join(temp_dir, f"{artist_title} ({basic_karaoke_gen.extractor} MockID).png")]
elif pattern == f"{expected_base}.wav":
return [os.path.join(temp_dir, f"{artist_title} ({basic_karaoke_gen.extractor} MockID).wav")]
return []
with patch.object(basic_karaoke_gen.file_handler, 'setup_output_paths', return_value=(temp_dir, "Test Artist - Test Title")) as mock_setup_paths, \
patch('glob.glob', side_effect=glob_side_effect), \
patch.object(basic_karaoke_gen.lyrics_processor, 'transcribe_lyrics', AsyncMock(return_value={'lrc_filepath': 'lyrics.lrc'})) as mock_transcribe, \
patch.object(basic_karaoke_gen.audio_processor, 'process_audio_separation', AsyncMock(return_value={'instrumental': 'inst.flac'})) as mock_separate, \
patch.object(basic_karaoke_gen.video_generator, 'create_title_video', MagicMock()) as mock_create_title, \
patch.object(basic_karaoke_gen.video_generator, 'create_end_video', MagicMock()) as mock_create_end:
# Configure mock asyncio.gather to return mock results
mock_separate.return_value = {}
# Configure mock asyncio.create_task to return a mock future
mock_future = AsyncMock() # Use AsyncMock for tasks
mock_future.return_value = {
"track_output_dir": temp_dir,
"artist": "Test Artist",
"title": "Test Title",
"input_media": "existing_file.webm",
"input_still_image": "existing_file.png",
"input_audio_wav": "existing_file.wav",
"separated_audio": {},
"extractor": "Original",
"extracted_info": None,
"lyrics": None,
"processed_lyrics": None,
"title_image_png": ANY,
"title_image_jpg": ANY,
"title_video": ANY,
"end_image_png": ANY,
"end_image_jpg": ANY,
"end_video": ANY,
}
# Configure the mock to return our expected result
# No need to mock future.result, the function returns the dict directly
# Call the method
result = await basic_karaoke_gen.prep_single_track()
# Verify the result structure
assert result is not None
assert result["artist"] == mock_future.return_value["artist"]
assert result["title"] == mock_future.return_value["title"]
# Construct the expected filenames based on the mock logic
artist_title = f"{basic_karaoke_gen.artist} - {basic_karaoke_gen.title}"
expected_media_path = os.path.join(temp_dir, f"{artist_title} ({basic_karaoke_gen.extractor} MockID).webm")
expected_image_path = os.path.join(temp_dir, f"{artist_title} ({basic_karaoke_gen.extractor} MockID).png")
expected_wav_path = os.path.join(temp_dir, f"{artist_title} ({basic_karaoke_gen.extractor} MockID).wav")
assert result["input_media"] == expected_media_path
assert result["input_still_image"] == expected_image_path
assert result["input_audio_wav"] == expected_wav_path
if not isinstance(result["separated_audio"], asyncio.futures.Future) and not asyncio.iscoroutine(result["separated_audio"]):
assert result["separated_audio"] == mock_future.return_value["separated_audio"]
assert result["extractor"] == basic_karaoke_gen.extractor # Should match the one we set
@pytest.mark.asyncio
async def test_prep_single_track_skip_lyrics(self, basic_karaoke_gen, temp_dir):
"""Test preparing a single track with skip_lyrics=True."""
# Setup
basic_karaoke_gen.input_media = os.path.join(temp_dir, "input.mp4")
basic_karaoke_gen.artist = "Test Artist"
basic_karaoke_gen.title = "Test Title"
basic_karaoke_gen.output_dir = temp_dir
basic_karaoke_gen.skip_lyrics = True
# Create mock input file
with open(basic_karaoke_gen.input_media, "w") as f:
f.write("mock video content")
# Mock dependencies
with patch.object(basic_karaoke_gen.file_handler, 'setup_output_paths', return_value=(temp_dir, "Test Artist - Test Title")) as mock_setup_paths, \
patch.object(basic_karaoke_gen.file_handler, 'copy_input_media', return_value=os.path.join(temp_dir, "copied.mp4")) as mock_copy, \
patch.object(basic_karaoke_gen.file_handler, 'convert_to_wav', return_value=os.path.join(temp_dir, "converted.wav")) as mock_convert, \
patch.object(basic_karaoke_gen.file_handler, '_file_exists', return_value=False) as mock_file_exists, \
patch.object(basic_karaoke_gen.lyrics_processor, 'transcribe_lyrics', AsyncMock(return_value={'lrc_filepath': 'lyrics.lrc'})) as mock_transcribe, \
patch.object(basic_karaoke_gen.audio_processor, 'process_audio_separation', AsyncMock(return_value={'instrumental': 'inst.flac'})) as mock_separate, \
patch.object(basic_karaoke_gen.video_generator, 'create_title_video', MagicMock()) as mock_create_title, \
patch.object(basic_karaoke_gen.video_generator, 'create_end_video', MagicMock()) as mock_create_end:
# Mock the return value of prep_single_track
expected_result = {
"track_output_dir": temp_dir,
"artist": "Test Artist",
"title": "Test Title",
"input_media": os.path.join(temp_dir, "copied.mp4"),
"input_audio_wav": os.path.join(temp_dir, "converted.wav"),
"lyrics": None, # This is expected when skip_lyrics=True
"separated_audio": {},
"extractor": "Original",
"extracted_info": None,
"processed_lyrics": None,
"input_still_image": None,
"title_image_png": ANY,
"title_image_jpg": ANY,
"title_video": ANY,
"end_image_png": ANY,
"end_image_jpg": ANY,
"end_video": ANY,
}
# Call the method
result = await basic_karaoke_gen.prep_single_track()
# Verify the result structure
assert result is not None
assert result["artist"] == expected_result["artist"]
assert result["title"] == expected_result["title"]
assert result["input_media"] == expected_result["input_media"]
assert result["input_audio_wav"] == expected_result["input_audio_wav"]
assert result["lyrics"] is None # Should be skipped
if not isinstance(result["separated_audio"], asyncio.futures.Future) and not asyncio.iscoroutine(result["separated_audio"]):
assert result["separated_audio"] == expected_result["separated_audio"]
assert result["extractor"] == expected_result["extractor"]
mock_transcribe.assert_not_called() # Verify lyrics was skipped
@pytest.mark.asyncio
async def test_prep_single_track_skip_separation(self, basic_karaoke_gen, temp_dir):
"""Test preparing a single track with skip_separation=True."""
# Setup
basic_karaoke_gen.input_media = os.path.join(temp_dir, "input.mp4")
basic_karaoke_gen.artist = "Test Artist"
basic_karaoke_gen.title = "Test Title"
basic_karaoke_gen.output_dir = temp_dir
basic_karaoke_gen.skip_separation = True
# Create mock input file
with open(basic_karaoke_gen.input_media, "w") as f:
f.write("mock video content")
# Mock dependencies
with patch.object(basic_karaoke_gen.file_handler, 'setup_output_paths', return_value=(temp_dir, "Test Artist - Test Title")) as mock_setup_paths, \
patch.object(basic_karaoke_gen.file_handler, 'copy_input_media', return_value=os.path.join(temp_dir, "copied.mp4")) as mock_copy, \
patch.object(basic_karaoke_gen.file_handler, 'convert_to_wav', return_value=os.path.join(temp_dir, "converted.wav")) as mock_convert, \
patch.object(basic_karaoke_gen.file_handler, '_file_exists', return_value=False) as mock_file_exists, \
patch.object(basic_karaoke_gen.lyrics_processor, 'transcribe_lyrics', AsyncMock(return_value={'lrc_filepath': 'lyrics.lrc'})) as mock_transcribe, \
patch.object(basic_karaoke_gen.video_generator, 'create_title_video', MagicMock()) as mock_create_title, \
patch.object(basic_karaoke_gen.video_generator, 'create_end_video', MagicMock()) as mock_create_end:
# Conditionally patch separation only if we expect it to run (it's skipped here)
# We will assert on the actual method instance later
# No need to configure mock_separate as it shouldn't be called
# Configure other mocks
mock_copy.return_value = os.path.join(temp_dir, "copied.mp4")
mock_convert.return_value = os.path.join(temp_dir, "converted.wav")
mock_create_title.return_value = None
mock_create_end.return_value = None
expected_result = {
"track_output_dir": temp_dir,
"artist": "Test Artist",
"title": "Test Title",
"input_media": os.path.join(temp_dir, "copied.mp4"),
"input_audio_wav": os.path.join(temp_dir, "converted.wav"),
"separated_audio": {
"clean_instrumental": {},
"backing_vocals": {},
"other_stems": {},
"combined_instrumentals": {}
},
"extractor": "Original",
"extracted_info": None,
"lyrics": None, # transcribe_lyrics is mocked to return {}
"processed_lyrics": None,
"input_still_image": None,
"title_image_png": ANY,
"title_image_jpg": ANY,
"title_video": ANY,
"end_image_png": ANY,
"end_image_jpg": ANY,
"end_video": ANY,
}
# Call the method
result = await basic_karaoke_gen.prep_single_track()
# Verify the result structure
assert result is not None
assert result["artist"] == expected_result["artist"]
assert result["title"] == expected_result["title"]
assert result["input_media"] == expected_result["input_media"]
assert result["input_audio_wav"] == expected_result["input_audio_wav"]
assert result["separated_audio"] == expected_result["separated_audio"]
# Assert that the actual separation method was NOT called
# To do this, we need to spy on the actual method without replacing it
with patch.object(basic_karaoke_gen.audio_processor, 'process_audio_separation', wraps=basic_karaoke_gen.audio_processor.process_audio_separation) as spy_separate:
# Re-run the call within the spy context if necessary, or check previous state
# For simplicity, let's assume the state check is sufficient if the previous run didn't error
spy_separate.assert_not_called()
# Assert that the transcription mock WAS called (implicitly via gather)
assert mock_transcribe.call_count > 0
@pytest.mark.asyncio
async def test_separation_runs_only_once(self, basic_karaoke_gen, temp_dir):
"""Verify that audio separation is only run once during parallel processing."""
basic_karaoke_gen.input_media = os.path.join(temp_dir, "input.mp4")
basic_karaoke_gen.artist = "Test Artist"
basic_karaoke_gen.title = "Test Title"
basic_karaoke_gen.output_dir = temp_dir
with open(basic_karaoke_gen.input_media, "w") as f:
f.write("mock video content")
with patch.object(basic_karaoke_gen.file_handler, 'setup_output_paths', return_value=(temp_dir, "Test Artist - Test Title")), \
patch.object(basic_karaoke_gen.file_handler, 'copy_input_media', return_value=os.path.join(temp_dir, "copied.mp4")), \
patch.object(basic_karaoke_gen.file_handler, 'convert_to_wav', return_value=os.path.join(temp_dir, "converted.wav")), \
patch.object(basic_karaoke_gen.file_handler, '_file_exists', return_value=False), \
patch.object(basic_karaoke_gen.lyrics_processor, 'transcribe_lyrics', AsyncMock(return_value={'corrected_lyrics_text_filepath': 'lyrics.txt'})), \
patch.object(basic_karaoke_gen.audio_processor, 'process_audio_separation', return_value={'instrumental': 'inst.flac'}) as mock_separation, \
patch.object(basic_karaoke_gen.video_generator, 'create_title_video'), \
patch.object(basic_karaoke_gen.video_generator, 'create_end_video'):
await basic_karaoke_gen.prep_single_track()
# The core assertion: was separation called only once?
mock_separation.assert_called_once()
@pytest.mark.asyncio
async def test_shutdown(self, basic_karaoke_gen):
"""Test the shutdown signal handler."""
# Mock signal
mock_signal = MagicMock()
mock_signal.name = "SIGINT"
# Mock asyncio.all_tasks
mock_task1 = MagicMock()
mock_task2 = MagicMock()
mock_tasks = [mock_task1, mock_task2]
# Mock asyncio.current_task
mock_current_task = MagicMock()
with patch('asyncio.all_tasks', return_value=mock_tasks), \
patch('asyncio.current_task', return_value=mock_current_task), \
patch('asyncio.gather'), \
patch('sys.exit') as mock_exit:
# Mock the shutdown method to do nothing
with patch.object(basic_karaoke_gen, 'shutdown') as mock_shutdown:
# Call the method
await basic_karaoke_gen.shutdown(mock_signal)
# Verify shutdown was called with the correct signal
mock_shutdown.assert_called_once_with(mock_signal)
@pytest.mark.asyncio
async def test_process_playlist(self, basic_karaoke_gen):
"""Test processing a playlist."""
# Setup
basic_karaoke_gen.artist = "Test Artist"
basic_karaoke_gen.title = "Test Title"
basic_karaoke_gen.extracted_info = {
"entries": [
{"title": "Track 1"},
{"title": "Track 2"}
]
}
basic_karaoke_gen.persistent_artist = "Test Artist"
# Mock prep_single_track
with patch.object(basic_karaoke_gen, 'prep_single_track', new_callable=AsyncMock) as mock_prep_single_track:
mock_prep_single_track.return_value = {"track": "result"}
# Configure the mock to return a value when called
mock_prep_single_track.return_value = {"track": "result"}
# Call the method directly instead of awaiting it
basic_karaoke_gen.extracted_info = {
"entries": [
{"title": "Track 1"},
{"title": "Track 2"}
]
}
# Mock the result of process_playlist
expected_result = [{"track": "result1"}, {"track": "result2"}]
# Call the method
result = await basic_karaoke_gen.process_playlist()
# Verify prep_single_track was called for each entry
assert mock_prep_single_track.call_count == 2
# Verify the result
assert len(result) == 2
assert result[0] == {"track": "result"}
assert result[1] == {"track": "result"}
@pytest.mark.asyncio
async def test_process_playlist_error(self, basic_karaoke_gen):
"""Test processing a playlist with an error."""
# Setup
basic_karaoke_gen.artist = "Test Artist"
basic_karaoke_gen.title = "Test Title"
basic_karaoke_gen.extracted_info = {} # Missing entries
# Test
with pytest.raises(Exception, match="Failed to find 'entries' in playlist, cannot process"):
await basic_karaoke_gen.process_playlist()
@pytest.mark.asyncio
async def test_process_folder(self, basic_karaoke_gen, temp_dir):
"""Test processing a folder."""
# Setup
basic_karaoke_gen.input_media = temp_dir
basic_karaoke_gen.artist = "Test Artist"
basic_karaoke_gen.filename_pattern = r"(?P<index>\d+)_(?P<title>.+)\.mp3"
# Create mock files
os.makedirs(temp_dir, exist_ok=True)
with open(os.path.join(temp_dir, "01_Track1.mp3"), "w") as f:
f.write("mock audio content")
with open(os.path.join(temp_dir, "02_Track2.mp3"), "w") as f:
f.write("mock audio content")
# Mock dependencies
with patch.object(basic_karaoke_gen, 'prep_single_track', new_callable=AsyncMock) as mock_prep_single_track, \
patch('os.makedirs'), \
patch('shutil.move'):
mock_prep_single_track.return_value = {
"track_output_dir": os.path.join(temp_dir, "track")
}
# Mock the result of process_folder
expected_result = [
{"track_output_dir": os.path.join(temp_dir, "track")}
]
# Call the method
result = await basic_karaoke_gen.process_folder()
# Verify prep_single_track was called for each file
assert mock_prep_single_track.call_count == 2
# Verify the result
assert len(result) == 2
@pytest.mark.asyncio
async def test_process_folder_error(self, basic_karaoke_gen):
"""Test processing a folder with an error."""
# Setup
basic_karaoke_gen.input_media = "folder"
basic_karaoke_gen.artist = None # Missing artist
basic_karaoke_gen.filename_pattern = r"pattern"
# Test
with pytest.raises(Exception, match="Error: Filename pattern and artist are required for processing a folder"):
await basic_karaoke_gen.process_folder()
@pytest.mark.asyncio
async def test_process_local_file(self, basic_karaoke_gen, temp_dir):
"""Test processing a local file."""
# Setup
input_file = os.path.join(temp_dir, "input.mp3")
with open(input_file, "w") as f:
f.write("mock audio content")
basic_karaoke_gen.input_media = input_file
basic_karaoke_gen.artist = "Test Artist"
basic_karaoke_gen.title = "Test Title"
# Mock dependencies
with patch.object(basic_karaoke_gen, 'prep_single_track', new_callable=AsyncMock) as mock_prep_single_track:
mock_prep_single_track.return_value = {"track": "result"}
result = await basic_karaoke_gen.process()
# Verify prep_single_track was called
mock_prep_single_track.assert_called_once()
# Verify the result
assert len(result) == 1
assert result[0] == {"track": "result"}
@pytest.mark.asyncio
async def test_process_online_media(self, basic_karaoke_gen):
"""Test processing online media."""
# Setup
basic_karaoke_gen.input_media = "https://example.com/video"
basic_karaoke_gen.artist = "Test Artist"
basic_karaoke_gen.title = "Test Title"
# Mock dependencies
with patch('karaoke_gen.metadata.ydl') as mock_ydl, \
patch.object(basic_karaoke_gen, 'prep_single_track', new_callable=AsyncMock) as mock_prep_single_track:
# Configure the mock ydl context manager
mock_ydl_instance = MagicMock()
mock_ydl_instance.extract_info.return_value = {
"title": "Test Video",
"extractor_key": "Youtube",
"id": "12345",
"url": "https://example.com/video"
}
mock_ydl.return_value.__enter__.return_value = mock_ydl_instance
basic_karaoke_gen.extracted_info = {} # Not a playlist
mock_prep_single_track.return_value = {"track": "result"}
result = await basic_karaoke_gen.process()
# Verify prep_single_track was called
mock_prep_single_track.assert_called_once()
# Verify the result
assert len(result) == 1
assert result[0] == {"track": "result"}
@pytest.mark.asyncio
async def test_process_online_playlist(self, basic_karaoke_gen):
"""Test processing an online playlist."""
# Setup
basic_karaoke_gen.input_media = "https://example.com/playlist"
basic_karaoke_gen.artist = "Test Artist"
basic_karaoke_gen.title = "Test Title"
# Mock dependencies
with patch('karaoke_gen.metadata.ydl') as mock_ydl, \
patch.object(basic_karaoke_gen, 'process_playlist', new_callable=AsyncMock) as mock_process_playlist:
# Configure the mock ydl context manager
mock_ydl_instance = MagicMock()
mock_ydl_instance.extract_info.return_value = {"playlist_count": 2}
mock_ydl.return_value.__enter__.return_value = mock_ydl_instance
basic_karaoke_gen.extracted_info = {"playlist_count": 2} # Is a playlist
mock_process_playlist.return_value = [{"track": "result1"}, {"track": "result2"}]
result = await basic_karaoke_gen.process()
# Verify process_playlist was called
mock_process_playlist.assert_called_once()
# Verify the result
assert len(result) == 2
assert result[0] == {"track": "result1"}
assert result[1] == {"track": "result2"}
+290
View File
@@ -0,0 +1,290 @@
import os
import pytest
import glob
import json
import tempfile
from unittest.mock import MagicMock, patch, call, mock_open
import datetime as dt # Use alias to avoid conflict
import fcntl
from pydub import AudioSegment
from karaoke_gen.karaoke_gen import KaraokePrep
from audio_separator.separator import Separator # Keep for patching target
class TestAudio:
def test_separate_audio(self, basic_karaoke_gen, temp_dir):
"""Test separating audio into instrumental and vocals."""
# Setup
audio_file = os.path.join(temp_dir, "input.wav")
with open(audio_file, "w") as f:
f.write("mock audio content")
model_name = "test_model.ckpt"
artist_title = "Test Artist - Test Title"
track_output_dir = temp_dir
instrumental_path = os.path.join(temp_dir, f"{artist_title} (Instrumental {model_name}).flac")
vocals_path = os.path.join(temp_dir, f"{artist_title} (Vocals {model_name}).flac")
# Mock Separator
mock_separator = MagicMock()
mock_separator.load_model.return_value = None
mock_separator.separate.return_value = [
f"{artist_title} (Vocals)_test_model.flac",
f"{artist_title} (Instrumental)_test_model.flac",
f"{artist_title}_(Piano)_test_model.flac"
]
# Mock dependencies
with patch('audio_separator.separator.Separator', return_value=mock_separator), \
patch('os.rename') as mock_rename:
# Call the method
basic_karaoke_gen.audio_processor.separate_audio(
audio_file=audio_file,
model_name=model_name,
artist_title=artist_title,
track_output_dir=track_output_dir,
instrumental_path=instrumental_path,
vocals_path=vocals_path
)
# Verify Separator.load_model was called with correct arguments
mock_separator.load_model.assert_called_once_with(model_filename=model_name)
# Verify Separator.separate was called with correct arguments
mock_separator.separate.assert_called_once_with(audio_file)
# Verify os.rename was called for each output file
assert mock_rename.call_count == 3
mock_rename.assert_any_call(
f"{artist_title} (Vocals)_test_model.flac",
vocals_path
)
mock_rename.assert_any_call(
f"{artist_title} (Instrumental)_test_model.flac",
instrumental_path
)
def test_separate_audio_invalid_audio_file(self, basic_karaoke_gen):
"""Test separating audio with an invalid audio file."""
with pytest.raises(Exception, match="Error: Invalid audio source provided."):
basic_karaoke_gen.audio_processor.separate_audio(
audio_file=None,
model_name="test_model.ckpt",
artist_title="Test Artist - Test Title",
track_output_dir="output_dir",
instrumental_path="instrumental.flac",
vocals_path="vocals.flac"
)
def test_process_audio_separation(self, basic_karaoke_gen, temp_dir):
"""Test the process_audio_separation method."""
# Setup
audio_file = os.path.join(temp_dir, "input.wav")
with open(audio_file, "w") as f:
f.write("mock audio content")
artist_title = "Test Artist - Test Title"
track_output_dir = temp_dir
# Create stems directory
stems_dir = os.path.join(track_output_dir, "stems")
os.makedirs(stems_dir, exist_ok=True)
# Mock Separator
mock_separator = MagicMock()
mock_separator.load_model.return_value = None
# Mock output files for different models
clean_model = "model_bs_roformer_ep_317_sdr_12.9755.ckpt"
backing_model = "mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"
other_model = "htdemucs_6s.yaml"
# Determine intermediate filenames based on input to _separate_backing_vocals
# The input path for backing vocal separation is the output vocals from the clean separation
clean_vocals_output_path = os.path.join(stems_dir, f"{artist_title} (Vocals {clean_model}).flac")
# audio-separator appends _(Vocals) or _(Instrumental) to the *input* filename stem (without extension), relative to the input file's directory
clean_vocals_input_stem = clean_vocals_output_path[:-len(basic_karaoke_gen.lossless_output_format)-1] # Remove .flac
intermediate_bv_vocals = f"{clean_vocals_input_stem}_(Vocals).{basic_karaoke_gen.lossless_output_format}"
intermediate_bv_instrumental = f"{clean_vocals_input_stem}_(Instrumental).{basic_karaoke_gen.lossless_output_format}"
mock_separator.separate.side_effect = [
# 1. Clean instrumental model outputs (called by _separate_clean_instrumental)
# These are output relative to the *input* audio file's directory (temp_dir)
[
# These names need the model name appended by the separator convention
os.path.join(temp_dir, f"{artist_title}_(Vocals)_{clean_model}.{basic_karaoke_gen.lossless_output_format}"),
os.path.join(temp_dir, f"{artist_title}_(Instrumental)_{clean_model}.{basic_karaoke_gen.lossless_output_format}")
],
# 2. Other stems model outputs (called by _separate_other_stems)
# These are also output relative to the *input* audio file's directory (temp_dir)
[
os.path.join(temp_dir, f"{artist_title}_(Piano)_{other_model}.{basic_karaoke_gen.lossless_output_format}"),
os.path.join(temp_dir, f"{artist_title}_(Guitar)_{other_model}.{basic_karaoke_gen.lossless_output_format}")
],
# 3. Backing vocals model outputs (called by _separate_backing_vocals)
# These are output relative to the *vocals input* file's directory (stems_dir)
[
intermediate_bv_vocals, # e.g., .../stems/Artist - Title (Vocals model_clean)_(Vocals).flac
intermediate_bv_instrumental # e.g., .../stems/Artist - Title (Vocals model_clean)_(Instrumental).flac
]
]
# Mock dependencies
with patch('audio_separator.separator.Separator', return_value=mock_separator), \
patch('os.rename') as mock_rename, \
patch('os.path.exists', return_value=True), \
patch('os.getpid', return_value=12345), \
patch('psutil.pid_exists', return_value=False), \
patch('datetime.datetime') as mock_datetime, \
patch('json.dump'), \
patch('fcntl.flock'), \
patch('os.remove'), \
patch('os.system'), \
patch('builtins.open', mock_open(read_data='{"pid": 123, "start_time": "2023-01-01T11:00:00", "track": "Old Track"}')) as mock_file_open, \
patch.object(basic_karaoke_gen.audio_processor, '_normalize_audio_files') as mock_normalize_files, \
patch.object(basic_karaoke_gen.file_handler, '_file_exists') as mock_file_exists:
# Configure _file_exists side effect: False initially, then True for normalization checks
# Needs to return False for:
# 1. clean instrumental path check (_separate_clean_instrumental)
# 2. clean vocals path check (_separate_clean_instrumental)
# 3. other stem piano path check (_separate_other_stems loop 1)
# 4. other stem guitar path check (_separate_other_stems loop 1) - Assuming 1 'other' model
# 5. lead vocals path check (_separate_backing_vocals)
# 6. backing vocals path check (_separate_backing_vocals)
# 7. combined instrumental path check (_generate_combined_instrumentals)
# Then True for normalization checks:
# 8. backing lead vocals path check (inner loop in _separate_backing_vocals)
# 9. backing backing vocals path check (inner loop in _separate_backing_vocals)
# 10. combined instrumental path check (_generate_combined_instrumentals)
# Then True for normalization checks:
# 11. clean instrumental path check (in _normalize_audio_files)
# 12. combined instrumental path check (in _normalize_audio_files)
mock_file_exists.side_effect = [False] * 9 + [True] * 2 # Adjusted from 7 to 9 False values
# Configure the mock datetime object
mock_datetime.now.return_value = dt.datetime.fromisoformat("2023-01-01T12:00:00")
mock_datetime.fromisoformat.side_effect = lambda *args, **kwargs: dt.datetime.fromisoformat(*args, **kwargs)
# Call the method
result = basic_karaoke_gen.audio_processor.process_audio_separation(
audio_file=audio_file,
artist_title=artist_title,
track_output_dir=track_output_dir
)
# Verify the result structure
assert "clean_instrumental" in result
assert "other_stems" in result
assert "backing_vocals" in result
assert "combined_instrumentals" in result
# Verify Separator.load_model was called for each model
assert mock_separator.load_model.call_count == 3
# Verify Separator.separate was called for each separation
assert mock_separator.separate.call_count == 3
# Verify _normalize_audio_files was called once
assert mock_normalize_files.call_count == 1
def test_process_audio_separation_with_skip_env_var(self, basic_karaoke_gen, temp_dir):
"""Test process_audio_separation with KARAOKE_GEN_SKIP_AUDIO_SEPARATION environment variable."""
# Setup
audio_file = os.path.join(temp_dir, "input.wav")
with open(audio_file, "w") as f:
f.write("mock audio content")
artist_title = "Test Artist - Test Title"
track_output_dir = temp_dir
# Mock environment variable
with patch.dict('os.environ', {'KARAOKE_GEN_SKIP_AUDIO_SEPARATION': '1'}), \
patch('fcntl.flock'), \
patch('psutil.pid_exists', return_value=False), \
patch('builtins.open', mock_open()) as mock_file_open:
# Call the method
result = basic_karaoke_gen.audio_processor.process_audio_separation(
audio_file=audio_file,
artist_title=artist_title,
track_output_dir=track_output_dir
)
# Verify the result structure
assert "clean_instrumental" in result
assert "other_stems" in result
assert "backing_vocals" in result
assert "combined_instrumentals" in result
# Verify all result sections are empty
assert result["clean_instrumental"] == {}
assert result["other_stems"] == {}
assert result["backing_vocals"] == {}
assert result["combined_instrumentals"] == {}
def test_normalize_audio(self, basic_karaoke_gen, temp_dir):
"""Test normalizing audio."""
# Setup
input_path = os.path.join(temp_dir, "input.flac")
output_path = os.path.join(temp_dir, "output.flac")
# Create a mock AudioSegment
mock_audio = MagicMock(spec=AudioSegment)
mock_audio.max_dBFS = -6.0
mock_audio.apply_gain.return_value = mock_audio
mock_audio.rms = 100 # Non-zero RMS
# Mock dependencies
with patch('pydub.AudioSegment.from_file', return_value=mock_audio):
# Call the method
basic_karaoke_gen.audio_processor._normalize_audio(input_path, output_path)
# Verify AudioSegment.from_file was called with correct arguments
AudioSegment.from_file.assert_called_once_with(input_path, format="flac")
# Verify apply_gain was called with correct arguments (target_level - current_level)
mock_audio.apply_gain.assert_called_once_with(0.0 - (-6.0))
# Verify export was called with correct arguments
mock_audio.export.assert_called_once_with(output_path, format="flac")
def test_normalize_audio_silent_result(self, basic_karaoke_gen, temp_dir):
"""Test normalizing audio when the result would be silent."""
# Setup
input_path = os.path.join(temp_dir, "input.flac")
output_path = os.path.join(temp_dir, "output.flac")
# Create a mock AudioSegment
mock_audio = MagicMock(spec=AudioSegment)
mock_audio.max_dBFS = -6.0
# First mock has RMS of 0 (silent)
mock_normalized = MagicMock(spec=AudioSegment)
mock_normalized.rms = 0
mock_audio.apply_gain.return_value = mock_normalized
# Mock dependencies
with patch('pydub.AudioSegment.from_file', return_value=mock_audio):
# Call the method
basic_karaoke_gen.audio_processor._normalize_audio(input_path, output_path)
# Verify AudioSegment.from_file was called with correct arguments
AudioSegment.from_file.assert_called_once_with(input_path, format="flac")
# Verify apply_gain was called with correct arguments
mock_audio.apply_gain.assert_called_once_with(0.0 - (-6.0))
# Verify export was called with the original audio (not the silent one)
mock_audio.export.assert_called_once_with(output_path, format="flac")
def test_file_exists(self, basic_karaoke_gen):
"""Test the _file_exists helper method."""
# Test with existing file
with patch('os.path.isfile', return_value=True):
assert basic_karaoke_gen.file_handler._file_exists("existing_file.txt") is True
# Test with non-existing file
with patch('os.path.isfile', return_value=False):
assert basic_karaoke_gen.file_handler._file_exists("non_existing_file.txt") is False
+339
View File
@@ -0,0 +1,339 @@
import os
import tempfile
import unittest
from unittest.mock import patch, MagicMock, call
import logging
from karaoke_gen.audio_processor import AudioProcessor
class TestRemoteAudioSeparation(unittest.TestCase):
def setUp(self):
self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.DEBUG)
# Create a temporary directory for testing
self.temp_dir = tempfile.mkdtemp()
# Initialize AudioProcessor with test parameters
self.audio_processor = AudioProcessor(
logger=self.logger,
log_level=logging.DEBUG,
log_formatter=None,
model_file_dir="/tmp/test-models",
lossless_output_format="FLAC",
clean_instrumental_model="model_bs_roformer_ep_317_sdr_12.9755.ckpt",
backing_vocals_models=["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"],
other_stems_models=["htdemucs_6s.yaml"],
ffmpeg_base_command="ffmpeg"
)
def tearDown(self):
# Clean up temporary directory
import shutil
shutil.rmtree(self.temp_dir, ignore_errors=True)
@patch.dict(os.environ, {'AUDIO_SEPARATOR_API_URL': 'https://test-api.com'})
@patch('karaoke_gen.audio_processor.REMOTE_API_AVAILABLE', True)
@patch('karaoke_gen.audio_processor.AudioSeparatorAPIClient')
def test_remote_api_detection(self, mock_client_class):
"""Test that remote API is detected when environment variable is set."""
mock_client = MagicMock()
mock_client_class.return_value = mock_client
# Mock the API responses for the two-stage approach
mock_client.separate_audio_and_wait.side_effect = [
# Stage 1: Clean instrumental + other stems
{
"status": "completed",
"downloaded_files": [
"/tmp/test_file_(Vocals)_model_bs_roformer_ep_317_sdr_12.9755.flac",
"/tmp/test_file_(Instrumental)_model_bs_roformer_ep_317_sdr_12.9755.flac",
"/tmp/test_file_(Drums)_htdemucs_6s.flac",
"/tmp/test_file_(Bass)_htdemucs_6s.flac",
"/tmp/test_file_(Other)_htdemucs_6s.flac"
]
},
# Stage 2: Backing vocals
{
"status": "completed",
"downloaded_files": [
"/tmp/test_vocals_(Vocals)_mel_band_roformer_karaoke_aufr33_viperx_sdr_10.flac",
"/tmp/test_vocals_(Instrumental)_mel_band_roformer_karaoke_aufr33_viperx_sdr_10.flac"
]
}
]
# Mock file operations
with patch('os.path.exists', return_value=True), \
patch('shutil.move'), \
patch('os.makedirs'), \
patch('builtins.open', create=True) as mock_open, \
patch('os.path.abspath', side_effect=lambda x: x), \
patch('sys.platform', 'darwin'), \
patch('os.system'), \
patch.object(self.audio_processor, '_generate_combined_instrumentals', return_value={"mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt": "/tmp/combined.flac"}), \
patch.object(self.audio_processor, '_normalize_audio_files'):
result = self.audio_processor.process_audio_separation(
"/tmp/test_audio.wav",
"Test Artist - Test Song",
self.temp_dir
)
# Verify remote API was called twice (stage 1 and stage 2)
self.assertTrue(mock_client_class.called)
self.assertEqual(mock_client.separate_audio_and_wait.call_count, 2)
# Verify stage 1 call parameters (original song with clean + other stems models)
stage1_call_args = mock_client.separate_audio_and_wait.call_args_list[0]
self.assertEqual(stage1_call_args[0][0], "/tmp/test_audio.wav") # original audio file
self.assertIn("model_bs_roformer_ep_317_sdr_12.9755.ckpt", stage1_call_args[1]["models"])
self.assertIn("htdemucs_6s.yaml", stage1_call_args[1]["models"])
# Stage 1 should NOT include backing vocals models
self.assertNotIn("mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt", stage1_call_args[1]["models"])
# Verify stage 2 call parameters (clean vocals with backing vocals models)
stage2_call_args = mock_client.separate_audio_and_wait.call_args_list[1]
# Stage 2 should process the vocals file from stage 1
self.assertTrue(stage2_call_args[0][0].endswith("(Vocals model_bs_roformer_ep_317_sdr_12.9755.ckpt).FLAC"))
self.assertEqual(stage2_call_args[1]["models"], ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"])
@patch.dict(os.environ, {}, clear=True) # Clear AUDIO_SEPARATOR_API_URL
def test_local_fallback_when_no_env_var(self):
"""Test that local processing is used when environment variable is not set."""
with patch('audio_separator.separator.Separator') as mock_separator_class:
mock_separator = MagicMock()
mock_separator_class.return_value = mock_separator
mock_separator.separate.return_value = []
# Mock the locking mechanism and file operations
mock_open = MagicMock()
with patch('tempfile.gettempdir', return_value='/tmp'), \
patch('fcntl.flock'), \
patch('os.getpid', return_value=12345), \
patch('os.path.exists', return_value=False), \
patch('builtins.open', mock_open), \
patch('json.dump'), \
patch('os.makedirs'), \
patch.object(self.audio_processor, '_generate_combined_instrumentals', return_value={"mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt": "/tmp/combined.flac"}), \
patch.object(self.audio_processor, '_normalize_audio_files'), \
patch.object(self.audio_processor, '_separate_clean_instrumental', return_value={"vocals": "/tmp/vocals.flac", "instrumental": "/tmp/instrumental.flac"}), \
patch.object(self.audio_processor, '_separate_other_stems', return_value={}), \
patch.object(self.audio_processor, '_separate_backing_vocals', return_value={"mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt": {"lead_vocals": "/tmp/lead.flac", "backing_vocals": "/tmp/backing.flac"}}):
result = self.audio_processor.process_audio_separation(
"/tmp/test_audio.wav",
"Test Artist - Test Song",
self.temp_dir
)
# Verify local Separator was used
mock_separator_class.assert_called()
@patch.dict(os.environ, {'AUDIO_SEPARATOR_API_URL': 'https://test-api.com'})
@patch('karaoke_gen.audio_processor.REMOTE_API_AVAILABLE', False)
def test_local_fallback_when_remote_unavailable(self):
"""Test that local processing is used when remote API is unavailable."""
with patch('audio_separator.separator.Separator') as mock_separator_class:
mock_separator = MagicMock()
mock_separator_class.return_value = mock_separator
mock_separator.separate.return_value = []
# Mock the locking mechanism and file operations
mock_open = MagicMock()
with patch('tempfile.gettempdir', return_value='/tmp'), \
patch('fcntl.flock'), \
patch('os.getpid', return_value=12345), \
patch('os.path.exists', return_value=False), \
patch('builtins.open', mock_open), \
patch('json.dump'), \
patch('os.makedirs'), \
patch.object(self.audio_processor, '_generate_combined_instrumentals', return_value={"mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt": "/tmp/combined.flac"}), \
patch.object(self.audio_processor, '_normalize_audio_files'), \
patch.object(self.audio_processor, '_separate_clean_instrumental', return_value={"vocals": "/tmp/vocals.flac", "instrumental": "/tmp/instrumental.flac"}), \
patch.object(self.audio_processor, '_separate_other_stems', return_value={}), \
patch.object(self.audio_processor, '_separate_backing_vocals', return_value={"mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt": {"lead_vocals": "/tmp/lead.flac", "backing_vocals": "/tmp/backing.flac"}}):
result = self.audio_processor.process_audio_separation(
"/tmp/test_audio.wav",
"Test Artist - Test Song",
self.temp_dir
)
# Verify local Separator was used as fallback
mock_separator_class.assert_called()
@patch.dict(os.environ, {'AUDIO_SEPARATOR_API_URL': 'https://test-api.com'})
@patch('karaoke_gen.audio_processor.REMOTE_API_AVAILABLE', True)
@patch('karaoke_gen.audio_processor.AudioSeparatorAPIClient')
def test_fallback_on_remote_error(self, mock_client_class):
"""Test that local processing is used when remote API fails."""
mock_client = MagicMock()
mock_client_class.return_value = mock_client
# Mock API failure
mock_client.separate_audio_and_wait.side_effect = Exception("API Error")
with patch('audio_separator.separator.Separator') as mock_separator_class:
mock_separator = MagicMock()
mock_separator_class.return_value = mock_separator
mock_separator.separate.return_value = []
# Mock the locking mechanism and file operations
mock_open = MagicMock()
with patch('tempfile.gettempdir', return_value='/tmp'), \
patch('fcntl.flock'), \
patch('os.getpid', return_value=12345), \
patch('os.path.exists', return_value=False), \
patch('builtins.open', mock_open), \
patch('json.dump'), \
patch('os.makedirs'), \
patch.object(self.audio_processor, '_generate_combined_instrumentals', return_value={"mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt": "/tmp/combined.flac"}), \
patch.object(self.audio_processor, '_normalize_audio_files'), \
patch.object(self.audio_processor, '_separate_clean_instrumental', return_value={"vocals": "/tmp/vocals.flac", "instrumental": "/tmp/instrumental.flac"}), \
patch.object(self.audio_processor, '_separate_other_stems', return_value={}), \
patch.object(self.audio_processor, '_separate_backing_vocals', return_value={"mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt": {"lead_vocals": "/tmp/lead.flac", "backing_vocals": "/tmp/backing.flac"}}):
result = self.audio_processor.process_audio_separation(
"/tmp/test_audio.wav",
"Test Artist - Test Song",
self.temp_dir
)
# Verify remote API was attempted first
mock_client.separate_audio_and_wait.assert_called_once()
# Verify local Separator was used as fallback
mock_separator_class.assert_called()
def test_organize_remote_separation_results(self):
"""Test the organization of downloaded files from remote API."""
# Test stage 1 organization (clean instrumental + other stems)
stage1_files = [
"/tmp/test_audio_(Vocals)_model_bs_roformer_ep_317_sdr_12.9755.flac",
"/tmp/test_audio_(Instrumental)_model_bs_roformer_ep_317_sdr_12.9755.flac",
"/tmp/test_audio_(Drums)_htdemucs_6s.flac",
"/tmp/test_audio_(Bass)_htdemucs_6s.flac",
"/tmp/test_audio_(Other)_htdemucs_6s.flac"
]
artist_title = "Test Artist - Test Song"
stems_dir = os.path.join(self.temp_dir, "stems")
with patch('shutil.move') as mock_move, \
patch('os.makedirs'):
result = self.audio_processor._organize_stage1_remote_results(
stage1_files, artist_title, self.temp_dir, stems_dir
)
# Verify stage 1 file organization
self.assertIn("clean_instrumental", result)
self.assertIn("other_stems", result)
# Verify that files were moved for both clean instrumental and other stems
self.assertTrue(mock_move.called)
# Should have moved: vocals, instrumental, drums, bass, other (5 files)
self.assertEqual(mock_move.call_count, 5)
# Test stage 2 organization (backing vocals)
stage2_files = [
"/tmp/test_vocals_(Vocals)_mel_band_roformer_karaoke_aufr33_viperx_sdr_10.flac",
"/tmp/test_vocals_(Instrumental)_mel_band_roformer_karaoke_aufr33_viperx_sdr_10.flac"
]
with patch('shutil.move') as mock_move_stage2:
backing_vocals_result = self.audio_processor._organize_stage2_remote_results(
stage2_files, artist_title, stems_dir
)
# Verify stage 2 file organization
self.assertIn("mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt", backing_vocals_result)
# Verify that files were moved for backing vocals (lead vocals + backing vocals = 2 files)
self.assertTrue(mock_move_stage2.called)
self.assertEqual(mock_move_stage2.call_count, 2)
@patch.dict(os.environ, {'AUDIO_SEPARATOR_API_URL': 'https://test-api.com'})
@patch('karaoke_gen.audio_processor.REMOTE_API_AVAILABLE', True)
@patch('karaoke_gen.audio_processor.AudioSeparatorAPIClient')
def test_remote_api_download_failure(self, mock_client_class):
"""Test that download failures cause clear exceptions."""
mock_client = MagicMock()
mock_client_class.return_value = mock_client
# Mock Stage 1 success but Stage 2 download failure (like the user's issue)
mock_client.separate_audio_and_wait.side_effect = [
# Stage 1: Success with downloads
{
"status": "completed",
"downloaded_files": [
"/tmp/test_file_(Vocals)_model_bs_roformer_ep_317_sdr_12.9755.flac",
"/tmp/test_file_(Instrumental)_model_bs_roformer_ep_317_sdr_12.9755.flac",
"/tmp/test_file_(Drums)_htdemucs_6s.flac",
]
},
# Stage 2: Success but no downloads (like the 404 issue)
{
"status": "completed",
"downloaded_files": [] # No files downloaded due to 404s
}
]
# Mock file operations
with patch('os.path.exists', return_value=True), \
patch('shutil.move'), \
patch('os.makedirs'):
# This should raise an exception due to Stage 2 download failure
with self.assertRaises(Exception) as context:
self.audio_processor.process_audio_separation(
"/tmp/test_audio.wav",
"Test Artist - Test Song",
self.temp_dir
)
# Verify the exception message is clear and helpful
error_message = str(context.exception)
self.assertIn("Stage 2 backing vocals separation completed successfully but no files were downloaded", error_message)
self.assertIn("filename encoding or API issue", error_message)
self.assertIn("Expected 2 files", error_message)
@patch.dict(os.environ, {'AUDIO_SEPARATOR_API_URL': 'https://test-api.com'})
@patch('karaoke_gen.audio_processor.REMOTE_API_AVAILABLE', True)
@patch('karaoke_gen.audio_processor.AudioSeparatorAPIClient')
def test_stage1_download_failure(self, mock_client_class):
"""Test that Stage 1 download failures cause clear exceptions."""
mock_client = MagicMock()
mock_client_class.return_value = mock_client
# Mock Stage 1 job success but no downloads
mock_client.separate_audio_and_wait.return_value = {
"status": "completed",
"downloaded_files": [] # No files downloaded
}
# Mock file operations
with patch('os.path.exists', return_value=True), \
patch('os.makedirs'):
# This should raise an exception due to Stage 1 download failure
with self.assertRaises(Exception) as context:
self.audio_processor.process_audio_separation(
"/tmp/test_audio.wav",
"Test Artist - Test Song",
self.temp_dir
)
# Verify the exception message is clear and helpful
error_message = str(context.exception)
self.assertIn("Stage 1 audio separation completed successfully but no files were downloaded", error_message)
self.assertIn("filename encoding or API issue", error_message)
if __name__ == '__main__':
unittest.main()
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff. Show more