// 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 { 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('web_speech') const [processingStep, setProcessingStep] = useState(null) const [corrections, setCorrections] = useState([]) 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([]) 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) => { 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 = { web_speech: '瀏覽器辨識', vocab_corrected: '詞彙校正', device_ai: '設備 AI', gemini: 'Gemini 辨識', nlp_corrected: 'NLP 已校正', user_edit: '已手動修改', } return ( <> { 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) }} />

語音辨識結果

{processingStep && ( {processingStep} )} {sourceLabel[source]}