Spaces:
Running
Running
File size: 10,865 Bytes
09b5094 |
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 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 |
import React, { useState, useRef, useEffect } from 'react';
import { ParakeetModel, getParakeetModel } from 'parakeet.js';
import './App.css';
export default function App() {
const repoId = 'istupakov/parakeet-tdt-0.6b-v2-onnx';
const [backend, setBackend] = useState('webgpu-hybrid');
const [encoderQuant, setEncoderQuant] = useState('fp32');
const [decoderQuant, setDecoderQuant] = useState('int8');
const [preprocessor, setPreprocessor] = useState('nemo128');
const [status, setStatus] = useState('Idle');
const [progress, setProgress] = useState('');
const [progressText, setProgressText] = useState('');
const [progressPct, setProgressPct] = useState(null);
const [text, setText] = useState('');
const [latestMetrics, setLatestMetrics] = useState(null);
const [transcriptions, setTranscriptions] = useState([]);
const [isTranscribing, setIsTranscribing] = useState(false);
const [verboseLog, setVerboseLog] = useState(false);
const [frameStride, setFrameStride] = useState(1);
const [dumpDetail, setDumpDetail] = useState(false);
const maxCores = navigator.hardwareConcurrency || 8;
const [cpuThreads, setCpuThreads] = useState(Math.max(1, maxCores - 2));
const modelRef = useRef(null);
const fileInputRef = useRef(null);
// Auto-adjust quant presets when backend changes
useEffect(() => {
if (backend.startsWith('webgpu')) {
setEncoderQuant('fp32');
setDecoderQuant('int8');
} else {
setEncoderQuant('int8');
setDecoderQuant('int8');
}
}, [backend]);
async function loadModel() {
setStatus('Loading model…');
setProgress('');
setProgressText('');
setProgressPct(0);
console.time('LoadModel');
try {
const progressCallback = (p) => setProgress(`${p.file}: ${Math.round(p.loaded/p.total*100)}%`);
// 1. Download all model files from HuggingFace Hub
const modelUrls = await getParakeetModel(repoId, {
encoderQuant,
decoderQuant,
preprocessor,
progress: progressCallback
});
// Show compiling sessions stage
setStatus('Creating sessions…');
setProgressText('Compiling model (this may take ~10 s)…');
setProgressPct(null);
// 2. Create the model instance with all file URLs
modelRef.current = await ParakeetModel.fromUrls({
...modelUrls.urls,
backend,
});
// 3. Warm-up and verify
setStatus('Warming up & verifying…');
setProgressText('Model ready! Upload an audio file to transcribe.');
setProgressPct(null);
console.timeEnd('LoadModel');
setStatus('Model ready ✔');
setProgressText('');
} catch (e) {
console.error(e);
setStatus(`Failed: ${e.message}`);
setProgress('');
}
}
async function transcribeFile(e) {
if (!modelRef.current) return alert('Load model first');
const file = e.target.files?.[0];
if (!file) return;
setIsTranscribing(true);
setStatus(`Transcribing "${file.name}"…`);
try {
const buf = await file.arrayBuffer();
const audioCtx = new AudioContext({ sampleRate: 16000 });
const decoded = await audioCtx.decodeAudioData(buf);
const pcm = decoded.getChannelData(0);
console.time(`Transcribe-${file.name}`);
const res = await modelRef.current.transcribe(pcm, 16_000, {
returnTimestamps: true,
returnConfidences: true,
frameStride
});
console.timeEnd(`Transcribe-${file.name}`);
if (dumpDetail) {
console.log('[Parakeet] Detailed transcription output', res);
}
setLatestMetrics(res.metrics);
// Add to transcriptions list
const newTranscription = {
id: Date.now(),
filename: file.name,
text: res.utterance_text,
timestamp: new Date().toLocaleTimeString(),
duration: pcm.length / 16000, // duration in seconds
wordCount: res.words?.length || 0,
confidence: res.confidence_scores?.token_avg ?? res.confidence_scores?.word_avg ?? null,
metrics: res.metrics
};
setTranscriptions(prev => [newTranscription, ...prev]);
setText(res.utterance_text); // Show latest transcription
setStatus('Model ready ✔'); // Ready for next file
} catch (error) {
console.error('Transcription failed:', error);
setStatus('Transcription failed');
alert(`Failed to transcribe "${file.name}": ${error.message}`);
} finally {
setIsTranscribing(false);
// Clear the file input so the same file can be selected again
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
}
}
function clearTranscriptions() {
setTranscriptions([]);
setText('');
}
return (
<div className="app">
<h2>🦜 Parakeet.js - HF Spaces Demo</h2>
<p>NVIDIA Parakeet speech recognition for the browser using WebGPU/WASM</p>
<div className="controls">
<p>
<strong>Model:</strong> {repoId}
</p>
</div>
<div className="controls">
<label>
Backend:
<select value={backend} onChange={e=>setBackend(e.target.value)}>
<option value="webgpu-hybrid">WebGPU</option>
<option value="wasm">WASM (CPU)</option>
</select>
</label>
{' '}
<label>
Encoder Quant:
<select value={encoderQuant} onChange={e=>setEncoderQuant(e.target.value)}>
<option value="int8">int8 (faster)</option>
<option value="fp32">fp32 (higher quality)</option>
</select>
</label>
{' '}
<label>
Decoder Quant:
<select value={decoderQuant} onChange={e=>setDecoderQuant(e.target.value)}>
<option value="int8">int8 (faster)</option>
<option value="fp32">fp32 (higher quality)</option>
</select>
</label>
{' '}
<label>
Preprocessor:
<select value={preprocessor} onChange={e=>setPreprocessor(e.target.value)}>
<option value="nemo128">nemo128 (default)</option>
</select>
</label>
{' '}
<label>
Stride:
<select value={frameStride} onChange={e=>setFrameStride(Number(e.target.value))}>
<option value={1}>1</option>
<option value={2}>2</option>
<option value={4}>4</option>
</select>
</label>
{' '}
<label>
<input type="checkbox" checked={verboseLog} onChange={e => setVerboseLog(e.target.checked)} />
Verbose Log
</label>
{' '}
<label style={{fontSize:'0.9em'}}>
<input type="checkbox" checked={dumpDetail} onChange={e=>setDumpDetail(e.target.checked)} />
Dump result to console
</label>
{(backend === 'wasm') && (
<label style={{fontSize:'0.9em'}}>
Threads:
<input type="number" min="1" max={maxCores} value={cpuThreads} onChange={e=>setCpuThreads(Number(e.target.value))} style={{width:'4rem'}} />
</label>
)}
<button
onClick={loadModel}
disabled={!status.toLowerCase().includes('fail') && status !== 'Idle'}
className="primary"
>
{status === 'Model ready ✔' ? 'Model Loaded' : 'Load Model'}
</button>
</div>
{typeof SharedArrayBuffer === 'undefined' && backend === 'wasm' && (
<div style={{
marginBottom: '1rem',
padding: '0.5rem',
backgroundColor: '#fff3cd',
border: '1px solid #ffeaa7',
borderRadius: '4px',
fontSize: '0.9em'
}}>
⚠️ <strong>Performance Note:</strong> SharedArrayBuffer is not available.
WASM will run single-threaded. For better performance, use WebGPU.
</div>
)}
<div className="controls">
<input
ref={fileInputRef}
type="file"
accept="audio/*"
onChange={transcribeFile}
disabled={status !== 'Model ready ✔' || isTranscribing}
/>
{transcriptions.length > 0 && (
<button
onClick={clearTranscriptions}
style={{ marginLeft: '1rem', padding: '0.25rem 0.5rem' }}
>
Clear History
</button>
)}
</div>
<p>Status: {status}</p>
{progressPct!==null && (
<div className="progress-wrapper">
<div className="progress-bar"><div style={{ width: `${progressPct}%` }} /></div>
<p className="progress-text">{progressText}</p>
</div>
)}
{/* Latest transcription */}
<div className="controls">
<h3>Latest Transcription:</h3>
<textarea
value={text}
readOnly
className="textarea"
placeholder="Transcribed text will appear here..."
/>
</div>
{/* Latest transcription performace info */}
{latestMetrics && (
<div className="performance">
<strong>RTF:</strong> {latestMetrics.rtf?.toFixed(2)}x | Total: {latestMetrics.total_ms} ms<br/>
Preprocess {latestMetrics.preprocess_ms} ms · Encode {latestMetrics.encode_ms} ms · Decode {latestMetrics.decode_ms} ms · Tokenize {latestMetrics.tokenize_ms} ms
</div>
)}
{/* Transcription history */}
{transcriptions.length > 0 && (
<div className="history">
<h3>Transcription History ({transcriptions.length} files):</h3>
<div style={{ maxHeight: '400px', overflowY: 'auto', border: '1px solid #ddd', borderRadius: '4px' }}>
{transcriptions.map((trans) => (
<div className="history-item" key={trans.id}>
<div className="history-meta"><strong>{trans.filename}</strong><span>{trans.timestamp}</span></div>
<div className="history-stats">Duration: {trans.duration.toFixed(1)}s | Words: {trans.wordCount}{trans.confidence && ` | Confidence: ${trans.confidence.toFixed(2)}`}{trans.metrics && ` | RTF: ${trans.metrics.rtf?.toFixed(2)}x`}</div>
<div className="history-text">{trans.text}</div>
</div>
))}
</div>
</div>
)}
<div style={{ marginTop: '2rem', padding: '1rem', backgroundColor: '#f8f9fa', borderRadius: '4px', fontSize: '0.9em' }}>
<h4>🔗 Links:</h4>
<p>
<a href="https://github.com/ysdede/parakeet.js" target="_blank" rel="noopener noreferrer">
GitHub Repository
</a>
{' | '}
<a href="https://www.npmjs.com/package/parakeet.js" target="_blank" rel="noopener noreferrer">
npm Package
</a>
</p>
</div>
</div>
);
}
|