fix(diarization): synchronize transcript highlighting with acoustic timestamps and pause during silence
This commit is contained in:
+67
-19
@@ -560,14 +560,14 @@
|
||||
const resp = await fetch('/api/transcribe', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ audio_b64, language_code: lang })
|
||||
body: JSON.stringify({ audio_b64, language_code: lang, num_speakers: 2 })
|
||||
});
|
||||
|
||||
const data = await resp.json();
|
||||
if (!resp.ok) throw new Error(data.error || 'Server error ' + resp.status);
|
||||
|
||||
currentTranscript = data.transcript || '';
|
||||
parseAndSetFullTranscript(currentTranscript, secondsElapsed);
|
||||
parseAndSetFullTranscript(currentTranscript, secondsElapsed, data.entries);
|
||||
recStatusText.textContent = `Completed in ${fmtTime(secondsElapsed)} • Generating clinical summary…`;
|
||||
showToast('Full transcript synchronized! Generating summary…');
|
||||
|
||||
@@ -592,7 +592,7 @@
|
||||
}
|
||||
|
||||
// ── Parse Full Transcript & Assign Real-time Audio Timestamps ─────────────
|
||||
function parseAndSetFullTranscript(text, totalDurationSec) {
|
||||
function parseAndSetFullTranscript(text, totalDurationSec, entries) {
|
||||
if (!text || !text.trim()) {
|
||||
transcriptBody.innerHTML = '<div class="transcript-placeholder"><p>No speech detected in audio.</p></div>';
|
||||
return;
|
||||
@@ -604,7 +604,37 @@
|
||||
|
||||
liveUtterances = [];
|
||||
|
||||
// Strip markdown formatting like ** or *
|
||||
// Case 1: Use true acoustic timestamps returned directly by Sarvam Diarization
|
||||
if (entries && Array.isArray(entries) && entries.length > 0) {
|
||||
liveUtterances = entries.map((entry, idx) => {
|
||||
const role = (entry.role || 'patient').toLowerCase();
|
||||
let speaker = doctorName;
|
||||
if (role === 'patient') {
|
||||
speaker = patientName;
|
||||
} else if (role === 'relative') {
|
||||
speaker = 'Relative (नातेवाईक)';
|
||||
} else if (role === 'nurse') {
|
||||
speaker = 'Nurse (परिचारिका)';
|
||||
}
|
||||
|
||||
const startSec = typeof entry.startSec === 'number' ? entry.startSec : (parseFloat(entry.startSec) || 0);
|
||||
const endSec = typeof entry.endSec === 'number' ? entry.endSec : (parseFloat(entry.endSec) || (startSec + 2));
|
||||
|
||||
return {
|
||||
id: 'utt-' + idx,
|
||||
role: role,
|
||||
speaker: speaker,
|
||||
text: entry.text || entry.textContent || '',
|
||||
startSec: startSec,
|
||||
endSec: endSec
|
||||
};
|
||||
});
|
||||
|
||||
renderAllUtterances();
|
||||
return;
|
||||
}
|
||||
|
||||
// Case 2: Fallback text parsing if no structured timestamps provided
|
||||
const plainText = text.replace(/\*/g, '').trim();
|
||||
|
||||
// Check if text has Doctor/Patient/Relative/Nurse markers OR the new [Speaker_X | Role] format
|
||||
@@ -614,6 +644,16 @@
|
||||
// Split the text before each speaker label
|
||||
const segments = plainText.split(/(?=\[Speaker_\d+\s*\|\s*(?:Doctor|Patient|Relative|Nurse)\]|(?:डॉक्टर|पेशंट|Doctor|Patient|रुग्ण|Relative|नातेवाईक|Nurse|परिचारिका|नर्स)\s*[::\-])/i).map(s => s.trim()).filter(s => s.length > 0);
|
||||
|
||||
const wordCounts = segments.map(s => {
|
||||
const cleaned = s.replace(/^(?:\[Speaker_\d+\s*\|\s*(?:Doctor|Patient|Relative|Nurse)\]\s*)|^(?:(?:डॉक्टर|पेशंट|doctor|patient|रुग्ण|relative|नातेवाईक|nurse|परिचारिका|नर्स)\s*[::\-]\s*)/i, '').trim();
|
||||
return Math.max(1, cleaned.split(/\s+/).length);
|
||||
});
|
||||
const totalWords = wordCounts.reduce((a, b) => a + b, 0);
|
||||
|
||||
// Allocate 85% of total audio to speech, 15% to pauses between turns
|
||||
const pausePerTurn = segments.length > 1 ? (duration * 0.15) / (segments.length - 1) : 0;
|
||||
const speechDurationBudget = duration - (pausePerTurn * Math.max(0, segments.length - 1));
|
||||
|
||||
let currentOffset = 0;
|
||||
segments.forEach((segment, idx) => {
|
||||
const isPatient = /^(?:\[Speaker_\d+\s*\|\s*Patient\])|(?:(?:पेशंट|patient|रुग्ण)\s*[::\-])/i.test(segment);
|
||||
@@ -636,9 +676,8 @@
|
||||
|
||||
const cleanedText = segment.replace(/^(?:\[Speaker_\d+\s*\|\s*(?:Doctor|Patient|Relative|Nurse)\]\s*)|^(?:(?:डॉक्टर|पेशंट|doctor|patient|रुग्ण|relative|नातेवाईक|nurse|परिचारिका|नर्स)\s*[::\-]\s*)/i, '').trim();
|
||||
|
||||
// Approximate duration based on word count (avg 2.5 words per second)
|
||||
const wordCount = cleanedText.split(/\s+/).length;
|
||||
const segmentDuration = Math.max(2, wordCount / 2.5);
|
||||
const proportion = wordCounts[idx] / totalWords;
|
||||
const segmentDuration = Math.max(1.5, proportion * speechDurationBudget);
|
||||
|
||||
liveUtterances.push({
|
||||
id: 'utt-' + idx,
|
||||
@@ -648,7 +687,7 @@
|
||||
startSec: currentOffset,
|
||||
endSec: currentOffset + segmentDuration
|
||||
});
|
||||
currentOffset += segmentDuration;
|
||||
currentOffset += segmentDuration + pausePerTurn;
|
||||
});
|
||||
} else {
|
||||
// Fallback if AI didn't format it properly
|
||||
@@ -697,7 +736,7 @@
|
||||
}
|
||||
|
||||
html += `
|
||||
<div class="utterance-item ${utt.role}" id="${utt.id}" data-start="${utt.startSec.toFixed(1)}" data-end="${utt.endSec.toFixed(1)}" onclick="window.app.seekToTime(${utt.startSec})">
|
||||
<div class="utterance-item ${utt.role}" id="${utt.id}" data-start="${utt.startSec.toFixed(2)}" data-end="${utt.endSec.toFixed(2)}" onclick="window.app.seekToTime(${utt.startSec})">
|
||||
<div class="utterance-avatar">${icon}</div>
|
||||
<div class="utterance-content">
|
||||
<div class="utterance-meta">
|
||||
@@ -797,17 +836,26 @@
|
||||
|
||||
function syncHighlightUtterance(currentSec) {
|
||||
const items = document.querySelectorAll('.utterance-item');
|
||||
let matchedItem = null;
|
||||
|
||||
items.forEach((item) => {
|
||||
const start = parseFloat(item.getAttribute('data-start') || 0);
|
||||
const end = parseFloat(item.getAttribute('data-end') || 0);
|
||||
if (currentSec >= start && currentSec <= end) {
|
||||
if (!item.classList.contains('active-playing')) {
|
||||
items.forEach(i => i.classList.remove('active-playing'));
|
||||
item.classList.add('active-playing');
|
||||
item.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
||||
}
|
||||
matchedItem = item;
|
||||
}
|
||||
});
|
||||
|
||||
if (matchedItem) {
|
||||
if (!matchedItem.classList.contains('active-playing')) {
|
||||
items.forEach(i => i.classList.remove('active-playing'));
|
||||
matchedItem.classList.add('active-playing');
|
||||
matchedItem.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
||||
}
|
||||
} else {
|
||||
// Audio is currently in silence / pause: remove active highlight so it remains still
|
||||
items.forEach(i => i.classList.remove('active-playing'));
|
||||
}
|
||||
}
|
||||
|
||||
function removePlayingHighlights() {
|
||||
@@ -1006,16 +1054,16 @@
|
||||
const transcribePromise = fetch('/api/transcribe', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ audio_b64, language_code: lang })
|
||||
body: JSON.stringify({ audio_b64, language_code: lang, num_speakers: 2 })
|
||||
}).then(async resp => {
|
||||
const data = await resp.json();
|
||||
if (!resp.ok) throw new Error(data.error || 'Server error');
|
||||
return data.transcript;
|
||||
return data;
|
||||
});
|
||||
|
||||
const finalTranscriptText = await transcribePromise;
|
||||
currentTranscript = finalTranscriptText;
|
||||
parseAndSetFullTranscript(currentTranscript, totalDurationSec);
|
||||
const transcribeData = await transcribePromise;
|
||||
currentTranscript = transcribeData.transcript || '';
|
||||
parseAndSetFullTranscript(currentTranscript, totalDurationSec, transcribeData.entries);
|
||||
|
||||
recStatusText.textContent = `✅ Transcribed ${file.name} successfully! Generating Summary...`;
|
||||
showToast('Audio transcribed & diarized! Generating AI Summary...');
|
||||
|
||||
Reference in New Issue
Block a user