Myriad changes.
This commit is contained in:
1 parent
f6ff8873c8
commit
bbe2b41880
74 files changed
+6022
-1866
No files matched your search
@@ -65,6 +65,441 @@ Secondary test stabilizations:
|
||||
|
||||
---
|
||||
|
||||
## 2026-04-04 Update — Sing settings UX and Subsonic browse wiring
|
||||
|
||||
Completed follow-up corrections for the library/sing shell flow and Subsonic connectivity visibility.
|
||||
|
||||
### Implemented
|
||||
|
||||
- `frontend/src/App.tsx`
|
||||
- Added a discrete right-side Settings overlay for library routes.
|
||||
- Overlay close behaviors now include:
|
||||
- close button,
|
||||
- backdrop click,
|
||||
- `Escape` key.
|
||||
- Kept direct `/settings` route support for compatibility.
|
||||
|
||||
- `frontend/src/components/AppLibraryShell.tsx`
|
||||
- Added optional `onOpenSettings` callback prop.
|
||||
- Settings button now opens overlay when callback is provided, otherwise falls back to route navigation.
|
||||
|
||||
- `frontend/src/hooks/useSubsonicLibrary.ts` (new)
|
||||
- Added shared hook to load library data via:
|
||||
- `getSubsonicConfig()`
|
||||
- `searchSubsonic()`
|
||||
- Exposes `songs`, `loading`, `configured`, `error`, and `refresh` state.
|
||||
|
||||
- `frontend/src/pages/Tracks.tsx`
|
||||
- Replaced placeholder tracks with Subsonic-backed results.
|
||||
- Added configuration and API error banners.
|
||||
|
||||
- `frontend/src/pages/Albums.tsx`
|
||||
- Replaced placeholder albums with derived album groupings from Subsonic songs.
|
||||
- Added configuration and API error banners.
|
||||
|
||||
- `frontend/src/pages/Artists.tsx`
|
||||
- Replaced placeholder artists with derived artist/album counts from Subsonic songs.
|
||||
- Added configuration and API error banners.
|
||||
|
||||
- `frontend/src/pages/Playlists.tsx`
|
||||
- Added explicit notice that playlist browse wiring is pending backend endpoint parity.
|
||||
|
||||
### Validation
|
||||
|
||||
- `cd frontend && npm run build` → pass
|
||||
|
||||
### Documentation
|
||||
|
||||
- Updated: `docs/KARAOKE_FRONTEND_STEMENGINE_CONNECTIVITY_PLAN.md`
|
||||
- Added section: `2026-04-04 discrepancy review + action plan (Sing settings + Subsonic browsing)`
|
||||
|
||||
---
|
||||
|
||||
## 2026-04-04 Update — Playlist API wiring + convert status end-to-end
|
||||
|
||||
Completed Subsonic playlist backend/frontend wiring and connected library convert buttons to live status transitions.
|
||||
|
||||
### Implemented
|
||||
|
||||
- `backend/routers/subsonic.py`
|
||||
- Added playlist routes:
|
||||
- `GET /api/subsonic/playlists`
|
||||
- `GET /api/subsonic/playlists/{playlist_id}`
|
||||
- Removed the early-empty guard in `GET /api/subsonic/search` so browse flows can request results without forcing a manual query term.
|
||||
|
||||
- `backend/services/subsonic_service.py`
|
||||
- `search_songs()` now falls back to wildcard query (`*`) when no query/filter is supplied.
|
||||
- Added `list_playlists()` to call `getPlaylists.view`.
|
||||
- Added `get_playlist()` to call `getPlaylist.view` and return normalized track entries.
|
||||
|
||||
- `frontend/src/types.ts`
|
||||
- Added:
|
||||
- `SubsonicPlaylist`
|
||||
- `SubsonicPlaylistDetail`
|
||||
|
||||
- `frontend/src/api/client.ts`
|
||||
- Added:
|
||||
- `listSubsonicPlaylists()`
|
||||
- `getSubsonicPlaylist(playlistId)`
|
||||
|
||||
- `frontend/src/pages/Playlists.tsx`
|
||||
- Replaced placeholder-only behavior with API-backed playlist loading.
|
||||
- Added config/loader/error states tied to Subsonic configuration.
|
||||
|
||||
- `frontend/src/hooks/useConvertStatus.ts` (new)
|
||||
- Added end-to-end convert orchestration:
|
||||
- import from Subsonic,
|
||||
- submit separation from imported path,
|
||||
- poll job to terminal state,
|
||||
- refresh project list,
|
||||
- map per-song status to `queued` / `running` / `ready` / `failed`.
|
||||
|
||||
- `frontend/src/pages/Tracks.tsx`
|
||||
- Convert button now executes full conversion pipeline.
|
||||
- Button label reflects live status (`Queued`, `Running`, `Ready`, `Retry`).
|
||||
|
||||
- `frontend/src/pages/Albums.tsx`
|
||||
- Album convert now runs batched song conversion.
|
||||
- Album-level button status is derived from per-song state aggregate (`queued` / `running` / `ready` / `failed`).
|
||||
|
||||
### Validation
|
||||
|
||||
- `cd frontend && npm run build` → pass
|
||||
- `python3 -m py_compile backend/routers/subsonic.py backend/services/subsonic_service.py` → pass
|
||||
|
||||
---
|
||||
|
||||
## 2026-04-04 Update — Sing interface Subsonic browsing + convert status in-route
|
||||
|
||||
Follow-up implementation aligned with the connectivity plan expectations for the Sing interface itself.
|
||||
|
||||
### Implemented
|
||||
|
||||
- `frontend/src/pages/Sing.tsx`
|
||||
- Added dual-mode Sing view:
|
||||
- `Karaoke Projects`
|
||||
- `Subsonic Library`
|
||||
- Added shared search input behavior per active mode.
|
||||
- Added Subsonic config/error/loading states directly in Sing page.
|
||||
- Added per-song convert action in Sing Subsonic mode with live status labels:
|
||||
- `Queued`, `Running`, `Ready`, `Retry`.
|
||||
|
||||
- `frontend/src/hooks/useSubsonicLibrary.ts`
|
||||
- Switched browse query to wildcard (`q='*'`) to support list-style browsing even when no explicit search term is entered.
|
||||
|
||||
### Validation
|
||||
|
||||
- `cd frontend && npm run build` → pass
|
||||
|
||||
### Documentation
|
||||
|
||||
- Updated: `docs/KARAOKE_FRONTEND_STEMENGINE_CONNECTIVITY_PLAN.md`
|
||||
- Added section: `2026-04-04 implementation update — Sing interface functional parity slice`
|
||||
|
||||
---
|
||||
|
||||
## 2026-04-04 Update — Sing standard-player interface refactor
|
||||
|
||||
Expanded Sing route UI from simple dual-toggle into a standard player-style interface with integrated karaoke workflows.
|
||||
|
||||
### Implemented
|
||||
|
||||
- `frontend/src/pages/Sing.tsx`
|
||||
- Added in-page mode tabs:
|
||||
- `Home`, `Tracks`, `Albums`, `Artists`, `Playlists`, `Karaoke`.
|
||||
- Added mode-specific search behavior and content rendering.
|
||||
- Added home dashboard cards (tracks/albums/artists/karaoke projects) and featured sections.
|
||||
- Added Tracks list with per-song convert status/actions.
|
||||
- Added Albums grid with batch convert + aggregate status labels.
|
||||
- Added Artists and Playlists browse views in Sing route.
|
||||
- Retained Karaoke project launcher behavior to `/karaoke` route.
|
||||
|
||||
- `frontend/src/hooks/useSubsonicLibrary.ts`
|
||||
- Ensured browse mode query uses wildcard (`q='*'`) so initial library load does not require manual search text.
|
||||
|
||||
### Validation
|
||||
|
||||
- `cd frontend && npm run build` → pass
|
||||
|
||||
### Documentation
|
||||
|
||||
- Updated: `docs/KARAOKE_FRONTEND_STEMENGINE_CONNECTIVITY_PLAN.md`
|
||||
- Added section: `2026-04-04 implementation update — Sing as standard player + karaoke hub`
|
||||
|
||||
---
|
||||
|
||||
## 2026-04-05 Update — Deployment port alignment + API-only backend mode
|
||||
|
||||
Aligned runtime deployment behavior with split frontend/backend services.
|
||||
|
||||
### Implemented
|
||||
|
||||
- `stemengine.yml`
|
||||
- Confirmed/kept canonical port mappings:
|
||||
- WebUI: `5174:5173`
|
||||
- Backend: `8000:8000`
|
||||
- SingUI: `3001:5173`
|
||||
- Added backend env guard:
|
||||
- `BACKEND_SERVE_LEGACY_WEBUI=${BACKEND_SERVE_LEGACY_WEBUI:-false}`
|
||||
- Clarified compose comments for WebUI/SingUI canonical mapping.
|
||||
|
||||
- `backend/main.py`
|
||||
- Changed backend static frontend serving to opt-in only.
|
||||
- Default backend mode is now API-only unless:
|
||||
- `BACKEND_SERVE_LEGACY_WEBUI=true`
|
||||
|
||||
### Validation
|
||||
|
||||
- `python3 -m py_compile backend/main.py` → pass
|
||||
- `docker compose -f stemengine.yml config` → pass
|
||||
|
||||
### Operational note
|
||||
|
||||
- After deployment, WebUI/SingUI should be served only from their dedicated frontend containers.
|
||||
- Backend port `8000` should serve API responses without legacy SPA fallback unless explicitly re-enabled.
|
||||
|
||||
---
|
||||
|
||||
## 2026-04-06 Update — SEK packaging flow + project video sync + SEK-first SingUI direction
|
||||
|
||||
Implemented StemEngine Karaoke package workflow improvements and documented the SEK-first runtime direction.
|
||||
|
||||
### Implemented
|
||||
|
||||
- `backend/services/project_assets_service.py`
|
||||
- Added per-project karaoke config persistence (`stemengine_karaoke_config.json`):
|
||||
- `video_source`
|
||||
- `include_video`
|
||||
- `sync_reference_track`
|
||||
- `track_offsets_seconds`
|
||||
- `last_sync`
|
||||
- Added video source resolution:
|
||||
- local file path
|
||||
- YouTube/remote URL via `yt-dlp`
|
||||
- Added track/video sync estimation using onset-envelope cross-correlation.
|
||||
- Updated `.sek` manifest output to include synchronization block:
|
||||
- `meta.synchronization.reference_track`
|
||||
- `meta.synchronization.track_offsets_seconds`
|
||||
- `meta.synchronization.video_source`
|
||||
- `meta.synchronization.last_sync`
|
||||
|
||||
- `backend/routers/projects.py`
|
||||
- Added endpoints:
|
||||
- `GET /api/projects/{project_id}/karaoke-config`
|
||||
- `PATCH /api/projects/{project_id}/karaoke-config`
|
||||
- `POST /api/projects/{project_id}/sync-video-offset`
|
||||
- Kept/used `.sek` export endpoint:
|
||||
- `POST /api/projects/{project_id}/export-sek`
|
||||
|
||||
- `backend/services/project_service.py`
|
||||
- Re-exported new karaoke config + sync service functions.
|
||||
|
||||
- `frontend/src/api/client.ts`
|
||||
- Added typed API helpers:
|
||||
- `getProjectKaraokeConfig()`
|
||||
- `patchProjectKaraokeConfig()`
|
||||
- `syncProjectVideoOffset()`
|
||||
- Retained `.sek` export helper:
|
||||
- `exportProjectSek()`
|
||||
|
||||
- `frontend/src/pages/ProjectDetail.tsx`
|
||||
- Added **Karaoke Packaging (.sek)** section with:
|
||||
- video source input
|
||||
- sync reference track selector
|
||||
- offset field
|
||||
- include-video toggle
|
||||
- `Save`, `Sync Offset`, and `Package` buttons
|
||||
- Added run feedback (success/error) and last package path display.
|
||||
|
||||
- Auto Pipeline integration
|
||||
- `frontend/src/utils/autoPipeline.ts`
|
||||
- Added `sekPackage` step type and display label.
|
||||
- `frontend/src/components/AutoPipelineDialog.tsx`
|
||||
- Added `sekPackage` execution path using `exportProjectSek()`.
|
||||
- `frontend/src/pages/Settings.tsx`
|
||||
- Added `sekPackage` add/config UI.
|
||||
|
||||
### Documentation
|
||||
|
||||
- Reworked top of `docs/KARAOKE_BOX_PLAN.md` to authoritative **SEK-first** direction:
|
||||
- SingUI should read from user-set `.sek` folder
|
||||
- runtime should avoid direct project-internal reads for karaoke playback
|
||||
- packaging + sync offset requirements and acceptance criteria defined
|
||||
|
||||
### Validation
|
||||
|
||||
- Diagnostics check across edited backend/frontend files → no reported errors.
|
||||
|
||||
---
|
||||
|
||||
## 2026-04-06 Update — Karaoke Phase 2 implemented (SEK folder library runtime)
|
||||
|
||||
Implemented SingUI runtime support for loading karaoke songs from user-selected `.sek` folder.
|
||||
|
||||
### Implemented
|
||||
|
||||
- `backend/services/sek_library_service.py` (new)
|
||||
- Added SEK folder scanning (`*.sek`)
|
||||
- Added manifest parsing/validation
|
||||
- Added package id hashing from package path
|
||||
- Added packaged asset extraction (stems/lyrics/video) by inner path
|
||||
|
||||
- `backend/routers/karaoke_sek.py` (new)
|
||||
- Added endpoints:
|
||||
- `GET /api/karaoke-sek/library`
|
||||
- `GET /api/karaoke-sek/packages/{package_id}`
|
||||
- `GET /api/karaoke-sek/packages/{package_id}/asset?path=...`
|
||||
|
||||
- `backend/main.py`
|
||||
- Registered `karaoke_sek` router
|
||||
|
||||
- `backend/routers/settings.py`
|
||||
- Added settings keys:
|
||||
- `karaoke_source_mode` (`projects` | `sek-folder`)
|
||||
- `karaoke_sek_folder`
|
||||
- Added validation for source mode
|
||||
|
||||
- `frontend/src/api/client.ts`
|
||||
- Added SEK library APIs and asset URL helper:
|
||||
- `listSekLibrary()`
|
||||
- `getSekManifest()`
|
||||
- `sekAssetUrl()`
|
||||
- Extended `AppSettings` shape with karaoke source/folder keys
|
||||
|
||||
- `frontend/src/pages/Sing.tsx`
|
||||
- Added karaoke source switch UI (`Project-linked` / `SEK Folder`)
|
||||
- Added user-set SEK folder input + refresh/save controls
|
||||
- Added package list rendering from backend scan
|
||||
- Added launch flow to karaoke route using selected `sekPackageId`
|
||||
|
||||
- `frontend/src/pages/Karaoke.tsx`
|
||||
- Added SEK playback mode based on route state:
|
||||
- loads package manifest
|
||||
- streams stems/lyrics/video via SEK asset endpoint
|
||||
- keeps existing project-based mode as fallback
|
||||
|
||||
### Documentation
|
||||
|
||||
- Updated `docs/KARAOKE_BOX_PLAN.md`:
|
||||
- Marked Phase 2 as implemented
|
||||
- Added concrete delivered API/UI/runtime items
|
||||
|
||||
### Validation
|
||||
|
||||
- Backend/frontend diagnostics for touched files → no reported errors.
|
||||
|
||||
---
|
||||
|
||||
## 2026-04-06 Update — Karaoke Phase 3 implemented (SEK-first default mode)
|
||||
|
||||
Completed default-runtime switch so karaoke now prefers SEK folder mode by default.
|
||||
|
||||
### Implemented
|
||||
|
||||
- `backend/routers/settings.py`
|
||||
- Updated default settings value:
|
||||
- `karaoke_source_mode: "sek-folder"` (was `"projects"`)
|
||||
|
||||
- `frontend/src/pages/Sing.tsx`
|
||||
- Updated local fallback initialization to `sek-folder`
|
||||
- Updated settings fallback read to `sek-folder` when key is absent
|
||||
- Retained explicit source toggle so users can switch back to `projects`
|
||||
|
||||
### Documentation
|
||||
|
||||
- Updated `docs/KARAOKE_BOX_PLAN.md`
|
||||
- Marked Phase 3 as implemented
|
||||
- Captured SEK-first default + project fallback behavior
|
||||
|
||||
- Updated `docs/plans/API_REFERENCE.md`
|
||||
- Added Karaoke SEK endpoint group
|
||||
- Added settings keys:
|
||||
- `karaoke_source_mode`
|
||||
- `karaoke_sek_folder`
|
||||
- Documented default mode now set to `sek-folder`
|
||||
|
||||
### Validation
|
||||
|
||||
- Diagnostics check for touched files → no reported errors.
|
||||
|
||||
---
|
||||
|
||||
## 2026-04-06 Update — Karaoke plan closure items completed (settings UX + API docs)
|
||||
|
||||
Closed remaining plan-level gaps by adding dedicated settings UX and API documentation coverage.
|
||||
|
||||
### Implemented
|
||||
|
||||
- `frontend/src/pages/Settings.tsx`
|
||||
- Added **Karaoke Runtime Source** block in Integrations tab:
|
||||
- default mode selector (`sek-folder` / `projects`)
|
||||
- SEK folder path input
|
||||
- save action with status feedback
|
||||
|
||||
### Documentation
|
||||
|
||||
- `docs/KARAOKE_BOX_PLAN.md`
|
||||
- Added explicit completion status and “Remaining Work” closure
|
||||
- Added Settings UI deliverable note under Phase 2
|
||||
|
||||
- `docs/plans/API_REFERENCE.md`
|
||||
- Added project karaoke endpoint docs:
|
||||
- `GET /api/projects/{project_id}/karaoke-config`
|
||||
- `PATCH /api/projects/{project_id}/karaoke-config`
|
||||
- `POST /api/projects/{project_id}/sync-video-offset`
|
||||
- `POST /api/projects/{project_id}/export-sek`
|
||||
- Added settings keys/default docs and karaoke SEK library endpoint group
|
||||
|
||||
### Validation
|
||||
|
||||
- Diagnostics check for touched files → no reported errors.
|
||||
|
||||
---
|
||||
|
||||
## 2026-04-06 Update — SEK packager sync behavior changed to automatic
|
||||
|
||||
Adjusted packaging flow to remove manual offset entry and compute offset automatically during package export.
|
||||
|
||||
### Implemented
|
||||
|
||||
- `backend/services/project_assets_service.py`
|
||||
- `export_project_stemengine_karaoke()` now supports:
|
||||
- `video_source` override
|
||||
- `sync_reference_track` override
|
||||
- `auto_sync` (default `true`)
|
||||
- During export, if video source is available and auto-sync is enabled:
|
||||
- estimates offset automatically
|
||||
- persists to karaoke config
|
||||
- writes to `.sek` `manifest.json` synchronization block
|
||||
|
||||
- `backend/routers/projects.py`
|
||||
- Extended `POST /api/projects/{project_id}/export-sek` body with:
|
||||
- `video_source`
|
||||
- `sync_reference_track`
|
||||
- `auto_sync`
|
||||
|
||||
- `frontend/src/api/client.ts`
|
||||
- `exportProjectSek()` updated to pass auto-sync inputs and read sync status in response.
|
||||
|
||||
- `frontend/src/pages/ProjectDetail.tsx`
|
||||
- Removed manual `Offset (seconds)` input and explicit `Sync Offset` button
|
||||
- Packaging header/UX now states sync runs automatically
|
||||
- `Package` action now sends video source + reference track and relies on backend auto-sync
|
||||
|
||||
### Documentation
|
||||
|
||||
- `docs/KARAOKE_BOX_PLAN.md`
|
||||
- Updated flow language to automatic sync during packaging
|
||||
|
||||
- `docs/plans/API_REFERENCE.md`
|
||||
- Updated `export-sek` section with auto-sync request/behavior notes
|
||||
|
||||
### Validation
|
||||
|
||||
- Diagnostics check for touched files → no reported errors.
|
||||
|
||||
---
|
||||
|
||||
## 2026-04-02 Update — Apollo LQ pipeline stabilization + targeted validation
|
||||
|
||||
### User-visible failures observed
|
||||
@@ -2336,6 +2771,29 @@ These route-level tests now verify that:
|
||||
|
||||
## Phase 2 closeout
|
||||
|
||||
## 2026-04-06 Draft + documentation — Nightingale-style SingUI karaoke flow
|
||||
|
||||
Prepared a concrete architecture draft for adopting Nightingale’s separation-to-playback lifecycle in SingUI.
|
||||
|
||||
### Added documentation
|
||||
|
||||
- `docs/SINGUI_NIGHTINGALE_FLOW_DRAFT.md`
|
||||
- defines a staged lifecycle:
|
||||
1. async prepare job (separate + lyric stage + asset materialization)
|
||||
2. playback readiness gate (`Ready` required)
|
||||
3. synchronized per-stem playback with `leading` muted by default
|
||||
4. single timeline bus for lyrics/HUD/overlays
|
||||
- proposes a backend `karaoke_assets.json` contract to decouple UI from in-flight job internals
|
||||
- includes API sketch, UX mapping, cache invalidation rules, rollout steps, and acceptance criteria
|
||||
|
||||
- `docs/KARAOKE_FRONTEND_STEMENGINE_CONNECTIVITY_PLAN.md`
|
||||
- appended section **36** summarizing the Nightingale-style adaptation and linking to the detailed draft
|
||||
|
||||
### Outcome
|
||||
|
||||
- The request to “draft and document” is fulfilled with implementation-ready design guidance for SingUI.
|
||||
- No runtime code behavior changed in this step; this pass is documentation and architecture planning only.
|
||||
|
||||
Phase 2 goals are now considered complete for this codebase pass:
|
||||
|
||||
- persistence is centralized in repository modules (`backend/repositories/*`)
|
||||
@@ -6689,3 +7147,277 @@ Plan + docs updates:
|
||||
Phase E status: ✅ **COMPLETE**
|
||||
|
||||
Next planned slice: Phase F hardening + UX polish.
|
||||
|
||||
### 2026-04-05 deployment fix — restore legacy StemEngine WebUI on 5174
|
||||
|
||||
Requested:
|
||||
- Ensure `5174` serves the **legacy StemEngine WebUI** (management tools),
|
||||
while SingUI remains isolated on `3001`.
|
||||
|
||||
Root cause:
|
||||
- Both `stemengine-webui` and `stemengine-sing` were pointing at the same
|
||||
frontend source (`appdata/stemengine/frontend`), so `5174` was rendering the
|
||||
new SingUI app instead of legacy management UI.
|
||||
|
||||
Fixes implemented:
|
||||
|
||||
1. `stemengine.yml`
|
||||
- Rewired `stemengine-webui` to legacy source:
|
||||
- build context: `x/StemEngine-0.9alpha/frontend`
|
||||
- image: `stemengine-legacy-webui:latest`
|
||||
- added dedicated dependency volume:
|
||||
`stemengine-legacy-webui-node-modules`
|
||||
- Kept `stemengine-sing` mapped to current frontend on `3001:5173`.
|
||||
|
||||
2. `x/StemEngine-0.9alpha/frontend/Dockerfile.webui.dev`
|
||||
- Added legacy dev Dockerfile for Vite service.
|
||||
- Uses `npm install` (legacy project has no lockfile).
|
||||
|
||||
3. `x/StemEngine-0.9alpha/frontend/vite.config.ts`
|
||||
- Set Docker-friendly host binding: `0.0.0.0`.
|
||||
- Set proxy target for `/api` to backend service via
|
||||
`VITE_API_PROXY_TARGET` (default `http://stemengine:8000`).
|
||||
|
||||
4. Documentation sync
|
||||
- Updated connectivity plan with final routing split:
|
||||
- `docs/KARAOKE_FRONTEND_STEMENGINE_CONNECTIVITY_PLAN.md`
|
||||
section: `## 27) 2026-04-05 final routing split — 5174 serves legacy StemEngine WebUI`.
|
||||
|
||||
Runtime validation:
|
||||
- `http://127.0.0.1:5174/` → `200` (legacy management UI)
|
||||
- `http://127.0.0.1:3001/` → `200` (new SingUI)
|
||||
- Compose config validates (`docker compose -f stemengine.yml config --quiet`).
|
||||
|
||||
### 2026-04-05 correction — restore 5174 to current WebUI (undo legacy reroute)
|
||||
|
||||
Requested:
|
||||
- Restore frontend WebUI on `5174` to the **current app state** (as of
|
||||
2026-04-04), because the prior change rerouted `5174` to legacy UI and
|
||||
effectively reverted visible WebUI behavior.
|
||||
|
||||
Fixes implemented:
|
||||
|
||||
1. `stemengine.yml`
|
||||
- Restored `stemengine-webui` to current frontend source:
|
||||
- context: `${SEFOLDER}/frontend`
|
||||
- image: `stemengine-webui:latest`
|
||||
- volume: `${SEFOLDER}/frontend:/app/frontend`
|
||||
- dependency volume: `stemengine-webui-node-modules`
|
||||
- Removed legacy-specific dependency volume wiring from compose.
|
||||
- Left `stemengine-sing` on `3001:5173` using the same current frontend.
|
||||
|
||||
2. Documentation updates
|
||||
- `docs/KARAOKE_FRONTEND_STEMENGINE_CONNECTIVITY_PLAN.md`
|
||||
- added correction section that supersedes the prior legacy split note.
|
||||
|
||||
Validation:
|
||||
- `docker compose -f stemengine.yml config --quiet` passes.
|
||||
- Frontend services can be recreated on corrected mapping (`5174` WebUI,
|
||||
`3001` SingUI endpoint).
|
||||
|
||||
### 2026-04-05 correction — restore StemEngine sidebar shell on WebUI
|
||||
|
||||
Issue reported:
|
||||
- Even after port/source correction, WebUI (`5174`) was still presenting the
|
||||
music-library navigation shell (Albums/Tracks/Artists/Playlists/Sing), not
|
||||
the expected StemEngine workflow shell.
|
||||
|
||||
Expected shell:
|
||||
- Sidebar with:
|
||||
- Subsonic search/import
|
||||
- YT-DL import
|
||||
- project list/search
|
||||
|
||||
Fixes implemented:
|
||||
|
||||
1. `frontend/src/App.tsx`
|
||||
- Replaced library-shell composition with the route-based StemEngine shell
|
||||
that mounts `Sidebar` + workflow pages.
|
||||
- Restored route mapping:
|
||||
- `/` → `Separator`
|
||||
- `/projects/:projectId` → `ProjectDetail`
|
||||
- `/settings` → `Settings`
|
||||
- Wired sidebar state + `activeProjectId` with route parsing.
|
||||
|
||||
2. Runtime refresh
|
||||
- Recreated `stemengine-webui` and `stemengine-sing` containers to ensure
|
||||
latest source is live.
|
||||
|
||||
Validation:
|
||||
- `frontend` build passes (`npm run build`).
|
||||
- `http://127.0.0.1:5174/` responds `200`.
|
||||
- Served sidebar source confirms `SubsonicPanel` and `YtDlPanel` are present.
|
||||
|
||||
### 2026-04-06 investigation — WebUI (5174) vs SingUI (3001) conflation root cause
|
||||
|
||||
Investigation outcome:
|
||||
|
||||
- The repeated confusion came from architecture coupling:
|
||||
- `stemengine-webui` and `stemengine-sing` were both built from the same
|
||||
frontend context (`appdata/stemengine/frontend`),
|
||||
- both used the same image digest,
|
||||
- both mounted the same bind source and node_modules volume.
|
||||
|
||||
Implication:
|
||||
|
||||
- Any shell-level edit in `frontend/src/App.tsx` affects **both** ports unless a
|
||||
strict service-mode gate exists.
|
||||
|
||||
Operational findings:
|
||||
|
||||
- Runtime containers confirm compose source:
|
||||
- config file: `/home/translator/docker/stemengine.yml`
|
||||
- working dir: `/home/translator/docker`
|
||||
- Workspace contains another `stemengine.yml` under
|
||||
`/home/translator/docker/appdata/stemengine/`, which increases edit-path
|
||||
ambiguity during rapid changes.
|
||||
|
||||
Documented mitigation path:
|
||||
|
||||
- Added incident write-up and guardrail recommendations to
|
||||
`docs/KARAOKE_FRONTEND_STEMENGINE_CONNECTIVITY_PLAN.md`:
|
||||
- explicit `VITE_UI_FLAVOR` split (`webui|sing`),
|
||||
- canonical compose file policy,
|
||||
- startup/CI smoke checks for `5174` and `3001` shell markers.
|
||||
|
||||
### 2026-04-06 implementation — `VITE_UI_FLAVOR` split completed
|
||||
|
||||
Implemented the recommended mode split to prevent future WebUI/SingUI conflation.
|
||||
|
||||
Changes:
|
||||
|
||||
1. `frontend/src/App.tsx`
|
||||
- Added explicit runtime shell selection:
|
||||
- `VITE_UI_FLAVOR=webui` → StemEngine workflow shell
|
||||
- `VITE_UI_FLAVOR=sing` → Sing/Subsonic navigation shell
|
||||
|
||||
2. `stemengine.yml`
|
||||
- `stemengine-webui` now sets `VITE_UI_FLAVOR=webui`
|
||||
- `stemengine-sing` now sets `VITE_UI_FLAVOR=sing`
|
||||
|
||||
Validation:
|
||||
- `frontend` build passes.
|
||||
- Compose config passes.
|
||||
- Container env inspection confirms flavor values are set correctly per service.
|
||||
|
||||
### 2026-04-06 planning update — SingUI Subsonic parity + process-action roadmap
|
||||
|
||||
Planned and documented the next execution slice for SingUI (`3001`):
|
||||
|
||||
- Feishin/Navidrome-style browse parity over Subsonic (tracks/albums/artists/playlists)
|
||||
- scalable paged browse endpoints on backend
|
||||
- explicit track/album detail pages in Sing shell
|
||||
- per-song `Process` and per-album `Process Album` actions with enforced button order
|
||||
(`Process` before favorite)
|
||||
- shared convert-status lifecycle (`Queued`, `Running`, `Ready`, `Retry`)
|
||||
- readiness propagation into karaoke launch flows
|
||||
|
||||
Primary documentation target:
|
||||
|
||||
- `docs/KARAOKE_FRONTEND_STEMENGINE_CONNECTIVITY_PLAN.md`
|
||||
- added section: `## 32) 2026-04-06 execution plan — SingUI Subsonic browse parity + StemEngine process actions`
|
||||
|
||||
### 2026-04-06 implementation — SingUI detail browse + per-song/per-album process actions
|
||||
|
||||
Implemented a concrete execution slice for SingUI (`3001`) aligned with Feishin/Navidrome browse patterns.
|
||||
|
||||
Changes shipped:
|
||||
|
||||
1. Detail routes and shell wiring
|
||||
- `frontend/src/App.tsx`
|
||||
- Added Sing-mode route handling for:
|
||||
- `/albums/:albumId`
|
||||
- `/tracks/:trackId`
|
||||
|
||||
2. New detail pages
|
||||
- `frontend/src/pages/AlbumDetail.tsx` (new)
|
||||
- header actions ordered as `Process Album` then `Favorite`
|
||||
- per-track rows include `Process` then `Favorite`
|
||||
- `frontend/src/pages/TrackDetail.tsx` (new)
|
||||
- actions ordered as `Process` then `Favorite`
|
||||
|
||||
3. Browse pages linked to detail pages
|
||||
- `frontend/src/pages/Albums.tsx`
|
||||
- switched album browse source to `listSubsonicAlbums` for stable ids
|
||||
- added links to album detail route
|
||||
- process fallback: fetch album detail when local song map is not present
|
||||
- `frontend/src/pages/Tracks.tsx`
|
||||
- song title links to track detail route
|
||||
- `frontend/src/pages/Sing.tsx`
|
||||
- tracks/albums lists link to detail routes
|
||||
|
||||
Validation:
|
||||
- `npm run build` passes for frontend.
|
||||
- Containers recreated for webui/sing.
|
||||
- Runtime source checks confirm:
|
||||
- Sing detail routes are present,
|
||||
- album and track process controls are present in served pages.
|
||||
|
||||
### 2026-04-06 UX fix — SingUI settings close affordance
|
||||
|
||||
Issue:
|
||||
- SingUI settings opened as fullscreen with no explicit close button.
|
||||
|
||||
Fix:
|
||||
- Updated `frontend/src/App.tsx` (`SingUiShell`) to include:
|
||||
- `closeSettings()` handler:
|
||||
- `navigate(-1)` when history exists,
|
||||
- fallback to `/sing`.
|
||||
- top settings toolbar with `Close` button and `X` icon.
|
||||
|
||||
Validation:
|
||||
- Runtime source check on `3001` confirms:
|
||||
- `SingUI Settings` header present,
|
||||
- `closeSettings` handler present.
|
||||
|
||||
### 2026-04-06 SingUI compatibility fix — albums load, tracks/artists fail
|
||||
|
||||
Symptom:
|
||||
- In SingUI, Subsonic albums loaded but tracks/artists did not.
|
||||
|
||||
Cause:
|
||||
- Track/artist rendering relied on wildcard search (`/api/subsonic/search?q=*`).
|
||||
- Target Subsonic-compatible server supports browse endpoints better than wildcard
|
||||
search behavior.
|
||||
|
||||
Fixes applied:
|
||||
|
||||
1. `frontend/src/hooks/useSubsonicLibrary.ts`
|
||||
- Added fallback for wildcard search failures:
|
||||
- fetch album list,
|
||||
- fetch album detail per album,
|
||||
- flatten + dedupe songs for track consumption.
|
||||
|
||||
2. `frontend/src/pages/Artists.tsx`
|
||||
- Moved artists page to direct endpoint model (`listSubsonicArtists`) instead
|
||||
of deriving artists from wildcard track search.
|
||||
|
||||
Validation:
|
||||
- Frontend build passes.
|
||||
- Containers recreated.
|
||||
- Served source verifies:
|
||||
- library fallback path present,
|
||||
- artists page wired to artist browse endpoint.
|
||||
|
||||
### 2026-04-06 fix — SingUI Subsonic connect 500 (proxy target)
|
||||
|
||||
Reported symptom:
|
||||
- Subsonic connect from SingUI failed with `500`, while WebUI Subsonic search worked.
|
||||
|
||||
Root cause:
|
||||
- Vite dev proxy in current frontend pointed `/api` to `http://localhost:8000`.
|
||||
- In Docker, that resolves to the frontend container itself, not backend service,
|
||||
causing proxy errors for SingUI requests using relative `/api`.
|
||||
|
||||
Implemented fix:
|
||||
|
||||
1. `frontend/vite.config.ts`
|
||||
- moved proxy target to env-driven Docker-safe value:
|
||||
- `VITE_API_PROXY_TARGET` or fallback `http://stemengine:8000`
|
||||
|
||||
2. `stemengine.yml`
|
||||
- added for both `stemengine-webui` and `stemengine-sing`:
|
||||
- `VITE_API_PROXY_TARGET=http://stemengine:8000`
|
||||
|
||||
Validation:
|
||||
- `GET http://127.0.0.1:3001/api/subsonic/config` returns `200` after recreate.
|
||||
@@ -126,6 +126,8 @@ All configuration is via environment variables. The `docker-compose.yml` accepts
|
||||
| `GABOX_SMALL_MODEL_PREFERRED_FOR_LOW_VRAM` | `false` | Reserved policy flag for low-VRAM auto-preference workflows |
|
||||
| `STEMENGINE_LYRIC_SEGMENTER` | `auto` | Lyric line splitter strategy: `auto`, `karaoke_processor`, `legacy` |
|
||||
| `STEMENGINE_LYRIC_MAX_LINE_LENGTH` | `36` | Max line length target used by karaoke lyric segmentation |
|
||||
| `STEMENGINE_KARAOKE_EXPORT_DIR` | empty | Optional global `.sek` export directory inside the container. If empty, exports go under each project (`Exports/StemEngineKaraoke`). |
|
||||
| `SEK_EXPORTS` | `${SEFOLDER}/sek_exports` | Host path mounted to `/app/media/sek_exports` for centralized `.sek` package output. |
|
||||
| `TZ` | `UTC` | Timezone |
|
||||
| `NAVSERVER` | — | Subsonic server URL (can also be set in the UI) |
|
||||
| `NAVUSER` | — | Subsonic username |
|
||||
|
||||
@@ -41,6 +41,10 @@ JOBS_DIR = Path(os.environ.get("JOBS_DIR", str(MEDIA_DIR / "jobs")))
|
||||
PROJECTS_DIR = Path(os.environ.get("PROJECTS_DIR", str(MEDIA_DIR / "projects")))
|
||||
DB_PATH = Path(os.environ.get("DB_PATH", str(MEDIA_DIR / "db" / "stemengine.db")))
|
||||
LRC_SYNC_DIR = Path(os.environ.get("LRC_SYNC_DIR", str(MEDIA_DIR / "lrc_sync")))
|
||||
# Optional global output directory for .sek packages.
|
||||
# - empty (default): write to per-project path <project>/Exports/StemEngineKaraoke
|
||||
# - set: write to this directory (absolute path recommended), grouped by project name
|
||||
STEMENGINE_KARAOKE_EXPORT_DIR = os.environ.get("STEMENGINE_KARAOKE_EXPORT_DIR", "").strip()
|
||||
|
||||
# BS-RoFormer model directory
|
||||
BS_ROFORMER_MODEL_DIR = Path(os.environ.get("BS_ROFORMER_MODEL_DIR", "/opt/bs_roformer_models"))
|
||||
|
||||
+9
-2
@@ -1,10 +1,11 @@
|
||||
"""
|
||||
StemEngine — FastAPI application entry point.
|
||||
Mounts all API routers and serves the built React frontend as static files.
|
||||
Mounts API routers and optionally serves legacy static WebUI when explicitly enabled.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import logging.config
|
||||
import os
|
||||
import warnings
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
@@ -39,7 +40,7 @@ from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from . import job_manager as jm
|
||||
from .routers import separate, transcribe, abc_convert, pipeline, jobs, lrc, subsonic, projects, models, lyric_transcribe, system, settings
|
||||
from .routers import separate, transcribe, abc_convert, pipeline, jobs, lrc, subsonic, projects, models, lyric_transcribe, system, settings, karaoke_sek
|
||||
from .config import SUBSONIC_CONFIG_PATH
|
||||
from .app_settings import settings as app_settings
|
||||
from .db import init_db
|
||||
@@ -100,9 +101,15 @@ def _include_routers(app: FastAPI) -> None:
|
||||
app.include_router(lyric_transcribe.router)
|
||||
app.include_router(system.router)
|
||||
app.include_router(settings.router)
|
||||
app.include_router(karaoke_sek.router)
|
||||
|
||||
|
||||
def _mount_static(app: FastAPI) -> None:
|
||||
# Legacy behavior (backend-served frontend) is opt-in only.
|
||||
# Default runtime is API-only with separate WebUI/SingUI services.
|
||||
if os.environ.get("BACKEND_SERVE_LEGACY_WEBUI", "false").lower() != "true":
|
||||
return
|
||||
|
||||
# Serve built React frontend from /app/backend/static
|
||||
# Mount order matters: API routes always win over static assets.
|
||||
_static_dir = Path(__file__).parent / "static"
|
||||
|
||||
@@ -100,7 +100,7 @@ def append_files(job_id: str, new_files: list) -> bool:
|
||||
|
||||
def list_completed_separation_candidates() -> list[JobRecord]:
|
||||
with _session() as session:
|
||||
return (
|
||||
rows = (
|
||||
session.query(JobRecord)
|
||||
.filter(
|
||||
JobRecord.job_type.in_(["separate", "pipeline"]),
|
||||
@@ -108,6 +108,13 @@ def list_completed_separation_candidates() -> list[JobRecord]:
|
||||
)
|
||||
.all()
|
||||
)
|
||||
candidates: list[JobRecord] = []
|
||||
for row in rows:
|
||||
result = row.result if isinstance(row.result, dict) else {}
|
||||
if result.get("reprocess"):
|
||||
continue
|
||||
candidates.append(row)
|
||||
return candidates
|
||||
|
||||
|
||||
def list_terminal_unlinked_older_than(older_than: datetime, limit: int = 200) -> list[str]:
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from fastapi.responses import Response
|
||||
|
||||
from ..services.project_service_common import ProjectOperationError
|
||||
from ..services.sek_library_service import (
|
||||
get_sek_asset,
|
||||
get_sek_manifest,
|
||||
list_sek_packages,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/karaoke-sek", tags=["karaoke-sek"])
|
||||
|
||||
|
||||
@router.get("/library")
|
||||
def list_library(folder: str | None = Query(default=None, description="Optional SEK folder override")):
|
||||
try:
|
||||
return list_sek_packages(folder)
|
||||
except ProjectOperationError as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
|
||||
|
||||
|
||||
@router.get("/packages/{package_id}")
|
||||
def get_manifest(package_id: str, folder: str | None = Query(default=None, description="Optional SEK folder override")):
|
||||
try:
|
||||
return get_sek_manifest(package_id, folder)
|
||||
except ProjectOperationError as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
|
||||
|
||||
|
||||
@router.get("/packages/{package_id}/asset")
|
||||
def get_asset(
|
||||
package_id: str,
|
||||
path: str = Query(..., description="Inner package path, e.g. stems/vocals.mp3"),
|
||||
folder: str | None = Query(default=None, description="Optional SEK folder override"),
|
||||
):
|
||||
try:
|
||||
data, mime, filename = get_sek_asset(package_id, path, folder)
|
||||
return Response(
|
||||
content=data,
|
||||
media_type=mime,
|
||||
headers={
|
||||
"Content-Disposition": f'inline; filename="{filename}"',
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
},
|
||||
)
|
||||
except ProjectOperationError as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
|
||||
@@ -22,6 +22,9 @@ from ..services.project_service import (
|
||||
enqueue_project_mix,
|
||||
enqueue_project_transcription,
|
||||
enqueue_stem_reprocess,
|
||||
export_project_karaoke_mugen,
|
||||
export_project_stemengine_karaoke,
|
||||
get_project_karaoke_config,
|
||||
get_project_cover_art,
|
||||
get_project_or_raise,
|
||||
list_projects as list_projects_service,
|
||||
@@ -31,6 +34,8 @@ from ..services.project_service import (
|
||||
purge_orphaned_separation_jobs_from_store,
|
||||
rename_project_stem,
|
||||
rescan_project_stems,
|
||||
sync_project_video_offset,
|
||||
update_project_karaoke_config,
|
||||
verify_all_project_stems,
|
||||
write_all_project_metadata_snapshots,
|
||||
)
|
||||
@@ -314,6 +319,31 @@ class DeleteStemRequest(BaseModel):
|
||||
stem_name: str
|
||||
|
||||
|
||||
class KaraokeMugenExportRequest(BaseModel):
|
||||
default_title_lang: str = "eng"
|
||||
repository: str = "stemengine.local"
|
||||
|
||||
|
||||
class StemEngineKaraokeExportRequest(BaseModel):
|
||||
package_name: Optional[str] = None
|
||||
include_video: bool = True
|
||||
video_source: Optional[str] = None
|
||||
sync_reference_track: Optional[str] = None
|
||||
auto_sync: bool = True
|
||||
|
||||
|
||||
class ProjectKaraokeConfigPatchRequest(BaseModel):
|
||||
video_source: Optional[str] = None
|
||||
include_video: Optional[bool] = None
|
||||
sync_reference_track: Optional[str] = None
|
||||
offset_seconds: Optional[float] = None
|
||||
|
||||
|
||||
class ProjectVideoSyncRequest(BaseModel):
|
||||
video_source: str
|
||||
reference_track: str = "source"
|
||||
|
||||
|
||||
@router.delete("/{project_id}/stem")
|
||||
def delete_stem_endpoint(project_id: str, body: DeleteStemRequest):
|
||||
"""Delete a stem file from disk and remove it from the job record."""
|
||||
@@ -324,6 +354,77 @@ def delete_stem_endpoint(project_id: str, body: DeleteStemRequest):
|
||||
raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
|
||||
|
||||
|
||||
@router.post("/{project_id}/export-karaoke-mugen")
|
||||
def export_karaoke_mugen_endpoint(project_id: str, body: KaraokeMugenExportRequest):
|
||||
"""Export project artifacts as a Karaoke Mugen-compatible package scaffold."""
|
||||
project = _get_project_or_404(project_id)
|
||||
try:
|
||||
return export_project_karaoke_mugen(
|
||||
project,
|
||||
default_title_lang=body.default_title_lang,
|
||||
repository=body.repository,
|
||||
)
|
||||
except ProjectOperationError as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
|
||||
|
||||
|
||||
@router.post("/{project_id}/export-sek")
|
||||
def export_stemengine_karaoke_endpoint(project_id: str, body: StemEngineKaraokeExportRequest):
|
||||
"""Export a StemEngine Karaoke (.sek) package with stems + .elrc (+ optional video)."""
|
||||
project = _get_project_or_404(project_id)
|
||||
try:
|
||||
return export_project_stemengine_karaoke(
|
||||
project,
|
||||
package_name=body.package_name,
|
||||
include_video=body.include_video,
|
||||
video_source=body.video_source,
|
||||
sync_reference_track=body.sync_reference_track,
|
||||
auto_sync=body.auto_sync,
|
||||
)
|
||||
except ProjectOperationError as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
|
||||
|
||||
|
||||
@router.get("/{project_id}/karaoke-config")
|
||||
def get_project_karaoke_config_endpoint(project_id: str):
|
||||
"""Return persisted karaoke packaging config for this project."""
|
||||
project = _get_project_or_404(project_id)
|
||||
try:
|
||||
return get_project_karaoke_config(project)
|
||||
except ProjectOperationError as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
|
||||
|
||||
|
||||
@router.patch("/{project_id}/karaoke-config")
|
||||
def patch_project_karaoke_config_endpoint(project_id: str, body: ProjectKaraokeConfigPatchRequest):
|
||||
"""Update persisted karaoke packaging config for this project."""
|
||||
project = _get_project_or_404(project_id)
|
||||
try:
|
||||
return update_project_karaoke_config(
|
||||
project,
|
||||
video_source=body.video_source,
|
||||
include_video=body.include_video,
|
||||
sync_reference_track=body.sync_reference_track,
|
||||
offset_seconds=body.offset_seconds,
|
||||
)
|
||||
except ProjectOperationError as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
|
||||
|
||||
|
||||
@router.post("/{project_id}/sync-video-offset")
|
||||
def sync_video_offset_endpoint(project_id: str, body: ProjectVideoSyncRequest):
|
||||
"""Estimate and persist sync offset between a linked video and a project track."""
|
||||
project = _get_project_or_404(project_id)
|
||||
try:
|
||||
return sync_project_video_offset(
|
||||
project,
|
||||
video_source=body.video_source,
|
||||
reference_track=body.reference_track,
|
||||
)
|
||||
except ProjectOperationError as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Stem Rescan
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -33,6 +33,7 @@ _VALID_WHISPER_MODELS = {
|
||||
"large", "large-v1", "large-v2", "large-v3",
|
||||
"large-v3-turbo", "turbo",
|
||||
}
|
||||
_VALID_KARAOKE_SOURCE_MODE = {"projects", "sek-folder"}
|
||||
|
||||
# Default values for all known preference keys
|
||||
_DEFAULTS: dict[str, Any] = {
|
||||
@@ -45,6 +46,8 @@ _DEFAULTS: dict[str, Any] = {
|
||||
"auto_model": "htdemucs",
|
||||
"auto_format": "mp3",
|
||||
"auto_presets": [],
|
||||
"karaoke_source_mode": "sek-folder",
|
||||
"karaoke_sek_folder": "",
|
||||
}
|
||||
|
||||
|
||||
@@ -101,6 +104,8 @@ class SettingsPatch(BaseModel):
|
||||
auto_model: Optional[str] = None
|
||||
auto_format: Optional[str] = None
|
||||
auto_presets: Optional[list] = None
|
||||
karaoke_source_mode: Optional[str] = None
|
||||
karaoke_sek_folder: Optional[str] = None
|
||||
|
||||
@field_validator("sep_power")
|
||||
@classmethod
|
||||
@@ -120,6 +125,15 @@ class SettingsPatch(BaseModel):
|
||||
)
|
||||
return v
|
||||
|
||||
@field_validator("karaoke_source_mode")
|
||||
@classmethod
|
||||
def _validate_karaoke_source_mode(cls, v: Optional[str]) -> Optional[str]:
|
||||
if v is not None and v not in _VALID_KARAOKE_SOURCE_MODE:
|
||||
raise ValueError(
|
||||
f"Unknown karaoke_source_mode '{v}'. Valid values: {sorted(_VALID_KARAOKE_SOURCE_MODE)}"
|
||||
)
|
||||
return v
|
||||
|
||||
|
||||
@router.patch("")
|
||||
def patch_settings(body: SettingsPatch):
|
||||
|
||||
@@ -72,8 +72,6 @@ def search(
|
||||
album_artist: str = "",
|
||||
):
|
||||
"""Search songs on the configured Subsonic server."""
|
||||
if not any([q.strip(), title.strip(), artist.strip(), album.strip(), album_artist.strip()]):
|
||||
return []
|
||||
try:
|
||||
return subsonic_service.search_songs(
|
||||
query=q.strip(),
|
||||
@@ -90,6 +88,72 @@ def search(
|
||||
raise HTTPException(status_code=502, detail=f"Subsonic search failed: {exc}")
|
||||
|
||||
|
||||
@router.get("/playlists")
|
||||
def list_playlists():
|
||||
"""List playlists from the configured Subsonic server."""
|
||||
try:
|
||||
return subsonic_service.list_playlists()
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=502, detail=f"Subsonic playlist list failed: {exc}")
|
||||
|
||||
|
||||
@router.get("/playlists/{playlist_id}")
|
||||
def get_playlist(playlist_id: str):
|
||||
"""Return playlist metadata and songs for a playlist id."""
|
||||
try:
|
||||
return subsonic_service.get_playlist(playlist_id)
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=502, detail=f"Subsonic playlist fetch failed: {exc}")
|
||||
|
||||
|
||||
@router.get("/albums")
|
||||
def list_albums(offset: int = 0, size: int = 50, query: str = "", artist_id: str = ""):
|
||||
"""List albums from the configured Subsonic server (paged browse)."""
|
||||
try:
|
||||
return subsonic_service.list_albums(offset=offset, size=size, query=query.strip(), artist_id=artist_id.strip())
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=502, detail=f"Subsonic album list failed: {exc}")
|
||||
|
||||
|
||||
@router.get("/albums/{album_id}")
|
||||
def get_album(album_id: str):
|
||||
"""Return album metadata and songs by id."""
|
||||
try:
|
||||
return subsonic_service.get_album(album_id)
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=502, detail=f"Subsonic album fetch failed: {exc}")
|
||||
|
||||
|
||||
@router.get("/artists")
|
||||
def list_artists(offset: int = 0, size: int = 200, query: str = ""):
|
||||
"""List artists from the configured Subsonic server."""
|
||||
try:
|
||||
return subsonic_service.list_artists(offset=offset, size=size, query=query.strip())
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=502, detail=f"Subsonic artist list failed: {exc}")
|
||||
|
||||
|
||||
@router.get("/artists/{artist_id}")
|
||||
def get_artist(artist_id: str):
|
||||
"""Return artist metadata and albums by id."""
|
||||
try:
|
||||
return subsonic_service.get_artist(artist_id)
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=502, detail=f"Subsonic artist fetch failed: {exc}")
|
||||
|
||||
|
||||
class ImportRequest(BaseModel):
|
||||
id: str
|
||||
title: str
|
||||
|
||||
@@ -2,13 +2,21 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import shutil
|
||||
import tempfile
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from datetime import datetime, timezone
|
||||
from urllib import error as urlerror
|
||||
from urllib import request as urlrequest
|
||||
from uuid import uuid4
|
||||
|
||||
import librosa
|
||||
import numpy as np
|
||||
|
||||
from .. import job_manager as jm
|
||||
from ..config import UPLOAD_DIR
|
||||
from ..config import STEMENGINE_KARAOKE_EXPORT_DIR, UPLOAD_DIR
|
||||
from ..repositories import jobs as jobs_repo
|
||||
from ..repositories import projects as projects_repo
|
||||
from .metadata_util import _read_cover_art, read_metadata
|
||||
@@ -290,3 +298,667 @@ def get_project_cover_art(project: dict) -> tuple[bytes, str]:
|
||||
pass
|
||||
|
||||
raise ProjectOperationError(404, "No cover art")
|
||||
|
||||
|
||||
def _pick_source_media_file(sep_job: dict | None) -> Path | None:
|
||||
for file_entry in (sep_job or {}).get("files", []):
|
||||
if file_entry.get("type") != "source":
|
||||
continue
|
||||
raw = file_entry.get("path")
|
||||
if not raw:
|
||||
continue
|
||||
candidate = Path(str(raw))
|
||||
if candidate.exists() and candidate.is_file():
|
||||
return candidate
|
||||
return None
|
||||
|
||||
|
||||
def _cover_extension_from_mime(mime: str | None) -> str:
|
||||
normalized = str(mime or "").strip().lower()
|
||||
mapping = {
|
||||
"image/jpeg": ".jpg",
|
||||
"image/jpg": ".jpg",
|
||||
"image/png": ".png",
|
||||
"image/webp": ".webp",
|
||||
"image/gif": ".gif",
|
||||
"image/bmp": ".bmp",
|
||||
"image/tiff": ".tiff",
|
||||
}
|
||||
return mapping.get(normalized, ".jpg")
|
||||
|
||||
|
||||
def _build_source_metadata_component(source_media: Path | None) -> tuple[dict, bytes | None, str | None, str | None]:
|
||||
metadata = {
|
||||
"source_file": source_media.name if source_media else "",
|
||||
"title": "",
|
||||
"artist": "",
|
||||
"albumartist": "",
|
||||
"album": "",
|
||||
"cover_art": None,
|
||||
}
|
||||
if source_media is None:
|
||||
return metadata, None, None, None
|
||||
|
||||
try:
|
||||
tags = read_metadata(str(source_media))
|
||||
metadata["title"] = str(tags.get("title") or "").strip()
|
||||
metadata["artist"] = str(tags.get("artist") or "").strip()
|
||||
metadata["albumartist"] = str(tags.get("albumartist") or "").strip()
|
||||
metadata["album"] = str(tags.get("album") or "").strip()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
cover_bytes: bytes | None = None
|
||||
cover_mime: str | None = None
|
||||
|
||||
try:
|
||||
data, mime = _read_cover_art(str(source_media))
|
||||
if data:
|
||||
cover_bytes = data
|
||||
cover_mime = mime or "image/jpeg"
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not cover_bytes:
|
||||
thumbnail_url = _read_source_thumbnail_url(source_media)
|
||||
if thumbnail_url:
|
||||
try:
|
||||
remote_data, remote_mime = _fetch_remote_image(thumbnail_url)
|
||||
if remote_data:
|
||||
cover_bytes = remote_data
|
||||
cover_mime = remote_mime or "image/jpeg"
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if cover_bytes:
|
||||
ext = _cover_extension_from_mime(cover_mime)
|
||||
cover_name = f"cover{ext}"
|
||||
metadata["cover_art"] = {
|
||||
"file": f"metadata/{cover_name}",
|
||||
"mime": cover_mime or "image/jpeg",
|
||||
"bytes": len(cover_bytes),
|
||||
}
|
||||
return metadata, cover_bytes, cover_mime, cover_name
|
||||
|
||||
return metadata, None, None, None
|
||||
|
||||
|
||||
def _pick_best_lyrics_file(project_root: Path) -> Path | None:
|
||||
candidates = [
|
||||
p for p in project_root.rglob("*")
|
||||
if p.is_file() and p.suffix.lower() in {".ass", ".lrc", ".elrc"}
|
||||
]
|
||||
if not candidates:
|
||||
return None
|
||||
|
||||
def priority(path: Path) -> tuple[int, float]:
|
||||
ext = path.suffix.lower()
|
||||
weight = 0 if ext == ".ass" else (1 if ext == ".lrc" else 2)
|
||||
return (weight, -path.stat().st_mtime)
|
||||
|
||||
return sorted(candidates, key=priority)[0]
|
||||
|
||||
|
||||
def _pick_best_elrc_file(project_root: Path) -> Path | None:
|
||||
candidates = [p for p in project_root.rglob("*.elrc") if p.is_file()]
|
||||
if not candidates:
|
||||
return None
|
||||
return sorted(candidates, key=lambda p: p.stat().st_mtime, reverse=True)[0]
|
||||
|
||||
|
||||
def _karaoke_config_path(project_root: Path) -> Path:
|
||||
return project_root / "stemengine_karaoke_config.json"
|
||||
|
||||
|
||||
def _default_karaoke_config() -> dict:
|
||||
return {
|
||||
"video_source": "",
|
||||
"include_video": True,
|
||||
"sync_reference_track": "source",
|
||||
"track_offsets_seconds": {},
|
||||
"last_sync": None,
|
||||
}
|
||||
|
||||
|
||||
def _read_karaoke_config(project_root: Path) -> dict:
|
||||
cfg = _default_karaoke_config()
|
||||
path = _karaoke_config_path(project_root)
|
||||
if not path.exists():
|
||||
return cfg
|
||||
try:
|
||||
raw = json.loads(path.read_text(encoding="utf-8"))
|
||||
if isinstance(raw, dict):
|
||||
cfg.update(raw)
|
||||
except Exception:
|
||||
pass
|
||||
cfg["video_source"] = str(cfg.get("video_source") or "").strip()
|
||||
cfg["sync_reference_track"] = str(cfg.get("sync_reference_track") or "source").strip() or "source"
|
||||
cfg["include_video"] = bool(cfg.get("include_video", True))
|
||||
offsets = cfg.get("track_offsets_seconds")
|
||||
cfg["track_offsets_seconds"] = offsets if isinstance(offsets, dict) else {}
|
||||
return cfg
|
||||
|
||||
|
||||
def _write_karaoke_config(project_root: Path, cfg: dict) -> dict:
|
||||
normalized = _default_karaoke_config()
|
||||
normalized.update(cfg or {})
|
||||
normalized["video_source"] = str(normalized.get("video_source") or "").strip()
|
||||
normalized["sync_reference_track"] = str(normalized.get("sync_reference_track") or "source").strip() or "source"
|
||||
normalized["include_video"] = bool(normalized.get("include_video", True))
|
||||
offsets = normalized.get("track_offsets_seconds")
|
||||
normalized["track_offsets_seconds"] = offsets if isinstance(offsets, dict) else {}
|
||||
_karaoke_config_path(project_root).write_text(
|
||||
json.dumps(normalized, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return normalized
|
||||
|
||||
|
||||
def get_project_karaoke_config(project: dict) -> dict:
|
||||
project_root = project_output_dir(project)
|
||||
if not project_root.exists():
|
||||
raise ProjectOperationError(404, "Project directory not found")
|
||||
cfg = _read_karaoke_config(project_root)
|
||||
return {
|
||||
"project_id": project.get("id"),
|
||||
"project_name": project.get("name"),
|
||||
"config": cfg,
|
||||
}
|
||||
|
||||
|
||||
def update_project_karaoke_config(
|
||||
project: dict,
|
||||
*,
|
||||
video_source: str | None = None,
|
||||
include_video: bool | None = None,
|
||||
sync_reference_track: str | None = None,
|
||||
offset_seconds: float | None = None,
|
||||
) -> dict:
|
||||
project_root = project_output_dir(project)
|
||||
if not project_root.exists():
|
||||
raise ProjectOperationError(404, "Project directory not found")
|
||||
|
||||
cfg = _read_karaoke_config(project_root)
|
||||
if video_source is not None:
|
||||
cfg["video_source"] = str(video_source).strip()
|
||||
if include_video is not None:
|
||||
cfg["include_video"] = bool(include_video)
|
||||
if sync_reference_track is not None and str(sync_reference_track).strip():
|
||||
cfg["sync_reference_track"] = str(sync_reference_track).strip()
|
||||
if offset_seconds is not None:
|
||||
track = str(cfg.get("sync_reference_track") or "source")
|
||||
offsets = dict(cfg.get("track_offsets_seconds") or {})
|
||||
offsets[track] = float(offset_seconds)
|
||||
cfg["track_offsets_seconds"] = offsets
|
||||
cfg["last_sync"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
written = _write_karaoke_config(project_root, cfg)
|
||||
return {
|
||||
"success": True,
|
||||
"project_id": project.get("id"),
|
||||
"config": written,
|
||||
}
|
||||
|
||||
|
||||
def _resolve_reference_track_file(project: dict, track_name: str) -> Path:
|
||||
sep_job = jobs_repo.get(project["sep_job_id"]) or {}
|
||||
if track_name == "source":
|
||||
source = _pick_source_media_file(sep_job)
|
||||
if source is None:
|
||||
raise ProjectOperationError(404, "No source media file found for project")
|
||||
return source
|
||||
|
||||
stems = _collect_project_stems(sep_job)
|
||||
for stem in stems:
|
||||
if str(stem["name"]).lower() == track_name.lower():
|
||||
return Path(stem["path"])
|
||||
raise ProjectOperationError(404, f"Reference track not found: {track_name}")
|
||||
|
||||
|
||||
def _looks_like_url(value: str) -> bool:
|
||||
return value.startswith("http://") or value.startswith("https://")
|
||||
|
||||
|
||||
def _download_video_from_url(video_url: str, target_dir: Path) -> Path:
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
out_tpl = str(target_dir / "video.%(ext)s")
|
||||
cmd = [
|
||||
"yt-dlp",
|
||||
"--no-playlist",
|
||||
"-f",
|
||||
"bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best",
|
||||
"-o",
|
||||
out_tpl,
|
||||
video_url,
|
||||
]
|
||||
completed = subprocess.run(cmd, capture_output=True, text=True)
|
||||
if completed.returncode != 0:
|
||||
msg = (completed.stderr or completed.stdout or "yt-dlp failed").strip()
|
||||
raise ProjectOperationError(400, f"Failed to fetch video URL: {msg}")
|
||||
|
||||
candidates = sorted(target_dir.glob("video.*"), key=lambda p: p.stat().st_mtime, reverse=True)
|
||||
if not candidates:
|
||||
raise ProjectOperationError(400, "Failed to download video from URL")
|
||||
return candidates[0]
|
||||
|
||||
|
||||
def _resolve_video_source_to_file(project_root: Path, source: str) -> Path:
|
||||
cleaned = str(source or "").strip()
|
||||
if not cleaned:
|
||||
raise ProjectOperationError(400, "Video source is empty")
|
||||
|
||||
if _looks_like_url(cleaned):
|
||||
assets_dir = project_root / "Assets" / "Video"
|
||||
return _download_video_from_url(cleaned, assets_dir)
|
||||
|
||||
candidate = Path(cleaned)
|
||||
if not candidate.is_absolute():
|
||||
candidate = (project_root / candidate).resolve()
|
||||
if not candidate.exists() or not candidate.is_file():
|
||||
raise ProjectOperationError(404, f"Video file not found: {cleaned}")
|
||||
return candidate
|
||||
|
||||
|
||||
def _estimate_track_offset_seconds(reference_file: Path, video_file: Path) -> float:
|
||||
sr = 22050
|
||||
duration = 120.0
|
||||
y_ref, _ = librosa.load(str(reference_file), sr=sr, mono=True, offset=0.0, duration=duration)
|
||||
y_vid, _ = librosa.load(str(video_file), sr=sr, mono=True, offset=0.0, duration=duration)
|
||||
if y_ref.size == 0 or y_vid.size == 0:
|
||||
raise ProjectOperationError(400, "Could not decode audio for sync")
|
||||
|
||||
ref_env = librosa.onset.onset_strength(y=y_ref, sr=sr)
|
||||
vid_env = librosa.onset.onset_strength(y=y_vid, sr=sr)
|
||||
if ref_env.size < 16 or vid_env.size < 16:
|
||||
raise ProjectOperationError(400, "Not enough audio detail to estimate sync offset")
|
||||
|
||||
ref_env = ref_env - np.mean(ref_env)
|
||||
vid_env = vid_env - np.mean(vid_env)
|
||||
corr = np.correlate(vid_env, ref_env, mode="full")
|
||||
lag = int(np.argmax(corr) - (ref_env.size - 1))
|
||||
|
||||
hop_length = 512
|
||||
offset_seconds = float((lag * hop_length) / sr)
|
||||
return round(offset_seconds, 3)
|
||||
|
||||
|
||||
def sync_project_video_offset(
|
||||
project: dict,
|
||||
*,
|
||||
video_source: str,
|
||||
reference_track: str = "source",
|
||||
) -> dict:
|
||||
project_root = project_output_dir(project)
|
||||
if not project_root.exists():
|
||||
raise ProjectOperationError(404, "Project directory not found")
|
||||
|
||||
ref_file = _resolve_reference_track_file(project, reference_track)
|
||||
video_file = _resolve_video_source_to_file(project_root, video_source)
|
||||
offset_seconds = _estimate_track_offset_seconds(ref_file, video_file)
|
||||
|
||||
cfg = _read_karaoke_config(project_root)
|
||||
cfg["video_source"] = str(video_source).strip()
|
||||
cfg["sync_reference_track"] = reference_track
|
||||
offsets = dict(cfg.get("track_offsets_seconds") or {})
|
||||
offsets[reference_track] = offset_seconds
|
||||
cfg["track_offsets_seconds"] = offsets
|
||||
cfg["last_sync"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
written = _write_karaoke_config(project_root, cfg)
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"project_id": project.get("id"),
|
||||
"reference_track": reference_track,
|
||||
"offset_seconds": offset_seconds,
|
||||
"resolved_video": str(video_file),
|
||||
"config": written,
|
||||
}
|
||||
|
||||
|
||||
def _collect_project_stems(sep_job: dict | None) -> list[dict]:
|
||||
stems: list[dict] = []
|
||||
for file_entry in (sep_job or {}).get("files", []):
|
||||
if file_entry.get("type") != "stem":
|
||||
continue
|
||||
raw_path = file_entry.get("path")
|
||||
if not raw_path:
|
||||
continue
|
||||
path = Path(str(raw_path))
|
||||
if not path.exists() or not path.is_file():
|
||||
continue
|
||||
stems.append(
|
||||
{
|
||||
"name": str(file_entry.get("stem") or path.stem),
|
||||
"path": path,
|
||||
"filename": path.name,
|
||||
}
|
||||
)
|
||||
return stems
|
||||
|
||||
|
||||
def _pick_optional_video_file(project_root: Path, sep_job: dict | None) -> Path | None:
|
||||
video_exts = {".mp4", ".mkv", ".webm", ".mov", ".m4v"}
|
||||
|
||||
source_media = _pick_source_media_file(sep_job)
|
||||
if source_media and source_media.suffix.lower() in video_exts:
|
||||
return source_media
|
||||
|
||||
candidates = [
|
||||
p
|
||||
for p in project_root.rglob("*")
|
||||
if p.is_file() and p.suffix.lower() in video_exts
|
||||
]
|
||||
if not candidates:
|
||||
return None
|
||||
return sorted(candidates, key=lambda p: p.stat().st_mtime, reverse=True)[0]
|
||||
|
||||
|
||||
def _sanitize_filename_component(value: str) -> str:
|
||||
bad = '<>:"/\\|?*'
|
||||
cleaned = "".join("_" if ch in bad or ord(ch) < 32 else ch for ch in (value or "").strip())
|
||||
cleaned = " ".join(cleaned.split())
|
||||
return cleaned.strip(". ")
|
||||
|
||||
|
||||
def export_project_stemengine_karaoke(
|
||||
project: dict,
|
||||
package_name: str | None = None,
|
||||
include_video: bool = True,
|
||||
video_source: str | None = None,
|
||||
sync_reference_track: str | None = None,
|
||||
auto_sync: bool = True,
|
||||
) -> dict:
|
||||
"""
|
||||
Build a StemEngine Karaoke (.sek) package for a project.
|
||||
|
||||
A .sek file is a ZIP archive with this layout:
|
||||
- manifest.json
|
||||
- stems/*
|
||||
- lyrics/*.elrc
|
||||
- video/* (optional)
|
||||
"""
|
||||
sep_job = jobs_repo.get(project["sep_job_id"]) or {}
|
||||
project_root = project_output_dir(project)
|
||||
if not project_root.exists():
|
||||
raise ProjectOperationError(404, "Project directory not found")
|
||||
|
||||
stems = _collect_project_stems(sep_job)
|
||||
if not stems:
|
||||
raise ProjectOperationError(404, "No stem files found for project")
|
||||
|
||||
elrc_path = _pick_best_elrc_file(project_root)
|
||||
if elrc_path is None:
|
||||
raise ProjectOperationError(404, "No .elrc lyrics file found for project")
|
||||
|
||||
cfg = _read_karaoke_config(project_root)
|
||||
if video_source is not None:
|
||||
cfg["video_source"] = str(video_source).strip()
|
||||
if sync_reference_track is not None and str(sync_reference_track).strip():
|
||||
cfg["sync_reference_track"] = str(sync_reference_track).strip()
|
||||
|
||||
# Persist any explicit overrides so project config remains the source of truth.
|
||||
cfg = _write_karaoke_config(project_root, cfg)
|
||||
|
||||
cfg_include_video = bool(cfg.get("include_video", True))
|
||||
effective_include_video = bool(include_video and cfg_include_video)
|
||||
|
||||
video_path: Path | None = None
|
||||
configured_source = str(cfg.get("video_source") or "").strip()
|
||||
if effective_include_video and configured_source:
|
||||
try:
|
||||
video_path = _resolve_video_source_to_file(project_root, configured_source)
|
||||
except ProjectOperationError:
|
||||
video_path = None
|
||||
if effective_include_video and video_path is None:
|
||||
video_path = _pick_optional_video_file(project_root, sep_job)
|
||||
|
||||
warnings: list[str] = []
|
||||
|
||||
# Automatic synchronization: when video is requested and a configured source exists,
|
||||
# estimate and persist offset for the selected reference track before packaging.
|
||||
auto_sync_applied = False
|
||||
auto_sync_offset: float | None = None
|
||||
reference_track = str(cfg.get("sync_reference_track") or "source")
|
||||
if auto_sync and effective_include_video and configured_source:
|
||||
try:
|
||||
ref_file = _resolve_reference_track_file(project, reference_track)
|
||||
resolved_video_for_sync = _resolve_video_source_to_file(project_root, configured_source)
|
||||
estimated = _estimate_track_offset_seconds(ref_file, resolved_video_for_sync)
|
||||
|
||||
offsets = dict(cfg.get("track_offsets_seconds") or {})
|
||||
offsets[reference_track] = estimated
|
||||
cfg["track_offsets_seconds"] = offsets
|
||||
cfg["last_sync"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
cfg = _write_karaoke_config(project_root, cfg)
|
||||
|
||||
auto_sync_applied = True
|
||||
auto_sync_offset = estimated
|
||||
except ProjectOperationError as exc:
|
||||
warnings.append(f"Auto-sync failed: {exc.detail}")
|
||||
except Exception:
|
||||
warnings.append("Auto-sync failed due to an unexpected error")
|
||||
|
||||
stem_count = len(stems)
|
||||
now_iso = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
source_media = _pick_source_media_file(sep_job)
|
||||
source_metadata, cover_bytes, _cover_mime, cover_name = _build_source_metadata_component(source_media)
|
||||
default_base = project.get("name") or (source_media.stem if source_media else project.get("id") or "StemEngine Karaoke")
|
||||
chosen_base = _sanitize_filename_component(package_name or default_base) or "StemEngine Karaoke"
|
||||
sek_filename = chosen_base if chosen_base.lower().endswith(".sek") else f"{chosen_base}.sek"
|
||||
|
||||
configured_export_dir = str(STEMENGINE_KARAOKE_EXPORT_DIR or "").strip()
|
||||
if configured_export_dir:
|
||||
base_export_dir = Path(configured_export_dir)
|
||||
if not base_export_dir.is_absolute():
|
||||
base_export_dir = project_root / base_export_dir
|
||||
project_bucket = _sanitize_filename_component(project.get("name") or project.get("id") or "project") or "project"
|
||||
export_dir = base_export_dir / project_bucket
|
||||
else:
|
||||
export_dir = project_root / "Exports" / "StemEngineKaraoke"
|
||||
export_dir.mkdir(parents=True, exist_ok=True)
|
||||
sek_path = export_dir / sek_filename
|
||||
|
||||
video_note: str | None = None
|
||||
if not effective_include_video:
|
||||
video_note = "No video included: video packaging is disabled."
|
||||
elif video_path is None:
|
||||
video_note = "No video included: no video source/file could be resolved for this package."
|
||||
|
||||
manifest = {
|
||||
"format": "stemengine-karaoke",
|
||||
"version": 1,
|
||||
"created_at": now_iso,
|
||||
"project": {
|
||||
"id": project.get("id"),
|
||||
"name": project.get("name"),
|
||||
},
|
||||
"metadata": source_metadata,
|
||||
"contents": {
|
||||
"lyrics": f"lyrics/{elrc_path.name}",
|
||||
"video": f"video/{video_path.name}" if video_path else None,
|
||||
"stems": [
|
||||
{
|
||||
"name": stem["name"],
|
||||
"file": f"stems/{stem['filename']}",
|
||||
"bytes": stem["path"].stat().st_size,
|
||||
}
|
||||
for stem in stems
|
||||
],
|
||||
},
|
||||
"meta": {
|
||||
"stem_count": stem_count,
|
||||
"has_video": bool(video_path),
|
||||
"video_note": video_note,
|
||||
"lyrics_type": "elrc",
|
||||
"synchronization": {
|
||||
"reference_track": reference_track,
|
||||
"track_offsets_seconds": cfg.get("track_offsets_seconds") or {},
|
||||
"video_source": configured_source,
|
||||
"last_sync": cfg.get("last_sync"),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
with zipfile.ZipFile(sek_path, mode="w", compression=zipfile.ZIP_DEFLATED) as zf:
|
||||
zf.writestr("manifest.json", json.dumps(manifest, ensure_ascii=False, indent=2))
|
||||
zf.write(elrc_path, arcname=f"lyrics/{elrc_path.name}")
|
||||
for stem in stems:
|
||||
zf.write(stem["path"], arcname=f"stems/{stem['filename']}")
|
||||
if cover_bytes and cover_name:
|
||||
zf.writestr(f"metadata/{cover_name}", cover_bytes)
|
||||
if video_path:
|
||||
zf.write(video_path, arcname=f"video/{video_path.name}")
|
||||
|
||||
if effective_include_video and video_path is None:
|
||||
warnings.append("No video file found; packaged audio stems + .elrc only.")
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"project_id": project.get("id"),
|
||||
"project_name": project.get("name"),
|
||||
"sek_path": str(sek_path),
|
||||
"package_name": sek_filename,
|
||||
"export_dir": str(export_dir),
|
||||
"stem_count": stem_count,
|
||||
"lyrics": str(elrc_path),
|
||||
"video": str(video_path) if video_path else "",
|
||||
"auto_sync_applied": auto_sync_applied,
|
||||
"auto_sync_reference_track": reference_track,
|
||||
"auto_sync_offset_seconds": auto_sync_offset,
|
||||
"warnings": warnings,
|
||||
}
|
||||
|
||||
|
||||
def export_project_karaoke_mugen(
|
||||
project: dict,
|
||||
default_title_lang: str = "eng",
|
||||
repository: str = "stemengine.local",
|
||||
) -> dict:
|
||||
"""
|
||||
Build a Karaoke Mugen-compatible export folder for a StemEngine project.
|
||||
|
||||
Output layout:
|
||||
<project>/Exports/KaraokeMugen/<kid>/
|
||||
- <kid>.kara.json
|
||||
- <copied media file>
|
||||
- <copied lyrics file> (preferred .ass, fallback .lrc/.elrc)
|
||||
"""
|
||||
sep_job = jobs_repo.get(project["sep_job_id"]) or {}
|
||||
media_path = _pick_source_media_file(sep_job)
|
||||
if media_path is None:
|
||||
raise ProjectOperationError(404, "No source media file found for project")
|
||||
|
||||
project_root = project_output_dir(project)
|
||||
if not project_root.exists():
|
||||
raise ProjectOperationError(404, "Project directory not found")
|
||||
|
||||
lyrics_path = _pick_best_lyrics_file(project_root)
|
||||
|
||||
kid = str(uuid4())
|
||||
now_iso = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
export_dir = project_root / "Exports" / "KaraokeMugen" / kid
|
||||
export_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
media_dest = export_dir / media_path.name
|
||||
shutil.copy2(media_path, media_dest)
|
||||
|
||||
lyrics_entries = []
|
||||
warnings: list[str] = []
|
||||
if lyrics_path is not None:
|
||||
lyrics_dest = export_dir / lyrics_path.name
|
||||
shutil.copy2(lyrics_path, lyrics_dest)
|
||||
lyrics_entries.append(
|
||||
{
|
||||
"default": True,
|
||||
"filename": lyrics_dest.name,
|
||||
"version": "Default",
|
||||
}
|
||||
)
|
||||
if lyrics_dest.suffix.lower() != ".ass":
|
||||
warnings.append(
|
||||
"Lyrics file is not ASS; convert to .ass in Aegisub for best Karaoke Mugen compatibility."
|
||||
)
|
||||
else:
|
||||
warnings.append(
|
||||
"No lyrics file (.ass/.lrc/.elrc) was found in the project; add one before importing into Karaoke Mugen."
|
||||
)
|
||||
|
||||
title_lang = (default_title_lang or "eng").strip().lower() or "eng"
|
||||
title_value = project.get("name") or media_path.stem
|
||||
year_value = datetime.now(timezone.utc).year
|
||||
|
||||
kara_payload = {
|
||||
"header": {
|
||||
"version": 4,
|
||||
"description": "Karaoke Mugen Karaoke Data File",
|
||||
},
|
||||
"medias": [
|
||||
{
|
||||
"default": True,
|
||||
"duration": 0,
|
||||
"filename": media_dest.name,
|
||||
"filesize": media_dest.stat().st_size,
|
||||
"lyrics": lyrics_entries,
|
||||
"version": "Default",
|
||||
}
|
||||
],
|
||||
"data": {
|
||||
"created_at": now_iso,
|
||||
"ignoreHooks": False,
|
||||
"kid": kid,
|
||||
"modified_at": now_iso,
|
||||
"repository": (repository or "stemengine.local").strip() or "stemengine.local",
|
||||
"songname": title_value,
|
||||
"tags": {
|
||||
"authors": [],
|
||||
"collections": [],
|
||||
"creators": [],
|
||||
"families": [],
|
||||
"genres": [],
|
||||
"groups": [],
|
||||
"langs": [],
|
||||
"misc": [],
|
||||
"origins": [],
|
||||
"platforms": [],
|
||||
"series": [],
|
||||
"singers": [],
|
||||
"singergroups": [],
|
||||
"songtypes": [],
|
||||
"songwriters": [],
|
||||
"versions": [],
|
||||
"warnings": [],
|
||||
"franchises": [],
|
||||
},
|
||||
"titles": {
|
||||
title_lang: title_value,
|
||||
},
|
||||
"titles_default_language": title_lang,
|
||||
"titles_aliases": [],
|
||||
"year": year_value,
|
||||
},
|
||||
"meta": {
|
||||
"stemengine": {
|
||||
"project_id": project.get("id"),
|
||||
"project_name": project.get("name"),
|
||||
"source_media": str(media_path),
|
||||
"source_lyrics": str(lyrics_path) if lyrics_path else None,
|
||||
"warnings": warnings,
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
kara_path = export_dir / f"{kid}.kara.json"
|
||||
kara_path.write_text(json.dumps(kara_payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"project_id": project.get("id"),
|
||||
"project_name": project.get("name"),
|
||||
"kid": kid,
|
||||
"export_dir": str(export_dir),
|
||||
"kara_json": str(kara_path),
|
||||
"media": str(media_dest),
|
||||
"lyrics": str((export_dir / lyrics_path.name) if lyrics_path else ""),
|
||||
"warnings": warnings,
|
||||
}
|
||||
@@ -47,6 +47,15 @@ def enqueue_stem_reprocess(
|
||||
project_dir = project_output_dir(project)
|
||||
reprocess_dir = project_dir / "Stems" / "Reprocessed" / _safe_reprocess_folder_name(stem_name)
|
||||
job_id = jm.create_job("separate")
|
||||
jobs_repo.update(
|
||||
job_id,
|
||||
result={
|
||||
"reprocess": True,
|
||||
"parent_job_id": project["sep_job_id"],
|
||||
"parent_project_id": project["id"],
|
||||
"source_stem": stem_name,
|
||||
},
|
||||
)
|
||||
jm.submit_gpu(
|
||||
run_separation,
|
||||
job_id,
|
||||
|
||||
@@ -8,12 +8,17 @@ from .project_assets_service import (
|
||||
build_project_detail,
|
||||
collect_related_job_ids,
|
||||
delete_project_stem,
|
||||
export_project_stemengine_karaoke,
|
||||
delete_project_with_related_jobs,
|
||||
export_project_karaoke_mugen,
|
||||
get_project_karaoke_config,
|
||||
get_project_cover_art,
|
||||
get_project_or_raise,
|
||||
list_projects,
|
||||
rename_project_stem,
|
||||
rescan_project_stems,
|
||||
sync_project_video_offset,
|
||||
update_project_karaoke_config,
|
||||
)
|
||||
from .project_cleanup_service import (
|
||||
cleanup_all_lrc_output_files,
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import mimetypes
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from zipfile import BadZipFile, ZipFile
|
||||
|
||||
from ..config import SETTINGS_PATH
|
||||
from .project_service_common import ProjectOperationError
|
||||
|
||||
|
||||
def _load_settings() -> dict[str, Any]:
|
||||
if not SETTINGS_PATH.exists():
|
||||
return {}
|
||||
try:
|
||||
raw = json.loads(SETTINGS_PATH.read_text(encoding="utf-8"))
|
||||
return raw if isinstance(raw, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _resolve_folder_path(folder: str | None = None) -> Path:
|
||||
if folder and str(folder).strip():
|
||||
return Path(str(folder).strip())
|
||||
settings = _load_settings()
|
||||
configured = str(settings.get("karaoke_sek_folder") or "").strip()
|
||||
if not configured:
|
||||
raise ProjectOperationError(400, "No SEK folder configured")
|
||||
return Path(configured)
|
||||
|
||||
|
||||
def _package_id(path: Path) -> str:
|
||||
return hashlib.sha1(str(path.resolve()).encode("utf-8")).hexdigest()[:16]
|
||||
|
||||
|
||||
def _safe_zip_member(member: str) -> bool:
|
||||
if not member:
|
||||
return False
|
||||
p = Path(member)
|
||||
if p.is_absolute():
|
||||
return False
|
||||
return ".." not in p.parts
|
||||
|
||||
|
||||
def _read_manifest(package_path: Path) -> dict[str, Any]:
|
||||
with ZipFile(package_path, "r") as zf:
|
||||
try:
|
||||
raw = zf.read("manifest.json")
|
||||
except KeyError as exc:
|
||||
raise ProjectOperationError(400, f"Package missing manifest.json: {package_path.name}") from exc
|
||||
try:
|
||||
parsed = json.loads(raw.decode("utf-8"))
|
||||
if not isinstance(parsed, dict):
|
||||
raise ValueError("manifest root must be object")
|
||||
return parsed
|
||||
except Exception as exc:
|
||||
raise ProjectOperationError(400, f"Invalid manifest.json in {package_path.name}") from exc
|
||||
|
||||
|
||||
def list_sek_packages(folder: str | None = None) -> dict[str, Any]:
|
||||
base = _resolve_folder_path(folder)
|
||||
if not base.exists() or not base.is_dir():
|
||||
raise ProjectOperationError(404, f"SEK folder does not exist: {base}")
|
||||
|
||||
packages: list[dict[str, Any]] = []
|
||||
for package_path in sorted(base.glob("*.sek"), key=lambda p: p.stat().st_mtime, reverse=True):
|
||||
warnings: list[str] = []
|
||||
manifest: dict[str, Any] | None = None
|
||||
valid = True
|
||||
|
||||
try:
|
||||
manifest = _read_manifest(package_path)
|
||||
except (ProjectOperationError, BadZipFile):
|
||||
valid = False
|
||||
warnings.append("Unreadable package or missing manifest.json")
|
||||
|
||||
contents = (manifest or {}).get("contents") if isinstance(manifest, dict) else {}
|
||||
stems = contents.get("stems") if isinstance(contents, dict) else []
|
||||
lyrics = contents.get("lyrics") if isinstance(contents, dict) else ""
|
||||
video = contents.get("video") if isinstance(contents, dict) else ""
|
||||
|
||||
title = (
|
||||
((manifest or {}).get("project") or {}).get("name")
|
||||
if isinstance((manifest or {}).get("project"), dict)
|
||||
else None
|
||||
) or package_path.stem
|
||||
|
||||
if valid and not lyrics:
|
||||
warnings.append("manifest contents.lyrics is missing")
|
||||
if valid and not isinstance(stems, list):
|
||||
warnings.append("manifest contents.stems is not a list")
|
||||
|
||||
packages.append(
|
||||
{
|
||||
"id": _package_id(package_path),
|
||||
"filename": package_path.name,
|
||||
"path": str(package_path.resolve()),
|
||||
"title": title,
|
||||
"valid": valid,
|
||||
"stem_count": len(stems) if isinstance(stems, list) else 0,
|
||||
"has_video": bool(video),
|
||||
"lyrics": lyrics if isinstance(lyrics, str) else "",
|
||||
"mtime": package_path.stat().st_mtime,
|
||||
"warnings": warnings,
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"folder": str(base.resolve()),
|
||||
"count": len(packages),
|
||||
"packages": packages,
|
||||
}
|
||||
|
||||
|
||||
def _resolve_package_by_id(package_id: str, folder: str | None = None) -> Path:
|
||||
base = _resolve_folder_path(folder)
|
||||
if not base.exists() or not base.is_dir():
|
||||
raise ProjectOperationError(404, f"SEK folder does not exist: {base}")
|
||||
|
||||
for package_path in base.glob("*.sek"):
|
||||
if _package_id(package_path) == package_id:
|
||||
return package_path
|
||||
raise ProjectOperationError(404, f"Package not found: {package_id}")
|
||||
|
||||
|
||||
def get_sek_manifest(package_id: str, folder: str | None = None) -> dict[str, Any]:
|
||||
package_path = _resolve_package_by_id(package_id, folder)
|
||||
manifest = _read_manifest(package_path)
|
||||
return {
|
||||
"id": package_id,
|
||||
"filename": package_path.name,
|
||||
"path": str(package_path.resolve()),
|
||||
"manifest": manifest,
|
||||
}
|
||||
|
||||
|
||||
def get_sek_asset(package_id: str, inner_path: str, folder: str | None = None) -> tuple[bytes, str, str]:
|
||||
package_path = _resolve_package_by_id(package_id, folder)
|
||||
normalized = str(inner_path or "").strip().replace("\\", "/")
|
||||
if not _safe_zip_member(normalized):
|
||||
raise ProjectOperationError(400, "Invalid package asset path")
|
||||
|
||||
with ZipFile(package_path, "r") as zf:
|
||||
names = set(zf.namelist())
|
||||
if normalized not in names:
|
||||
raise ProjectOperationError(404, f"Asset not found in package: {normalized}")
|
||||
data = zf.read(normalized)
|
||||
|
||||
mime, _ = mimetypes.guess_type(normalized)
|
||||
return data, (mime or "application/octet-stream"), normalized.split("/")[-1]
|
||||
@@ -1342,6 +1342,8 @@ def _run_separation_impl(
|
||||
progress="Separation complete.",
|
||||
files=all_files,
|
||||
result={
|
||||
"reprocess": output_dir_override is not None,
|
||||
"parent_job_id": parent_job_id if output_dir_override is not None else None,
|
||||
"project_name": proj_name,
|
||||
"project_path": str(dirs['project']),
|
||||
"stems_dir": str(stems_dir),
|
||||
|
||||
@@ -264,7 +264,9 @@ def search_songs(
|
||||
x for x in [title.strip(), artist.strip(), album.strip(), album_artist.strip()] if x
|
||||
)
|
||||
if not effective_query:
|
||||
return []
|
||||
# Browsing mode fallback when no explicit query is provided.
|
||||
# Most Subsonic-compatible servers accept '*' as wildcard for search3.
|
||||
effective_query = '*'
|
||||
|
||||
p = _params(config)
|
||||
# Over-fetch and post-filter so advanced fields (title/album/albumArtist)
|
||||
@@ -319,6 +321,252 @@ def search_songs(
|
||||
return songs[: max(1, int(count or 20))]
|
||||
|
||||
|
||||
def list_playlists() -> list[dict]:
|
||||
"""Return playlists from Subsonic server."""
|
||||
config = load_config()
|
||||
if not config:
|
||||
raise RuntimeError("Subsonic server not configured")
|
||||
|
||||
p = _params(config)
|
||||
r = _requests.get(_url(config, 'getPlaylists.view'), params=p, timeout=20)
|
||||
r.raise_for_status()
|
||||
resp = r.json().get('subsonic-response', {})
|
||||
|
||||
if resp.get('status') != 'ok':
|
||||
msg = resp.get('error', {}).get('message', 'Subsonic API error')
|
||||
raise RuntimeError(msg)
|
||||
|
||||
playlists = resp.get('playlists', {}).get('playlist', []) or []
|
||||
results = []
|
||||
for item in playlists:
|
||||
results.append({
|
||||
'id': item.get('id', ''),
|
||||
'name': item.get('name', 'Untitled Playlist'),
|
||||
'songCount': int(item.get('songCount') or 0),
|
||||
'duration': int(item.get('duration') or 0),
|
||||
'public': bool(item.get('public', False)),
|
||||
'owner': item.get('owner', ''),
|
||||
'created': item.get('created', ''),
|
||||
'changed': item.get('changed', ''),
|
||||
})
|
||||
return results
|
||||
|
||||
|
||||
def get_playlist(playlist_id: str) -> dict:
|
||||
"""Return playlist details with songs."""
|
||||
config = load_config()
|
||||
if not config:
|
||||
raise RuntimeError("Subsonic server not configured")
|
||||
|
||||
p = _params(config)
|
||||
p['id'] = playlist_id
|
||||
r = _requests.get(_url(config, 'getPlaylist.view'), params=p, timeout=20)
|
||||
r.raise_for_status()
|
||||
resp = r.json().get('subsonic-response', {})
|
||||
|
||||
if resp.get('status') != 'ok':
|
||||
msg = resp.get('error', {}).get('message', 'Subsonic API error')
|
||||
raise RuntimeError(msg)
|
||||
|
||||
playlist = resp.get('playlist') or {}
|
||||
entries = playlist.get('entry') or []
|
||||
|
||||
songs = []
|
||||
for s in entries:
|
||||
song_artist = s.get('artist', '')
|
||||
song_album_artist = s.get('albumArtist', '')
|
||||
songs.append({
|
||||
'id': s.get('id', ''),
|
||||
'title': s.get('title', 'Unknown'),
|
||||
'artist': song_album_artist or song_artist,
|
||||
'songArtist': song_artist,
|
||||
'albumArtist': song_album_artist,
|
||||
'album': s.get('album', ''),
|
||||
'duration': int(s.get('duration') or 0),
|
||||
'suffix': s.get('suffix', 'mp3'),
|
||||
'size': int(s.get('size') or 0),
|
||||
'bitRate': int(s.get('bitRate') or 0),
|
||||
})
|
||||
|
||||
return {
|
||||
'id': playlist.get('id', ''),
|
||||
'name': playlist.get('name', 'Untitled Playlist'),
|
||||
'songCount': int(playlist.get('songCount') or len(songs)),
|
||||
'duration': int(playlist.get('duration') or 0),
|
||||
'public': bool(playlist.get('public', False)),
|
||||
'owner': playlist.get('owner', ''),
|
||||
'created': playlist.get('created', ''),
|
||||
'changed': playlist.get('changed', ''),
|
||||
'songs': songs,
|
||||
}
|
||||
|
||||
|
||||
def _normalize_song(s: dict) -> dict:
|
||||
song_artist = s.get('artist', '')
|
||||
song_album_artist = s.get('albumArtist', '')
|
||||
return {
|
||||
'id': s.get('id', ''),
|
||||
'title': s.get('title', 'Unknown'),
|
||||
'artist': song_album_artist or song_artist,
|
||||
'songArtist': song_artist,
|
||||
'albumArtist': song_album_artist,
|
||||
'album': s.get('album', ''),
|
||||
'duration': int(s.get('duration') or 0),
|
||||
'suffix': s.get('suffix', 'mp3'),
|
||||
'size': int(s.get('size') or 0),
|
||||
'bitRate': int(s.get('bitRate') or 0),
|
||||
}
|
||||
|
||||
|
||||
def list_albums(offset: int = 0, size: int = 50, query: str = '', artist_id: str = '') -> list[dict]:
|
||||
"""Return paged album browse results from Subsonic server."""
|
||||
config = load_config()
|
||||
if not config:
|
||||
raise RuntimeError("Subsonic server not configured")
|
||||
|
||||
p = _params(config)
|
||||
p.update({
|
||||
'type': 'alphabeticalByName',
|
||||
'size': max(1, min(int(size or 50), 500)),
|
||||
'offset': max(0, int(offset or 0)),
|
||||
})
|
||||
if artist_id:
|
||||
p['artistId'] = artist_id
|
||||
|
||||
r = _requests.get(_url(config, 'getAlbumList2.view'), params=p, timeout=20)
|
||||
r.raise_for_status()
|
||||
resp = r.json().get('subsonic-response', {})
|
||||
|
||||
if resp.get('status') != 'ok':
|
||||
msg = resp.get('error', {}).get('message', 'Subsonic API error')
|
||||
raise RuntimeError(msg)
|
||||
|
||||
albums = resp.get('albumList2', {}).get('album', []) or []
|
||||
q = (query or '').strip().lower()
|
||||
|
||||
results = []
|
||||
for album in albums:
|
||||
title = album.get('name', 'Unknown Album')
|
||||
artist = album.get('artist', 'Unknown Artist')
|
||||
if q and q not in title.lower() and q not in artist.lower():
|
||||
continue
|
||||
results.append({
|
||||
'id': album.get('id', ''),
|
||||
'name': title,
|
||||
'artist': artist,
|
||||
'songCount': int(album.get('songCount') or 0),
|
||||
'duration': int(album.get('duration') or 0),
|
||||
'year': int(album.get('year') or 0) if album.get('year') else None,
|
||||
'coverArt': album.get('coverArt', ''),
|
||||
})
|
||||
return results
|
||||
|
||||
|
||||
def get_album(album_id: str) -> dict:
|
||||
"""Return album details with tracks."""
|
||||
config = load_config()
|
||||
if not config:
|
||||
raise RuntimeError("Subsonic server not configured")
|
||||
|
||||
p = _params(config)
|
||||
p['id'] = album_id
|
||||
r = _requests.get(_url(config, 'getAlbum.view'), params=p, timeout=20)
|
||||
r.raise_for_status()
|
||||
resp = r.json().get('subsonic-response', {})
|
||||
|
||||
if resp.get('status') != 'ok':
|
||||
msg = resp.get('error', {}).get('message', 'Subsonic API error')
|
||||
raise RuntimeError(msg)
|
||||
|
||||
album = resp.get('album') or {}
|
||||
songs = [_normalize_song(s) for s in (album.get('song') or [])]
|
||||
|
||||
return {
|
||||
'id': album.get('id', ''),
|
||||
'name': album.get('name', 'Unknown Album'),
|
||||
'artist': album.get('artist', 'Unknown Artist'),
|
||||
'songCount': int(album.get('songCount') or len(songs)),
|
||||
'duration': int(album.get('duration') or 0),
|
||||
'year': int(album.get('year') or 0) if album.get('year') else None,
|
||||
'coverArt': album.get('coverArt', ''),
|
||||
'songs': songs,
|
||||
}
|
||||
|
||||
|
||||
def list_artists(offset: int = 0, size: int = 200, query: str = '') -> list[dict]:
|
||||
"""Return artist browse results from Subsonic server.
|
||||
|
||||
Subsonic `getArtists` is index-based (non-paged), so pagination is applied
|
||||
in-process after flattening.
|
||||
"""
|
||||
config = load_config()
|
||||
if not config:
|
||||
raise RuntimeError("Subsonic server not configured")
|
||||
|
||||
p = _params(config)
|
||||
r = _requests.get(_url(config, 'getArtists.view'), params=p, timeout=20)
|
||||
r.raise_for_status()
|
||||
resp = r.json().get('subsonic-response', {})
|
||||
|
||||
if resp.get('status') != 'ok':
|
||||
msg = resp.get('error', {}).get('message', 'Subsonic API error')
|
||||
raise RuntimeError(msg)
|
||||
|
||||
flat = []
|
||||
for bucket in (resp.get('artists', {}).get('index', []) or []):
|
||||
for artist in (bucket.get('artist', []) or []):
|
||||
flat.append({
|
||||
'id': artist.get('id', ''),
|
||||
'name': artist.get('name', 'Unknown Artist'),
|
||||
'albumCount': int(artist.get('albumCount') or 0),
|
||||
})
|
||||
|
||||
q = (query or '').strip().lower()
|
||||
if q:
|
||||
flat = [a for a in flat if q in a['name'].lower()]
|
||||
|
||||
start = max(0, int(offset or 0))
|
||||
end = start + max(1, min(int(size or 200), 1000))
|
||||
return flat[start:end]
|
||||
|
||||
|
||||
def get_artist(artist_id: str) -> dict:
|
||||
"""Return artist details including albums."""
|
||||
config = load_config()
|
||||
if not config:
|
||||
raise RuntimeError("Subsonic server not configured")
|
||||
|
||||
p = _params(config)
|
||||
p['id'] = artist_id
|
||||
r = _requests.get(_url(config, 'getArtist.view'), params=p, timeout=20)
|
||||
r.raise_for_status()
|
||||
resp = r.json().get('subsonic-response', {})
|
||||
|
||||
if resp.get('status') != 'ok':
|
||||
msg = resp.get('error', {}).get('message', 'Subsonic API error')
|
||||
raise RuntimeError(msg)
|
||||
|
||||
artist = resp.get('artist') or {}
|
||||
albums = []
|
||||
for album in (artist.get('album') or []):
|
||||
albums.append({
|
||||
'id': album.get('id', ''),
|
||||
'name': album.get('name', 'Unknown Album'),
|
||||
'artist': album.get('artist', artist.get('name', 'Unknown Artist')),
|
||||
'songCount': int(album.get('songCount') or 0),
|
||||
'duration': int(album.get('duration') or 0),
|
||||
'year': int(album.get('year') or 0) if album.get('year') else None,
|
||||
'coverArt': album.get('coverArt', ''),
|
||||
})
|
||||
|
||||
return {
|
||||
'id': artist.get('id', ''),
|
||||
'name': artist.get('name', 'Unknown Artist'),
|
||||
'albumCount': int(artist.get('albumCount') or len(albums)),
|
||||
'albums': albums,
|
||||
}
|
||||
|
||||
|
||||
def import_song(
|
||||
song_id: str,
|
||||
title: str,
|
||||
|
||||
@@ -19,8 +19,8 @@
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
||||
<meta name="apple-mobile-web-app-title" content="StemEngine" />
|
||||
<link rel="apple-touch-icon" href="/icon.svg" />
|
||||
<script type="module" crossorigin src="/assets/index-Dyzk5W1F.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-wvyRPrYl.css">
|
||||
<script type="module" crossorigin src="/assets/index-DdcaFE3Q.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-ECRklfN-.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -5,6 +5,54 @@ from backend.tests.support import BackendTestCase
|
||||
|
||||
|
||||
class ProjectReprocessTests(BackendTestCase):
|
||||
def test_reprocess_done_job_is_not_auto_promoted_to_project(self):
|
||||
from backend import job_manager as jm
|
||||
|
||||
sep_job_id = jm.create_job("separate")
|
||||
project_dir = Path(self._temp_dir.name) / "media" / "projects" / "Reprocess"
|
||||
stems_dir = project_dir / "Stems"
|
||||
stems_dir.mkdir(parents=True, exist_ok=True)
|
||||
source_path = project_dir / "Reprocess.mp3"
|
||||
source_path.write_bytes(b"audio")
|
||||
stem_path = stems_dir / "Reprocess (vocals).mp3"
|
||||
stem_path.write_bytes(b"audio")
|
||||
|
||||
jm.update_job(
|
||||
sep_job_id,
|
||||
status=jm.JobStatus.DONE,
|
||||
files=[
|
||||
{"name": source_path.name, "path": str(source_path), "type": "source"},
|
||||
{"name": stem_path.name, "path": str(stem_path), "type": "stem", "stem": "vocals"},
|
||||
],
|
||||
result={"project_name": "Reprocess", "project_path": str(project_dir), "project_id": "seed"},
|
||||
)
|
||||
project = jm.find_or_create_project("Reprocess", sep_job_id)
|
||||
|
||||
reprocess_job_id = jm.create_job("separate")
|
||||
jm.update_job(
|
||||
reprocess_job_id,
|
||||
status=jm.JobStatus.DONE,
|
||||
files=[{"name": "Reprocess (Instrumental).mp3", "path": str(stem_path), "type": "stem", "stem": "instrumental"}],
|
||||
result={
|
||||
"reprocess": True,
|
||||
"parent_job_id": sep_job_id,
|
||||
"project_name": "Reprocess (Instrumental)",
|
||||
"project_path": str(project_dir / "Stems" / "Reprocessed" / "vocals"),
|
||||
"project_id": None,
|
||||
},
|
||||
)
|
||||
|
||||
response = self.client.get("/api/projects")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
projects = response.json()
|
||||
|
||||
self.assertEqual(len(projects), 1)
|
||||
self.assertEqual(projects[0]["id"], project["id"])
|
||||
self.assertNotIn(
|
||||
reprocess_job_id,
|
||||
[p.get("sep_job_id") for p in projects],
|
||||
)
|
||||
|
||||
def test_reprocess_rejects_unknown_model(self):
|
||||
from backend import job_manager as jm
|
||||
|
||||
|
||||
@@ -0,0 +1,432 @@
|
||||
# StemEngine Karaoke Box — SEK-First Rework (Authoritative)
|
||||
|
||||
> This top section supersedes the older project-direct playback notes below.
|
||||
> StemEngine karaoke should now target **SEK package playback** as the primary flow.
|
||||
|
||||
## Current Status
|
||||
|
||||
All SEK-first phases in this plan are implemented (Phase 1, Phase 2, Phase 3).
|
||||
|
||||
## Remaining Work
|
||||
|
||||
- No open items remain in the SEK-first phase list.
|
||||
- Legacy notes below are historical reference only.
|
||||
|
||||
## Core Shift
|
||||
|
||||
SingUI should load songs from a **user-selected SEK folder** and play `.sek` bundles directly,
|
||||
instead of reading StemEngine project internals at runtime.
|
||||
|
||||
## Execution Phases (SEK-first)
|
||||
|
||||
### Phase 1 — Packaging + Sync Foundation (**implemented 2026-04-06**)
|
||||
|
||||
Delivered:
|
||||
|
||||
- Project-level karaoke packaging config persistence
|
||||
- Video source linking (URL/path)
|
||||
- Sync offset estimation against selected reference track
|
||||
- `.sek` packaging with synchronization metadata in `manifest.json`
|
||||
- Project page **Package** workflow (`Save`, `Sync Offset`, `Package`)
|
||||
- Auto Pipeline step for `.sek` export
|
||||
|
||||
Implemented endpoints:
|
||||
|
||||
- `GET /api/projects/{id}/karaoke-config`
|
||||
- `PATCH /api/projects/{id}/karaoke-config`
|
||||
- `POST /api/projects/{id}/sync-video-offset`
|
||||
- `POST /api/projects/{id}/export-sek`
|
||||
|
||||
Implemented UI areas:
|
||||
|
||||
- `ProjectDetail` → `Karaoke Packaging (.sek)` section
|
||||
- `Settings` / Auto Pipeline → `Export StemEngine .sek Package`
|
||||
|
||||
### Phase 2 — SingUI SEK Folder Library (**implemented 2026-04-06**)
|
||||
|
||||
Delivered:
|
||||
|
||||
- User-set karaoke source mode + SEK folder persisted in app settings
|
||||
- `karaoke_source_mode`: `projects` | `sek-folder`
|
||||
- `karaoke_sek_folder`: folder path
|
||||
- Backend SEK library API:
|
||||
- `GET /api/karaoke-sek/library`
|
||||
- `GET /api/karaoke-sek/packages/{package_id}`
|
||||
- `GET /api/karaoke-sek/packages/{package_id}/asset?path=...`
|
||||
- Folder scan + `manifest.json` parsing for `.sek` packages
|
||||
- SingUI karaoke tab source switch:
|
||||
- Project-linked mode (existing)
|
||||
- SEK Folder mode (new)
|
||||
- Settings → Integrations controls for:
|
||||
- default karaoke source mode
|
||||
- SEK folder path persistence
|
||||
- Karaoke player launch from package payload:
|
||||
- stems from package assets
|
||||
- `.elrc` from package assets
|
||||
- optional video from package assets
|
||||
|
||||
### Phase 3 — SEK-first default runtime (**implemented 2026-04-06**)
|
||||
|
||||
Delivered:
|
||||
|
||||
- Default karaoke source mode switched to `sek-folder`
|
||||
- backend settings defaults now initialize `karaoke_source_mode = sek-folder`
|
||||
- SingUI fallback default also starts in `sek-folder` mode
|
||||
- `projects` mode retained as explicit user-select fallback/debug path
|
||||
|
||||
## Packaging Requirements (Project Pages + Auto Pipeline)
|
||||
|
||||
Each project can be prepared for packaging via a **Karaoke Packaging** panel:
|
||||
|
||||
1. Link a video source (YouTube URL or local video path)
|
||||
2. Choose sync reference track (`source` or any stem)
|
||||
3. Click **Package** — sync offset is computed automatically
|
||||
4. Package writes computed per-track offset into `manifest.json`
|
||||
|
||||
The same `.sek` export is available as an **Auto Pipeline** step.
|
||||
|
||||
### Required manifest data in `.sek`
|
||||
|
||||
`manifest.json` must include synchronization metadata:
|
||||
|
||||
- `meta.synchronization.reference_track`
|
||||
- `meta.synchronization.track_offsets_seconds`
|
||||
- `meta.synchronization.video_source`
|
||||
- `meta.synchronization.last_sync`
|
||||
|
||||
This allows playback clients to apply track-aware timing offsets consistently.
|
||||
|
||||
`manifest.json` must also include a source-inherited `metadata` component:
|
||||
|
||||
- `metadata.title`
|
||||
- `metadata.artist`
|
||||
- `metadata.albumartist`
|
||||
- `metadata.album`
|
||||
- `metadata.source_file`
|
||||
- `metadata.cover_art` (if available), with the cover image packaged as `metadata/cover.*`
|
||||
|
||||
## SingUI Runtime (SEK Folder Mode)
|
||||
|
||||
Add settings for:
|
||||
|
||||
- `source mode`: `projects` | `sek-folder`
|
||||
- `sek folder path`: user-defined filesystem path
|
||||
|
||||
When in `sek-folder` mode:
|
||||
|
||||
1. Scan folder for `.sek`
|
||||
2. Read each `manifest.json`
|
||||
3. Build song list from package metadata
|
||||
4. Launch karaoke player from package assets (`stems`, `.elrc`, optional video)
|
||||
|
||||
No direct dependence on project DB/job layout is required for playback.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- Project pages show a visible **Package** button for `.sek`
|
||||
- User can link video and reference track; offset is auto-computed during packaging
|
||||
- Packaged `.sek` writes that offset into `manifest.json`
|
||||
- Auto Pipeline can export `.sek`
|
||||
- SingUI can read/play `.sek` from user folder without loading projects directly
|
||||
|
||||
---
|
||||
|
||||
# Legacy notes (kept for reference)
|
||||
|
||||
**Source analysis:** `johnpc/karaoke-for-jellyfin` (Next.js 15 + Socket.IO)
|
||||
**Target:** StemEngine SingUI (React + Vite + TanStack Query, port 3001)
|
||||
**Date:** 2025-06
|
||||
|
||||
---
|
||||
|
||||
## What Was Learned From karaoke-for-jellyfin
|
||||
|
||||
### Architecture (3 interfaces)
|
||||
| Route | Role |
|
||||
|---|---|
|
||||
| `/` | Mobile — search Jellyfin library, add songs to queue, reorder |
|
||||
| `/tv` | TV Display — fullscreen lyrics, state machine, transitions |
|
||||
| `/admin` | Admin — host controls panel |
|
||||
|
||||
### TV State Machine
|
||||
```
|
||||
waiting ──► playing ──[song ends]──► applause (15s)
|
||||
▲ │
|
||||
└── [queue empty] ◄──── next-up (15s) ◄─┘
|
||||
│
|
||||
[has next song]──► playing
|
||||
```
|
||||
|
||||
### Key Source Components
|
||||
- **`KaraokeSessionManager`** (singleton) — in-memory session: queue CRUD, playback state, user management, `skipInProgress` / `songTransitionInProgress` mutex locks, auto-advance timer
|
||||
- **`server.js`** — custom Next.js server with Socket.IO; events: `join-session`, `add-song`, `remove-song`, `playback-control`, `skip-song`, `song-ended`, `start-next-song`, `user-heartbeat`; TV auto-joins as host on connect
|
||||
- **`src/types/index.ts`** — `QueueItem`, `KaraokeSession`, `PlaybackState`, `TVDisplayState`, `SongRating`, `TransitionState`, `HostControls`, `SessionSettings`, `ConnectedUser`, full WS event types
|
||||
|
||||
### Type Inventory (relevant subset)
|
||||
|
||||
```ts
|
||||
// Queue
|
||||
interface QueueItem { id, mediaItem, addedBy, addedAt, position, status: 'pending'|'playing'|'completed'|'skipped' }
|
||||
|
||||
// Session
|
||||
interface PlaybackState { isPlaying, currentTime, volume, isMuted, playbackRate, lyricsOffset }
|
||||
interface HostControls { autoAdvance, allowUserSkip, allowUserRemove, maxSongsPerUser, requireApproval }
|
||||
interface SessionSettings { maxUsers, lyricsEnabled, crossfadeEnabled, crossfadeDuration }
|
||||
|
||||
// TV display
|
||||
type TVDisplayState = 'waiting' | 'playing' | 'applause' | 'next-up' | 'transitioning'
|
||||
interface SongRating { grade: string, score: number, message: string } // random, not mic-computed
|
||||
interface TransitionState { displayState, completedSong?, nextSong?, rating?, transitionStartTime? }
|
||||
```
|
||||
|
||||
### Rating System
|
||||
Weighted random grade (B+ most common):
|
||||
```
|
||||
A+ 5% A 15% A- 20% B+ 25% B 20% B- 10% C+ 3% C 1% ... F 0.1%
|
||||
Score range per grade (e.g. A+ → 95–100, B → 75–79)
|
||||
```
|
||||
**Note:** Rating is not computed from mic input — it is purely random.
|
||||
|
||||
### Key Patterns
|
||||
1. **Mutex locks** on queue/skip/transition ops prevent race conditions
|
||||
2. **Immediate removal** of completed/skipped items from queue (not left as `completed`)
|
||||
3. **Deduplication** on reconnect (same user name → old socket removed)
|
||||
4. **TV auto-join** via `socket.handshake.query.client === 'tv'` — no explicit join needed
|
||||
5. **`time-update`** sent periodically from TV (every ~2s) to server — server tracks position but does NOT broadcast back (avoids spam)
|
||||
6. **`lyricsOffset`** in `PlaybackState` — adjustable ±N seconds via playback-control event, broadcast to all clients
|
||||
7. **Heartbeat** + 5-min stale threshold, cleanup every 2 min
|
||||
|
||||
---
|
||||
|
||||
## StemEngine Mapping
|
||||
|
||||
| karaoke-for-jellyfin | StemEngine equivalent |
|
||||
|---|---|
|
||||
| `MediaItem` (Jellyfin song) | `Project` (StemEngine project with stems + LRC) |
|
||||
| `streamUrl` | stem audio URLs via `downloadUrl(jobId, name)` |
|
||||
| `lyricsPath` | LRC/ELRC file from `detail.lrc_jobs` |
|
||||
| `WaitingScreen` | New `KaraokeWaitingScreen` |
|
||||
| `LyricsDisplay` | Existing `KaraokePerformanceMode` |
|
||||
| `RatingAnimation` | New `KaraokeRatingOverlay` |
|
||||
| `NextSongSplash` | New `KaraokeNextUpSplash` |
|
||||
| `ApplausePlayer` | New `KaraokeApplausePlayer` |
|
||||
| `HostControls` overlay | Already in `KaraokePerformanceMode` HUD |
|
||||
| `QueuePreview` overlay | New `KaraokeQueuePreview` |
|
||||
| `QRCode` | New `KaraokeQRCode` |
|
||||
| `KaraokeSessionManager` | Phase 2: `KaraokeSessionManager` or backend WS |
|
||||
| `server.js` Socket.IO | Phase 2: new backend `/ws/karaoke` endpoint |
|
||||
| Mobile `/` search + add | Phase 2: new `/karaoke/join` route |
|
||||
|
||||
---
|
||||
|
||||
## Implementation Phases
|
||||
|
||||
### Phase 1 — Local Queue + Auto-advance *(single-device, no backend changes)*
|
||||
|
||||
**Complexity:** Low
|
||||
**Value:** High — makes it feel like a karaoke box immediately
|
||||
|
||||
#### 1a. `KaraokeQueueContext`
|
||||
New file: `src/context/KaraokeQueueContext.tsx`
|
||||
|
||||
```ts
|
||||
interface KaraokeQueueItem {
|
||||
projectId: string
|
||||
title: string
|
||||
artist?: string
|
||||
albumArt?: string
|
||||
}
|
||||
|
||||
interface KaraokeQueueState {
|
||||
queue: KaraokeQueueItem[]
|
||||
currentIndex: number // -1 = nothing playing
|
||||
}
|
||||
|
||||
// Actions
|
||||
addToQueue(item)
|
||||
removeFromQueue(projectId)
|
||||
moveItem(from, to)
|
||||
advanceQueue() // currentIndex++, or wraps/stops
|
||||
clearQueue()
|
||||
setCurrentIndex(n)
|
||||
```
|
||||
|
||||
- Persisted to `localStorage` (`karaoke-queue-v1`) with debounce
|
||||
- Provided at App root level
|
||||
|
||||
#### 1b. Sing.tsx — Queue sidebar
|
||||
- Add "Add to Queue" button on each karaoke row that is `ready` + has linked project
|
||||
- New right panel in karaoke tab: drag-reorderable queue list with remove buttons
|
||||
- "Sing" button now **either** starts a standalone song (no queue) **or** plays from queue position
|
||||
|
||||
#### 1c. Karaoke.tsx — Queue-aware player
|
||||
- On mount: if entering from queue context (`location.state.fromQueue === true`), read `currentQueueItem` instead of explicit `projectId`
|
||||
- When song ends (user hits exit / `onExit`): if more songs in queue → call `advanceQueue()` then navigate to next song automatically
|
||||
- Pass "up next" info to `KaraokePerformanceMode` for HUD display
|
||||
|
||||
#### 1d. `KaraokePerformanceMode` — "Up next" HUD element
|
||||
- Small persistent chip in bottom-left corner: `⏭ Song Title – Artist`
|
||||
- Disappears when queue exhausted
|
||||
|
||||
---
|
||||
|
||||
### Phase 2 — Post-song Transitions (TV State Machine) *(pure client-side)*
|
||||
|
||||
**Complexity:** Medium
|
||||
**Value:** High — the biggest visual upgrade
|
||||
|
||||
#### New components
|
||||
|
||||
**`src/components/karaoke/KaraokeRatingOverlay.tsx`**
|
||||
- Props: `song: { title, artist }`, `rating: SongRating`, `onComplete: () => void`, `duration?: number`
|
||||
- Full-screen overlay on top of player
|
||||
- Animated grade reveal: big letter grade (A+..F) + score bar + message
|
||||
- Uses same weighted random generator as karaoke-for-jellyfin
|
||||
- Auto-dismisses after `duration` ms (default 15 000)
|
||||
|
||||
**`src/components/karaoke/KaraokeNextUpSplash.tsx`**
|
||||
- Props: `nextSong: KaraokeQueueItem`, `onComplete: () => void`, `duration?: number`
|
||||
- Full-screen "Next Up" card: album art placeholder + title + artist + countdown ring
|
||||
- Auto-dismisses after `duration` ms (default 15 000)
|
||||
|
||||
**`src/components/karaoke/KaraokeApplausePlayer.tsx`**
|
||||
- Renders `<audio autoPlay>` with embedded applause SFX (base64 or `/public/sfx/applause.mp3`)
|
||||
- Volume ~60%
|
||||
|
||||
**`src/components/karaoke/KaraokeWaitingScreen.tsx`**
|
||||
- Full-screen waiting state: animated music note, session name, "Scan QR to add songs" prompt
|
||||
- Shows first 3 queued songs as preview
|
||||
|
||||
#### Karaoke.tsx state machine
|
||||
|
||||
```ts
|
||||
type KaraokeDisplayState = 'loading' | 'error' | 'playing' | 'applause' | 'next-up' | 'waiting'
|
||||
|
||||
// On song ended (KaraokePerformanceMode fires onSongEnded callback):
|
||||
// 1. Generate random rating
|
||||
// 2. Set state → 'applause'
|
||||
// 3. After RATING_DURATION → set state → 'next-up' (or 'waiting' if no next)
|
||||
// 4. After NEXT_UP_DURATION → advance queue + navigate to next project
|
||||
```
|
||||
|
||||
#### Rating generator
|
||||
New file: `src/utils/karaokeRating.ts`
|
||||
Direct port of `generateRandomRating()` from karaoke-for-jellyfin.
|
||||
|
||||
---
|
||||
|
||||
### Phase 3 — TV Display Route *(dedicated fullscreen display)*
|
||||
|
||||
**Complexity:** Low
|
||||
**Value:** Medium — makes it projector-ready
|
||||
|
||||
#### New route: `/karaoke/tv`
|
||||
- New constant `KARAOKE_TV_ROUTE = '/karaoke/tv'` in `routes.ts`
|
||||
- New page: `src/pages/KaraokeTV.tsx`
|
||||
- Added to `App.tsx` as lazy route **without** Sidebar wrapper (fullscreen only)
|
||||
|
||||
#### Features
|
||||
- Auto-connects to local queue context (no explicit navigation state needed)
|
||||
- Full state machine: waiting → playing → applause → next-up → playing
|
||||
- Keyboard shortcuts:
|
||||
- `Space` — play/pause (or skip current transition phase)
|
||||
- `S` — skip song (or skip transition)
|
||||
- `H` — toggle host controls overlay
|
||||
- `Q` — toggle queue preview overlay
|
||||
- `Esc` — close any overlay
|
||||
- Auto-hide controls overlay after 10s inactivity (`CONTROLS_AUTO_HIDE_DELAY`)
|
||||
- Connection status chip (local-only: always "Connected")
|
||||
- **QR code** (top-right corner): shows `window.location.origin` encoded as QR — guests scan to open SingUI on mobile
|
||||
|
||||
#### QR code implementation
|
||||
- Use `qrcode.react` (already in many React stacks) or `qrcode` npm package
|
||||
- `<KaraokeQRCode url={origin} size={80} />`
|
||||
|
||||
---
|
||||
|
||||
### Phase 4 — Multi-device WebSocket Session *(backend required)*
|
||||
|
||||
**Complexity:** High
|
||||
**Value:** High for party use; overkill for single-user
|
||||
|
||||
This phase requires backend changes and is designed to mirror karaoke-for-jellyfin's Socket.IO architecture adapted to StemEngine's stack.
|
||||
|
||||
#### Backend changes
|
||||
- Add `socket.io` (or `python-socketio` if Python backend) to StemEngine backend
|
||||
- New WS endpoint at `/ws/karaoke`
|
||||
- Implement `KaraokeSessionManager` pattern (single in-memory session per server)
|
||||
- Events to implement:
|
||||
- `join-session { sessionId, userName }` → broadcast `session-joined`, `user-joined`
|
||||
- `add-song { projectId, userName }` → validates project ready → broadcast `queue-updated`, `song-started` (if first)
|
||||
- `remove-song { queueItemId }` → broadcast `queue-updated`
|
||||
- `reorder-queue { queueItemId, newPosition }` (host only) → broadcast `queue-updated`
|
||||
- `playback-control { action, value? }` → broadcast `playback-state-changed`
|
||||
- `skip-song` → broadcast `song-ended`, `queue-updated`, `playback-state-changed`
|
||||
- `song-ended` (from TV client) → generate rating → broadcast `song-ended { song, rating, nextSong? }`
|
||||
- `start-next-song` (from TV after transitions) → broadcast `song-started`, `queue-updated`
|
||||
- `user-heartbeat` → update `lastSeen`
|
||||
|
||||
#### Frontend changes
|
||||
- New hook: `src/hooks/useKaraokeSession.ts`
|
||||
- Wraps `socket.io-client` connection
|
||||
- Returns: `{ isConnected, joinSession, addSong, removeSong, reorderQueue, playbackControl, skipSong, songEnded, startNextSong, queue, currentSong, playbackState, session }`
|
||||
- KaraokeTV.tsx reads from `useKaraokeSession` instead of local `KaraokeQueueContext`
|
||||
- New route `/karaoke/join` — mobile-friendly "join session" page
|
||||
- Enter user name → join session → search songs → add to queue → view queue
|
||||
|
||||
#### Session model (StemEngine-specific)
|
||||
- `MediaItem` replaced by `{ projectId, title, artist, albumArt? }` (project must be `done`)
|
||||
- `streamUrl` not needed — TV resolves it from `projectId` via `getProjectDetail()`
|
||||
- TV is host by default (auto-joins on page load)
|
||||
- Mobile users join with name; first non-TV user becomes host if TV disconnects
|
||||
|
||||
---
|
||||
|
||||
## Implementation Order (Recommended)
|
||||
|
||||
```
|
||||
Phase 1a KaraokeQueueContext + localStorage ~2h ← start here
|
||||
Phase 1b Sing.tsx queue sidebar + Add button ~1h
|
||||
Phase 1c Karaoke.tsx auto-advance on exit ~30m
|
||||
Phase 2 Rating + NextUp + Applause overlays ~3h ← biggest visual win
|
||||
Phase 1d KaraokePerformanceMode "up next" chip ~30m
|
||||
Phase 3 /karaoke/tv route + keyboard + QR ~2h
|
||||
Phase 4 WebSocket multi-device session ~1d ← defer until needed
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## File Checklist
|
||||
|
||||
### New files
|
||||
- [ ] `src/context/KaraokeQueueContext.tsx`
|
||||
- [ ] `src/hooks/useKaraokeQueue.ts`
|
||||
- [ ] `src/utils/karaokeRating.ts`
|
||||
- [ ] `src/components/karaoke/KaraokeRatingOverlay.tsx`
|
||||
- [ ] `src/components/karaoke/KaraokeNextUpSplash.tsx`
|
||||
- [ ] `src/components/karaoke/KaraokeApplausePlayer.tsx`
|
||||
- [ ] `src/components/karaoke/KaraokeWaitingScreen.tsx`
|
||||
- [ ] `src/components/karaoke/KaraokeQueuePreview.tsx`
|
||||
- [ ] `src/components/karaoke/KaraokeQRCode.tsx`
|
||||
- [ ] `src/pages/KaraokeTV.tsx`
|
||||
- [ ] `public/sfx/applause.mp3` *(short 5–10s clip)*
|
||||
|
||||
### Modified files
|
||||
- [ ] `src/routes.ts` — add `KARAOKE_TV_ROUTE`
|
||||
- [ ] `src/App.tsx` — add `/karaoke/tv` route (fullscreen, no sidebar)
|
||||
- [ ] `src/pages/Karaoke.tsx` — queue-aware + state machine
|
||||
- [ ] `src/pages/Sing.tsx` — queue sidebar + Add to Queue button
|
||||
- [ ] `src/components/KaraokePerformanceMode.tsx` — `onSongEnded` callback + "up next" chip
|
||||
|
||||
---
|
||||
|
||||
## Constants (mirrored from karaoke-for-jellyfin)
|
||||
|
||||
```ts
|
||||
// src/utils/karaokeConstants.ts
|
||||
export const RATING_ANIMATION_DURATION = 15_000 // ms
|
||||
export const NEXT_SONG_DURATION = 15_000 // ms
|
||||
export const CONTROLS_AUTO_HIDE_DELAY = 10_000 // ms
|
||||
export const AUTOPLAY_DELAY = 500 // ms
|
||||
export const TIME_UPDATE_INTERVAL = 2_000 // ms (WS only)
|
||||
```
|
||||
@@ -0,0 +1,195 @@
|
||||
# SingUI playback flow draft (Nightingale-inspired)
|
||||
|
||||
Status: Draft (2026-04-06)
|
||||
|
||||
## Goal
|
||||
|
||||
Adopt Nightingale’s effective karaoke lifecycle in SingUI:
|
||||
|
||||
1. prepare assets asynchronously,
|
||||
2. gate playback on readiness,
|
||||
3. run synchronized per-stem playback with `leading` muted by default,
|
||||
4. drive all overlays from one timeline bus.
|
||||
|
||||
---
|
||||
|
||||
## Reference pattern from Nightingale
|
||||
|
||||
Observed architecture in `rzru/nightingale`:
|
||||
|
||||
- **Analysis phase**
|
||||
- Separation (UVR Karaoke or Demucs)
|
||||
- Lyrics source bootstrap (LRCLIB when available)
|
||||
- WhisperX transcribe or forced alignment
|
||||
- Cached by file hash
|
||||
- **Playback phase**
|
||||
- Readiness event (`stems-ready`) before starting player
|
||||
- Multiple synchronized stem paths loaded into one playback session
|
||||
- Shared clock for lyrics/HUD/background/pitch scoring
|
||||
|
||||
This pattern maps directly to SingUI’s needs and avoids race conditions between processing and playback.
|
||||
|
||||
---
|
||||
|
||||
## Proposed SingUI flow
|
||||
|
||||
### A) Prepare job (background)
|
||||
|
||||
For each selected track (`media_id`):
|
||||
|
||||
1. Resolve source media path (already imported or import first).
|
||||
2. Run selected StemEngine separator preset.
|
||||
3. Run lyric stage:
|
||||
- align existing lyrics when available, else
|
||||
- AI transcribe (`whisperx`/`parakeet`) and write timed output.
|
||||
4. Produce normalized karaoke playback assets.
|
||||
5. Persist status and output manifest.
|
||||
|
||||
Target states:
|
||||
|
||||
- `queued` -> `running` -> `ready`
|
||||
- `failed` (with retriable error)
|
||||
|
||||
### B) Asset contract (per prepared track)
|
||||
|
||||
`karaoke_assets.json` should be the single source of truth consumed by SingUI:
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 1,
|
||||
"media_id": "<subsonic media id>",
|
||||
"project_id": "<stemengine project id>",
|
||||
"status": "ready",
|
||||
"audio": {
|
||||
"stems": {
|
||||
"instrumental": {
|
||||
"path": "<path or URL>",
|
||||
"default_gain": 1.0,
|
||||
"default_muted": false
|
||||
},
|
||||
"leading": {
|
||||
"path": "<path or URL>",
|
||||
"default_gain": 0.0,
|
||||
"default_muted": true
|
||||
},
|
||||
"backing": {
|
||||
"path": "<path or URL>",
|
||||
"default_gain": 1.0,
|
||||
"default_muted": false
|
||||
}
|
||||
},
|
||||
"duration_sec": 214.33
|
||||
},
|
||||
"lyrics": {
|
||||
"transcript_json": "<path or URL>",
|
||||
"elrc": "<path or URL>",
|
||||
"ass": "<path or URL>",
|
||||
"source": "align|transcribe"
|
||||
},
|
||||
"timing": {
|
||||
"intro_start_sec": 0.0,
|
||||
"lyric_start_sec": 12.8,
|
||||
"outro_start_sec": 206.2
|
||||
},
|
||||
"updated_at": "2026-04-06T00:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
### C) Playback gate
|
||||
|
||||
Before opening karaoke playback route:
|
||||
|
||||
1. Query `prepare status` by `media_id`.
|
||||
2. If not `ready`, show progress panel and subscribe/poll for completion.
|
||||
3. Enter playback only when manifest resolves to `ready`.
|
||||
|
||||
### D) Playback engine
|
||||
|
||||
Use synchronized per-stem audio streams, all bound to the same transport.
|
||||
|
||||
Minimum expected behavior:
|
||||
|
||||
- `instrumental`: always on
|
||||
- `leading`: loaded but **muted by default**
|
||||
- `backing`: optional, enabled when available
|
||||
|
||||
This keeps the learning-mode behavior from Nightingale, but adapts it to
|
||||
StemEngine’s richer stem model instead of collapsing everything into a single
|
||||
guide-vocal track.
|
||||
|
||||
Recommended controls:
|
||||
|
||||
- `Leading` mute/unmute toggle
|
||||
- `Leading` gain slider
|
||||
- optional per-stem toggles for `backing`, `drums`, `bass`, etc. when present
|
||||
|
||||
Single timeline bus (`currentTime`) fans out to:
|
||||
|
||||
- lyrics highlighter,
|
||||
- intro/outro skip controls,
|
||||
- future scoring/mic overlays,
|
||||
- animated backgrounds.
|
||||
|
||||
### E) Cache policy
|
||||
|
||||
Rebuild assets only when one of these changes:
|
||||
|
||||
- source media checksum/mtime,
|
||||
- selected separator preset/model,
|
||||
- lyric mode/model,
|
||||
- explicit user “rebuild” request.
|
||||
|
||||
---
|
||||
|
||||
## API sketch for SingUI
|
||||
|
||||
### Processing
|
||||
|
||||
- `POST /api/karaoke/process` (already used)
|
||||
- `POST /api/karaoke/process/album` (already used)
|
||||
- `GET /api/karaoke/process/status?media_id=...` (already used)
|
||||
|
||||
### New/extended
|
||||
|
||||
- `GET /api/karaoke/assets/{media_id}`
|
||||
- returns `karaoke_assets.json` shape
|
||||
- `POST /api/karaoke/assets/{media_id}/rebuild`
|
||||
- forces cache invalidation + re-prepare
|
||||
|
||||
---
|
||||
|
||||
## UX mapping in SingUI
|
||||
|
||||
Library/album/track rows:
|
||||
|
||||
- `Process` / `Process Album`
|
||||
- state badges: `Queued` / `Running` / `Ready` / `Retry`
|
||||
- `Sing` button only enabled when `Ready`
|
||||
|
||||
Playback page:
|
||||
|
||||
- leading-stem toggle (default off)
|
||||
- leading-stem gain slider
|
||||
- optional additional per-stem toggles for available stems
|
||||
- synchronized lyric surface using transcript word timestamps
|
||||
|
||||
---
|
||||
|
||||
## Incremental implementation plan
|
||||
|
||||
1. **Contract-first**: add `assets` endpoint + manifest generation in backend.
|
||||
2. **Gate**: enforce ready-state before entering karaoke playback route.
|
||||
3. **Dual-stream player**: wire instrumental + guide-vocal gain control.
|
||||
4. **Timeline fanout**: unify lyric/HUD/background time source.
|
||||
5. **Observability**: add progress/error details and retry path per stage.
|
||||
|
||||
---
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
1. A track cannot enter karaoke playback until assets are `ready`.
|
||||
2. Playback uses instrumental + optional guide-vocal stream with stable sync.
|
||||
2. Playback uses synchronized per-stem audio, with `leading` muted by default.
|
||||
3. Lyrics timing source is deterministic (`transcript_json`/ELRC) and bound to one clock.
|
||||
4. Re-processing correctly invalidates outdated assets and produces a new manifest.
|
||||
5. Album batch processing updates per-track status without page refresh.
|
||||
@@ -444,12 +444,63 @@ JSON body supports engine, model, alignment options, diarization, and existing l
|
||||
### POST /api/projects/{project_id}/reprocess
|
||||
Reprocess a single stem with a selected model.
|
||||
|
||||
Behavior note: reprocess jobs write outputs under the existing project's reprocessed stems folder and are **not** auto-promoted into standalone projects.
|
||||
|
||||
### POST /api/projects/{project_id}/rename-stem
|
||||
Rename tracked stem file.
|
||||
|
||||
### POST /api/projects/{project_id}/rescan-stems
|
||||
Rescan stem directory and register untracked files.
|
||||
|
||||
### GET /api/projects/{project_id}/karaoke-config
|
||||
Get persisted karaoke packaging configuration for the project.
|
||||
|
||||
### PATCH /api/projects/{project_id}/karaoke-config
|
||||
Update karaoke packaging configuration.
|
||||
|
||||
Common patch keys:
|
||||
- `video_source`
|
||||
- `include_video`
|
||||
- `sync_reference_track`
|
||||
- `offset_seconds`
|
||||
|
||||
### POST /api/projects/{project_id}/sync-video-offset
|
||||
Estimate and persist sync offset between linked video and selected reference track.
|
||||
|
||||
Example body:
|
||||
|
||||
```json
|
||||
{
|
||||
"video_source": "https://youtube.com/watch?v=...",
|
||||
"reference_track": "source"
|
||||
}
|
||||
```
|
||||
|
||||
### POST /api/projects/{project_id}/export-sek
|
||||
Build `.sek` package including stems + `.elrc` + optional video and `manifest.json` sync metadata.
|
||||
|
||||
`manifest.json` also includes a `metadata` component inherited from the project source file:
|
||||
- `metadata.title`
|
||||
- `metadata.artist`
|
||||
- `metadata.albumartist`
|
||||
- `metadata.album`
|
||||
- `metadata.source_file`
|
||||
- `metadata.cover_art` (when available, references packaged `metadata/cover.*`)
|
||||
|
||||
Supports automatic sync on package:
|
||||
|
||||
- `video_source` (optional override)
|
||||
- `sync_reference_track` (optional override)
|
||||
- `auto_sync` (default `true`)
|
||||
|
||||
When `auto_sync=true` and a video source is available, offset estimation runs automatically and is written to `meta.synchronization.track_offsets_seconds`.
|
||||
|
||||
If no video is included in the package, `manifest.json` sets `meta.has_video=false` and includes a `meta.video_note` message describing why video is missing.
|
||||
|
||||
Output location behavior:
|
||||
- default: `<project>/Exports/StemEngineKaraoke`
|
||||
- optional centralized folder: set `STEMENGINE_KARAOKE_EXPORT_DIR` (typically via docker compose, with a mounted host path)
|
||||
|
||||
### Maintenance (admin-protected)
|
||||
- `GET /api/projects/cleanup/verify`
|
||||
- `POST /api/projects/cleanup/write-metadata`
|
||||
@@ -539,6 +590,13 @@ Partial update. Common keys include:
|
||||
- `auto_model`
|
||||
- `auto_format`
|
||||
- `auto_presets`
|
||||
- `karaoke_source_mode` (`projects` | `sek-folder`)
|
||||
- `karaoke_sek_folder` (absolute or server-resolved folder path)
|
||||
|
||||
Karaoke defaults:
|
||||
|
||||
- `karaoke_source_mode` now defaults to `sek-folder` (SEK-first runtime)
|
||||
- `projects` mode remains available as an explicit fallback/debug path
|
||||
|
||||
Example patch:
|
||||
|
||||
@@ -555,6 +613,34 @@ Delete stored token; env-var fallback can still apply.
|
||||
|
||||
---
|
||||
|
||||
## Karaoke SEK library
|
||||
|
||||
### GET /api/karaoke-sek/library
|
||||
List `.sek` packages from configured folder or optional query override.
|
||||
|
||||
Query params:
|
||||
- `folder` (optional): overrides stored `karaoke_sek_folder`
|
||||
|
||||
Response includes:
|
||||
- `folder`
|
||||
- `count`
|
||||
- `packages[]` with `id`, `filename`, `title`, `valid`, `stem_count`, `has_video`, `warnings`
|
||||
|
||||
### GET /api/karaoke-sek/packages/{package_id}
|
||||
Read one package `manifest.json` payload.
|
||||
|
||||
Query params:
|
||||
- `folder` (optional)
|
||||
|
||||
### GET /api/karaoke-sek/packages/{package_id}/asset
|
||||
Stream one inner package asset (stem/lyrics/video) by package-relative path.
|
||||
|
||||
Query params:
|
||||
- `path` (required), example: `stems/vocals.mp3`
|
||||
- `folder` (optional)
|
||||
|
||||
---
|
||||
|
||||
## Subsonic integration
|
||||
|
||||
### GET /api/subsonic/config
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+697
@@ -939,3 +939,700 @@ See Section 21 for Phase B details. Priority:
|
||||
4. Wire sidebar Sing button to karaoke player service URL (separate port)
|
||||
5. Add now-playing footer data binding to playback context
|
||||
- [ ] Add regression tests for layout, action order, and performance mode UI contract
|
||||
|
||||
---
|
||||
|
||||
## 23) 2026-04-04 discrepancy review + action plan (Sing settings + Subsonic browsing)
|
||||
|
||||
### Review findings
|
||||
|
||||
1. **Sing settings UX was not discrete/closable**
|
||||
- In library/sing routes, Settings previously navigated to a dedicated full-page route.
|
||||
- This interrupted browsing flow and did not behave like an overlay panel.
|
||||
|
||||
2. **Subsonic browsing looked non-functional because pages were placeholder-only**
|
||||
- `Tracks`, `Albums`, and `Artists` pages were rendering static sample arrays.
|
||||
- No runtime fetch from `/api/subsonic/search` was wired in those pages.
|
||||
- `Playlists` had no backend browse endpoint integration and also showed placeholders.
|
||||
|
||||
3. **Backend/API capability gap for playlists**
|
||||
- Current client supports Subsonic config + search/import endpoints.
|
||||
- Dedicated playlist browsing endpoint contract is still not present in this frontend slice.
|
||||
|
||||
### Implemented corrections (this update)
|
||||
|
||||
1. **Discrete closable settings panel for library/sing flow**
|
||||
- Added right-side settings overlay for library routes.
|
||||
- Overlay supports close via:
|
||||
- close button,
|
||||
- backdrop click,
|
||||
- `Esc` key.
|
||||
- Kept direct `/settings` route for compatibility.
|
||||
|
||||
2. **Subsonic browsing wiring for core library pages**
|
||||
- Added `useSubsonicLibrary()` hook:
|
||||
- checks `/api/subsonic/config`,
|
||||
- fetches songs via `/api/subsonic/search`,
|
||||
- exposes loading/config/error states.
|
||||
- `Tracks` now renders real Subsonic song results.
|
||||
- `Albums` now derives album cards from fetched Subsonic songs.
|
||||
- `Artists` now derives artist cards/stats from fetched Subsonic songs.
|
||||
- Added explicit configuration/error banners when Subsonic is unavailable.
|
||||
|
||||
3. **Playlist status surfaced clearly**
|
||||
- `Playlists` page now explicitly communicates that backend playlist browsing wiring is pending.
|
||||
|
||||
### Next execution plan
|
||||
|
||||
1. **Playlist browse parity**
|
||||
- Add backend route + client method for playlist listing/detail.
|
||||
- Replace placeholder playlist cards with real data.
|
||||
|
||||
2. **Queue/playback integration**
|
||||
- Wire track/album actions to queue context.
|
||||
- Connect now-playing footer controls to active audio engine.
|
||||
|
||||
3. **Convert action statefulness**
|
||||
- Hook track/album convert buttons to processing API.
|
||||
- Surface `queued/running/ready/failed` states inline.
|
||||
|
||||
4. **Validation and regression coverage**
|
||||
- Add E2E checks for:
|
||||
- settings overlay open/close behavior,
|
||||
- Subsonic configured/unconfigured states,
|
||||
- library browse rendering from live API data.
|
||||
|
||||
---
|
||||
|
||||
## 24) 2026-04-04 implementation update — Sing interface functional parity slice
|
||||
|
||||
Implemented in the current interface:
|
||||
|
||||
1. **Sing page now supports dual browse modes**
|
||||
- Added mode toggle:
|
||||
- `Karaoke Projects` (StemEngine project launcher)
|
||||
- `Subsonic Library` (song browsing inside Sing route)
|
||||
- File: `frontend/src/pages/Sing.tsx`
|
||||
|
||||
2. **Subsonic browse now works in Sing without backend wildcard dependency**
|
||||
- Updated library hook query behavior to use wildcard search input (`*`) for browse mode.
|
||||
- File: `frontend/src/hooks/useSubsonicLibrary.ts`
|
||||
|
||||
3. **Convert status is wired in Sing Subsonic mode**
|
||||
- Per-song convert action now reflects runtime status:
|
||||
- `queued`
|
||||
- `running`
|
||||
- `ready`
|
||||
- `failed` (retry action)
|
||||
- Reuses existing conversion orchestration hook.
|
||||
- File: `frontend/src/hooks/useConvertStatus.ts`
|
||||
|
||||
### Scope coverage status (this slice)
|
||||
|
||||
- Sing route hosts both project browsing and Subsonic song browsing: **done**
|
||||
- In-context conversion actions from Sing library view: **done**
|
||||
- Project launch path from Sing to karaoke performance route: **done**
|
||||
|
||||
### Remaining follow-up
|
||||
|
||||
- Add detail views (album/track) with convert button placement contract.
|
||||
- Add E2E coverage for Sing dual-mode behavior and convert-state transitions.
|
||||
|
||||
---
|
||||
|
||||
## 25) 2026-04-04 implementation update — Sing as standard player + karaoke hub
|
||||
|
||||
Implemented an expanded Sing interface so it behaves like a standard music player while retaining karaoke workflows.
|
||||
|
||||
### Implemented in `frontend/src/pages/Sing.tsx`
|
||||
|
||||
1. **Standard player-style navigation inside Sing**
|
||||
- Added in-page mode tabs:
|
||||
- `Home`
|
||||
- `Tracks`
|
||||
- `Albums`
|
||||
- `Artists`
|
||||
- `Playlists`
|
||||
- `Karaoke`
|
||||
|
||||
2. **Unified browse/search experience**
|
||||
- Search input now adapts placeholder/filtering by active mode.
|
||||
- Home mode exposes top-level library/karaoke summary cards and featured lists.
|
||||
|
||||
3. **Library browsing with karaoke actions**
|
||||
- Tracks mode shows Subsonic songs with direct convert action.
|
||||
- Albums mode shows grouped albums with batch convert action and aggregate status.
|
||||
- Artists mode shows artist cards with album/song counts.
|
||||
- Playlists mode displays Subsonic playlists.
|
||||
- Karaoke mode remains project launcher to full-screen karaoke route.
|
||||
|
||||
4. **Status-driven conversion UX retained**
|
||||
- Convert labels continue to reflect runtime state:
|
||||
- `Queued`
|
||||
- `Running`
|
||||
- `Ready`
|
||||
- `Retry`
|
||||
|
||||
5. **Operational resilience states**
|
||||
- Added/kept explicit config, loading, and error surfaces for:
|
||||
- Subsonic connectivity,
|
||||
- playlist fetch,
|
||||
- karaoke project fetch.
|
||||
|
||||
### Supporting hook adjustment
|
||||
|
||||
- `frontend/src/hooks/useSubsonicLibrary.ts`
|
||||
- Uses wildcard query (`q='*'`) for browse-like loading behavior.
|
||||
|
||||
### Validation
|
||||
|
||||
- `cd frontend && npm run build` → pass
|
||||
|
||||
---
|
||||
|
||||
## 26) 2026-04-05 deployment alignment update — WebUI / API / SingUI ports
|
||||
|
||||
Applied runtime alignment updates in compose/backend to match the intended split-service topology.
|
||||
|
||||
### Required topology (now enforced)
|
||||
|
||||
1. **WebUI**
|
||||
- Host: `5174`
|
||||
- Container: `5173`
|
||||
- Mapping: `5174:5173`
|
||||
|
||||
2. **Backend API**
|
||||
- Host/Container: `8000`
|
||||
- Mapping: `8000:8000`
|
||||
- Legacy backend-served WebUI behavior disabled by default.
|
||||
|
||||
3. **SingUI**
|
||||
- Host: `3001`
|
||||
- Container: `5173`
|
||||
- Mapping: `3001:5173`
|
||||
|
||||
### Implementation details
|
||||
|
||||
- `stemengine.yml`
|
||||
- Added explicit backend env guard:
|
||||
- `BACKEND_SERVE_LEGACY_WEBUI=${BACKEND_SERVE_LEGACY_WEBUI:-false}`
|
||||
- Clarified canonical port mapping comments for WebUI and SingUI services.
|
||||
|
||||
- `backend/main.py`
|
||||
- Legacy static WebUI mount is now gated behind:
|
||||
- `BACKEND_SERVE_LEGACY_WEBUI=true`
|
||||
- Default mode is API-only backend + separate frontend services.
|
||||
|
||||
### Validation
|
||||
|
||||
- `python3 -m py_compile backend/main.py` → pass
|
||||
- `docker compose -f stemengine.yml config` → pass
|
||||
|
||||
---
|
||||
|
||||
## 27) 2026-04-05 final routing split — 5174 serves legacy StemEngine WebUI
|
||||
|
||||
Confirmed and documented final UI service ownership:
|
||||
|
||||
1. **Port 5174 (`stemengine-webui`)**
|
||||
- Serves the **legacy StemEngine management UI** (Separator/Transcriber/Pipeline/LRC workflow).
|
||||
- Source is pinned to: `x/StemEngine-0.9alpha/frontend`.
|
||||
|
||||
2. **Port 3001 (`stemengine-sing`)**
|
||||
- Serves the **new Feishin-style SingUI** (library browse + karaoke mode).
|
||||
- Source remains: `appdata/stemengine/frontend`.
|
||||
|
||||
3. **Port 8000 (`stemengine`)**
|
||||
- API-only backend.
|
||||
- Legacy backend static serving remains opt-in via `BACKEND_SERVE_LEGACY_WEBUI=true`.
|
||||
|
||||
### Implementation details
|
||||
|
||||
- `stemengine.yml`
|
||||
- Rewired `stemengine-webui` build context to `x/StemEngine-0.9alpha/frontend`.
|
||||
- Added dedicated volume `stemengine-legacy-webui-node-modules` to isolate legacy dependencies.
|
||||
- Kept `stemengine-sing` bound to current frontend service on `3001:5173`.
|
||||
|
||||
- `x/StemEngine-0.9alpha/frontend/Dockerfile.webui.dev`
|
||||
- Added dev container definition for legacy WebUI (Vite on port `5173`).
|
||||
|
||||
- `x/StemEngine-0.9alpha/frontend/vite.config.ts`
|
||||
- Set Docker-friendly dev host (`0.0.0.0`).
|
||||
- Updated `/api` proxy target to backend service (`http://stemengine:8000`) via `VITE_API_PROXY_TARGET`.
|
||||
|
||||
### Runtime verification
|
||||
|
||||
- `http://127.0.0.1:5174/` → `200` (legacy management WebUI)
|
||||
- `http://127.0.0.1:3001/` → `200` (new SingUI)
|
||||
|
||||
---
|
||||
|
||||
## 28) 2026-04-05 correction — 5174 restored to current WebUI (as-of-yesterday)
|
||||
|
||||
This supersedes section 27.
|
||||
|
||||
Requested correction:
|
||||
- Frontend WebUI on `5174` must remain the **current WebUI state** (the latest
|
||||
appdata frontend), not the legacy `x/StemEngine-0.9alpha` UI.
|
||||
|
||||
Applied fix:
|
||||
|
||||
- `stemengine.yml`
|
||||
- `stemengine-webui` restored to current frontend source:
|
||||
- build context: `${SEFOLDER}/frontend`
|
||||
- image: `stemengine-webui:latest`
|
||||
- volume: `${SEFOLDER}/frontend:/app/frontend`
|
||||
- volume: `stemengine-webui-node-modules:/app/frontend/node_modules`
|
||||
- Removed legacy-only volume wiring (`stemengine-legacy-webui-node-modules`).
|
||||
- `stemengine-sing` remains on `3001:5173` using the same current frontend.
|
||||
|
||||
Resulting topology:
|
||||
|
||||
1. **WebUI (current)**: `5174:5173`
|
||||
2. **Backend API**: `8000:8000` (API-only by default)
|
||||
3. **SingUI endpoint**: `3001:5173`
|
||||
|
||||
Validation:
|
||||
- Compose config validates after correction.
|
||||
|
||||
---
|
||||
|
||||
## 29) 2026-04-05 correction — restore StemEngine sidebar workflow shell (Subsonic + YT-DL + Projects)
|
||||
|
||||
Follow-up correction applied because `5174` was still rendering the music-library
|
||||
navigation shell rather than the expected StemEngine workflow shell.
|
||||
|
||||
Expected WebUI behavior (restored):
|
||||
|
||||
- Sidebar includes:
|
||||
- **Subsonic import/search panel**
|
||||
- **YT-DL import panel**
|
||||
- **Project list/search panel**
|
||||
- Main content uses StemEngine workflow pages (`Separator`, `ProjectDetail`, `Settings`),
|
||||
not the library-first Albums/Tracks/Artists/Playlists shell.
|
||||
|
||||
Implementation:
|
||||
|
||||
- `frontend/src/App.tsx`
|
||||
- Replaced library-shell wiring with route-based StemEngine shell using `Sidebar`.
|
||||
- Restored routes:
|
||||
- `/` → `Separator`
|
||||
- `/projects/:projectId` → `ProjectDetail`
|
||||
- `/settings` → `Settings`
|
||||
- Header actions wired to home/settings and GPU reset status.
|
||||
|
||||
Verification:
|
||||
|
||||
- Frontend build passes.
|
||||
- Runtime confirms WebUI host responds and serves sidebar components with
|
||||
`SubsonicPanel` and `YtDlPanel`.
|
||||
|
||||
---
|
||||
|
||||
## 30) 2026-04-06 incident investigation — why WebUI/SingUI were repeatedly conflated
|
||||
|
||||
### Summary
|
||||
|
||||
The confusion was caused by **deployment topology coupling**, not just operator error.
|
||||
Both `5174` and `3001` were configured as separate containers but built from the
|
||||
same source tree and image, so UI-shell changes applied globally unless additional
|
||||
mode gating was implemented.
|
||||
|
||||
### Evidence collected
|
||||
|
||||
1. **Same compose file + same working directory**
|
||||
- Running containers are sourced from:
|
||||
- config file: `/home/translator/docker/stemengine.yml`
|
||||
- working dir: `/home/translator/docker`
|
||||
|
||||
2. **Same image digest for both services**
|
||||
- `stemengine-webui` and `stemengine-sing` both run the same image digest.
|
||||
|
||||
3. **Same bind mount for frontend source**
|
||||
- both mount:
|
||||
- `/home/translator/docker/appdata/stemengine/frontend -> /app/frontend`
|
||||
- both mount the same node_modules volume.
|
||||
|
||||
4. **No explicit app-mode split in runtime code path**
|
||||
- UI flavor was controlled only by route usage (`/` vs `/sing`) and recent
|
||||
`App.tsx` shell changes, not by an enforced service-level mode switch.
|
||||
|
||||
### Why this produced repeated regressions
|
||||
|
||||
- Changing `frontend/src/App.tsx` for one service immediately changed both services.
|
||||
- Re-pointing one service to a legacy tree (`x/StemEngine-0.9alpha`) temporarily
|
||||
solved one symptom while creating version drift and new regressions.
|
||||
- There are two `stemengine.yml` files in workspace (`/home/translator/docker/...`
|
||||
and `/home/translator/docker/appdata/stemengine/...`), increasing mental
|
||||
overhead during rapid edits (even though active runtime used the top-level file).
|
||||
|
||||
### Correct current state (after fixes)
|
||||
|
||||
- `5174` = StemEngine workflow shell (Sidebar: Subsonic + YT-DL + Projects)
|
||||
- `3001` = Sing entry endpoint on the same frontend codebase
|
||||
- `8000` = API backend (legacy static mount gated by env)
|
||||
|
||||
### Guardrails recommended
|
||||
|
||||
1. Introduce explicit service mode env (e.g., `VITE_UI_FLAVOR=webui|sing`) and
|
||||
branch shell composition by mode in app bootstrap.
|
||||
2. Keep one canonical compose file for active deployment, archive/deprecate
|
||||
duplicate filename variants.
|
||||
3. Add smoke checks in CI/start script:
|
||||
- `5174` must expose sidebar markers (`SubsonicPanel`, `YtDlPanel`)
|
||||
- `3001` must expose Sing route shell markers.
|
||||
|
||||
---
|
||||
|
||||
## 31) 2026-04-06 implementation — explicit UI flavor split (`webui` vs `sing`)
|
||||
|
||||
Implemented the guardrail proposed in section 30 so service behavior is no longer
|
||||
implicitly coupled by default shell edits.
|
||||
|
||||
### What was implemented
|
||||
|
||||
1. **Runtime flavor gate in app bootstrap**
|
||||
- `frontend/src/App.tsx`
|
||||
- Added mode switch based on `import.meta.env.VITE_UI_FLAVOR`:
|
||||
- `webui` → StemEngine workflow shell (`Sidebar` + `Separator/ProjectDetail/Settings`)
|
||||
- `sing` → Subsonic library + karaoke shell (`AppLibraryShell`, `/sing`, `/karaoke`)
|
||||
|
||||
2. **Service-level flavor assignment in compose**
|
||||
- `stemengine.yml`
|
||||
- `stemengine-webui` environment:
|
||||
- `VITE_UI_FLAVOR=webui`
|
||||
- `stemengine-sing` environment:
|
||||
- `VITE_UI_FLAVOR=sing`
|
||||
|
||||
### Validation
|
||||
|
||||
- Frontend build passes after split.
|
||||
- Compose config validates.
|
||||
- Runtime container env confirms:
|
||||
- WebUI container: `VITE_UI_FLAVOR=webui`
|
||||
- SingUI container: `VITE_UI_FLAVOR=sing`
|
||||
|
||||
### Net effect
|
||||
|
||||
- Port `5174` and `3001` now have an explicit behavioral contract even while
|
||||
sharing the same repository and image lineage.
|
||||
- Future shell changes can be scoped by mode instead of accidentally affecting
|
||||
both services.
|
||||
|
||||
---
|
||||
|
||||
## 32) 2026-04-06 execution plan — SingUI Subsonic browse parity + StemEngine process actions
|
||||
|
||||
Objective:
|
||||
|
||||
- Make SingUI (`3001`) behave like Feishin/Navidrome for library browsing,
|
||||
while preserving StemEngine-specific actions:
|
||||
- per-song **Process** button,
|
||||
- per-album **Process Album** button.
|
||||
|
||||
### Current baseline (already present)
|
||||
|
||||
- Sing shell mode is now explicit via `VITE_UI_FLAVOR=sing`.
|
||||
- Subsonic integration exists through backend `/api/subsonic/*` and frontend hooks.
|
||||
- Per-song and grouped album processing status patterns are already implemented in core pages.
|
||||
|
||||
### Gaps to close for Feishin/Navidrome-level UX
|
||||
|
||||
1. **Large-library browse scalability**
|
||||
- Current song-first fetch/group approach can degrade on very large libraries.
|
||||
- Need server-side paged browse for albums/artists/tracks.
|
||||
|
||||
2. **Detail-first interaction parity**
|
||||
- Add explicit track/album detail screens in Sing shell with action rows
|
||||
matching music-player expectations.
|
||||
|
||||
3. **Consistent convert affordance placement**
|
||||
- Enforce action ordering: **Process** before favorite/heart, for both track
|
||||
and album contexts.
|
||||
|
||||
4. **Queue/now-playing integration refinement**
|
||||
- Ensure browse lists, detail pages, and now-playing all share one playback state model.
|
||||
|
||||
### Implementation plan
|
||||
|
||||
#### Phase S1 — Backend browse APIs for parity + performance
|
||||
|
||||
Add Subsonic browse endpoints optimized for paging/filtering:
|
||||
|
||||
- `GET /api/subsonic/albums?offset=&size=&query=&artistId=`
|
||||
- `GET /api/subsonic/artists?offset=&size=&query=`
|
||||
- `GET /api/subsonic/albums/{albumId}` (album metadata + tracks)
|
||||
- `GET /api/subsonic/artists/{artistId}` (artist metadata + top albums)
|
||||
|
||||
Guidelines:
|
||||
|
||||
- Keep response shapes normalized and stable for frontend list virtualization.
|
||||
- Keep existing `/api/subsonic/search` for global search bar use.
|
||||
- Preserve current playlist endpoints.
|
||||
|
||||
#### Phase S2 — SingUI browse surfaces (Feishin/Navidrome behavior)
|
||||
|
||||
In Sing mode (`frontend/src/App.tsx` + pages):
|
||||
|
||||
- Home, Tracks, Albums, Artists, Playlists, Karaoke remain top-level sections.
|
||||
- Introduce dedicated detail routes:
|
||||
- `/albums/:albumId`
|
||||
- `/tracks/:trackId`
|
||||
- `/artists/:artistId`
|
||||
- Add list virtualization and paged loading for track/album grids.
|
||||
|
||||
#### Phase S3 — StemEngine process actions in SingUI
|
||||
|
||||
Action contract:
|
||||
|
||||
- **Track detail** action row:
|
||||
1. `Process` (or status badge: Queued/Running/Ready/Retry)
|
||||
2. `Favorite`
|
||||
|
||||
- **Album detail** header action row:
|
||||
1. `Process Album`
|
||||
2. `Favorite`
|
||||
|
||||
Processing behavior:
|
||||
|
||||
- Track action: import source → submit StemEngine processing job → poll status.
|
||||
- Album action: enqueue each track (or backend batch endpoint if added) and show
|
||||
aggregate state.
|
||||
- Reuse `useConvertStatus` state model for consistency.
|
||||
|
||||
#### Phase S4 — Reliability, observability, and UX hardening
|
||||
|
||||
- Add stale/error/empty states per domain (connection, auth, browse, process).
|
||||
- Add toast + inline status transitions with deterministic labels.
|
||||
- Add cross-tab synchronization for process completion/project readiness.
|
||||
- Add telemetry hooks (counts for process started/succeeded/failed by scope).
|
||||
|
||||
### File-level execution map
|
||||
|
||||
Backend:
|
||||
|
||||
- `backend/routers/subsonic.py` (new browse endpoints)
|
||||
- `backend/services/subsonic_service.py` (paged album/artist/detail methods)
|
||||
|
||||
Frontend (Sing mode):
|
||||
|
||||
- `frontend/src/App.tsx` (sing-mode detail routes)
|
||||
- `frontend/src/pages/Sing.tsx` (overview surfaces)
|
||||
- `frontend/src/pages/Tracks.tsx`, `Albums.tsx`, `Artists.tsx`, `Playlists.tsx`
|
||||
- `frontend/src/hooks/useSubsonicLibrary.ts` (evolve into paged data hooks)
|
||||
- `frontend/src/hooks/useConvertStatus.ts` (shared process state)
|
||||
- `frontend/src/api/client.ts` + `frontend/src/types.ts` (API contracts)
|
||||
|
||||
### Acceptance criteria
|
||||
|
||||
1. SingUI can connect to Subsonic and browse by tracks/albums/artists/playlists
|
||||
with page-scale behavior acceptable for large libraries.
|
||||
2. Track and album detail pages include process buttons in required order
|
||||
(**Process** before favorite).
|
||||
3. Process status transitions are visible and accurate (`Queued`, `Running`,
|
||||
`Ready`, `Retry`) for both per-song and per-album flows.
|
||||
4. Completing a process action makes the corresponding project discoverable in
|
||||
karaoke launch flows without manual refresh.
|
||||
5. WebUI (`5174`) remains unaffected due to explicit UI flavor split.
|
||||
|
||||
---
|
||||
|
||||
## 33) 2026-04-06 implementation — SingUI detail browse + process actions
|
||||
|
||||
Implemented the first concrete slice from section 32 to deliver Feishin/Navidrome-style
|
||||
browse progression with explicit detail actions.
|
||||
|
||||
### Implemented UI behavior
|
||||
|
||||
1. **SingUI detail routes added**
|
||||
- Album detail route: `/albums/:albumId`
|
||||
- Track detail route: `/tracks/:trackId`
|
||||
|
||||
2. **Per-album processing UI**
|
||||
- Album detail header now has action order:
|
||||
1. `Process Album`
|
||||
2. `Favorite`
|
||||
- Uses aggregate state from convert lifecycle (`Queued`, `Running`, `Ready`, `Retry`).
|
||||
|
||||
3. **Per-song processing UI**
|
||||
- Track detail action row now has:
|
||||
1. `Process`
|
||||
2. `Favorite`
|
||||
- Album detail track rows also expose per-song `Process` before `Favorite`.
|
||||
|
||||
4. **Browse-to-detail navigation**
|
||||
- Tracks lists now link song titles to track detail route.
|
||||
- Albums lists now link album titles to album detail route.
|
||||
- Sing page tracks/albums sections now deep-link to detail routes.
|
||||
|
||||
### Files changed
|
||||
|
||||
- `frontend/src/App.tsx`
|
||||
- Sing mode shell recognizes detail paths and routes them to detail pages.
|
||||
- `frontend/src/pages/Albums.tsx`
|
||||
- Uses Subsonic album browse endpoint (`listSubsonicAlbums`) for stable album ids.
|
||||
- Adds detail navigation and per-album process fallback via album detail fetch.
|
||||
- `frontend/src/pages/Tracks.tsx`
|
||||
- Adds detail navigation to `/tracks/:trackId`.
|
||||
- `frontend/src/pages/Sing.tsx`
|
||||
- Adds links from Sing tracks/albums views into detail routes.
|
||||
- `frontend/src/pages/AlbumDetail.tsx` (new)
|
||||
- Album metadata + songs + process/favorite actions.
|
||||
- `frontend/src/pages/TrackDetail.tsx` (new)
|
||||
- Track metadata + process/favorite actions.
|
||||
|
||||
### Validation
|
||||
|
||||
- Frontend build succeeds after changes.
|
||||
- SingUI runtime serves new route markers and detail pages.
|
||||
- Process buttons are present at detail level for both album and track scopes.
|
||||
|
||||
---
|
||||
|
||||
## 34) 2026-04-06 implementation — SingUI settings is now explicitly closable
|
||||
|
||||
Issue:
|
||||
|
||||
- In SingUI mode, opening settings navigated to a fullscreen settings view with
|
||||
no explicit close affordance, which made it feel non-closable.
|
||||
|
||||
Fix implemented:
|
||||
|
||||
- `frontend/src/App.tsx` (`SingUiShell`)
|
||||
- Added `closeSettings()` handler:
|
||||
- uses `navigate(-1)` when browser history exists,
|
||||
- otherwise falls back to `navigate('/sing')`.
|
||||
- Added a top settings header in Sing mode with a **Close** button (`X` icon)
|
||||
labeled `Close settings`.
|
||||
|
||||
Result:
|
||||
|
||||
- SingUI settings now has a deterministic close path and no longer traps users
|
||||
in fullscreen settings context.
|
||||
|
||||
Validation:
|
||||
|
||||
- Runtime source checks confirm `SingUI Settings` header and `closeSettings`
|
||||
handler are served on `3001`.
|
||||
|
||||
---
|
||||
|
||||
## 35) 2026-04-06 SingUI hotfix — albums load but tracks/artists do not
|
||||
|
||||
Issue observed (SingUI scope):
|
||||
|
||||
- Subsonic **albums** browse loaded,
|
||||
- but **tracks** and **artists** views were failing/empty.
|
||||
|
||||
Root cause:
|
||||
|
||||
- Tracks and artist derivation depended on `useSubsonicLibrary()` wildcard search
|
||||
(`/api/subsonic/search?q=*`).
|
||||
- Some Subsonic-compatible servers accept album/artist browse endpoints but do not
|
||||
reliably support wildcard search semantics.
|
||||
|
||||
Fix implemented:
|
||||
|
||||
1. `frontend/src/hooks/useSubsonicLibrary.ts`
|
||||
- Added resilient fallback path when wildcard search fails:
|
||||
- load album browse list,
|
||||
- fetch album details,
|
||||
- flatten songs into a deduped track list.
|
||||
|
||||
2. `frontend/src/pages/Artists.tsx`
|
||||
- Switched from song-derived artist list to direct artist browse endpoint:
|
||||
- `listSubsonicArtists(...)`
|
||||
- This removes dependence on wildcard track search for artists page rendering.
|
||||
|
||||
Result:
|
||||
|
||||
- Track-oriented views continue to function via fallback even when wildcard search
|
||||
is unsupported.
|
||||
- Artists page now uses a dedicated browse endpoint and no longer fails due to
|
||||
track search incompatibility.
|
||||
|
||||
Validation:
|
||||
|
||||
- Frontend build passes.
|
||||
- Runtime source checks confirm fallback and artist endpoint wiring are served in SingUI.
|
||||
|
||||
---
|
||||
|
||||
## 35) 2026-04-06 fix — SingUI Subsonic connect 500 while WebUI search worked
|
||||
|
||||
Issue observed:
|
||||
|
||||
- Subsonic connection attempts from SingUI (`3001`) returned `500`.
|
||||
- WebUI (`5174`) Subsonic search still worked.
|
||||
|
||||
Root cause:
|
||||
|
||||
- In dev-container mode, frontend API calls were using relative `/api` in SingUI.
|
||||
- Vite proxy target in `frontend/vite.config.ts` pointed to `http://localhost:8000`.
|
||||
- Inside container, `localhost` points to the frontend container itself, not backend,
|
||||
producing proxy failures (surfacing as `500` on SingUI API calls).
|
||||
|
||||
Why WebUI could still appear functional:
|
||||
|
||||
- WebUI may have used an origin-local API base override, bypassing proxy path,
|
||||
while SingUI (separate origin) used default relative `/api` and hit the broken proxy.
|
||||
|
||||
Fix implemented:
|
||||
|
||||
1. `frontend/vite.config.ts`
|
||||
- Switched proxy target to Docker-safe backend service default:
|
||||
- `VITE_API_PROXY_TARGET` (env override), else `http://stemengine:8000`.
|
||||
|
||||
2. `stemengine.yml`
|
||||
- Added explicit env for both frontend services:
|
||||
- `VITE_API_PROXY_TARGET=http://stemengine:8000`
|
||||
|
||||
Validation:
|
||||
|
||||
- `GET http://127.0.0.1:3001/api/subsonic/config` now returns `200`.
|
||||
- Backend logs show normal startup and API handling; no Subsonic-related traceback.
|
||||
|
||||
---
|
||||
|
||||
## 36) 2026-04-06 architecture draft — Nightingale-style separation→karaoke playback flow for SingUI
|
||||
|
||||
Objective:
|
||||
|
||||
- Adopt a proven karaoke architecture pattern from Nightingale for SingUI, while
|
||||
preserving StemEngine’s existing API surface and process lifecycle states.
|
||||
|
||||
Draft produced:
|
||||
|
||||
- Added a dedicated design draft:
|
||||
- `docs/SINGUI_NIGHTINGALE_FLOW_DRAFT.md`
|
||||
|
||||
Core proposed lifecycle:
|
||||
|
||||
1. **Prepare phase** (async, cached)
|
||||
- separation
|
||||
- lyric align/transcribe
|
||||
- materialize playback assets manifest
|
||||
2. **Playback gate**
|
||||
- block karaoke playback until track is `Ready`
|
||||
3. **Per-stem playback**
|
||||
- synchronized stems with `leading` muted by default
|
||||
4. **Single timeline bus**
|
||||
- drive lyrics, HUD, skip logic, and future scoring from one clock
|
||||
|
||||
Key contract proposal:
|
||||
|
||||
- Per-track `karaoke_assets.json` manifest returned by backend to remove frontend
|
||||
ambiguity and prevent race conditions.
|
||||
|
||||
Incremental delivery sequence:
|
||||
|
||||
1. Add assets endpoint + manifest generation
|
||||
2. Enforce ready gate in Sing route
|
||||
3. Wire dual-stream player controls
|
||||
4. Unify timeline fanout for overlays
|
||||
5. Add retry/error observability per stage
|
||||
|
||||
Rationale:
|
||||
|
||||
- This mirrors Nightingale’s strongest operational characteristic: asynchronous,
|
||||
cache-first preparation with deterministic readiness before playback.
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+242
-18
@@ -1,9 +1,26 @@
|
||||
import { lazy, Suspense } from 'react'
|
||||
import { Music2 } from 'lucide-react'
|
||||
import { Route, Routes, useLocation } from 'react-router-dom'
|
||||
import { lazy, Suspense, useEffect, useMemo, useState } from 'react'
|
||||
import { Music2, Settings, Cpu, X } from 'lucide-react'
|
||||
import { Navigate, Route, Routes, useLocation, useNavigate, useParams } from 'react-router-dom'
|
||||
import Separator from './pages/Separator'
|
||||
import ProjectDetail from './pages/ProjectDetail'
|
||||
import SettingsPage from './pages/Settings'
|
||||
import { ThemeProvider } from './context/ThemeContext'
|
||||
import Sidebar from './components/Sidebar'
|
||||
import GlobalAudioBar from './components/GlobalAudioBar'
|
||||
import AppLibraryShell from './components/AppLibraryShell'
|
||||
import { HOME_ROUTE, KARAOKE_ROUTE, SETTINGS_ROUTE, ALBUMS_ROUTE, TRACKS_ROUTE, ARTISTS_ROUTE, PLAYLISTS_ROUTE, SING_ROUTE } from './routes'
|
||||
import { getGpuInfo, resetGpu } from './api/client'
|
||||
import {
|
||||
HOME_ROUTE,
|
||||
ALBUMS_ROUTE,
|
||||
TRACKS_ROUTE,
|
||||
ARTISTS_ROUTE,
|
||||
PLAYLISTS_ROUTE,
|
||||
SING_ROUTE,
|
||||
SETTINGS_ROUTE,
|
||||
KARAOKE_ROUTE,
|
||||
projectRoute,
|
||||
} from './routes'
|
||||
import { applyAccent, applyFont } from './utils/appearance'
|
||||
|
||||
const HomePage = lazy(() => import('./pages/Home'))
|
||||
const AlbumsPage = lazy(() => import('./pages/Albums'))
|
||||
@@ -11,9 +28,32 @@ const TracksPage = lazy(() => import('./pages/Tracks'))
|
||||
const ArtistsPage = lazy(() => import('./pages/Artists'))
|
||||
const PlaylistsPage = lazy(() => import('./pages/Playlists'))
|
||||
const SingPage = lazy(() => import('./pages/Sing'))
|
||||
const SettingsPage = lazy(() => import('./pages/Settings'))
|
||||
const AlbumDetailPage = lazy(() => import('./pages/AlbumDetail'))
|
||||
const TrackDetailPage = lazy(() => import('./pages/TrackDetail'))
|
||||
const KaraokePage = lazy(() => import('./pages/Karaoke'))
|
||||
|
||||
interface GpuInfo {
|
||||
cuda_available: boolean
|
||||
cuda_ok: boolean
|
||||
name: string | null
|
||||
free_mb: number
|
||||
total_mb: number
|
||||
}
|
||||
|
||||
function ProjectDetailRoute() {
|
||||
const navigate = useNavigate()
|
||||
const { projectId = '' } = useParams<{ projectId: string }>()
|
||||
const id = useMemo(() => {
|
||||
try {
|
||||
return decodeURIComponent(projectId)
|
||||
} catch {
|
||||
return projectId
|
||||
}
|
||||
}, [projectId])
|
||||
|
||||
return <ProjectDetail id={id} onDelete={() => navigate('/')} />
|
||||
}
|
||||
|
||||
function PageLoader() {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-screen bg-gray-950 text-gray-100">
|
||||
@@ -25,18 +65,192 @@ function PageLoader() {
|
||||
)
|
||||
}
|
||||
|
||||
function AppShell() {
|
||||
function WebUiShell() {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
|
||||
// Check which view type we're in
|
||||
const [sidebarOpen, setSidebarOpen] = useState(() => window.innerWidth >= 640)
|
||||
const [gpuInfo, setGpuInfo] = useState<GpuInfo | null>(null)
|
||||
const [gpuResetting, setGpuResetting] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
applyFont(localStorage.getItem('stemengine-font') ?? 'system')
|
||||
applyAccent(localStorage.getItem('stemengine-accent') ?? 'blue')
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchGpu() {
|
||||
try {
|
||||
setGpuInfo(await getGpuInfo())
|
||||
} catch {}
|
||||
}
|
||||
fetchGpu()
|
||||
const id = setInterval(fetchGpu, 30_000)
|
||||
return () => clearInterval(id)
|
||||
}, [])
|
||||
|
||||
async function handleGpuReset() {
|
||||
setGpuResetting(true)
|
||||
try {
|
||||
await resetGpu()
|
||||
setGpuInfo(await getGpuInfo())
|
||||
} catch {}
|
||||
setGpuResetting(false)
|
||||
}
|
||||
|
||||
const gpuContextFailed = gpuInfo?.cuda_available === true && gpuInfo.cuda_ok === false
|
||||
useEffect(() => {
|
||||
if (gpuContextFailed && !gpuResetting) {
|
||||
handleGpuReset()
|
||||
}
|
||||
}, [gpuContextFailed, gpuResetting])
|
||||
|
||||
const activeProjectId = useMemo(() => {
|
||||
const match = location.pathname.match(/^\/projects\/([^/]+)$/)
|
||||
if (!match) return null
|
||||
try {
|
||||
return decodeURIComponent(match[1])
|
||||
} catch {
|
||||
return match[1]
|
||||
}
|
||||
}, [location.pathname])
|
||||
|
||||
const inSettings = location.pathname === SETTINGS_ROUTE
|
||||
|
||||
const gpuError = gpuInfo ? (!gpuInfo.cuda_ok || !gpuInfo.cuda_available) : false
|
||||
const gpuTitle = gpuInfo
|
||||
? gpuInfo.cuda_available
|
||||
? `${gpuInfo.name ?? 'GPU'} · ${gpuInfo.free_mb} / ${gpuInfo.total_mb} MB free${!gpuInfo.cuda_ok ? ' · Context error — click to reset' : ''}`
|
||||
: 'CUDA unavailable — click to attempt reset'
|
||||
: 'GPU status unknown'
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col overflow-hidden">
|
||||
<header className="shrink-0 border-b border-slate-200 dark:border-gray-800 bg-white dark:bg-gray-950 z-20">
|
||||
<div className="h-1 bg-gradient-to-r from-brand-500 via-purple-500 to-rose-500" />
|
||||
|
||||
<div className="px-4 py-2.5 flex items-center gap-3">
|
||||
<button
|
||||
onClick={() => navigate('/')}
|
||||
title="Home"
|
||||
className="flex items-center gap-2 flex-1 min-w-0 hover:opacity-80 transition-opacity text-left"
|
||||
>
|
||||
<div className="w-8 h-8 rounded-lg bg-gradient-to-br from-brand-500 to-brand-700 flex items-center justify-center shrink-0 shadow-md shadow-brand-500/30">
|
||||
<Music2 className="w-4 h-4 text-white" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<span className="text-base font-bold text-slate-900 dark:text-white tracking-tight">StemEngine</span>
|
||||
<span className="text-xs text-slate-400 dark:text-gray-600 ml-2 hidden sm:inline">Audio processing toolkit</span>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={handleGpuReset}
|
||||
title={gpuTitle}
|
||||
className={`relative p-2 rounded-xl border transition-all ${
|
||||
gpuError
|
||||
? 'border-red-400 bg-red-50 dark:bg-red-950/30 text-red-500 dark:text-red-400 hover:border-red-500'
|
||||
: 'border-slate-200 dark:border-gray-700 bg-slate-50 dark:bg-gray-900 text-slate-400 dark:text-gray-600 hover:text-brand-600 dark:hover:text-brand-400 hover:border-brand-400'
|
||||
}`}
|
||||
>
|
||||
<Cpu className={`w-4 h-4 ${gpuResetting ? 'animate-pulse' : ''}`} />
|
||||
{gpuInfo && (
|
||||
<span className={`absolute top-1 right-1 w-1.5 h-1.5 rounded-full ${
|
||||
!gpuInfo.cuda_available
|
||||
? 'bg-slate-400 dark:bg-gray-600'
|
||||
: !gpuInfo.cuda_ok
|
||||
? 'bg-red-500 animate-pulse'
|
||||
: 'bg-emerald-400'
|
||||
}`} />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => navigate(SETTINGS_ROUTE)}
|
||||
title="Settings"
|
||||
className={`p-2 rounded-xl border transition-all ${
|
||||
inSettings
|
||||
? 'border-brand-500 bg-brand-50 dark:bg-brand-950/30 text-brand-600 dark:text-brand-400'
|
||||
: 'border-slate-200 dark:border-gray-700 bg-slate-50 dark:bg-gray-900 text-slate-500 hover:text-brand-600 dark:text-gray-400 dark:hover:text-brand-400 hover:border-brand-400'
|
||||
}`}
|
||||
>
|
||||
<Settings className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="flex flex-1 overflow-hidden">
|
||||
{sidebarOpen && <div className="sm:hidden fixed inset-0 z-20 bg-black/40" onClick={() => setSidebarOpen(false)} />}
|
||||
|
||||
<Sidebar
|
||||
isOpen={sidebarOpen}
|
||||
onToggle={() => setSidebarOpen((v) => !v)}
|
||||
onDeleteProject={(project) => {
|
||||
if (activeProjectId === project.id) navigate('/')
|
||||
}}
|
||||
activeProjectId={activeProjectId}
|
||||
onProjectNavigate={() => setSidebarOpen(false)}
|
||||
/>
|
||||
|
||||
<div className="flex-1 flex flex-col overflow-hidden bg-slate-100 dark:bg-gray-950">
|
||||
<main className="flex-1 overflow-y-auto pb-12">
|
||||
<div className="max-w-3xl mx-auto px-2 sm:px-4 py-4 sm:py-6">
|
||||
<div className="rounded-2xl border border-slate-200 dark:border-gray-800 bg-white dark:bg-gray-900/60 p-3 sm:p-6 shadow-sm dark:shadow-xl">
|
||||
<Routes>
|
||||
<Route
|
||||
path="/"
|
||||
element={
|
||||
<Separator
|
||||
onSeparationComplete={(id) => navigate(projectRoute(id))}
|
||||
onOpenSettings={() => {
|
||||
localStorage.setItem('stemengine-settings-initial-tab', 'autopipeline')
|
||||
navigate(SETTINGS_ROUTE)
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<Route path="/projects/:projectId" element={<ProjectDetailRoute />} />
|
||||
<Route path={SETTINGS_ROUTE} element={<SettingsPage />} />
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</div>
|
||||
|
||||
<footer className="mt-6 text-center text-xs text-slate-400 dark:text-gray-700">
|
||||
StemEngine · Demucs · BS-RoFormer · Omnizart · wav2vec2
|
||||
</footer>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<GlobalAudioBar />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SingUiShell() {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
|
||||
function closeSettings() {
|
||||
if (window.history.length > 1) {
|
||||
navigate(-1)
|
||||
return
|
||||
}
|
||||
navigate(SING_ROUTE)
|
||||
}
|
||||
|
||||
const isAlbumDetailView = location.pathname.startsWith(`${ALBUMS_ROUTE}/`)
|
||||
const isTrackDetailView = location.pathname.startsWith(`${TRACKS_ROUTE}/`)
|
||||
const isLibraryView = [HOME_ROUTE, ALBUMS_ROUTE, TRACKS_ROUTE, ARTISTS_ROUTE, PLAYLISTS_ROUTE, SING_ROUTE].includes(location.pathname)
|
||||
|| isAlbumDetailView
|
||||
|| isTrackDetailView
|
||||
const isKaraokeView = location.pathname === KARAOKE_ROUTE
|
||||
const isSettingsView = location.pathname === SETTINGS_ROUTE
|
||||
|
||||
// Render app library shell for library views
|
||||
if (isLibraryView) {
|
||||
return (
|
||||
<AppLibraryShell>
|
||||
<AppLibraryShell onOpenSettings={() => navigate(SETTINGS_ROUTE)}>
|
||||
<Routes>
|
||||
<Route path={HOME_ROUTE} element={<Suspense fallback={<PageLoader />}><HomePage /></Suspense>} />
|
||||
<Route path={ALBUMS_ROUTE} element={<Suspense fallback={<PageLoader />}><AlbumsPage /></Suspense>} />
|
||||
@@ -44,12 +258,13 @@ function AppShell() {
|
||||
<Route path={ARTISTS_ROUTE} element={<Suspense fallback={<PageLoader />}><ArtistsPage /></Suspense>} />
|
||||
<Route path={PLAYLISTS_ROUTE} element={<Suspense fallback={<PageLoader />}><PlaylistsPage /></Suspense>} />
|
||||
<Route path={SING_ROUTE} element={<Suspense fallback={<PageLoader />}><SingPage /></Suspense>} />
|
||||
<Route path={`${ALBUMS_ROUTE}/:albumId`} element={<Suspense fallback={<PageLoader />}><AlbumDetailPage /></Suspense>} />
|
||||
<Route path={`${TRACKS_ROUTE}/:trackId`} element={<Suspense fallback={<PageLoader />}><TrackDetailPage /></Suspense>} />
|
||||
</Routes>
|
||||
</AppLibraryShell>
|
||||
)
|
||||
}
|
||||
|
||||
// Render karaoke view (full-screen performance mode)
|
||||
if (isKaraokeView) {
|
||||
return (
|
||||
<Suspense fallback={<PageLoader />}>
|
||||
@@ -58,27 +273,36 @@ function AppShell() {
|
||||
)
|
||||
}
|
||||
|
||||
// Render settings view
|
||||
if (isSettingsView) {
|
||||
return (
|
||||
<div className="h-screen overflow-auto bg-gray-950">
|
||||
<div className="max-w-4xl mx-auto px-4 py-6">
|
||||
<Suspense fallback={<PageLoader />}>
|
||||
<SettingsPage />
|
||||
</Suspense>
|
||||
<div className="max-w-4xl mx-auto px-4 py-4">
|
||||
<div className="mb-3 flex items-center justify-between rounded-lg border border-gray-800 bg-gray-900 px-3 py-2">
|
||||
<h2 className="text-sm font-semibold text-gray-200">SingUI Settings</h2>
|
||||
<button
|
||||
onClick={closeSettings}
|
||||
className="inline-flex items-center gap-2 rounded border border-gray-700 px-2 py-1 text-sm text-gray-300 hover:border-gray-500 hover:text-white"
|
||||
title="Close settings"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
<SettingsPage />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Fallback for unknown routes
|
||||
return <PageLoader />
|
||||
return <Navigate to={SING_ROUTE} replace />
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const uiFlavor = (((import.meta as any).env?.VITE_UI_FLAVOR as string | undefined) ?? 'webui').toLowerCase()
|
||||
|
||||
return (
|
||||
<ThemeProvider>
|
||||
<AppShell />
|
||||
{uiFlavor === 'sing' ? <SingUiShell /> : <WebUiShell />}
|
||||
</ThemeProvider>
|
||||
)
|
||||
}
|
||||
@@ -9,6 +9,12 @@ import type {
|
||||
DynamicLevels,
|
||||
LyricsStyleOptions,
|
||||
SubsonicSong,
|
||||
SubsonicPlaylist,
|
||||
SubsonicPlaylistDetail,
|
||||
SubsonicAlbum,
|
||||
SubsonicAlbumDetail,
|
||||
SubsonicArtist,
|
||||
SubsonicArtistDetail,
|
||||
SubsonicConfig,
|
||||
ImportedFile,
|
||||
Project,
|
||||
@@ -437,6 +443,35 @@ export const importYtDl = (url: string, title = '', artist = '') =>
|
||||
body: JSON.stringify({ url, title, artist }),
|
||||
})
|
||||
|
||||
export const listSubsonicPlaylists = () =>
|
||||
request<SubsonicPlaylist[]>(`${BASE}/subsonic/playlists`)
|
||||
|
||||
export const getSubsonicPlaylist = (playlistId: string) =>
|
||||
request<SubsonicPlaylistDetail>(`${BASE}/subsonic/playlists/${encodeURIComponent(playlistId)}`)
|
||||
|
||||
export const listSubsonicAlbums = (params?: { offset?: number; size?: number; query?: string; artistId?: string }) => {
|
||||
const qs = new URLSearchParams()
|
||||
qs.set('offset', String(params?.offset ?? 0))
|
||||
qs.set('size', String(params?.size ?? 50))
|
||||
if (params?.query) qs.set('query', params.query)
|
||||
if (params?.artistId) qs.set('artist_id', params.artistId)
|
||||
return request<SubsonicAlbum[]>(`${BASE}/subsonic/albums?${qs.toString()}`)
|
||||
}
|
||||
|
||||
export const getSubsonicAlbum = (albumId: string) =>
|
||||
request<SubsonicAlbumDetail>(`${BASE}/subsonic/albums/${encodeURIComponent(albumId)}`)
|
||||
|
||||
export const listSubsonicArtists = (params?: { offset?: number; size?: number; query?: string }) => {
|
||||
const qs = new URLSearchParams()
|
||||
qs.set('offset', String(params?.offset ?? 0))
|
||||
qs.set('size', String(params?.size ?? 200))
|
||||
if (params?.query) qs.set('query', params.query)
|
||||
return request<SubsonicArtist[]>(`${BASE}/subsonic/artists?${qs.toString()}`)
|
||||
}
|
||||
|
||||
export const getSubsonicArtist = (artistId: string) =>
|
||||
request<SubsonicArtistDetail>(`${BASE}/subsonic/artists/${encodeURIComponent(artistId)}`)
|
||||
|
||||
export const listImports = () =>
|
||||
request<ImportedFile[]>(`${BASE}/subsonic/imports`)
|
||||
|
||||
@@ -674,6 +709,122 @@ export const deleteStem = (projectId: string, stemName: string) =>
|
||||
body: JSON.stringify({ stem_name: stemName }),
|
||||
})
|
||||
|
||||
export const exportProjectKaraokeMugen = (
|
||||
projectId: string,
|
||||
opts?: {
|
||||
defaultTitleLang?: string
|
||||
repository?: string
|
||||
}
|
||||
) =>
|
||||
request<{
|
||||
success: boolean
|
||||
project_id: string
|
||||
project_name: string
|
||||
kid: string
|
||||
export_dir: string
|
||||
kara_json: string
|
||||
media: string
|
||||
lyrics: string
|
||||
warnings: string[]
|
||||
}>(`${BASE}/projects/${projectId}/export-karaoke-mugen`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
default_title_lang: opts?.defaultTitleLang ?? 'eng',
|
||||
repository: opts?.repository ?? 'stemengine.local',
|
||||
}),
|
||||
})
|
||||
|
||||
export const exportProjectSek = (
|
||||
projectId: string,
|
||||
opts?: {
|
||||
packageName?: string
|
||||
includeVideo?: boolean
|
||||
videoSource?: string
|
||||
syncReferenceTrack?: string
|
||||
autoSync?: boolean
|
||||
}
|
||||
) =>
|
||||
request<{
|
||||
success: boolean
|
||||
project_id: string
|
||||
project_name: string
|
||||
sek_path: string
|
||||
package_name: string
|
||||
export_dir: string
|
||||
stem_count: number
|
||||
lyrics: string
|
||||
video: string
|
||||
auto_sync_applied: boolean
|
||||
auto_sync_reference_track: string
|
||||
auto_sync_offset_seconds: number | null
|
||||
warnings: string[]
|
||||
}>(`${BASE}/projects/${projectId}/export-sek`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
package_name: opts?.packageName ?? null,
|
||||
include_video: opts?.includeVideo ?? true,
|
||||
video_source: opts?.videoSource ?? null,
|
||||
sync_reference_track: opts?.syncReferenceTrack ?? null,
|
||||
auto_sync: opts?.autoSync ?? true,
|
||||
}),
|
||||
})
|
||||
|
||||
export interface ProjectKaraokeConfig {
|
||||
video_source: string
|
||||
include_video: boolean
|
||||
sync_reference_track: string
|
||||
track_offsets_seconds: Record<string, number>
|
||||
last_sync?: string | null
|
||||
}
|
||||
|
||||
export const getProjectKaraokeConfig = (projectId: string) =>
|
||||
request<{
|
||||
project_id: string
|
||||
project_name: string
|
||||
config: ProjectKaraokeConfig
|
||||
}>(`${BASE}/projects/${projectId}/karaoke-config`)
|
||||
|
||||
export const patchProjectKaraokeConfig = (
|
||||
projectId: string,
|
||||
patch: {
|
||||
video_source?: string
|
||||
include_video?: boolean
|
||||
sync_reference_track?: string
|
||||
offset_seconds?: number
|
||||
}
|
||||
) =>
|
||||
request<{
|
||||
success: boolean
|
||||
project_id: string
|
||||
config: ProjectKaraokeConfig
|
||||
}>(`${BASE}/projects/${projectId}/karaoke-config`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(patch),
|
||||
})
|
||||
|
||||
export const syncProjectVideoOffset = (
|
||||
projectId: string,
|
||||
payload: {
|
||||
video_source: string
|
||||
reference_track: string
|
||||
}
|
||||
) =>
|
||||
request<{
|
||||
success: boolean
|
||||
project_id: string
|
||||
reference_track: string
|
||||
offset_seconds: number
|
||||
resolved_video: string
|
||||
config: ProjectKaraokeConfig
|
||||
}>(`${BASE}/projects/${projectId}/sync-video-offset`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
|
||||
// ---------- Per-Instrument Models ----------
|
||||
|
||||
export const getPerInstrumentModels = () =>
|
||||
@@ -787,6 +938,8 @@ export interface AppSettings {
|
||||
auto_model: string
|
||||
auto_format: string
|
||||
auto_presets: unknown[]
|
||||
karaoke_source_mode?: 'projects' | 'sek-folder'
|
||||
karaoke_sek_folder?: string
|
||||
}
|
||||
|
||||
export const getAppSettings = () =>
|
||||
@@ -801,3 +954,64 @@ export const patchAppSettings = (patch: Partial<AppSettings & { hf_token: string
|
||||
|
||||
export const deleteHfToken = () =>
|
||||
request<{ hf_token_set: boolean }>(`${BASE}/settings/hf-token`, { method: 'DELETE' })
|
||||
|
||||
// ── SEK library ─────────────────────────────────────────────────────────────
|
||||
|
||||
export interface SekLibraryItem {
|
||||
id: string
|
||||
filename: string
|
||||
path: string
|
||||
title: string
|
||||
valid: boolean
|
||||
stem_count: number
|
||||
has_video: boolean
|
||||
lyrics: string
|
||||
mtime: number
|
||||
warnings: string[]
|
||||
}
|
||||
|
||||
export interface SekLibraryResponse {
|
||||
folder: string
|
||||
count: number
|
||||
packages: SekLibraryItem[]
|
||||
}
|
||||
|
||||
export interface SekManifestResponse {
|
||||
id: string
|
||||
filename: string
|
||||
path: string
|
||||
manifest: {
|
||||
format?: string
|
||||
version?: number
|
||||
project?: { id?: string; name?: string }
|
||||
contents?: {
|
||||
lyrics?: string
|
||||
video?: string | null
|
||||
stems?: Array<{ name?: string; file?: string; bytes?: number }>
|
||||
}
|
||||
meta?: {
|
||||
synchronization?: {
|
||||
reference_track?: string
|
||||
track_offsets_seconds?: Record<string, number>
|
||||
video_source?: string
|
||||
last_sync?: string | null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const listSekLibrary = (folder?: string) =>
|
||||
request<SekLibraryResponse>(
|
||||
`${BASE}/karaoke-sek/library${folder ? `?folder=${encodeURIComponent(folder)}` : ''}`
|
||||
)
|
||||
|
||||
export const getSekManifest = (packageId: string, folder?: string) =>
|
||||
request<SekManifestResponse>(
|
||||
`${BASE}/karaoke-sek/packages/${encodeURIComponent(packageId)}${folder ? `?folder=${encodeURIComponent(folder)}` : ''}`
|
||||
)
|
||||
|
||||
export const sekAssetUrl = (packageId: string, innerPath: string, folder?: string) => {
|
||||
const q = new URLSearchParams({ path: innerPath })
|
||||
if (folder) q.set('folder', folder)
|
||||
return `${BASE}/karaoke-sek/packages/${encodeURIComponent(packageId)}/asset?${q.toString()}`
|
||||
}
|
||||
@@ -23,9 +23,10 @@ const NAV_ITEMS: NavItem[] = [
|
||||
|
||||
interface AppLibraryShellProps {
|
||||
children: React.ReactNode
|
||||
onOpenSettings?: () => void
|
||||
}
|
||||
|
||||
export default function AppLibraryShell({ children }: AppLibraryShellProps) {
|
||||
export default function AppLibraryShell({ children, onOpenSettings }: AppLibraryShellProps) {
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
const [sidebarOpen, setSidebarOpen] = useState(true)
|
||||
@@ -84,7 +85,13 @@ export default function AppLibraryShell({ children }: AppLibraryShellProps) {
|
||||
{/* Settings */}
|
||||
<div className="border-t border-gray-800 p-3">
|
||||
<button
|
||||
onClick={() => navigate(SETTINGS_ROUTE)}
|
||||
onClick={() => {
|
||||
if (onOpenSettings) {
|
||||
onOpenSettings()
|
||||
return
|
||||
}
|
||||
navigate(SETTINGS_ROUTE)
|
||||
}}
|
||||
className={`w-full flex items-center gap-3 px-3 py-2 rounded-lg transition-colors ${
|
||||
currentRoute === SETTINGS_ROUTE
|
||||
? 'bg-brand-500 text-white'
|
||||
|
||||
@@ -7,11 +7,11 @@
|
||||
*/
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { X, Zap, Loader2, CheckCircle2, XCircle, Music2, Mic2, AlignLeft, Settings, BookmarkPlus, Tag, Trash2 } from 'lucide-react'
|
||||
import { X, Zap, Loader2, CheckCircle2, XCircle, Music2, Mic2, AlignLeft, Settings, BookmarkPlus, Tag, Trash2, FileArchive } from 'lucide-react'
|
||||
import {
|
||||
getSepModels,
|
||||
submitSeparate, submitSeparateFromPath,
|
||||
getJob, reprocessStem, transcribeProject, lyricTranscribeProject, lrcProject, renameStem, deleteStem,
|
||||
getJob, reprocessStem, transcribeProject, lyricTranscribeProject, lrcProject, renameStem, deleteStem, exportProjectKaraokeMugen, exportProjectSek,
|
||||
} from '../api/client'
|
||||
import type { Job, ModelOption } from '../types'
|
||||
import {
|
||||
@@ -111,6 +111,8 @@ function StepIcon({ step }: { step: AutoStep }) {
|
||||
if (step.type === 'lyricsAlign') return <BookmarkPlus className="w-3.5 h-3.5 text-teal-500" />
|
||||
if (step.type === 'renameStem') return <Tag className="w-3.5 h-3.5 text-amber-500" />
|
||||
if (step.type === 'deleteStem') return <Trash2 className="w-3.5 h-3.5 text-rose-500" />
|
||||
if (step.type === 'karaokeMugen') return <FileArchive className="w-3.5 h-3.5 text-fuchsia-500" />
|
||||
if (step.type === 'sekPackage') return <FileArchive className="w-3.5 h-3.5 text-indigo-500" />
|
||||
return <AlignLeft className="w-3.5 h-3.5 text-sky-500" />
|
||||
}
|
||||
|
||||
@@ -336,6 +338,38 @@ export default function AutoPipelineDialog({ target, onClose, onComplete, onOpen
|
||||
await deleteStem(projectId, stem)
|
||||
}, ctrl.signal, retry)
|
||||
patchStep(stepIdx, { status: 'done', detail: step.stem })
|
||||
|
||||
} else if (step.type === 'karaokeMugen' && projectId) {
|
||||
await withRetry(async () => {
|
||||
patchStep(stepIdx, { detail: 'Packaging Karaoke Mugen export…' })
|
||||
const result = await exportProjectKaraokeMugen(projectId, {
|
||||
defaultTitleLang: step.defaultTitleLang ?? 'eng',
|
||||
repository: step.repository ?? 'stemengine.local',
|
||||
})
|
||||
const warningCount = result.warnings?.length ?? 0
|
||||
patchStep(stepIdx, {
|
||||
detail: warningCount > 0
|
||||
? `Exported (${warningCount} warning${warningCount > 1 ? 's' : ''})`
|
||||
: 'Exported',
|
||||
})
|
||||
}, ctrl.signal, retry)
|
||||
patchStep(stepIdx, { status: 'done' })
|
||||
|
||||
} else if (step.type === 'sekPackage' && projectId) {
|
||||
await withRetry(async () => {
|
||||
patchStep(stepIdx, { detail: 'Packaging StemEngine .sek file…' })
|
||||
const result = await exportProjectSek(projectId, {
|
||||
packageName: step.packageName,
|
||||
includeVideo: step.includeVideo ?? true,
|
||||
})
|
||||
const warningCount = result.warnings?.length ?? 0
|
||||
patchStep(stepIdx, {
|
||||
detail: warningCount > 0
|
||||
? `Exported ${result.package_name} (${warningCount} warning${warningCount > 1 ? 's' : ''})`
|
||||
: `Exported ${result.package_name}`,
|
||||
})
|
||||
}, ctrl.signal, retry)
|
||||
patchStep(stepIdx, { status: 'done' })
|
||||
}
|
||||
|
||||
stepIdx++
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import {
|
||||
getJob,
|
||||
importSubsonicSong,
|
||||
listProjects,
|
||||
submitSeparateFromPath,
|
||||
} from '../api/client'
|
||||
import type { Job, Project, SubsonicSong } from '../types'
|
||||
import { readAutoFormat, readAutoModel } from '../utils/autoPipeline'
|
||||
|
||||
export type ConvertStatus = 'idle' | 'queued' | 'running' | 'ready' | 'failed'
|
||||
|
||||
interface ConvertState {
|
||||
status: ConvertStatus
|
||||
error?: string
|
||||
jobId?: string
|
||||
}
|
||||
|
||||
function normalizeText(value?: string): string {
|
||||
return (value || '')
|
||||
.toLowerCase()
|
||||
.replace(/\.[a-z0-9]+$/i, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
}
|
||||
|
||||
function findProjectForSong(song: SubsonicSong, projects: Project[]): Project | null {
|
||||
const byArtistTitle = normalizeText(`${song.songArtist ?? song.artist} - ${song.title}`)
|
||||
const byTitle = normalizeText(song.title)
|
||||
|
||||
return projects.find((project) => {
|
||||
const name = normalizeText(project.name)
|
||||
if (!name) return false
|
||||
if (name === byArtistTitle || name === byTitle) return true
|
||||
if (byArtistTitle && name.includes(byArtistTitle)) return true
|
||||
if (byTitle && name.includes(byTitle)) return true
|
||||
return false
|
||||
}) || null
|
||||
}
|
||||
|
||||
async function pollJobUntilTerminal(jobId: string): Promise<Job> {
|
||||
for (;;) {
|
||||
const job = await getJob(jobId)
|
||||
if (job.status === 'done' || job.status === 'error' || job.status === 'cancelled') {
|
||||
return job
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 2500))
|
||||
}
|
||||
}
|
||||
|
||||
export function useConvertStatus(songs: SubsonicSong[]) {
|
||||
const [projects, setProjects] = useState<Project[]>([])
|
||||
const [stateBySongId, setStateBySongId] = useState<Record<string, ConvertState>>({})
|
||||
|
||||
const refreshProjects = useCallback(async () => {
|
||||
try {
|
||||
const data = await listProjects()
|
||||
setProjects(data)
|
||||
} catch {
|
||||
setProjects([])
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
refreshProjects()
|
||||
}, [refreshProjects])
|
||||
|
||||
const statusBySongId = useMemo<Record<string, ConvertState>>(() => {
|
||||
const out: Record<string, ConvertState> = {}
|
||||
songs.forEach((song) => {
|
||||
const runtime = stateBySongId[song.id]
|
||||
if (runtime?.status === 'queued' || runtime?.status === 'running' || runtime?.status === 'failed') {
|
||||
out[song.id] = runtime
|
||||
return
|
||||
}
|
||||
|
||||
const project = findProjectForSong(song, projects)
|
||||
out[song.id] = project ? { status: 'ready' } : runtime ?? { status: 'idle' }
|
||||
})
|
||||
return out
|
||||
}, [projects, songs, stateBySongId])
|
||||
|
||||
const convertSong = useCallback(async (song: SubsonicSong) => {
|
||||
const current = stateBySongId[song.id]?.status
|
||||
if (current === 'queued' || current === 'running') return
|
||||
|
||||
setStateBySongId((prev) => ({
|
||||
...prev,
|
||||
[song.id]: { status: 'queued' },
|
||||
}))
|
||||
|
||||
try {
|
||||
const imported = await importSubsonicSong(song)
|
||||
const model = readAutoModel()
|
||||
const format = readAutoFormat()
|
||||
const projectName = `${song.songArtist ?? song.artist} - ${song.title}`.trim()
|
||||
|
||||
const submit = await submitSeparateFromPath(imported.path, model, format, {
|
||||
presetType: 'stems_only',
|
||||
projectName,
|
||||
})
|
||||
|
||||
setStateBySongId((prev) => ({
|
||||
...prev,
|
||||
[song.id]: { status: 'running', jobId: submit.job_id },
|
||||
}))
|
||||
|
||||
const finalJob = await pollJobUntilTerminal(submit.job_id)
|
||||
|
||||
if (finalJob.status === 'done') {
|
||||
await refreshProjects()
|
||||
setStateBySongId((prev) => ({
|
||||
...prev,
|
||||
[song.id]: { status: 'ready' },
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
const error = finalJob.error || (finalJob.status === 'cancelled' ? 'Job was cancelled' : 'Conversion failed')
|
||||
setStateBySongId((prev) => ({
|
||||
...prev,
|
||||
[song.id]: { status: 'failed', error, jobId: submit.job_id },
|
||||
}))
|
||||
} catch (error) {
|
||||
setStateBySongId((prev) => ({
|
||||
...prev,
|
||||
[song.id]: {
|
||||
status: 'failed',
|
||||
error: error instanceof Error ? error.message : 'Conversion failed',
|
||||
},
|
||||
}))
|
||||
}
|
||||
}, [refreshProjects, stateBySongId])
|
||||
|
||||
const convertSongs = useCallback(async (batch: SubsonicSong[]) => {
|
||||
for (const song of batch) {
|
||||
const current = statusBySongId[song.id]?.status
|
||||
if (current === 'ready' || current === 'queued' || current === 'running') continue
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await convertSong(song)
|
||||
}
|
||||
}, [convertSong, statusBySongId])
|
||||
|
||||
return {
|
||||
statusBySongId,
|
||||
convertSong,
|
||||
convertSongs,
|
||||
refreshProjects,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { getSubsonicAlbum, getSubsonicConfig, listSubsonicAlbums, searchSubsonic } from '../api/client'
|
||||
import type { SubsonicSong } from '../types'
|
||||
|
||||
interface UseSubsonicLibraryResult {
|
||||
songs: SubsonicSong[]
|
||||
loading: boolean
|
||||
configured: boolean
|
||||
error: string | null
|
||||
refresh: () => Promise<void>
|
||||
}
|
||||
|
||||
export function useSubsonicLibrary(count = 300): UseSubsonicLibraryResult {
|
||||
const [songs, setSongs] = useState<SubsonicSong[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [configured, setConfigured] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const cfg = await getSubsonicConfig()
|
||||
if (!cfg.configured) {
|
||||
setConfigured(false)
|
||||
setSongs([])
|
||||
return
|
||||
}
|
||||
|
||||
setConfigured(true)
|
||||
|
||||
const dedupe = new Map<string, SubsonicSong>()
|
||||
|
||||
try {
|
||||
// Primary path: wildcard search (fastest when server supports it)
|
||||
const fetched = await searchSubsonic({ q: '*', count, offset: 0 })
|
||||
setSongs(fetched)
|
||||
return
|
||||
} catch {
|
||||
// Fallback path: album browse + album detail flattening
|
||||
// Some Subsonic-compatible servers reject wildcard search queries.
|
||||
}
|
||||
|
||||
const estimatedSongsPerAlbum = 10
|
||||
const albumFetchSize = Math.min(80, Math.max(20, Math.ceil(count / estimatedSongsPerAlbum)))
|
||||
const albums = await listSubsonicAlbums({ offset: 0, size: albumFetchSize })
|
||||
|
||||
const details = await Promise.all(
|
||||
albums.map((album) => getSubsonicAlbum(album.id).catch(() => null))
|
||||
)
|
||||
|
||||
for (const detail of details) {
|
||||
if (!detail) continue
|
||||
for (const song of detail.songs) {
|
||||
if (!dedupe.has(song.id)) dedupe.set(song.id, song)
|
||||
if (dedupe.size >= count) break
|
||||
}
|
||||
if (dedupe.size >= count) break
|
||||
}
|
||||
|
||||
setSongs(Array.from(dedupe.values()))
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load Subsonic library')
|
||||
setSongs([])
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [count])
|
||||
|
||||
useEffect(() => {
|
||||
refresh()
|
||||
}, [refresh])
|
||||
|
||||
return { songs, loading, configured, error, refresh }
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import { useMemo } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Heart, Loader2, Music2, Zap } from 'lucide-react'
|
||||
import { Link, useParams } from 'react-router-dom'
|
||||
import { getSubsonicAlbum } from '../api/client'
|
||||
import { useConvertStatus } from '../hooks/useConvertStatus'
|
||||
import { ALBUMS_ROUTE } from '../routes'
|
||||
|
||||
const LS_FAVORITE_ALBUMS = 'stemengine-sing-favorite-albums'
|
||||
const LS_FAVORITE_TRACKS = 'stemengine-sing-favorite-tracks'
|
||||
|
||||
function readFavorites(key: string): Set<string> {
|
||||
try {
|
||||
const raw = localStorage.getItem(key)
|
||||
if (!raw) return new Set()
|
||||
const arr = JSON.parse(raw)
|
||||
if (!Array.isArray(arr)) return new Set()
|
||||
return new Set(arr.filter((v) => typeof v === 'string'))
|
||||
} catch {
|
||||
return new Set()
|
||||
}
|
||||
}
|
||||
|
||||
function writeFavorites(key: string, set: Set<string>) {
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(Array.from(set)))
|
||||
} catch {
|
||||
// ignore localStorage write failures
|
||||
}
|
||||
}
|
||||
|
||||
export default function AlbumDetailPage() {
|
||||
const { albumId = '' } = useParams<{ albumId: string }>()
|
||||
const decodedAlbumId = useMemo(() => {
|
||||
try { return decodeURIComponent(albumId) } catch { return albumId }
|
||||
}, [albumId])
|
||||
|
||||
const { data: album, isLoading, error } = useQuery({
|
||||
queryKey: ['subsonic-album-detail', decodedAlbumId],
|
||||
queryFn: () => getSubsonicAlbum(decodedAlbumId),
|
||||
enabled: Boolean(decodedAlbumId),
|
||||
})
|
||||
|
||||
const songs = album?.songs ?? []
|
||||
const { statusBySongId, convertSong, convertSongs } = useConvertStatus(songs)
|
||||
|
||||
const albumStatus = useMemo(() => {
|
||||
if (!songs.length) return 'idle'
|
||||
const states = songs.map((song) => statusBySongId[song.id]?.status ?? 'idle')
|
||||
if (states.every((s) => s === 'ready')) return 'ready'
|
||||
if (states.some((s) => s === 'running')) return 'running'
|
||||
if (states.some((s) => s === 'queued')) return 'queued'
|
||||
if (states.some((s) => s === 'failed')) return 'failed'
|
||||
return 'idle'
|
||||
}, [songs, statusBySongId])
|
||||
|
||||
function toggleAlbumFavorite() {
|
||||
if (!album) return
|
||||
const favs = readFavorites(LS_FAVORITE_ALBUMS)
|
||||
if (favs.has(album.id)) favs.delete(album.id)
|
||||
else favs.add(album.id)
|
||||
writeFavorites(LS_FAVORITE_ALBUMS, favs)
|
||||
}
|
||||
|
||||
function isAlbumFavorite(): boolean {
|
||||
if (!album) return false
|
||||
return readFavorites(LS_FAVORITE_ALBUMS).has(album.id)
|
||||
}
|
||||
|
||||
function toggleSongFavorite(songId: string) {
|
||||
const favs = readFavorites(LS_FAVORITE_TRACKS)
|
||||
if (favs.has(songId)) favs.delete(songId)
|
||||
else favs.add(songId)
|
||||
writeFavorites(LS_FAVORITE_TRACKS, favs)
|
||||
}
|
||||
|
||||
function isSongFavorite(songId: string): boolean {
|
||||
return readFavorites(LS_FAVORITE_TRACKS).has(songId)
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return <div className="p-6 text-sm text-gray-400">Loading album…</div>
|
||||
}
|
||||
|
||||
if (error || !album) {
|
||||
return (
|
||||
<div className="p-6 space-y-3">
|
||||
<div className="text-sm text-red-300">Failed to load album.</div>
|
||||
<Link to={ALBUMS_ROUTE} className="text-sm text-brand-400 underline">Back to albums</Link>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const albumFavorite = isAlbumFavorite()
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
<div className="flex items-start gap-4">
|
||||
<div className="w-28 h-28 rounded-lg bg-gray-800 flex items-center justify-center">
|
||||
<Music2 className="w-10 h-10 text-gray-500" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<Link to={ALBUMS_ROUTE} className="text-xs text-gray-400 hover:text-gray-300">← Back to albums</Link>
|
||||
<h1 className="text-2xl font-bold truncate">{album.name}</h1>
|
||||
<p className="text-gray-400 truncate">{album.artist}</p>
|
||||
<p className="text-xs text-gray-500 mt-1">{album.songCount} songs</p>
|
||||
|
||||
<div className="mt-3 flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => void convertSongs(songs)}
|
||||
disabled={albumStatus === 'queued' || albumStatus === 'running'}
|
||||
className="inline-flex items-center gap-2 px-3 py-2 rounded bg-brand-500 hover:bg-brand-600 disabled:opacity-70 disabled:cursor-not-allowed text-sm font-medium"
|
||||
>
|
||||
{albumStatus === 'running' ? <Loader2 className="w-4 h-4 animate-spin" /> : <Zap className="w-4 h-4" />}
|
||||
{albumStatus === 'queued' && 'Queued'}
|
||||
{albumStatus === 'running' && 'Running'}
|
||||
{albumStatus === 'ready' && 'Ready'}
|
||||
{albumStatus === 'failed' && 'Retry'}
|
||||
{albumStatus === 'idle' && 'Process Album'}
|
||||
</button>
|
||||
<button
|
||||
onClick={toggleAlbumFavorite}
|
||||
className={`inline-flex items-center gap-2 px-3 py-2 rounded border text-sm ${albumFavorite ? 'border-rose-500 text-rose-400' : 'border-gray-700 text-gray-300'}`}
|
||||
>
|
||||
<Heart className={`w-4 h-4 ${albumFavorite ? 'fill-rose-500' : ''}`} />
|
||||
Favorite
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{songs.map((song, idx) => {
|
||||
const status = statusBySongId[song.id]?.status ?? 'idle'
|
||||
const favorite = isSongFavorite(song.id)
|
||||
return (
|
||||
<div key={song.id} className="flex items-center gap-3 rounded-lg border border-gray-800 bg-gray-900 p-3">
|
||||
<span className="w-6 text-xs text-gray-500 text-right">{idx + 1}</span>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="truncate font-medium">{song.title}</p>
|
||||
<p className="text-xs text-gray-500 truncate">{song.songArtist ?? song.artist}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => void convertSong(song)}
|
||||
disabled={status === 'queued' || status === 'running'}
|
||||
className="inline-flex items-center gap-2 px-3 py-2 rounded bg-brand-500 hover:bg-brand-600 disabled:opacity-70 disabled:cursor-not-allowed text-sm"
|
||||
>
|
||||
{status === 'running' ? <Loader2 className="w-4 h-4 animate-spin" /> : <Zap className="w-4 h-4" />}
|
||||
{status === 'queued' && 'Queued'}
|
||||
{status === 'running' && 'Running'}
|
||||
{status === 'ready' && 'Ready'}
|
||||
{status === 'failed' && 'Retry'}
|
||||
{status === 'idle' && 'Process'}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => toggleSongFavorite(song.id)}
|
||||
className={`inline-flex items-center gap-2 px-3 py-2 rounded border text-sm ${favorite ? 'border-rose-500 text-rose-400' : 'border-gray-700 text-gray-300'}`}
|
||||
>
|
||||
<Heart className={`w-4 h-4 ${favorite ? 'fill-rose-500' : ''}`} />
|
||||
Favorite
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,11 @@
|
||||
import { useState } from 'react'
|
||||
import { Disc3, Play, Zap, Search } from 'lucide-react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getSubsonicAlbum, getSubsonicConfig, listSubsonicAlbums } from '../api/client'
|
||||
import { useSubsonicLibrary } from '../hooks/useSubsonicLibrary'
|
||||
import { type ConvertStatus, useConvertStatus } from '../hooks/useConvertStatus'
|
||||
import { albumRoute, SETTINGS_ROUTE } from '../routes'
|
||||
|
||||
interface Album {
|
||||
id: string
|
||||
@@ -11,16 +17,69 @@ interface Album {
|
||||
|
||||
export default function AlbumsPage() {
|
||||
const [searchTerm, setSearchTerm] = useState('')
|
||||
const { songs, loading: songsLoading } = useSubsonicLibrary(800)
|
||||
const { statusBySongId, convertSongs } = useConvertStatus(songs)
|
||||
|
||||
const albums: Album[] = [
|
||||
{ id: '1', title: 'Sample Album 1', artist: 'Artist One', trackCount: 12 },
|
||||
{ id: '2', title: 'Sample Album 2', artist: 'Artist Two', trackCount: 15 },
|
||||
]
|
||||
const { data: config } = useQuery({
|
||||
queryKey: ['subsonic-config'],
|
||||
queryFn: getSubsonicConfig,
|
||||
})
|
||||
|
||||
const filteredAlbums = albums.filter(a =>
|
||||
a.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
a.artist.toLowerCase().includes(searchTerm.toLowerCase())
|
||||
)
|
||||
const { data: subsonicAlbums = [], isLoading: albumsLoading, error } = useQuery({
|
||||
queryKey: ['subsonic-albums-browse', searchTerm],
|
||||
queryFn: () => listSubsonicAlbums({ offset: 0, size: 300, query: searchTerm || undefined }),
|
||||
enabled: Boolean(config?.configured),
|
||||
})
|
||||
|
||||
const configured = Boolean(config?.configured)
|
||||
|
||||
const albums: Album[] = subsonicAlbums.map((album) => ({
|
||||
id: album.id,
|
||||
title: album.name,
|
||||
artist: album.artist,
|
||||
trackCount: album.songCount,
|
||||
coverUrl: album.coverArt,
|
||||
}))
|
||||
|
||||
const albumSongsMap = new Map<string, typeof songs>()
|
||||
songs.forEach((song) => {
|
||||
const key = `${song.albumArtist ?? song.artist}::${song.album}`.toLowerCase()
|
||||
const list = albumSongsMap.get(key) ?? []
|
||||
list.push(song)
|
||||
albumSongsMap.set(key, list)
|
||||
})
|
||||
|
||||
const albumLookupKey = (album: Album) => `${album.artist}::${album.title}`.toLowerCase()
|
||||
|
||||
function resolveAlbumStatus(albumId: string): ConvertStatus {
|
||||
const album = albums.find((a) => a.id === albumId)
|
||||
if (!album) return 'idle'
|
||||
const albumSongs = albumSongsMap.get(albumLookupKey(album)) ?? []
|
||||
if (!albumSongs.length) return 'idle'
|
||||
const statuses = albumSongs.map((song) => statusBySongId[song.id]?.status ?? 'idle')
|
||||
if (statuses.every((s) => s === 'ready')) return 'ready'
|
||||
if (statuses.some((s) => s === 'running')) return 'running'
|
||||
if (statuses.some((s) => s === 'queued')) return 'queued'
|
||||
if (statuses.some((s) => s === 'failed')) return 'failed'
|
||||
return 'idle'
|
||||
}
|
||||
|
||||
const filteredAlbums = albums
|
||||
|
||||
async function handleConvertAlbum(album: Album) {
|
||||
const localSongs = albumSongsMap.get(albumLookupKey(album)) ?? []
|
||||
if (localSongs.length > 0) {
|
||||
await convertSongs(localSongs)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const detail = await getSubsonicAlbum(album.id)
|
||||
await convertSongs(detail.songs)
|
||||
} catch {
|
||||
// ignore here; status hook will remain unchanged and user can retry
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
@@ -38,6 +97,22 @@ export default function AlbumsPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!configured && (
|
||||
<div className="rounded-lg border border-amber-700/40 bg-amber-950/20 p-4 text-amber-200">
|
||||
Subsonic is not configured yet. Open <Link to={SETTINGS_ROUTE} className="underline">Settings</Link> and save your Subsonic server details.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="rounded-lg border border-red-700/40 bg-red-950/20 p-4 text-red-200">
|
||||
{error instanceof Error ? error.message : 'Failed to load albums'}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(songsLoading || albumsLoading) && (
|
||||
<div className="text-sm text-gray-400">Loading albums from Subsonic…</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
|
||||
{filteredAlbums.map((album) => (
|
||||
<div
|
||||
@@ -51,12 +126,24 @@ export default function AlbumsPage() {
|
||||
</button>
|
||||
</div>
|
||||
<div className="p-3">
|
||||
<h3 className="font-medium truncate">{album.title}</h3>
|
||||
<h3 className="font-medium truncate">
|
||||
<Link to={albumRoute(album.id)} className="hover:text-brand-400">
|
||||
{album.title}
|
||||
</Link>
|
||||
</h3>
|
||||
<p className="text-sm text-gray-400 truncate">{album.artist}</p>
|
||||
<p className="text-xs text-gray-500 mt-1">{album.trackCount} songs</p>
|
||||
<button className="mt-2 w-full flex items-center justify-center gap-2 px-3 py-2 bg-brand-500 hover:bg-brand-600 rounded text-white text-sm font-medium transition-colors">
|
||||
<button
|
||||
onClick={() => void handleConvertAlbum(album)}
|
||||
disabled={resolveAlbumStatus(album.id) === 'queued' || resolveAlbumStatus(album.id) === 'running'}
|
||||
className="mt-2 w-full flex items-center justify-center gap-2 px-3 py-2 bg-brand-500 hover:bg-brand-600 rounded text-white text-sm font-medium transition-colors disabled:opacity-70 disabled:cursor-not-allowed"
|
||||
>
|
||||
<Zap className="w-4 h-4" />
|
||||
Convert
|
||||
{resolveAlbumStatus(album.id) === 'queued' && 'Queued'}
|
||||
{resolveAlbumStatus(album.id) === 'running' && 'Running'}
|
||||
{resolveAlbumStatus(album.id) === 'ready' && 'Ready'}
|
||||
{resolveAlbumStatus(album.id) === 'failed' && 'Retry'}
|
||||
{resolveAlbumStatus(album.id) === 'idle' && 'Convert'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,20 +1,41 @@
|
||||
import { useState } from 'react'
|
||||
import { Users, Search } from 'lucide-react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getSubsonicConfig, listSubsonicArtists } from '../api/client'
|
||||
import { SETTINGS_ROUTE } from '../routes'
|
||||
|
||||
interface Artist {
|
||||
id: string
|
||||
name: string
|
||||
albumCount: number
|
||||
trackCount: number
|
||||
}
|
||||
|
||||
export default function ArtistsPage() {
|
||||
const [searchTerm, setSearchTerm] = useState('')
|
||||
const {
|
||||
data: config,
|
||||
isLoading: configLoading,
|
||||
error: configError,
|
||||
} = useQuery({
|
||||
queryKey: ['subsonic-config'],
|
||||
queryFn: getSubsonicConfig,
|
||||
})
|
||||
|
||||
const artists: Artist[] = [
|
||||
{ id: '1', name: 'Artist One', albumCount: 3, trackCount: 25 },
|
||||
{ id: '2', name: 'Artist Two', albumCount: 2, trackCount: 18 },
|
||||
]
|
||||
const configured = Boolean(config?.configured)
|
||||
|
||||
const {
|
||||
data: artists = [],
|
||||
isLoading: artistsLoading,
|
||||
error: artistsError,
|
||||
} = useQuery<Artist[]>({
|
||||
queryKey: ['subsonic-artists-page'],
|
||||
queryFn: () => listSubsonicArtists({ offset: 0, size: 1200 }),
|
||||
enabled: configured,
|
||||
})
|
||||
|
||||
const loading = configLoading || artistsLoading
|
||||
const error = (artistsError ?? configError) as Error | null
|
||||
|
||||
const filteredArtists = artists.filter(a =>
|
||||
a.name.toLowerCase().includes(searchTerm.toLowerCase())
|
||||
@@ -36,6 +57,22 @@ export default function ArtistsPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!configured && (
|
||||
<div className="rounded-lg border border-amber-700/40 bg-amber-950/20 p-4 text-amber-200">
|
||||
Subsonic is not configured yet. Open <Link to={SETTINGS_ROUTE} className="underline">Settings</Link> and save your Subsonic server details.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="rounded-lg border border-red-700/40 bg-red-950/20 p-4 text-red-200">
|
||||
{error.message || 'Failed to load artists'}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading && (
|
||||
<div className="text-sm text-gray-400">Loading artists from Subsonic…</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
|
||||
{filteredArtists.map((artist) => (
|
||||
<div
|
||||
@@ -47,7 +84,7 @@ export default function ArtistsPage() {
|
||||
</div>
|
||||
<h3 className="font-medium">{artist.name}</h3>
|
||||
<p className="text-sm text-gray-400">
|
||||
{artist.albumCount} albums • {artist.trackCount} songs
|
||||
{artist.albumCount} albums
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
|
||||
+189
-1718
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,9 @@
|
||||
import { useState } from 'react'
|
||||
import { List, Search } from 'lucide-react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getSubsonicConfig, listSubsonicPlaylists } from '../api/client'
|
||||
import { SETTINGS_ROUTE } from '../routes'
|
||||
|
||||
interface Playlist {
|
||||
id: string
|
||||
@@ -11,17 +15,50 @@ interface Playlist {
|
||||
export default function PlaylistsPage() {
|
||||
const [searchTerm, setSearchTerm] = useState('')
|
||||
|
||||
const playlists: Playlist[] = [
|
||||
{ id: '1', name: 'My Favorites', trackCount: 42, owner: 'You' },
|
||||
{ id: '2', name: 'Workout Mix', trackCount: 28, owner: 'You' },
|
||||
]
|
||||
const { data: config } = useQuery({
|
||||
queryKey: ['subsonic-config'],
|
||||
queryFn: getSubsonicConfig,
|
||||
})
|
||||
|
||||
const filteredPlaylists = playlists.filter(p =>
|
||||
const {
|
||||
data: playlists = [],
|
||||
isLoading,
|
||||
error,
|
||||
} = useQuery({
|
||||
queryKey: ['subsonic-playlists'],
|
||||
queryFn: listSubsonicPlaylists,
|
||||
enabled: !!config?.configured,
|
||||
})
|
||||
|
||||
const mappedPlaylists: Playlist[] = playlists.map((playlist) => ({
|
||||
id: playlist.id,
|
||||
name: playlist.name,
|
||||
trackCount: playlist.songCount,
|
||||
owner: playlist.owner || 'Unknown',
|
||||
}))
|
||||
|
||||
const filteredPlaylists = mappedPlaylists.filter(p =>
|
||||
p.name.toLowerCase().includes(searchTerm.toLowerCase())
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
{config && !config.configured && (
|
||||
<div className="rounded-lg border border-amber-700/40 bg-amber-950/20 p-4 text-amber-200">
|
||||
Subsonic is not configured yet. Open <Link to={SETTINGS_ROUTE} className="underline">Settings</Link> and save your Subsonic server details.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="rounded-lg border border-red-700/40 bg-red-950/20 p-4 text-red-200">
|
||||
{error instanceof Error ? error.message : 'Failed to load playlists'}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isLoading && (
|
||||
<div className="text-sm text-gray-400">Loading playlists from Subsonic…</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold mb-4">Playlists</h1>
|
||||
<div className="relative">
|
||||
|
||||
@@ -6,8 +6,9 @@ import {
|
||||
CheckCircle, XCircle, Clock, AlertCircle, ChevronDown, ChevronUp,
|
||||
ListMusic, Edit2, Check, X as XIcon, Wand2, RotateCcw, Copy, Users,
|
||||
Play, Pause, Square, Eye, EyeOff,
|
||||
FileArchive, Save,
|
||||
} from 'lucide-react'
|
||||
import { getProjectDetail, transcribeProject, abcProject, mixProject, lrcProject, lyricTranscribeProject, downloadUrl, reprocessStem, renameStem, deleteStem, getPerInstrumentModels, getTranscribeModes, getLyricModels, projectCoverArtUrl } from '../api/client'
|
||||
import { getProjectDetail, transcribeProject, abcProject, mixProject, lrcProject, lyricTranscribeProject, downloadUrl, reprocessStem, renameStem, deleteStem, getPerInstrumentModels, getTranscribeModes, getLyricModels, projectCoverArtUrl, getProjectKaraokeConfig, patchProjectKaraokeConfig, exportProjectSek } from '../api/client'
|
||||
import type { ProjectDetail as PD, Job, JobFile, ModeOption, LyricModelsPayload } from '../types'
|
||||
import DynamicMixPlayer from '../components/DynamicMixPlayer'
|
||||
import { publishProjectInvalidated } from '../utils/crossTab'
|
||||
@@ -2627,6 +2628,199 @@ function LyricsSection({
|
||||
)
|
||||
}
|
||||
|
||||
function KaraokePackagingSection({
|
||||
project,
|
||||
onAction,
|
||||
}: {
|
||||
project: PD
|
||||
onAction: () => void
|
||||
}) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [packaging, setPackaging] = useState(false)
|
||||
const [err, setErr] = useState<string | null>(null)
|
||||
const [info, setInfo] = useState<string | null>(null)
|
||||
|
||||
const stemNames = useMemo(() => {
|
||||
const stems = project.sep_job.files
|
||||
.filter((f) => f.type === 'stem')
|
||||
.map((f) => (f.stem ?? f.name.replace(/\.[^.]+$/, '')).trim())
|
||||
.filter(Boolean)
|
||||
return ['source', ...stems]
|
||||
}, [project.sep_job.files])
|
||||
|
||||
const [videoSource, setVideoSource] = useState('')
|
||||
const [referenceTrack, setReferenceTrack] = useState('source')
|
||||
const [includeVideo, setIncludeVideo] = useState(true)
|
||||
const [packageName, setPackageName] = useState(project.name)
|
||||
const [lastSekPath, setLastSekPath] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
async function loadConfig() {
|
||||
setBusy(true)
|
||||
setErr(null)
|
||||
try {
|
||||
const res = await getProjectKaraokeConfig(project.id)
|
||||
if (cancelled) return
|
||||
const cfg = res.config
|
||||
setVideoSource(cfg.video_source || '')
|
||||
setReferenceTrack(cfg.sync_reference_track || 'source')
|
||||
setIncludeVideo(cfg.include_video !== false)
|
||||
} catch (e: unknown) {
|
||||
if (cancelled) return
|
||||
setErr(e instanceof Error ? e.message : String(e))
|
||||
} finally {
|
||||
if (!cancelled) setBusy(false)
|
||||
}
|
||||
}
|
||||
loadConfig()
|
||||
return () => { cancelled = true }
|
||||
}, [project.id])
|
||||
|
||||
useEffect(() => {
|
||||
if (!stemNames.includes(referenceTrack)) {
|
||||
setReferenceTrack(stemNames[0] ?? 'source')
|
||||
}
|
||||
}, [stemNames, referenceTrack])
|
||||
|
||||
async function saveConfig() {
|
||||
setErr(null)
|
||||
setInfo(null)
|
||||
setBusy(true)
|
||||
try {
|
||||
await patchProjectKaraokeConfig(project.id, {
|
||||
video_source: videoSource.trim(),
|
||||
include_video: includeVideo,
|
||||
sync_reference_track: referenceTrack,
|
||||
})
|
||||
setInfo('Saved package config.')
|
||||
onAction()
|
||||
} catch (e: unknown) {
|
||||
setErr(e instanceof Error ? e.message : String(e))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function packageSek() {
|
||||
setErr(null)
|
||||
setInfo(null)
|
||||
setPackaging(true)
|
||||
try {
|
||||
const res = await exportProjectSek(project.id, {
|
||||
packageName: packageName.trim() || project.name,
|
||||
includeVideo,
|
||||
videoSource: videoSource.trim() || undefined,
|
||||
syncReferenceTrack: referenceTrack,
|
||||
autoSync: true,
|
||||
})
|
||||
setLastSekPath(res.sek_path)
|
||||
const warningCount = res.warnings?.length ?? 0
|
||||
const syncText = res.auto_sync_applied && res.auto_sync_offset_seconds != null
|
||||
? ` Auto-sync ${res.auto_sync_reference_track}: ${res.auto_sync_offset_seconds.toFixed(3)}s.`
|
||||
: ''
|
||||
setInfo(
|
||||
warningCount > 0
|
||||
? `Packaged ${res.package_name} (${warningCount} warning${warningCount > 1 ? 's' : ''}).${syncText}`
|
||||
: `Packaged ${res.package_name}.${syncText}`
|
||||
)
|
||||
onAction()
|
||||
} catch (e: unknown) {
|
||||
setErr(e instanceof Error ? e.message : String(e))
|
||||
} finally {
|
||||
setPackaging(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="space-y-3">
|
||||
<button
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className="w-full flex items-center justify-between rounded-xl border ui-border ui-surface px-4 py-3"
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<FileArchive className="w-4 h-4 text-indigo-500" />
|
||||
<div className="text-left min-w-0">
|
||||
<p className="text-sm font-semibold ui-text truncate">Karaoke Packaging (.sek)</p>
|
||||
<p className="text-xs ui-text-muted truncate">Link video and package. Sync offset runs automatically.</p>
|
||||
</div>
|
||||
</div>
|
||||
{open ? <ChevronUp className="w-4 h-4 ui-text-muted" /> : <ChevronDown className="w-4 h-4 ui-text-muted" />}
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<div className="rounded-xl border ui-border ui-surface p-4 space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
<label className="space-y-1 block md:col-span-2">
|
||||
<span className="text-xs ui-text-muted uppercase tracking-wider">Video Source</span>
|
||||
<input
|
||||
type="text"
|
||||
value={videoSource}
|
||||
onChange={(e) => setVideoSource(e.target.value)}
|
||||
placeholder="https://youtube.com/watch?v=... or /path/to/video.mp4"
|
||||
className="w-full rounded-lg border ui-border ui-surface-2 px-3 py-2 text-sm ui-text"
|
||||
/>
|
||||
</label>
|
||||
<label className="space-y-1 block">
|
||||
<span className="text-xs ui-text-muted uppercase tracking-wider">Sync Track</span>
|
||||
<select
|
||||
value={referenceTrack}
|
||||
onChange={(e) => setReferenceTrack(e.target.value)}
|
||||
className="w-full rounded-lg border ui-border ui-surface-2 px-3 py-2 text-sm ui-text"
|
||||
>
|
||||
{stemNames.map((name) => <option key={name} value={name}>{name}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
<label className="inline-flex items-center gap-2 text-sm ui-text md:col-span-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={includeVideo}
|
||||
onChange={(e) => setIncludeVideo(e.target.checked)}
|
||||
className="rounded border-slate-300 dark:border-gray-600"
|
||||
/>
|
||||
Include video in package (if available)
|
||||
</label>
|
||||
<label className="space-y-1 block md:col-span-2">
|
||||
<span className="text-xs ui-text-muted uppercase tracking-wider">Package Name</span>
|
||||
<input
|
||||
type="text"
|
||||
value={packageName}
|
||||
onChange={(e) => setPackageName(e.target.value)}
|
||||
placeholder="Blind Melon - Change"
|
||||
className="w-full rounded-lg border ui-border ui-surface-2 px-3 py-2 text-sm ui-text"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
onClick={saveConfig}
|
||||
disabled={busy || packaging}
|
||||
className="inline-flex items-center gap-1.5 rounded-lg border ui-border px-3 py-2 text-sm ui-text hover:border-brand-400 disabled:opacity-60"
|
||||
>
|
||||
<Save className="w-4 h-4" /> Save
|
||||
</button>
|
||||
<button
|
||||
onClick={packageSek}
|
||||
disabled={busy || packaging}
|
||||
className="inline-flex items-center gap-1.5 rounded-lg border border-fuchsia-300/60 bg-fuchsia-50 dark:bg-fuchsia-950/30 px-3 py-2 text-sm text-fuchsia-700 dark:text-fuchsia-300 hover:border-fuchsia-400 disabled:opacity-60"
|
||||
>
|
||||
{packaging ? <Loader2 className="w-4 h-4 animate-spin" /> : <FileArchive className="w-4 h-4" />} Package
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{lastSekPath && (
|
||||
<p className="text-xs ui-text-muted break-all">Last package: {lastSekPath}</p>
|
||||
)}
|
||||
{info && <p className="text-xs text-emerald-600 dark:text-emerald-400">{info}</p>}
|
||||
{err && <p className="text-xs text-red-500 break-all">{err}</p>}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Main ProjectDetail page ─────────────────────────────────────────────────
|
||||
|
||||
interface Props {
|
||||
@@ -2746,6 +2940,14 @@ export default function ProjectDetail({ id, onDelete }: Props) {
|
||||
onAction={invalidate}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 6 — Karaoke Packaging */}
|
||||
<div className="pt-6">
|
||||
<KaraokePackagingSection
|
||||
project={project}
|
||||
onAction={invalidate}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
Sun, Moon, Monitor, Wrench, FileText, Tag, ShieldCheck, Ghost, Zap, Scissors,
|
||||
Eye, EyeOff, ArrowUp, ArrowDown, Settings2, Workflow, Plus, Music2, Mic2, AlignLeft,
|
||||
Save, FolderOpen, BookmarkPlus,
|
||||
FileArchive,
|
||||
} from 'lucide-react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useTheme } from '../context/ThemeContext'
|
||||
@@ -1300,6 +1301,8 @@ function AutoPipelineSettings() {
|
||||
if (type === 'lyricsAlign') saveSteps([...steps, { type: 'lyricsAlign', timingPrecision: 'word' }])
|
||||
if (type === 'renameStem') saveSteps([...steps, { type: 'renameStem', fromStem: 'vocals', toStem: 'leading' }])
|
||||
if (type === 'deleteStem') saveSteps([...steps, { type: 'deleteStem', stem: 'instrumental' }])
|
||||
if (type === 'karaokeMugen') saveSteps([...steps, { type: 'karaokeMugen', defaultTitleLang: 'eng', repository: 'stemengine.local' }])
|
||||
if (type === 'sekPackage') saveSteps([...steps, { type: 'sekPackage', packageName: '', includeVideo: true }])
|
||||
}
|
||||
|
||||
function saveInstrumentModels(next: Record<string, string>) {
|
||||
@@ -1547,6 +1550,8 @@ function AutoPipelineSettings() {
|
||||
{step.type === 'lyricsAlign' && <BookmarkPlus className="w-4 h-4 text-teal-500 shrink-0" />}
|
||||
{step.type === 'renameStem' && <Tag className="w-4 h-4 text-amber-500 shrink-0" />}
|
||||
{step.type === 'deleteStem' && <Trash2 className="w-4 h-4 text-rose-500 shrink-0" />}
|
||||
{step.type === 'karaokeMugen' && <FileArchive className="w-4 h-4 text-fuchsia-500 shrink-0" />}
|
||||
{step.type === 'sekPackage' && <FileArchive className="w-4 h-4 text-indigo-500 shrink-0" />}
|
||||
<span className="flex-1 text-sm font-medium text-slate-700 dark:text-gray-200 truncate">
|
||||
{stepLabel(step)}
|
||||
</span>
|
||||
@@ -1840,6 +1845,61 @@ function AutoPipelineSettings() {
|
||||
</p>
|
||||
</label>
|
||||
)}
|
||||
|
||||
{step.type === 'karaokeMugen' && (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
<label className="space-y-1 block">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Default Title Language</span>
|
||||
<input
|
||||
type="text"
|
||||
value={step.defaultTitleLang ?? 'eng'}
|
||||
onChange={e => patchStep(idx, { defaultTitleLang: e.target.value } as Partial<AutoStep>)}
|
||||
placeholder="eng"
|
||||
className={AP_SELECT}
|
||||
/>
|
||||
</label>
|
||||
<label className="space-y-1 block">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Repository</span>
|
||||
<input
|
||||
type="text"
|
||||
value={step.repository ?? 'stemengine.local'}
|
||||
onChange={e => patchStep(idx, { repository: e.target.value } as Partial<AutoStep>)}
|
||||
placeholder="stemengine.local"
|
||||
className={AP_SELECT}
|
||||
/>
|
||||
</label>
|
||||
<p className="md:col-span-2 text-xs text-slate-400 dark:text-gray-500 mt-1">
|
||||
Creates <code>.kara.json</code> package scaffolding under the project export folder and copies detected media/lyrics files.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step.type === 'sekPackage' && (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
<label className="space-y-1 block md:col-span-2">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Package Name (optional)</span>
|
||||
<input
|
||||
type="text"
|
||||
value={step.packageName ?? ''}
|
||||
onChange={e => patchStep(idx, { packageName: e.target.value } as Partial<AutoStep>)}
|
||||
placeholder="Blind Melon - Change"
|
||||
className={AP_SELECT}
|
||||
/>
|
||||
</label>
|
||||
<label className="md:col-span-2 inline-flex items-center gap-2 text-sm text-slate-700 dark:text-gray-300">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={step.includeVideo ?? true}
|
||||
onChange={e => patchStep(idx, { includeVideo: e.target.checked } as Partial<AutoStep>)}
|
||||
className="rounded border-slate-300 dark:border-gray-600"
|
||||
/>
|
||||
Include video if one is available
|
||||
</label>
|
||||
<p className="md:col-span-2 text-xs text-slate-400 dark:text-gray-500 mt-1">
|
||||
Creates a single <code>.sek</code> package containing all stems, a required <code>.elrc</code> file, and optional video.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
@@ -1916,6 +1976,26 @@ function AutoPipelineSettings() {
|
||||
<p className="text-xs text-slate-500 dark:text-gray-500">Remove a stem you do not want to keep</p>
|
||||
</div>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => addStep('karaokeMugen')}
|
||||
className="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-left hover:bg-slate-50 dark:hover:bg-gray-800 transition-colors border-t border-slate-100 dark:border-gray-800"
|
||||
>
|
||||
<FileArchive className="w-4 h-4 text-fuchsia-500 shrink-0" />
|
||||
<div>
|
||||
<p className="font-medium text-slate-800 dark:text-gray-100">Export Karaoke Mugen Package</p>
|
||||
<p className="text-xs text-slate-500 dark:text-gray-500">Generate KM-compatible .kara.json scaffolding + media/lyrics copy</p>
|
||||
</div>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => addStep('sekPackage')}
|
||||
className="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-left hover:bg-slate-50 dark:hover:bg-gray-800 transition-colors border-t border-slate-100 dark:border-gray-800"
|
||||
>
|
||||
<FileArchive className="w-4 h-4 text-indigo-500 shrink-0" />
|
||||
<div>
|
||||
<p className="font-medium text-slate-800 dark:text-gray-100">Export StemEngine .sek Package</p>
|
||||
<p className="text-xs text-slate-500 dark:text-gray-500">Bundle stems + .elrc + optional video into one .sek file</p>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -2303,6 +2383,12 @@ function IntegrationsSettings() {
|
||||
const [separatorStatus, setSeparatorStatus] = useState<'idle' | 'saved' | 'error'>('idle')
|
||||
const [separatorStatusText, setSeparatorStatusText] = useState('')
|
||||
|
||||
const [karaokeSourceMode, setKaraokeSourceMode] = useState<'projects' | 'sek-folder'>('sek-folder')
|
||||
const [karaokeSekFolderInput, setKaraokeSekFolderInput] = useState('')
|
||||
const [savingKaraokeRuntime, setSavingKaraokeRuntime] = useState(false)
|
||||
const [karaokeRuntimeStatus, setKaraokeRuntimeStatus] = useState<'idle' | 'saved' | 'error'>('idle')
|
||||
const [karaokeRuntimeStatusText, setKaraokeRuntimeStatusText] = useState('')
|
||||
|
||||
const [hfTokenSet, setHfTokenSet] = useState<boolean>(false)
|
||||
const [hfTokenInput, setHfTokenInput] = useState('')
|
||||
const [showToken, setShowToken] = useState(false)
|
||||
@@ -2321,10 +2407,37 @@ function IntegrationsSettings() {
|
||||
setSeparatorAddressInput(savedAddress)
|
||||
setSeparatorConfigured(Boolean(savedAddress))
|
||||
|
||||
api.getAppSettings().then((s) => setHfTokenSet(s.hf_token_set)).catch(() => {})
|
||||
api.getAppSettings().then((s) => {
|
||||
setHfTokenSet(s.hf_token_set)
|
||||
setKaraokeSourceMode((s.karaoke_source_mode ?? 'sek-folder') as 'projects' | 'sek-folder')
|
||||
setKaraokeSekFolderInput(s.karaoke_sek_folder ?? '')
|
||||
}).catch(() => {})
|
||||
setAdminTokenSet(Boolean(api.getAdminToken()))
|
||||
}, [])
|
||||
|
||||
async function handleSaveKaraokeRuntime() {
|
||||
setSavingKaraokeRuntime(true)
|
||||
setKaraokeRuntimeStatus('idle')
|
||||
setKaraokeRuntimeStatusText('')
|
||||
try {
|
||||
await api.patchAppSettings({
|
||||
karaoke_source_mode: karaokeSourceMode,
|
||||
karaoke_sek_folder: karaokeSekFolderInput.trim(),
|
||||
})
|
||||
setKaraokeRuntimeStatus('saved')
|
||||
setKaraokeRuntimeStatusText(
|
||||
karaokeSourceMode === 'sek-folder'
|
||||
? 'Saved. Karaoke will default to SEK folder mode.'
|
||||
: 'Saved. Karaoke will default to project-linked mode.'
|
||||
)
|
||||
} catch (error: any) {
|
||||
setKaraokeRuntimeStatus('error')
|
||||
setKaraokeRuntimeStatusText(error?.message || 'Failed to save karaoke runtime settings.')
|
||||
} finally {
|
||||
setSavingKaraokeRuntime(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSaveSeparatorAddress() {
|
||||
setSavingSeparatorAddress(true)
|
||||
setSeparatorStatus('idle')
|
||||
@@ -2526,6 +2639,68 @@ function IntegrationsSettings() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* HuggingFace Token */}
|
||||
<div className="space-y-3 pt-2 border-t border-slate-200 dark:border-gray-700">
|
||||
<div className="flex items-center gap-2">
|
||||
<Music2 className="w-4 h-4 text-slate-400 dark:text-gray-500" />
|
||||
<label className="text-sm font-medium text-slate-700 dark:text-gray-300">
|
||||
Karaoke Runtime Source
|
||||
</label>
|
||||
</div>
|
||||
<p className="text-xs text-slate-500 dark:text-gray-400">
|
||||
Choose whether SingUI karaoke defaults to project-linked content or scans a folder of <span className="font-mono">.sek</span> packages.
|
||||
</p>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
<label className="space-y-1 block">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Default source mode</span>
|
||||
<select
|
||||
value={karaokeSourceMode}
|
||||
onChange={(e) => setKaraokeSourceMode(e.target.value as 'projects' | 'sek-folder')}
|
||||
className="w-full px-3 py-2 text-sm rounded-lg border border-slate-200 dark:border-gray-700 bg-white dark:bg-gray-800 text-slate-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400"
|
||||
>
|
||||
<option value="sek-folder">SEK Folder (recommended)</option>
|
||||
<option value="projects">Project-linked (fallback)</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label className="space-y-1 block md:col-span-1">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">SEK folder path</span>
|
||||
<input
|
||||
type="text"
|
||||
value={karaokeSekFolderInput}
|
||||
onChange={(e) => setKaraokeSekFolderInput(e.target.value)}
|
||||
placeholder="/path/to/sek/folder"
|
||||
className="w-full px-3 py-2 text-sm rounded-lg border border-slate-200 dark:border-gray-700 bg-white dark:bg-gray-800 text-slate-900 dark:text-gray-100 placeholder-slate-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-brand-400"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={handleSaveKaraokeRuntime}
|
||||
disabled={savingKaraokeRuntime}
|
||||
className="flex items-center gap-1.5 px-4 py-2 text-sm font-medium rounded-lg bg-brand-500 hover:bg-brand-600 text-white disabled:opacity-40 transition-colors"
|
||||
>
|
||||
<Save className="w-4 h-4" />
|
||||
{savingKaraokeRuntime ? 'Saving…' : 'Save'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{karaokeRuntimeStatus === 'saved' && karaokeRuntimeStatusText && (
|
||||
<p className="flex items-center gap-1.5 text-xs text-emerald-600 dark:text-emerald-400">
|
||||
<CheckCircle className="w-3.5 h-3.5" />
|
||||
{karaokeRuntimeStatusText}
|
||||
</p>
|
||||
)}
|
||||
{karaokeRuntimeStatus === 'error' && karaokeRuntimeStatusText && (
|
||||
<p className="flex items-center gap-1.5 text-xs text-red-500 dark:text-red-400">
|
||||
<AlertCircle className="w-3.5 h-3.5" />
|
||||
{karaokeRuntimeStatusText}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* HuggingFace Token */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
|
||||
+591
-66
@@ -1,101 +1,626 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Music2, Play, Search, Loader2 } from 'lucide-react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { listProjects } from '../api/client'
|
||||
import type { Project } from '../types'
|
||||
import { KARAOKE_ROUTE } from '../routes'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Music2, Mic2, Play, Search, Loader2, Zap, Disc3, Users, ListMusic, Radio } from 'lucide-react'
|
||||
import { Link, useNavigate } from 'react-router-dom'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getAppSettings, getSubsonicAlbum, listProjects, listSekLibrary, listSubsonicAlbums, listSubsonicArtists, listSubsonicPlaylists, patchAppSettings } from '../api/client'
|
||||
import type { Project, SubsonicAlbum, SubsonicArtist, SubsonicPlaylist, SubsonicSong } from '../types'
|
||||
import { albumRoute, KARAOKE_ROUTE, SETTINGS_ROUTE, trackRoute } from '../routes'
|
||||
import { useSubsonicLibrary } from '../hooks/useSubsonicLibrary'
|
||||
import { useConvertStatus } from '../hooks/useConvertStatus'
|
||||
|
||||
// ─── helpers used by the Nightingale-style karaoke track list ───────────────
|
||||
|
||||
function normalizeForMatch(value?: string): string {
|
||||
return (value || '').toLowerCase().replace(/\.[a-z0-9]+$/i, '').replace(/\s+/g, ' ').trim()
|
||||
}
|
||||
|
||||
function findProjectForSong(song: SubsonicSong, projectList: Project[]): Project | null {
|
||||
const byArtistTitle = normalizeForMatch(`${song.songArtist ?? song.artist} - ${song.title}`)
|
||||
const byTitle = normalizeForMatch(song.title)
|
||||
return (
|
||||
projectList.find((p) => {
|
||||
const name = normalizeForMatch(p.name)
|
||||
if (!name) return false
|
||||
if (name === byArtistTitle || name === byTitle) return true
|
||||
if (byArtistTitle && name.includes(byArtistTitle)) return true
|
||||
if (byTitle && name.includes(byTitle)) return true
|
||||
return false
|
||||
}) ?? null
|
||||
)
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
type SingViewMode = 'home' | 'tracks' | 'albums' | 'artists' | 'playlists' | 'karaoke'
|
||||
|
||||
export default function SingPage() {
|
||||
const navigate = useNavigate()
|
||||
const [searchTerm, setSearchTerm] = useState('')
|
||||
const [viewMode, setViewMode] = useState<SingViewMode>('home')
|
||||
const [projects, setProjects] = useState<Project[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [projectsLoading, setProjectsLoading] = useState(true)
|
||||
const [karaokeSourceMode, setKaraokeSourceMode] = useState<'projects' | 'sek-folder'>('sek-folder')
|
||||
const [sekFolderInput, setSekFolderInput] = useState('')
|
||||
const [sekPrefsSaving, setSekPrefsSaving] = useState(false)
|
||||
|
||||
const [albumActionState, setAlbumActionState] = useState<Record<string, 'idle' | 'queued' | 'running' | 'ready' | 'failed'>>({})
|
||||
const {
|
||||
songs,
|
||||
loading: libraryLoading,
|
||||
configured,
|
||||
error: libraryError,
|
||||
} = useSubsonicLibrary(400)
|
||||
const { statusBySongId, convertSong, convertSongs } = useConvertStatus(songs)
|
||||
|
||||
const { data: appSettings } = useQuery({
|
||||
queryKey: ['app-settings-sing-karaoke'],
|
||||
queryFn: getAppSettings,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (!appSettings) return
|
||||
setKaraokeSourceMode((appSettings.karaoke_source_mode ?? 'sek-folder') as 'projects' | 'sek-folder')
|
||||
setSekFolderInput(appSettings.karaoke_sek_folder ?? '')
|
||||
}, [appSettings])
|
||||
|
||||
const {
|
||||
data: sekLibrary,
|
||||
isLoading: sekLoading,
|
||||
error: sekError,
|
||||
refetch: refetchSekLibrary,
|
||||
} = useQuery({
|
||||
queryKey: ['sek-library', sekFolderInput],
|
||||
queryFn: () => listSekLibrary(sekFolderInput.trim() || undefined),
|
||||
enabled: karaokeSourceMode === 'sek-folder' && !!sekFolderInput.trim(),
|
||||
})
|
||||
|
||||
const {
|
||||
data: playlists = [],
|
||||
isLoading: playlistsLoading,
|
||||
error: playlistsError,
|
||||
} = useQuery<SubsonicPlaylist[]>({
|
||||
queryKey: ['subsonic-playlists-sing'],
|
||||
queryFn: listSubsonicPlaylists,
|
||||
enabled: configured,
|
||||
})
|
||||
|
||||
const {
|
||||
data: albums = [],
|
||||
isLoading: albumsLoading,
|
||||
error: albumsError,
|
||||
} = useQuery<SubsonicAlbum[]>({
|
||||
queryKey: ['subsonic-albums-sing'],
|
||||
queryFn: () => listSubsonicAlbums({ offset: 0, size: 400 }),
|
||||
enabled: configured,
|
||||
})
|
||||
|
||||
const {
|
||||
data: artists = [],
|
||||
isLoading: artistsLoading,
|
||||
error: artistsError,
|
||||
} = useQuery<SubsonicArtist[]>({
|
||||
queryKey: ['subsonic-artists-sing'],
|
||||
queryFn: () => listSubsonicArtists({ offset: 0, size: 600 }),
|
||||
enabled: configured,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchProjects() {
|
||||
try {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
setProjectsLoading(true)
|
||||
const data = await listProjects()
|
||||
setProjects(data)
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load projects')
|
||||
} catch {
|
||||
// non-fatal: karaoke status will show idle for unmatched songs
|
||||
} finally {
|
||||
setLoading(false)
|
||||
setProjectsLoading(false)
|
||||
}
|
||||
}
|
||||
fetchProjects()
|
||||
}, [])
|
||||
|
||||
const filteredProjects = projects.filter(p =>
|
||||
p.name.toLowerCase().includes(searchTerm.toLowerCase())
|
||||
const q = searchTerm.toLowerCase()
|
||||
|
||||
const filteredProjects = projects.filter((project) =>
|
||||
project.name.toLowerCase().includes(q)
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold mb-4">Sing - Karaoke Projects</h1>
|
||||
<p className="text-gray-400 mb-4">Browse and launch karaoke projects from StemEngine</p>
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-500" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search projects..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="w-full pl-10 pr-4 py-2 rounded-lg bg-gray-900 border border-gray-800 text-white placeholder-gray-500 focus:border-brand-500 focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
const filteredSongs = songs.filter((song) =>
|
||||
song.title.toLowerCase().includes(q)
|
||||
|| (song.songArtist ?? song.artist).toLowerCase().includes(q)
|
||||
|| song.album.toLowerCase().includes(q)
|
||||
)
|
||||
|
||||
{loading && (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-brand-500" />
|
||||
</div>
|
||||
)}
|
||||
const filteredAlbums = albums.filter((album) =>
|
||||
album.name.toLowerCase().includes(q) || album.artist.toLowerCase().includes(q)
|
||||
)
|
||||
|
||||
{error && (
|
||||
<div className="p-4 bg-red-900 border border-red-700 rounded-lg text-red-200">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
const filteredArtists = artists.filter((artist) => artist.name.toLowerCase().includes(q))
|
||||
|
||||
{!loading && !error && (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
|
||||
{filteredProjects.map((project) => (
|
||||
<div
|
||||
key={project.id}
|
||||
className="bg-gray-900 rounded-lg overflow-hidden border border-gray-800 hover:border-brand-500 hover:shadow-lg transition-all cursor-pointer group"
|
||||
onClick={() => navigate(KARAOKE_ROUTE, { state: { projectId: project.id } })}
|
||||
const filteredPlaylists = playlists.filter((playlist) =>
|
||||
playlist.name.toLowerCase().includes(q) || (playlist.owner || '').toLowerCase().includes(q)
|
||||
)
|
||||
|
||||
async function convertAlbum(albumId: string) {
|
||||
try {
|
||||
setAlbumActionState((prev) => ({ ...prev, [albumId]: 'queued' }))
|
||||
const detail = await getSubsonicAlbum(albumId)
|
||||
setAlbumActionState((prev) => ({ ...prev, [albumId]: 'running' }))
|
||||
await convertSongs(detail.songs)
|
||||
setAlbumActionState((prev) => ({ ...prev, [albumId]: 'ready' }))
|
||||
} catch {
|
||||
setAlbumActionState((prev) => ({ ...prev, [albumId]: 'failed' }))
|
||||
}
|
||||
}
|
||||
|
||||
function albumStatus(albumId: string): 'idle' | 'queued' | 'running' | 'ready' | 'failed' {
|
||||
return albumActionState[albumId] ?? 'idle'
|
||||
}
|
||||
|
||||
const modePlaceholder: Record<SingViewMode, string> = {
|
||||
home: 'Search songs, artists, albums...',
|
||||
tracks: 'Search tracks...',
|
||||
albums: 'Search albums...',
|
||||
artists: 'Search artists...',
|
||||
playlists: 'Search playlists...',
|
||||
karaoke: 'Search your library...',
|
||||
}
|
||||
|
||||
const modeButton = (mode: SingViewMode, label: string) => (
|
||||
<button
|
||||
key={mode}
|
||||
onClick={() => setViewMode(mode)}
|
||||
className={`rounded-md px-3 py-1.5 text-sm ${viewMode === mode ? 'bg-brand-500 text-white' : 'text-gray-300 hover:text-white'}`}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
)
|
||||
|
||||
const showSubsonicWarnings = viewMode !== 'karaoke'
|
||||
|
||||
const homeFeaturedSongs = filteredSongs.slice(0, 8)
|
||||
const homeFeaturedProjects = filteredProjects.slice(0, 6)
|
||||
|
||||
const isAnyLibraryLoading = libraryLoading || playlistsLoading
|
||||
|
||||
const currentModeRequiresLibrary = viewMode === 'home' || viewMode === 'tracks' || viewMode === 'albums' || viewMode === 'artists' || viewMode === 'playlists'
|
||||
|
||||
const shouldShowLibraryEmptyState = currentModeRequiresLibrary && !libraryLoading && configured && !libraryError
|
||||
|
||||
const hasLibraryContent = songs.length > 0
|
||||
|
||||
const baseSongRows = (rows: typeof filteredSongs) => (
|
||||
<div className="space-y-2">
|
||||
{rows.map((song) => (
|
||||
<div
|
||||
key={song.id}
|
||||
className="flex items-center gap-4 rounded-lg border border-gray-800 bg-gray-900 p-3"
|
||||
>
|
||||
<Music2 className="h-5 w-5 text-gray-500" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate font-medium text-white">
|
||||
<Link to={trackRoute(song.id)} className="hover:text-brand-400">
|
||||
{song.title}
|
||||
</Link>
|
||||
</p>
|
||||
<p className="truncate text-sm text-gray-400">{song.songArtist ?? song.artist} • {song.album}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => void convertSong(song)}
|
||||
disabled={statusBySongId[song.id]?.status === 'queued' || statusBySongId[song.id]?.status === 'running'}
|
||||
title={statusBySongId[song.id]?.error || 'Convert with StemEngine'}
|
||||
className="inline-flex items-center gap-2 rounded bg-brand-500 px-3 py-2 text-sm font-medium text-white hover:bg-brand-600 disabled:cursor-not-allowed disabled:opacity-70"
|
||||
>
|
||||
<Zap className="h-4 w-4" />
|
||||
{statusBySongId[song.id]?.status === 'queued' && 'Queued'}
|
||||
{statusBySongId[song.id]?.status === 'running' && 'Running'}
|
||||
{statusBySongId[song.id]?.status === 'ready' && 'Ready'}
|
||||
{statusBySongId[song.id]?.status === 'failed' && 'Retry'}
|
||||
{(!statusBySongId[song.id] || statusBySongId[song.id]?.status === 'idle') && 'Convert'}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
|
||||
const baseProjectGrid = (rows: typeof filteredProjects) => (
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||
{rows.map((project) => (
|
||||
<div
|
||||
key={project.id}
|
||||
className="group cursor-pointer overflow-hidden rounded-lg border border-gray-800 bg-gray-900 transition-all hover:border-brand-500 hover:shadow-lg"
|
||||
onClick={() => navigate(KARAOKE_ROUTE, { state: { projectId: project.id } })}
|
||||
>
|
||||
<div className="relative flex aspect-square items-center justify-center overflow-hidden bg-gray-800">
|
||||
<Music2 className="h-16 w-16 text-gray-700" />
|
||||
<button
|
||||
className="absolute inset-0 flex items-center justify-center bg-black bg-opacity-50 opacity-0 transition-opacity group-hover:opacity-100"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
navigate(KARAOKE_ROUTE, { state: { projectId: project.id } })
|
||||
}}
|
||||
>
|
||||
<div className="w-full aspect-square bg-gray-800 flex items-center justify-center relative overflow-hidden">
|
||||
<Music2 className="w-16 h-16 text-gray-700" />
|
||||
<button
|
||||
className="absolute inset-0 flex items-center justify-center bg-black bg-opacity-50 opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
navigate(KARAOKE_ROUTE, { state: { projectId: project.id } })
|
||||
}}
|
||||
>
|
||||
<Play className="w-12 h-12 text-brand-500 fill-brand-500" />
|
||||
</button>
|
||||
<Play className="h-12 w-12 fill-brand-500 text-brand-500" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="p-3">
|
||||
<h3 className="truncate font-medium">{project.name}</h3>
|
||||
<p className="truncate text-sm text-gray-400">{project.tab_label}</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
|
||||
const homeStats = [
|
||||
{ label: 'Tracks', value: songs.length, icon: Music2 },
|
||||
{ label: 'Albums', value: albums.length, icon: Disc3 },
|
||||
{ label: 'Artists', value: artists.length, icon: Users },
|
||||
{ label: 'Karaoke Projects', value: projects.length, icon: Radio },
|
||||
]
|
||||
|
||||
const playlistErrorMessage = playlistsError instanceof Error ? playlistsError.message : null
|
||||
const albumsErrorMessage = albumsError instanceof Error ? albumsError.message : null
|
||||
const artistsErrorMessage = artistsError instanceof Error ? artistsError.message : null
|
||||
const combinedLibraryError = libraryError || playlistErrorMessage || albumsErrorMessage || artistsErrorMessage
|
||||
|
||||
const showLibraryLoading = showSubsonicWarnings && (isAnyLibraryLoading || albumsLoading || artistsLoading)
|
||||
|
||||
const showLibraryConfigWarning = showSubsonicWarnings && !configured
|
||||
|
||||
const showLibraryError = showSubsonicWarnings && Boolean(combinedLibraryError)
|
||||
|
||||
const renderModeContent = () => {
|
||||
if (viewMode === 'karaoke') {
|
||||
const sourceSwitch = (
|
||||
<div className="mb-3 flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
onClick={() => setKaraokeSourceMode('projects')}
|
||||
className={`rounded-md px-3 py-1.5 text-xs ${karaokeSourceMode === 'projects' ? 'bg-brand-500 text-white' : 'bg-gray-900 text-gray-300 border border-gray-800'}`}
|
||||
>
|
||||
Project-linked
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setKaraokeSourceMode('sek-folder')}
|
||||
className={`rounded-md px-3 py-1.5 text-xs ${karaokeSourceMode === 'sek-folder' ? 'bg-brand-500 text-white' : 'bg-gray-900 text-gray-300 border border-gray-800'}`}
|
||||
>
|
||||
SEK Folder
|
||||
</button>
|
||||
<button
|
||||
onClick={async () => {
|
||||
try {
|
||||
setSekPrefsSaving(true)
|
||||
await patchAppSettings({
|
||||
karaoke_source_mode: karaokeSourceMode,
|
||||
karaoke_sek_folder: sekFolderInput,
|
||||
})
|
||||
} finally {
|
||||
setSekPrefsSaving(false)
|
||||
}
|
||||
}}
|
||||
className="rounded-md border border-gray-700 px-3 py-1.5 text-xs text-gray-300 hover:text-white disabled:opacity-60"
|
||||
disabled={sekPrefsSaving}
|
||||
>
|
||||
{sekPrefsSaving ? 'Saving…' : 'Save source'}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
|
||||
if (karaokeSourceMode === 'sek-folder') {
|
||||
const sekRows = (sekLibrary?.packages ?? []).filter((p) =>
|
||||
p.title.toLowerCase().includes(q) || p.filename.toLowerCase().includes(q)
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{sourceSwitch}
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={sekFolderInput}
|
||||
onChange={(e) => setSekFolderInput(e.target.value)}
|
||||
placeholder="/path/to/sek/folder"
|
||||
className="w-full rounded-lg border border-gray-800 bg-gray-900 px-3 py-2 text-sm text-white placeholder-gray-500"
|
||||
/>
|
||||
<button
|
||||
onClick={() => void refetchSekLibrary()}
|
||||
className="rounded-lg border border-gray-700 px-3 py-2 text-xs text-gray-300 hover:text-white"
|
||||
>
|
||||
Refresh
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{!sekFolderInput.trim() && (
|
||||
<div className="rounded-lg border border-amber-700/40 bg-amber-950/20 p-3 text-xs text-amber-200">
|
||||
Set a SEK folder path, then click Refresh.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{sekError && (
|
||||
<div className="rounded-lg border border-red-700/40 bg-red-950/20 p-3 text-xs text-red-200">
|
||||
{sekError instanceof Error ? sekError.message : 'Failed to load SEK library.'}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{sekLoading && (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-brand-500" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!sekLoading && sekRows.length === 0 && sekFolderInput.trim() && !sekError && (
|
||||
<div className="py-10 text-center text-sm text-gray-400">No .sek packages found.</div>
|
||||
)}
|
||||
|
||||
{!sekLoading && sekRows.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
{sekRows.map((pkg) => (
|
||||
<div key={pkg.id} className="flex items-center gap-3 rounded-lg border border-gray-800 bg-gray-900 p-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-medium text-white">{pkg.title}</p>
|
||||
<p className="truncate text-xs text-gray-400">{pkg.filename} · {pkg.stem_count} stems{pkg.has_video ? ' · video' : ''}</p>
|
||||
{!pkg.valid && <p className="text-[10px] text-red-400 mt-1">Invalid package</p>}
|
||||
{pkg.warnings?.length > 0 && <p className="text-[10px] text-amber-300 mt-1 truncate">{pkg.warnings[0]}</p>}
|
||||
</div>
|
||||
<button
|
||||
disabled={!pkg.valid}
|
||||
onClick={() => navigate(KARAOKE_ROUTE, { state: { sekPackageId: pkg.id, sekFolder: sekFolderInput.trim() } })}
|
||||
className="inline-flex items-center gap-1.5 rounded bg-brand-500 px-3 py-1.5 text-xs font-medium text-white hover:bg-brand-600 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<Mic2 className="h-3.5 w-3.5" /> Sing
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!configured) {
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{sourceSwitch}
|
||||
<div className="py-12 text-center">
|
||||
<Music2 className="mx-auto mb-3 h-12 w-12 text-gray-700" />
|
||||
<p className="text-gray-400 mb-2">Subsonic library not configured.</p>
|
||||
<Link to={SETTINGS_ROUTE} className="text-sm text-brand-400 hover:underline">Open Settings</Link>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const karaokeRows = filteredSongs.map((song) => ({
|
||||
song,
|
||||
status: statusBySongId[song.id]?.status ?? 'idle',
|
||||
linked: findProjectForSong(song, projects),
|
||||
}))
|
||||
|
||||
if (karaokeRows.length === 0 && !libraryLoading) {
|
||||
return (
|
||||
<div className="py-12 text-center">
|
||||
<Music2 className="mx-auto mb-3 h-12 w-12 text-gray-700" />
|
||||
<p className="text-gray-400">No tracks in your library yet.</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{sourceSwitch}
|
||||
{karaokeRows.map(({ song, status, linked }) => {
|
||||
const isPreparing = status === 'queued' || status === 'running'
|
||||
const isReady = status === 'ready' && !!linked
|
||||
return (
|
||||
<div
|
||||
key={song.id}
|
||||
className="flex items-center gap-3 rounded-lg border border-gray-800 bg-gray-900 p-3"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-medium text-white">{song.title}</p>
|
||||
<p className="truncate text-xs text-gray-400">
|
||||
{song.songArtist ?? song.artist}{song.album ? ` · ${song.album}` : ''}
|
||||
</p>
|
||||
<span className={`mt-1 inline-flex items-center gap-1 text-[10px] font-medium ${
|
||||
status === 'ready' ? 'text-emerald-400' :
|
||||
status === 'running' ? 'text-sky-400' :
|
||||
status === 'queued' ? 'text-yellow-400' :
|
||||
status === 'failed' ? 'text-red-400' : 'text-gray-600'
|
||||
}`}>
|
||||
{status === 'ready' && '● Ready'}
|
||||
{status === 'running' && '● Processing'}
|
||||
{status === 'queued' && '● Queued'}
|
||||
{status === 'failed' && '● Failed'}
|
||||
{status === 'idle' && '○ Not prepared'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
{isPreparing && (
|
||||
<span className="inline-flex items-center gap-1.5 text-xs text-gray-400">
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
{status === 'queued' ? 'Queued' : 'Processing…'}
|
||||
</span>
|
||||
)}
|
||||
{!isPreparing && !isReady && (
|
||||
<button
|
||||
onClick={() => void convertSong(song)}
|
||||
className="inline-flex items-center gap-1.5 rounded border border-brand-500/50 px-2.5 py-1.5 text-xs font-medium text-brand-400 hover:bg-brand-500/10"
|
||||
>
|
||||
<Zap className="h-3.5 w-3.5" />
|
||||
{status === 'failed' ? 'Retry' : 'Prepare'}
|
||||
</button>
|
||||
)}
|
||||
{isReady && (
|
||||
<button
|
||||
onClick={() => navigate(KARAOKE_ROUTE, { state: { projectId: linked!.id } })}
|
||||
className="inline-flex items-center gap-1.5 rounded bg-brand-500 px-3 py-1.5 text-xs font-medium text-white hover:bg-brand-600"
|
||||
>
|
||||
<Mic2 className="h-3.5 w-3.5" />
|
||||
Sing
|
||||
</button>
|
||||
)}
|
||||
{status === 'ready' && !linked && projectsLoading && (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-gray-500" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (viewMode === 'tracks') return baseSongRows(filteredSongs)
|
||||
|
||||
if (viewMode === 'albums') {
|
||||
return (
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||
{filteredAlbums.map((album) => (
|
||||
<div key={album.id} className="overflow-hidden rounded-lg border border-gray-800 bg-gray-900">
|
||||
<div className="flex aspect-square items-center justify-center bg-gray-800">
|
||||
<Disc3 className="h-16 w-16 text-gray-700" />
|
||||
</div>
|
||||
<div className="p-3">
|
||||
<h3 className="font-medium truncate">{project.name}</h3>
|
||||
<p className="text-sm text-gray-400 truncate">{project.tab_label}</p>
|
||||
<h3 className="truncate font-medium">
|
||||
<Link to={albumRoute(album.id)} className="hover:text-brand-400">
|
||||
{album.name}
|
||||
</Link>
|
||||
</h3>
|
||||
<p className="truncate text-sm text-gray-400">{album.artist}</p>
|
||||
<p className="mt-1 text-xs text-gray-500">{album.songCount} songs</p>
|
||||
<button
|
||||
onClick={() => void convertAlbum(album.id)}
|
||||
disabled={albumStatus(album.id) === 'queued' || albumStatus(album.id) === 'running'}
|
||||
className="mt-2 inline-flex w-full items-center justify-center gap-2 rounded bg-brand-500 px-3 py-2 text-sm font-medium text-white hover:bg-brand-600 disabled:cursor-not-allowed disabled:opacity-70"
|
||||
>
|
||||
<Zap className="h-4 w-4" />
|
||||
{albumStatus(album.id) === 'queued' && 'Queued'}
|
||||
{albumStatus(album.id) === 'running' && 'Running'}
|
||||
{albumStatus(album.id) === 'ready' && 'Ready'}
|
||||
{albumStatus(album.id) === 'failed' && 'Retry'}
|
||||
{albumStatus(album.id) === 'idle' && 'Convert'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
)
|
||||
}
|
||||
|
||||
{!loading && !error && filteredProjects.length === 0 && (
|
||||
<div className="text-center py-12">
|
||||
<Music2 className="w-12 h-12 text-gray-700 mx-auto mb-3" />
|
||||
<p className="text-gray-400">{projects.length === 0 ? 'No projects available' : 'No projects match your search'}</p>
|
||||
if (viewMode === 'artists') {
|
||||
return (
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||
{filteredArtists.map((artist) => (
|
||||
<div key={artist.id} className="rounded-lg border border-gray-800 bg-gray-900 p-4 text-center">
|
||||
<div className="mx-auto mb-3 flex h-20 w-20 items-center justify-center rounded-full bg-gray-800">
|
||||
<Users className="h-10 w-10 text-gray-700" />
|
||||
</div>
|
||||
<h3 className="font-medium">{artist.name}</h3>
|
||||
<p className="text-sm text-gray-400">{artist.albumCount} albums</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (viewMode === 'playlists') {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{filteredPlaylists.map((playlist) => (
|
||||
<div key={playlist.id} className="flex items-center gap-4 rounded-lg border border-gray-800 bg-gray-900 p-4">
|
||||
<ListMusic className="h-6 w-6 shrink-0 text-gray-500" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<h3 className="truncate font-medium">{playlist.name}</h3>
|
||||
<p className="text-sm text-gray-400">{playlist.songCount} songs</p>
|
||||
</div>
|
||||
<span className="text-sm text-gray-500">{playlist.owner || 'Unknown'}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="grid grid-cols-1 gap-3 md:grid-cols-2 lg:grid-cols-4">
|
||||
{homeStats.map(({ label, value, icon: Icon }) => (
|
||||
<div key={label} className="rounded-lg border border-gray-800 bg-gray-900 p-4">
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<span className="text-sm text-gray-400">{label}</span>
|
||||
<Icon className="h-4 w-4 text-gray-500" />
|
||||
</div>
|
||||
<p className="text-2xl font-bold">{value}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2 className="mb-3 text-sm font-semibold uppercase tracking-wide text-gray-300">Featured Tracks</h2>
|
||||
{baseSongRows(homeFeaturedSongs)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2 className="mb-3 text-sm font-semibold uppercase tracking-wide text-gray-300">Karaoke Projects</h2>
|
||||
{baseProjectGrid(homeFeaturedProjects)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 p-6">
|
||||
<div>
|
||||
<h1 className="mb-4 text-3xl font-bold">Sing</h1>
|
||||
<p className="mb-4 text-gray-400">Standard music-player browsing with integrated karaoke conversion and launch.</p>
|
||||
|
||||
<div className="mb-4 inline-flex flex-wrap rounded-lg border border-gray-800 bg-gray-900 p-1">
|
||||
{modeButton('home', 'Home')}
|
||||
{modeButton('tracks', 'Tracks')}
|
||||
{modeButton('albums', 'Albums')}
|
||||
{modeButton('artists', 'Artists')}
|
||||
{modeButton('playlists', 'Playlists')}
|
||||
{modeButton('karaoke', 'Karaoke')}
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 h-5 w-5 -translate-y-1/2 transform text-gray-500" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder={modePlaceholder[viewMode]}
|
||||
value={searchTerm}
|
||||
onChange={(event) => setSearchTerm(event.target.value)}
|
||||
className="w-full rounded-lg border border-gray-800 bg-gray-900 py-2 pl-10 pr-4 text-white placeholder-gray-500 focus:border-brand-500 focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showLibraryConfigWarning && (
|
||||
<div className="rounded-lg border border-amber-700/40 bg-amber-950/20 p-4 text-amber-200">
|
||||
Subsonic is not configured yet. Open <Link to={SETTINGS_ROUTE} className="underline">Settings</Link> and save your Subsonic server details.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showLibraryError && (
|
||||
<div className="rounded-lg border border-red-700/40 bg-red-950/20 p-4 text-red-200">
|
||||
{combinedLibraryError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showLibraryLoading && (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-brand-500" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!showLibraryLoading && renderModeContent()}
|
||||
|
||||
{shouldShowLibraryEmptyState && !hasLibraryContent && (
|
||||
<div className="py-12 text-center">
|
||||
<Music2 className="mx-auto mb-3 h-12 w-12 text-gray-700" />
|
||||
<p className="text-gray-400">No Subsonic songs available.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { useMemo } from 'react'
|
||||
import { Heart, Loader2, Zap } from 'lucide-react'
|
||||
import { Link, useParams } from 'react-router-dom'
|
||||
import { useSubsonicLibrary } from '../hooks/useSubsonicLibrary'
|
||||
import { useConvertStatus } from '../hooks/useConvertStatus'
|
||||
import { TRACKS_ROUTE } from '../routes'
|
||||
|
||||
const LS_FAVORITE_TRACKS = 'stemengine-sing-favorite-tracks'
|
||||
|
||||
function readFavorites(): Set<string> {
|
||||
try {
|
||||
const raw = localStorage.getItem(LS_FAVORITE_TRACKS)
|
||||
if (!raw) return new Set()
|
||||
const arr = JSON.parse(raw)
|
||||
if (!Array.isArray(arr)) return new Set()
|
||||
return new Set(arr.filter((v) => typeof v === 'string'))
|
||||
} catch {
|
||||
return new Set()
|
||||
}
|
||||
}
|
||||
|
||||
function writeFavorites(set: Set<string>) {
|
||||
try {
|
||||
localStorage.setItem(LS_FAVORITE_TRACKS, JSON.stringify(Array.from(set)))
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
export default function TrackDetailPage() {
|
||||
const { trackId = '' } = useParams<{ trackId: string }>()
|
||||
const decodedTrackId = useMemo(() => {
|
||||
try { return decodeURIComponent(trackId) } catch { return trackId }
|
||||
}, [trackId])
|
||||
|
||||
const { songs, loading } = useSubsonicLibrary(1000)
|
||||
const song = songs.find((s) => s.id === decodedTrackId)
|
||||
const { statusBySongId, convertSong } = useConvertStatus(song ? [song] : [])
|
||||
|
||||
function toggleFavorite() {
|
||||
if (!song) return
|
||||
const favs = readFavorites()
|
||||
if (favs.has(song.id)) favs.delete(song.id)
|
||||
else favs.add(song.id)
|
||||
writeFavorites(favs)
|
||||
}
|
||||
|
||||
function isFavorite(): boolean {
|
||||
if (!song) return false
|
||||
return readFavorites().has(song.id)
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return <div className="p-6 text-sm text-gray-400">Loading track…</div>
|
||||
}
|
||||
|
||||
if (!song) {
|
||||
return (
|
||||
<div className="p-6 space-y-3">
|
||||
<div className="text-sm text-red-300">Track not found in current library window.</div>
|
||||
<Link to={TRACKS_ROUTE} className="text-sm text-brand-400 underline">Back to tracks</Link>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const favorite = isFavorite()
|
||||
const status = statusBySongId[song.id]?.status ?? 'idle'
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
<div>
|
||||
<Link to={TRACKS_ROUTE} className="text-xs text-gray-400 hover:text-gray-300">← Back to tracks</Link>
|
||||
<h1 className="text-2xl font-bold mt-1">{song.title}</h1>
|
||||
<p className="text-gray-400">{song.songArtist ?? song.artist} • {song.album}</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => void convertSong(song)}
|
||||
disabled={status === 'queued' || status === 'running'}
|
||||
className="inline-flex items-center gap-2 px-3 py-2 rounded bg-brand-500 hover:bg-brand-600 disabled:opacity-70 disabled:cursor-not-allowed text-sm font-medium"
|
||||
>
|
||||
{status === 'running' ? <Loader2 className="w-4 h-4 animate-spin" /> : <Zap className="w-4 h-4" />}
|
||||
{status === 'queued' && 'Queued'}
|
||||
{status === 'running' && 'Running'}
|
||||
{status === 'ready' && 'Ready'}
|
||||
{status === 'failed' && 'Retry'}
|
||||
{status === 'idle' && 'Process'}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={toggleFavorite}
|
||||
className={`inline-flex items-center gap-2 px-3 py-2 rounded border text-sm ${favorite ? 'border-rose-500 text-rose-400' : 'border-gray-700 text-gray-300'}`}
|
||||
>
|
||||
<Heart className={`w-4 h-4 ${favorite ? 'fill-rose-500' : ''}`} />
|
||||
Favorite
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,15 @@
|
||||
import { useState } from 'react'
|
||||
import { Music2, Play, Zap, Search } from 'lucide-react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { useSubsonicLibrary } from '../hooks/useSubsonicLibrary'
|
||||
import { useConvertStatus } from '../hooks/useConvertStatus'
|
||||
import { SETTINGS_ROUTE, trackRoute } from '../routes'
|
||||
|
||||
function formatDuration(seconds: number): string {
|
||||
const mins = Math.floor(seconds / 60)
|
||||
const secs = Math.max(0, seconds % 60)
|
||||
return `${mins}:${String(secs).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
interface Track {
|
||||
id: string
|
||||
@@ -12,10 +22,16 @@ interface Track {
|
||||
export default function TracksPage() {
|
||||
const [searchTerm, setSearchTerm] = useState('')
|
||||
|
||||
const tracks: Track[] = [
|
||||
{ id: '1', title: 'Song One', artist: 'Artist A', album: 'Album 1', duration: '3:45' },
|
||||
{ id: '2', title: 'Song Two', artist: 'Artist B', album: 'Album 2', duration: '4:12' },
|
||||
]
|
||||
const { songs, loading, configured, error } = useSubsonicLibrary(400)
|
||||
const { statusBySongId, convertSong } = useConvertStatus(songs)
|
||||
|
||||
const tracks: Track[] = songs.map((song) => ({
|
||||
id: song.id,
|
||||
title: song.title,
|
||||
artist: song.songArtist ?? song.artist,
|
||||
album: song.album,
|
||||
duration: formatDuration(song.duration),
|
||||
}))
|
||||
|
||||
const filteredTracks = tracks.filter(t =>
|
||||
t.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
@@ -38,6 +54,22 @@ export default function TracksPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!configured && (
|
||||
<div className="rounded-lg border border-amber-700/40 bg-amber-950/20 p-4 text-amber-200">
|
||||
Subsonic is not configured yet. Open <Link to={SETTINGS_ROUTE} className="underline">Settings</Link> and save your Subsonic server details.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="rounded-lg border border-red-700/40 bg-red-950/20 p-4 text-red-200">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading && (
|
||||
<div className="text-sm text-gray-400">Loading tracks from Subsonic…</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
{filteredTracks.map((track) => (
|
||||
<div
|
||||
@@ -49,13 +81,30 @@ export default function TracksPage() {
|
||||
</button>
|
||||
<Music2 className="w-5 h-5 text-gray-500" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="font-medium truncate">{track.title}</h3>
|
||||
<h3 className="font-medium truncate">
|
||||
<Link to={trackRoute(track.id)} className="hover:text-brand-400">
|
||||
{track.title}
|
||||
</Link>
|
||||
</h3>
|
||||
<p className="text-sm text-gray-400 truncate">{track.artist} • {track.album}</p>
|
||||
</div>
|
||||
<span className="text-sm text-gray-500">{track.duration}</span>
|
||||
<button className="flex items-center gap-2 px-3 py-2 bg-brand-500 hover:bg-brand-600 rounded text-white text-sm font-medium transition-colors opacity-0 group-hover:opacity-100">
|
||||
<button
|
||||
onClick={() => {
|
||||
const song = songs.find((item) => item.id === track.id)
|
||||
if (!song) return
|
||||
void convertSong(song)
|
||||
}}
|
||||
disabled={statusBySongId[track.id]?.status === 'queued' || statusBySongId[track.id]?.status === 'running'}
|
||||
title={statusBySongId[track.id]?.error || 'Convert with StemEngine'}
|
||||
className="flex items-center gap-2 px-3 py-2 rounded text-white text-sm font-medium transition-colors opacity-0 group-hover:opacity-100 disabled:opacity-70 disabled:cursor-not-allowed bg-brand-500 hover:bg-brand-600"
|
||||
>
|
||||
<Zap className="w-4 h-4" />
|
||||
Convert
|
||||
{statusBySongId[track.id]?.status === 'queued' && 'Queued'}
|
||||
{statusBySongId[track.id]?.status === 'running' && 'Running'}
|
||||
{statusBySongId[track.id]?.status === 'ready' && 'Ready'}
|
||||
{statusBySongId[track.id]?.status === 'failed' && 'Retry'}
|
||||
{(!statusBySongId[track.id] || statusBySongId[track.id]?.status === 'idle') && 'Convert'}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
|
||||
@@ -133,6 +133,45 @@ export interface SubsonicSong {
|
||||
bitRate: number
|
||||
}
|
||||
|
||||
export interface SubsonicPlaylist {
|
||||
id: string
|
||||
name: string
|
||||
songCount: number
|
||||
duration: number
|
||||
owner?: string
|
||||
public?: boolean
|
||||
created?: string
|
||||
changed?: string
|
||||
}
|
||||
|
||||
export interface SubsonicPlaylistDetail extends SubsonicPlaylist {
|
||||
songs: SubsonicSong[]
|
||||
}
|
||||
|
||||
export interface SubsonicAlbum {
|
||||
id: string
|
||||
name: string
|
||||
artist: string
|
||||
songCount: number
|
||||
duration: number
|
||||
year?: number | null
|
||||
coverArt?: string
|
||||
}
|
||||
|
||||
export interface SubsonicAlbumDetail extends SubsonicAlbum {
|
||||
songs: SubsonicSong[]
|
||||
}
|
||||
|
||||
export interface SubsonicArtist {
|
||||
id: string
|
||||
name: string
|
||||
albumCount: number
|
||||
}
|
||||
|
||||
export interface SubsonicArtistDetail extends SubsonicArtist {
|
||||
albums: SubsonicAlbum[]
|
||||
}
|
||||
|
||||
export interface SubsonicConfig {
|
||||
configured: boolean
|
||||
url?: string
|
||||
|
||||
@@ -50,7 +50,19 @@ export interface AutoStepDeleteStem {
|
||||
stem: string
|
||||
}
|
||||
|
||||
export type AutoStep = AutoStepReprocess | AutoStepMidi | AutoStepLyrics | AutoStepLyricsAlign | AutoStepRenameStem | AutoStepDeleteStem
|
||||
export interface AutoStepKaraokeMugen {
|
||||
type: 'karaokeMugen'
|
||||
defaultTitleLang?: string
|
||||
repository?: string
|
||||
}
|
||||
|
||||
export interface AutoStepSekPackage {
|
||||
type: 'sekPackage'
|
||||
packageName?: string
|
||||
includeVideo?: boolean
|
||||
}
|
||||
|
||||
export type AutoStep = AutoStepReprocess | AutoStepMidi | AutoStepLyrics | AutoStepLyricsAlign | AutoStepRenameStem | AutoStepDeleteStem | AutoStepKaraokeMugen | AutoStepSekPackage
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Preset types
|
||||
@@ -107,6 +119,12 @@ function migrateStep(step: AutoStep): AutoStep {
|
||||
mp3Bitrate: step.mp3Bitrate ?? '256k',
|
||||
}
|
||||
}
|
||||
if (step.type === 'sekPackage') {
|
||||
return {
|
||||
...step,
|
||||
includeVideo: step.includeVideo ?? true,
|
||||
}
|
||||
}
|
||||
if (step.type !== 'lyrics') return step
|
||||
const engine = 'whisperx' as const
|
||||
const model = step.model ?? step.whisperModel ?? 'medium'
|
||||
@@ -179,5 +197,13 @@ export function stepLabel(step: AutoStep): string {
|
||||
case 'lyricsAlign': return `Lyrics Align — ${step.timingPrecision}-level`
|
||||
case 'renameStem': return `Rename stem "${step.fromStem}" → "${step.toStem}"`
|
||||
case 'deleteStem': return `Delete stem "${step.stem}"`
|
||||
case 'karaokeMugen': {
|
||||
const lang = (step.defaultTitleLang || 'eng').toLowerCase()
|
||||
return `Export Karaoke Mugen package (${lang})`
|
||||
}
|
||||
case 'sekPackage': {
|
||||
const mode = step.includeVideo === false ? 'stems + .elrc' : 'stems + .elrc + video'
|
||||
return `Export StemEngine .sek package (${mode})`
|
||||
}
|
||||
}
|
||||
}
|
||||
+27
-19
@@ -1,26 +1,34 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import { defineConfig, loadEnv } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
build: {
|
||||
outDir: '../backend/static',
|
||||
emptyOutDir: true,
|
||||
chunkSizeWarningLimit: 1200,
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': new URL('./src', import.meta.url).pathname,
|
||||
export default defineConfig(({ mode }) => {
|
||||
const env = loadEnv(mode, new URL('.', import.meta.url).pathname, '')
|
||||
const apiProxyTarget = env.VITE_API_PROXY_TARGET || 'http://stemengine:8000'
|
||||
|
||||
return {
|
||||
plugins: [react()],
|
||||
build: {
|
||||
outDir: '../backend/static',
|
||||
emptyOutDir: true,
|
||||
chunkSizeWarningLimit: 1200,
|
||||
},
|
||||
},
|
||||
server: {
|
||||
allowedHosts: true,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:8000',
|
||||
changeOrigin: true,
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': new URL('./src', import.meta.url).pathname,
|
||||
},
|
||||
},
|
||||
},
|
||||
server: {
|
||||
allowedHosts: ['localhost', '127.0.0.1', 'work'],
|
||||
proxy: {
|
||||
'/api': {
|
||||
// In Docker dev, localhost points at the frontend container itself.
|
||||
// Route API calls to the backend service name on the compose network.
|
||||
// Can be overridden with VITE_API_PROXY_TARGET when needed.
|
||||
target: apiProxyTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
})
|
||||
Reference in new issue
Block a user