File size: 10,013 Bytes
891fa77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
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<Health | null>(null)
  const [healthIssue, setHealthIssue] = useState<Issue | null>(null)
  const [healthChecking, setHealthChecking] = useState(false)
  const [healthRefresh, setHealthRefresh] = useState(0)
  const [job, setJob] = useState<Job | null>(null)
  const [busy, setBusy] = useState(false)
  const [uploading, setUploading] = useState(false)
  const [issue, setIssue] = useState<Issue | null>(null)
  const [paused, setPaused] = useState(false)
  const ticket = useRef<Ticket | null>(null)
  const deadline = useRef(0)
  const controller = useRef<AbortController | null>(null)
  const next = useRef<ReturnType<typeof setTimeout> | null>(null)
  const stopTimer = useRef<ReturnType<typeof setTimeout> | 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<typeof setTimeout> | undefined
    let active: AbortController | undefined
    const check = async () => {
      active = new AbortController()
      setHealthChecking(true)
      const timeout = setTimeout(() => active?.abort(), 15000)
      try {
        const value = await request<Health>('/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<Job>(`/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<Ticket>('/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 }
}