Files
stemengine_old/frontend/src/api/client.ts
T

733 lines
23 KiB
TypeScript
Executable File

import type {
Job,
ModelOption,
FormatOption,
ModeOption,
PresetsResponse,
LyricsSource,
LyricsData,
DynamicLevels,
LyricsStyleOptions,
SubsonicSong,
SubsonicConfig,
ImportedFile,
Project,
ProjectDetail,
LyricModelsPayload,
ModelDownloadInfo,
ModelDownloadProgress,
} from '../types'
const BASE = '/api'
const SEPARATOR_API_ADDRESS_KEY = 'stemengine-separator-api-address'
function normalizeApiBase(input: string): string {
const raw = input.trim().replace(/\/+$/, '')
if (!raw) return BASE
if (raw === BASE) return BASE
if (raw.startsWith('http://') || raw.startsWith('https://')) {
return raw.endsWith('/api') ? raw : `${raw}/api`
}
// Relative path support (advanced): "/stemengine" -> "/stemengine/api"
if (raw.startsWith('/')) {
return raw.endsWith('/api') ? raw : `${raw}/api`
}
// Bare host fallback:
// "work" -> "https://work/api" (when page is https)
// "192.168.1.10" -> "http://192.168.1.10/api" (when page is http)
const pageProtocol = (typeof window !== 'undefined' && window.location.protocol === 'https:')
? 'https://'
: 'http://'
return `${pageProtocol}${raw}${raw.endsWith('/api') ? '' : '/api'}`
}
function getDefaultApiBase(): string {
const envBase = (import.meta as any).env?.VITE_STEMENGINE_API_BASE as string | undefined
return normalizeApiBase(envBase ?? BASE)
}
export function getSeparatorApiAddress(): string {
if (typeof window === 'undefined') return ''
return localStorage.getItem(SEPARATOR_API_ADDRESS_KEY)?.trim() || ''
}
export function setSeparatorApiAddress(address: string): void {
if (typeof window === 'undefined') return
const trimmed = address.trim()
if (!trimmed) {
localStorage.removeItem(SEPARATOR_API_ADDRESS_KEY)
return
}
localStorage.setItem(SEPARATOR_API_ADDRESS_KEY, trimmed)
}
export function clearSeparatorApiAddress(): void {
if (typeof window === 'undefined') return
localStorage.removeItem(SEPARATOR_API_ADDRESS_KEY)
}
function getActiveApiBase(): string {
const override = getSeparatorApiAddress()
if (override) return normalizeApiBase(override)
return getDefaultApiBase()
}
function resolveApiUrl(url: string): string {
if (!url.startsWith(BASE)) return url
const suffix = url.slice(BASE.length)
return `${getActiveApiBase()}${suffix}`
}
const ADMIN_TOKEN_KEY = 'stemengine-admin-token'
export function getAdminToken(): string {
if (typeof window === 'undefined') return ''
return localStorage.getItem(ADMIN_TOKEN_KEY)?.trim() || ''
}
export function setAdminToken(token: string): void {
if (typeof window === 'undefined') return
const trimmed = token.trim()
if (!trimmed) {
localStorage.removeItem(ADMIN_TOKEN_KEY)
return
}
localStorage.setItem(ADMIN_TOKEN_KEY, trimmed)
}
export function clearAdminToken(): void {
if (typeof window === 'undefined') return
localStorage.removeItem(ADMIN_TOKEN_KEY)
}
function requiresAdminToken(url: string, method?: string): boolean {
const verb = (method ?? 'GET').toUpperCase()
// Normalize absolute URLs to pathnames; keep relative paths as-is.
let path = url
try {
path = new URL(url, window.location.origin).pathname
} catch {
// keep original string
}
if (path === `${BASE}/system/gpu-reset`) return true
if (path.startsWith(`${BASE}/projects/cleanup/`)) return true
if (path.startsWith(`${BASE}/models/`) && verb !== 'GET') return true
return false
}
async function request<T>(url: string, init?: RequestInit): Promise<T> {
const resolvedUrl = resolveApiUrl(url)
const headers = new Headers(init?.headers)
if (requiresAdminToken(url, init?.method)) {
const token = getAdminToken()
if (token) headers.set('X-Admin-Token', token)
}
const res = await fetch(resolvedUrl, { ...init, headers })
if (!res.ok) {
const text = await res.text()
if (res.status === 403 && requiresAdminToken(url, init?.method)) {
const detail = text || 'Forbidden'
throw new Error(`403: ${detail} (admin token required — set it in Settings → Integrations)`)
}
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) =>
resolveApiUrl(`${BASE}/jobs/${jobId}/download/${encodeURIComponent(filename)}`)
export const projectCoverArtUrl = (projectId: string) =>
resolveApiUrl(`${BASE}/projects/${encodeURIComponent(projectId)}/cover-art`)
// ---------- 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
instrumentModels?: Record<string, string>
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?.instrumentModels && Object.keys(options.instrumentModels).length > 0) {
fd.append('instrument_models', JSON.stringify(options.instrumentModels))
}
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 = (
params: {
q?: string
title?: string
artist?: string
album?: string
albumArtist?: string
count?: number
offset?: number
}
) => {
const qs = new URLSearchParams()
if (params.q) qs.set('q', params.q)
if (params.title) qs.set('title', params.title)
if (params.artist) qs.set('artist', params.artist)
if (params.album) qs.set('album', params.album)
if (params.albumArtist) qs.set('album_artist', params.albumArtist)
qs.set('count', String(params.count ?? 20))
qs.set('offset', String(params.offset ?? 0))
return request<SubsonicSong[]>(`${BASE}/subsonic/search?${qs.toString()}`)
}
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.songArtist ?? song.artist,
album_artist: song.albumArtist ?? song.artist,
album: song.album,
suffix: song.suffix,
}),
})
export const importYtDl = (url: string, title = '', artist = '') =>
request<{ job_id: string }>(`${BASE}/subsonic/import-ytdl`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url, title, artist }),
})
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
instrumentModels?: Record<string, string>
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?.instrumentModels && Object.keys(options.instrumentModels).length > 0) {
fd.append('instrument_models', JSON.stringify(options.instrumentModels))
}
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 getLyricModels = () =>
request<LyricModelsPayload>(`${BASE}/lyric-transcribe/models`)
export const lyricTranscribeProject = (
projectId: string,
stemName: string,
opts?: {
engine?: 'whisperx' | 'parakeet'
model?: string
language?: string
task?: 'transcribe' | 'translate'
outputFormats?: string[]
initialPrompt?: string
temperature?: number
wordTimestamps?: boolean
conditionOnPreviousText?: boolean
beamSize?: number
diarize?: boolean
lrcPowerPreset?: string
phonemeAlign?: boolean
lsyncAlign?: boolean
twoPass?: boolean
vocalStyle?: string
explicit?: boolean
}
) => {
const engine = opts?.engine ?? 'whisperx'
const wordTs = opts?.wordTimestamps ?? true
const phonemeAlign = opts?.phonemeAlign ?? false
const lsyncAlign = opts?.lsyncAlign ?? false
// lsyncAlign requires word-level timestamps to write syllable data into ELRC
const effectiveWordTs = wordTs || lsyncAlign
const defaultFormats = effectiveWordTs
? (phonemeAlign ? ['sylrc', 'elrc', 'lrc', 'txt'] : ['elrc', 'lrc', 'txt'])
: ['lrc', 'txt']
return request<{ job_id: string }>(`${BASE}/projects/${projectId}/lyric-transcribe`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
stem_name: stemName,
engine,
model: opts?.model ?? (engine === 'parakeet' ? 'parakeet-1.1b-rnnt-multilingual-asr' : 'large-v2'),
language: opts?.language || undefined,
task: opts?.task ?? 'transcribe',
output_formats: opts?.outputFormats ?? defaultFormats,
initial_prompt: opts?.initialPrompt,
temperature: opts?.temperature ?? 0.0,
word_timestamps: effectiveWordTs,
condition_on_previous_text: opts?.conditionOnPreviousText ?? true,
beam_size: opts?.beamSize ?? undefined,
diarize: opts?.diarize ?? false,
lrc_power_preset: opts?.lrcPowerPreset ?? 'standard',
phoneme_align: phonemeAlign,
lsync_align: opts?.lsyncAlign ?? false,
two_pass: opts?.twoPass ?? false,
vocal_style: opts?.vocalStyle ?? 'general',
explicit: opts?.explicit ?? 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' }
)
export const getSystemHealth = () =>
request<{ ok: boolean; app_env: string }>(
`${BASE}/system/health`
)
// ── Settings ─────────────────────────────────────────────────────────────────
export interface AppSettings {
hf_token_set: boolean
whisper_model: string
sep_power: string
whisper_word_ts: boolean
whisper_condition_prev: boolean
whisper_phoneme_align: boolean
auto_steps: unknown[]
auto_model: string
auto_format: string
auto_presets: unknown[]
}
export const getAppSettings = () =>
request<AppSettings>(`${BASE}/settings`)
export const patchAppSettings = (patch: Partial<AppSettings & { hf_token: string }>) =>
request<AppSettings>(`${BASE}/settings`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(patch),
})
export const deleteHfToken = () =>
request<{ hf_token_set: boolean }>(`${BASE}/settings/hf-token`, { method: 'DELETE' })