73 Commits

Author SHA1 Message Date
max 2ab85b64ff fix #26 (backend,frontend): Frontend can't apply codecs filters correctly 2026-09-02 21:24:18 +05:00
max cf0b9f62cb fix #22 (backend,frontend): the backend and frontend had whitelists that only included audio formats 2026-09-02 20:12:00 +05:00
max 1b0767af90 fix #27 (core): no write permissions fail 2026-09-02 19:36:28 +05:00
max a8b0c538ff fix #25 (core): wrong output filename extensions when they are autodetected 2026-09-02 19:14:57 +05:00
max 3a41bd2920 fix #18 (core): malformed names of output files 2026-09-02 18:30:53 +05:00
max 78ec4dd63a Fix #28: warn when timestamps overlap
Add overlap detection in resolve_end_times. When consecutive tracks have
overlapping time ranges (end of track N > start of track N+1), a warning
is printed but processing continues as before.
2026-09-02 16:57:10 +05:00
max 8b67de59a3 Fix #29: validate --container against known containers
Before this fix, passing an invalid container name (e.g., 'nonexistent')
was passed directly to FFmpeg, which would fail with a cryptic error.
Now the container name is validated against CONTAINER_NAMES before any
processing begins, and a clear error message listing valid containers
is shown.
2026-09-02 15:41:38 +05:00
max 25e8c0293e feat (core): allows user to add an external cover image to split tracks 2026-09-02 11:42:47 +05:00
max e36c1d69ed minor (core): updates DEFAULT_BAD_CHARS 2026-09-01 15:54:38 +05:00
max e77434cf30 feat (core): updates codecs info in constants.py 2026-09-01 15:47:02 +05:00
max 90d73d0e74 refact (core): removes useless fields from CODEC_INFO 2026-09-01 13:08:28 +05:00
max 7a7b63b03b refact (core): simplifies constants.py, removes redundancy, updates dependent code 2026-09-01 12:17:21 +05:00
max a67acc31b7 feat (back): removes cover image handling, since it's in core now 2026-08-31 19:50:44 +05:00
max 5f68eccdbf feat (core): If user_format is provided, map it to the correct container if it's a codec name 2026-08-31 19:48:31 +05:00
max 156dfa693f update (core): new values for codec/container/file_extension compatibility 2026-08-31 14:20:02 +05:00
max 580837fa73 feature (core): adds special handlers for audio+cover_image cases 2026-08-31 14:19:07 +05:00
max 747a349877 fix (core): checks the compatibility even if default options are used 2026-08-30 19:00:12 +05:00
max 6f6637a9a2 REFACTOR (BACKEND): removes an useless file 2026-08-30 15:48:28 +05:00
max 5e02184c8f REFACTOR (FRONTEND): exports some functionality from web/frontend/src/components/OptionsPanel.tsx into separated hooks 2026-08-30 15:26:02 +05:00
max e935241fd8 REFACTOR (CORE): splits build_ffmpeg_command method into one orchestrator and helper methods 2026-08-30 14:47:13 +05:00
max 8e0d345ba7 FIX: maps codecs names and ffmpeg encoders correctly 2026-08-28 15:41:21 +05:00
max 3533525df0 FEATURE: propagate improvements from CLI and web-API versions to web-frontend 2026-08-28 15:40:38 +05:00
max 834239674a FEATURE: propogate improvements from CLI version to web-backend 2026-08-28 13:24:46 +05:00
max 748532be7c FIX: codec/container/file_extension autodetection when default values are used 2026-08-28 11:04:40 +05:00
max f3abbb8f0c FEATURE: adds quality flag for video stream 2026-08-25 17:00:43 +05:00
max 690c5f98c6 FEATURE: adds strict codec/container/file_extension verification, renames ambiguous options, adds flexible transcoding 2026-08-25 10:40:48 +05:00
max 262d458ce4 FEATURE: codecs/containers/file_extensions inconsistency fixed 2026-08-21 15:59:05 +05:00
max 7af2600ed8 FEATURE: all versions use single source of truth for codec/container/file_extension info 2026-08-21 14:58:55 +05:00
max d08045bf02 Merge pull request 'fix(frontend): frontend functional bugs' (#9) from frontend_bugs into dev
Reviewed-on: #9
2026-08-21 13:35:17 +04:00
max 4843ac1cb5 FEATURE: clarifes 'format' option in output section of the frontend 2026-08-20 20:21:15 +05:00
max 364fc7a8fe FEATURE: adds automatic format detected to the frontend 2026-08-20 19:59:11 +05:00
max 8a1e2a5335 FIX: aligns line number with the corresponding lines in the tracklist editor 2026-08-20 12:47:58 +05:00
max 3c7ff97e76 Merge pull request 'feat(core): single source of truth for default values added' (#6) from default_args into dev
Reviewed-on: #6
2026-08-20 09:34:21 +04:00
max 140a0fbc46 FEATURE: single source of truth for default values added 2026-08-20 10:28:07 +05:00
max 05fcc8ea29 Merge pull request 'FEAT(backend): allows the backend to take a tracklis text file' (#5) from backend_tracks_file into dev
Reviewed-on: #5
2026-08-19 16:30:10 +04:00
max 52d01f1bcd FEATURE: allows the backend to take a tracklis text file 2026-08-19 17:26:07 +05:00
max 607836b280 CHANGE: drops cli version docker support 2026-08-19 13:12:34 +05:00
max 5e124645c0 Merge pull request 'feat(core): output format detected logic improved' (#4) from reverse-proxy into main
Reviewed-on: #4
2026-08-19 10:21:11 +04:00
max 02b730b082 CHANGE: maps codec/container/file_extension more accurate
Build and Push Docker Image / build-and-push-backend (pull_request) Failing after 19m21s
Build and Push Docker Image / build-and-push-frontend (pull_request) Successful in 54s
Build and Push Docker Image / notify-deployment-server (pull_request) Successful in 11s
2026-08-19 11:12:48 +05:00
max c27f832c95 Update README.md 2026-08-07 06:35:53 +00:00
max 5cf6812338 Update README.md 2026-08-07 06:34:36 +00:00
max bb883409e1 run-name added for images building action 2026-08-05 17:11:43 +05:00
max f868de9d3b Merge pull request 'Reverse proxy config added, secret is used in build images action' (#3) from reverse-proxy into main
Reviewed-on: #3
2026-08-05 12:08:10 +00:00
max 800ad9c280 Building images action uses a secret to authenticate webhook server
Build and Push Docker Image / build-and-push-backend (pull_request) Successful in 1m2s
Build and Push Docker Image / build-and-push-frontend (pull_request) Successful in 49s
Build and Push Docker Image / notify-deployment-server (pull_request) Successful in 13s
2026-08-05 16:57:12 +05:00
max bf6c6780da New deployment instructions added - simple NGINX reverse proxy example 2026-08-05 14:33:03 +05:00
max 96b1588fcc Merge pull request 'Ci cd merge request' (#2) from ci-cd into main
Reviewed-on: #2
2026-08-05 04:57:46 +00:00
max f00a70cb2e Merge pull request 'Web interface merge' (#1) from web-interface into main
Reviewed-on: #1
2026-08-05 04:56:17 +00:00
max 7f2b82aae0 .env.example is improved, comments added. docker-compose-prod.yaml is replaced with docker-compose.yaml, development version is docker-compose.override.yaml now
Build and Push Docker Image / build-and-push-backend (pull_request) Successful in 21m4s
Build and Push Docker Image / build-and-push-frontend (pull_request) Successful in 52s
Build and Push Docker Image / notify-deployment-server (pull_request) Successful in 13s
2026-08-05 09:52:23 +05:00
max a028b875fb building image actions is triggered only if a pull request has been merged into main 2026-08-05 09:07:00 +05:00
max d1a166a0f1 docker-compose-prod.yaml uses more variables from .env.example now 2026-08-05 08:52:45 +05:00
max fb9413e6f8 .env is untracked now 2026-08-04 21:50:06 +05:00
max e0490c5f41 .env.example is committed to the repo from now on. .env is used as a development file and ignored 2026-08-04 21:46:48 +05:00
max b6deed78c8 Building image action builds both images first, only then notifies the deployment server. Docker compose production file added 2026-08-04 20:41:21 +05:00
max e802b684ff Docker build context fixed in frontend building job
Build and Push Docker Image / build-and-push (push) Successful in 4m46s
2026-08-04 20:18:11 +05:00
max e28bcc27fc fixes in the build image action
Build and Push Docker Image / build-and-push (push) Failing after 1m27s
2026-08-04 20:12:41 +05:00
max 3a326859de Building image action fixed to use correct Dockerfile and build context
Build and Push Docker Image / build-and-push (push) Failing after 19m37s
2026-08-04 19:50:41 +05:00
max 26fb4fb3f4 Test CI/CD job was removed. Image building job was updated to build web version of the app
Build and Push Docker Image / build-and-push (push) Failing after 39s
2026-08-04 19:17:36 +05:00
max c455bd541b New test action added. It builds a docker image and pushes it to the registry
Build and Push Docker Image / build-and-push (push) Successful in 20m15s
Gitea Actions Demo / Explore-Gitea-Actions (push) Successful in 15s
2026-08-04 10:56:01 +05:00
max c66dbf9dc3 Test CI/CD file added
Gitea Actions Demo / Explore-Gitea-Actions (push) Successful in 18s
2026-08-03 13:02:48 +05:00
max dcdae41706 Tracs validation added. A warning is thrown if the input contains a video strem, but the requested output format doesn't support it 2026-08-03 11:26:17 +05:00
max 1d1f8563c0 Backend: endpoint for single output download added 2026-08-03 10:53:13 +05:00
max e23b0f44ce Download section didn't appear. Resolved 2026-08-03 10:46:01 +05:00
max ea49920a12 Useless Dockerfile has been removed. .gitignore updated 2026-08-02 13:38:43 +05:00
max 6707a8e27e Working docker-compose.yaml added. Services start and work. 2026-08-02 13:19:19 +05:00
max cd3ce0337b Frontend and backend work together fine, complete workflow is implemented 2026-08-01 17:04:03 +05:00
max e87d8089bf Simple frontend added, tests are required 2026-08-01 08:41:25 +00:00
max b6ace3f68b Bugs are fixed in the backend, it works now 2026-08-01 08:40:53 +00:00
max cd56637d2a Simple web backend added with upload/status/process/download API 2026-07-30 12:24:37 +00:00
max 277c538f21 Merge pull request 'Docker package' (#2) from docker_package into main
Reviewed-on: #2
2026-07-30 10:28:15 +00:00
max bb4adb1886 README.md includes information about docker setup 2026-07-30 10:22:01 +00:00
max 6c72834933 test_data added to .dockerignore 2026-07-30 09:57:59 +00:00
max 9d30844a1e Docker image hardened, seems to be working stable 2026-07-30 09:46:31 +00:00
max 5b0bb25177 Test docker image, basic functionality 2026-07-29 20:05:17 +05:00
79 changed files with 9245 additions and 504 deletions
+45
View File
@@ -0,0 +1,45 @@
# Git
.git/
.gitignore
# Python cache
*.pyc
__pycache__/
*.pyo
*.pyd
# Build artifacts
build/
dist/
*.egg-info/
.eggs/
# Virtual environments
.venv
venv/
env/
ENV/
# IDE
.vscode/
.idea/
*.swp
# License (not needed for installation)
LICENSE
# Docker files (not needed in build context)
Dockerfile
.dockerignore
# Local test files
test_data/
*.mp3
*.flac
*.wav
*.txt
*.log
# Deployment
deploy/
+26
View File
@@ -0,0 +1,26 @@
# ------------------------------------------------------------------------------
# Production Environment Variables
# ------------------------------------------------------------------------------
# Backend
DEBUG=0
MAX_UPLOAD_SIZE_MB=500
CLEANUP_AFTER_SECONDS=3600
# Backend data directory (bind mount)
# This directory will store all temporary files during splitting.
# It can get large (audio files), so place it on a partition with enough space.
BACKEND_DATA_DIR=/var/lib/audio_splitter_data
# Ports
BACKEND_PORT=8000
FRONTEND_PORT=5173
# ------------------------------------------------------------------------------
# Development Overrides (docker-compose.override.yaml)
# ------------------------------------------------------------------------------
# These are only used when docker-compose.override.yaml is present.
# They override the production settings for local development.
# Frontend (development)
VITE_BACKEND_URL=http://localhost:8000
+64
View File
@@ -0,0 +1,64 @@
name: Build and Push Docker Image
run-name: Production images are being built
on:
pull_request:
types: [closed]
branches: [ main ]
env:
REGISTRY: git.vmn.su
OWNER: max
REPO: audio_splitter
jobs:
build-and-push-backend:
if: github.event.pull_request.merged == true
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Log in to Gitea Container Registry
run: |
echo "${{ secrets.CI_PUSHER_GITEA_TOKEN }}" | docker login ${{ env.REGISTRY }} -u ${{ github.actor }} --password-stdin
- name: Build backend image
run: |
docker build -t ${{ env.REGISTRY }}/${{ env.OWNER }}/${{ env.REPO }}_backend:${{ github.sha }} -f ./web/backend/Dockerfile .
docker tag ${{ env.REGISTRY }}/${{ env.OWNER }}/${{ env.REPO }}_backend:${{ github.sha }} ${{ env.REGISTRY }}/${{ env.OWNER }}/${{ env.REPO }}_backend:latest
- name: Push backend image
run: |
docker push ${{ env.REGISTRY }}/${{ env.OWNER }}/${{ env.REPO }}_backend:${{ github.sha }}
docker push ${{ env.REGISTRY }}/${{ env.OWNER }}/${{ env.REPO }}_backend:latest
build-and-push-frontend:
if: github.event.pull_request.merged == true
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Log in to Gitea Container Registry
run: |
echo "${{ secrets.CI_PUSHER_GITEA_TOKEN }}" | docker login ${{ env.REGISTRY }} -u ${{ github.actor }} --password-stdin
- name: Build frontend image
run: |
docker build -t ${{ env.REGISTRY }}/${{ env.OWNER }}/${{ env.REPO }}_frontend:${{ github.sha }} -f ./web/frontend/Dockerfile ./web/frontend
docker tag ${{ env.REGISTRY }}/${{ env.OWNER }}/${{ env.REPO }}_frontend:${{ github.sha }} ${{ env.REGISTRY }}/${{ env.OWNER }}/${{ env.REPO }}_frontend:latest
- name: Push frontend image
run: |
docker push ${{ env.REGISTRY }}/${{ env.OWNER }}/${{ env.REPO }}_frontend:${{ github.sha }}
docker push ${{ env.REGISTRY }}/${{ env.OWNER }}/${{ env.REPO }}_frontend:latest
notify-deployment-server:
if: github.event.pull_request.merged == true
runs-on: ubuntu-latest
steps:
- name: Trigger the webhook on the deployment server to start pulling the images
run: curl "https://webhook.vmn.su/hooks/deploy-audio-splitter?token=${{ secrets.CD_WEBHOOK_TOKEN }}"
+5
View File
@@ -3,3 +3,8 @@ build/
dist/ dist/
*.egg-info/ *.egg-info/
*.pyc *.pyc
test_data/
venv/
web/frontend/node_modules
TODO.md
.env
+13 -237
View File
@@ -2,7 +2,8 @@
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/) [![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
[![FFmpeg](https://img.shields.io/badge/FFmpeg-required-green.svg)](https://ffmpeg.org/) [![FFmpeg](https://img.shields.io/badge/FFmpeg-required-green.svg)](https://ffmpeg.org/)
[![License: MIT](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://opensource.org/license/gpl-3.0) [![License: GPLv3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
[![Docker](https://img.shields.io/badge/Docker-ready-blue.svg)](https://www.docker.com/)
**Split audio files into tracks using a flexible tracklist format.** **Split audio files into tracks using a flexible tracklist format.**
@@ -10,6 +11,10 @@
--- ---
## 📖 Documentation
Full documentation including all CLI options, tracklist formats, deployment guides, and architecture details is available in the [**Wiki**](https://git.vmn.su/max/audio_splitter/wiki).
## ✨ Features ## ✨ Features
- **Flexible tracklist parsing** Define your own format with placeholders (`%ts`, `%tn`, `%an`, `%al`, `%date`, `%ext`) - **Flexible tracklist parsing** Define your own format with placeholders (`%ts`, `%tn`, `%an`, `%al`, `%date`, `%ext`)
@@ -20,242 +25,12 @@
- **Character replacement** Replace problematic filename characters with a custom character - **Character replacement** Replace problematic filename characters with a custom character
- **Dryrun mode** Preview parsed tracks without splitting - **Dryrun mode** Preview parsed tracks without splitting
- **Skip existing files** Avoid overwriting alreadyextracted tracks - **Skip existing files** Avoid overwriting alreadyextracted tracks
- **Delete original** Optionally remove the input file after successful splitting
- **Docker image** Run without installing dependencies; simple oneline commands
--- ---
## 📦 Installation
### Prerequisites
- **Python 3.8 or higher**
- **FFmpeg** required for audio processing
### Install FFmpeg
| OS | Command |
| -------------------- | ------------------------------------------------------------ |
| **Ubuntu/Debian** | `sudo apt install ffmpeg` |
| **macOS (Homebrew)** | `brew install ffmpeg` |
| **Windows** | Download from [ffmpeg.org](https://ffmpeg.org/download.html) |
### Install Audio Splitter
Clone the repository and install:
```bash
git clone https://github.com/yourusername/audio-splitter.git
cd audio-splitter
pip install .
```
Now the `audio_splitter` command is available globally:
```bash
audio_splitter input.mp3 tracks.txt
```
Or run directly without installation:
```bash
python -m audio_splitter.main input.mp3 tracklist.txt
```
---
## Quick Start
### 1. Prepare a tracklist file
Create a `tracks.txt` file with one track per line:
```
00:00 Intro
01:30 Song One - Artist A
04:20-06:45 Another Song - Artist B
08:10 Finale - Artist C
```
- `00:00` startonly timestamp (track ends at next track's start or end of file)
- `04:20-06:45` explicit start and end timestamps
### 2. Run the splitter
```bash
# If not installed
python -m audio_splitter.main my_album.mp3 tracks.txt
# If installed
audio_splitter my_album.mp3 tracks.txt
```
Output:
```
Found 4 tracks.
Detected streams: audio=True, video=False, subs=False
Audio codec: mp3
Output container: mp3
Extracting track 1: Intro (00:00:00 - 00:01:30)
-> Saved to: my_album_splits/Intro.mp3
Extracting track 2: Song One (00:01:30 - 00:04:20)
-> Saved to: my_album_splits/Song One - Artist A.mp3
...
Done!
```
---
## ⚙️ CommandLine Options
### Basic Options
| Option | Description |
| ---------------------- | ------------------------------------------------------------- |
| `input_file` | Input audio/video file |
| `tracklist_file` | Tracklist file |
| `-o, --output-dir DIR` | Output directory (default: `<input>_splits`) |
| `--format FORMAT` | Output container format (mp3, m4a, mkv, mp4, ogg, opus, etc.) |
| `--transcode-to CODEC` | Reencode audio to CODEC (e.g., libmp3lame, aac, libopus) |
| `--drop-video` | Remove video streams |
| `--drop-subs` | Remove subtitle streams |
| `--dry-run` | Preview parsed tracklist without splitting |
### Filename Options
| Option | Description |
| ---------------------------- | --------------------------------------------------------------- |
| `--number-tracks` | Prepend track number (`01 - `) to filenames |
| `--output-template TEMPLATE` | Custom filename template (default: `%an-%tn.%ext`) |
| `--replace-bad-chars` | Replace problematic characters in filenames |
| `--replacement-char CHAR` | Replacement character (default: `_`) |
| `--bad-chars CHARS` | Characters to replace (default includes space and single quote) |
### Metadata Options
| Option | Description |
| ------------------------- | ----------------------------------------------- |
| `--album ALBUM` | Set album name (overrides parsed `%al`) |
| `--comment COMMENT` | Set comment text |
| `--no-comment` | Ignore comment entirely |
| `--comment-stream INDEX` | Select comment from a specific stream (0based) |
| `--merge-comments` | Merge all comments from all streams |
| `--comment-separator SEP` | Separator for merged comments (default: `; `) |
### Tracklist Format Options
| Option | Description |
| --------------------------- | -------------------------------------------------- |
| `--tracklist-format FORMAT` | Custom tracklist format (default: `%ts %tn - %an`) |
| `--skip-existing` | Skip extraction if output file already exists |
---
## 📝 Placeholders Reference
### Tracklist Format Placeholders (`--tracklist-format`)
| Placeholder | Meaning |
| ----------- | --------------------------------------------------- |
| `%ts` | **Timestamp** required (`00:00` or `00:00-01:30`) |
| `%tn` | Track name |
| `%an` | Author/artist |
| `%al` | Album |
| `%date` | Date/year |
| `%ext` | File extension |
**Default:** `%ts %tn - %an`
### Output Template Placeholders (`--output-template`)
| Placeholder | Meaning |
| ----------- | -------------------------------------- |
| `%tn` | Track name |
| `%an` | Author/artist |
| `%al` | Album |
| `%date` | Date/year |
| `%ext` | File extension (without leading dot) |
| `%num` | Track number (zeropadded, e.g., `01`) |
**Default:** `%an-%tn.%ext`
---
## 💡 Examples
### Custom tracklist format
If your tracklist uses `artist - title [time]`:
```bash
python -m audio_splitter.main input.flac tracks.txt \
--tracklist-format "%an - %tn [%ts]"
```
### Custom output filenames
Name files as `01 - Artist - Song.mp3`:
```bash
python -m audio_splitter.main input.flac tracks.txt \
--output-template "%num - %an - %tn.%ext"
```
### Override album and comment
```bash
python -m audio_splitter.main input.flac tracks.txt \
--album "Greatest Hits" \
--comment "Live recording"
```
### Merge multiple comments from input file
```bash
python -m audio_splitter.main input.flac tracks.txt \
--merge-comments \
--comment-separator " | "
```
### Dryrun to preview parsing
```bash
python -m audio_splitter.main input.flac tracks.txt --dry-run
```
Output:
```
Parsed tracklist:
------------------------------------------------------------
ts | tn | an
------------------------------------------------------------
1 | 00:00 | Intro |
2 | 01:30 | Song One | Artist A
3 | 04:20-06:45 | Another Song | Artist B
...
------------------------------------------------------------
Dryrun complete. No files were created.
```
---
## 📂 Project Structure
```
audio_splitter/
├── __init__.py # Package initialisation
├── constants.py # Global constants (FORMAT_INFO, DEFAULT_BAD_CHARS)
├── utils.py # Generic helpers (timestamps, string manipulation)
├── tracklist.py # Tracklist parsing with custom formats
├── ffmpeg.py # FFmpeg/FFprobe interactions and command building
├── timestamp.py # Timestamp parsing and resolution
├── filename.py # Output filename generation
├── metadata.py # Metadata selection and building
├── formats.py # Container format decision and validation
├── core.py # Main orchestration logic
└── main.py # Commandline interface
```
---
## 🤝 Contributing ## 🤝 Contributing
@@ -267,13 +42,13 @@ Contributions are welcome! Please follow these steps:
4. Push to the branch (`git push origin feature/amazing-feature`) 4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request 5. Open a Pull Request
For bug reports or feature requests, please [open an issue](https://github.com/yourusername/audio-splitter/issues). For bug reports or feature requests, please [open an issue](https://git.vmn.su/max/audio_splitter/issues).
--- ---
## 📄 License ## 📄 License
Distributed under the GPU GPL v3 or later. See [LICENSE](LICENSE) for more information. Distributed under the GNU General Public License v3 (or later). See the [LICENSE](LICENSE) file for more details.
--- ---
@@ -281,10 +56,11 @@ Distributed under the GPU GPL v3 or later. See [LICENSE](LICENSE) for more infor
- [FFmpeg](https://ffmpeg.org/) the powerhouse behind audio processing - [FFmpeg](https://ffmpeg.org/) the powerhouse behind audio processing
- [Python](https://www.python.org/) the language that makes it all possible - [Python](https://www.python.org/) the language that makes it all possible
- [gosu](https://github.com/tianon/gosu) privilege dropping for Docker
--- ---
## 📬 Contact ## 📬 Contact
**Maintainer:** [Maxim Vershinin](https://git.vmn.su/max) **Maintainer:** Maxim Vershinin
**Project Link:** [https://git.vmn.su/max/audio-splitter](https://git.vmn.su/max/audio-splitter) **Project Link:** [https://git.vmn.su/max/audio_splitter](https://git.vmn.su/max/audio_splitter)
+121 -17
View File
@@ -1,20 +1,124 @@
"""Global constants and default values.""" # audio_splitter/constants.py
"""Global constants for the audio splitter.
# Mapping from userfriendly format names to FFmpeg format identifiers, This file serves as the single source of truth for:
# file extensions, and whether the container is audioonly. - Container formats and their properties
FORMAT_INFO = { - Audio codecs and their recommended containers
'mp3': {'ffmpeg': 'mp3', 'ext': '.mp3', 'audio_only': True}, - Video codec support per container
'm4a': {'ffmpeg': 'mp4', 'ext': '.m4a', 'audio_only': True}, - File extensions for each codec/container combination
'mp4': {'ffmpeg': 'mp4', 'ext': '.mp4', 'audio_only': False}, - Compatibility matrix for codec/container validation
'mkv': {'ffmpeg': 'matroska', 'ext': '.mkv', 'audio_only': False},
'matroska': {'ffmpeg': 'matroska', 'ext': '.mkv', 'audio_only': False}, Codec != Container != File Extension.
'ogg': {'ffmpeg': 'ogg', 'ext': '.ogg', 'audio_only': True}, Example: Opus (codec) → Ogg (container) → .opus (extension)
'opus': {'ffmpeg': 'ogg', 'ext': '.opus', 'audio_only': True}, """
'flac': {'ffmpeg': 'flac', 'ext': '.flac', 'audio_only': True}, from typing import Dict, Optional
'wav': {'ffmpeg': 'wav', 'ext': '.wav', 'audio_only': True},
'aac': {'ffmpeg': 'adts', 'ext': '.aac', 'audio_only': True}, # ------------------------------------------------------------------------------
# Container information
# ------------------------------------------------------------------------------
CONTAINER_INFO = [
# Audio-only containers
{'name': 'mp3', 'ffmpeg': 'mp3', 'extension': '.mp3', 'supports_video': True, 'supports_subs': False},
{'name': 'm4a', 'ffmpeg': 'mp4', 'extension': '.m4a', 'supports_video': False, 'supports_subs': False},
{'name': 'flac', 'ffmpeg': 'flac', 'extension': '.flac', 'supports_video': False, 'supports_subs': False},
{'name': 'wav', 'ffmpeg': 'wav', 'extension': '.wav', 'supports_video': False, 'supports_subs': False},
{'name': 'aac', 'ffmpeg': 'adts', 'extension': '.aac', 'supports_video': False, 'supports_subs': False},
# Containers that support video and subtitles
{'name': 'mp4', 'ffmpeg': 'mp4', 'extension': '.mp4', 'supports_video': True, 'supports_subs': True},
{'name': 'mkv', 'ffmpeg': 'matroska', 'extension': '.mkv', 'supports_video': True, 'supports_subs': True},
{'name': 'ogg', 'ffmpeg': 'ogg', 'extension': '.ogg', 'supports_video': True, 'supports_subs': True},
{'name': 'webm', 'ffmpeg': 'webm', 'extension': '.webm', 'supports_video': True, 'supports_subs': False},
]
# Container name lookup set for fast membership checks
CONTAINER_NAMES = {container['name'] for container in CONTAINER_INFO}
def get_container_info(container_name: str) -> Optional[Dict]:
"""Return container info dict or None if not found."""
for container in CONTAINER_INFO:
if container['name'] == container_name:
return container
return None
# ------------------------------------------------------------------------------
# Codec information
# ------------------------------------------------------------------------------
CODEC_INFO = [
# Audio codecs
{'name': 'opus', 'ffmpeg': 'libopus', 'recommended_container': 'ogg', 'recommended_extension': '.opus', 'codec_type': 'audio'},
{'name': 'vorbis', 'ffmpeg': 'libvorbis', 'recommended_container': 'ogg', 'recommended_extension': '.ogg', 'codec_type': 'audio'},
{'name': 'flac', 'ffmpeg': 'flac', 'recommended_container': 'flac', 'recommended_extension': '.flac', 'codec_type': 'audio'},
{'name': 'aac', 'ffmpeg': 'aac', 'recommended_container': 'mp4', 'recommended_extension': '.m4a', 'codec_type': 'audio'},
{'name': 'mp3', 'ffmpeg': 'libmp3lame', 'recommended_container': 'mp3', 'recommended_extension': '.mp3', 'codec_type': 'audio'},
{'name': 'alac', 'ffmpeg': 'alac', 'recommended_container': 'mp4', 'recommended_extension': '.m4a', 'codec_type': 'audio'},
{'name': 'pcm_s16le', 'ffmpeg': 'pcm_s16le', 'recommended_container': 'wav', 'recommended_extension': '.wav', 'codec_type': 'audio'},
# Video codecs (including cover images)
{'name': 'theora', 'ffmpeg': 'libtheora', 'recommended_container': 'ogg', 'recommended_extension': '.ogv', 'codec_type': 'video'},
{'name': 'vp8', 'ffmpeg': 'libvpx', 'recommended_container': 'webm', 'recommended_extension': '.webm', 'codec_type': 'video'},
{'name': 'vp9', 'ffmpeg': 'libvpx-vp9', 'recommended_container': 'webm', 'recommended_extension': '.webm', 'codec_type': 'video'},
{'name': 'av1', 'ffmpeg': 'libaom-av1', 'recommended_container': 'mkv', 'recommended_extension': '.mkv', 'codec_type': 'video'},
{'name': 'h264', 'ffmpeg': 'libx264', 'recommended_container': 'mp4', 'recommended_extension': '.mp4', 'codec_type': 'video'},
{'name': 'h265', 'ffmpeg': 'libx265', 'recommended_container': 'mp4', 'recommended_extension': '.mp4', 'codec_type': 'video'},
{'name': 'png', 'ffmpeg': 'png', 'recommended_container': 'ogg', 'recommended_extension': '.png', 'codec_type': 'video'},
{'name': 'mjpeg', 'ffmpeg': 'mjpeg', 'recommended_container': 'ogg', 'recommended_extension': '.jpg', 'codec_type': 'video'},
# Subtitle codecs
{'name': 'srt', 'ffmpeg': 'srt', 'recommended_container': 'mkv', 'recommended_extension': '.srt', 'codec_type': 'subtitle'},
{'name': 'ass', 'ffmpeg': 'ass', 'recommended_container': 'mkv', 'recommended_extension': '.ass', 'codec_type': 'subtitle'},
{'name': 'vtt', 'ffmpeg': 'webvtt', 'recommended_container': 'webm', 'recommended_extension': '.vtt', 'codec_type': 'subtitle'},
]
# Map codec name → recommended container
CODEC_TO_CONTAINER_MAP = {codec['name']: codec['recommended_container'] for codec in CODEC_INFO}
CODEC_TO_EXTENSION_MAP = {codec['name']: codec['recommended_extension'] for codec in CODEC_INFO}
# Map codec name → FFmpeg encoder name
CODEC_NAME_TO_FFMPEG = {codec['name']: codec['ffmpeg'] for codec in CODEC_INFO}
# ------------------------------------------------------------------------------
# Compatibility matrix: container → supported audio and video codecs
# ------------------------------------------------------------------------------
# Each container entry maps to a dict with 'audio' and 'video' keys.
# - 'audio': list of audio codec names that are supported in this container.
# Use None to indicate that any audio codec is supported.
# - 'video': list of video codec names that are supported in this container.
# Use None to indicate that any video codec is supported.
# Empty list means no video support (audio-only container).
COMPATIBILITY_MATRIX = {
'mp3': {'audio': ['mp3'], 'video': ['png', 'mjpeg']},
'm4a': {'audio': ['aac', 'alac', 'opus', 'flac'], 'video': []},
'mp4': {'audio': ['aac', 'alac', 'opus', 'flac', 'mp3'], 'video': ['h264', 'h265', 'vp9', 'av1']},
'mkv': {'audio': None, 'video': None},
'ogg': {'audio': ['opus', 'vorbis', 'flac'], 'video': ['theora', 'vp8', 'png', 'mjpeg']},
'webm': {'audio': ['opus', 'vorbis'], 'video': ['vp8', 'vp9', 'av1']},
'flac': {'audio': ['flac'], 'video': ['png', 'mjpeg']},
'wav': {'audio': ['pcm_s16le'], 'video': []},
'aac': {'audio': ['aac'], 'video': []},
} }
# Default characters to replace when --replace-bad-chars is enabled. # ------------------------------------------------------------------------------
# Includes common punctuation, single quote, and a trailing space. # Helper functions for compatibility checking
DEFAULT_BAD_CHARS = r',!@#№$;:%^&?*(){}[]\/<>+=~`\' ' # ------------------------------------------------------------------------------
def is_audio_codec_supported(container: str, audio_codec: str) -> bool:
"""Check if an audio codec is supported in the given container."""
entry = COMPATIBILITY_MATRIX.get(container, {})
supported = entry.get('audio')
if supported is None:
return True
return audio_codec in supported
def is_video_codec_supported(container: str, video_codec: str) -> bool:
"""Check if a video codec is supported in the given container."""
entry = COMPATIBILITY_MATRIX.get(container, {})
supported = entry.get('video')
if supported is None:
return True
return video_codec in supported
# ------------------------------------------------------------------------------
# Default bad characters (for filename sanitization)
# ------------------------------------------------------------------------------
DEFAULT_BAD_CHARS = r'!@#№$;:%^&?*(){}[]\/<>+=~`\'|," '
+204 -29
View File
@@ -1,36 +1,87 @@
"""Core logic: orchestrates the splitting process.""" # audio_splitter/core.py
"""Core splitting logic orchestrates the entire split process."""
import os import os
import subprocess import subprocess
import sys
from typing import List, Dict, Any
from .constants import FORMAT_INFO from .constants import (
from .ffmpeg import get_audio_duration, get_stream_info, get_metadata, build_ffmpeg_command CONTAINER_INFO,
from .formats import determine_output_format, validate_format_compatibility CONTAINER_NAMES,
CODEC_TO_EXTENSION_MAP,
CODEC_NAME_TO_FFMPEG,
)
from .ffmpeg import (
get_audio_duration,
get_stream_info,
get_metadata,
build_ffmpeg_command,
is_attached_picture,
extract_cover_image,
)
from .formats import (
determine_output_format,
validate_format_compatibility,
)
from .handlers import get_handler, needs_drop_video
from .timestamp import parse_track_timestamps, resolve_end_times from .timestamp import parse_track_timestamps, resolve_end_times
from .filename import build_filename from .filename import build_filename
from .metadata import build_metadata_dict from .metadata import build_metadata_dict
from .utils import format_time from .utils import format_time
def split_audio(input_file, output_directory, tracks, args): def split_audio(input_file: str, output_directory: str, tracks: List[Dict[str, Any]], args) -> None:
""" """
Main orchestration function: split the audio file into tracks. Main orchestration function: split the audio file into tracks.
Args: Args:
input_file: Path to the input media file. input_file: Path to the input media file.
output_directory: Directory where output files will be saved. output_directory: Directory where output files will be saved.
tracks: List of dicts, each containing parsed fields. tracks: List of dicts, each containing parsed fields (ts, tn, an, ...).
args: Parsed commandline arguments (namespace). args: Parsed commandline arguments (namespace) with attributes:
- container: output container name (or None for auto-detect)
- audio_codec: audio codec (copy or encoder)
- video_codec: video codec (copy or encoder)
- subtitle_codec: subtitle codec (copy or encoder)
- video_quality: integer or None
- drop_video: bool
- drop_subs: bool
- number_tracks: bool
- output_template: str
- replace_bad_chars: bool
- replacement_char: str
- bad_chars: str
- skip_existing: bool
- album: str or None
- comment: str or None
- no_comment: bool
- comment_stream: int or None
- merge_comments: bool
- comment_separator: str
- delete_original: bool
- cover_image: List[str] or None (optional, CLI list of cover image paths)
Raises: Raises:
RuntimeError: If no audio stream is found. RuntimeError: If no audio stream is found.
ValueError: If timestamp parsing or format compatibility fails. ValueError: If compatibility validation fails.
""" """
# -------------------------------------------------------------------------- # --------------------------------------------------------------------------
# 1. Setup # 1. Setup
# -------------------------------------------------------------------------- # --------------------------------------------------------------------------
os.makedirs(output_directory, exist_ok=True) os.makedirs(output_directory, exist_ok=True)
# Check write permission on output directory.
try:
test_file = os.path.join(output_directory, f'.write_test_{os.getpid()}')
with open(test_file, 'w') as f:
f.write('test')
os.remove(test_file)
except PermissionError:
raise RuntimeError(
f"Error: No write permission for output directory: {output_directory}"
)
total_duration = get_audio_duration(input_file) total_duration = get_audio_duration(input_file)
stream_info = get_stream_info(input_file) stream_info = get_stream_info(input_file)
@@ -42,26 +93,62 @@ def split_audio(input_file, output_directory, tracks, args):
raise RuntimeError("No audio stream found in input file.") raise RuntimeError("No audio stream found in input file.")
# -------------------------------------------------------------------------- # --------------------------------------------------------------------------
# 2. Format decision # 2. Determine output container
# -------------------------------------------------------------------------- # --------------------------------------------------------------------------
output_format = determine_output_format(stream_info, args.format, args.transcode_to) user_container = getattr(args, 'container', None)
print(f"Output container: {output_format}") output_container = determine_output_format(
stream_info,
validate_format_compatibility(output_format, stream_info, user_format=user_container,
args.drop_video, args.drop_subs) transcode_audio=args.audio_codec if args.audio_codec != 'copy' else None,
input_file=input_file
# Determine file extension. )
extension_info = FORMAT_INFO.get(output_format, {}) print(f"Output container: {output_container}")
extension = extension_info.get('ext', '.mkv')
# -------------------------------------------------------------------------- # --------------------------------------------------------------------------
# 3. Parse timestamps # 3. Validate compatibility
# --------------------------------------------------------------------------
try:
validate_format_compatibility(
container=output_container,
stream_info=stream_info,
drop_video=args.drop_video,
drop_subs=args.drop_subs,
input_file=input_file,
audio_codec=args.audio_codec,
video_codec=args.video_codec,
)
except ValueError as e:
raise RuntimeError(f"Compatibility error: {e}")
# --------------------------------------------------------------------------
# 4. Determine output audio codec and extension
# --------------------------------------------------------------------------
# Determine the audio codec that will be used in the output
if args.audio_codec != 'copy':
output_audio_codec = args.audio_codec
else:
output_audio_codec = stream_info.get('audio_codec', '')
# Choose extension based on the output container, not the audio codec.
# When user specifies --container, the file extension must match the container.
container_info = next((c for c in CONTAINER_INFO if c['name'] == output_container), None)
if container_info:
extension = container_info['extension']
elif output_audio_codec in CODEC_TO_EXTENSION_MAP:
extension = CODEC_TO_EXTENSION_MAP[output_audio_codec]
else:
extension = '.mkv'
print(f"Output extension: {extension}")
# --------------------------------------------------------------------------
# 5. Parse timestamps
# -------------------------------------------------------------------------- # --------------------------------------------------------------------------
track_times = parse_track_timestamps(tracks) track_times = parse_track_timestamps(tracks)
resolved_times = resolve_end_times(track_times, total_duration) resolved_times = resolve_end_times(track_times, total_duration)
# -------------------------------------------------------------------------- # --------------------------------------------------------------------------
# 4. Fetch original metadata (for fallbacks) # 6. Fetch original metadata (for fallbacks)
# -------------------------------------------------------------------------- # --------------------------------------------------------------------------
input_metadata = get_metadata(input_file) input_metadata = get_metadata(input_file)
original_album = input_metadata.get('album') original_album = input_metadata.get('album')
@@ -78,7 +165,39 @@ def split_audio(input_file, output_directory, tracks, args):
print(f" Stream {idx}: '{comment}'") print(f" Stream {idx}: '{comment}'")
# -------------------------------------------------------------------------- # --------------------------------------------------------------------------
# 5. Process each track # 7. Handle attached picture (cover art)
# --------------------------------------------------------------------------
user_cover_images = getattr(args, 'cover_image', None)
# Resolve per-track cover images: single image reused, or one-per-track
track_cover_images = []
if user_cover_images:
for img in user_cover_images:
if os.path.exists(img):
track_cover_images.append(img)
else:
print(f"Warning: Cover image not found, skipping: {img}")
# Extract cover from input if no user cover and input has video
if not track_cover_images and not args.drop_video and stream_info.get('has_video'):
if is_attached_picture(input_file):
cover_image_path = os.path.join(output_directory, 'cover.png')
if extract_cover_image(input_file, cover_image_path):
track_cover_images.append(cover_image_path)
print("Extracted cover image for all tracks.")
else:
track_cover_images = []
# Check if we need special handling (e.g., Opus files need opustags)
# Use output_audio_codec (not input_audio_codec) so the handler is resolved
# against the actual output codec (e.g., transcoding aac→opus in ogg).
input_audio_codec = stream_info.get('audio_codec')
cover_handler = get_handler(output_container, output_audio_codec)
needs_drop = needs_drop_video(output_container, output_audio_codec)
if track_cover_images and needs_drop:
print(f"Using special handler for {output_container} + {output_audio_codec}")
print("Temporarily dropping video for opustags post-processing.")
# --------------------------------------------------------------------------
# 8. Process each track
# -------------------------------------------------------------------------- # --------------------------------------------------------------------------
for idx, track in enumerate(tracks, start=1): for idx, track in enumerate(tracks, start=1):
start_seconds, end_seconds = resolved_times[idx - 1] start_seconds, end_seconds = resolved_times[idx - 1]
@@ -91,31 +210,62 @@ def split_audio(input_file, output_directory, tracks, args):
track_name = track.get('tn', 'Unknown') track_name = track.get('tn', 'Unknown')
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# 5a. Build filename # 8a. Build filename
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
clean_filename = build_filename(track, idx, extension, args) clean_filename = build_filename(track, idx, extension, args)
output_path = os.path.join(output_directory, clean_filename) output_path = os.path.join(output_directory, clean_filename)
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# 5b. Handle existing files # 8b. Handle existing files
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
if args.skip_existing and os.path.exists(output_path): if args.skip_existing and os.path.exists(output_path):
print(f"Skipping track {idx}: {output_path} already exists.") print(f"Skipping track {idx}: {output_path} already exists.")
continue continue
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# 5c. Build metadata # 8c. Build metadata
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
metadata = build_metadata_dict(track, idx, input_metadata, args) metadata = build_metadata_dict(track, idx, input_metadata, args)
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# 5d. Build and execute FFmpeg command # 8d. Build and execute FFmpeg command
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Map codec names to FFmpeg encoder names
audio_enc = args.audio_codec
if audio_enc != 'copy':
audio_enc = CODEC_NAME_TO_FFMPEG.get(audio_enc, audio_enc) # fallback to itself if not found
video_enc = args.video_codec
if video_enc != 'copy':
video_enc = CODEC_NAME_TO_FFMPEG.get(video_enc, video_enc)
subtitle_enc = args.subtitle_codec
if subtitle_enc != 'copy':
subtitle_enc = CODEC_NAME_TO_FFMPEG.get(subtitle_enc, subtitle_enc)
# Then build command with these mapped encoders
# Use temporary drop_video for handlers that need it
effective_drop_video = args.drop_video or (track_cover_images and needs_drop)
# For handlers that need opustags post-processing, don't pass cover_image_path
# to ffmpeg - it will process audio-only, then handler adds cover afterward
per_track_cover = (
track_cover_images[idx - 1] if len(track_cover_images) == len(tracks)
else (track_cover_images[0] if track_cover_images else None)
)
ffmpeg_cover_path = None if (per_track_cover and needs_drop) else per_track_cover
cmd = build_ffmpeg_command( cmd = build_ffmpeg_command(
input_file, start_seconds, duration_seconds, output_path, input_file=input_file,
stream_info, output_format, args.transcode_to, start_seconds=start_seconds,
args.drop_video, args.drop_subs, duration_seconds=duration_seconds,
metadata=metadata output_path=output_path,
stream_info=stream_info,
format_opt=output_container,
audio_codec=audio_enc,
video_codec=video_enc,
subtitle_codec=subtitle_enc,
metadata=metadata,
cover_image_path=ffmpeg_cover_path,
video_quality=getattr(args, 'video_quality', None),
drop_video=effective_drop_video,
drop_subs=args.drop_subs,
) )
print(f"Extracting track {idx}: {track_name} " print(f"Extracting track {idx}: {track_name} "
@@ -128,3 +278,28 @@ def split_audio(input_file, output_directory, tracks, args):
print(result.stderr) print(result.stderr)
else: else:
print(f" -> Saved to: {output_path}") print(f" -> Saved to: {output_path}")
# Apply cover image handler if needed
if per_track_cover and needs_drop:
print(f"Applying cover image via {output_container} handler...")
if not cover_handler(
input_file=input_file,
cover_image_path=per_track_cover,
output_path=output_path,
stream_info=stream_info,
audio_codec=audio_enc,
video_codec=video_enc,
video_quality=getattr(args, 'video_quality', None),
drop_video=args.drop_video,
drop_subs=args.drop_subs,
):
print(f"Warning: Failed to attach cover image to {output_path}")
# --------------------------------------------------------------------------
# 9. Delete original file if requested
# --------------------------------------------------------------------------
if getattr(args, 'delete_original', False):
try:
os.remove(input_file)
print(f"Deleted original file: {input_file}")
except OSError as e:
print(f"Warning: Could not delete original file: {e}")
+35
View File
@@ -0,0 +1,35 @@
"""Default values for all configurable options shared between CLI, web backend, and frontend."""
# Output container format (used when user doesn't specify one; auto-detection overrides this)
DEFAULT_FORMAT = "mp3"
# Filename template
DEFAULT_OUTPUT_TEMPLATE = "%an-%tn.%ext"
# Character replacement
DEFAULT_REPLACEMENT_CHAR = "_"
DEFAULT_BAD_CHARS = r'!@#№$;:%^&?*(){}[]\/<>+=~`\' '
# Tracklist parsing
DEFAULT_TRACKLIST_FORMAT = "%ts %tn - %an"
# Metadata defaults
DEFAULT_ALBUM = None
DEFAULT_COMMENT = None
DEFAULT_COMMENT_STREAM = None
DEFAULT_COMMENT_SEPARATOR = "; "
DEFAULT_NO_COMMENT = False
DEFAULT_MERGE_COMMENTS = False
# Stream handling
DEFAULT_DROP_VIDEO = False
DEFAULT_DROP_SUBS = False
# Filename/export options
DEFAULT_NUMBER_TRACKS = False
DEFAULT_REPLACE_BAD_CHARS = True
DEFAULT_SKIP_EXISTING = False
DEFAULT_DELETE_ORIGINAL = False
# Transcoding (None means copy codec)
DEFAULT_TRANSCODE_TO = None
+396 -103
View File
@@ -1,9 +1,12 @@
"""FFmpeg / FFprobe interactions and command building.""" # audio_splitter/ffmpeg.py
"""FFmpeg/FFprobe interaction utilities."""
import subprocess
import json import json
import os
import subprocess
from typing import Dict, List, Optional, Tuple
from .constants import FORMAT_INFO from .constants import CONTAINER_INFO
from .utils import format_time from .utils import format_time
@@ -24,7 +27,10 @@ def get_audio_duration(input_file: str) -> float:
input_file input_file
] ]
result = subprocess.run(cmd, capture_output=True, text=True, check=False) result = subprocess.run(cmd, capture_output=True, text=True, check=False)
return float(result.stdout.strip()) try:
return float(result.stdout.strip())
except ValueError:
return 0.0
def has_stream_type(input_file: str, stream_type: str) -> bool: def has_stream_type(input_file: str, stream_type: str) -> bool:
@@ -49,7 +55,7 @@ def has_stream_type(input_file: str, stream_type: str) -> bool:
return bool(result.stdout.strip()) return bool(result.stdout.strip())
def get_audio_codec(input_file: str) -> str: def get_audio_codec(input_file: str) -> Optional[str]:
""" """
Return the codec name of the first audio stream. Return the codec name of the first audio stream.
@@ -71,7 +77,29 @@ def get_audio_codec(input_file: str) -> str:
return codec if codec else None return codec if codec else None
def get_stream_info(input_file: str): def get_video_codec(input_file: str) -> Optional[str]:
"""
Return the codec name of the first video stream.
Args:
input_file: Path to the media file.
Returns:
Codec name as a lowercase string, or None if no video stream exists.
"""
cmd = [
'ffprobe', '-v', 'error',
'-select_streams', 'v:0',
'-show_entries', 'stream=codec_name',
'-of', 'default=noprint_wrappers=1:nokey=1',
input_file
]
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
codec = result.stdout.strip().lower()
return codec if codec else None
def get_stream_info(input_file: str) -> Dict[str, any]:
""" """
Collect information about the streams present in the input file. Collect information about the streams present in the input file.
@@ -88,94 +116,12 @@ def get_stream_info(input_file: str):
'audio_codec': get_audio_codec(input_file) 'audio_codec': get_audio_codec(input_file)
} }
def build_ffmpeg_command(input_file, start_seconds, duration_seconds, output_path,
stream_info, format_opt, transcode_audio,
drop_video, drop_subs, metadata=None):
"""
Construct the FFmpeg command line as a list of arguments.
Args: def get_metadata(input_file: str) -> Dict[str, any]:
input_file: Path to the input media file.
start_seconds: Start time for the segment (in seconds).
duration_seconds: Duration of the segment (in seconds).
output_path: Destination path for the output file.
stream_info: Dictionary from get_stream_info().
format_opt: Output container format (e.g., 'mp3').
transcode_audio: Audio codec to transcode to (or None).
drop_video: True to remove video streams.
drop_subs: True to remove subtitle streams.
metadata: Optional dict of metadata key/value pairs to write.
Returns:
A list of commandline arguments suitable for subprocess.run().
"""
cmd = [
'ffmpeg',
'-i', input_file,
'-ss', format_time(start_seconds),
'-t', format_time(duration_seconds)
]
# -------------------- Clear all original metadata --------------------
cmd.append('-map_metadata')
cmd.append('-1')
# -------------------- Apply custom metadata --------------------
if metadata:
for key, value in metadata.items():
if value is not None and value != '':
cmd.extend(['-metadata', f"{key}={value}"])
# -------------------- Stream mapping --------------------
# Map the streams we want to keep.
if drop_video and drop_subs:
cmd.extend(['-map', '0:a:0'])
elif drop_video:
cmd.extend(['-map', '0:a:0', '-map', '0:s?'])
elif drop_subs:
cmd.extend(['-map', '0:a:0', '-map', '0:v:0'])
else:
cmd.extend(['-map', '0'])
# -------------------- Audio codec --------------------
if transcode_audio:
cmd.extend(['-c:a', transcode_audio])
if transcode_audio in ('libmp3lame', 'mp3'):
cmd.extend(['-b:a', '192k'])
elif transcode_audio in ('libopus', 'opus'):
cmd.extend(['-b:a', '128k'])
else:
cmd.extend(['-c:a', 'copy'])
# -------------------- Video codec --------------------
if not drop_video and stream_info['has_video']:
cmd.extend(['-c:v', 'copy'])
else:
cmd.append('-vn')
# -------------------- Subtitle codec --------------------
if not drop_subs and stream_info['has_subtitle']:
cmd.extend(['-c:s', 'copy'])
else:
cmd.append('-sn')
# -------------------- Output format --------------------
if format_opt:
ffmpeg_format = FORMAT_INFO.get(format_opt, {}).get('ffmpeg', format_opt)
cmd.extend(['-f', ffmpeg_format])
# Overwrite output if it already exists.
cmd.extend(['-y', output_path])
return cmd
def get_metadata(input_file: str) -> dict:
""" """
Retrieve metadata from the input file using ffprobe with JSON output. Retrieve metadata from the input file using ffprobe with JSON output.
Returns a dict with:
- album: merged from all sources (last wins) Returns a dict with keys: album, title, comments (list of (stream_index, comment)).
- title: merged from all sources (last wins)
- comments: list of (stream_index, comment) tuples
""" """
cmd = [ cmd = [
'ffprobe', '-v', 'quiet', 'ffprobe', '-v', 'quiet',
@@ -190,34 +136,381 @@ def get_metadata(input_file: str) -> dict:
try: try:
data = json.loads(result.stdout) data = json.loads(result.stdout)
# Collect album and title (merged, last wins).
album = None album = None
title = None title = None
comments = [] # list of (stream_index, comment) comments = []
# Format tags.
fmt_tags = data.get('format', {}).get('tags', {}) fmt_tags = data.get('format', {}).get('tags', {})
album = fmt_tags.get('album') or album album = fmt_tags.get('album') or album
title = fmt_tags.get('title') or title title = fmt_tags.get('title') or title
# Format does not have a stream index; we'll treat it as -1 if needed.
# Stream tags.
for idx, stream in enumerate(data.get('streams', [])): for idx, stream in enumerate(data.get('streams', [])):
stream_tags = stream.get('tags', {}) stream_tags = stream.get('tags', {})
# Album and title: update if present.
if 'album' in stream_tags: if 'album' in stream_tags:
album = stream_tags['album'] album = stream_tags['album']
if 'title' in stream_tags: if 'title' in stream_tags:
title = stream_tags['title'] title = stream_tags['title']
# Comment: collect all occurrences.
if 'comment' in stream_tags: if 'comment' in stream_tags:
comments.append((idx, stream_tags['comment'])) comments.append((idx, stream_tags['comment']))
return { return {'album': album, 'title': title, 'comments': comments}
'album': album,
'title': title,
'comments': comments
}
except (json.JSONDecodeError, KeyError): except (json.JSONDecodeError, KeyError):
return {'album': None, 'title': None, 'comments': []} return {'album': None, 'title': None, 'comments': []}
def get_container_format(input_file: str) -> Optional[str]:
"""
Retrieve the container format name (e.g., 'mp4', 'mp3', 'mkv') from the input file.
Args:
input_file: Path to the media file.
Returns:
Container format name (normalized) or None if detection fails.
"""
cmd = [
'ffprobe', '-v', 'error',
'-show_entries', 'format=format_name',
'-of', 'default=noprint_wrappers=1:nokey=1',
input_file
]
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
if result.returncode != 0:
return None
format_name = result.stdout.strip().split(',')[0] # take first if multiple
if not format_name:
return None
# Normalize common aliases to names used in CONTAINER_INFO
mapping = {
'mpeg': 'mp3',
'mp2': 'mp3',
'mp4': 'mp4',
'm4a': 'mp4',
'mov': 'mp4',
'3gp': 'mp4',
'matroska': 'mkv',
'webm': 'mkv',
'ogg': 'ogg',
'flac': 'flac',
'wav': 'wav',
'aac': 'aac',
'opus': 'opus',
'mp3': 'mp3',
'adts': 'aac',
'amr': 'amr',
}
return mapping.get(format_name, format_name)
MAX_COVER_IMAGE_SIZE_MB = 4
def has_cover_or_video(input_file: str) -> bool:
"""
Check if the input file contains a cover image (attached picture) or any video track.
Returns:
True if a cover image or video stream is detected, False otherwise.
"""
cmd = [
'ffprobe', '-v', 'quiet',
'-print_format', 'json',
'-select_streams', 'v',
'-show_entries', 'stream=codec_type,codec_name,disposition',
input_file
]
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
if result.returncode != 0:
return False
try:
data = json.loads(result.stdout)
streams = data.get('streams', [])
return len(streams) > 0
except (json.JSONDecodeError, KeyError):
return False
def validate_cover_images(cover_images: List[str], num_tracks: int) -> None:
"""
Validate cover image(s) before splitting.
Checks:
- Each file exists
- Only PNG and JPEG formats are accepted
- Single image OR count matches number of tracks
- File size warning for images > 4 MB
Args:
cover_images: List of cover image paths (single image or multiple).
num_tracks: Number of tracks in the tracklist.
Raises:
ValueError: If validation fails.
"""
if len(cover_images) == 0:
return
if len(cover_images) == 1 and num_tracks > 1:
# Single image is fine - will be reused for all tracks
pass
elif len(cover_images) == num_tracks:
pass
else:
raise ValueError(
f"Cover image count ({len(cover_images)}) must be 1 or match "
f"the number of tracks ({num_tracks})."
)
for img_path in cover_images:
if not os.path.exists(img_path):
raise ValueError(f"Cover image not found: {img_path}")
ext = os.path.splitext(img_path)[1].lower()
if ext not in ('.png', '.jpg', '.jpeg'):
raise ValueError(
f"Unsupported cover image format '{ext}' for '{img_path}'. "
f"Only PNG and JPEG are supported."
)
size_mb = os.path.getsize(img_path) / (1024 * 1024)
if size_mb > MAX_COVER_IMAGE_SIZE_MB:
print(
f"Warning: Cover image '{img_path}' is {size_mb:.1f} MB "
f"(exceeds {MAX_COVER_IMAGE_SIZE_MB} MB limit). "
f"Large images may cause issues."
)
def is_attached_picture(input_file: str) -> bool:
"""
Check if the input file has a video stream that is an attached picture (cover art).
Detection logic:
1. If there is a video stream with disposition.attached_pic == 1, return True.
2. Otherwise, if there is exactly one video stream and its codec is an image
format (PNG, MJPEG, JPEG, GIF, BMP), return True.
Returns:
True if a cover image is detected, False otherwise.
"""
cmd = [
'ffprobe', '-v', 'quiet',
'-print_format', 'json',
'-select_streams', 'v',
'-show_entries', 'stream=codec_name,disposition',
input_file
]
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
if result.returncode != 0:
return False
try:
data = json.loads(result.stdout)
streams = data.get('streams', [])
if not streams:
return False
# Check each stream
for stream in streams:
codec = stream.get('codec_name', '').lower()
disposition = stream.get('disposition', {})
# If attached_pic is set, it's a cover image
if disposition.get('attached_pic') == 1:
return True
# If not, check if it's an image codec and we have exactly one video stream
if codec in ('png', 'mjpeg', 'jpeg', 'gif', 'bmp'):
# If there is exactly one video stream, treat it as cover
if len(streams) == 1:
return True
return False
except (json.JSONDecodeError, KeyError):
return False
def extract_cover_image(input_file: str, output_path: str) -> bool:
"""
Extract the first frame of the video stream (assumed to be an attached picture)
and save it to output_path.
Returns:
True if extraction succeeded, False otherwise.
"""
cmd = [
'ffmpeg', '-i', input_file,
'-map', '0:v:0',
'-frames:v', '1',
'-y',
output_path
]
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
if result.returncode != 0:
print(f"Failed to extract cover image: {result.stderr}")
return False
return True
def _build_inputs(cmd: List[str], input_file: str, cover_image_path: Optional[str]) -> None:
"""Add input files to the command."""
if cover_image_path:
cmd.extend(['-i', cover_image_path])
cmd.extend(['-i', input_file])
def _build_time_options(cmd: List[str], start_seconds: int, duration_seconds: int) -> None:
"""Add time-based options to the command."""
cmd.extend(['-ss', format_time(start_seconds), '-t', format_time(duration_seconds)])
def _build_metadata(cmd: List[str], metadata: Optional[Dict]) -> None:
"""Add metadata options to the command."""
cmd.append('-map_metadata')
cmd.append('-1')
if metadata:
for key, value in metadata.items():
if value is not None and value != '':
cmd.extend(['-metadata', f"{key}={value}"])
def _build_cover_image_mapping(
cmd: List[str],
audio_codec: Optional[str],
video_codec: Optional[str],
video_quality: Optional[int],
) -> None:
"""Build stream mapping for cover image extraction (audio + cover video)."""
cmd.extend(['-map', '1:a:0', '-map', '0:v:0'])
if video_codec and video_codec != 'copy':
cmd.extend(['-c:v', video_codec])
else:
cmd.extend(['-c:v', 'png'])
if audio_codec and audio_codec != 'copy':
cmd.extend(['-c:a', audio_codec])
else:
cmd.extend(['-c:a', 'copy'])
# Preserve attached_pic disposition for cover image
cmd.extend(['-disposition', 'attached_pic'])
cmd.append('-sn')
if video_quality is not None:
cmd.extend(['-q:v', str(video_quality)])
def _build_standard_mapping(
cmd: List[str],
stream_info: Dict,
audio_codec: Optional[str],
video_codec: Optional[str],
subtitle_codec: Optional[str],
video_quality: Optional[int],
drop_video: bool,
drop_subs: bool,
) -> None:
"""Build stream mapping for standard extraction (no cover image)."""
if drop_video and drop_subs:
cmd.extend(['-map', '0:a:0'])
elif drop_video:
cmd.extend(['-map', '0:a:0', '-map', '0:s?'])
elif drop_subs:
cmd.extend(['-map', '0:a:0', '-map', '0:v:0'])
else:
cmd.extend(['-map', '0'])
if audio_codec and audio_codec != 'copy':
cmd.extend(['-c:a', audio_codec])
else:
cmd.extend(['-c:a', 'copy'])
if not drop_video and stream_info.get('has_video'):
if video_codec and video_codec != 'copy':
cmd.extend(['-c:v', video_codec])
if video_quality is not None:
cmd.extend(['-q:v', str(video_quality)])
else:
cmd.extend(['-c:v', 'copy'])
else:
cmd.append('-vn')
if not drop_subs and stream_info.get('has_subtitle'):
if subtitle_codec and subtitle_codec != 'copy':
cmd.extend(['-c:s', subtitle_codec])
else:
cmd.extend(['-c:s', 'copy'])
else:
cmd.append('-sn')
def _build_format(cmd: List[str], format_opt: Optional[str]) -> None:
"""Add output format option if specified."""
if format_opt:
ffmpeg_format = next((c['ffmpeg'] for c in CONTAINER_INFO if c['name'] == format_opt), format_opt)
cmd.extend(['-f', ffmpeg_format])
def _build_output(cmd: List[str], output_path: str) -> None:
"""Add output file to the command."""
cmd.extend(['-y', output_path])
def build_ffmpeg_command(
input_file: str,
start_seconds: int,
duration_seconds: int,
output_path: str,
stream_info: Dict,
format_opt: Optional[str],
audio_codec: Optional[str] = 'copy',
video_codec: Optional[str] = 'copy',
subtitle_codec: Optional[str] = 'copy',
metadata: Optional[Dict] = None,
cover_image_path: Optional[str] = None,
video_quality: Optional[int] = None,
drop_video: bool = False,
drop_subs: bool = False,
) -> List[str]:
"""
Construct the FFmpeg command line as a list of arguments.
Args:
input_file: Path to the input media file.
start_seconds: Start time for the segment (in seconds).
duration_seconds: Duration of the segment (in seconds).
output_path: Destination path for the output file.
stream_info: Dictionary from get_stream_info().
format_opt: Output container format (e.g., 'mp3', 'mkv').
audio_codec: Audio codec to use ('copy' or encoder name like 'libopus').
video_codec: Video codec to use ('copy' or encoder name).
subtitle_codec: Subtitle codec to use ('copy' or encoder name).
metadata: Optional dict of metadata key/value pairs to write.
cover_image_path: Path to extracted cover image (if any).
video_quality: Quality value for video encoder (e.g., 1-31, lower=better).
drop_video: If True, remove video streams.
drop_subs: If True, remove subtitle streams.
Returns:
A list of commandline arguments suitable for subprocess.run().
"""
cmd = ['ffmpeg']
_build_inputs(cmd, input_file, cover_image_path)
_build_time_options(cmd, start_seconds, duration_seconds)
_build_metadata(cmd, metadata)
if cover_image_path:
_build_cover_image_mapping(cmd, audio_codec, video_codec, video_quality)
else:
_build_standard_mapping(
cmd, stream_info, audio_codec, video_codec, subtitle_codec,
video_quality, drop_video, drop_subs
)
_build_format(cmd, format_opt)
_build_output(cmd, output_path)
return cmd
+12 -1
View File
@@ -41,7 +41,18 @@ def build_filename(track, idx, extension, args):
clean_filename = apply_replacement(raw_filename, clean_filename = apply_replacement(raw_filename,
args.bad_chars, args.bad_chars,
args.replacement_char) args.replacement_char)
clean_filename = cleanup_good_chars(clean_filename, args.replacement_char) # Split off the file extension before cleanup so trailing
# replacement chars don't leak into the name portion.
name_part, _, ext_part = clean_filename.rpartition('.')
clean_filename = cleanup_good_chars(name_part, args.replacement_char)
# Strip leading/trailing separator characters (replacement char,
# hyphen, etc.) that may result from empty fields or bad-char
# sequences adjacent to template separators.
clean_filename = clean_filename.strip(f'{args.replacement_char}-')
# Fallback: if cleanup leaves an empty name, use the track number.
if not clean_filename:
clean_filename = f"{idx:02d}"
clean_filename = f"{clean_filename}.{ext_part}"
else: else:
clean_filename = raw_filename clean_filename = raw_filename
# Warn about unsafe characters. # Warn about unsafe characters.
+110 -28
View File
@@ -1,55 +1,137 @@
# audio_splitter/formats.py
"""Container format decision and validation.""" """Container format decision and validation."""
from .constants import FORMAT_INFO from typing import Dict, Optional
from .constants import (
CONTAINER_NAMES,
CONTAINER_INFO,
CODEC_TO_CONTAINER_MAP,
COMPATIBILITY_MATRIX,
is_audio_codec_supported,
is_video_codec_supported,
)
from .defaults import DEFAULT_FORMAT
def determine_output_format(stream_info, user_format, transcode_audio): def determine_default_format(container: Optional[str], codec: Optional[str]) -> Optional[str]:
"""
Given the container format and audio codec, determine the recommended output format.
Uses the CODEC_TO_CONTAINER_MAP to map codec → container.
If the codec is not found, it falls back to the container.
Args:
container: Container name (e.g., 'ogg', 'mp4', 'mkv') as returned by get_container_format().
codec: Audio codec name (e.g., 'opus', 'aac', 'mp3') as returned by get_audio_codec().
Returns:
Format name (e.g., 'opus', 'm4a', 'mp3') or None if unknown.
"""
if not container:
return None
if codec and codec in CODEC_TO_CONTAINER_MAP:
fmt = CODEC_TO_CONTAINER_MAP[codec]
if fmt in CONTAINER_NAMES:
return fmt
if container in CONTAINER_NAMES:
return container
return None
def determine_output_format(stream_info: Dict, user_format: Optional[str],
transcode_audio: Optional[str], input_file: Optional[str] = None) -> str:
""" """
Decide which container format to use. Decide which container format to use.
Args: If user_format is provided, map it to the correct container if it's a codec name.
stream_info: Dict from get_stream_info(). Else, try to detect the input file's container and codec, and use the recommended format.
user_format: Userrequested format (or None). If detection fails or format is not supported, fallback to:
transcode_audio: Audio codec to transcode to (or None). - MKV if video/subtitles exist
- MP3 if the audio codec is MP3
Returns: - MP4 (M4A) otherwise
A format name that exists in FORMAT_INFO.
""" """
if user_format: if user_format:
# Map codec names to their correct containers
# e.g., 'opus' -> 'ogg', 'aac' -> 'mp4', etc.
if user_format in CODEC_TO_CONTAINER_MAP:
return CODEC_TO_CONTAINER_MAP[user_format]
return user_format return user_format
# If video or subtitles exist, use MKV (which supports everything). if input_file:
if stream_info['has_video'] or stream_info['has_subtitle']: try:
return 'matroska' from .ffmpeg import get_container_format, get_audio_codec
container = get_container_format(input_file)
audio_codec = get_audio_codec(input_file)
fmt = determine_default_format(container, audio_codec)
if fmt in CONTAINER_NAMES:
return fmt
except Exception:
pass
# Audioonly: choose based on the current audio codec. # Fallback
if stream_info.get('has_video') or stream_info.get('has_subtitle'):
return 'mkv'
audio_codec = stream_info.get('audio_codec', '') audio_codec = stream_info.get('audio_codec', '')
if audio_codec == 'mp3': if audio_codec == 'mp3':
return 'mp3' return 'mp3'
else: else:
return 'mp4' # .m4a return 'mp4'
def validate_format_compatibility(format_name, stream_info, drop_video, drop_subs): def validate_format_compatibility(
container: str,
stream_info: Dict,
drop_video: bool,
drop_subs: bool,
input_file: Optional[str] = None,
audio_codec: Optional[str] = None,
video_codec: Optional[str] = None,
) -> None:
""" """
Ensure the chosen container can accommodate the streams we intend to keep. Ensure the chosen container and codec combination is valid.
Raises: Raises:
ValueError: If the format is incompatible with the intended streams. ValueError: If the combination is incompatible.
""" """
info = FORMAT_INFO.get(format_name) info = next((c for c in CONTAINER_INFO if c['name'] == container), None)
if not info: if not info:
print(f"Warning: Unknown format '{format_name}'. Proceeding, but may fail.") print(f"Warning: Unknown container '{container}'. Proceeding, but may fail.")
return return
if info['audio_only']: # Check if container is audio-only and video is present (unless dropped)
if stream_info['has_video'] and not drop_video: if not info['supports_video'] and stream_info.get('has_video') and not drop_video:
raise ValueError(
f"Container '{container}' does not support video streams. "
"Please use --drop-video or choose a container that supports video (e.g., MKV, MP4)."
)
# Determine actual audio codec for validation
# When 'copy' is used, we must still validate the input codec against the container
actual_audio_codec = audio_codec if audio_codec and audio_codec != 'copy' else stream_info.get('audio_codec')
if actual_audio_codec:
if not is_audio_codec_supported(container, actual_audio_codec):
raise ValueError( raise ValueError(
f"Format '{format_name}' does not support video streams. " f"Container '{container}' does not support audio codec '{actual_audio_codec}'. "
"Please use --drop-video or choose a container that supports video." f"Please choose a different container or audio codec."
)
if stream_info['has_subtitle'] and not drop_subs:
raise ValueError(
f"Format '{format_name}' does not support subtitle streams. "
"Please use --drop-subs or choose a container that supports subtitles."
) )
# Check if video codec is supported (if video is present and not dropped)
if stream_info.get('has_video') and not drop_video:
# Determine the video codec from input file if not provided
if video_codec is None and input_file:
from .ffmpeg import get_video_codec
video_codec = get_video_codec(input_file)
# When 'copy' is used, validate the input video codec against the container
if video_codec == 'copy' and input_file:
from .ffmpeg import get_video_codec
video_codec = get_video_codec(input_file)
if video_codec:
if not is_video_codec_supported(container, video_codec):
raise ValueError(
f"Container '{container}' does not support video codec '{video_codec}'. "
f"Please choose a different container, drop video, or transcode video to a supported codec."
)
+167
View File
@@ -0,0 +1,167 @@
# audio_splitter/handlers.py
"""Handler system for cover image attachment.
This module provides a registry of handlers for different
codec + image combinations. Each handler is responsible for
attaching the cover image to the output file in the appropriate way.
"""
import os
import subprocess
from typing import Dict, Optional
def _run_opustags(input_file: str, cover_image_path: str, output_path: Optional[str] = None) -> bool:
"""
Run opustags to attach a cover image to an Opus file.
Args:
input_file: Path to the input Opus file.
cover_image_path: Path to the cover image.
output_path: Optional output path (if None, overwrites input).
Returns:
True if successful, False otherwise.
"""
cmd = ['opustags', '--set-cover', cover_image_path, input_file]
if output_path:
cmd.extend(['-o', output_path, '-y'])
else:
cmd.extend(['-i'])
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
if result.returncode != 0:
print(f"opustags failed: {result.stderr}")
return False
return True
def _handler_default(
input_file: str,
cover_image_path: str,
output_path: str,
stream_info: Dict,
audio_codec: str,
video_codec: str,
video_quality: Optional[int],
drop_video: bool,
drop_subs: bool,
) -> bool:
"""
Default handler: use ffmpeg with -disposition attached_pic.
This is the standard approach for formats like MP3, FLAC, etc.
"""
# This handler doesn't do anything - the cover is already handled
# by the ffmpeg command in core.py via build_ffmpeg_command()
# We just return True to indicate success.
return True
def _handler_opus_with_cover(
input_file: str,
cover_image_path: str,
output_path: str,
stream_info: Dict,
audio_codec: str,
video_codec: str,
video_quality: Optional[int],
drop_video: bool,
drop_subs: bool,
) -> bool:
"""
Handler for Opus files with cover image.
Uses opustags to attach the cover image after the file is processed.
"""
return _run_opustags(output_path, cover_image_path)
def _handler_mp3_with_cover(
input_file: str,
cover_image_path: str,
output_path: str,
stream_info: Dict,
audio_codec: str,
video_codec: str,
video_quality: Optional[int],
drop_video: bool,
drop_subs: bool,
) -> bool:
"""
Handler for MP3 files with cover image.
Uses ffmpeg with -disposition attached_pic.
"""
# MP3 handler - the cover is already attached by ffmpeg in core.py
return True
def _handler_flac_with_cover(
input_file: str,
cover_image_path: str,
output_path: str,
stream_info: Dict,
audio_codec: str,
video_codec: str,
video_quality: Optional[int],
drop_video: bool,
drop_subs: bool,
) -> bool:
"""
Handler for FLAC files with cover image.
Uses ffmpeg with -disposition attached_pic.
"""
# FLAC handler - the cover is already attached by ffmpeg in core.py
return True
# Handler registry: maps (output_container, input_codec) to handler function
HANDLER_REGISTRY: Dict[tuple, callable] = {
('opus', 'opus'): _handler_opus_with_cover,
('ogg', 'opus'): _handler_opus_with_cover,
('mp3', 'mp3'): _handler_mp3_with_cover,
('flac', 'flac'): _handler_flac_with_cover,
}
def get_handler(output_container: str, input_audio_codec: Optional[str] = None):
"""
Get the appropriate handler for the given container and input codec.
Args:
output_container: Output container format (e.g., 'opus', 'mp3', 'flac').
input_audio_codec: Input audio codec (e.g., 'opus', 'mp3', 'flac').
Returns:
Handler function, or the default handler if no specific handler is found.
"""
if input_audio_codec:
key = (output_container, input_audio_codec)
if key in HANDLER_REGISTRY:
return HANDLER_REGISTRY[key]
# Fall back to container-only key
if (output_container, None) in HANDLER_REGISTRY:
return HANDLER_REGISTRY[(output_container, None)]
# Default handler
return _handler_default
def needs_drop_video(output_container: str, input_audio_codec: Optional[str] = None) -> bool:
"""
Check if the handler requires dropping video even if user didn't specify --drop-video.
Args:
output_container: Output container format.
input_audio_codec: Input audio codec.
Returns:
True if video should be dropped, False otherwise.
"""
handler = get_handler(output_container, input_audio_codec)
# The opus handler requires dropping video
return handler == _handler_opus_with_cover
+147 -89
View File
@@ -1,139 +1,194 @@
"""Commandline interface and entry point.""" #!/usr/bin/env python3
"""
Audio Splitter CommandLine Interface
Split an audio file into tracks using a tracklist file.
Usage:
audio_splitter input.mp3 tracklist.txt [OPTIONS]
"""
import os import os
import sys import sys
import subprocess import subprocess
import argparse import argparse
from .constants import DEFAULT_BAD_CHARS from .defaults import (
from .tracklist import read_tracklist, parse_format DEFAULT_FORMAT,
DEFAULT_OUTPUT_TEMPLATE,
DEFAULT_REPLACEMENT_CHAR,
DEFAULT_BAD_CHARS,
DEFAULT_TRACKLIST_FORMAT,
DEFAULT_ALBUM,
DEFAULT_COMMENT,
DEFAULT_COMMENT_STREAM,
DEFAULT_COMMENT_SEPARATOR,
DEFAULT_NO_COMMENT,
DEFAULT_MERGE_COMMENTS,
DEFAULT_DROP_VIDEO,
DEFAULT_DROP_SUBS,
DEFAULT_NUMBER_TRACKS,
DEFAULT_REPLACE_BAD_CHARS,
DEFAULT_SKIP_EXISTING,
DEFAULT_DELETE_ORIGINAL,
)
from .constants import CONTAINER_NAMES
from .core import split_audio from .core import split_audio
from .tracklist import read_tracklist, parse_format
from .ffmpeg import has_cover_or_video, validate_cover_images
def main(): def main():
"""Parse arguments and start the splitting process."""
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
description="Split an audio file into tracks using a tracklist.", description="Split an audio file into tracks using a tracklist.",
epilog="Tracklist format: mm:ss track_name - author_name" epilog="Tracklist format: mm:ss track_name - author_name (or custom with --tracklist-format)"
) )
# Positional arguments. # Positional
parser.add_argument('input_file', help='Input audio/video file') parser.add_argument('input_file', help='Input audio file')
parser.add_argument('tracklist_file', help='Tracklist file') parser.add_argument('tracklist_file', help='Tracklist file')
# Optional arguments. # Container and codec options
parser.add_argument( parser.add_argument(
'--output-dir', '-o', '--container',
help='Output directory for split tracks (default: <input_basename>_splits)' default=None,
help="Output container format (auto-detect if not specified)"
) )
parser.add_argument( parser.add_argument(
'--format', '--audio-codec',
help='Output container format (e.g., mp3, m4a, mkv, mp4, ogg, opus)' default='copy',
help="Audio codec (copy or encoder name, e.g., libopus)"
) )
parser.add_argument( parser.add_argument(
'--transcode-to', '--video-codec',
help='Re-encode audio to this codec (e.g., libmp3lame, aac, libopus)' default='copy',
help="Video codec (copy or encoder name, e.g., libx264)"
)
parser.add_argument(
'--subtitle-codec',
default='copy',
help="Subtitle codec (copy or encoder name, e.g., srt)"
)
parser.add_argument(
'--video-quality', '-vq',
type=int,
default=None,
help="Video quality (integer, encoder-specific; usually 1-31, lower=better). "
"If omitted, FFmpeg default is used."
) )
parser.add_argument( parser.add_argument(
'--drop-video', '--drop-video',
action='store_true', action='store_true',
help='Remove video streams from output' default=DEFAULT_DROP_VIDEO,
help="Drop video streams"
) )
parser.add_argument( parser.add_argument(
'--drop-subs', '--drop-subs',
action='store_true', action='store_true',
help='Remove subtitle streams from output' default=DEFAULT_DROP_SUBS,
help="Drop subtitle streams"
) )
# Filename options
parser.add_argument( parser.add_argument(
'--number-tracks', '--number-tracks',
action='store_true', action='store_true',
help='Prepend track number to output filenames (convenience; use %%num in template for full control)' default=DEFAULT_NUMBER_TRACKS,
help="Prepend track numbers"
)
parser.add_argument(
'--output-template',
default=DEFAULT_OUTPUT_TEMPLATE,
help="Output filename template (default: %(default)s)"
) )
parser.add_argument( parser.add_argument(
'--replace-bad-chars', '--replace-bad-chars',
action='store_true', action='store_true',
help='Replace problematic characters in filenames (default: off)' default=DEFAULT_REPLACE_BAD_CHARS,
help="Replace bad characters"
) )
parser.add_argument( parser.add_argument(
'--replacement-char', '--replacement-char',
default='_', default=DEFAULT_REPLACEMENT_CHAR,
help='Character used as replacement (default: "_")' help="Replacement character (default: %(default)s)"
) )
parser.add_argument( parser.add_argument(
'--bad-chars', '--bad-chars',
default=DEFAULT_BAD_CHARS, default=DEFAULT_BAD_CHARS,
help='String of characters to replace (default includes space and single quote)' help="Bad characters to replace (default: %(default)s)"
) )
parser.add_argument( parser.add_argument(
'--skip-existing', '--skip-existing',
action='store_true', action='store_true',
help='Skip extraction if output file already exists (default: overwrite)' default=DEFAULT_SKIP_EXISTING,
) help="Skip existing output files"
parser.add_argument(
'--tracklist-format',
default='%ts %tn - %an',
help='Format of each line in the tracklist using placeholders: '
'%%ts (timestamp), %%tn (track name), %%an (author), %%al (album), '
'%%date (date/year), %%ext (file extension). '
'Default: "%%ts %%tn - %%an"'
)
parser.add_argument(
'--output-template',
default='%an-%tn.%ext',
help='Template for output filenames using placeholders: '
'%%tn (track name), %%an (author), %%al (album), '
'%%date (date/year), %%ext (file extension), %%num (track number). '
'Default: "%%an-%%tn.%%ext"'
)
parser.add_argument(
'--dry-run',
action='store_true',
help='Parse and display the tracklist without splitting any files'
) )
# Metadata options. # Metadata
parser.add_argument( parser.add_argument('--album', default=DEFAULT_ALBUM, help="Album name")
'--album', parser.add_argument('--comment', default=DEFAULT_COMMENT, help="Comment")
help='Set album name in output metadata (overrides parsed %%al and original album)'
)
parser.add_argument(
'--comment',
help='Explicit comment text (overrides all other comment settings)'
)
parser.add_argument( parser.add_argument(
'--no-comment', '--no-comment',
action='store_true', action='store_true',
help='Explicitly ignore any comment (no comment written)' default=DEFAULT_NO_COMMENT,
help="Ignore comment"
) )
parser.add_argument( parser.add_argument(
'--comment-stream', '--comment-stream',
type=int, type=int,
default=None, default=DEFAULT_COMMENT_STREAM,
help='Select comment from a specific stream index (0based). Default: first stream with a comment.' help="Comment stream index"
) )
parser.add_argument( parser.add_argument(
'--merge-comments', '--merge-comments',
action='store_true', action='store_true',
help='Merge all comments from all streams into one (separated by --comment-separator)' default=DEFAULT_MERGE_COMMENTS,
help="Merge all comments"
) )
parser.add_argument( parser.add_argument(
'--comment-separator', '--comment-separator',
default='; ', default=DEFAULT_COMMENT_SEPARATOR,
help='Separator used when merging comments (default: "; ")' help="Separator for merged comments (default: %(default)s)"
) )
# NEW: Delete original after successful split. # Tracklist format
parser.add_argument(
'--tracklist-format',
default=DEFAULT_TRACKLIST_FORMAT,
help="Tracklist format (default: %(default)s)"
)
# Cover image
parser.add_argument(
'--cover-image',
nargs='+',
metavar='IMAGE',
default=None,
help="Cover image path(s). Single image applied to all tracks, "
"or one per track (must match track count)."
)
# Other
parser.add_argument( parser.add_argument(
'--delete-original', '--delete-original',
action='store_true', action='store_true',
help='Delete the original input file after successful splitting (default: keep)' default=DEFAULT_DELETE_ORIGINAL,
help="Delete original file after split"
)
parser.add_argument(
'--dry-run',
action='store_true',
help="Parse and display tracklist without splitting"
)
parser.add_argument(
'--output-dir', '-o',
default=None,
help="Output directory (default: <input_basename>_splits)"
) )
args = parser.parse_args() args = parser.parse_args()
# -------------------------------------------------------------------------- # Validate input
# Input validation
# --------------------------------------------------------------------------
if not os.path.exists(args.input_file): if not os.path.exists(args.input_file):
print(f"Error: Input file not found: {args.input_file}") print(f"Error: Input file not found: {args.input_file}")
sys.exit(1) sys.exit(1)
@@ -142,12 +197,13 @@ def main():
print(f"Error: Tracklist file not found: {args.tracklist_file}") print(f"Error: Tracklist file not found: {args.tracklist_file}")
sys.exit(1) sys.exit(1)
# Ensure the replacement character is a single character. # Validate container if provided
if len(args.replacement_char) != 1: if args.container and args.container not in CONTAINER_NAMES:
print("Error: --replacement-char must be a single character.") print(f"Error: Invalid container '{args.container}'. "
f"Valid containers: {', '.join(sorted(CONTAINER_NAMES))}.")
sys.exit(1) sys.exit(1)
# Check that FFmpeg is installed. # Check FFmpeg
try: try:
subprocess.run(['ffmpeg', '-version'], capture_output=True, check=True) subprocess.run(['ffmpeg', '-version'], capture_output=True, check=True)
except (subprocess.CalledProcessError, FileNotFoundError): except (subprocess.CalledProcessError, FileNotFoundError):
@@ -155,14 +211,14 @@ def main():
print(" - https://ffmpeg.org/download.html") print(" - https://ffmpeg.org/download.html")
sys.exit(1) sys.exit(1)
# Parse the tracklist using the userprovided format. # Parse tracklist format
try: try:
tokens = parse_format(args.tracklist_format) tokens = parse_format(args.tracklist_format)
except ValueError as error: except ValueError as e:
print(f"Error in --tracklist-format: {error}") print(f"Error in --tracklist-format: {e}")
sys.exit(1) sys.exit(1)
# Read and parse the tracklist file. # Read tracklist
tracks = read_tracklist(args.tracklist_file, tokens) tracks = read_tracklist(args.tracklist_file, tokens)
if not tracks: if not tracks:
print("Error: No valid tracks found in tracklist file.") print("Error: No valid tracks found in tracklist file.")
@@ -170,7 +226,21 @@ def main():
print(f"Found {len(tracks)} tracks.") print(f"Found {len(tracks)} tracks.")
# Dryrun mode: display parsed data and exit. # Validate cover images if provided
if args.cover_image:
# Check if input already has cover image or video track
# Allow if --drop-video is specified (user wants to discard existing video)
if has_cover_or_video(args.input_file) and not args.drop_video:
print("Error: Input file already contains a cover image or video track. "
"Remove it first, or use --drop-video to discard video streams.")
sys.exit(1)
try:
validate_cover_images(args.cover_image, len(tracks))
except ValueError as e:
print(f"Error: {e}")
sys.exit(1)
if args.dry_run: if args.dry_run:
print("\nParsed tracklist:") print("\nParsed tracklist:")
print("-" * 60) print("-" * 60)
@@ -184,34 +254,22 @@ def main():
print(f"{idx:3d} | " + " | ".join(values)) print(f"{idx:3d} | " + " | ".join(values))
print("-" * 60) print("-" * 60)
print("Dryrun complete. No files were created.") print("Dryrun complete. No files were created.")
sys.exit(0) return
# Determine the output directory. # Determine output directory
if args.output_dir: if args.output_dir:
output_dir = args.output_dir output_dir = args.output_dir
print(f"Using custom output directory: {output_dir}")
else: else:
base_name = os.path.splitext(os.path.basename(args.input_file))[0] base_name = os.path.splitext(os.path.basename(args.input_file))[0]
output_dir = base_name + "_splits" output_dir = base_name + "_splits"
print(f"Using default output directory: {output_dir}")
# Run the splitter. # Run split
try: try:
split_audio(args.input_file, output_dir, tracks, args) split_audio(args.input_file, output_dir, tracks, args)
except (RuntimeError, ValueError) as error: except Exception as e:
print(f"Error: {error}") print(f"Error during split: {e}")
sys.exit(1) sys.exit(1)
# --------------------------------------------------------------------------
# Delete original file if requested and successful.
# --------------------------------------------------------------------------
if args.delete_original:
try:
os.remove(args.input_file)
print(f"Deleted original file: {args.input_file}")
except OSError as e:
print(f"Warning: Could not delete original file: {e}")
print("Done!") print("Done!")
+11
View File
@@ -73,4 +73,15 @@ def resolve_end_times(track_times, total_duration):
if end_sec <= start_sec: if end_sec <= start_sec:
raise ValueError(f"Track {idx+1}: end time ({end_sec}) is not after start ({start_sec})") raise ValueError(f"Track {idx+1}: end time ({end_sec}) is not after start ({start_sec})")
resolved.append((start_sec, end_sec)) resolved.append((start_sec, end_sec))
# Warn about overlapping intervals
for idx in range(len(resolved) - 1):
cur_end = resolved[idx][1]
next_start = resolved[idx + 1][0]
if cur_end > next_start:
print(
f"Warning: Track {idx+1} ends at {cur_end}s but Track {idx+2} starts at "
f"{next_start}s — timestamps overlap by {cur_end - next_start:.1f}s."
)
return resolved return resolved
+44
View File
@@ -0,0 +1,44 @@
# ------------------------------------------------------------------------------
# HTTPS Server Block (TLS Termination)
# ------------------------------------------------------------------------------
server {
listen 443 ssl;
server_name your.domain.tld;
ssl_certificate path;
ssl_certificate_key path;
# --------------------------------------------------------------------------
# Security Headers
# --------------------------------------------------------------------------
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
# --------------------------------------------------------------------------
# Proxy to Frontend Container (everything goes through it)
# --------------------------------------------------------------------------
location / {
# Forward all traffic to the frontend container
proxy_pass http://127.0.0.1:5173; # <-- Frontend host port (adjust if needed)
proxy_http_version 1.1;
# Headers for correct client IP and protocol forwarding
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# The frontend container handles WebSocket upgrades internally,
# but we still need to pass the upgrade headers through.
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
# Increase timeouts for long-running operations
proxy_read_timeout 600s;
proxy_send_timeout 600s;
# Allow large file uploads (matches client_max_body_size in frontend NGINX)
client_max_body_size 500M;
}
}
+26
View File
@@ -0,0 +1,26 @@
services:
backend:
build:
context: .
dockerfile: web/backend/Dockerfile
#image: max/audio_splitter_backend:latest
ports:
- "${BACKEND_PORT:-8000}:8000"
volumes:
#- "${BACKEND_DATA_DIR:-/var/lib/audio_splitter_data}:/tmp/audio_splitter_web"
- "/tmp/test:/tmp/audio_splitter_web"
environment:
- PYTHONUNBUFFERED=1
- DEBUG=${DEBUG:-0}
restart: unless-stopped
frontend:
build:
context: .
dockerfile: web/frontend/Dockerfile
#image: max/audio_splitter_frontend:latest
ports:
- "${FRONTEND_PORT:-5173}:80"
depends_on:
- backend
restart: unless-stopped
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""
Generate TypeScript constants from audio_splitter/defaults.py.
"""
import importlib.util
import json
import sys
from pathlib import Path
# Get the directory where this script is located
SCRIPT_DIR = Path(__file__).parent.absolute()
# The defaults.py is in the same directory as the script
DEFAULTS_PATH = SCRIPT_DIR / "defaults.py"
# The frontend source is at SCRIPT_DIR.parent (i.e., /app)
# The generated file should be at /app/src/constants/generated.ts
FRONTEND_ROOT = SCRIPT_DIR.parent
OUTPUT_PATH = FRONTEND_ROOT / "src" / "constants" / "generated.ts"
def load_defaults_module():
spec = importlib.util.spec_from_file_location("defaults", DEFAULTS_PATH)
if spec is None:
raise RuntimeError(f"Could not load spec for {DEFAULTS_PATH}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def format_value(value):
"""Convert Python value to TypeScript literal."""
if value is None:
return "null"
if isinstance(value, bool):
return str(value).lower()
if isinstance(value, str):
# Use json.dumps to produce a properly escaped string literal
return json.dumps(value)
if isinstance(value, (int, float)):
return str(value)
if isinstance(value, list):
return f"[{', '.join(format_value(v) for v in value)}]"
return repr(value)
def main():
print(f"Generating TypeScript defaults from {DEFAULTS_PATH}")
defaults = load_defaults_module()
constants = {name: value for name, value in vars(defaults).items() if name.startswith("DEFAULT_")}
if not constants:
print("No DEFAULT_* constants found.")
sys.exit(1)
lines = [
"// ============================================================================",
"// GENERATED FILE DO NOT EDIT MANUALLY.",
"// This file is generated from audio_splitter/defaults.py.",
"// Run `npm run generate` or `python scripts/generate_ts_defaults.py` to update.",
"// ============================================================================",
"",
]
for name, value in sorted(constants.items()):
ts_value = format_value(value)
lines.append(f"export const {name} = {ts_value};")
OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True)
OUTPUT_PATH.write_text("\n".join(lines) + "\n")
print(f"✅ Generated {OUTPUT_PATH}")
print(f" {len(constants)} constants exported.")
if __name__ == "__main__":
main()
+18
View File
@@ -0,0 +1,18 @@
__pycache__
*.pyc
*.pyo
*.pyd
.Python
*.so
*.egg
*.egg-info
dist
build
.venv
venv
.env
.git
.gitignore
README.md
Dockerfile
.dockerignore
+4
View File
@@ -0,0 +1,4 @@
MAX_UPLOAD_SIZE_MB=500
TEMP_DIR=/tmp/audio_splitter_web
CLEANUP_AFTER_SECONDS=3600
ALLOW_ORIGINS=http://localhost:5173,http://localhost:3000
+46
View File
@@ -0,0 +1,46 @@
FROM python:3.13-slim
# Install FFmpeg, opustags, system dependencies, and gosu from APT
RUN apt-get update && \
apt-get install -y --no-install-recommends \
ffmpeg \
opustags \
ca-certificates \
gosu \
&& \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
# Set Python environment variables
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1
# Set working directory
WORKDIR /app
# Copy requirements and install Python dependencies
COPY web/backend/requirements-web.txt .
RUN pip install --no-cache-dir -r requirements-web.txt
# Copy backend code
COPY web/backend /app/backend
# Copy and install audio_splitter package
COPY audio_splitter /app/audio_splitter
COPY setup.py pyproject.toml README.md /app/
RUN pip install --no-cache-dir /app
# Create a non-root user
RUN addgroup --system --gid 1000 appgroup && \
adduser --system --uid 1000 --ingroup appgroup appuser && \
chown -R appuser:appgroup /app
# Copy entrypoint script
COPY web/backend/docker-entrypoint.sh /docker-entrypoint.sh
RUN chmod +x /docker-entrypoint.sh
# Set entrypoint
ENTRYPOINT ["/docker-entrypoint.sh"]
# Expose port
EXPOSE 8000
+8
View File
@@ -0,0 +1,8 @@
# From the web/ directory
cd web
# Install dependencies
pip install -r requirements-web.txt
# Run the server (note the module path: backend.main)
uvicorn backend.main:app --reload --port 8000
+1
View File
@@ -0,0 +1 @@
"""Audio Splitter Web Backend"""
+3
View File
@@ -0,0 +1,3 @@
"""API route handlers."""
from . import upload, split, split_file, status, download, websocket, formats, info
+90
View File
@@ -0,0 +1,90 @@
"""Download endpoint for split results."""
from fastapi import APIRouter, HTTPException
from fastapi.responses import FileResponse
from zipfile import ZipFile
import os
from backend.config import settings
from backend.services.task_manager import task_manager
from backend.models.response import TaskStatus
router = APIRouter(prefix="/api", tags=["download"])
def _prepare_download(task_id: str):
"""Common logic to prepare and return the ZIP file."""
if not task_manager.has_task(task_id):
raise HTTPException(status_code=404, detail=f"Task {task_id} not found")
status = task_manager.get_status(task_id)
if status["status"] != TaskStatus.DONE:
raise HTTPException(
status_code=400,
detail=f"Task {task_id} is not complete. Current status: {status['status']}"
)
output_dir = settings.temp_dir / task_id / "output"
if not output_dir.exists() or not any(output_dir.iterdir()):
raise HTTPException(status_code=404, detail="No output files found")
zip_path = settings.temp_dir / task_id / "splits.zip"
with ZipFile(zip_path, "w") as zipf:
for file_path in output_dir.iterdir():
if file_path.is_file():
zipf.write(file_path, arcname=file_path.name)
return zip_path
@router.get("/download/{task_id}")
async def download_results(task_id: str):
zip_path = _prepare_download(task_id)
return FileResponse(
path=zip_path,
media_type="application/zip",
filename=f"{task_id}_splits.zip",
headers={"Content-Disposition": f"attachment; filename={task_id}_splits.zip"}
)
@router.get("/download/{task_id}/splits.zip")
async def download_results_as_zip(task_id: str):
"""Alias endpoint that provides a .zip suffix for easier curl usage."""
zip_path = _prepare_download(task_id)
return FileResponse(
path=zip_path,
media_type="application/zip",
filename="splits.zip",
headers={"Content-Disposition": "attachment; filename=splits.zip"}
)
# NEW: Endpoint for downloading individual tracks
@router.get("/download/{task_id}/{filename}")
async def download_single_track(task_id: str, filename: str):
"""
Download a single track file from the output directory.
"""
if not task_manager.has_task(task_id):
raise HTTPException(status_code=404, detail=f"Task {task_id} not found")
status = task_manager.get_status(task_id)
if status["status"] != TaskStatus.DONE:
raise HTTPException(
status_code=400,
detail=f"Task {task_id} is not complete. Current status: {status['status']}"
)
output_dir = settings.temp_dir / task_id / "output"
file_path = output_dir / filename
if not file_path.exists() or not file_path.is_file():
raise HTTPException(status_code=404, detail=f"File '{filename}' not found")
return FileResponse(
path=file_path,
filename=filename,
media_type="application/octet-stream",
headers={"Content-Disposition": f"attachment; filename={filename}"}
)
+20
View File
@@ -0,0 +1,20 @@
# web/backend/api/formats.py
"""Endpoint to expose format information to the frontend."""
from fastapi import APIRouter
from audio_splitter.constants import CONTAINER_INFO, CODEC_INFO, COMPATIBILITY_MATRIX
router = APIRouter(prefix="/api", tags=["formats"])
@router.get("/formats")
async def get_formats():
"""
Return the list of supported containers, codecs, and compatibility matrix.
"""
return {
"containers": CONTAINER_INFO,
"codecs": CODEC_INFO,
"compatibility": COMPATIBILITY_MATRIX,
}
+72
View File
@@ -0,0 +1,72 @@
"""Endpoint to retrieve stream information for an uploaded file."""
from fastapi import APIRouter, HTTPException
from backend.config import settings
from backend.services.file_manager import FileManager
from backend.services.task_manager import task_manager
# Import core functions
from audio_splitter.ffmpeg import get_stream_info, get_container_format, get_audio_codec
from audio_splitter.formats import determine_default_format
from audio_splitter.constants import CONTAINER_NAMES
from audio_splitter.defaults import DEFAULT_FORMAT
router = APIRouter(prefix="/api", tags=["info"])
@router.get("/info/{task_id}")
async def get_task_info(task_id: str):
"""
Return stream information (has_audio, has_video, has_subtitle, audio_codec)
for the uploaded file.
"""
if not task_manager.has_task(task_id):
raise HTTPException(status_code=404, detail=f"Task {task_id} not found")
input_path = FileManager.get_input_path(task_id)
if not input_path or not input_path.exists():
raise HTTPException(status_code=404, detail="Input file not found")
try:
info = get_stream_info(str(input_path))
return {
"task_id": task_id,
"has_audio": info["has_audio"],
"has_video": info["has_video"],
"has_subtitle": info["has_subtitle"],
"audio_codec": info["audio_codec"],
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to retrieve stream info: {str(e)}")
@router.get("/info/recommended-format/{task_id}")
async def get_recommended_format(task_id: str):
"""
Return the recommended output format (container name) for the uploaded file,
based on its container and audio codec.
"""
if not task_manager.has_task(task_id):
raise HTTPException(status_code=404, detail=f"Task {task_id} not found")
input_path = FileManager.get_input_path(task_id)
if not input_path or not input_path.exists():
raise HTTPException(status_code=404, detail="Input file not found")
try:
container = get_container_format(str(input_path))
codec = get_audio_codec(str(input_path))
fmt = determine_default_format(container, codec)
# Fallback if detection fails or format is unsupported
if fmt is None:
fmt = DEFAULT_FORMAT
if fmt not in CONTAINER_NAMES:
fmt = "mp3" # ultimate fallback
return {"format": fmt}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to determine format: {str(e)}")
+67
View File
@@ -0,0 +1,67 @@
"""Split task endpoint (JSON tracklist)."""
from fastapi import APIRouter, HTTPException, BackgroundTasks
from backend.models.request import SplitRequest
from backend.models.response import SplitResponse, TaskStatus
from backend.services.splitter import run_split_task
from backend.services.task_manager import task_manager
router = APIRouter(prefix="/api", tags=["split"])
@router.post("/split", response_model=SplitResponse)
async def start_split(request: SplitRequest, background_tasks: BackgroundTasks):
task_id = request.task_id
if not task_manager.has_task(task_id):
raise HTTPException(status_code=404, detail=f"Task {task_id} not found")
status = task_manager.get_status(task_id)
if status and status["status"] in (TaskStatus.PROCESSING, TaskStatus.DONE):
raise HTTPException(
status_code=409,
detail=f"Task {task_id} is already {status['status']}"
)
# Build options dict from request
options = {
"container": request.container,
"audio_codec": request.audio_codec,
"video_codec": request.video_codec,
"subtitle_codec": request.subtitle_codec,
"video_quality": request.video_quality,
"drop_video": request.drop_video,
"drop_subs": request.drop_subs,
"number_tracks": request.number_tracks,
"replace_bad_chars": request.replace_bad_chars,
"replacement_char": request.replacement_char,
"bad_chars": request.bad_chars,
"skip_existing": request.skip_existing,
"output_template": request.output_template,
"album": request.album,
"comment": request.comment,
"no_comment": request.no_comment,
"comment_stream": request.comment_stream,
"merge_comments": request.merge_comments,
"comment_separator": request.comment_separator,
}
task_manager.update_task(
task_id,
status=TaskStatus.PROCESSING,
progress=0,
message="Preparing to split..."
)
background_tasks.add_task(
run_split_task,
task_id,
request.tracklist,
options
)
return SplitResponse(
task_id=task_id,
status=TaskStatus.PROCESSING
)
+151
View File
@@ -0,0 +1,151 @@
"""Endpoint for splitting with a tracklist file upload."""
import json
from pathlib import Path
from typing import Optional
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks
from backend.config import settings
from backend.services.task_manager import task_manager
from backend.services.splitter import run_split_task
from backend.models.request import TracklistEntry
from backend.models.response import SplitResponse, TaskStatus
router = APIRouter(prefix="/api", tags=["split"])
from audio_splitter.tracklist import parse_format, read_tracklist
@router.post("/split-file", response_model=SplitResponse)
async def split_from_file(
background_tasks: BackgroundTasks,
task_id: str = Form(...),
tracklist_file: UploadFile = File(...),
# New fields
container: Optional[str] = Form(None),
audio_codec: str = Form("copy"),
video_codec: str = Form("copy"),
subtitle_codec: str = Form("copy"),
video_quality: Optional[int] = Form(None),
drop_video: bool = Form(False),
drop_subs: bool = Form(False),
number_tracks: bool = Form(False),
replace_bad_chars: bool = Form(False),
replacement_char: str = Form("_"),
bad_chars: str = Form(r'!@#№$;:%^&?*(){}[]\/<>+=~`\' '),
skip_existing: bool = Form(False),
output_template: str = Form("%an-%tn.%ext"),
album: Optional[str] = Form(None),
comment: Optional[str] = Form(None),
no_comment: bool = Form(False),
comment_stream: Optional[int] = Form(None),
merge_comments: bool = Form(False),
comment_separator: str = Form("; "),
options: str = Form("{}"), # backward-compatible, but we now use explicit fields
tracklist_format: str = Form("%ts %tn - %an"),
):
# Validate task exists
if not task_manager.has_task(task_id):
raise HTTPException(status_code=404, detail=f"Task {task_id} not found")
status = task_manager.get_status(task_id)
if status and status["status"] in (TaskStatus.PROCESSING, TaskStatus.DONE):
raise HTTPException(
status_code=409,
detail=f"Task {task_id} is already {status['status']}"
)
if not tracklist_file.filename.endswith(('.txt', '.text')):
raise HTTPException(
status_code=400,
detail="Tracklist file must be a text file (.txt or .text)"
)
try:
content = await tracklist_file.read()
text = content.decode('utf-8')
except UnicodeDecodeError:
raise HTTPException(
status_code=400,
detail="Tracklist file must be UTF-8 encoded"
)
if not text.strip():
raise HTTPException(
status_code=400,
detail="Tracklist file is empty"
)
# Parse tracklist using CLI logic
try:
tokens = parse_format(tracklist_format)
temp_tracklist_path = settings.temp_dir / task_id / "tracklist.txt"
temp_tracklist_path.parent.mkdir(parents=True, exist_ok=True)
temp_tracklist_path.write_text(text, encoding='utf-8')
tracklist_dicts = read_tracklist(str(temp_tracklist_path), tokens)
except Exception as e:
raise HTTPException(
status_code=400,
detail=f"Failed to parse tracklist: {str(e)}"
)
if not tracklist_dicts:
raise HTTPException(
status_code=400,
detail="No valid tracks found in tracklist file"
)
# Convert dicts to TracklistEntry objects
try:
tracklist_entries = [TracklistEntry(**entry) for entry in tracklist_dicts]
except Exception as e:
raise HTTPException(
status_code=400,
detail=f"Invalid tracklist data: {str(e)}"
)
# Build options dict from explicit fields (ignore `options` parameter)
options = {
"container": container,
"audio_codec": audio_codec,
"video_codec": video_codec,
"subtitle_codec": subtitle_codec,
"video_quality": video_quality,
"drop_video": drop_video,
"drop_subs": drop_subs,
"number_tracks": number_tracks,
"replace_bad_chars": replace_bad_chars,
"replacement_char": replacement_char,
"bad_chars": bad_chars,
"skip_existing": skip_existing,
"output_template": output_template,
"album": album,
"comment": comment,
"no_comment": no_comment,
"comment_stream": comment_stream,
"merge_comments": merge_comments,
"comment_separator": comment_separator,
}
# Update task status
task_manager.update_task(
task_id,
status=TaskStatus.PROCESSING,
progress=0,
message="Preparing to split..."
)
background_tasks.add_task(
run_split_task,
task_id,
tracklist_entries,
options
)
return SplitResponse(
task_id=task_id,
status=TaskStatus.PROCESSING
)
+25
View File
@@ -0,0 +1,25 @@
"""Status query endpoint."""
from fastapi import APIRouter, HTTPException
from backend.models.response import StatusResponse
from backend.services.task_manager import task_manager
router = APIRouter(prefix="/api", tags=["status"])
@router.get("/status/{task_id}", response_model=StatusResponse)
async def get_status(task_id: str):
if not task_manager.has_task(task_id):
raise HTTPException(status_code=404, detail=f"Task {task_id} not found")
status = task_manager.get_status(task_id)
return StatusResponse(
task_id=task_id,
status=status["status"],
progress=status["progress"],
message=status["message"],
error=status.get("error"),
tracks=status.get("tracks", [])
)
+59
View File
@@ -0,0 +1,59 @@
"""File upload endpoint."""
import uuid
import shutil
from pathlib import Path
from fastapi import APIRouter, UploadFile, File, HTTPException
from backend.config import settings
from backend.models.response import UploadResponse
from backend.services.task_manager import task_manager
router = APIRouter(prefix="/api", tags=["upload"])
ALLOWED_EXTENSIONS = {
".mp3", ".flac", ".wav", ".m4a", ".ogg", ".opus",
".aac", ".wma", ".aiff", ".alac", ".ac3",
".mp4", ".mkv", ".webm",
}
@router.post("/upload", response_model=UploadResponse)
async def upload_file(file: UploadFile = File(...)):
extension = Path(file.filename).suffix.lower()
if extension not in ALLOWED_EXTENSIONS:
raise HTTPException(
status_code=400,
detail=f"Unsupported file format. Allowed: {', '.join(sorted(ALLOWED_EXTENSIONS))}"
)
task_id = str(uuid.uuid4())[:8]
task_dir = settings.temp_dir / task_id
task_dir.mkdir(parents=True, exist_ok=True)
input_path = task_dir / f"input{extension}"
try:
with open(input_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
except Exception as e:
shutil.rmtree(task_dir, ignore_errors=True)
raise HTTPException(status_code=500, detail=f"Failed to save file: {str(e)}")
file_size = input_path.stat().st_size
max_size_bytes = settings.max_upload_size_mb * 1024 * 1024
if file_size > max_size_bytes:
shutil.rmtree(task_dir, ignore_errors=True)
raise HTTPException(
status_code=400,
detail=f"File too large. Maximum size: {settings.max_upload_size_mb} MB"
)
# Create task entry in the task manager
task_manager.create_task(task_id, file.filename, file_size)
return UploadResponse(
task_id=task_id,
filename=file.filename,
size=file_size
)
+46
View File
@@ -0,0 +1,46 @@
"""WebSocket endpoint for realtime progress updates."""
import json
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from backend.services.task_manager import task_manager
from backend.services.progress_publisher import register_connection, unregister_connection
router = APIRouter(tags=["websocket"])
@router.websocket("/ws/{task_id}")
async def websocket_endpoint(websocket: WebSocket, task_id: str):
await websocket.accept()
register_connection(task_id, websocket)
try:
# Send initial status
status = task_manager.get_status(task_id)
await websocket.send_json({
"type": "status",
"data": status
})
while True:
data = await websocket.receive_text()
try:
message = json.loads(data)
if message.get("type") == "ping":
await websocket.send_json({"type": "pong"})
elif message.get("type") == "get_status":
status = task_manager.get_status(task_id)
await websocket.send_json({
"type": "status",
"data": status
})
except json.JSONDecodeError:
pass
except WebSocketDisconnect:
unregister_connection(task_id, websocket)
except Exception as e:
unregister_connection(task_id, websocket)
print(f"WebSocket error: {e}")
+33
View File
@@ -0,0 +1,33 @@
"""Configuration settings for the web backend."""
import os
from pathlib import Path
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
"""Application settings loaded from environment variables."""
# Server
host: str = "0.0.0.0"
port: int = 8000
debug: bool = False
# File handling
max_upload_size_mb: int = 500
temp_dir: Path = Path("/tmp/audio_splitter_web")
cleanup_after_seconds: int = 3600 # 1 hour
# CORS
allow_origins: list[str] = ["http://localhost:5173", "http://localhost:3000"]
class Config:
env_file = ".env"
env_file_encoding = "utf-8"
settings = Settings()
# Ensure temp directory exists
settings.temp_dir.mkdir(parents=True, exist_ok=True)
+21
View File
@@ -0,0 +1,21 @@
#!/bin/bash
set -e
# Detect if we are running as root (default)
if [ "$(id -u)" = "0" ]; then
# Ensure the temp directory exists and set ownership
if [ -d "/tmp/audio_splitter_web" ]; then
echo "Setting ownership of /tmp/audio_splitter_web to appuser:appgroup"
chown -R appuser:appgroup /tmp/audio_splitter_web
else
echo "Creating /tmp/audio_splitter_web and setting ownership"
mkdir -p /tmp/audio_splitter_web
chown -R appuser:appgroup /tmp/audio_splitter_web
fi
# Drop privileges and run uvicorn using gosu
exec gosu appuser uvicorn backend.main:app --host 0.0.0.0 --port 8000
else
# If not root, just run directly
exec uvicorn backend.main:app --host 0.0.0.0 --port 8000
fi
+79
View File
@@ -0,0 +1,79 @@
"""FFmpeg/FFprobe interaction utilities for the web backend."""
import subprocess
import json
def get_stream_info(input_file: str):
"""
Retrieve stream information (audio, video, subtitle presence) from a media file.
Returns a dict with keys: has_audio, has_video, has_subtitle, audio_codec.
"""
# Get audio codec (if any)
audio_codec = None
try:
cmd = [
'ffprobe', '-v', 'error',
'-select_streams', 'a:0',
'-show_entries', 'stream=codec_name',
'-of', 'default=noprint_wrappers=1:nokey=1',
input_file
]
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
codec = result.stdout.strip().lower()
if codec:
audio_codec = codec
except Exception:
pass
# Check for video stream
has_video = False
try:
cmd = [
'ffprobe', '-v', 'error',
'-select_streams', 'v',
'-show_entries', 'stream=codec_type',
'-of', 'default=noprint_wrappers=1:nokey=1',
input_file
]
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
has_video = bool(result.stdout.strip())
except Exception:
pass
# Check for subtitle stream
has_subtitle = False
try:
cmd = [
'ffprobe', '-v', 'error',
'-select_streams', 's',
'-show_entries', 'stream=codec_type',
'-of', 'default=noprint_wrappers=1:nokey=1',
input_file
]
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
has_subtitle = bool(result.stdout.strip())
except Exception:
pass
return {
'has_audio': audio_codec is not None,
'has_video': has_video,
'has_subtitle': has_subtitle,
'audio_codec': audio_codec,
}
def get_audio_duration(input_file: str) -> float:
"""Get the duration of the audio file in seconds."""
cmd = [
'ffprobe', '-v', 'error',
'-show_entries', 'format=duration',
'-of', 'default=noprint_wrappers=1:nokey=1',
input_file
]
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
try:
return float(result.stdout.strip())
except ValueError:
return 0.0
+51
View File
@@ -0,0 +1,51 @@
"""FastAPI application entry point."""
import asyncio
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from backend.config import settings
from backend.api import upload, split, split_file, status, download, websocket, formats, info
from backend.services import progress_publisher
app = FastAPI(
title="Audio Splitter Web API",
description="Web interface for splitting audio files using a tracklist",
version="0.1.0",
)
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=settings.allow_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.on_event("startup")
async def startup_event():
"""Store the main event loop for use in other threads."""
progress_publisher.MAIN_LOOP = asyncio.get_running_loop()
# Include routers
app.include_router(upload.router)
app.include_router(split.router)
app.include_router(split_file.router) # NEW
app.include_router(status.router)
app.include_router(download.router)
app.include_router(websocket.router)
app.include_router(formats.router)
app.include_router(info.router)
@app.get("/")
async def root():
return {"status": "ok", "service": "Audio Splitter Web API"}
@app.get("/health")
async def health():
return {"status": "healthy"}
+1
View File
@@ -0,0 +1 @@
"""Pydantic models for request/response validation."""
+80
View File
@@ -0,0 +1,80 @@
"""Request models for API endpoints."""
from typing import Optional, List
from pydantic import BaseModel, Field, validator
class TracklistEntry(BaseModel):
"""A single track entry from the tracklist."""
ts: str = Field(..., description="Timestamp (e.g., '00:00' or '00:00-01:30')")
tn: Optional[str] = Field("", description="Track name")
an: Optional[str] = Field("", description="Author/artist")
al: Optional[str] = Field("", description="Album")
date: Optional[str] = Field("", description="Date/year")
ext: Optional[str] = Field("", description="File extension")
@validator("ts")
def validate_timestamp(cls, v: str) -> str:
v = v.strip()
if not v:
raise ValueError("Timestamp cannot be empty")
if "-" in v:
parts = v.split("-", 1)
start = parts[0].strip()
end = parts[1].strip()
if not start or not end:
raise ValueError("Invalid range format. Expected 'start-end'")
for ts in [start, end]:
cls._validate_single_timestamp(ts)
else:
cls._validate_single_timestamp(v)
return v
@staticmethod
def _validate_single_timestamp(ts: str) -> None:
parts = ts.split(":")
if len(parts) not in (2, 3):
raise ValueError(f"Invalid timestamp format: {ts}. Expected mm:ss or HH:MM:SS")
try:
for p in parts:
int(p)
except ValueError:
raise ValueError(f"Invalid timestamp: {ts}. Must contain only numbers.")
class SplitRequest(BaseModel):
"""Request model for the split endpoint."""
task_id: str = Field(..., description="Task ID from upload")
tracklist: List[TracklistEntry] = Field(..., description="List of tracks")
# Container and codec options
container: Optional[str] = Field(None, description="Output container (auto-detect if None)")
audio_codec: Optional[str] = Field("copy", description="Audio codec (copy or encoder name)")
video_codec: Optional[str] = Field("copy", description="Video codec (copy or encoder name)")
subtitle_codec: Optional[str] = Field("copy", description="Subtitle codec (copy or encoder name)")
video_quality: Optional[int] = Field(None, description="Video quality (encoder-specific integer)")
# Stream handling
drop_video: bool = Field(False, description="Remove video streams")
drop_subs: bool = Field(False, description="Remove subtitle streams")
# Filename options
number_tracks: bool = Field(False, description="Prepend track numbers")
replace_bad_chars: bool = Field(False, description="Replace bad characters")
replacement_char: str = Field("_", description="Replacement character")
bad_chars: str = Field(r'!@#№$;:%^&?*(){}[]\/<>+=~`\' ', description="Bad characters to replace")
skip_existing: bool = Field(False, description="Skip existing files")
output_template: str = Field("%an-%tn.%ext", description="Output filename template")
# Metadata options
album: Optional[str] = Field(None, description="Album name")
comment: Optional[str] = Field(None, description="Comment")
no_comment: bool = Field(False, description="Ignore comment")
comment_stream: Optional[int] = Field(None, description="Comment stream index")
merge_comments: bool = Field(False, description="Merge all comments")
comment_separator: str = Field("; ", description="Separator for merged comments")
+38
View File
@@ -0,0 +1,38 @@
"""Response models for API endpoints."""
from typing import Optional, List
from enum import Enum
from pydantic import BaseModel, Field
class TaskStatus(str, Enum):
PENDING = "pending"
PROCESSING = "processing"
DONE = "done"
ERROR = "error"
class TrackInfo(BaseModel):
filename: str
size: int # bytes
class UploadResponse(BaseModel):
task_id: str
filename: str
size: int
class SplitResponse(BaseModel):
task_id: str
status: TaskStatus
class StatusResponse(BaseModel):
task_id: str
status: TaskStatus
progress: int = Field(0, ge=0, le=100)
message: str = ""
error: Optional[str] = None
tracks: List[TrackInfo] = []
+8
View File
@@ -0,0 +1,8 @@
fastapi>=0.104.0
uvicorn[standard]>=0.24.0
python-multipart>=0.0.6
aiofiles>=23.2.0
pydantic>=2.5.0
pydantic-settings>=2.0.0
python-dotenv>=1.0.0
websockets>=12.0
+1
View File
@@ -0,0 +1 @@
"""Business logic services."""
+47
View File
@@ -0,0 +1,47 @@
"""Temporary file management for web operations."""
import shutil
from pathlib import Path
from backend.config import settings
class FileManager:
@staticmethod
def get_task_dir(task_id: str) -> Path:
return settings.temp_dir / task_id
@staticmethod
def get_input_path(task_id: str) -> Path:
task_dir = FileManager.get_task_dir(task_id)
for f in task_dir.iterdir():
if f.name.startswith("input."):
return f
return None
@staticmethod
def get_output_dir(task_id: str) -> Path:
return FileManager.get_task_dir(task_id) / "output"
@staticmethod
def ensure_output_dir(task_id: str) -> Path:
output_dir = FileManager.get_output_dir(task_id)
output_dir.mkdir(parents=True, exist_ok=True)
return output_dir
@staticmethod
def cleanup_task(task_id: str) -> None:
task_dir = FileManager.get_task_dir(task_id)
if task_dir.exists():
shutil.rmtree(task_dir, ignore_errors=True)
@staticmethod
def get_output_files(task_id: str) -> list:
output_dir = FileManager.get_output_dir(task_id)
if not output_dir.exists():
return []
files = []
for f in output_dir.iterdir():
if f.is_file():
files.append({"filename": f.name, "size": f.stat().st_size})
return files
@@ -0,0 +1,66 @@
"""WebSocket progress publisher decouples task manager from WebSocket."""
import asyncio
from typing import Dict, Set
from fastapi import WebSocket
# This will be set by main.py during startup
MAIN_LOOP = None
active_connections: Dict[str, Set[WebSocket]] = {}
def publish_progress(task_id: str, progress: int, message: str, status: str = "processing"):
"""
Publish progress update to all connected WebSocket clients for a task.
"""
if task_id not in active_connections:
return
data = {
"type": "progress",
"data": {
"task_id": task_id,
"status": status,
"progress": progress,
"message": message
}
}
to_remove = set()
# Get the loop to use: either the stored one or try to get the current loop
loop = MAIN_LOOP
if loop is None:
try:
loop = asyncio.get_running_loop()
except RuntimeError:
# No running loop, fallback to default event loop
loop = asyncio.get_event_loop()
for websocket in active_connections.get(task_id, set()):
try:
asyncio.run_coroutine_threadsafe(websocket.send_json(data), loop)
except Exception:
to_remove.add(websocket)
# Clean up disconnected clients
for websocket in to_remove:
active_connections[task_id].discard(websocket)
if task_id in active_connections and not active_connections[task_id]:
del active_connections[task_id]
def register_connection(task_id: str, websocket: WebSocket):
"""Register a WebSocket connection for a task."""
if task_id not in active_connections:
active_connections[task_id] = set()
active_connections[task_id].add(websocket)
def unregister_connection(task_id: str, websocket: WebSocket):
"""Unregister a WebSocket connection for a task."""
if task_id in active_connections:
active_connections[task_id].discard(websocket)
if not active_connections[task_id]:
del active_connections[task_id]
+106
View File
@@ -0,0 +1,106 @@
"""Splitter service that calls the core audio_splitter logic."""
import os
import sys
import shutil
from pathlib import Path
from typing import List, Dict, Any
import time
from backend.config import settings
from backend.services.task_manager import task_manager
from backend.services.file_manager import FileManager
from backend.models.request import TracklistEntry
from backend.models.response import TaskStatus
def run_split_task(task_id: str, tracklist: List[TracklistEntry], options: Dict[str, Any]) -> None:
try:
task_manager.update_task_with_progress(
task_id, progress=5, message="Initializing..."
)
input_path = FileManager.get_input_path(task_id)
if not input_path or not input_path.exists():
raise RuntimeError(f"Input file not found for task {task_id}")
output_dir = FileManager.ensure_output_dir(task_id)
tracks = []
for entry in tracklist:
track_dict = {
"ts": entry.ts,
"tn": entry.tn or "",
"an": entry.an or "",
"al": entry.al or "",
"date": entry.date or "",
"ext": entry.ext or ""
}
tracks.append(track_dict)
from types import SimpleNamespace
# Build args namespace using the new fields
args = SimpleNamespace(
container=options.get("container"), # None -> auto-detect
audio_codec=options.get("audio_codec", "copy"),
video_codec=options.get("video_codec", "copy"),
subtitle_codec=options.get("subtitle_codec", "copy"),
video_quality=options.get("video_quality"),
drop_video=options.get("drop_video", False),
drop_subs=options.get("drop_subs", False),
number_tracks=options.get("number_tracks", False),
replace_bad_chars=options.get("replace_bad_chars", False),
replacement_char=options.get("replacement_char", "_"),
bad_chars=options.get("bad_chars", r'!@#№$;:%^&?*(){}[]\/<>+=~`\' '),
skip_existing=options.get("skip_existing", False),
output_template=options.get("output_template", "%an-%tn.%ext"),
album=options.get("album", None),
comment=options.get("comment", None),
no_comment=options.get("no_comment", False),
comment_stream=options.get("comment_stream", None),
merge_comments=options.get("merge_comments", False),
comment_separator=options.get("comment_separator", "; "),
delete_original=False,
)
project_root = Path(__file__).parent.parent.parent.parent
if str(project_root) not in sys.path:
sys.path.insert(0, str(project_root))
from audio_splitter.core import split_audio
# Cover image handling is now done internally by split_audio()
# via the handler system (opustags for Opus, ffmpeg for others)
args.cover_image = None
task_manager.update_task_with_progress(
task_id, progress=10, message="Starting split..."
)
split_audio(str(input_path), str(output_dir), tracks, args)
output_files = FileManager.get_output_files(task_id)
task_manager.update_task_with_progress(
task_id,
progress=100,
message="Split complete",
status=TaskStatus.DONE
)
task_manager.update_task(
task_id,
tracks=output_files
)
time.sleep(0.5)
except Exception as e:
task_manager.update_task_with_progress(
task_id,
progress=0,
message="Split failed",
status=TaskStatus.ERROR,
error=str(e)
)
+110
View File
@@ -0,0 +1,110 @@
"""In-memory task state management."""
from typing import Dict, Optional, List
from datetime import datetime, timedelta
import threading
import time
from backend.config import settings
from backend.models.response import TaskStatus, TrackInfo
from backend.services.progress_publisher import publish_progress
class TaskManager:
def __init__(self):
self._tasks: Dict[str, dict] = {}
self._lock = threading.Lock()
def create_task(self, task_id: str, filename: str, file_size: int) -> None:
with self._lock:
self._tasks[task_id] = {
"task_id": task_id,
"filename": filename,
"file_size": file_size,
"status": TaskStatus.PENDING,
"progress": 0,
"message": "Upload complete",
"error": None,
"tracks": [],
"created_at": datetime.now(),
"updated_at": datetime.now()
}
def has_task(self, task_id: str) -> bool:
return task_id in self._tasks
def get_status(self, task_id: str) -> dict:
"""Get task status with datetime objects converted to ISO format."""
with self._lock:
if task_id not in self._tasks:
return {}
# Return a copy with datetime objects converted to ISO strings
status = self._tasks[task_id].copy()
return self._prepare_status_for_serialization(status)
def _prepare_status_for_serialization(self, status: dict) -> dict:
"""Convert datetime objects to ISO format strings for JSON serialization."""
serializable = {}
for key, value in status.items():
if isinstance(value, datetime):
serializable[key] = value.isoformat()
elif isinstance(value, list):
# Handle lists of objects (e.g., tracks)
serializable[key] = [
{k: v.isoformat() if isinstance(v, datetime) else v for k, v in item.items()}
if isinstance(item, dict)
else item
for item in value
]
elif isinstance(value, dict):
# Recursively handle nested dicts
serializable[key] = {
k: v.isoformat() if isinstance(v, datetime) else v
for k, v in value.items()
}
else:
serializable[key] = value
return serializable
def update_task(self, task_id: str, **kwargs) -> None:
with self._lock:
if task_id in self._tasks:
self._tasks[task_id].update(kwargs)
self._tasks[task_id]["updated_at"] = datetime.now()
def update_task_with_progress(self, task_id: str, progress: int, message: str,
status: str = None, error: str = None) -> None:
update_kwargs = {
"progress": progress,
"message": message
}
if status:
update_kwargs["status"] = status
if error is not None:
update_kwargs["error"] = error
self.update_task(task_id, **update_kwargs)
# Publish progress via WebSocket
publish_progress(task_id, progress, message, status or "processing")
def cleanup_old_tasks(self) -> None:
now = datetime.now()
timeout = timedelta(seconds=settings.cleanup_after_seconds)
with self._lock:
to_delete = []
for task_id, data in self._tasks.items():
if now - data["created_at"] > timeout:
to_delete.append(task_id)
for task_id in to_delete:
self._delete_task_files(task_id)
del self._tasks[task_id]
def _delete_task_files(self, task_id: str) -> None:
import shutil
task_dir = settings.temp_dir / task_id
if task_dir.exists():
shutil.rmtree(task_dir, ignore_errors=True)
task_manager = TaskManager()
+1
View File
@@ -0,0 +1 @@
"""Utility functions for the web backend."""
+23
View File
@@ -0,0 +1,23 @@
"""Input validation utilities."""
import re
from typing import List, Tuple
from ..models.request import TracklistEntry
def validate_tracklist(tracklist: List[TracklistEntry]) -> Tuple[bool, List[str]]:
"""
Validate a tracklist and return any errors.
Returns:
(is_valid, error_messages)
"""
errors = []
for idx, entry in enumerate(tracklist, 1):
# Each entry must have a timestamp
if not entry.ts or not entry.ts.strip():
errors.append(f"Line {idx}: Missing timestamp (%ts)")
# Additional validation could be added here
return len(errors) == 0, errors
+12
View File
@@ -0,0 +1,12 @@
node_modules
dist
.git
.gitignore
*.log
.env
.env.local
.DS_Store
Dockerfile
Dockerfile.dev
.dockerignore
nginx.conf
+42
View File
@@ -0,0 +1,42 @@
# web/frontend/Dockerfile
# Build context must be the project root.
FROM node:20-alpine AS builder
# Install Python for the generation script
RUN apk add --no-cache python3 py3-pip
WORKDIR /app
# Copy frontend package files and install dependencies
COPY web/frontend/package.json web/frontend/package-lock.json* ./
RUN npm install
# Copy the frontend source code
COPY web/frontend/ .
# Copy the Python defaults and the generation script into the expected location
# The generate script in package.json expects ../../scripts/generate_ts_defaults.py
# So we must place it at /app/../../scripts/ which is /scripts/
# But we can't COPY to a parent directory. Instead, we'll copy to /app/scripts/
# and adjust the package.json script to use ./scripts/generate_ts_defaults.py
# Actually, the simplest fix is to copy to /app/scripts/ and then adjust package.json.
#
# Let's use a different approach: copy to /app/scripts/ and update the generate script.
COPY audio_splitter/defaults.py /app/scripts/defaults.py
COPY scripts/generate_ts_defaults.py /app/scripts/generate_ts_defaults.py
# Run the generation script
RUN python /app/scripts/generate_ts_defaults.py
# Build the frontend
RUN npm run build
# Stage 2: Production (nginx)
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
COPY web/frontend/nginx/nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Audio Splitter</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+35
View File
@@ -0,0 +1,35 @@
server {
listen 80;
server_name _;
client_max_body_size 500M;
# Root directory for static files
root /usr/share/nginx/html;
index index.html;
# Serve React app
location / {
try_files $uri $uri/ /index.html;
}
# Proxy API requests to backend
location /api/ {
proxy_pass http://backend:8000/api/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# Proxy WebSocket requests to backend
location /ws/ {
proxy_pass http://backend:8000/ws/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
+4239
View File
File diff suppressed because it is too large Load Diff
+39
View File
@@ -0,0 +1,39 @@
{
"name": "audio-splitter-web",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"generate": "python scripts/generate_ts_defaults.py",
"predev": "npm run generate",
"prebuild": "npm run generate",
"dev": "vite",
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
"@emotion/react": "^11.11.1",
"@emotion/styled": "^11.11.0",
"@mui/icons-material": "^5.14.19",
"@mui/material": "^5.14.20",
"@mui/x-data-grid": "^6.18.5",
"axios": "^1.6.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-dropzone": "^14.2.3",
"zustand": "^4.4.7"
},
"devDependencies": {
"@types/react": "^18.2.43",
"@types/react-dom": "^18.2.17",
"@typescript-eslint/eslint-plugin": "^6.14.0",
"@typescript-eslint/parser": "^6.14.0",
"@vitejs/plugin-react": "^4.2.1",
"eslint": "^8.55.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.5",
"typescript": "^5.2.2",
"vite": "^5.0.8"
}
}
+126
View File
@@ -0,0 +1,126 @@
import React from 'react'
import { ThemeProvider, createTheme, CssBaseline } from '@mui/material'
import { Box, Grid, Button, CircularProgress, Typography } from '@mui/material'
import { PlayArrow } from '@mui/icons-material'
import { Layout } from './components/Layout'
import { UploadZone } from './components/UploadZone'
import { TracklistEditor } from './components/TracklistEditor'
import { OptionsPanel } from './components/OptionsPanel'
import { ProgressDisplay } from './components/ProgressDisplay'
import { DownloadSection } from './components/DownloadSection'
import { useUploadStore } from './stores/uploadStore'
import { useTracklistStore } from './stores/tracklistStore'
import { useOptionsStore } from './stores/optionsStore'
import { useTaskStore } from './stores/taskStore'
import { useUIStore } from './stores/uiStore'
import { useValidationStore } from './stores/validationStore'
import { useWebSocket } from './hooks/useWebSocket'
import { startSplit } from './api/client'
const App: React.FC = () => {
const { theme } = useUIStore()
const { taskId } = useUploadStore()
const { entries, isValid } = useTracklistStore()
const { options } = useOptionsStore()
const {
isProcessing,
setTaskId,
setError,
setIsProcessing,
addLog,
reset,
} = useTaskStore()
const { formatError } = useValidationStore()
useWebSocket(taskId && isProcessing ? taskId : null)
const handleSplit = async () => {
if (!taskId) {
alert('Please upload a file first')
return
}
if (!isValid) {
alert('Tracklist has errors. Please fix them before splitting.')
return
}
if (entries.length === 0) {
alert('Tracklist is empty')
return
}
try {
setTaskId(taskId)
setIsProcessing(true)
addLog('🚀 Starting split...')
const response = await startSplit(taskId, entries, options)
addLog(`✅ Split task started (ID: ${response.task_id})`)
} catch (error: any) {
setError(error.response?.data?.detail || error.message || 'Failed to start split')
addLog(`❌ Error: ${error.response?.data?.detail || error.message || 'Failed to start split'}`)
setIsProcessing(false)
}
}
const handleReset = () => {
reset()
}
const isSplitDisabled =
!taskId ||
!isValid ||
entries.length === 0 ||
isProcessing ||
!!formatError
return (
<ThemeProvider theme={createTheme({ palette: { mode: theme } })}>
<CssBaseline />
<Layout>
<Grid container spacing={3}>
<Grid item xs={12} md={6}>
<UploadZone />
</Grid>
<Grid item xs={12} md={6}>
<TracklistEditor />
</Grid>
<Grid item xs={12} md={4}>
<OptionsPanel />
</Grid>
<Grid item xs={12} md={8}>
<Box sx={{ display: 'flex', gap: 2, mb: 3 }}>
<Button
variant="contained"
color="success"
startIcon={isProcessing ? <CircularProgress size={20} color="inherit" /> : <PlayArrow />}
onClick={handleSplit}
disabled={isSplitDisabled}
sx={{ flex: 1 }}
>
{isProcessing ? 'Processing...' : 'Split'}
</Button>
<Button variant="outlined" color="secondary" onClick={handleReset} disabled={isProcessing}>
Reset
</Button>
</Box>
{formatError && (
<Box sx={{ mb: 2, p: 2, bgcolor: 'warning.light', borderRadius: 1 }}>
<Typography color="warning.dark" variant="body2">
{formatError}
</Typography>
</Box>
)}
<ProgressDisplay />
<DownloadSection />
</Grid>
</Grid>
</Layout>
</ThemeProvider>
)
}
export default App
+94
View File
@@ -0,0 +1,94 @@
import axios from 'axios'
import {
TracklistEntry,
SplitOptions,
TaskStatus,
FormatsResponse,
UploadResponse,
SplitResponse,
} from '../types'
export const api = axios.create({
baseURL: '/api',
headers: {
'Content-Type': 'application/json',
},
})
export const uploadFile = async (file: File): Promise<UploadResponse> => {
const formData = new FormData()
formData.append('file', file)
const response = await api.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
return response.data
}
export const startSplit = async (
task_id: string,
tracklist: TracklistEntry[],
options: SplitOptions
): Promise<SplitResponse> => {
// Build request payload (only send fields that are not undefined)
const payload: any = {
task_id,
tracklist,
container: options.container, // null means auto-detect
audio_codec: options.audio_codec,
video_codec: options.video_codec,
subtitle_codec: options.subtitle_codec,
video_quality: options.video_quality,
drop_video: options.drop_video,
drop_subs: options.drop_subs,
number_tracks: options.number_tracks,
replace_bad_chars: options.replace_bad_chars,
replacement_char: options.replacement_char,
bad_chars: options.bad_chars,
skip_existing: options.skip_existing,
output_template: options.output_template,
album: options.album || null,
comment: options.comment || null,
no_comment: options.no_comment,
comment_stream: options.comment_stream,
merge_comments: options.merge_comments,
comment_separator: options.comment_separator,
}
const response = await api.post('/split', payload)
return response.data
}
export const getStatus = async (task_id: string): Promise<TaskStatus> => {
const response = await api.get(`/status/${task_id}`)
return response.data
}
export const getDownloadUrl = (task_id: string): string => {
return `/api/download/${task_id}`
}
export const getDownloadZipUrl = (task_id: string): string => {
return `/api/download/${task_id}/splits.zip`
}
export const getFormats = async (): Promise<FormatsResponse> => {
const response = await api.get('/formats')
return response.data
}
export const getTaskInfo = async (task_id: string): Promise<{
task_id: string
has_audio: boolean
has_video: boolean
has_subtitle: boolean
audio_codec: string | null
}> => {
const response = await api.get(`/info/${task_id}`)
return response.data
}
export const getRecommendedFormat = async (task_id: string): Promise<{ format: string }> => {
const response = await api.get(`/info/recommended-format/${task_id}`)
return response.data
}
@@ -0,0 +1,73 @@
import React from 'react'
import { Paper, Typography, Button, List, ListItem, ListItemText, IconButton, Divider } from '@mui/material'
import { Download, FolderZip } from '@mui/icons-material'
import { useTaskStore } from '../stores/taskStore'
import { getDownloadZipUrl } from '../api/client'
import { formatFileSize } from '../utils/formatters'
export const DownloadSection: React.FC = () => {
const { taskId, tracks, status } = useTaskStore()
console.log('[DownloadSection] Rendering:', { status, tracks, taskId })
// Check if we should show the download section
if (status !== 'done' || !tracks || tracks.length === 0 || !taskId) {
return null
}
// If we get here, we have tracks
console.log('[DownloadSection] Showing tracks:', tracks)
const handleDownloadZip = () => {
const url = getDownloadZipUrl(taskId)
window.open(url, '_blank')
}
const handleDownloadTrack = (filename: string) => {
const url = `/api/download/${taskId}/${filename}`
window.open(url, '_blank')
}
return (
<Paper sx={{ p: 3, mt: 3 }}>
<Typography variant="h6" sx={{ mb: 2 }}>
📥 Download Results
</Typography>
<Button
variant="contained"
color="primary"
startIcon={<FolderZip />}
onClick={handleDownloadZip}
sx={{ mb: 2 }}
fullWidth
>
Download All as ZIP
</Button>
<Divider sx={{ my: 2 }} />
<Typography variant="subtitle2" sx={{ mb: 1 }}>
Individual Tracks
</Typography>
<List dense>
{tracks.map((track, index) => (
<ListItem
key={index}
secondaryAction={
<IconButton edge="end" onClick={() => handleDownloadTrack(track.filename)} size="small">
<Download />
</IconButton>
}
>
<ListItemText
primary={track.filename}
secondary={formatFileSize(track.size)}
/>
</ListItem>
))}
</List>
</Paper>
)
}
+57
View File
@@ -0,0 +1,57 @@
import React from 'react'
import { AppBar, Toolbar, Typography, IconButton, Box, Container, Badge } from '@mui/material'
import { Brightness4, Brightness7, FiberManualRecord } from '@mui/icons-material'
import { useUIStore } from '../stores/uiStore'
interface LayoutProps {
children: React.ReactNode
}
export const Layout: React.FC<LayoutProps> = ({ children }) => {
const { theme, toggleTheme, wsConnected } = useUIStore()
return (
<Box sx={{ display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
<AppBar position="static" color="default" elevation={1}>
<Toolbar>
<Typography variant="h6" component="div" sx={{ flexGrow: 1, fontWeight: 600 }}>
🎵 Audio Splitter
</Typography>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Badge
color={wsConnected ? 'success' : 'error'}
variant="dot"
sx={{ mr: 1 }}
>
<FiberManualRecord
sx={{
fontSize: 12,
color: wsConnected ? 'green' : 'red',
visibility: 'hidden',
}}
/>
</Badge>
<Typography variant="caption" color="text.secondary">
{wsConnected ? 'Connected' : 'Disconnected'}
</Typography>
<IconButton onClick={toggleTheme} color="inherit">
{theme === 'light' ? <Brightness4 /> : <Brightness7 />}
</IconButton>
</Box>
</Toolbar>
</AppBar>
<Container maxWidth="lg" sx={{ flex: 1, py: 4 }}>
{children}
</Container>
<Box component="footer" sx={{ py: 2, textAlign: 'center', borderTop: 1, borderColor: 'divider' }}>
<Typography variant="body2" color="text.secondary">
Audio Splitter v0.1.0 Built with
</Typography>
</Box>
</Box>
)
}
@@ -0,0 +1,370 @@
import React, { useEffect, useMemo } from 'react'
import {
Box,
Paper,
Typography,
TextField,
MenuItem,
FormControlLabel,
Switch,
Collapse,
IconButton,
Divider,
Alert,
} from '@mui/material'
import { ExpandMore, ExpandLess } from '@mui/icons-material'
import { useOptionsStore } from '../stores/optionsStore'
import { useUploadStore } from '../stores/uploadStore'
import { useValidationStore } from '../stores/validationStore'
import { getFormats } from '../api/client'
import { SplitOptions } from '../types'
import { useFilterCodecs } from '../hooks/useFilterCodecs'
import { useFormatValidation } from '../hooks/useFormatValidation'
// ------------------------------------------------------------------------------
// Section component (collapsible)
// ------------------------------------------------------------------------------
interface SectionProps {
title: string
children: React.ReactNode
defaultExpanded?: boolean
}
const Section: React.FC<SectionProps> = ({ title, children, defaultExpanded = false }) => {
const [expanded, setExpanded] = React.useState(defaultExpanded)
return (
<Box sx={{ mb: 2 }}>
<Box
sx={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
cursor: 'pointer',
py: 1,
}}
onClick={() => setExpanded(!expanded)}
>
<Typography variant="subtitle2" sx={{ fontWeight: 600 }}>
{title}
</Typography>
<IconButton size="small">{expanded ? <ExpandLess /> : <ExpandMore />}</IconButton>
</Box>
<Divider />
<Collapse in={expanded}>
<Box sx={{ pt: 2, pb: 1 }}>{children}</Box>
</Collapse>
</Box>
)
}
// ------------------------------------------------------------------------------
// Main OptionsPanel
// ------------------------------------------------------------------------------
export const OptionsPanel: React.FC = () => {
const {
options,
setOptions,
containers,
codecs,
compatibility,
setContainers,
setCodecs,
setCompatibility,
} = useOptionsStore()
const { hasVideo } = useUploadStore()
const { formatError, setFormatError } = useValidationStore()
// Fetch formats on mount
useEffect(() => {
const fetchFormats = async () => {
try {
const data = await getFormats()
setContainers(data.containers || [])
setCodecs(data.codecs || [])
setCompatibility(data.compatibility || {})
} catch (err) {
console.error('Failed to fetch formats:', err)
}
}
fetchFormats()
}, [setContainers, setCodecs, setCompatibility])
// --------------------------------------------------------------
// Filter codec options based on selected container
// --------------------------------------------------------------
const { filteredAudioCodecs, filteredVideoCodecs } = useFilterCodecs(compatibility, options.container, codecs)
// --------------------------------------------------------------
// Validate compatibility
// --------------------------------------------------------------
useFormatValidation(options, hasVideo, compatibility, containers, setFormatError)
// --------------------------------------------------------------
// Handlers
// --------------------------------------------------------------
const handleChange = (field: keyof SplitOptions, value: any) => {
setOptions({ [field]: value })
}
const handleContainerChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value === '' ? null : e.target.value
handleChange('container', value)
}
// --------------------------------------------------------------
// Render
// --------------------------------------------------------------
return (
<Paper sx={{ p: 3 }}>
<Typography variant="h6" sx={{ mb: 2 }}>
Options
</Typography>
{formatError && (
<Alert severity="warning" sx={{ mb: 2 }}>
{formatError}
</Alert>
)}
{/* ------------------------------------------------------------------------
Output Settings
------------------------------------------------------------------------ */}
<Section title="Output Settings" defaultExpanded>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
{/* Container dropdown */}
<TextField
label="Container"
select
value={options.container ?? ''}
onChange={handleContainerChange}
fullWidth
size="small"
error={!!formatError}
helperText={
formatError || "Select a container (auto-detect if empty)."
}
>
<MenuItem value="">Auto-detect</MenuItem>
{containers.map((c) => (
<MenuItem key={c.name} value={c.name}>
{c.name.toUpperCase()} ({c.extension})
</MenuItem>
))}
</TextField>
{/* Audio Codec dropdown */}
<TextField
label="Audio Codec"
select
value={options.audio_codec}
onChange={(e) => handleChange('audio_codec', e.target.value)}
fullWidth
size="small"
helperText="Audio codec (copy = keep original)"
>
<MenuItem value="copy">Copy (original)</MenuItem>
{filteredAudioCodecs.map((c) => (
<MenuItem key={c.name} value={c.name}>
{c.name.toUpperCase()}
</MenuItem>
))}
</TextField>
{/* Video Codec dropdown */}
<TextField
label="Video Codec"
select
value={options.video_codec}
onChange={(e) => handleChange('video_codec', e.target.value)}
fullWidth
size="small"
helperText="Video codec (copy = keep original)"
disabled={!hasVideo || options.drop_video}
>
<MenuItem value="copy">Copy (original)</MenuItem>
{filteredVideoCodecs.map((c) => (
<MenuItem key={c.name} value={c.name}>
{c.name.toUpperCase()}
</MenuItem>
))}
</TextField>
{/* Video Quality */}
<TextField
label="Video Quality"
type="number"
value={options.video_quality ?? ''}
onChange={(e) => {
const val = e.target.value === '' ? null : parseInt(e.target.value, 10)
handleChange('video_quality', val)
}}
fullWidth
size="small"
disabled={!hasVideo || options.drop_video}
helperText="Optional quality value (encoder-specific; e.g., 1-31 for libx264, 0-10 for Theora)"
InputProps={{
inputProps: { min: 0, max: 51, step: 1 },
}}
/>
{/* Drop video (if video present) */}
{hasVideo && (
<FormControlLabel
control={
<Switch
checked={options.drop_video}
onChange={(e) => handleChange('drop_video', e.target.checked)}
/>
}
label="Drop video streams"
/>
)}
{/* Drop subtitles */}
<FormControlLabel
control={
<Switch
checked={options.drop_subs}
onChange={(e) => handleChange('drop_subs', e.target.checked)}
/>
}
label="Drop subtitle streams"
/>
</Box>
</Section>
{/* ------------------------------------------------------------------------
Filename Settings
------------------------------------------------------------------------ */}
<Section title="Filename Settings">
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
<TextField
label="Output template"
value={options.output_template}
onChange={(e) => handleChange('output_template', e.target.value)}
fullWidth
size="small"
helperText="Placeholders: %tn (track name), %an (author), %al (album), %date, %ext, %num"
/>
<FormControlLabel
control={
<Switch
checked={options.number_tracks}
onChange={(e) => handleChange('number_tracks', e.target.checked)}
/>
}
label="Number tracks (01 - )"
/>
<FormControlLabel
control={
<Switch
checked={options.replace_bad_chars}
onChange={(e) => handleChange('replace_bad_chars', e.target.checked)}
/>
}
label="Replace bad characters"
/>
<TextField
label="Replacement character"
value={options.replacement_char}
onChange={(e) => handleChange('replacement_char', e.target.value)}
size="small"
disabled={!options.replace_bad_chars}
/>
<TextField
label="Bad characters list"
value={options.bad_chars}
onChange={(e) => handleChange('bad_chars', e.target.value)}
fullWidth
size="small"
disabled={!options.replace_bad_chars}
/>
<FormControlLabel
control={
<Switch
checked={options.skip_existing}
onChange={(e) => handleChange('skip_existing', e.target.checked)}
/>
}
label="Skip existing files"
/>
</Box>
</Section>
{/* ------------------------------------------------------------------------
Metadata Settings
------------------------------------------------------------------------ */}
<Section title="Metadata Settings">
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
<TextField
label="Album"
value={options.album}
onChange={(e) => handleChange('album', e.target.value)}
fullWidth
size="small"
/>
<TextField
label="Comment"
value={options.comment}
onChange={(e) => handleChange('comment', e.target.value)}
fullWidth
size="small"
/>
<FormControlLabel
control={
<Switch
checked={options.no_comment}
onChange={(e) => handleChange('no_comment', e.target.checked)}
/>
}
label="No comment"
/>
<TextField
label="Comment stream index"
type="number"
value={options.comment_stream ?? ''}
onChange={(e) =>
handleChange('comment_stream', e.target.value === '' ? null : parseInt(e.target.value, 10))
}
size="small"
disabled={options.no_comment}
/>
<FormControlLabel
control={
<Switch
checked={options.merge_comments}
onChange={(e) => handleChange('merge_comments', e.target.checked)}
/>
}
label="Merge all comments"
disabled={options.no_comment}
/>
<TextField
label="Comment separator"
value={options.comment_separator}
onChange={(e) => handleChange('comment_separator', e.target.value)}
size="small"
disabled={!options.merge_comments || options.no_comment}
/>
</Box>
</Section>
{/* ------------------------------------------------------------------------
Tracklist Settings
------------------------------------------------------------------------ */}
<Section title="Tracklist Settings" defaultExpanded>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
<TextField
label="Tracklist Format"
value={options.tracklist_format}
onChange={(e) => handleChange('tracklist_format', e.target.value)}
fullWidth
size="small"
helperText="Placeholders: %ts (timestamp), %tn (track name), %an (author), %al (album), %date, %ext"
/>
</Box>
</Section>
</Paper>
)
}
@@ -0,0 +1,107 @@
import React, { useEffect, useRef } from 'react'
import { Box, Paper, Typography, LinearProgress, Alert, Chip } from '@mui/material'
import { useTaskStore } from '../stores/taskStore'
export const ProgressDisplay: React.FC = () => {
const { status, progress, message, error, tracks, logs } = useTaskStore()
const logContainerRef = useRef<HTMLDivElement>(null)
useEffect(() => {
if (logContainerRef.current) {
logContainerRef.current.scrollTop = logContainerRef.current.scrollHeight
}
}, [logs])
if (!status) {
return null
}
const getStatusColor = () => {
switch (status) {
case 'pending':
return 'info'
case 'processing':
return 'warning'
case 'done':
return 'success'
case 'error':
return 'error'
default:
return 'default'
}
}
const getStatusLabel = () => {
switch (status) {
case 'pending':
return 'Waiting'
case 'processing':
return 'Processing'
case 'done':
return 'Complete'
case 'error':
return 'Error'
default:
return 'Unknown'
}
}
return (
<Paper sx={{ p: 3 }}>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
<Typography variant="h6">📊 Progress</Typography>
<Chip label={getStatusLabel()} color={getStatusColor()} size="small" />
</Box>
<Box sx={{ mb: 2 }}>
<LinearProgress
variant="determinate"
value={progress}
color={status === 'error' ? 'error' : status === 'done' ? 'success' : 'primary'}
sx={{ height: 10, borderRadius: 5 }}
/>
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
{progress}% {message}
</Typography>
</Box>
{error && (
<Alert severity="error" sx={{ mb: 2 }}>
{error}
</Alert>
)}
{tracks.length > 0 && status === 'done' && (
<Alert severity="success" sx={{ mb: 2 }}>
{tracks.length} track(s) extracted successfully!
</Alert>
)}
<Box
ref={logContainerRef}
sx={{
maxHeight: 200,
overflowY: 'auto',
bgcolor: 'background.default',
p: 2,
borderRadius: 1,
fontFamily: 'monospace',
fontSize: '12px',
lineHeight: 1.6,
}}
>
{logs.length === 0 ? (
<Typography variant="caption" color="text.secondary">
Waiting for progress updates...
</Typography>
) : (
logs.map((log, index) => (
<div key={index} style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
{log}
</div>
))
)}
</Box>
</Paper>
)
}
@@ -0,0 +1,167 @@
import React, { useCallback, useEffect, useRef, useState } from 'react'
import { Box, Paper, TextField, Typography, Alert } from '@mui/material'
import { useDropzone } from 'react-dropzone'
import { useTracklistStore } from '../stores/tracklistStore'
import { useOptionsStore } from '../stores/optionsStore'
import { parseAndValidateTracklist } from '../utils/validators'
export const TracklistEditor: React.FC = () => {
const { rawText, errors, isValid, setRawText, setEntries, setErrors, setIsValid } = useTracklistStore()
const { options } = useOptionsStore()
const [isDragging, setIsDragging] = useState(false)
const textAreaRef = useRef<HTMLTextAreaElement>(null)
const lineNumbersRef = useRef<HTMLDivElement>(null)
const validate = (text: string) => {
const result = parseAndValidateTracklist(text, options.tracklist_format)
setEntries(result.entries)
setErrors(result.errors)
setIsValid(result.isValid)
}
const handleTextChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
const text = event.target.value
setRawText(text)
validate(text)
}
const handleScroll = useCallback(() => {
if (lineNumbersRef.current && textAreaRef.current) {
lineNumbersRef.current.scrollTop = textAreaRef.current.scrollTop
}
}, [])
useEffect(() => {
const textArea = textAreaRef.current
if (textArea) {
textArea.addEventListener('scroll', handleScroll)
return () => textArea.removeEventListener('scroll', handleScroll)
}
}, [handleScroll])
useEffect(() => {
if (rawText) {
validate(rawText)
}
}, [options.tracklist_format])
const onDrop = useCallback(
(acceptedFiles: File[]) => {
if (acceptedFiles.length === 0) return
const file = acceptedFiles[0]
const reader = new FileReader()
reader.onload = (event) => {
const text = event.target?.result as string
setRawText(text)
validate(text)
setIsDragging(false)
}
reader.readAsText(file)
},
[setRawText]
)
const { getRootProps, getInputProps, isDragActive } = useDropzone({
onDrop,
accept: {
'text/plain': ['.txt'],
},
multiple: false,
})
const lineCount = rawText.split('\n').filter(line => line.trim() !== '').length
return (
<Paper
{...getRootProps()}
sx={{
p: 3,
border: isDragActive ? '2px dashed' : '1px solid',
borderColor: isDragActive ? 'primary.main' : 'divider',
borderRadius: 2,
backgroundColor: isDragActive ? 'action.hover' : 'background.paper',
transition: 'all 0.2s ease',
}}
>
<input {...getInputProps()} />
<Typography variant="subtitle1" sx={{ mb: 2 }}>
Tracklist
<Typography variant="caption" color="text.secondary" sx={{ ml: 2 }}>
{lineCount} track(s)
{isValid ? ' ✅' : errors.length > 0 ? ` ⚠️ ${errors.length} error(s)` : ''}
</Typography>
<Typography variant="caption" color="text.secondary" sx={{ ml: 2 }}>
Format: {options.tracklist_format}
</Typography>
</Typography>
<Box sx={{ display: 'flex', gap: 2, position: 'relative' }}>
{/* Line numbers column */}
<Box
ref={lineNumbersRef}
sx={{
minWidth: 40,
maxWidth: 60, // Allow more space for 3-digit numbers
fontFamily: 'monospace',
fontSize: '14px',
lineHeight: 1.7,
color: 'text.secondary',
textAlign: 'right',
userSelect: 'none',
overflow: 'hidden',
paddingTop: '8.5px',
paddingBottom: '8.5px',
scrollbarWidth: 'none',
'&::-webkit-scrollbar': { display: 'none' },
whiteSpace: 'nowrap', // Prevent wrapping of line numbers
}}
>
{rawText.split('\n').map((_, i) => (
<div key={i}>{i + 1}</div>
))}
</Box>
{/* Editor text area now with horizontal scroll and no wrap */}
<TextField
multiline
fullWidth
minRows={10}
maxRows={20}
value={rawText}
onChange={handleTextChange}
placeholder={`Enter your tracklist here...\n\nExample (format: ${options.tracklist_format}):\n00:00 Intro\n01:30 Song One - Artist A\n04:20-06:45 Another Song - Artist B`}
variant="outlined"
inputRef={textAreaRef}
sx={{
'& .MuiInputBase-root': {
fontFamily: 'monospace',
fontSize: '14px',
lineHeight: 1.7,
overflowX: 'auto', // Enable horizontal scroll
},
'& .MuiInputBase-input': {
paddingTop: '8.5px',
paddingBottom: '8.5px',
whiteSpace: 'nowrap', // Prevent wrapping
overflowX: 'auto',
},
}}
error={!isValid && errors.length > 0}
helperText={
!isValid && errors.length > 0
? errors.map((e) => `Line ${e.line}: ${e.message}`).join('; ')
: 'Drop a .txt file here or paste your tracklist'
}
/>
</Box>
{isDragActive && (
<Alert severity="info" sx={{ mt: 2 }}>
Drop your tracklist file (.txt) here
</Alert>
)}
</Paper>
)
}
+172
View File
@@ -0,0 +1,172 @@
import React, { useCallback } from 'react'
import { useDropzone } from 'react-dropzone'
import { Box, Typography, Paper, LinearProgress, Alert } from '@mui/material'
import { CloudUpload, InsertDriveFile } from '@mui/icons-material'
import { useUploadStore } from '../stores/uploadStore'
import { useOptionsStore } from '../stores/optionsStore' // NEW
import { uploadFile, getTaskInfo, getRecommendedFormat } from '../api/client' // NEW
import { useTaskStore } from '../stores/taskStore'
const ALLOWED_EXTENSIONS = ['.mp3', '.flac', '.wav', '.m4a', '.ogg', '.opus', '.aac', '.wma', '.aiff', '.alac', '.ac3', '.mp4', '.mkv', '.webm']
export const UploadZone: React.FC = () => {
const {
file,
fileName,
fileSize,
isUploading,
uploadProgress,
error,
setFile,
setFileName,
setFileSize,
setIsUploading,
setUploadProgress,
setError,
setTaskId,
setHasVideo,
setHasAudio,
setHasSubtitle,
setAudioCodec,
} = useUploadStore()
const { setTaskId: setTaskIdStore } = useTaskStore()
const { setOptions } = useOptionsStore() // NEW
const onDrop = useCallback(
async (acceptedFiles: File[]) => {
if (acceptedFiles.length === 0) return
const selectedFile = acceptedFiles[0]
const extension = '.' + selectedFile.name.split('.').pop()?.toLowerCase()
if (!ALLOWED_EXTENSIONS.includes(extension)) {
setError(`Unsupported file format. Allowed: ${ALLOWED_EXTENSIONS.join(', ')}`)
return
}
setFile(selectedFile)
setFileName(selectedFile.name)
setFileSize(selectedFile.size)
setError(null)
setIsUploading(true)
setUploadProgress(0)
try {
const response = await uploadFile(selectedFile)
const taskId = response.task_id
setTaskId(taskId)
setTaskIdStore(taskId)
setUploadProgress(100)
setIsUploading(false)
// Fetch stream info
try {
const info = await getTaskInfo(taskId)
setHasVideo(info.has_video)
setHasAudio(info.has_audio)
setHasSubtitle(info.has_subtitle)
setAudioCodec(info.audio_codec)
// Fetch recommended format and update options
try {
// Inside UploadZone.tsx, after fetching recommended format:
const rec = await getRecommendedFormat(taskId)
// Update options store with container (not format)
setOptions({ container: rec.format })
} catch (err) {
console.warn('Failed to fetch recommended format, using default', err)
}
} catch (err) {
console.error('Failed to fetch stream info:', err)
// Don't block upload flow; user can manually change options
}
} catch (err: any) {
setError(err.response?.data?.detail || err.message || 'Upload failed')
setIsUploading(false)
setUploadProgress(0)
setFile(null)
setFileName('')
setFileSize(0)
}
},
[setFile, setFileName, setFileSize, setIsUploading, setUploadProgress, setError, setTaskId, setTaskIdStore, setHasVideo, setHasAudio, setHasSubtitle, setAudioCodec, setOptions]
)
const { getRootProps, getInputProps, isDragActive } = useDropzone({
onDrop,
accept: {
'media/*': ALLOWED_EXTENSIONS
},
multiple: false,
disabled: isUploading,
})
const formatFileSize = (bytes: number): string => {
if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}
return (
<Box>
<Paper
{...getRootProps()}
sx={{
p: 4,
border: '2px dashed',
borderColor: isDragActive ? 'primary.main' : 'grey.300',
borderRadius: 2,
backgroundColor: isDragActive ? 'action.hover' : 'background.paper',
cursor: isUploading ? 'default' : 'pointer',
transition: 'all 0.2s ease',
textAlign: 'center',
}}
>
<input {...getInputProps()} />
{file ? (
<Box>
<InsertDriveFile sx={{ fontSize: 48, color: 'primary.main', mb: 1 }} />
<Typography variant="h6">{fileName}</Typography>
<Typography variant="body2" color="text.secondary">
{formatFileSize(fileSize)}
</Typography>
{isUploading && (
<Box sx={{ mt: 2, width: '100%' }}>
<LinearProgress variant="determinate" value={uploadProgress} />
<Typography variant="caption" color="text.secondary">
{uploadProgress}% uploaded
</Typography>
</Box>
)}
{!isUploading && (
<Typography variant="caption" color="success.main" sx={{ mt: 1, display: 'block' }}>
Uploaded successfully
</Typography>
)}
</Box>
) : (
<Box>
<CloudUpload sx={{ fontSize: 64, color: 'primary.main', mb: 2 }} />
<Typography variant="h6" color="text.secondary">
{isDragActive ? 'Drop your audio file here' : 'Drag & drop your audio file here'}
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
or click to browse
</Typography>
<Typography variant="caption" color="text.secondary" sx={{ mt: 2, display: 'block' }}>
Supported formats: {ALLOWED_EXTENSIONS.join(', ')}
</Typography>
</Box>
)}
</Paper>
{error && (
<Alert severity="error" sx={{ mt: 2 }}>
{error}
</Alert>
)}
</Box>
)
}
+31
View File
@@ -0,0 +1,31 @@
import { useMemo } from 'react'
import { CodecInfo } from '../types'
export interface CompatibilityEntry {
audio: string[] | null
video: string[] | null
}
export function useFilterCodecs(
compatibility: Record<string, CompatibilityEntry>,
container: string | null,
codecs: CodecInfo[]
) {
const filteredAudioCodecs = useMemo(() => {
const entry = compatibility?.[container || '']
if (!entry) return codecs.filter(c => c.codec_type === 'audio')
const audioList = entry.audio
if (audioList === null) return codecs.filter(c => c.codec_type === 'audio')
return codecs.filter(c => c.codec_type === 'audio' && audioList.includes(c.name))
}, [compatibility, container, codecs])
const filteredVideoCodecs = useMemo(() => {
const entry = compatibility?.[container || '']
if (!entry) return codecs.filter(c => c.codec_type === 'video')
const videoList = entry.video
if (videoList === null) return codecs.filter(c => c.codec_type === 'video')
return codecs.filter(c => c.codec_type === 'video' && videoList.includes(c.name))
}, [compatibility, container, codecs])
return { filteredAudioCodecs, filteredVideoCodecs }
}
@@ -0,0 +1,56 @@
import { useEffect } from 'react'
import { ContainerInfo } from '../types'
import { CompatibilityEntry } from './useFilterCodecs'
export function useFormatValidation(
options: {
container: string | null
audio_codec: string
video_codec: string
drop_video: boolean
},
hasVideo: boolean,
compatibility: Record<string, CompatibilityEntry>,
containers: ContainerInfo[],
setFormatError: (error: string | null) => void
) {
useEffect(() => {
const selectedContainer = containers.find(c => c.name === options.container)
if (!selectedContainer?.supports_video && hasVideo && !options.drop_video) {
setFormatError(
`Container '${options.container}' does not support video streams. Please enable "Drop video" or choose a container that supports video.`
)
return
}
// Check audio codec compatibility
if (options.audio_codec && options.audio_codec !== 'copy' && options.container) {
const entry = compatibility?.[options.container]
if (entry) {
const audioList = entry.audio
if (audioList !== null && !audioList.includes(options.audio_codec)) {
setFormatError(
`Audio codec '${options.audio_codec}' is not supported by container '${options.container}'.`
)
return
}
}
}
// Check video codec compatibility
if (options.video_codec && options.video_codec !== 'copy' && options.container && hasVideo && !options.drop_video) {
const entry = compatibility?.[options.container]
if (entry) {
const videoList = entry.video
if (videoList !== null && !videoList.includes(options.video_codec)) {
setFormatError(
`Video codec '${options.video_codec}' is not supported by container '${options.container}'.`
)
return
}
}
}
setFormatError(null)
}, [options.container, options.audio_codec, options.video_codec, options.drop_video, hasVideo, compatibility, containers, setFormatError])
}
+190
View File
@@ -0,0 +1,190 @@
import { useEffect, useRef } from 'react'
import { useTaskStore } from '../stores/taskStore'
import { useUIStore } from '../stores/uiStore'
import { getStatus } from '../api/client'
export const useWebSocket = (taskId: string | null) => {
const wsRef = useRef<WebSocket | null>(null)
const reconnectTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const reconnectAttempts = useRef(0)
const pollingRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const {
setStatus,
setProgress,
setMessage,
setError,
setTracks,
addLog,
setIsProcessing,
status,
} = useTaskStore()
const { setWsConnected } = useUIStore()
const pollStatus = async () => {
if (!taskId) return
try {
const response = await getStatus(taskId)
console.log('[Polling] Status response:', response)
// Update all state fields together
setStatus(response.status)
setProgress(response.progress)
setMessage(response.message)
// Explicitly set tracks if present
if (response.tracks && response.tracks.length > 0) {
console.log('[Polling] Setting tracks:', response.tracks)
setTracks(response.tracks)
}
if (response.status === 'done') {
console.log('[Polling] Split complete, tracks set:', response.tracks)
setIsProcessing(false)
// Ensure tracks are set one more time (safety)
if (response.tracks && response.tracks.length > 0) {
setTracks(response.tracks)
}
return
}
if (response.status === 'error') {
setError(response.error || 'Split failed')
setIsProcessing(false)
return
}
// Still processing poll again
if (pollingRef.current) {
clearTimeout(pollingRef.current)
}
pollingRef.current = setTimeout(pollStatus, 2000)
} catch (error) {
console.error('[Polling] Error:', error)
if (pollingRef.current) {
clearTimeout(pollingRef.current)
}
pollingRef.current = setTimeout(pollStatus, 3000)
}
}
useEffect(() => {
if (!taskId) {
if (wsRef.current) {
wsRef.current.close()
wsRef.current = null
}
setWsConnected(false)
// Clear polling
if (pollingRef.current) {
clearTimeout(pollingRef.current)
pollingRef.current = null
}
return
}
const connect = () => {
const wsUrl = `/ws/${taskId}`
const ws = new WebSocket(wsUrl)
ws.onopen = () => {
console.log(`WebSocket connected for task ${taskId}`)
setWsConnected(true)
reconnectAttempts.current = 0
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current)
reconnectTimeoutRef.current = null
}
// Start polling when connection is established
// This ensures we get the final status even if WebSocket fails
setTimeout(() => {
pollStatus()
}, 1000)
}
ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data)
console.log('[WebSocket] Message:', data)
if (data.type === 'status') {
const statusData = data.data
setStatus(statusData.status)
setProgress(statusData.progress)
setMessage(statusData.message)
if (statusData.error) {
setError(statusData.error)
}
if (statusData.tracks) {
setTracks(statusData.tracks)
}
if (statusData.status === 'done' || statusData.status === 'error') {
setIsProcessing(false)
}
} else if (data.type === 'progress') {
const progressData = data.data
setStatus(progressData.status)
setProgress(progressData.progress)
setMessage(progressData.message)
if (progressData.tracks) {
setTracks(progressData.tracks)
}
if (progressData.status === 'done') {
addLog('✅ Split complete!')
setIsProcessing(false)
} else if (progressData.status === 'error') {
setError(progressData.message)
addLog(`❌ Error: ${progressData.message}`)
setIsProcessing(false)
} else {
addLog(`🔄 ${progressData.message} (${progressData.progress}%)`)
}
}
} catch (error) {
console.error('[WebSocket] Failed to parse message:', error)
}
}
ws.onclose = () => {
console.log(`WebSocket disconnected for task ${taskId}`)
setWsConnected(false)
// If task is not done and we have a taskId, start polling
// We check the status store to see if it's already done
if (taskId && status !== 'done' && status !== 'error') {
console.log('[WebSocket] Disconnected while processing, starting polling...')
setTimeout(pollStatus, 1000)
}
}
ws.onerror = (error) => {
console.error('[WebSocket] Error:', error)
// onclose will handle reconnection
}
wsRef.current = ws
}
connect()
return () => {
if (wsRef.current) {
wsRef.current.close()
wsRef.current = null
}
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current)
reconnectTimeoutRef.current = null
}
if (pollingRef.current) {
clearTimeout(pollingRef.current)
pollingRef.current = null
}
setWsConnected(false)
}
}, [taskId, setStatus, setProgress, setMessage, setError, setTracks, addLog, setWsConnected, setIsProcessing, status])
return wsRef.current
}
+18
View File
@@ -0,0 +1,18 @@
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Roboto', 'Helvetica', 'Arial', sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
background-color: #f5f5f5;
}
#root {
min-height: 100vh;
display: flex;
flex-direction: column;
}
+10
View File
@@ -0,0 +1,10 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)
+77
View File
@@ -0,0 +1,77 @@
import { create } from 'zustand'
import { SplitOptions, ContainerInfo, CodecInfo } from '../types'
import {
DEFAULT_FORMAT,
DEFAULT_OUTPUT_TEMPLATE,
DEFAULT_REPLACEMENT_CHAR,
DEFAULT_BAD_CHARS,
DEFAULT_ALBUM,
DEFAULT_COMMENT,
DEFAULT_NO_COMMENT,
DEFAULT_COMMENT_STREAM,
DEFAULT_MERGE_COMMENTS,
DEFAULT_COMMENT_SEPARATOR,
DEFAULT_DROP_VIDEO,
DEFAULT_DROP_SUBS,
DEFAULT_NUMBER_TRACKS,
DEFAULT_REPLACE_BAD_CHARS,
DEFAULT_SKIP_EXISTING,
DEFAULT_TRACKLIST_FORMAT,
} from '../constants/generated'
// We use DEFAULT_FORMAT only as a fallback; container default is null (auto-detect)
const DEFAULT_OPTIONS: SplitOptions = {
container: null,
audio_codec: 'copy',
video_codec: 'copy',
subtitle_codec: 'copy',
video_quality: null,
drop_video: DEFAULT_DROP_VIDEO,
drop_subs: DEFAULT_DROP_SUBS,
number_tracks: DEFAULT_NUMBER_TRACKS,
replace_bad_chars: DEFAULT_REPLACE_BAD_CHARS,
replacement_char: DEFAULT_REPLACEMENT_CHAR,
bad_chars: DEFAULT_BAD_CHARS,
skip_existing: DEFAULT_SKIP_EXISTING,
output_template: DEFAULT_OUTPUT_TEMPLATE,
album: DEFAULT_ALBUM ?? '',
comment: DEFAULT_COMMENT ?? '',
no_comment: DEFAULT_NO_COMMENT,
comment_stream: DEFAULT_COMMENT_STREAM,
merge_comments: DEFAULT_MERGE_COMMENTS,
comment_separator: DEFAULT_COMMENT_SEPARATOR,
tracklist_format: DEFAULT_TRACKLIST_FORMAT,
}
interface OptionsState {
options: SplitOptions
containers: ContainerInfo[]
codecs: CodecInfo[]
compatibility: Record<string, { audio: string[] | null; video: string[] | null }>
setOptions: (newOptions: Partial<SplitOptions>) => void
setContainers: (containers: ContainerInfo[]) => void
setCodecs: (codecs: CodecInfo[]) => void
setCompatibility: (compat: Record<string, { audio: string[] | null; video: string[] | null }>) => void
reset: () => void
}
export const useOptionsStore = create<OptionsState>((set) => ({
options: { ...DEFAULT_OPTIONS },
containers: [],
codecs: [],
compatibility: {},
setOptions: (newOptions) =>
set((state) => ({
options: { ...state.options, ...newOptions },
})),
setContainers: (containers) => set({ containers }),
setCodecs: (codecs) => set({ codecs }),
setCompatibility: (compatibility) => set({ compatibility }),
reset: () =>
set({
options: { ...DEFAULT_OPTIONS },
containers: [],
codecs: [],
compatibility: {},
}),
}))
+54
View File
@@ -0,0 +1,54 @@
import { create } from 'zustand'
import { TrackInfo } from '../types'
interface TaskState {
taskId: string | null
status: 'pending' | 'processing' | 'done' | 'error' | null
progress: number
message: string
error: string | null
tracks: TrackInfo[]
logs: string[]
isProcessing: boolean
setTaskId: (taskId: string | null) => void
setStatus: (status: 'pending' | 'processing' | 'done' | 'error' | null) => void
setProgress: (progress: number) => void
setMessage: (message: string) => void
setError: (error: string | null) => void
setTracks: (tracks: TrackInfo[]) => void
addLog: (log: string) => void
setIsProcessing: (isProcessing: boolean) => void
reset: () => void
}
export const useTaskStore = create<TaskState>((set) => ({
taskId: null,
status: null,
progress: 0,
message: '',
error: null,
tracks: [],
logs: [],
isProcessing: false,
setTaskId: (taskId) => set({ taskId }),
setStatus: (status) => set({ status }),
setProgress: (progress) => set({ progress }),
setMessage: (message) => set({ message }),
setError: (error) => set({ error }),
setTracks: (tracks) => set({ tracks }),
addLog: (log) => set((state) => ({ logs: [...state.logs, log] })),
setIsProcessing: (isProcessing) => set({ isProcessing }),
reset: () =>
set({
taskId: null,
status: null,
progress: 0,
message: '',
error: null,
tracks: [],
logs: [],
isProcessing: false,
}),
}))
+39
View File
@@ -0,0 +1,39 @@
import { create } from 'zustand'
import { TracklistEntry } from '../types'
interface TracklistState {
rawText: string
entries: TracklistEntry[]
errors: { line: number; message: string }[]
isValid: boolean
isDragging: boolean
setRawText: (text: string) => void
setEntries: (entries: TracklistEntry[]) => void
setErrors: (errors: { line: number; message: string }[]) => void
setIsValid: (isValid: boolean) => void
setIsDragging: (isDragging: boolean) => void
reset: () => void
}
export const useTracklistStore = create<TracklistState>((set) => ({
rawText: '',
entries: [],
errors: [],
isValid: false,
isDragging: false,
setRawText: (rawText) => set({ rawText }),
setEntries: (entries) => set({ entries }),
setErrors: (errors) => set({ errors }),
setIsValid: (isValid) => set({ isValid }),
setIsDragging: (isDragging) => set({ isDragging }),
reset: () =>
set({
rawText: '',
entries: [],
errors: [],
isValid: false,
isDragging: false,
}),
}))
+31
View File
@@ -0,0 +1,31 @@
import { create } from 'zustand'
interface UIState {
theme: 'light' | 'dark'
isSidebarOpen: boolean
wsConnected: boolean
toggleTheme: () => void
setTheme: (theme: 'light' | 'dark') => void
toggleSidebar: () => void
setSidebarOpen: (isOpen: boolean) => void
setWsConnected: (connected: boolean) => void
}
export const useUIStore = create<UIState>((set) => ({
theme: 'light',
isSidebarOpen: false,
wsConnected: false,
toggleTheme: () =>
set((state) => ({
theme: state.theme === 'light' ? 'dark' : 'light',
})),
setTheme: (theme) => set({ theme }),
toggleSidebar: () =>
set((state) => ({
isSidebarOpen: !state.isSidebarOpen,
})),
setSidebarOpen: (isSidebarOpen) => set({ isSidebarOpen }),
setWsConnected: (wsConnected) => set({ wsConnected }),
}))
+69
View File
@@ -0,0 +1,69 @@
import { create } from 'zustand'
interface UploadState {
file: File | null
taskId: string | null
fileName: string
fileSize: number
isUploading: boolean
uploadProgress: number
error: string | null
// New fields for stream info
hasVideo: boolean
hasAudio: boolean
hasSubtitle: boolean
audioCodec: string | null
setFile: (file: File | null) => void
setTaskId: (taskId: string | null) => void
setFileName: (name: string) => void
setFileSize: (size: number) => void
setIsUploading: (isUploading: boolean) => void
setUploadProgress: (progress: number) => void
setError: (error: string | null) => void
setHasVideo: (hasVideo: boolean) => void
setHasAudio: (hasAudio: boolean) => void
setHasSubtitle: (hasSubtitle: boolean) => void
setAudioCodec: (audioCodec: string | null) => void
reset: () => void
}
export const useUploadStore = create<UploadState>((set) => ({
file: null,
taskId: null,
fileName: '',
fileSize: 0,
isUploading: false,
uploadProgress: 0,
error: null,
hasVideo: false,
hasAudio: false,
hasSubtitle: false,
audioCodec: null,
setFile: (file) => set({ file }),
setTaskId: (taskId) => set({ taskId }),
setFileName: (fileName) => set({ fileName }),
setFileSize: (fileSize) => set({ fileSize }),
setIsUploading: (isUploading) => set({ isUploading }),
setUploadProgress: (uploadProgress) => set({ uploadProgress }),
setError: (error) => set({ error }),
setHasVideo: (hasVideo) => set({ hasVideo }),
setHasAudio: (hasAudio) => set({ hasAudio }),
setHasSubtitle: (hasSubtitle) => set({ hasSubtitle }),
setAudioCodec: (audioCodec) => set({ audioCodec }),
reset: () =>
set({
file: null,
taskId: null,
fileName: '',
fileSize: 0,
isUploading: false,
uploadProgress: 0,
error: null,
hasVideo: false,
hasAudio: false,
hasSubtitle: false,
audioCodec: null,
}),
}))
@@ -0,0 +1,11 @@
import { create } from 'zustand'
interface ValidationState {
formatError: string | null
setFormatError: (error: string | null) => void
}
export const useValidationStore = create<ValidationState>((set) => ({
formatError: null,
setFormatError: (error) => set({ formatError: error }),
}))
+83
View File
@@ -0,0 +1,83 @@
export interface TracklistEntry {
ts: string
tn?: string
an?: string
al?: string
date?: string
ext?: string
}
export interface TrackInfo {
filename: string
size: number
}
export interface TaskStatus {
task_id: string
status: 'pending' | 'processing' | 'done' | 'error'
progress: number
message: string
error: string | null
tracks: TrackInfo[]
}
export interface SplitOptions {
container: string | null // null = auto-detect
audio_codec: string // 'copy' or encoder name
video_codec: string // 'copy' or encoder name
subtitle_codec: string // 'copy' or encoder name
video_quality: number | null // encoder-specific integer
drop_video: boolean
drop_subs: boolean
number_tracks: boolean
replace_bad_chars: boolean
replacement_char: string
bad_chars: string
skip_existing: boolean
output_template: string
album: string
comment: string
no_comment: boolean
comment_stream: number | null
merge_comments: boolean
comment_separator: string
tracklist_format: string // for frontend parsing
}
export interface ContainerInfo {
name: string
ffmpeg: string
extension: string
supports_video: boolean
supports_subs: boolean
}
export interface CodecInfo {
name: string
ffmpeg: string
recommended_container: string
recommended_extension: string
codec_type: 'audio' | 'video' | 'subtitle'
}
export interface CompatibilityEntry {
audio: string[] | null
video: string[] | null
}
export interface FormatsResponse {
containers: ContainerInfo[]
codecs: CodecInfo[]
compatibility: Record<string, CompatibilityEntry>
}
export interface UploadResponse {
task_id: string
filename: string
size: number
}
export interface SplitResponse {
task_id: string
status: string
}
+7
View File
@@ -0,0 +1,7 @@
export const formatFileSize = (bytes: number): string => {
if (bytes === 0) return '0 B'
const k = 1024
const sizes = ['B', 'KB', 'MB', 'GB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
}
+119
View File
@@ -0,0 +1,119 @@
// web/frontend/src/utils/parser.ts
import { TracklistEntry } from '../types'
type Token = { type: 'literal'; value: string } | { type: 'placeholder'; value: string }
export function parseFormat(formatStr: string): Token[] {
const validPlaceholders = new Set(['ts', 'tn', 'an', 'al', 'date', 'ext'])
const tokens: Token[] = []
let i = 0
while (i < formatStr.length) {
const ch = formatStr[i]
if (ch === '%') {
if (i + 1 < formatStr.length && formatStr[i + 1] === '%') {
tokens.push({ type: 'literal', value: '%' })
i += 2
continue
}
// match %letters
const match = formatStr.substring(i).match(/^%([a-zA-Z]+)/)
if (!match) {
throw new Error(`Invalid placeholder at position ${i}: '${formatStr.substring(i)}'`)
}
const placeholder = match[1]
if (!validPlaceholders.has(placeholder)) {
throw new Error(`Unknown placeholder '%${placeholder}'. Allowed: ${Array.from(validPlaceholders).join(', ')}`)
}
tokens.push({ type: 'placeholder', value: placeholder })
i += match[0].length
} else {
let j = i
while (j < formatStr.length && formatStr[j] !== '%') {
j++
}
tokens.push({ type: 'literal', value: formatStr.substring(i, j) })
i = j
}
}
return tokens
}
export function parseLine(line: string, tokens: Token[]): Record<string, string | null> {
line = line.trim()
if (!line) {
throw new Error('Empty line')
}
const result: Record<string, string | null> = {}
let pos = 0
for (let idx = 0; idx < tokens.length; idx++) {
const token = tokens[idx]
if (token.type === 'literal') {
const literal = token.value
if (!line.startsWith(literal, pos)) {
throw new Error(`Expected literal '${literal}' at position ${pos}, got '${line.substring(pos)}'`)
}
pos += literal.length
} else {
// placeholder
const placeholder = token.value
// If this is the last token, capture the rest
if (idx === tokens.length - 1) {
const value = line.substring(pos).trim()
result[placeholder] = value || null
pos = line.length
} else {
// Find the next literal to use as delimiter
let nextLiteral: string | null = null
for (let j = idx + 1; j < tokens.length; j++) {
if (tokens[j].type === 'literal') {
nextLiteral = tokens[j].value
break
}
}
if (nextLiteral === null) {
const value = line.substring(pos).trim()
result[placeholder] = value || null
pos = line.length
} else {
const nextPos = line.indexOf(nextLiteral, pos)
if (nextPos === -1) {
throw new Error(`Could not find literal '${nextLiteral}' after placeholder '${placeholder}'`)
}
const value = line.substring(pos, nextPos).trim()
result[placeholder] = value || null
pos = nextPos
}
}
}
}
return result
}
export function parseTracklistWithFormat(text: string, format: string): TracklistEntry[] {
const tokens = parseFormat(format)
const lines = text.split('\n').filter(line => line.trim() !== '')
const entries: TracklistEntry[] = []
for (const line of lines) {
try {
const parsed = parseLine(line, tokens)
const entry: TracklistEntry = {
ts: parsed.ts || '',
tn: parsed.tn || '',
an: parsed.an || '',
al: parsed.al || '',
date: parsed.date || '',
ext: parsed.ext || '',
}
entries.push(entry)
} catch (error) {
// We'll handle errors in the validator; just skip or mark as invalid
// For now, we'll push an empty entry with an error flag
entries.push({ ts: '', tn: line, an: '' })
}
}
return entries
}
+61
View File
@@ -0,0 +1,61 @@
// web/frontend/src/utils/validators.ts
import { TracklistEntry } from '../types'
import { parseTracklistWithFormat } from './parser'
export const validateTracklist = (
entries: TracklistEntry[]
): { isValid: boolean; errors: { line: number; message: string }[] } => {
const errors: { line: number; message: string }[] = []
entries.forEach((entry, index) => {
const lineNum = index + 1
if (!entry.ts || !entry.ts.trim()) {
errors.push({ line: lineNum, message: 'Missing timestamp (%ts)' })
} else {
// Validate timestamp format
const ts = entry.ts.trim()
if (!/^\d{1,2}:\d{2}(:\d{2})?$/.test(ts) && !/^\d{1,2}:\d{2}-\d{1,2}:\d{2}$/.test(ts)) {
errors.push({ line: lineNum, message: 'Invalid timestamp format. Expected mm:ss or mm:ss-HH:MM:SS' })
}
}
if (!entry.tn || !entry.tn.trim()) {
errors.push({ line: lineNum, message: 'Missing track name (%tn)' })
}
})
return {
isValid: errors.length === 0,
errors,
}
}
// New function that parses and validates using the format
export function parseAndValidateTracklist(text: string, format: string): {
entries: TracklistEntry[]
errors: { line: number; message: string }[]
isValid: boolean
} {
// We need to handle parsing errors gracefully.
// parseTracklistWithFormat will throw on some errors, but we can catch and mark as invalid.
try {
const entries = parseTracklistWithFormat(text, format)
const validation = validateTracklist(entries)
return {
entries,
errors: validation.errors,
isValid: validation.isValid,
}
} catch (error) {
// If parsing fails (e.g., invalid format), treat all lines as errors
const lines = text.split('\n').filter(line => line.trim() !== '')
const errors = lines.map((_, index) => ({
line: index + 1,
message: error instanceof Error ? error.message : 'Parse error',
}))
return {
entries: [],
errors,
isValid: false,
}
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}
+10
View File
@@ -0,0 +1,10 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true
},
"include": ["vite.config.ts"]
}
+24
View File
@@ -0,0 +1,24 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// Backend URL for proxy (default to localhost for local dev)
const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:8000'
export default defineConfig({
plugins: [react()],
server: {
proxy: {
'/api': {
target: BACKEND_URL,
changeOrigin: true,
secure: false,
},
'/ws': {
target: BACKEND_URL.replace(/^http/, 'ws'),
ws: true,
changeOrigin: true,
secure: false,
},
},
},
})
+8
View File
@@ -0,0 +1,8 @@
fastapi>=0.104.0
uvicorn[standard]>=0.24.0
python-multipart>=0.0.6
aiofiles>=23.2.0
pydantic>=2.5.0
pydantic-settings>=2.0.0
python-dotenv>=1.0.0
websockets>=12.0