Spaces:
Running
Running
File size: 2,243 Bytes
bb1fe7d dd1b723 bb1fe7d dd1b723 bb1fe7d dd1b723 bb1fe7d dd1b723 bb1fe7d | 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 | import { pipeline } from '@huggingface/transformers';
// Initialize transcriber (lazy loading)
let transcriber;
const getTranscriber = async () => {
if (!transcriber) {
document.getElementById('status').textContent = 'Loading Whisper model...';
transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');
document.getElementById('status').textContent = 'Model loaded.';
}
return transcriber;
};
// DOM Elements
const audioInput = document.getElementById('audioInput');
const useSampleBtn = document.getElementById('useSample');
const player = document.getElementById('player');
const output = document.getElementById('output');
const status = document.getElementById('status');
const modeOptions = document.querySelectorAll('input[name="mode"]');
// Set audio source from file
audioInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (file) {
const url = URL.createObjectURL(file);
player.src = url;
output.textContent = '';
}
});
// Use sample JFK audio
useSampleBtn.addEventListener('click', () => {
const sampleUrl = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';
player.src = sampleUrl;
output.textContent = '';
});
// Get selected mode
const getSelectedMode = () => {
for (const option of modeOptions) {
if (option.checked) return option.value;
}
return 'normal';
};
// Transcribe button click handler
player.addEventListener('play', async () => {
try {
const transcriber = await getTranscriber();
const mode = getSelectedMode();
// Prepare transcription options
let options = {};
if (mode === 'chunks') {
options.return_timestamps = true;
} else if (mode === 'words') {
options.return_timestamps = 'word';
}
// Update status
status.textContent = 'Transcribing...';
output.textContent = 'Transcribing...';
// Perform transcription
const result = await transcriber(player.src, options);
output.textContent = JSON.stringify(result, null, 2);
status.textContent = 'Transcription complete.';
} catch (err) {
console.error(err);
status.textContent = `Error: ${err.message}`;
output.textContent = '';
}
}); |