DONG-WEI-YANG
Claude Opus 4.7 (1M context)
refactor(ui): extract shouldOfferOfflineAI() helper, DRY the modal guard
dbfa411 Download src/components/SmartTranscript.tsx from mkc-itltc-AIOT/simple-case-management-assistant: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/spaces/mkc-itltc-AIOT/simple-case-management-assistant/resolve/main/src/components/SmartTranscript.tsx
- Command line
-
hf download hf://spaces/mkc-itltc-AIOT/simple-case-management-assistant/src/components/SmartTranscript.tsx
-
curl -L -o SmartTranscript.tsx https://huggingface.co/spaces/mkc-itltc-AIOT/simple-case-management-assistant/resolve/main/src/components/SmartTranscript.tsx
10.5 kB
| // 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) | |