Commit
First push
This commit is contained in:
commit
c4a020c191
146 files changed
+40796
No files matched your search
Executable
+273
@@ -0,0 +1,273 @@
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { Music2, Settings, Cpu } from 'lucide-react'
|
||||
import Separator from './pages/Separator'
|
||||
import ProjectDetail from './pages/ProjectDetail'
|
||||
import SettingsPage, { applyFont, applyAccent } from './pages/Settings'
|
||||
import { ThemeProvider } from './context/ThemeContext'
|
||||
import Sidebar from './components/Sidebar'
|
||||
import GlobalAudioBar from './components/GlobalAudioBar'
|
||||
import { listProjects, deleteProject, getGpuInfo, resetGpu } from './api/client'
|
||||
import type { Project } from './types'
|
||||
|
||||
interface ProjectTab {
|
||||
id: string
|
||||
label: string // e.g. "Demucs v4_MP3 (256 kbps)"
|
||||
name: string // e.g. "Artist - Title"
|
||||
}
|
||||
|
||||
interface GpuInfo {
|
||||
cuda_available: boolean
|
||||
cuda_ok: boolean
|
||||
name: string | null
|
||||
free_mb: number
|
||||
total_mb: number
|
||||
}
|
||||
|
||||
function AppShell() {
|
||||
const [activeTabId, setActiveTabId] = useState<string>(
|
||||
() => localStorage.getItem('stemengine-active-tab') ?? 'separate'
|
||||
)
|
||||
const [projectTabs, setProjectTabs] = useState<ProjectTab[]>([])
|
||||
const [sidebarOpen, setSidebarOpen] = useState(() => window.innerWidth >= 640)
|
||||
|
||||
// GPU state
|
||||
const [gpuInfo, setGpuInfo] = useState<GpuInfo | null>(null)
|
||||
const [gpuResetting, setGpuResetting] = useState(false)
|
||||
|
||||
// Persist active tab so it survives a page refresh
|
||||
useEffect(() => {
|
||||
localStorage.setItem('stemengine-active-tab', activeTabId)
|
||||
}, [activeTabId])
|
||||
|
||||
// Apply saved font and accent color on mount
|
||||
useEffect(() => {
|
||||
applyFont(localStorage.getItem('stemengine-font') ?? 'system')
|
||||
applyAccent(localStorage.getItem('stemengine-accent') ?? 'blue')
|
||||
}, [])
|
||||
|
||||
// Load all projects from DB on mount → restore persistent tabs
|
||||
useEffect(() => {
|
||||
listProjects()
|
||||
.then((projects: Project[]) => {
|
||||
const tabs = projects.map((p) => ({
|
||||
id: p.id,
|
||||
label: p.tab_label || p.name,
|
||||
name: p.name,
|
||||
}))
|
||||
setProjectTabs(tabs)
|
||||
// If the restored tab is a project that no longer exists, go home
|
||||
setActiveTabId((current) => {
|
||||
if (current === 'separate' || current === 'settings') return current
|
||||
return tabs.find((t) => t.id === current) ? current : 'separate'
|
||||
})
|
||||
})
|
||||
.catch(() => {/* ignore – server may not be ready yet */})
|
||||
}, [])
|
||||
|
||||
// Poll GPU info on mount + every 30 s
|
||||
useEffect(() => {
|
||||
async function fetchGpu() {
|
||||
try {
|
||||
setGpuInfo(await getGpuInfo())
|
||||
} catch { /* server not ready yet */ }
|
||||
}
|
||||
fetchGpu()
|
||||
const id = setInterval(fetchGpu, 30_000)
|
||||
return () => clearInterval(id)
|
||||
}, [])
|
||||
|
||||
async function handleGpuReset() {
|
||||
setGpuResetting(true)
|
||||
try {
|
||||
await resetGpu()
|
||||
setGpuInfo(await getGpuInfo())
|
||||
} catch { /* ignore */ }
|
||||
setGpuResetting(false)
|
||||
}
|
||||
|
||||
// Auto-reset when the GPU context is marked failed (e.g. after Whisper fallback)
|
||||
const gpuContextFailed = gpuInfo?.cuda_available === true && gpuInfo.cuda_ok === false
|
||||
useEffect(() => {
|
||||
if (gpuContextFailed && !gpuResetting) {
|
||||
handleGpuReset()
|
||||
}
|
||||
}, [gpuContextFailed])
|
||||
|
||||
// Called by Separator when a separation job finishes
|
||||
const handleSeparationComplete = useCallback(
|
||||
(projectId: string, tabLabel: string, projectName: string) => {
|
||||
setProjectTabs((prev) => {
|
||||
if (prev.find((t) => t.id === projectId)) return prev
|
||||
return [...prev, { id: projectId, label: tabLabel, name: projectName }]
|
||||
})
|
||||
setActiveTabId(projectId)
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
// Close (delete) a project tab
|
||||
async function handleCloseTab(projectId: string, projectName: string) {
|
||||
const label = projectTabs.find((t) => t.id === projectId)?.label || projectName
|
||||
if (!window.confirm(`Delete "${label}"?\n\nThis will permanently remove the project and all its files.`)) return
|
||||
|
||||
try {
|
||||
await deleteProject(projectId)
|
||||
} catch {
|
||||
// If delete fails, still remove from tabs (project may already be gone)
|
||||
}
|
||||
setProjectTabs((prev) => prev.filter((t) => t.id !== projectId))
|
||||
if (activeTabId === projectId) setActiveTabId('separate')
|
||||
}
|
||||
|
||||
// Called from sidebar when a project is deleted there
|
||||
function handleDeleteProjectFromSidebar(project: Project) {
|
||||
setProjectTabs((prev) => prev.filter((t) => t.id !== project.id))
|
||||
if (activeTabId === project.id) setActiveTabId('separate')
|
||||
}
|
||||
|
||||
// Open a project tab from sidebar click — adds it if not already open
|
||||
function handleOpenProject(project: Project) {
|
||||
setProjectTabs((prev) => {
|
||||
if (prev.find((t) => t.id === project.id)) return prev
|
||||
return [...prev, {
|
||||
id: project.id,
|
||||
label: project.tab_label || project.name,
|
||||
name: project.name,
|
||||
}]
|
||||
})
|
||||
setActiveTabId(project.id)
|
||||
}
|
||||
|
||||
// Derive GPU button appearance
|
||||
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 ── */}
|
||||
<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={() => setActiveTabId('separate')}
|
||||
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>
|
||||
|
||||
{/* GPU status 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' : ''}`} />
|
||||
{/* status dot */}
|
||||
{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={() => setActiveTabId('settings')}
|
||||
title="Settings"
|
||||
className={`p-2 rounded-xl border transition-all ${
|
||||
activeTabId === 'settings'
|
||||
? '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>
|
||||
|
||||
{/* ── Body: sidebar + main ── */}
|
||||
<div className="flex flex-1 overflow-hidden">
|
||||
|
||||
{/* Backdrop — tapping it closes the sidebar on mobile */}
|
||||
{sidebarOpen && (
|
||||
<div
|
||||
className="sm:hidden fixed inset-0 z-20 bg-black/40"
|
||||
onClick={() => setSidebarOpen(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Sidebar
|
||||
isOpen={sidebarOpen}
|
||||
onToggle={() => setSidebarOpen((v) => !v)}
|
||||
onOpenProject={(p) => { handleOpenProject(p); setSidebarOpen(false) }}
|
||||
onDeleteProject={handleDeleteProjectFromSidebar}
|
||||
openTabIds={projectTabs.map((t) => t.id)}
|
||||
/>
|
||||
|
||||
<div className="flex-1 flex flex-col overflow-hidden bg-slate-100 dark:bg-gray-950">
|
||||
|
||||
{/* Page content */}
|
||||
<main className="flex-1 overflow-y-auto pb-12">
|
||||
{activeTabId === 'settings' ? (
|
||||
<SettingsPage />
|
||||
) : (
|
||||
<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">
|
||||
{activeTabId === 'separate' ? (
|
||||
<Separator
|
||||
onSeparationComplete={handleSeparationComplete}
|
||||
onOpenSettings={() => {
|
||||
localStorage.setItem('stemengine-settings-initial-tab', 'autopipeline')
|
||||
setActiveTabId('settings')
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<ProjectDetail
|
||||
id={activeTabId}
|
||||
onDelete={() => {
|
||||
const tab = projectTabs.find((t) => t.id === activeTabId)
|
||||
if (tab) handleCloseTab(tab.id, tab.name)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</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>
|
||||
|
||||
{/* Floating playback bar — persists across page navigation */}
|
||||
<GlobalAudioBar />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<ThemeProvider>
|
||||
<AppShell />
|
||||
</ThemeProvider>
|
||||
)
|
||||
}
|
||||
Executable
+522
@@ -0,0 +1,522 @@
|
||||
import type {
|
||||
Job,
|
||||
ModelOption,
|
||||
FormatOption,
|
||||
ModeOption,
|
||||
PresetsResponse,
|
||||
LyricsSource,
|
||||
LyricsData,
|
||||
DynamicLevels,
|
||||
LyricsStyleOptions,
|
||||
SubsonicSong,
|
||||
SubsonicConfig,
|
||||
ImportedFile,
|
||||
Project,
|
||||
ProjectDetail,
|
||||
ModelDownloadInfo,
|
||||
ModelDownloadProgress,
|
||||
} from '../types'
|
||||
|
||||
const BASE = '/api'
|
||||
|
||||
async function request<T>(url: string, init?: RequestInit): Promise<T> {
|
||||
const res = await fetch(url, init)
|
||||
if (!res.ok) {
|
||||
const text = await res.text()
|
||||
throw new Error(`${res.status}: ${text}`)
|
||||
}
|
||||
return res.json() as Promise<T>
|
||||
}
|
||||
|
||||
// ---------- Jobs ----------
|
||||
|
||||
export const getJob = (id: string) =>
|
||||
request<Job>(`${BASE}/jobs/${id}`)
|
||||
|
||||
export const listJobs = () =>
|
||||
request<Job[]>(`${BASE}/jobs`)
|
||||
|
||||
export const cancelJob = (id: string) =>
|
||||
request<{ detail: string }>(`${BASE}/jobs/${id}`, { method: 'DELETE' })
|
||||
|
||||
export const downloadUrl = (jobId: string, filename: string) =>
|
||||
`${BASE}/jobs/${jobId}/download/${encodeURIComponent(filename)}`
|
||||
|
||||
// ---------- Separate ----------
|
||||
|
||||
export const getSepModels = () =>
|
||||
request<ModelOption[]>(`${BASE}/separate/models`)
|
||||
|
||||
export const getSepFormats = () =>
|
||||
request<FormatOption[]>(`${BASE}/separate/formats`)
|
||||
|
||||
export const getPresets = () =>
|
||||
request<PresetsResponse>(`${BASE}/separate/presets`)
|
||||
|
||||
export const submitSeparate = (
|
||||
file: File,
|
||||
model: string,
|
||||
outputFormat: string,
|
||||
options?: {
|
||||
presetType?: string
|
||||
staticOption?: string
|
||||
dynamicLevels?: DynamicLevels
|
||||
projectName?: string
|
||||
sepPowerPreset?: string
|
||||
}
|
||||
) => {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
fd.append('model', model)
|
||||
fd.append('output_format', outputFormat)
|
||||
|
||||
if (options?.presetType) {
|
||||
fd.append('preset_type', options.presetType)
|
||||
}
|
||||
if (options?.staticOption) {
|
||||
fd.append('static_option', options.staticOption)
|
||||
}
|
||||
if (options?.dynamicLevels) {
|
||||
fd.append('dynamic_levels', JSON.stringify(options.dynamicLevels))
|
||||
}
|
||||
if (options?.projectName) {
|
||||
fd.append('project_name', options.projectName)
|
||||
}
|
||||
if (options?.sepPowerPreset) {
|
||||
fd.append('sep_power_preset', options.sepPowerPreset)
|
||||
}
|
||||
|
||||
return request<{ job_id: string; preset_type: string; project_name?: string }>(
|
||||
`${BASE}/separate`,
|
||||
{ method: 'POST', body: fd }
|
||||
)
|
||||
}
|
||||
|
||||
// ---------- Transcribe ----------
|
||||
|
||||
export const getTranscribeModes = () =>
|
||||
request<ModeOption[]>(`${BASE}/transcribe/modes`)
|
||||
|
||||
export const submitTranscribe = (file: File, mode: string) => {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
fd.append('mode', mode)
|
||||
return request<{ job_id: string }>(`${BASE}/transcribe`, { method: 'POST', body: fd })
|
||||
}
|
||||
|
||||
// ---------- ABC Convert ----------
|
||||
|
||||
export const submitAbcConvert = (files: File[], songTitle: string) => {
|
||||
const fd = new FormData()
|
||||
files.forEach((f) => fd.append('files', f))
|
||||
fd.append('song_title', songTitle)
|
||||
return request<{ job_id: string }>(`${BASE}/abc-convert`, { method: 'POST', body: fd })
|
||||
}
|
||||
|
||||
// ---------- Pipeline ----------
|
||||
|
||||
export const submitPipeline = (
|
||||
file: File,
|
||||
sepModel: string,
|
||||
sepFormat: string,
|
||||
transcribeMode: string,
|
||||
songTitle: string,
|
||||
) => {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
fd.append('sep_model', sepModel)
|
||||
fd.append('sep_format', sepFormat)
|
||||
fd.append('transcribe_mode', transcribeMode)
|
||||
fd.append('song_title', songTitle)
|
||||
return request<{ job_id: string }>(`${BASE}/pipeline`, { method: 'POST', body: fd })
|
||||
}
|
||||
|
||||
// ---------- LRC Alignment ----------
|
||||
|
||||
export const getLyricsSources = () =>
|
||||
request<LyricsSource[]>(`${BASE}/lrc/sources`)
|
||||
|
||||
export const extractLyrics = (file: File) => {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
return request<LyricsData>(`${BASE}/lrc/extract`, { method: 'POST', body: fd })
|
||||
}
|
||||
|
||||
export const submitLrcAlign = (
|
||||
audio: File,
|
||||
options: {
|
||||
lyricsSource: string
|
||||
lyricsText?: string
|
||||
outputFilename?: string
|
||||
styleOptions?: LyricsStyleOptions
|
||||
}
|
||||
) => {
|
||||
const fd = new FormData()
|
||||
fd.append('audio', audio)
|
||||
fd.append('lyrics_source', options.lyricsSource)
|
||||
|
||||
if (options.lyricsText) {
|
||||
fd.append('lyrics_text', options.lyricsText)
|
||||
}
|
||||
if (options.outputFilename) {
|
||||
fd.append('output_filename', options.outputFilename)
|
||||
}
|
||||
if (options.styleOptions) {
|
||||
fd.append('style_options', JSON.stringify(options.styleOptions))
|
||||
}
|
||||
|
||||
return request<{ job_id: string }>(`${BASE}/lrc/align`, { method: 'POST', body: fd })
|
||||
}
|
||||
|
||||
export const submitLrcAlignWithFile = (
|
||||
audio: File,
|
||||
lyricsFile: File,
|
||||
outputFilename?: string,
|
||||
styleOptions?: LyricsStyleOptions
|
||||
) => {
|
||||
const fd = new FormData()
|
||||
fd.append('audio', audio)
|
||||
fd.append('lyrics_file', lyricsFile)
|
||||
|
||||
if (outputFilename) {
|
||||
fd.append('output_filename', outputFilename)
|
||||
}
|
||||
if (styleOptions) {
|
||||
fd.append('style_options', JSON.stringify(styleOptions))
|
||||
}
|
||||
|
||||
return request<{ job_id: string }>(`${BASE}/lrc/align-with-file`, { method: 'POST', body: fd })
|
||||
}
|
||||
|
||||
export const submitLrcAlignExisting = (
|
||||
projectName: string,
|
||||
options: {
|
||||
lyricsSource: string
|
||||
lyricsText?: string
|
||||
outputFilename?: string
|
||||
styleOptions?: LyricsStyleOptions
|
||||
}
|
||||
) => {
|
||||
const fd = new FormData()
|
||||
fd.append('project_name', projectName)
|
||||
fd.append('lyrics_source', options.lyricsSource)
|
||||
|
||||
if (options.lyricsText) {
|
||||
fd.append('lyrics_text', options.lyricsText)
|
||||
}
|
||||
if (options.outputFilename) {
|
||||
fd.append('output_filename', options.outputFilename)
|
||||
}
|
||||
if (options.styleOptions) {
|
||||
fd.append('style_options', JSON.stringify(options.styleOptions))
|
||||
}
|
||||
|
||||
return request<{ job_id: string }>(`${BASE}/lrc/align-existing`, { method: 'POST', body: fd })
|
||||
}
|
||||
|
||||
// ---------- Quick-action helpers (from existing project/job on server) ----------
|
||||
|
||||
export const submitTranscribeFromProject = (projectName: string, mode = 'music') => {
|
||||
const fd = new FormData()
|
||||
fd.append('project_name', projectName)
|
||||
fd.append('mode', mode)
|
||||
return request<{ job_id: string; stem: string }>(`${BASE}/transcribe/from-project`, { method: 'POST', body: fd })
|
||||
}
|
||||
|
||||
export const submitAbcConvertFromJob = (sourceJobId: string, songTitle = '') => {
|
||||
const fd = new FormData()
|
||||
fd.append('source_job_id', sourceJobId)
|
||||
fd.append('song_title', songTitle)
|
||||
return request<{ job_id: string }>(`${BASE}/abc-convert/from-job`, { method: 'POST', body: fd })
|
||||
}
|
||||
|
||||
// ---------- Subsonic ----------
|
||||
|
||||
export const getSubsonicConfig = () =>
|
||||
request<SubsonicConfig>(`${BASE}/subsonic/config`)
|
||||
|
||||
export const saveSubsonicConfig = (url: string, username: string, password: string) =>
|
||||
request<SubsonicConfig>(`${BASE}/subsonic/config`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url, username, password }),
|
||||
})
|
||||
|
||||
export const deleteSubsonicConfig = () =>
|
||||
request<SubsonicConfig>(`${BASE}/subsonic/config`, { method: 'DELETE' })
|
||||
|
||||
export const searchSubsonic = (q: string, count = 20) =>
|
||||
request<SubsonicSong[]>(`${BASE}/subsonic/search?q=${encodeURIComponent(q)}&count=${count}`)
|
||||
|
||||
export const importSubsonicSong = (song: SubsonicSong) =>
|
||||
request<ImportedFile>(`${BASE}/subsonic/import`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ id: song.id, title: song.title, artist: song.artist, suffix: song.suffix }),
|
||||
})
|
||||
|
||||
export const listImports = () =>
|
||||
request<ImportedFile[]>(`${BASE}/subsonic/imports`)
|
||||
|
||||
export const deleteImport = (filename: string) =>
|
||||
request<{ detail: string }>(`${BASE}/subsonic/imports/${encodeURIComponent(filename)}`, { method: 'DELETE' })
|
||||
|
||||
// ---------- Separate from imported file ----------
|
||||
|
||||
export const submitSeparateFromPath = (
|
||||
filePath: string,
|
||||
model: string,
|
||||
outputFormat: string,
|
||||
options?: {
|
||||
presetType?: string
|
||||
staticOption?: string
|
||||
dynamicLevels?: DynamicLevels
|
||||
projectName?: string
|
||||
sepPowerPreset?: string
|
||||
}
|
||||
) => {
|
||||
const fd = new FormData()
|
||||
fd.append('file_path', filePath)
|
||||
fd.append('model', model)
|
||||
fd.append('output_format', outputFormat)
|
||||
if (options?.presetType) fd.append('preset_type', options.presetType)
|
||||
if (options?.staticOption) fd.append('static_option', options.staticOption)
|
||||
if (options?.dynamicLevels) fd.append('dynamic_levels', JSON.stringify(options.dynamicLevels))
|
||||
if (options?.projectName) fd.append('project_name', options.projectName)
|
||||
if (options?.sepPowerPreset) fd.append('sep_power_preset', options.sepPowerPreset)
|
||||
return request<{ job_id: string; preset_type: string }>(`${BASE}/separate/from-path`, { method: 'POST', body: fd })
|
||||
}
|
||||
|
||||
// ---------- Projects ----------
|
||||
|
||||
export const listProjects = () =>
|
||||
request<Project[]>(`${BASE}/projects`)
|
||||
|
||||
export const getProjectDetail = (id: string) =>
|
||||
request<ProjectDetail>(`${BASE}/projects/${id}`)
|
||||
|
||||
export const deleteProject = (id: string) =>
|
||||
request<{ detail: string }>(`${BASE}/projects/${id}`, { method: 'DELETE' })
|
||||
|
||||
export const transcribeProject = (id: string, stemName: string, mode: string) =>
|
||||
request<{ job_id: string }>(`${BASE}/projects/${id}/transcribe`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ stem_name: stemName, mode }),
|
||||
})
|
||||
|
||||
export const abcProject = (id: string, stemName: string, songTitle?: string) =>
|
||||
request<{ job_id: string }>(`${BASE}/projects/${id}/abc`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ stem_name: stemName, song_title: songTitle }),
|
||||
})
|
||||
|
||||
export const mixProject = (
|
||||
id: string,
|
||||
presetType: 'static' | 'dynamic',
|
||||
opts?: { staticOption?: string; dynamicLevels?: Record<string, number> }
|
||||
) =>
|
||||
request<{ job_id: string }>(`${BASE}/projects/${id}/mix`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
preset_type: presetType,
|
||||
static_option: opts?.staticOption,
|
||||
dynamic_levels: opts?.dynamicLevels,
|
||||
}),
|
||||
})
|
||||
|
||||
export const lrcProject = (
|
||||
id: string,
|
||||
stemName: string,
|
||||
opts: {
|
||||
lyricsSource: string
|
||||
lyricsText?: string
|
||||
outputFilename?: string
|
||||
timingPrecision?: 'word' | 'syllable'
|
||||
lrcPowerPreset?: string
|
||||
}
|
||||
) =>
|
||||
request<{ job_id: string }>(`${BASE}/projects/${id}/lrc`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
stem_name: stemName,
|
||||
lyrics_source: opts.lyricsSource,
|
||||
lyrics_text: opts.lyricsText,
|
||||
output_filename: opts.outputFilename,
|
||||
timing_precision: opts.timingPrecision ?? 'word',
|
||||
lrc_power_preset: opts.lrcPowerPreset ?? 'standard',
|
||||
}),
|
||||
})
|
||||
|
||||
// ---------- Stem Reprocessing ----------
|
||||
|
||||
export const reprocessStem = (
|
||||
projectId: string,
|
||||
stemName: string,
|
||||
model: string,
|
||||
options?: {
|
||||
outputFormat?: string
|
||||
}
|
||||
) =>
|
||||
request<{ job_id: string }>(`${BASE}/projects/${projectId}/reprocess`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
stem_name: stemName,
|
||||
model,
|
||||
output_format: options?.outputFormat ?? 'mp3',
|
||||
}),
|
||||
})
|
||||
|
||||
// ---------- Lyric Transcription (Whisper AI) ----------
|
||||
|
||||
export const lyricTranscribeProject = (
|
||||
projectId: string,
|
||||
stemName: string,
|
||||
opts?: {
|
||||
model?: string
|
||||
language?: string
|
||||
task?: 'transcribe' | 'translate'
|
||||
outputFormats?: string[]
|
||||
initialPrompt?: string
|
||||
temperature?: number
|
||||
wordTimestamps?: boolean
|
||||
conditionOnPreviousText?: boolean
|
||||
beamSize?: number
|
||||
diarize?: boolean
|
||||
}
|
||||
) => {
|
||||
const wordTs = opts?.wordTimestamps ?? true
|
||||
return request<{ job_id: string }>(`${BASE}/projects/${projectId}/lyric-transcribe`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
stem_name: stemName,
|
||||
model: opts?.model ?? 'large-v2',
|
||||
language: opts?.language || undefined,
|
||||
task: opts?.task ?? 'transcribe',
|
||||
output_formats: opts?.outputFormats ?? (wordTs ? ['elrc', 'lrc', 'txt'] : ['lrc', 'txt']),
|
||||
initial_prompt: opts?.initialPrompt,
|
||||
temperature: opts?.temperature ?? 0.0,
|
||||
word_timestamps: wordTs,
|
||||
condition_on_previous_text: opts?.conditionOnPreviousText ?? true,
|
||||
beam_size: opts?.beamSize ?? undefined,
|
||||
engine: 'whisperx',
|
||||
diarize: opts?.diarize ?? false,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
// ---------- Stem Rename ----------
|
||||
|
||||
export const renameStem = (
|
||||
projectId: string,
|
||||
stemName: string,
|
||||
newName: string
|
||||
) =>
|
||||
request<{ success: boolean; new_path: string }>(`${BASE}/projects/${projectId}/rename-stem`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
stem_name: stemName,
|
||||
new_name: newName,
|
||||
}),
|
||||
})
|
||||
|
||||
// ---------- Per-Instrument Models ----------
|
||||
|
||||
export const getPerInstrumentModels = () =>
|
||||
request<ModelOption[]>(`${BASE}/separate/per-instrument-models`)
|
||||
|
||||
// ---------- Model Management ----------
|
||||
|
||||
export const listModels = () =>
|
||||
request<ModelDownloadInfo[]>(`${BASE}/models/list`)
|
||||
|
||||
export const downloadModel = (modelId: string) =>
|
||||
request<{ success: boolean; message: string }>(`${BASE}/models/download`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ model_id: modelId }),
|
||||
})
|
||||
|
||||
export const pauseModelDownload = (modelId: string) =>
|
||||
request<{ success: boolean; message: string }>(`${BASE}/models/pause`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ model_id: modelId }),
|
||||
})
|
||||
|
||||
export const resumeModelDownload = (modelId: string) =>
|
||||
request<{ success: boolean; message: string }>(`${BASE}/models/resume`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ model_id: modelId }),
|
||||
})
|
||||
|
||||
export const cancelModelDownload = (modelId: string) =>
|
||||
request<{ success: boolean; message: string }>(`${BASE}/models/cancel`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ model_id: modelId }),
|
||||
})
|
||||
|
||||
export const deleteModel = (modelId: string) =>
|
||||
request<{ success: boolean; message: string }>(`${BASE}/models/${modelId}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
export const getModelProgress = (modelId: string) =>
|
||||
request<ModelDownloadProgress>(`${BASE}/models/progress/${modelId}`)
|
||||
|
||||
export const getAllModelProgress = () =>
|
||||
request<Record<string, ModelDownloadProgress>>(`${BASE}/models/progress`)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Project cleanup / maintenance
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const cleanupVerify = () =>
|
||||
request<{ projects_with_missing_files: { project_id: string; name: string; missing_files: string[] }[]; total: number }>(
|
||||
`${BASE}/projects/cleanup/verify`
|
||||
)
|
||||
|
||||
export const cleanupWriteMetadata = () =>
|
||||
request<{ written: number; errors: { project: string; error: string }[] }>(
|
||||
`${BASE}/projects/cleanup/write-metadata`,
|
||||
{ method: 'POST' }
|
||||
)
|
||||
|
||||
export const cleanupRenameStems = () =>
|
||||
request<{ renamed: number; errors: { project: string; file: string; error: string }[] }>(
|
||||
`${BASE}/projects/cleanup/rename-stems`,
|
||||
{ method: 'POST' }
|
||||
)
|
||||
|
||||
export const cleanupPurgeOrphaned = () =>
|
||||
request<{ purged: number }>(
|
||||
`${BASE}/projects/cleanup/purge-orphaned`,
|
||||
{ method: 'POST' }
|
||||
)
|
||||
|
||||
export const cleanupCleanLrcFiles = () =>
|
||||
request<{ files_modified: number; lines_removed: number; errors: { file: string; error: string }[] }>(
|
||||
`${BASE}/projects/cleanup/clean-lrc-files`,
|
||||
{ method: 'POST' }
|
||||
)
|
||||
|
||||
// ── System ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export const getGpuInfo = () =>
|
||||
request<{ cuda_available: boolean; cuda_ok: boolean; name: string | null; total_mb: number; free_mb: number }>(
|
||||
`${BASE}/system/gpu-info`
|
||||
)
|
||||
|
||||
export const resetGpu = () =>
|
||||
request<{ ok: boolean; cuda_available: boolean; cuda_ok: boolean }>(
|
||||
`${BASE}/system/gpu-reset`,
|
||||
{ method: 'POST' }
|
||||
)
|
||||
+371
@@ -0,0 +1,371 @@
|
||||
/**
|
||||
* AutoPipelineDialog
|
||||
*
|
||||
* Lean "confirm & run" modal. Pipeline options (model, format, steps) are
|
||||
* configured in Settings → Auto Pipeline. This dialog just shows a summary
|
||||
* of the stored settings, accepts a project name, and orchestrates execution.
|
||||
*/
|
||||
import { useState, useRef } from 'react'
|
||||
import { X, Zap, Loader2, CheckCircle2, XCircle, Music2, Mic2, AlignLeft, Settings } from 'lucide-react'
|
||||
import {
|
||||
submitSeparate, submitSeparateFromPath,
|
||||
getJob, reprocessStem, transcribeProject, lyricTranscribeProject,
|
||||
} from '../api/client'
|
||||
import type { Job } from '../types'
|
||||
import {
|
||||
readAutoModel, readAutoFormat, readAutoSteps, stepLabel,
|
||||
} from '../utils/autoPipeline'
|
||||
import type { AutoStep } from '../utils/autoPipeline'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface AutoPipelineTarget {
|
||||
file?: File
|
||||
filePath?: string
|
||||
filename: string
|
||||
initialProjectName?: string
|
||||
}
|
||||
|
||||
interface Props {
|
||||
target: AutoPipelineTarget
|
||||
onClose: () => void
|
||||
/** Called when the full pipeline completes successfully. */
|
||||
onComplete?: (projectId: string, projectName: string) => void
|
||||
/** Called to navigate the user to Settings → Auto Pipeline tab. */
|
||||
onOpenSettings?: () => void
|
||||
}
|
||||
|
||||
type Phase = 'idle' | 'running' | 'done' | 'error'
|
||||
|
||||
interface StepStatus {
|
||||
label: string
|
||||
status: 'pending' | 'running' | 'done' | 'error'
|
||||
detail?: string
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Poll helper
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const MAX_RETRIES = 2
|
||||
|
||||
async function withRetry<T>(
|
||||
fn: () => Promise<T>,
|
||||
signal: AbortSignal | undefined,
|
||||
onRetry: (retryNum: number) => void,
|
||||
): Promise<T> {
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try {
|
||||
return await fn()
|
||||
} catch (e) {
|
||||
if (e instanceof Error && e.message === 'Cancelled') throw e
|
||||
if (signal?.aborted) throw new Error('Cancelled')
|
||||
if (attempt >= MAX_RETRIES) throw e
|
||||
onRetry(attempt + 1)
|
||||
await new Promise<void>((res, rej) => {
|
||||
const t = setTimeout(res, 3000)
|
||||
signal?.addEventListener('abort', () => { clearTimeout(t); rej(new Error('Cancelled')) })
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function pollUntilDone(jobId: string, signal?: AbortSignal): Promise<Job> {
|
||||
for (;;) {
|
||||
if (signal?.aborted) throw new Error('Cancelled')
|
||||
const job = await getJob(jobId)
|
||||
if (job.status === 'done') return job
|
||||
if (job.status === 'error') throw new Error(job.error || 'Job failed')
|
||||
if (job.status === 'cancelled') throw new Error('Job was cancelled')
|
||||
await new Promise<void>((res, rej) => {
|
||||
const t = setTimeout(res, 2500)
|
||||
signal?.addEventListener('abort', () => { clearTimeout(t); rej(new Error('Cancelled')) })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Step icon
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function StepIcon({ step }: { step: AutoStep }) {
|
||||
if (step.type === 'reprocess') return <Music2 className="w-3.5 h-3.5 text-purple-500" />
|
||||
if (step.type === 'midi') return <Mic2 className="w-3.5 h-3.5 text-emerald-500" />
|
||||
return <AlignLeft className="w-3.5 h-3.5 text-sky-500" />
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Component
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export default function AutoPipelineDialog({ target, onClose, onComplete, onOpenSettings }: Props) {
|
||||
const model = readAutoModel()
|
||||
const format = readAutoFormat()
|
||||
const steps = readAutoSteps()
|
||||
|
||||
const [projName, setProjName] = useState(
|
||||
target.initialProjectName ?? target.filename.replace(/\.[^/.]+$/, '')
|
||||
)
|
||||
const [phase, setPhase] = useState<Phase>('idle')
|
||||
const [stepStats, setStepStats] = useState<StepStatus[]>([])
|
||||
const [errMsg, setErrMsg] = useState<string | null>(null)
|
||||
const abortRef = useRef<AbortController | null>(null)
|
||||
|
||||
function patchStep(idx: number, patch: Partial<StepStatus>) {
|
||||
setStepStats(prev => prev.map((s, i) => i === idx ? { ...s, ...patch } : s))
|
||||
}
|
||||
|
||||
async function run() {
|
||||
setErrMsg(null)
|
||||
setPhase('running')
|
||||
const ctrl = new AbortController()
|
||||
abortRef.current = ctrl
|
||||
|
||||
// Build step labels upfront (separation is always first, then stored steps)
|
||||
const initialStats: StepStatus[] = [
|
||||
{ label: 'Stem separation', status: 'pending' },
|
||||
...steps.map(s => ({ label: stepLabel(s), status: 'pending' as const })),
|
||||
]
|
||||
setStepStats(initialStats)
|
||||
|
||||
let stepIdx = 0
|
||||
const retry = (n: number) => patchStep(stepIdx, { detail: `Retrying (${n}/${MAX_RETRIES})…` })
|
||||
|
||||
try {
|
||||
// ── Stage 0: Separation ────────────────────────────────────────────
|
||||
patchStep(stepIdx, { status: 'running' })
|
||||
|
||||
const sepPowerPreset = localStorage.getItem('stemengine-sep-power') ?? 'standard'
|
||||
const sepOpts = { presetType: 'stems_only', projectName: projName || undefined, sepPowerPreset }
|
||||
|
||||
const sepJob = await withRetry(async () => {
|
||||
patchStep(stepIdx, { detail: 'Submitting…' })
|
||||
const { job_id: sepJobId } = target.file
|
||||
? await submitSeparate(target.file, model, format, sepOpts)
|
||||
: await submitSeparateFromPath(target.filePath!, model, format, sepOpts)
|
||||
patchStep(stepIdx, { detail: 'Running…' })
|
||||
return pollUntilDone(sepJobId, ctrl.signal)
|
||||
}, ctrl.signal, retry)
|
||||
|
||||
const projectId = sepJob.result?.project_id
|
||||
const resolvedName = sepJob.result?.project_name ?? projName
|
||||
|
||||
patchStep(stepIdx, { status: 'done', detail: resolvedName })
|
||||
stepIdx++
|
||||
|
||||
// ── Configured steps ──────────────────────────────────────────────
|
||||
for (const step of steps) {
|
||||
patchStep(stepIdx, { status: 'running' })
|
||||
|
||||
if (step.type === 'reprocess' && projectId) {
|
||||
await withRetry(async () => {
|
||||
patchStep(stepIdx, { detail: `Reprocessing "${step.stem}"…` })
|
||||
const { job_id } = await reprocessStem(projectId, step.stem, step.model)
|
||||
await pollUntilDone(job_id, ctrl.signal)
|
||||
}, ctrl.signal, retry)
|
||||
patchStep(stepIdx, { status: 'done' })
|
||||
|
||||
} else if (step.type === 'midi' && projectId) {
|
||||
await withRetry(async () => {
|
||||
patchStep(stepIdx, { detail: 'Transcribing vocals to MIDI…' })
|
||||
const { job_id } = await transcribeProject(projectId, 'vocals', step.mode)
|
||||
await pollUntilDone(job_id, ctrl.signal)
|
||||
}, ctrl.signal, retry)
|
||||
patchStep(stepIdx, { status: 'done', detail: step.mode })
|
||||
|
||||
} else if (step.type === 'lyrics' && projectId) {
|
||||
const wordTs = localStorage.getItem('stemengine-whisper-word-ts') !== 'false'
|
||||
await withRetry(async () => {
|
||||
patchStep(stepIdx, { detail: `WhisperX ${step.whisperModel}…` })
|
||||
const { job_id: transcribeJobId } = await lyricTranscribeProject(projectId, 'vocals', {
|
||||
model: step.whisperModel,
|
||||
outputFormats: wordTs ? ['elrc', 'lrc', 'txt'] : ['lrc', 'txt'],
|
||||
wordTimestamps: wordTs,
|
||||
diarize: step.diarize,
|
||||
})
|
||||
await pollUntilDone(transcribeJobId, ctrl.signal)
|
||||
}, ctrl.signal, retry)
|
||||
patchStep(stepIdx, { status: 'done', detail: step.whisperModel })
|
||||
}
|
||||
|
||||
stepIdx++
|
||||
}
|
||||
|
||||
setPhase('done')
|
||||
if (projectId) onComplete?.(projectId, resolvedName)
|
||||
|
||||
} catch (e: unknown) {
|
||||
const msg = e instanceof Error ? e.message : String(e)
|
||||
if (msg === 'Cancelled') { setPhase('idle'); setStepStats([]); return }
|
||||
setErrMsg(msg)
|
||||
setStepStats(prev => prev.map((s, i) => i === stepIdx ? { ...s, status: 'error', detail: msg } : s))
|
||||
setPhase('error')
|
||||
}
|
||||
}
|
||||
|
||||
function cancel() { abortRef.current?.abort() }
|
||||
|
||||
const running = phase === 'running'
|
||||
const finished = phase === 'done' || phase === 'error'
|
||||
const canRun = !!(target.file || target.filePath)
|
||||
|
||||
return (
|
||||
<div className="fixed bottom-4 right-4 z-50 w-96 rounded-2xl bg-white dark:bg-gray-900 border border-slate-200 dark:border-gray-700 shadow-2xl flex flex-col max-h-[85vh]">
|
||||
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-3 px-5 py-4 border-b border-slate-200 dark:border-gray-800 shrink-0">
|
||||
<Zap className="w-5 h-5 text-amber-500 shrink-0" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<h2 className="text-sm font-bold text-slate-900 dark:text-white">Auto Pipeline</h2>
|
||||
<p className="text-xs text-slate-500 dark:text-gray-400 truncate">{target.filename}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={running ? cancel : onClose}
|
||||
className="p-1.5 rounded-lg text-slate-400 hover:text-slate-600 dark:hover:text-gray-200 transition-colors"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Body */}
|
||||
<div className="flex-1 overflow-y-auto p-5 space-y-4">
|
||||
|
||||
{/* Project name */}
|
||||
{!running && !finished && (
|
||||
<label className="space-y-1 block">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Project Name</span>
|
||||
<input
|
||||
type="text"
|
||||
value={projName}
|
||||
onChange={e => setProjName(e.target.value)}
|
||||
placeholder="Artist - Title"
|
||||
className="w-full rounded-lg bg-white dark:bg-gray-900 border border-slate-300 dark:border-gray-700 px-3 py-2 text-sm text-slate-900 dark:text-gray-100 focus:border-brand-500 focus:outline-none"
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
|
||||
{/* Pipeline summary (shown before run) */}
|
||||
{!running && !finished && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Pipeline ({1 + steps.length} step{steps.length !== 0 ? 's' : ''})
|
||||
</span>
|
||||
{onOpenSettings && (
|
||||
<button
|
||||
onClick={onOpenSettings}
|
||||
className="flex items-center gap-1 text-xs text-brand-500 hover:text-brand-600 dark:text-brand-400 transition-colors"
|
||||
>
|
||||
<Settings className="w-3 h-3" />
|
||||
Edit in Settings
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Separation step */}
|
||||
<div className="flex items-center gap-2.5 px-3 py-2 rounded-lg bg-slate-50 dark:bg-gray-800/50 border border-slate-200 dark:border-gray-700">
|
||||
<Music2 className="w-3.5 h-3.5 text-brand-500 shrink-0" />
|
||||
<span className="text-sm text-slate-700 dark:text-gray-200 flex-1">Stem Separation</span>
|
||||
<span className="text-xs text-slate-400 dark:text-gray-500 truncate max-w-32">
|
||||
{model} · {format}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{steps.length === 0 && (
|
||||
<p className="text-xs text-slate-400 dark:text-gray-500 italic px-1">
|
||||
No extra steps configured.{' '}
|
||||
{onOpenSettings && (
|
||||
<button onClick={onOpenSettings} className="text-brand-500 hover:underline">
|
||||
Add steps in Settings →
|
||||
</button>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{steps.map((step, i) => (
|
||||
<div key={i} className="flex items-center gap-2.5 px-3 py-2 rounded-lg bg-slate-50 dark:bg-gray-800/50 border border-slate-200 dark:border-gray-700">
|
||||
<StepIcon step={step} />
|
||||
<span className="text-sm text-slate-700 dark:text-gray-200 flex-1 truncate">
|
||||
{stepLabel(step)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Live progress */}
|
||||
{stepStats.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<span className="text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Progress
|
||||
</span>
|
||||
{stepStats.map((s, i) => (
|
||||
<div key={i} className="flex items-start gap-3">
|
||||
<div className="mt-0.5 shrink-0">
|
||||
{s.status === 'running' && <Loader2 className="w-4 h-4 text-brand-500 animate-spin" />}
|
||||
{s.status === 'done' && <CheckCircle2 className="w-4 h-4 text-emerald-500" />}
|
||||
{s.status === 'error' && <XCircle className="w-4 h-4 text-red-500" />}
|
||||
{s.status === 'pending' && <div className="w-4 h-4 rounded-full border-2 border-slate-300 dark:border-gray-600" />}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className={`text-sm font-medium ${
|
||||
s.status === 'running' ? 'text-brand-600 dark:text-brand-400'
|
||||
: s.status === 'done' ? 'text-emerald-700 dark:text-emerald-300'
|
||||
: s.status === 'error' ? 'text-red-600 dark:text-red-400'
|
||||
: 'text-slate-500 dark:text-gray-500'
|
||||
}`}>{s.label}</p>
|
||||
{s.detail && <p className="text-xs text-slate-400 dark:text-gray-500 truncate">{s.detail}</p>}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{errMsg && (
|
||||
<div className="rounded-lg bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-800 px-4 py-3 text-sm text-red-700 dark:text-red-300">
|
||||
{errMsg}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{phase === 'done' && (
|
||||
<div className="rounded-lg bg-emerald-50 dark:bg-emerald-950/30 border border-emerald-200 dark:border-emerald-800 px-4 py-3 text-sm text-emerald-700 dark:text-emerald-300 font-medium">
|
||||
Pipeline complete!
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="px-5 py-4 border-t border-slate-200 dark:border-gray-800 shrink-0 flex gap-3">
|
||||
{!finished && (
|
||||
<>
|
||||
<button
|
||||
onClick={running ? cancel : onClose}
|
||||
className="flex-1 rounded-lg border border-slate-300 dark:border-gray-600 px-4 py-2.5 text-sm font-medium text-slate-600 dark:text-gray-300 hover:bg-slate-50 dark:hover:bg-gray-800 transition-colors"
|
||||
>
|
||||
{running ? 'Cancel' : 'Dismiss'}
|
||||
</button>
|
||||
<button
|
||||
onClick={run}
|
||||
disabled={running || !canRun}
|
||||
className="flex-1 rounded-lg bg-amber-500 hover:bg-amber-400 disabled:bg-slate-200 disabled:text-slate-400 dark:disabled:bg-gray-800 dark:disabled:text-gray-500 px-4 py-2.5 text-sm font-bold text-white disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-2"
|
||||
>
|
||||
{running
|
||||
? <><Loader2 className="w-4 h-4 animate-spin" />Running…</>
|
||||
: <><Zap className="w-4 h-4" />Run Pipeline</>}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{finished && (
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="flex-1 rounded-lg bg-brand-600 hover:bg-brand-500 px-4 py-2.5 text-sm font-bold text-white transition-colors"
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Executable
+331
@@ -0,0 +1,331 @@
|
||||
import { useRef, useEffect, useState, useCallback } from 'react'
|
||||
import { Volume2, VolumeX } from 'lucide-react'
|
||||
import { registerPlayback, unregisterPlayback, publishMeta, clearMeta } from '../utils/audioRegistry'
|
||||
|
||||
interface Stem {
|
||||
name: string
|
||||
label: string
|
||||
url: string
|
||||
}
|
||||
|
||||
interface Props {
|
||||
stems: Stem[]
|
||||
title?: string
|
||||
onLevelChange?: (name: string, value: number) => void
|
||||
}
|
||||
|
||||
export default function DynamicMixPlayer({ stems, title, onLevelChange }: Props) {
|
||||
const audioRefs = useRef<Record<string, HTMLAudioElement>>({})
|
||||
const gainRefs = useRef<Record<string, GainNode>>({})
|
||||
const audioCtxRef = useRef<AudioContext | null>(null)
|
||||
|
||||
const [isPlaying, setIsPlaying] = useState(false)
|
||||
const [currentTime, setCurrentTime] = useState(0)
|
||||
const [duration, setDuration] = useState(0)
|
||||
const [loaded, setLoaded] = useState<Record<string, boolean>>({})
|
||||
|
||||
const [gains, setGains] = useState<Record<string, number>>(() =>
|
||||
stems.reduce((acc, s) => ({ ...acc, [s.name]: 1.0 }), {})
|
||||
)
|
||||
const [masterVolume, setMasterVolume] = useState(1)
|
||||
const [isMuted, setIsMuted] = useState(false)
|
||||
const [preMuteVolume, setPreMuteVolume] = useState(1)
|
||||
const [mutedStems, setMutedStems] = useState<Record<string, boolean>>({})
|
||||
const [soloedStems, setSoloedStems] = useState<Record<string, boolean>>({})
|
||||
|
||||
// Whether this player is "owning" the global floating bar
|
||||
const isActiveRef = useRef(false)
|
||||
|
||||
// Stable stop callback for the global audio registry
|
||||
const stopPlayback = useCallback(() => {
|
||||
isActiveRef.current = false
|
||||
Object.values(audioRefs.current).forEach(a => a.pause())
|
||||
setIsPlaying(false)
|
||||
clearMeta()
|
||||
}, [])
|
||||
|
||||
// Unregister + clear bar when unmounted
|
||||
useEffect(() => () => {
|
||||
unregisterPlayback(stopPlayback)
|
||||
clearMeta()
|
||||
}, [stopPlayback])
|
||||
|
||||
// Lazily create the shared AudioContext on first interaction (browser autoplay policy)
|
||||
function getCtx(): AudioContext {
|
||||
if (!audioCtxRef.current) {
|
||||
audioCtxRef.current = new AudioContext()
|
||||
}
|
||||
return audioCtxRef.current
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const ctx = getCtx()
|
||||
|
||||
stems.forEach((stem) => {
|
||||
if (audioRefs.current[stem.name]) return // already wired up
|
||||
|
||||
const audio = new Audio(stem.url)
|
||||
audio.preload = 'metadata'
|
||||
audio.crossOrigin = 'anonymous'
|
||||
|
||||
audio.addEventListener('loadedmetadata', () => {
|
||||
setDuration((d) => Math.max(d, audio.duration || 0))
|
||||
setLoaded((l) => ({ ...l, [stem.name]: true }))
|
||||
})
|
||||
audio.addEventListener('error', () => {
|
||||
setLoaded((l) => ({ ...l, [stem.name]: false }))
|
||||
})
|
||||
|
||||
// Route through Web Audio — all MediaElementSourceNodes in the same
|
||||
// AudioContext share one clock, eliminating independent-element drift.
|
||||
const source = ctx.createMediaElementSource(audio)
|
||||
const gain = ctx.createGain()
|
||||
source.connect(gain)
|
||||
gain.connect(ctx.destination)
|
||||
|
||||
audioRefs.current[stem.name] = audio
|
||||
gainRefs.current[stem.name] = gain
|
||||
})
|
||||
|
||||
// RAF loop — read playback position from the first element
|
||||
let raf: number
|
||||
function tick() {
|
||||
const first = Object.values(audioRefs.current)[0]
|
||||
if (first) setCurrentTime(first.currentTime)
|
||||
raf = requestAnimationFrame(tick)
|
||||
}
|
||||
raf = requestAnimationFrame(tick)
|
||||
|
||||
return () => cancelAnimationFrame(raf)
|
||||
}, [stems])
|
||||
|
||||
const togglePlay = useCallback(async () => {
|
||||
const ctx = getCtx()
|
||||
const audios = Object.values(audioRefs.current)
|
||||
|
||||
if (isPlaying) {
|
||||
audios.forEach((a) => a.pause())
|
||||
// Don't unregister — keep bar visible showing paused state.
|
||||
// A new player registering will call stopPlayback(), which clears.
|
||||
setIsPlaying(false)
|
||||
} else {
|
||||
registerPlayback(stopPlayback)
|
||||
isActiveRef.current = true
|
||||
// Suspend the audio clock, seek & start all elements, then resume —
|
||||
// guarantees all stems begin from the same audio frame simultaneously.
|
||||
await ctx.suspend()
|
||||
audios.forEach((a) => {
|
||||
a.currentTime = currentTime
|
||||
a.play().catch(() => {})
|
||||
})
|
||||
await ctx.resume()
|
||||
setIsPlaying(true)
|
||||
}
|
||||
}, [isPlaying, currentTime, stopPlayback])
|
||||
|
||||
function handleSeek(t: number) {
|
||||
setCurrentTime(t)
|
||||
Object.values(audioRefs.current).forEach((a) => {
|
||||
a.currentTime = t
|
||||
})
|
||||
}
|
||||
|
||||
// Keep a ref to togglePlay so the bar always calls the latest version
|
||||
const togglePlayRef = useRef(togglePlay)
|
||||
useEffect(() => { togglePlayRef.current = togglePlay }, [togglePlay])
|
||||
|
||||
// Keep a ref to updateMasterVolume so the bar's setVolume always uses fresh state
|
||||
const updateMasterVolumeRef = useRef(updateMasterVolume)
|
||||
updateMasterVolumeRef.current = updateMasterVolume
|
||||
|
||||
// Publish state to the global floating bar whenever anything relevant changes
|
||||
useEffect(() => {
|
||||
if (!isActiveRef.current) return
|
||||
publishMeta(
|
||||
{ title: title ?? 'Dynamic Mix', isPlaying, currentTime, duration, volume: isMuted ? 0 : masterVolume },
|
||||
{ toggle: () => togglePlayRef.current(), seek: handleSeek, setVolume: (v) => updateMasterVolumeRef.current(v) }
|
||||
)
|
||||
// handleSeek is recreated each render but is stateless; refs stay fresh
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isPlaying, currentTime, duration, title, masterVolume, isMuted])
|
||||
|
||||
// Apply GainNode values based on current mute/solo/master state
|
||||
function applyGains(overrides: {
|
||||
name?: string
|
||||
gain?: number
|
||||
master?: number
|
||||
muted?: boolean
|
||||
mutedStems?: Record<string, boolean>
|
||||
soloedStems?: Record<string, boolean>
|
||||
} = {}) {
|
||||
const resolvedMaster = overrides.master ?? masterVolume
|
||||
const resolvedMuted = overrides.muted ?? isMuted
|
||||
const resolvedMutes = overrides.mutedStems ?? mutedStems
|
||||
const resolvedSolos = overrides.soloedStems ?? soloedStems
|
||||
const anySolo = Object.values(resolvedSolos).some(Boolean)
|
||||
|
||||
Object.entries(gainRefs.current).forEach(([n, gn]) => {
|
||||
const stemGain = overrides.name === n ? (overrides.gain ?? gains[n] ?? 1) : (gains[n] ?? 1)
|
||||
const stemMuted = resolvedMutes[n] ?? false
|
||||
const stemSoloed = resolvedSolos[n] ?? false
|
||||
const effective = (resolvedMuted || stemMuted || (anySolo && !stemSoloed))
|
||||
? 0
|
||||
: Math.min(2, resolvedMaster * stemGain)
|
||||
gn.gain.value = effective
|
||||
})
|
||||
}
|
||||
|
||||
function updateGain(name: string, value: number) {
|
||||
setGains((g) => ({ ...g, [name]: value }))
|
||||
applyGains({ name, gain: value })
|
||||
onLevelChange?.(name, value)
|
||||
}
|
||||
|
||||
function updateMasterVolume(value: number) {
|
||||
setMasterVolume(value)
|
||||
setIsMuted(false)
|
||||
applyGains({ master: value, muted: false })
|
||||
}
|
||||
|
||||
function toggleMute() {
|
||||
if (isMuted) {
|
||||
setIsMuted(false)
|
||||
setMasterVolume(preMuteVolume)
|
||||
applyGains({ master: preMuteVolume, muted: false })
|
||||
} else {
|
||||
setPreMuteVolume(masterVolume)
|
||||
setIsMuted(true)
|
||||
applyGains({ muted: true })
|
||||
}
|
||||
}
|
||||
|
||||
function toggleStemMute(name: string) {
|
||||
setMutedStems((m) => {
|
||||
const next = { ...m, [name]: !(m[name] ?? false) }
|
||||
applyGains({ mutedStems: next })
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
function toggleStemSolo(name: string) {
|
||||
setSoloedStems((s) => {
|
||||
const next = { ...s, [name]: !(s[name] ?? false) }
|
||||
applyGains({ soloedStems: next })
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const allLoaded = stems.every((s) => loaded[s.name] !== false)
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* Playback controls */}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
onClick={togglePlay}
|
||||
disabled={!allLoaded}
|
||||
className="flex items-center justify-center w-9 h-9 rounded-full bg-brand-500 text-white hover:bg-brand-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors shrink-0"
|
||||
>
|
||||
{isPlaying ? (
|
||||
<svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
|
||||
<rect x="6" y="4" width="4" height="16" />
|
||||
<rect x="14" y="4" width="4" height="16" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={duration || 1}
|
||||
step={0.1}
|
||||
value={currentTime}
|
||||
onChange={(e) => handleSeek(parseFloat(e.target.value))}
|
||||
className="flex-1 min-w-[80px] h-2 bg-slate-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-brand-500"
|
||||
/>
|
||||
<span className="text-xs tabular-nums text-slate-500 dark:text-gray-400 shrink-0">
|
||||
{formatTime(currentTime)} / {formatTime(duration)}
|
||||
</span>
|
||||
|
||||
{/* Master volume */}
|
||||
<div className="flex items-center gap-1.5 pl-2 border-l border-slate-200 dark:border-gray-700 shrink-0">
|
||||
<button
|
||||
onClick={toggleMute}
|
||||
className="p-1.5 rounded-md text-slate-500 dark:text-gray-400 hover:text-slate-700 dark:hover:text-gray-200 hover:bg-slate-100 dark:hover:bg-gray-800 transition-colors"
|
||||
title={isMuted ? 'Unmute' : 'Mute'}
|
||||
>
|
||||
{isMuted || masterVolume === 0 ? (
|
||||
<VolumeX className="w-4 h-4" />
|
||||
) : (
|
||||
<Volume2 className="w-4 h-4" />
|
||||
)}
|
||||
</button>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.05}
|
||||
value={isMuted ? 0 : masterVolume}
|
||||
onChange={(e) => updateMasterVolume(parseFloat(e.target.value))}
|
||||
className="w-16 sm:w-20 h-2 bg-slate-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-brand-500"
|
||||
title="Master Volume"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Stem level sliders */}
|
||||
<div className="space-y-2 pt-2 border-t border-slate-200 dark:border-gray-700">
|
||||
{stems.map((stem) => (
|
||||
<div key={stem.name} className="flex items-center gap-1.5">
|
||||
<span className="text-xs font-medium text-slate-600 dark:text-gray-400 w-12 sm:w-16 truncate capitalize">
|
||||
{stem.label}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => toggleStemMute(stem.name)}
|
||||
title={mutedStems[stem.name] ? 'Unmute' : 'Mute'}
|
||||
className={`w-6 h-6 text-xs font-bold rounded transition-colors flex-shrink-0 ${
|
||||
mutedStems[stem.name]
|
||||
? 'bg-red-500 text-white'
|
||||
: 'bg-slate-200 dark:bg-gray-700 text-slate-600 dark:text-gray-400 hover:bg-slate-300 dark:hover:bg-gray-600'
|
||||
}`}
|
||||
>
|
||||
M
|
||||
</button>
|
||||
<button
|
||||
onClick={() => toggleStemSolo(stem.name)}
|
||||
title={soloedStems[stem.name] ? 'Unsolo' : 'Solo'}
|
||||
className={`w-6 h-6 text-xs font-bold rounded transition-colors flex-shrink-0 ${
|
||||
soloedStems[stem.name]
|
||||
? 'bg-yellow-400 text-black'
|
||||
: 'bg-slate-200 dark:bg-gray-700 text-slate-600 dark:text-gray-400 hover:bg-slate-300 dark:hover:bg-gray-600'
|
||||
}`}
|
||||
>
|
||||
S
|
||||
</button>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={2}
|
||||
step={0.1}
|
||||
value={gains[stem.name] ?? 1.0}
|
||||
onChange={(e) => updateGain(stem.name, parseFloat(e.target.value))}
|
||||
className="flex-1 h-2 bg-slate-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-brand-500"
|
||||
/>
|
||||
<span className="text-xs tabular-nums text-slate-500 dark:text-gray-400 w-9 text-right">
|
||||
{Math.round((gains[stem.name] ?? 1.0) * 100)}%
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function formatTime(s: number): string {
|
||||
const m = Math.floor(s / 60)
|
||||
const sec = Math.floor(s % 60)
|
||||
return `${m}:${sec.toString().padStart(2, '0')}`
|
||||
}
|
||||
Executable
+40
@@ -0,0 +1,40 @@
|
||||
import React, { useCallback } from 'react'
|
||||
import { Upload } from 'lucide-react'
|
||||
|
||||
interface Props {
|
||||
label?: string
|
||||
accept?: string
|
||||
onFiles: (files: File[]) => void
|
||||
}
|
||||
|
||||
export default function FileUpload({ label = 'Drop files here', accept, onFiles }: Props) {
|
||||
const handleDrop = useCallback(
|
||||
(e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
const files = Array.from(e.dataTransfer.files)
|
||||
if (files.length) onFiles(files)
|
||||
},
|
||||
[onFiles]
|
||||
)
|
||||
|
||||
const handleChange = useCallback(
|
||||
(e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const files = Array.from(e.target.files || [])
|
||||
if (files.length) onFiles(files)
|
||||
e.target.value = '' // reset for re-upload
|
||||
},
|
||||
[onFiles]
|
||||
)
|
||||
|
||||
return (
|
||||
<label
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
onDrop={handleDrop}
|
||||
className="flex flex-col items-center justify-center gap-3 px-6 py-10 rounded-xl border-2 border-dashed border-slate-300 dark:border-gray-700 bg-slate-50 dark:bg-gray-900/50 hover:border-brand-400 dark:hover:border-brand-500 hover:bg-slate-100 dark:hover:bg-gray-800/50 transition-colors cursor-pointer"
|
||||
>
|
||||
<Upload className="w-8 h-8 text-slate-400 dark:text-gray-600" />
|
||||
<span className="text-sm text-slate-600 dark:text-gray-400 text-center">{label}</span>
|
||||
<input type="file" accept={accept} onChange={handleChange} className="hidden" />
|
||||
</label>
|
||||
)
|
||||
}
|
||||
Executable
+105
@@ -0,0 +1,105 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { Volume2, VolumeX } from 'lucide-react'
|
||||
import { getMeta, getActions, subscribePlayback } from '../utils/audioRegistry'
|
||||
import type { PlaybackMeta } from '../utils/audioRegistry'
|
||||
|
||||
function fmtTime(s: number): string {
|
||||
const m = Math.floor(s / 60)
|
||||
return `${m}:${Math.floor(s % 60).toString().padStart(2, '0')}`
|
||||
}
|
||||
|
||||
export default function GlobalAudioBar() {
|
||||
const [meta, setMeta] = useState<PlaybackMeta | null>(() => getMeta())
|
||||
const prevVolumeRef = useRef(1)
|
||||
|
||||
useEffect(() => subscribePlayback(() => setMeta(getMeta())), [])
|
||||
|
||||
if (!meta) return null
|
||||
|
||||
const { title, isPlaying, currentTime, duration, volume } = meta
|
||||
|
||||
function handleMuteToggle() {
|
||||
if (volume === 0) {
|
||||
getActions().setVolume(prevVolumeRef.current || 1)
|
||||
} else {
|
||||
prevVolumeRef.current = volume
|
||||
getActions().setVolume(0)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed bottom-0 left-0 right-0 z-50 border-t border-slate-200 dark:border-gray-800 bg-white/95 dark:bg-gray-950/95 backdrop-blur-sm shadow-[0_-2px_8px_rgba(0,0,0,0.06)] dark:shadow-[0_-2px_8px_rgba(0,0,0,0.4)]">
|
||||
<div className="max-w-3xl mx-auto px-4 h-12 flex items-center gap-3">
|
||||
|
||||
{/* Play / Pause */}
|
||||
<button
|
||||
onClick={() => getActions().toggle()}
|
||||
className="flex items-center justify-center w-7 h-7 rounded-full bg-brand-500 text-white hover:bg-brand-600 transition-colors shrink-0"
|
||||
title={isPlaying ? 'Pause' : 'Play'}
|
||||
>
|
||||
{isPlaying ? (
|
||||
<svg className="w-3 h-3" fill="currentColor" viewBox="0 0 24 24">
|
||||
<rect x="6" y="4" width="4" height="16" />
|
||||
<rect x="14" y="4" width="4" height="16" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="w-3 h-3" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Current time */}
|
||||
<span className="text-xs tabular-nums text-slate-400 dark:text-gray-500 shrink-0 w-8 text-right">
|
||||
{fmtTime(currentTime)}
|
||||
</span>
|
||||
|
||||
{/* Seek slider */}
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={duration || 1}
|
||||
step={0.1}
|
||||
value={currentTime}
|
||||
onChange={e => getActions().seek(parseFloat(e.target.value))}
|
||||
className="flex-1 h-1.5 bg-slate-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-brand-500 min-w-0"
|
||||
/>
|
||||
|
||||
{/* Duration */}
|
||||
<span className="text-xs tabular-nums text-slate-400 dark:text-gray-500 shrink-0 w-8">
|
||||
{fmtTime(duration)}
|
||||
</span>
|
||||
|
||||
{/* Title */}
|
||||
<span
|
||||
className="text-xs font-medium text-slate-500 dark:text-gray-500 truncate shrink min-w-0 max-w-[120px] sm:max-w-[180px]"
|
||||
title={title}
|
||||
>
|
||||
{title}
|
||||
</span>
|
||||
|
||||
{/* Volume */}
|
||||
<div className="flex items-center gap-1 shrink-0 pl-2 border-l border-slate-200 dark:border-gray-700">
|
||||
<button
|
||||
onClick={handleMuteToggle}
|
||||
className="p-1 rounded text-slate-400 dark:text-gray-500 hover:text-slate-600 dark:hover:text-gray-300 transition-colors"
|
||||
title={volume === 0 ? 'Unmute' : 'Mute'}
|
||||
>
|
||||
{volume === 0 ? <VolumeX className="w-3.5 h-3.5" /> : <Volume2 className="w-3.5 h-3.5" />}
|
||||
</button>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.05}
|
||||
value={volume}
|
||||
onChange={e => getActions().setVolume(parseFloat(e.target.value))}
|
||||
className="w-14 h-1.5 bg-slate-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-brand-500"
|
||||
title="Volume"
|
||||
/>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Executable
+80
@@ -0,0 +1,80 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Loader2, CheckCircle, XCircle, AlertCircle } from 'lucide-react'
|
||||
import { getJob } from '../api/client'
|
||||
import type { Job } from '../types'
|
||||
|
||||
interface Props {
|
||||
jobId: string
|
||||
onDone?: (job: Job) => void
|
||||
}
|
||||
|
||||
export default function JobStatus({ jobId, onDone }: Props) {
|
||||
const [job, setJob] = useState<Job | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
let timeout: ReturnType<typeof setTimeout>
|
||||
|
||||
async function poll() {
|
||||
try {
|
||||
const j = await getJob(jobId)
|
||||
if (cancelled) return
|
||||
setJob(j)
|
||||
setError(null)
|
||||
|
||||
if (j.status === 'done' || j.status === 'error' || j.status === 'cancelled') {
|
||||
if (j.status === 'done') onDone?.(j)
|
||||
return
|
||||
}
|
||||
|
||||
timeout = setTimeout(poll, 2000)
|
||||
} catch (e) {
|
||||
if (cancelled) return
|
||||
setError(String(e))
|
||||
timeout = setTimeout(poll, 5000)
|
||||
}
|
||||
}
|
||||
|
||||
poll()
|
||||
return () => {
|
||||
cancelled = true
|
||||
clearTimeout(timeout)
|
||||
}
|
||||
}, [jobId, onDone])
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 text-xs text-red-500">
|
||||
<XCircle className="w-4 h-4" />
|
||||
Error: {error}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!job) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 text-xs text-slate-500">
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
Loading…
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const statusConfig: Record<string, { icon: React.ReactNode; text: string; color: string }> = {
|
||||
queued: { icon: <Loader2 className="w-4 h-4 animate-spin text-amber-500" />, text: 'Queued…', color: 'text-amber-600' },
|
||||
running: { icon: <Loader2 className="w-4 h-4 animate-spin text-brand-500" />, text: job.progress || 'Running…', color: 'text-brand-600' },
|
||||
done: { icon: <CheckCircle className="w-4 h-4 text-emerald-500" />, text: 'Complete', color: 'text-emerald-600' },
|
||||
error: { icon: <XCircle className="w-4 h-4 text-red-500" />, text: `Error: ${job.error || 'Failed'}`, color: 'text-red-600' },
|
||||
cancelled: { icon: <AlertCircle className="w-4 h-4 text-slate-400" />, text: 'Cancelled', color: 'text-slate-500' },
|
||||
}
|
||||
|
||||
const config = statusConfig[job.status]
|
||||
|
||||
return (
|
||||
<div className={`flex items-center gap-2 text-xs ${config.color}`}>
|
||||
{config.icon}
|
||||
<span className="truncate">{config.text}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+1486
File diff suppressed because it is too large.
Load diff
Executable
+45
@@ -0,0 +1,45 @@
|
||||
import React from 'react'
|
||||
import { Download, FileAudio, FileMusic, FileText, File } from 'lucide-react'
|
||||
import { downloadUrl } from '../api/client'
|
||||
import type { JobFile } from '../types'
|
||||
|
||||
interface Props {
|
||||
jobId: string
|
||||
files: JobFile[]
|
||||
}
|
||||
|
||||
const FILE_ICONS: Record<string, React.ElementType> = {
|
||||
stem: FileAudio,
|
||||
instrumental: FileAudio,
|
||||
static: FileAudio,
|
||||
dynamic: FileAudio,
|
||||
lrc: FileText,
|
||||
elrc: FileText,
|
||||
midi: FileMusic,
|
||||
}
|
||||
|
||||
function FileIcon({ type }: { type?: string }) {
|
||||
const Icon = FILE_ICONS[type || ''] || File
|
||||
return <Icon className="w-4 h-4 text-slate-400" />
|
||||
}
|
||||
|
||||
export default function ResultFiles({ jobId, files }: Props) {
|
||||
if (!files.length) return null
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{files.map((f) => (
|
||||
<a
|
||||
key={f.name}
|
||||
href={downloadUrl(jobId, f.name)}
|
||||
download={f.name}
|
||||
className="flex items-center gap-3 px-3 py-2 rounded-lg bg-slate-50 dark:bg-gray-800/50 border border-slate-200 dark:border-gray-700 hover:border-brand-400 dark:hover:border-brand-500 transition-colors group"
|
||||
>
|
||||
<FileIcon type={f.type} />
|
||||
<span className="flex-1 text-xs text-slate-700 dark:text-gray-300 truncate">{f.name}</span>
|
||||
<Download className="w-3.5 h-3.5 text-slate-400 group-hover:text-brand-500 transition-colors" />
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Executable
+100
@@ -0,0 +1,100 @@
|
||||
|
||||
import { X, Sun, Moon, Monitor, Settings, ChevronRight } from 'lucide-react'
|
||||
import { useTheme } from '../context/ThemeContext'
|
||||
|
||||
interface Props {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
onOpenFullSettings?: () => void
|
||||
}
|
||||
|
||||
export default function SettingsPanel({ isOpen, onClose, onOpenFullSettings }: Props) {
|
||||
const { theme, setTheme } = useTheme()
|
||||
|
||||
const handleOpenFullSettings = () => {
|
||||
onClose()
|
||||
onOpenFullSettings?.()
|
||||
}
|
||||
|
||||
if (!isOpen) return null
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-start justify-center pt-16">
|
||||
<div className="absolute inset-0 bg-black/50" onClick={onClose} />
|
||||
<div className="relative w-full max-w-md mx-4 rounded-xl bg-white dark:bg-gray-900 shadow-2xl border border-slate-200 dark:border-gray-800">
|
||||
<div className="flex items-center justify-between px-4 py-3 border-b border-slate-200 dark:border-gray-800">
|
||||
<h2 className="text-sm font-semibold text-slate-900 dark:text-white">Settings</h2>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="p-1 rounded text-slate-400 hover:text-slate-600 dark:text-gray-500 dark:hover:text-gray-300"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="p-4 space-y-4">
|
||||
{/* Theme */}
|
||||
<div>
|
||||
<label className="text-xs font-medium text-slate-500 dark:text-gray-400 uppercase tracking-wider block mb-2">
|
||||
Theme
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => setTheme('light')}
|
||||
className={`flex items-center gap-2 px-3 py-2 rounded-lg border text-xs font-medium transition-colors ${
|
||||
theme === 'light'
|
||||
? 'bg-brand-50 dark:bg-brand-950/30 border-brand-400 text-brand-600 dark:text-brand-400'
|
||||
: 'bg-white dark:bg-gray-800 border-slate-200 dark:border-gray-700 text-slate-600 dark:text-gray-400 hover:border-brand-400'
|
||||
}`}
|
||||
>
|
||||
<Sun className="w-3.5 h-3.5" />
|
||||
Light
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setTheme('dark')}
|
||||
className={`flex items-center gap-2 px-3 py-2 rounded-lg border text-xs font-medium transition-colors ${
|
||||
theme === 'dark'
|
||||
? 'bg-brand-50 dark:bg-brand-950/30 border-brand-400 text-brand-600 dark:text-brand-400'
|
||||
: 'bg-white dark:bg-gray-800 border-slate-200 dark:border-gray-700 text-slate-600 dark:text-gray-400 hover:border-brand-400'
|
||||
}`}
|
||||
>
|
||||
<Moon className="w-3.5 h-3.5" />
|
||||
Dark
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setTheme('system')}
|
||||
className={`flex items-center gap-2 px-3 py-2 rounded-lg border text-xs font-medium transition-colors ${
|
||||
theme === 'system'
|
||||
? 'bg-brand-50 dark:bg-brand-950/30 border-brand-400 text-brand-600 dark:text-brand-400'
|
||||
: 'bg-white dark:bg-gray-800 border-slate-200 dark:border-gray-700 text-slate-600 dark:text-gray-400 hover:border-brand-400'
|
||||
}`}
|
||||
>
|
||||
<Monitor className="w-3.5 h-3.5" />
|
||||
System
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="border-t border-slate-200 dark:border-gray-800 pt-4">
|
||||
<button
|
||||
onClick={handleOpenFullSettings}
|
||||
className="w-full flex items-center justify-between p-3 rounded-lg bg-slate-50 dark:bg-gray-800 hover:bg-slate-100 dark:hover:bg-gray-750 transition-colors group"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Settings className="w-4 h-4 text-slate-500 dark:text-gray-400" />
|
||||
<span className="text-sm font-medium text-slate-700 dark:text-gray-300">
|
||||
Full Settings
|
||||
</span>
|
||||
</div>
|
||||
<ChevronRight className="w-4 h-4 text-slate-400 group-hover:text-slate-600 dark:group-hover:text-gray-300 transition-colors" />
|
||||
</button>
|
||||
<p className="mt-1.5 text-xs text-slate-400 dark:text-gray-500 px-1">
|
||||
Configure Subsonic integration, manage AI models, and more.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Executable
+528
@@ -0,0 +1,528 @@
|
||||
import React, { useState, useRef, useMemo } from 'react'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
ChevronLeft, ChevronRight, Loader2, CheckCircle, XCircle,
|
||||
Clock, AlertCircle, X, Music2, Mic2, FileCode, Workflow,
|
||||
FolderOpen, Type, ChevronDown, ChevronUp, Radio, Search,
|
||||
Download, CheckCircle2, Trash2, Zap,
|
||||
} from 'lucide-react'
|
||||
import {
|
||||
listJobs, cancelJob,
|
||||
searchSubsonic, importSubsonicSong,
|
||||
listImports, deleteImport,
|
||||
listProjects, deleteProject,
|
||||
} from '../api/client'
|
||||
import type { Job, Project, SubsonicSong, ImportedFile } from '../types'
|
||||
import AutoPipelineDialog from './AutoPipelineDialog'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const JOB_COLORS: Record<string, string> = {
|
||||
separate: 'text-brand-500',
|
||||
transcribe: 'text-purple-500',
|
||||
'abc-convert': 'text-emerald-500',
|
||||
pipeline: 'text-rose-500',
|
||||
lrc_align: 'text-amber-500',
|
||||
mix: 'text-brand-500',
|
||||
}
|
||||
|
||||
const JOB_ICONS: Record<string, React.ElementType> = {
|
||||
separate: Music2,
|
||||
transcribe: Mic2,
|
||||
'abc-convert': FileCode,
|
||||
pipeline: Workflow,
|
||||
lrc_align: Type,
|
||||
mix: Music2,
|
||||
}
|
||||
|
||||
function StatusDot({ status }: { status: Job['status'] }) {
|
||||
switch (status) {
|
||||
case 'running': return <Loader2 className="w-3 h-3 text-brand-400 animate-spin shrink-0" />
|
||||
case 'queued': return <Clock className="w-3 h-3 text-amber-400 shrink-0" />
|
||||
case 'done': return <CheckCircle className="w-3 h-3 text-emerald-400 shrink-0" />
|
||||
case 'error': return <XCircle className="w-3 h-3 text-red-400 shrink-0" />
|
||||
case 'cancelled': return <AlertCircle className="w-3 h-3 text-gray-400 shrink-0" />
|
||||
}
|
||||
}
|
||||
|
||||
function timeSince(iso: string | null): string {
|
||||
if (!iso) return ''
|
||||
const ms = Date.now() - new Date(iso).getTime()
|
||||
const m = Math.floor(ms / 60000)
|
||||
if (m < 1) return 'just now'
|
||||
if (m < 60) return `${m}m ago`
|
||||
const h = Math.floor(m / 60)
|
||||
if (h < 24) return `${h}h ago`
|
||||
return `${Math.floor(h / 24)}d ago`
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Active job item (with cancel)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function ActiveJobItem({ job, onCancelled }: { job: Job; onCancelled: () => void }) {
|
||||
const [cancelling, setCancelling] = useState(false)
|
||||
const Icon = JOB_ICONS[job.job_type] ?? FolderOpen
|
||||
const colorCls = JOB_COLORS[job.job_type] ?? 'text-gray-400'
|
||||
|
||||
async function handleCancel(e: React.MouseEvent) {
|
||||
e.stopPropagation()
|
||||
setCancelling(true)
|
||||
try { await cancelJob(job.id) } catch { /* ignore */ }
|
||||
onCancelled()
|
||||
setCancelling(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-slate-50 dark:bg-gray-800/60 border border-slate-200 dark:border-gray-700/50">
|
||||
<Icon className={`w-3.5 h-3.5 shrink-0 ${colorCls}`} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-xs font-medium text-slate-700 dark:text-gray-200 truncate">
|
||||
{job.job_type.replace('-', ' ').replace('_', ' ')}
|
||||
</p>
|
||||
{job.progress && (
|
||||
<p className="text-xs text-slate-400 dark:text-gray-500 truncate leading-tight">{job.progress}</p>
|
||||
)}
|
||||
</div>
|
||||
<StatusDot status={job.status} />
|
||||
<button
|
||||
onClick={handleCancel}
|
||||
disabled={cancelling}
|
||||
title="Cancel"
|
||||
className="p-1 rounded text-slate-300 hover:text-red-400 dark:text-gray-600 dark:hover:text-red-400 transition-colors shrink-0"
|
||||
>
|
||||
{cancelling ? <Loader2 className="w-3 h-3 animate-spin" /> : <X className="w-3 h-3" />}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Project item
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function ProjectItem({
|
||||
project,
|
||||
isOpen,
|
||||
onOpen,
|
||||
onDeleted,
|
||||
}: {
|
||||
project: Project
|
||||
isOpen: boolean
|
||||
onOpen: () => void
|
||||
onDeleted: () => void
|
||||
}) {
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
|
||||
async function handleDelete(e: React.MouseEvent) {
|
||||
e.stopPropagation()
|
||||
if (!window.confirm(`Delete "${project.name}"?\n\nThis will permanently remove the project and all its files.`)) return
|
||||
setDeleting(true)
|
||||
try { await deleteProject(project.id) } catch { /* ignore */ }
|
||||
finally { setDeleting(false) }
|
||||
onDeleted()
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
onClick={onOpen}
|
||||
className={`group w-full flex items-center gap-2 px-3 py-2 rounded-lg border text-left transition-colors cursor-pointer ${
|
||||
isOpen
|
||||
? 'border-brand-400/50 bg-brand-50 dark:bg-brand-950/20 text-brand-700 dark:text-brand-300'
|
||||
: 'border-slate-200 dark:border-gray-700/60 hover:bg-slate-50 dark:hover:bg-gray-800/50 hover:border-brand-400/50'
|
||||
}`}
|
||||
>
|
||||
<Music2 className="w-3.5 h-3.5 shrink-0 text-brand-500" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-xs font-medium text-slate-700 dark:text-gray-200 truncate">{project.name}</p>
|
||||
{project.tab_label && (
|
||||
<p className="text-[10px] text-brand-500 dark:text-brand-400 truncate leading-tight">{project.tab_label}</p>
|
||||
)}
|
||||
<p className="text-[10px] text-slate-400 dark:text-gray-500">{timeSince(project.created_at)}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleDelete}
|
||||
disabled={deleting}
|
||||
title="Delete project"
|
||||
className="shrink-0 p-1 rounded text-slate-300 dark:text-gray-600 hover:text-red-500 dark:hover:text-red-400 transition-colors opacity-0 group-hover:opacity-100"
|
||||
>
|
||||
{deleting ? <Loader2 className="w-3 h-3 animate-spin" /> : <Trash2 className="w-3 h-3" />}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Subsonic import panel
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function formatDuration(secs: number): string {
|
||||
const m = Math.floor(secs / 60)
|
||||
const s = secs % 60
|
||||
return `${m}:${String(s).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
function SubsonicPanel() {
|
||||
const queryClient = useQueryClient()
|
||||
const [open, setOpen] = useState(false)
|
||||
const [query, setQuery] = useState('')
|
||||
const [results, setResults] = useState<SubsonicSong[]>([])
|
||||
const [searching, setSearching] = useState(false)
|
||||
const [searchErr, setSearchErr] = useState<string | null>(null)
|
||||
const [importing, setImporting] = useState<string | null>(null)
|
||||
const [importedIds, setImportedIds] = useState<Set<string>>(new Set())
|
||||
const [importErr, setImportErr] = useState<string | null>(null)
|
||||
const [deletingFile, setDeletingFile] = useState<string | null>(null)
|
||||
const [autoTarget, setAutoTarget] = useState<ImportedFile | null>(null)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const { data: importedFiles = [], refetch: refetchImports } = useQuery<ImportedFile[]>({
|
||||
queryKey: ['imports'],
|
||||
queryFn: listImports,
|
||||
enabled: open,
|
||||
refetchInterval: open ? 10000 : false,
|
||||
})
|
||||
|
||||
async function doSearch() {
|
||||
if (!query.trim()) return
|
||||
setSearching(true); setSearchErr(null); setResults([])
|
||||
try {
|
||||
const res = await searchSubsonic(query.trim())
|
||||
setResults(res)
|
||||
if (res.length === 0) setSearchErr('No results found.')
|
||||
} catch (e) {
|
||||
setSearchErr(String(e))
|
||||
} finally {
|
||||
setSearching(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function doImport(song: SubsonicSong) {
|
||||
setImporting(song.id); setImportErr(null)
|
||||
try {
|
||||
await importSubsonicSong(song)
|
||||
setImportedIds((prev) => new Set(prev).add(song.id))
|
||||
refetchImports()
|
||||
queryClient.invalidateQueries({ queryKey: ['imports'] })
|
||||
} catch (e) {
|
||||
setImportErr(String(e))
|
||||
} finally {
|
||||
setImporting(null)
|
||||
}
|
||||
}
|
||||
|
||||
async function doDeleteImport(filename: string) {
|
||||
setDeletingFile(filename)
|
||||
try {
|
||||
await deleteImport(filename)
|
||||
refetchImports()
|
||||
queryClient.invalidateQueries({ queryKey: ['imports'] })
|
||||
} catch { /* ignore */ }
|
||||
finally { setDeletingFile(null) }
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="border-b border-slate-200 dark:border-gray-800">
|
||||
<button
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className="w-full flex items-center gap-2 px-3 py-2.5 text-left hover:bg-slate-100 dark:hover:bg-gray-900/50 transition-colors"
|
||||
>
|
||||
<Radio className="w-3.5 h-3.5 text-sky-500 shrink-0" />
|
||||
<span className="text-xs font-bold uppercase tracking-widest text-sky-500 flex-1">Subsonic Import</span>
|
||||
{open
|
||||
? <ChevronUp className="w-3 h-3 text-slate-400 shrink-0" />
|
||||
: <ChevronDown className="w-3 h-3 text-slate-400 shrink-0" />}
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<div className="px-3 pb-3 space-y-2">
|
||||
{/* Search input */}
|
||||
<div className="flex gap-1.5">
|
||||
<input
|
||||
ref={inputRef}
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && doSearch()}
|
||||
placeholder="Search songs…"
|
||||
className="flex-1 rounded-md bg-white dark:bg-gray-900 border border-slate-300 dark:border-gray-700 px-2.5 py-1.5 text-xs text-slate-900 dark:text-gray-100 placeholder-slate-400 focus:border-sky-400 focus:outline-none"
|
||||
/>
|
||||
<button
|
||||
onClick={doSearch}
|
||||
disabled={searching || !query.trim()}
|
||||
className="rounded-md bg-sky-500 hover:bg-sky-400 disabled:bg-slate-200 dark:disabled:bg-gray-800 disabled:text-slate-400 px-2.5 py-1.5 text-xs font-medium text-white transition-colors shrink-0"
|
||||
>
|
||||
{searching ? <Loader2 className="w-3 h-3 animate-spin" /> : <Search className="w-3 h-3" />}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Errors */}
|
||||
{searchErr && <p className="text-xs text-red-500 dark:text-red-400">{searchErr}</p>}
|
||||
{importErr && <p className="text-xs text-red-500 dark:text-red-400 break-all">{importErr}</p>}
|
||||
|
||||
{/* Search results */}
|
||||
{results.length > 0 && (
|
||||
<div className="space-y-1 max-h-52 overflow-y-auto pr-0.5">
|
||||
{results.map((song) => {
|
||||
const done = importedIds.has(song.id)
|
||||
const busy = importing === song.id
|
||||
return (
|
||||
<div
|
||||
key={song.id}
|
||||
className="flex items-start gap-2 rounded-lg border border-slate-200 dark:border-gray-700/60 bg-white dark:bg-gray-900/50 px-2.5 py-2"
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-xs font-medium text-slate-700 dark:text-gray-200 truncate leading-tight">
|
||||
{song.title}
|
||||
</p>
|
||||
{song.artist && (
|
||||
<p className="text-[10px] text-slate-400 dark:text-gray-500 truncate leading-tight">
|
||||
{song.artist}{song.album ? ` · ${song.album}` : ''}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-[10px] text-slate-400 dark:text-gray-600 mt-0.5">
|
||||
{song.duration ? formatDuration(song.duration) : ''}{song.bitRate ? ` · ${song.bitRate} kbps` : ''}{song.suffix ? ` · ${song.suffix.toUpperCase()}` : ''}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => doImport(song)}
|
||||
disabled={busy || done}
|
||||
title={done ? 'Imported' : 'Import'}
|
||||
className="shrink-0 p-1.5 rounded-md border border-slate-200 dark:border-gray-700 bg-slate-50 dark:bg-gray-800 hover:border-sky-400 hover:text-sky-500 disabled:opacity-60 transition-colors"
|
||||
>
|
||||
{busy
|
||||
? <Loader2 className="w-3 h-3 animate-spin text-sky-400" />
|
||||
: done
|
||||
? <CheckCircle2 className="w-3 h-3 text-emerald-500" />
|
||||
: <Download className="w-3 h-3 text-slate-500 dark:text-gray-400" />}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Imported files list */}
|
||||
{importedFiles.length > 0 && (
|
||||
<div>
|
||||
<p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 dark:text-gray-600 mb-1">Imported Files</p>
|
||||
<div className="space-y-1 max-h-40 overflow-y-auto">
|
||||
{importedFiles.map((f) => {
|
||||
const isDeleting = deletingFile === f.filename
|
||||
return (
|
||||
<div
|
||||
key={f.path}
|
||||
className="group flex items-center gap-2 rounded-lg border border-slate-200 dark:border-gray-700/60 bg-white dark:bg-gray-900/50 px-2.5 py-1.5"
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-xs font-medium text-slate-700 dark:text-gray-200 truncate">{f.filename}</p>
|
||||
<p className="text-[10px] text-slate-400 dark:text-gray-500">{(f.size / 1024 / 1024).toFixed(1)} MB</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setAutoTarget(f)}
|
||||
title="Auto pipeline"
|
||||
className="shrink-0 p-1 rounded text-slate-300 dark:text-gray-600 hover:text-amber-500 dark:hover:text-amber-400 transition-colors opacity-0 group-hover:opacity-100"
|
||||
>
|
||||
<Zap className="w-3 h-3" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => doDeleteImport(f.filename)}
|
||||
disabled={isDeleting}
|
||||
title="Delete import"
|
||||
className="shrink-0 p-1 rounded text-slate-300 dark:text-gray-600 hover:text-red-500 dark:hover:text-red-400 transition-colors opacity-0 group-hover:opacity-100"
|
||||
>
|
||||
{isDeleting
|
||||
? <Loader2 className="w-3 h-3 animate-spin" />
|
||||
: <Trash2 className="w-3 h-3" />}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{autoTarget && (
|
||||
<AutoPipelineDialog
|
||||
target={{
|
||||
filePath: autoTarget.path,
|
||||
filename: autoTarget.filename,
|
||||
initialProjectName: autoTarget.artist && autoTarget.title
|
||||
? `${autoTarget.artist} - ${autoTarget.title}`
|
||||
: autoTarget.filename.replace(/\.[^/.]+$/, ''),
|
||||
}}
|
||||
onClose={() => setAutoTarget(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Sidebar
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface Props {
|
||||
isOpen: boolean
|
||||
onToggle: () => void
|
||||
onOpenProject: (project: Project) => void
|
||||
onDeleteProject: (project: Project) => void
|
||||
openTabIds: string[] // IDs of project tabs currently open in the tab bar
|
||||
}
|
||||
|
||||
export default function Sidebar({ isOpen, onToggle, onOpenProject, onDeleteProject, openTabIds }: Props) {
|
||||
const queryClient = useQueryClient()
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
|
||||
const { data: jobs = [] } = useQuery({
|
||||
queryKey: ['jobs'],
|
||||
queryFn: listJobs,
|
||||
refetchInterval: 3000,
|
||||
})
|
||||
|
||||
const { data: projects = [] } = useQuery<Project[]>({
|
||||
queryKey: ['projects'],
|
||||
queryFn: listProjects,
|
||||
refetchInterval: 8000,
|
||||
})
|
||||
|
||||
// Filter projects based on search query
|
||||
const filteredProjects = useMemo(() => {
|
||||
if (!searchQuery.trim()) return projects
|
||||
const query = searchQuery.toLowerCase()
|
||||
return projects.filter(p =>
|
||||
p.name.toLowerCase().includes(query) ||
|
||||
p.tab_label.toLowerCase().includes(query)
|
||||
)
|
||||
}, [projects, searchQuery])
|
||||
|
||||
const activeJobs = jobs.filter((j) => j.status === 'running' || j.status === 'queued')
|
||||
|
||||
function invalidate() { queryClient.invalidateQueries({ queryKey: ['jobs'] }) }
|
||||
|
||||
return (
|
||||
<aside
|
||||
className={`relative flex-shrink-0 flex flex-col border-r border-slate-200 dark:border-gray-800 bg-slate-50 dark:bg-gray-950 transition-all duration-200 ease-in-out ${
|
||||
isOpen ? 'sidebar-open' : 'sidebar-closed'
|
||||
}`}
|
||||
>
|
||||
{/* Toggle tab — always visible */}
|
||||
<button
|
||||
onClick={onToggle}
|
||||
title={isOpen ? 'Collapse sidebar' : 'Expand sidebar'}
|
||||
className={`absolute -right-3.5 top-6 z-10 flex items-center justify-center w-7 h-7 rounded-full bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 shadow-sm text-slate-400 hover:text-brand-500 dark:text-gray-500 dark:hover:text-brand-400 transition-colors`}
|
||||
>
|
||||
{isOpen ? <ChevronLeft className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
|
||||
</button>
|
||||
|
||||
{/* Collapsed indicator strip */}
|
||||
{!isOpen && (
|
||||
<div className="flex flex-col items-center gap-3 pt-16 px-2">
|
||||
{activeJobs.length > 0 && (
|
||||
<div className="relative">
|
||||
<Loader2 className="w-5 h-5 text-brand-400 animate-spin" />
|
||||
<span className="absolute -top-1 -right-1 w-3.5 h-3.5 rounded-full bg-brand-500 text-white text-[9px] flex items-center justify-center font-bold">
|
||||
{activeJobs.length}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<Radio className="w-5 h-5 text-slate-400 dark:text-gray-600" />
|
||||
{projects.length > 0 && (
|
||||
<div className="relative">
|
||||
<FolderOpen className="w-5 h-5 text-slate-400 dark:text-gray-600" />
|
||||
<span className="absolute -top-1 -right-1 w-3.5 h-3.5 rounded-full bg-slate-400 dark:bg-gray-600 text-white text-[9px] flex items-center justify-center font-bold">
|
||||
{projects.length}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Expanded content */}
|
||||
{isOpen && (
|
||||
<div className="flex flex-col flex-1 overflow-hidden">
|
||||
{/* Active jobs */}
|
||||
<div className="p-3 border-b border-slate-200 dark:border-gray-800">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<span className="text-xs font-bold uppercase tracking-widest text-amber-500">
|
||||
In Progress
|
||||
</span>
|
||||
{activeJobs.length > 0 && (
|
||||
<span className="ml-auto text-xs bg-amber-500 text-white px-1.5 py-0.5 rounded-full font-bold">
|
||||
{activeJobs.length}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{activeJobs.length === 0 ? (
|
||||
<p className="text-xs text-slate-400 dark:text-gray-600 italic text-center py-2">No active jobs</p>
|
||||
) : (
|
||||
<div className="space-y-1.5">
|
||||
{activeJobs.map((job) => (
|
||||
<ActiveJobItem key={job.id} job={job} onCancelled={invalidate} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Subsonic import */}
|
||||
<SubsonicPanel />
|
||||
|
||||
{/* Projects */}
|
||||
<div className="flex-1 overflow-y-auto p-3 space-y-1.5">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<span className="text-xs font-bold uppercase tracking-widest text-brand-500">Projects</span>
|
||||
{projects.length > 0 && (
|
||||
<span className="ml-auto text-xs text-slate-400 dark:text-gray-600">
|
||||
{filteredProjects.length}/{projects.length}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Search box for projects */}
|
||||
<div className="relative mb-2">
|
||||
<Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3 h-3 text-slate-400" />
|
||||
<input
|
||||
type="text"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
placeholder="Search projects..."
|
||||
className="w-full rounded-md bg-white dark:bg-gray-900 border border-slate-300 dark:border-gray-700 pl-7 pr-2 py-1.5 text-xs text-slate-900 dark:text-gray-100 placeholder-slate-400 focus:border-brand-400 focus:outline-none"
|
||||
/>
|
||||
{searchQuery && (
|
||||
<button
|
||||
onClick={() => setSearchQuery('')}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
|
||||
>
|
||||
<X className="w-3 h-3" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{filteredProjects.length === 0 ? (
|
||||
<p className="text-xs text-slate-400 dark:text-gray-600 italic text-center py-4">
|
||||
{searchQuery ? 'No projects match your search.' : 'Completed separations appear here.'}
|
||||
</p>
|
||||
) : (
|
||||
filteredProjects.map((project) => (
|
||||
<ProjectItem
|
||||
key={project.id}
|
||||
project={project}
|
||||
isOpen={openTabIds.includes(project.id)}
|
||||
onOpen={() => onOpenProject(project)}
|
||||
onDeleted={() => {
|
||||
queryClient.invalidateQueries({ queryKey: ['projects'] })
|
||||
onDeleteProject(project)
|
||||
}}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
Executable
+63
@@ -0,0 +1,63 @@
|
||||
import React, { createContext, useContext, useEffect, useState } from 'react'
|
||||
|
||||
type Theme = 'light' | 'dark' | 'system'
|
||||
|
||||
interface ThemeContextType {
|
||||
theme: Theme
|
||||
resolved: 'light' | 'dark'
|
||||
setTheme: (t: Theme) => void
|
||||
}
|
||||
|
||||
const ThemeContext = createContext<ThemeContextType | undefined>(undefined)
|
||||
|
||||
export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
||||
const [theme, setThemeState] = useState<Theme>(() => {
|
||||
if (typeof window === 'undefined') return 'system'
|
||||
return (localStorage.getItem('theme') as Theme) || 'system'
|
||||
})
|
||||
|
||||
const [resolved, setResolved] = useState<'light' | 'dark'>('dark')
|
||||
|
||||
useEffect(() => {
|
||||
const root = document.documentElement
|
||||
const media = window.matchMedia('(prefers-color-scheme: dark)')
|
||||
|
||||
function apply() {
|
||||
let r: 'light' | 'dark'
|
||||
if (theme === 'system') {
|
||||
r = media.matches ? 'dark' : 'light'
|
||||
} else {
|
||||
r = theme
|
||||
}
|
||||
setResolved(r)
|
||||
if (r === 'dark') {
|
||||
root.classList.add('dark')
|
||||
} else {
|
||||
root.classList.remove('dark')
|
||||
}
|
||||
}
|
||||
|
||||
apply()
|
||||
localStorage.setItem('theme', theme)
|
||||
|
||||
const listener = () => apply()
|
||||
media.addEventListener('change', listener)
|
||||
return () => media.removeEventListener('change', listener)
|
||||
}, [theme])
|
||||
|
||||
function setTheme(t: Theme) {
|
||||
setThemeState(t)
|
||||
}
|
||||
|
||||
return (
|
||||
<ThemeContext.Provider value={{ theme, resolved, setTheme }}>
|
||||
{children}
|
||||
</ThemeContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useTheme() {
|
||||
const ctx = useContext(ThemeContext)
|
||||
if (!ctx) throw new Error('useTheme must be used within ThemeProvider')
|
||||
return ctx
|
||||
}
|
||||
Executable
+163
@@ -0,0 +1,163 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
/* ── Brand color palette (default: Blue) ─────────────────────────────────────
|
||||
Values are bare RGB channels so Tailwind's opacity modifier works:
|
||||
bg-brand-500/30 → rgb(var(--brand-500) / 0.3)
|
||||
──────────────────────────────────────────────────────────────────────────── */
|
||||
:root {
|
||||
--brand-50: 239 246 255;
|
||||
--brand-100: 219 234 254;
|
||||
--brand-200: 191 219 254;
|
||||
--brand-300: 147 197 253;
|
||||
--brand-400: 96 165 250;
|
||||
--brand-500: 59 130 246;
|
||||
--brand-600: 37 99 235;
|
||||
--brand-700: 29 78 216;
|
||||
--brand-800: 30 64 175;
|
||||
--brand-900: 30 58 138;
|
||||
--brand-950: 23 37 84;
|
||||
}
|
||||
|
||||
/* ── Violet ─────────────────────────────────────────────────────────────── */
|
||||
[data-accent="violet"] {
|
||||
--brand-50: 245 243 255;
|
||||
--brand-100: 237 233 254;
|
||||
--brand-200: 221 214 254;
|
||||
--brand-300: 196 181 253;
|
||||
--brand-400: 167 139 250;
|
||||
--brand-500: 139 92 246;
|
||||
--brand-600: 124 58 237;
|
||||
--brand-700: 109 40 217;
|
||||
--brand-800: 91 33 182;
|
||||
--brand-900: 76 29 149;
|
||||
--brand-950: 46 16 101;
|
||||
}
|
||||
|
||||
/* ── Rose ────────────────────────────────────────────────────────────────── */
|
||||
[data-accent="rose"] {
|
||||
--brand-50: 255 241 242;
|
||||
--brand-100: 255 228 230;
|
||||
--brand-200: 254 205 211;
|
||||
--brand-300: 253 164 175;
|
||||
--brand-400: 251 113 133;
|
||||
--brand-500: 244 63 94;
|
||||
--brand-600: 225 29 72;
|
||||
--brand-700: 190 18 60;
|
||||
--brand-800: 159 18 57;
|
||||
--brand-900: 136 19 55;
|
||||
--brand-950: 76 5 25;
|
||||
}
|
||||
|
||||
/* ── Emerald ─────────────────────────────────────────────────────────────── */
|
||||
[data-accent="emerald"] {
|
||||
--brand-50: 236 253 245;
|
||||
--brand-100: 209 250 229;
|
||||
--brand-200: 167 243 208;
|
||||
--brand-300: 110 231 183;
|
||||
--brand-400: 52 211 153;
|
||||
--brand-500: 16 185 129;
|
||||
--brand-600: 5 150 105;
|
||||
--brand-700: 4 120 87;
|
||||
--brand-800: 6 95 70;
|
||||
--brand-900: 6 78 59;
|
||||
--brand-950: 2 44 34;
|
||||
}
|
||||
|
||||
/* ── Amber ───────────────────────────────────────────────────────────────── */
|
||||
[data-accent="amber"] {
|
||||
--brand-50: 255 251 235;
|
||||
--brand-100: 254 243 199;
|
||||
--brand-200: 253 230 138;
|
||||
--brand-300: 252 211 77;
|
||||
--brand-400: 251 191 36;
|
||||
--brand-500: 245 158 11;
|
||||
--brand-600: 217 119 6;
|
||||
--brand-700: 180 83 9;
|
||||
--brand-800: 146 64 14;
|
||||
--brand-900: 120 53 15;
|
||||
--brand-950: 69 26 3;
|
||||
}
|
||||
|
||||
/* ── Cyan ────────────────────────────────────────────────────────────────── */
|
||||
[data-accent="cyan"] {
|
||||
--brand-50: 236 254 255;
|
||||
--brand-100: 207 250 254;
|
||||
--brand-200: 165 243 252;
|
||||
--brand-300: 103 232 249;
|
||||
--brand-400: 34 211 238;
|
||||
--brand-500: 6 182 212;
|
||||
--brand-600: 8 145 178;
|
||||
--brand-700: 14 116 144;
|
||||
--brand-800: 21 94 117;
|
||||
--brand-900: 22 78 99;
|
||||
--brand-950: 8 51 68;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
html {
|
||||
@apply h-full;
|
||||
}
|
||||
body {
|
||||
@apply h-full antialiased;
|
||||
}
|
||||
#root {
|
||||
@apply h-full;
|
||||
}
|
||||
}
|
||||
|
||||
@layer utilities {
|
||||
.sidebar-open {
|
||||
@apply w-72;
|
||||
}
|
||||
.sidebar-closed {
|
||||
@apply w-14;
|
||||
}
|
||||
}
|
||||
|
||||
/* On small screens the sidebar overlays content instead of pushing it */
|
||||
@media (max-width: 639px) {
|
||||
.sidebar-open {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
z-index: 30;
|
||||
width: theme('spacing.72');
|
||||
}
|
||||
.sidebar-closed {
|
||||
width: theme('spacing.10');
|
||||
}
|
||||
}
|
||||
|
||||
/* Custom scrollbar */
|
||||
::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
@apply bg-transparent;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
@apply bg-slate-300 dark:bg-gray-600 rounded-full;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
@apply bg-slate-400 dark:bg-gray-500;
|
||||
}
|
||||
|
||||
/* Range input styling */
|
||||
input[type="range"] {
|
||||
@apply bg-slate-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer;
|
||||
}
|
||||
|
||||
input[type="range"]::-webkit-slider-thumb {
|
||||
@apply appearance-none w-4 h-4 rounded-full bg-brand-500 cursor-pointer;
|
||||
}
|
||||
|
||||
input[type="range"]::-moz-range-thumb {
|
||||
@apply w-4 h-4 rounded-full bg-brand-500 cursor-pointer border-0;
|
||||
}
|
||||
Executable
+28
@@ -0,0 +1,28 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import App from './App'
|
||||
import './index.css'
|
||||
|
||||
if ('serviceWorker' in navigator) {
|
||||
window.addEventListener('load', () => {
|
||||
navigator.serviceWorker.register('/sw.js').catch(() => {/* SW registration is best-effort */})
|
||||
})
|
||||
}
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 5000,
|
||||
retry: 1,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<App />
|
||||
</QueryClientProvider>
|
||||
</React.StrictMode>,
|
||||
)
|
||||
Executable
+1679
File diff suppressed because it is too large.
Load diff
Executable
+501
@@ -0,0 +1,501 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { RefreshCw, Radio, Zap } from 'lucide-react'
|
||||
import FileUpload from '../components/FileUpload'
|
||||
import JobStatus from '../components/JobStatus'
|
||||
import ResultFiles from '../components/ResultFiles'
|
||||
import AutoPipelineDialog from '../components/AutoPipelineDialog'
|
||||
import {
|
||||
getSepModels, getSepFormats, getPresets, submitSeparate, extractLyrics,
|
||||
listImports, submitSeparateFromPath,
|
||||
} from '../api/client'
|
||||
import type { Job, ModelOption, PresetsResponse, DynamicLevels, ImportedFile } from '../types'
|
||||
|
||||
const SELECT_CLS = 'w-full rounded-lg bg-white dark:bg-gray-900 border border-slate-300 dark:border-gray-700 px-3 py-2 text-sm text-slate-900 dark:text-gray-100 focus:border-brand-500 focus:outline-none'
|
||||
const INPUT_CLS = 'w-full rounded-lg bg-white dark:bg-gray-900 border border-slate-300 dark:border-gray-700 px-3 py-2 text-sm text-slate-900 dark:text-gray-100 focus:border-brand-500 focus:outline-none'
|
||||
const SLIDER_CLS = 'w-full h-2 bg-slate-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-brand-600'
|
||||
|
||||
function groupModels(models: ModelOption[]) {
|
||||
const groups: Record<string, ModelOption[]> = {}
|
||||
for (const m of models) {
|
||||
const g = m.group ?? 'Other'
|
||||
if (!groups[g]) groups[g] = []
|
||||
groups[g].push(m)
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
const DEFAULT_DYNAMIC_LEVELS: DynamicLevels = {
|
||||
vocals: 1.0,
|
||||
drums: 1.0,
|
||||
bass: 1.0,
|
||||
other: 1.0,
|
||||
}
|
||||
|
||||
interface Props {
|
||||
onSeparationComplete?: (projectId: string, tabLabel: string, projectName: string) => void
|
||||
onOpenSettings?: () => void
|
||||
}
|
||||
|
||||
export default function Separator({ onSeparationComplete, onOpenSettings }: Props) {
|
||||
const [inputMode, setInputMode] = useState<'upload' | 'imported'>('upload')
|
||||
const [file, setFile] = useState<File | null>(null)
|
||||
const [importedFile, setImportedFile] = useState<ImportedFile | null>(null)
|
||||
const [model, setModel] = useState('htdemucs')
|
||||
const [format, setFormat] = useState('mp3')
|
||||
const [presetType, setPresetType] = useState('stems_only')
|
||||
const [staticOption, setStaticOption] = useState('no_vocals')
|
||||
const [dynamicLevels, setDynamicLevels] = useState<DynamicLevels>(DEFAULT_DYNAMIC_LEVELS)
|
||||
const [projectName, setProjectName] = useState('')
|
||||
const [metadata, setMetadata] = useState<{artist?: string; title?: string}>({})
|
||||
const [jobId, setJobId] = useState<string | null>(null)
|
||||
const [result, setResult] = useState<Job | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [showAuto, setShowAuto] = useState(false)
|
||||
|
||||
const { data: models = [] } = useQuery({ queryKey: ['sep-models'], queryFn: getSepModels })
|
||||
const { data: formats = [] } = useQuery({ queryKey: ['sep-formats'], queryFn: getSepFormats })
|
||||
const { data: presets } = useQuery<PresetsResponse>({ queryKey: ['sep-presets'], queryFn: getPresets })
|
||||
const { data: imports = [], refetch: refetchImports } = useQuery<ImportedFile[]>({
|
||||
queryKey: ['imports'],
|
||||
queryFn: listImports,
|
||||
enabled: inputMode === 'imported',
|
||||
refetchInterval: inputMode === 'imported' ? 5000 : false,
|
||||
})
|
||||
|
||||
const grouped = groupModels(models)
|
||||
|
||||
// Read layout preferences saved in Settings → Model Settings
|
||||
const hiddenGroups = new Set<string>((() => {
|
||||
try { return JSON.parse(localStorage.getItem('se-model-hidden-groups') || '[]') as string[] }
|
||||
catch { return [] }
|
||||
})())
|
||||
const hiddenModels = new Set<string>((() => {
|
||||
try { return JSON.parse(localStorage.getItem('se-model-hidden-models') || '[]') as string[] }
|
||||
catch { return [] }
|
||||
})())
|
||||
const groupOrder: string[] = (() => {
|
||||
try { return JSON.parse(localStorage.getItem('se-model-group-order') || 'null') || [] }
|
||||
catch { return [] }
|
||||
})()
|
||||
const modelOrder: Record<string, string[]> = (() => {
|
||||
try { return JSON.parse(localStorage.getItem('se-model-model-order') || 'null') || {} }
|
||||
catch { return {} }
|
||||
})()
|
||||
|
||||
// Build visible + ordered groups (mirrors Settings ModelDownloader logic)
|
||||
const allGroupNames = Object.keys(grouped)
|
||||
const orderedGroupNames = [
|
||||
...groupOrder.filter(g => allGroupNames.includes(g)),
|
||||
...allGroupNames.filter(g => !groupOrder.includes(g)),
|
||||
]
|
||||
const visibleGrouped: Record<string, ModelOption[]> = {}
|
||||
for (const group of orderedGroupNames) {
|
||||
if (hiddenGroups.has(group)) continue
|
||||
const rawModels = grouped[group] || []
|
||||
const order = modelOrder[group] || rawModels.map(m => m.id)
|
||||
const ids = rawModels.map(m => m.id)
|
||||
const sorted = [
|
||||
...order.filter(id => ids.includes(id)).map(id => rawModels.find(m => m.id === id)!),
|
||||
...rawModels.filter(m => !order.includes(m.id)),
|
||||
]
|
||||
const visible = sorted.filter(m => !hiddenModels.has(m.id))
|
||||
if (visible.length > 0) visibleGrouped[group] = visible
|
||||
}
|
||||
|
||||
const rawGroup = models.find(m => m.id === model)?.group
|
||||
const selectedGroup = (rawGroup && visibleGrouped[rawGroup])
|
||||
? rawGroup
|
||||
: Object.keys(visibleGrouped)[0] ?? ''
|
||||
const isBSR = model.startsWith('bs_roformer_')
|
||||
|
||||
function handleGroupChange(group: string) {
|
||||
const first = visibleGrouped[group]?.[0]
|
||||
if (first) setModel(first.id)
|
||||
}
|
||||
|
||||
// Reset selected model when it becomes hidden/invisible
|
||||
useEffect(() => {
|
||||
if (!models.length) return
|
||||
const foundGroup = models.find(m => m.id === model)?.group
|
||||
const isVisible = foundGroup && visibleGrouped[foundGroup]?.some(m => m.id === model)
|
||||
if (!isVisible) {
|
||||
const firstGroup = Object.keys(visibleGrouped)[0]
|
||||
const firstModel = firstGroup ? visibleGrouped[firstGroup]?.[0] : undefined
|
||||
if (firstModel) setModel(firstModel.id)
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [models])
|
||||
|
||||
// Fire callback when a separation job completes
|
||||
const firedRef = useRef<string | null>(null)
|
||||
useEffect(() => {
|
||||
if (
|
||||
result?.status === 'done' &&
|
||||
result.result?.project_id &&
|
||||
result.result?.tab_label &&
|
||||
onSeparationComplete &&
|
||||
firedRef.current !== result.id
|
||||
) {
|
||||
firedRef.current = result.id
|
||||
onSeparationComplete(
|
||||
result.result.project_id,
|
||||
result.result.tab_label,
|
||||
result.result.project_name ?? '',
|
||||
)
|
||||
}
|
||||
}, [result, onSeparationComplete])
|
||||
|
||||
// Extract metadata when file changes
|
||||
useEffect(() => {
|
||||
if (!file) {
|
||||
setMetadata({})
|
||||
setProjectName('')
|
||||
return
|
||||
}
|
||||
|
||||
// Try to extract metadata from the file
|
||||
extractLyrics(file).then(() => {
|
||||
// Use filename as fallback
|
||||
const filename = file.name.replace(/\.[^/.]+$/, '')
|
||||
setMetadata({ artist: '', title: filename })
|
||||
}).catch(() => {
|
||||
const filename = file.name.replace(/\.[^/.]+$/, '')
|
||||
setMetadata({ artist: '', title: filename })
|
||||
})
|
||||
}, [file])
|
||||
|
||||
// Auto-generate project name from metadata
|
||||
useEffect(() => {
|
||||
if (metadata.artist && metadata.title) {
|
||||
setProjectName(`${metadata.artist} - ${metadata.title}`)
|
||||
} else if (metadata.title) {
|
||||
setProjectName(metadata.title)
|
||||
} else if (file) {
|
||||
setProjectName(file.name.replace(/\.[^/.]+$/, ''))
|
||||
}
|
||||
}, [metadata, file])
|
||||
|
||||
async function submit() {
|
||||
if (inputMode === 'upload' && !file) return
|
||||
if (inputMode === 'imported' && !importedFile) return
|
||||
setError(null); setResult(null); setJobId(null); setLoading(true)
|
||||
try {
|
||||
const sepPowerPreset = localStorage.getItem('stemengine-sep-power') ?? 'standard'
|
||||
const opts = {
|
||||
presetType,
|
||||
projectName: projectName || undefined,
|
||||
staticOption: presetType === 'static' ? staticOption : undefined,
|
||||
dynamicLevels: presetType === 'dynamic' ? dynamicLevels : undefined,
|
||||
sepPowerPreset,
|
||||
}
|
||||
|
||||
let job_id: string
|
||||
if (inputMode === 'imported' && importedFile) {
|
||||
const res = await submitSeparateFromPath(importedFile.path, model, format, opts)
|
||||
job_id = res.job_id
|
||||
} else {
|
||||
const res = await submitSeparate(file!, model, format, opts)
|
||||
job_id = res.job_id
|
||||
}
|
||||
setJobId(job_id)
|
||||
} catch (e) {
|
||||
setError(String(e))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDynamicChange = (stem: keyof DynamicLevels, value: number) => {
|
||||
setDynamicLevels(prev => ({ ...prev, [stem]: value }))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h2 className="text-xl font-semibold text-slate-900 dark:text-white mb-1">Stem Separator</h2>
|
||||
<p className="text-sm text-slate-500 dark:text-gray-400">
|
||||
Separate an audio track into individual stems using Demucs, BS-RoFormer, MelBand, or MDX-Net.
|
||||
Create presets like Instrumental, Static mixes, or Dynamic volume-adjusted mixes.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Input mode toggle */}
|
||||
<div className="flex rounded-lg border border-slate-200 dark:border-gray-700 overflow-hidden">
|
||||
<button
|
||||
onClick={() => setInputMode('upload')}
|
||||
className={`flex-1 py-2 text-xs font-medium transition-colors ${
|
||||
inputMode === 'upload'
|
||||
? 'bg-brand-600 text-white'
|
||||
: 'bg-white dark:bg-gray-900 text-slate-600 dark:text-gray-400 hover:bg-slate-50 dark:hover:bg-gray-800'
|
||||
}`}
|
||||
>
|
||||
Upload File
|
||||
</button>
|
||||
<button
|
||||
onClick={() => { setInputMode('imported'); refetchImports() }}
|
||||
className={`flex-1 py-2 text-xs font-medium transition-colors flex items-center justify-center gap-1.5 ${
|
||||
inputMode === 'imported'
|
||||
? 'bg-sky-600 text-white'
|
||||
: 'bg-white dark:bg-gray-900 text-slate-600 dark:text-gray-400 hover:bg-slate-50 dark:hover:bg-gray-800'
|
||||
}`}
|
||||
>
|
||||
<Radio className="w-3 h-3" />
|
||||
Imported Files
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{inputMode === 'upload' && (
|
||||
<>
|
||||
<FileUpload
|
||||
label="Drop an audio file here, or click to select (MP3, FLAC, WAV, OGG…)"
|
||||
accept="audio/*"
|
||||
onFiles={([f]) => { setFile(f); setJobId(null); setResult(null) }}
|
||||
/>
|
||||
{file && (
|
||||
<div className="rounded-lg border border-slate-200 dark:border-gray-700 bg-slate-50 dark:bg-gray-800/50 px-4 py-3">
|
||||
<p className="text-sm font-medium text-slate-700 dark:text-gray-300">
|
||||
Selected: {file.name}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{inputMode === 'imported' && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Select imported file</span>
|
||||
<button
|
||||
onClick={() => refetchImports()}
|
||||
title="Refresh"
|
||||
className="p-1 rounded text-slate-400 hover:text-brand-500 transition-colors"
|
||||
>
|
||||
<RefreshCw className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{imports.length === 0 ? (
|
||||
<div className="rounded-lg border border-dashed border-slate-200 dark:border-gray-700 px-4 py-6 text-center">
|
||||
<Radio className="w-6 h-6 text-slate-300 dark:text-gray-600 mx-auto mb-2" />
|
||||
<p className="text-sm text-slate-400 dark:text-gray-600">No imported files yet.</p>
|
||||
<p className="text-xs text-slate-400 dark:text-gray-600 mt-1">Use the Subsonic panel in the sidebar to import songs.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1 max-h-48 overflow-y-auto rounded-lg border border-slate-200 dark:border-gray-700">
|
||||
{imports.map((f) => (
|
||||
<button
|
||||
key={f.path}
|
||||
onClick={() => {
|
||||
setImportedFile(f)
|
||||
setProjectName(f.filename.replace(/\.[^/.]+$/, ''))
|
||||
setJobId(null); setResult(null)
|
||||
}}
|
||||
className={`w-full flex items-start gap-2 px-3 py-2 text-left transition-colors ${
|
||||
importedFile?.path === f.path
|
||||
? 'bg-sky-50 dark:bg-sky-950/30 border-l-2 border-sky-500'
|
||||
: 'hover:bg-slate-50 dark:hover:bg-gray-800/50'
|
||||
}`}
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-xs font-medium text-slate-700 dark:text-gray-200 truncate">{f.filename}</p>
|
||||
<p className="text-[10px] text-slate-400 dark:text-gray-500">
|
||||
{(f.size / 1024 / 1024).toFixed(1)} MB
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Model Family</span>
|
||||
<select value={selectedGroup} onChange={(e) => handleGroupChange(e.target.value)} className={SELECT_CLS}>
|
||||
{Object.keys(visibleGrouped).map((g) => (
|
||||
<option key={g} value={g}>{g}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Model</span>
|
||||
<select value={model} onChange={(e) => setModel(e.target.value)} className={SELECT_CLS}>
|
||||
{(visibleGrouped[selectedGroup] ?? []).map((m) => (
|
||||
<option key={m.id} value={m.id}>{m.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Output Format</span>
|
||||
<select value={format} onChange={(e) => setFormat(e.target.value)} className={SELECT_CLS}>
|
||||
{formats.map((f) => <option key={f.id} value={f.id}>{f.label}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{isBSR && (
|
||||
<div className="rounded-lg border border-purple-300 dark:border-purple-800 bg-purple-50 dark:bg-purple-950/30 px-4 py-3 text-xs text-purple-700 dark:text-purple-300 space-y-1">
|
||||
<p className="font-semibold">BS-RoFormer selected</p>
|
||||
<p>State-of-the-art transformer model. Runs in-process — may take longer on CPU.</p>
|
||||
<ul className="list-disc list-inside mt-1 space-y-0.5 text-purple-600 dark:text-purple-400">
|
||||
<li><strong>4-stem</strong> — vocals · drums · bass · other</li>
|
||||
<li><strong>5-stem (guitar)</strong> — + guitar as separate stem</li>
|
||||
<li><strong>5-stem (piano)</strong> — + piano as separate stem</li>
|
||||
<li><strong>6-stem (full)</strong> — vocals · drums · bass · guitar · piano · other</li>
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Project Name */}
|
||||
<div className="space-y-2">
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Project Name</span>
|
||||
<input
|
||||
type="text"
|
||||
value={projectName}
|
||||
onChange={(e) => setProjectName(e.target.value)}
|
||||
placeholder="Artist - Title"
|
||||
className={INPUT_CLS}
|
||||
/>
|
||||
</label>
|
||||
<p className="text-xs text-slate-500 dark:text-gray-500">
|
||||
Used for folder naming. Auto-generated from metadata if available.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Preset Type */}
|
||||
<div className="space-y-3">
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Output Preset</span>
|
||||
<select value={presetType} onChange={(e) => setPresetType(e.target.value)} className={SELECT_CLS}>
|
||||
{presets?.preset_types.map((p) => (
|
||||
<option key={p.id} value={p.id}>{p.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<p className="text-xs text-slate-500 dark:text-gray-500">
|
||||
{presets?.preset_types.find(p => p.id === presetType)?.description}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Static Options */}
|
||||
{presetType === 'static' && (
|
||||
<div className="space-y-3 rounded-lg border border-slate-200 dark:border-gray-700 bg-slate-50 dark:bg-gray-800/50 p-4">
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Remove Elements</span>
|
||||
<select value={staticOption} onChange={(e) => setStaticOption(e.target.value)} className={SELECT_CLS}>
|
||||
{presets?.static_options.map((o) => (
|
||||
<option key={o.id} value={o.id}>{o.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<p className="text-xs text-slate-500 dark:text-gray-500">
|
||||
{presets?.static_options.find(o => o.id === staticOption)?.description}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Dynamic Options */}
|
||||
{presetType === 'dynamic' && (
|
||||
<div className="space-y-4 rounded-lg border border-slate-200 dark:border-gray-700 bg-slate-50 dark:bg-gray-800/50 p-4">
|
||||
<p className="text-sm font-medium text-slate-700 dark:text-gray-300">Volume Levels</p>
|
||||
<p className="text-xs text-slate-500 dark:text-gray-500">Adjust the volume of each stem (0 = mute, 1 = original, 2 = double)</p>
|
||||
|
||||
{Object.entries(dynamicLevels).map(([stem, value]) => (
|
||||
<div key={stem} className="space-y-1">
|
||||
<div className="flex justify-between items-center">
|
||||
<label className="text-sm capitalize text-slate-700 dark:text-gray-300">{stem}</label>
|
||||
<span className="text-sm text-slate-500 dark:text-gray-400">{Math.round(value * 100)}%</span>
|
||||
</div>
|
||||
<input
|
||||
type="range"
|
||||
min="0"
|
||||
max="2"
|
||||
step="0.1"
|
||||
value={value}
|
||||
onChange={(e) => handleDynamicChange(stem as keyof DynamicLevels, parseFloat(e.target.value))}
|
||||
className={SLIDER_CLS}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Preset Preview */}
|
||||
{presetType !== 'stems_only' && (
|
||||
<div className="rounded-lg border border-blue-200 dark:border-blue-800 bg-blue-50 dark:bg-blue-950/30 px-4 py-3 text-sm text-blue-700 dark:text-blue-300">
|
||||
<p className="font-medium">Output Structure Preview:</p>
|
||||
<code className="block mt-2 text-xs whitespace-pre text-blue-600 dark:text-blue-400">
|
||||
{projectName || 'Project Name'}/
|
||||
{'\n'} Stems/ (always created)
|
||||
{presetType === 'instrumental' && "\n Instrumental/ (vocals removed)"}
|
||||
{presetType === 'static' && `\n Static/ (${presets?.static_options.find(o => o.id === staticOption)?.label})`}
|
||||
{presetType === 'dynamic' && "\n Dynamic/ (volume adjusted mix)"}
|
||||
</code>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && <p className="text-sm text-red-500 dark:text-red-400">{error}</p>}
|
||||
|
||||
<button
|
||||
onClick={submit}
|
||||
disabled={(inputMode === 'upload' ? !file : !importedFile) || loading}
|
||||
className="w-full rounded-lg bg-brand-600 hover:bg-brand-500 disabled:bg-slate-200 disabled:text-slate-400 dark:disabled:bg-gray-800 dark:disabled:text-gray-500 px-4 py-2.5 text-sm font-semibold text-white disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
{loading ? 'Submitting…' : presetType === 'stems_only' ? 'Separate Stems' : `Separate & Create ${presets?.preset_types.find(p => p.id === presetType)?.label}`}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setShowAuto(true)}
|
||||
disabled={(inputMode === 'upload' ? !file : !importedFile)}
|
||||
className="w-full rounded-lg border border-amber-400 dark:border-amber-600 bg-amber-50 dark:bg-amber-950/30 hover:bg-amber-100 dark:hover:bg-amber-900/40 disabled:opacity-40 disabled:cursor-not-allowed px-4 py-2.5 text-sm font-semibold text-amber-700 dark:text-amber-400 transition-colors flex items-center justify-center gap-2"
|
||||
>
|
||||
<Zap className="w-4 h-4" />
|
||||
Auto Pipeline
|
||||
</button>
|
||||
|
||||
{showAuto && (
|
||||
<AutoPipelineDialog
|
||||
target={{
|
||||
file: inputMode === 'upload' ? file ?? undefined : undefined,
|
||||
filePath: inputMode === 'imported' ? importedFile?.path : undefined,
|
||||
filename: inputMode === 'upload'
|
||||
? (file?.name ?? '')
|
||||
: (importedFile?.filename ?? ''),
|
||||
initialModel: model,
|
||||
initialFormat: format,
|
||||
initialProjectName: projectName || undefined,
|
||||
}}
|
||||
onClose={() => setShowAuto(false)}
|
||||
onComplete={(projectId, name) => {
|
||||
setShowAuto(false)
|
||||
onSeparationComplete?.(projectId, `Auto Pipeline`, name)
|
||||
}}
|
||||
onOpenSettings={onOpenSettings}
|
||||
/>
|
||||
)}
|
||||
|
||||
{jobId && <JobStatus jobId={jobId} onDone={setResult} />}
|
||||
{result && (
|
||||
<div className="space-y-4">
|
||||
{result.result?.project_name && (
|
||||
<div className="rounded-lg border border-green-200 dark:border-green-800 bg-green-50 dark:bg-green-950/30 px-4 py-3">
|
||||
<p className="text-sm font-medium text-green-800 dark:text-green-300">
|
||||
Project: {result.result.project_name}
|
||||
</p>
|
||||
<p className="text-xs text-green-600 dark:text-green-400 mt-1">
|
||||
Location: {result.result.project_path}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<ResultFiles jobId={result.id} files={result.files} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Executable
+1834
File diff suppressed because it is too large.
Load diff
Executable
+179
@@ -0,0 +1,179 @@
|
||||
export type JobStatus = 'queued' | 'running' | 'done' | 'error' | 'cancelled'
|
||||
|
||||
export interface JobFile {
|
||||
name: string
|
||||
path: string
|
||||
stage?: string // 'separation' | 'transcription' | 'abc' | 'elrc'
|
||||
type?: string // 'stem' | 'instrumental' | 'static' | 'dynamic' | 'lrc' | 'elrc' | 'source'
|
||||
stem?: string // stem name for stem files
|
||||
}
|
||||
|
||||
export interface Job {
|
||||
id: string
|
||||
job_type: 'separate' | 'transcribe' | 'abc-convert' | 'pipeline' | 'lrc_align' | 'mix' | 'lyric-transcribe'
|
||||
status: JobStatus
|
||||
progress: string
|
||||
error: string
|
||||
files: JobFile[]
|
||||
result?: {
|
||||
project_name?: string
|
||||
project_path?: string
|
||||
stems_dir?: string
|
||||
transcriptions_dir?: string
|
||||
model_label?: string
|
||||
format_label?: string
|
||||
tab_label?: string
|
||||
project_id?: string
|
||||
}
|
||||
created_at: string | null
|
||||
updated_at: string | null
|
||||
}
|
||||
|
||||
export interface ModelOption {
|
||||
id: string
|
||||
label: string
|
||||
group?: string // 'Demucs' | 'BS-RoFormer' | 'MDX-Net' | 'MelBand'
|
||||
}
|
||||
|
||||
export interface PerInstrumentModel {
|
||||
id: string
|
||||
label: string
|
||||
instrument: string
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface ModeOption {
|
||||
id: string
|
||||
label: string
|
||||
}
|
||||
|
||||
export interface FormatOption {
|
||||
id: string
|
||||
label: string
|
||||
}
|
||||
|
||||
// Preset types
|
||||
export interface PresetType {
|
||||
id: string
|
||||
label: string
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface StaticOption {
|
||||
id: string
|
||||
label: string
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface PresetsResponse {
|
||||
preset_types: PresetType[]
|
||||
static_options: StaticOption[]
|
||||
}
|
||||
|
||||
// Dynamic preset volume levels
|
||||
export interface DynamicLevels {
|
||||
vocals?: number
|
||||
drums?: number
|
||||
bass?: number
|
||||
other?: number
|
||||
guitar?: number
|
||||
piano?: number
|
||||
}
|
||||
|
||||
// LRC/Lyrics types
|
||||
export interface LyricsSource {
|
||||
id: string
|
||||
label: string
|
||||
}
|
||||
|
||||
export interface LyricsData {
|
||||
source: string
|
||||
synced: boolean
|
||||
lyrics: string
|
||||
raw: string
|
||||
}
|
||||
|
||||
// Subsonic integration
|
||||
export interface SubsonicSong {
|
||||
id: string
|
||||
title: string
|
||||
artist: string
|
||||
album: string
|
||||
duration: number
|
||||
suffix: string
|
||||
size: number
|
||||
bitRate: number
|
||||
}
|
||||
|
||||
export interface SubsonicConfig {
|
||||
configured: boolean
|
||||
url?: string
|
||||
username?: string
|
||||
}
|
||||
|
||||
export interface ImportedFile {
|
||||
filename: string
|
||||
path: string
|
||||
size: number
|
||||
title?: string
|
||||
artist?: string
|
||||
}
|
||||
|
||||
// Model download types
|
||||
export interface ModelDownloadInfo {
|
||||
id: string
|
||||
label: string
|
||||
group: string
|
||||
description: string
|
||||
size_mb: number
|
||||
status: 'not_downloaded' | 'downloaded' | 'downloading' | 'paused' | 'error' | 'cancelled'
|
||||
progress_percent: number
|
||||
}
|
||||
|
||||
export interface ModelDownloadProgress {
|
||||
model_id: string
|
||||
status: string
|
||||
progress_percent: number
|
||||
bytes_downloaded: number
|
||||
total_bytes: number
|
||||
speed_mbps: number
|
||||
error_message?: string
|
||||
}
|
||||
|
||||
// Project management
|
||||
export interface Project {
|
||||
id: string
|
||||
name: string
|
||||
tab_label: string // display label for tab e.g. "Demucs v4_MP3 (256 kbps)"
|
||||
created_at: string | null
|
||||
sep_job_id: string
|
||||
trans_jobs: Record<string, string> // stem_name → job_id
|
||||
abc_jobs: Record<string, string> // stem_name → job_id
|
||||
lrc_jobs: Record<string, string> // stem_name → job_id
|
||||
mix_job_id: string | null
|
||||
}
|
||||
|
||||
export interface ProjectDetail {
|
||||
id: string
|
||||
name: string
|
||||
created_at: string | null
|
||||
sep_job_id: string
|
||||
trans_jobs: Record<string, Job> // stem_name → expanded Job
|
||||
abc_jobs: Record<string, Job> // stem_name → expanded Job
|
||||
lrc_jobs: Record<string, Job> // stem_name → expanded Job
|
||||
mix_job_id: string | null
|
||||
sep_job: Job
|
||||
mix_job: Job | null
|
||||
}
|
||||
|
||||
// Lyrics Style options
|
||||
export interface LyricsStyleOptions {
|
||||
fontFamily: string
|
||||
fontSize: number
|
||||
textColor: string
|
||||
highlightColor: string
|
||||
backgroundColor: string
|
||||
wordHighlightColor: string
|
||||
lineSpacing: number
|
||||
textAlign: 'left' | 'center' | 'right'
|
||||
}
|
||||
Executable
+101
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* Global audio playback registry.
|
||||
*
|
||||
* Only one audio player should be playing at a time. When a player starts,
|
||||
* it registers a stop callback here. Any previously registered callback is
|
||||
* called first, pausing the old player before the new one starts.
|
||||
*
|
||||
* Players also publish live state so the GlobalAudioBar can reflect playback
|
||||
* position, title and play/pause status across page navigation.
|
||||
*/
|
||||
|
||||
type StopFn = () => void
|
||||
|
||||
export interface PlaybackMeta {
|
||||
title: string
|
||||
isPlaying: boolean
|
||||
currentTime: number
|
||||
duration: number
|
||||
volume: number
|
||||
}
|
||||
|
||||
export interface PlaybackActions {
|
||||
toggle: () => void
|
||||
seek: (t: number) => void
|
||||
setVolume: (v: number) => void
|
||||
}
|
||||
|
||||
let _current: StopFn | null = null
|
||||
|
||||
// Mutable singleton — players overwrite toggle/seek/setVolume in-place each render,
|
||||
// so the bar always invokes the freshest closures without any ref gymnastics.
|
||||
const _actions: PlaybackActions = { toggle: () => {}, seek: () => {}, setVolume: () => {} }
|
||||
|
||||
let _meta: PlaybackMeta | null = null
|
||||
const _listeners = new Set<() => void>()
|
||||
|
||||
// ── Stop / unregister ────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Call this when a player begins playback.
|
||||
* The previously active player (if any) will be stopped.
|
||||
*/
|
||||
export function registerPlayback(stop: StopFn): void {
|
||||
if (_current && _current !== stop) {
|
||||
_current()
|
||||
}
|
||||
_current = stop
|
||||
}
|
||||
|
||||
/**
|
||||
* Call this when a player unmounts or hard-resets so the registry no
|
||||
* longer holds a stale reference. Do NOT call on simple pause — let the
|
||||
* registry keep holding the player so the bar stays visible.
|
||||
*/
|
||||
export function unregisterPlayback(stop: StopFn): void {
|
||||
if (_current === stop) {
|
||||
_current = null
|
||||
}
|
||||
}
|
||||
|
||||
// ── Bar state ────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Players call this whenever their state changes (play, pause, seek, RAF tick).
|
||||
* The mutable _actions singleton is updated in-place so the bar always has
|
||||
* fresh callbacks without needing extra refs.
|
||||
*/
|
||||
export function publishMeta(meta: PlaybackMeta, actions: PlaybackActions): void {
|
||||
_meta = meta
|
||||
_actions.toggle = actions.toggle
|
||||
_actions.seek = actions.seek
|
||||
_actions.setVolume = actions.setVolume
|
||||
_listeners.forEach(l => l())
|
||||
}
|
||||
|
||||
/**
|
||||
* Call this when the player is forcibly stopped (registry takeover) or unmounts.
|
||||
* Simple pause should NOT clear — the bar stays visible showing paused state.
|
||||
*/
|
||||
export function clearMeta(): void {
|
||||
if (_meta !== null) {
|
||||
_meta = null
|
||||
_listeners.forEach(l => l())
|
||||
}
|
||||
}
|
||||
|
||||
export function getMeta(): PlaybackMeta | null {
|
||||
return _meta
|
||||
}
|
||||
|
||||
export function getActions(): PlaybackActions {
|
||||
return _actions
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to bar state changes. Returns an unsubscribe function.
|
||||
*/
|
||||
export function subscribePlayback(listener: () => void): () => void {
|
||||
_listeners.add(listener)
|
||||
return () => _listeners.delete(listener)
|
||||
}
|
||||
Executable
+63
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Shared types and localStorage helpers for the Auto Pipeline feature.
|
||||
* Both Settings.tsx (configuration) and AutoPipelineDialog.tsx (execution) import from here.
|
||||
*/
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface AutoStepReprocess {
|
||||
type: 'reprocess'
|
||||
stem: string // e.g. 'other', 'vocals', 'drums'
|
||||
model: string // model id, e.g. 'mel_band_roformer_4stem'
|
||||
}
|
||||
|
||||
export interface AutoStepMidi {
|
||||
type: 'midi'
|
||||
mode: 'polyphonic' | 'melody'
|
||||
}
|
||||
|
||||
export interface AutoStepLyrics {
|
||||
type: 'lyrics'
|
||||
whisperModel: string // e.g. 'large-v2'
|
||||
diarize: boolean
|
||||
}
|
||||
|
||||
export type AutoStep = AutoStepReprocess | AutoStepMidi | AutoStepLyrics
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// localStorage keys
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const LS_AUTO_MODEL = 'se-auto-model'
|
||||
export const LS_AUTO_FORMAT = 'se-auto-format'
|
||||
export const LS_AUTO_STEPS = 'se-auto-steps'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Readers / writers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function readAutoModel(): string { return localStorage.getItem(LS_AUTO_MODEL) ?? 'htdemucs' }
|
||||
export function readAutoFormat(): string { return localStorage.getItem(LS_AUTO_FORMAT) ?? 'mp3' }
|
||||
|
||||
export function readAutoSteps(): AutoStep[] {
|
||||
try { return JSON.parse(localStorage.getItem(LS_AUTO_STEPS) || '[]') as AutoStep[] }
|
||||
catch { return [] }
|
||||
}
|
||||
|
||||
export function writeAutoSteps(steps: AutoStep[]): void {
|
||||
localStorage.setItem(LS_AUTO_STEPS, JSON.stringify(steps))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Step display helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function stepLabel(step: AutoStep): string {
|
||||
switch (step.type) {
|
||||
case 'reprocess': return `Reprocess "${step.stem}" stem`
|
||||
case 'midi': return `MIDI Transcription (${step.mode})`
|
||||
case 'lyrics': return `Lyric Transcription & Alignment — WhisperX ${step.whisperModel}`
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user