File size: 10,524 Bytes
182d832
9392a10
4837cc3
182d832
94a07ff
182d832
4837cc3
 
dbfa411
a752482
182d832
 
 
 
 
 
 
 
 
 
4837cc3
 
182d832
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4837cc3
9392a10
94a07ff
182d832
 
 
 
4837cc3
182d832
 
9392a10
 
 
a752482
9392a10
182d832
9392a10
182d832
 
4837cc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182d832
 
 
 
 
 
 
9392a10
182d832
9392a10
 
 
 
 
182d832
4837cc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9392a10
182d832
 
 
 
94a07ff
182d832
 
 
 
9392a10
182d832
 
 
9392a10
182d832
9392a10
 
182d832
 
 
9392a10
182d832
9392a10
4837cc3
9392a10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a752482
dbfa411
9392a10
 
 
 
182d832
 
9392a10
182d832
 
 
9392a10
182d832
 
9392a10
182d832
9392a10
182d832
 
 
 
 
 
 
 
 
 
94a07ff
 
 
 
 
 
9392a10
182d832
4837cc3
 
182d832
9392a10
182d832
 
 
 
a752482
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182d832
 
 
9392a10
182d832
 
 
 
 
9392a10
182d832
 
 
 
 
 
 
 
 
 
 
 
 
 
9392a10
94a07ff
9392a10
94a07ff
9392a10
 
 
 
 
 
 
 
182d832
a752482
182d832
 
94a07ff
 
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
// src/components/SmartTranscript.tsx
// Editable transcript with auto Gemini transcription + NLP correction pipeline
// Flow: Web Speech → Vocab correction → Device AI → Gemini re-transcribe → NLP 4-layer correction → editable

import { memo, useState, useEffect, useCallback, useRef, useMemo } from 'react'
import { trpc } from '@/lib/trpc'
import type { Role } from '@/lib/types'
import { loadRoleVocab, correctWithVocab, type VocabTerm } from '@/lib/vocab'
import { execute as deviceAIExecute, detectCapabilities, shouldOfferOfflineAI } from '@/lib/deviceAI'
import { EnableOfflineAIModal } from './EnableOfflineAIModal'

interface SmartTranscriptProps {
  /** Web Speech API transcript (real-time) */
  webSpeechText: string
  /** Audio blob from MediaRecorder */
  audioBlob: Blob | null
  /** Called when the final transcript changes (either auto-upgrade or user edit) */
  onTranscriptChange: (text: string) => void
  /** Accent color for the border/label */
  accentColor?: 'emerald' | 'blue' | 'amber' | 'purple'
  /** Current user role — used to load role-specific vocabulary */
  role?: Role
}

const ACCENT = {
  emerald: { border: 'border-emerald-200', bg: 'bg-emerald-50', label: 'text-emerald-700', badge: 'bg-emerald-100 text-emerald-700' },
  blue:    { border: 'border-blue-200',    bg: 'bg-blue-50',    label: 'text-blue-700',    badge: 'bg-blue-100 text-blue-700'    },
  amber:   { border: 'border-amber-200',   bg: 'bg-amber-50',   label: 'text-amber-700',   badge: 'bg-amber-100 text-amber-700'  },
  purple:  { border: 'border-purple-200',  bg: 'bg-purple-50',  label: 'text-purple-700',  badge: 'bg-purple-100 text-purple-700' },
}

function blobToBase64(blob: Blob): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onloadend = () => {
      const result = reader.result as string
      const base64 = result.split(',')[1] || result
      resolve(base64)
    }
    reader.onerror = reject
    reader.readAsDataURL(blob)
  })
}

type TranscriptSource = 'web_speech' | 'vocab_corrected' | 'device_ai' | 'gemini' | 'nlp_corrected' | 'user_edit'

