import { useCallback, useEffect, useRef, useState } from 'react' import { useTranslation } from 'react-i18next' import type { TFunction } from 'i18next' import { MAX_POLL_MS, POLL_INTERVAL_MS, errorMessage, jobHeaders, request, uploadHeaders, uploadProblem } from './api' import type { Health, Job, Ticket, UploadProblem } from './api' type Fallback = 'errors.healthUnknown' | 'errors.modelUnavailable' | 'errors.pollUnknown' | 'errors.jobFailed' | 'errors.uploadRejected' // The API still sends raw diagnostic text. Translate known legacy messages at the UI boundary. export function localizeBackendMessage(t: TFunction, language: string | undefined, raw: string, fallback: Fallback): string { if (language === 'zh' && raw) return raw const duration = raw.match(/^当前解码时长为([\d.]+)秒;请上传([\d.]+)至([\d.]+)秒/) if (duration) return t('errors.audioDuration', { duration: duration[1], min: duration[2], max: duration[3] }) const dependencies = raw.match(/^后端推理依赖未安装:([\w., -]+)$/) if (dependencies) return t('errors.dependencies', { value: dependencies[1] }) if (/^HTTP \d{3}$/.test(raw)) return raw const messages = [ [/缺少论文训练得到的预测头权重/, 'missingHead'], [/缺少固定版本MERT模型/, 'missingMert'], [/MERT模型版本与论文不一致|模型版本不匹配/, 'modelMismatch'], [/MERT配置不完整/, 'modelIncomplete'], [/模型来源记录无法读取/, 'modelManifest'], [/^(上传文件|音频)为空/, 'audioEmpty'], [/采样率或声道数/, 'audioChannels'], [/非有限数值/, 'audioNonFinite'], [/解码后的音频超过/, 'audioTooLong'], [/没有有效采样/, 'audioNoSamples'], [/音频无法解码/, 'audioDecode'], [/重采样后音频无效/, 'audioResample'], [/SHA256|MERT模型文件|MERT张量数量|MERT加载后权重|预测头结构/, 'invalidAssets'], [/特征时间bin缺失|模型特征包含无效数值|预测数值无效/, 'invalidPrediction'], [/服务(正在关闭|已关闭)/, 'serviceShutdown'], [/CPU任务处理超时/, 'cpuTimeout'], [/CPU工作进程(退出|连接中断)/, 'cpuUnavailable'], [/CPU推理失败/, 'cpuFailed'], [/需要有效的演示访问令牌/, 'auth'], [/仅支持WAV/, 'unsupportedFormat'], [/任务队列已满|上传处理繁忙/, 'queueFull'], [/音频文件超过|上传请求超过大小限制/, 'uploadTooLarge'], [/无效请求长度/, 'invalidLength'], [/上传超时,请重试/, 'uploadServerTimeout'], [/任务不存在、已过期或访问令牌无效/, 'jobMissing'], [/^(Failed to fetch|Load failed|NetworkError when attempting to fetch resource\.|Network request failed)$/i, 'network'], ] as const const match = messages.find(([pattern]) => pattern.test(raw)) return match ? t(`errors.${match[1]}`) : t(fallback) } type Issue = | { kind: 'healthTimeout' | 'uploadTimeout' | 'pollDeadline' } | { kind: 'validation'; key: UploadProblem; max: string } | { kind: 'healthFailed' | 'uploadFailed' | 'pollInterrupted' | 'jobFailed'; detail: string | null } function issueText(t: TFunction, language: string | undefined, issue: Issue | null): string | null { if (!issue) return null const backend = (raw: string, fallback: Fallback) => localizeBackendMessage(t, language, raw, fallback) switch (issue.kind) { case 'validation': return t(issue.key, { max: issue.max }) case 'healthFailed': return backend(issue.detail ?? '', 'errors.healthUnknown') case 'jobFailed': return backend(issue.detail ?? '', 'errors.jobFailed') case 'uploadFailed': return t('errors.uploadFailed', { detail: backend(issue.detail ?? '', 'errors.uploadRejected') }) case 'pollInterrupted': return t('errors.pollInterrupted', { detail: issue.detail === null ? t('errors.requestTimeout') : backend(issue.detail, 'errors.pollUnknown') }) default: return t(`errors.${issue.kind}`) } } export function useAnalysis() { const { t, i18n } = useTranslation() const [health, setHealth] = useState(null) const [healthIssue, setHealthIssue] = useState(null) const [healthChecking, setHealthChecking] = useState(false) const [healthRefresh, setHealthRefresh] = useState(0) const [job, setJob] = useState(null) const [busy, setBusy] = useState(false) const [uploading, setUploading] = useState(false) const [issue, setIssue] = useState(null) const [paused, setPaused] = useState(false) const ticket = useRef(null) const deadline = useRef(0) const controller = useRef(null) const next = useRef | null>(null) const stopTimer = useRef | null>(null) const mounted = useRef(true) const submission = useRef(false) const stop = useCallback(() => { controller.current?.abort() controller.current = null if (next.current) clearTimeout(next.current) if (stopTimer.current) clearTimeout(stopTimer.current) next.current = null stopTimer.current = null }, []) useEffect(() => { mounted.current = true return () => { mounted.current = false; stop(); ticket.current = null } }, [stop]) useEffect(() => { let disposed = false let timer: ReturnType | undefined let active: AbortController | undefined const check = async () => { active = new AbortController() setHealthChecking(true) const timeout = setTimeout(() => active?.abort(), 15000) try { const value = await request('/api/health', active.signal) if (!disposed) { setHealth(value); setHealthIssue(null) } } catch (err) { if (!disposed) { setHealth(null); setHealthIssue(active.signal.aborted ? { kind: 'healthTimeout' } : { kind: 'healthFailed', detail: errorMessage(err) }) } } finally { clearTimeout(timeout) if (!disposed) { setHealthChecking(false); timer = setTimeout(check, 5000) } } } void check() return () => { disposed = true; active?.abort(); clearTimeout(timer) } }, [healthRefresh]) const poll = useCallback(() => { stop() const current = ticket.current if (!current || !mounted.current) return if (Date.now() >= deadline.current) { setIssue({ kind: 'pollDeadline' }); setBusy(false); setPaused(false); return } const active = new AbortController() controller.current = active setBusy(true) setPaused(false) setIssue(null) stopTimer.current = setTimeout(() => { active.abort() if (next.current) clearTimeout(next.current) if (mounted.current) { setIssue({ kind: 'pollDeadline' }); setBusy(false); setPaused(false) } }, deadline.current - Date.now()) const check = async () => { const perRequest = new AbortController() const abort = () => perRequest.abort() active.signal.addEventListener('abort', abort, { once: true }) const timeout = setTimeout(abort, 15000) try { const value = await request(`/api/jobs/${encodeURIComponent(current.job_id)}`, perRequest.signal, { headers: jobHeaders(current) }) if (active.signal.aborted || !mounted.current) return setJob(value) if (value.status === 'completed' || value.status === 'failed') { setBusy(false) setIssue(value.status === 'failed' ? { kind: 'jobFailed', detail: value.error } : null) stop() ticket.current = null } else next.current = setTimeout(check, POLL_INTERVAL_MS) } catch (err) { if (active.signal.aborted || !mounted.current) return setPaused(true) setIssue({ kind: 'pollInterrupted', detail: perRequest.signal.aborted ? null : errorMessage(err) }) // Keep the overall deadline running while paused. } finally { clearTimeout(timeout) active.signal.removeEventListener('abort', abort) } } void check() }, [stop]) const upload = useCallback(async (file: File) => { if (submission.current || busy || healthIssue || health?.status !== 'ready' || !health.model.assets_available) return const problem = uploadProblem(file, health.limits.max_upload_bytes) if (problem) { setIssue({ kind: 'validation', key: problem, max: (health.limits.max_upload_bytes / 1024 / 1024).toFixed(0) }); return } submission.current = true stop() ticket.current = null setJob(null) setIssue(null) setPaused(false) setBusy(true) setUploading(true) const active = new AbortController() controller.current = active const timeout = setTimeout(() => active.abort(), 60000) const body = new FormData() body.append('file', file) try { const value = await request('/api/jobs', active.signal, { method: 'POST', body, headers: uploadHeaders() }) if (!mounted.current || controller.current !== active) return ticket.current = value deadline.current = Date.now() + MAX_POLL_MS setJob({ job_id: value.job_id, status: 'queued', stage: 'queued', progress: 0, result: null, error: null }) setUploading(false) poll() } catch (err) { if (!mounted.current) return setIssue(active.signal.aborted ? { kind: 'uploadTimeout' } : { kind: 'uploadFailed', detail: errorMessage(err) }) setBusy(false) setUploading(false) } finally { clearTimeout(timeout); submission.current = false } }, [busy, health, healthIssue, poll, stop]) const clearResult = useCallback(() => { if (busy || submission.current) return stop() ticket.current = null setJob(null) setIssue(null) setPaused(false) }, [busy, stop]) return { health, healthError: issueText(t, i18n.resolvedLanguage, healthIssue), healthChecking, refreshHealth: () => setHealthRefresh(value => value + 1), job, busy, uploading, error: issueText(t, i18n.resolvedLanguage, issue), paused, resume: poll, upload, clearResult } }