function SmartTranscript({
  webSpeechText,
  audioBlob,
  onTranscriptChange,
  accentColor = 'emerald',
  role = 'nurse',
}: SmartTranscriptProps) {
  const [displayText, setDisplayText] = useState(webSpeechText)
  const [source, setSource] = useState<TranscriptSource>('web_speech')
  const [processingStep, setProcessingStep] = useState<string | null>(null)
  const [corrections, setCorrections] = useState<string[]>([])
  const [showOfflineAIModal, setShowOfflineAIModal] = useState(false)
  const pipelineCalledRef = useRef(false)
  const transcribeMutation = trpc.ai.transcribeAudio.useMutation()
  const correctMutation = trpc.ai.correctTranscript.useMutation()
  const colors = ACCENT[accentColor]

  // Vocab index
  const vocabRef = useRef<VocabTerm[]>([])

  useEffect(() => {
    loadRoleVocab(role).then((terms) => { vocabRef.current = terms }).catch(() => {})
  }, [role])

  // Device AI availability
  const [deviceAIAvailable, setDeviceAIAvailable] = useState(false)

  useEffect(() => {
    detectCapabilities().then((caps) => {
      setDeviceAIAvailable(caps.builtinAI || caps.wasm)
    }).catch(() => {})
  }, [])

  // Sync Web Speech text updates (while recording is ongoing)
  useEffect(() => {
    if (source === 'web_speech') {
      setDisplayText(webSpeechText)
    }
  }, [webSpeechText, source])

  // Auto-trigger pipeline when audioBlob arrives (recording stopped)
  useEffect(() => {
    if (!audioBlob || audioBlob.size < 1000 || pipelineCalledRef.current) return
    pipelineCalledRef.current = true

    const runPipeline = async () => {
      let bestText = webSpeechText.trim()

      // Step 0 (NEW): Vocabulary correction (instant, client-side)
      if (vocabRef.current.length > 0 && bestText.length >= 3) {
        const vocabResult = correctWithVocab(bestText, vocabRef.current)
        if (vocabResult.corrections.length > 0) {
          bestText = vocabResult.corrected
          setSource('vocab_corrected')
          setDisplayText(bestText)
          onTranscriptChange(bestText)
          setCorrections((prev) => [
            ...prev,
            ...vocabResult.corrections.map((c) => `「${c.from}」→「${c.to}」`),
          ])
        }
      }

      // Step 1 (NEW): Device AI correction (if available)
      if (deviceAIAvailable && bestText.length >= 10) {
        setProcessingStep('設備 AI 校正中...')
        try {
          const contextHints = vocabRef.current
            .slice(0, 20)
            .map((t) => t.correct)
            .join('、')
          const result = await deviceAIExecute('correct', bestText, contextHints)
          if (result && result.output && result.confidence >= 0.5) {
            const deviceText = result.output.trim()
            if (deviceText.length > bestText.length * 0.5 && deviceText !== bestText) {
              bestText = deviceText
              setSource('device_ai')
              setDisplayText(bestText)
              onTranscriptChange(bestText)
            }
          }
        } catch {
          // Device AI correction failed — continue pipeline
        }
      }

      // Step 2: Gemini re-transcription
      setProcessingStep('Gemini 重新辨識中...')
      try {
        const audioBase64 = await blobToBase64(audioBlob)
        const result = await transcribeMutation.mutateAsync({
          audioBase64,
          mimeType: (audioBlob.type || 'audio/webm;codecs=opus') as 'audio/webm;codecs=opus',
        })

        if (result.ok && result.data) {
          const geminiText = result.data.trim()
          const webLen = bestText.length
          const geminiLen = geminiText.length

          if (geminiLen > webLen * 0.8 || webLen < 20) {
            bestText = geminiText
            setSource('gemini')
            setDisplayText(bestText)
            onTranscriptChange(bestText)
          }
        }
      } catch {
        // Gemini failed — continue with Web Speech text
      }

      // Step 3: NLP correction pipeline (4 layers)
      if (bestText.length >= 5) {
        setProcessingStep('NLP 校正中...')
        try {
          const corrResult = await correctMutation.mutateAsync({
            transcript: bestText,
            useHfModel: true,
          })

          if (corrResult.ok && corrResult.data.corrected !== bestText) {
            bestText = corrResult.data.corrected
            setCorrections(corrResult.data.changes)
            setSource('nlp_corrected')
            setDisplayText(bestText)
            onTranscriptChange(bestText)
          }
        } catch {
          // NLP correction failed — continue with current text
          // Offer offline AI when cloud correction fails and user hasn't declined this session
          if (shouldOfferOfflineAI()) setShowOfflineAIModal(true)
        }
      }

      setProcessingStep(null)
    }

    runPipeline()
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [audioBlob])

  // Reset when audioBlob changes to null (new recording)
  useEffect(() => {
    if (!audioBlob) {
      pipelineCalledRef.current = false
      setSource('web_speech')
      setCorrections([])
    }
  }, [audioBlob])

  const handleTextChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const newText = e.target.value
    setDisplayText(newText)
    setSource('user_edit')
    onTranscriptChange(newText)
  }, [onTranscriptChange])

  const correctionsText = useMemo(() => {
    if (corrections.length === 0) return ''
    const shown = corrections.slice(0, 5).join('、')
    return corrections.length > 5 ? `校正:${shown}...等 ${corrections.length} 項` : `校正:${shown}`
  }, [corrections])

  const sourceLabel: Record<TranscriptSource, string> = {
    web_speech: '瀏覽器辨識',
    vocab_corrected: '詞彙校正',
    device_ai: '設備 AI',
    gemini: 'Gemini 辨識',
    nlp_corrected: 'NLP 已校正',
    user_edit: '已手動修改',
  }

  return (
    <>
      <EnableOfflineAIModal
        open={showOfflineAIModal}
        onEnable={() => {
          localStorage.setItem('deviceAI.enabled', 'true')
          setShowOfflineAIModal(false)
          // Pre-load wllama in background; the OfflineAIBanner (mounted at App level) shows progress
          import('../lib/wllamaProvider').then((m) => m.getWllamaSession()).catch(() => { /* banner surfaces errors */ })
        }}
        onDecline={() => {
          sessionStorage.setItem('deviceAI.declinedThisSession', 'true')
          setShowOfflineAIModal(false)
        }}
      />
      <div className={`rounded-lg border ${colors.border} ${colors.bg} p-3`}>
      <div className="flex items-center justify-between mb-1.5">
        <p className={`text-xs font-medium ${colors.label}`}>語音辨識結果</p>
        <div className="flex items-center gap-1.5">
          {processingStep && (
            <span className="flex items-center gap-1 text-[10px] text-slate-500">
              <svg className="h-3 w-3 animate-spin" viewBox="0 0 24 24" fill="none">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
              </svg>
              {processingStep}
            </span>
          )}
          <span className={`rounded-full px-2 py-0.5 text-[10px] font-medium ${colors.badge}`}>
            {sourceLabel[source]}
          </span>
        </div>
      </div>
      <textarea
        value={displayText}
        onChange={handleTextChange}
        rows={Math.max(3, Math.min(8, Math.ceil(displayText.length / 40)))}
        className="w-full resize-y rounded-md border border-slate-200 bg-white px-3 py-2 text-sm text-slate-700 focus:border-indigo-300 focus:outline-none focus:ring-1 focus:ring-indigo-200"
        placeholder="語音辨識結果會顯示在這裡,你也可以手動編輯修正..."
      />
      <div className="mt-1 flex items-center justify-between">
        {correctionsText ? (
          <p className="text-[10px] text-amber-600">
            {correctionsText}
          </p>
        ) : (
          <span />
        )}
        <p className="text-[10px] text-slate-400">
          共 {displayText.length} 字 · 可直接編輯修正後再按 AI 填寫
        </p>
      </div>
    </div>
    </>
  )
}

export default memo(SmartTranscript)