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', {
|
const resp = await fetch('/api/transcribe', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
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();
|
const data = await resp.json();
|
||||||
if (!resp.ok) throw new Error(data.error || 'Server error ' + resp.status);
|
if (!resp.ok) throw new Error(data.error || 'Server error ' + resp.status);
|
||||||
|
|
||||||
currentTranscript = data.transcript || '';
|
currentTranscript = data.transcript || '';
|
||||||
parseAndSetFullTranscript(currentTranscript, secondsElapsed);
|
parseAndSetFullTranscript(currentTranscript, secondsElapsed, data.entries);
|
||||||
recStatusText.textContent = `Completed in ${fmtTime(secondsElapsed)} • Generating clinical summary…`;
|
recStatusText.textContent = `Completed in ${fmtTime(secondsElapsed)} • Generating clinical summary…`;
|
||||||
showToast('Full transcript synchronized! Generating summary…');
|
showToast('Full transcript synchronized! Generating summary…');
|
||||||
|
|
||||||
@@ -592,7 +592,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ── Parse Full Transcript & Assign Real-time Audio Timestamps ─────────────
|
// ── Parse Full Transcript & Assign Real-time Audio Timestamps ─────────────
|
||||||
function parseAndSetFullTranscript(text, totalDurationSec) {
|
function parseAndSetFullTranscript(text, totalDurationSec, entries) {
|
||||||
if (!text || !text.trim()) {
|
if (!text || !text.trim()) {
|
||||||
transcriptBody.innerHTML = '<div class="transcript-placeholder"><p>No speech detected in audio.</p></div>';
|
transcriptBody.innerHTML = '<div class="transcript-placeholder"><p>No speech detected in audio.</p></div>';
|
||||||
return;
|
return;
|
||||||
@@ -604,7 +604,37 @@
|
|||||||
|
|
||||||
liveUtterances = [];
|
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();
|
const plainText = text.replace(/\*/g, '').trim();
|
||||||
|
|
||||||
// Check if text has Doctor/Patient/Relative/Nurse markers OR the new [Speaker_X | Role] format
|
// 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
|
// 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 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;
|
let currentOffset = 0;
|
||||||
segments.forEach((segment, idx) => {
|
segments.forEach((segment, idx) => {
|
||||||
const isPatient = /^(?:\[Speaker_\d+\s*\|\s*Patient\])|(?:(?:पेशंट|patient|रुग्ण)\s*[::\-])/i.test(segment);
|
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();
|
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 proportion = wordCounts[idx] / totalWords;
|
||||||
const wordCount = cleanedText.split(/\s+/).length;
|
const segmentDuration = Math.max(1.5, proportion * speechDurationBudget);
|
||||||
const segmentDuration = Math.max(2, wordCount / 2.5);
|
|
||||||
|
|
||||||
liveUtterances.push({
|
liveUtterances.push({
|
||||||
id: 'utt-' + idx,
|
id: 'utt-' + idx,
|
||||||
@@ -648,7 +687,7 @@
|
|||||||
startSec: currentOffset,
|
startSec: currentOffset,
|
||||||
endSec: currentOffset + segmentDuration
|
endSec: currentOffset + segmentDuration
|
||||||
});
|
});
|
||||||
currentOffset += segmentDuration;
|
currentOffset += segmentDuration + pausePerTurn;
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// Fallback if AI didn't format it properly
|
// Fallback if AI didn't format it properly
|
||||||
@@ -697,7 +736,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
html += `
|
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-avatar">${icon}</div>
|
||||||
<div class="utterance-content">
|
<div class="utterance-content">
|
||||||
<div class="utterance-meta">
|
<div class="utterance-meta">
|
||||||
@@ -797,17 +836,26 @@
|
|||||||
|
|
||||||
function syncHighlightUtterance(currentSec) {
|
function syncHighlightUtterance(currentSec) {
|
||||||
const items = document.querySelectorAll('.utterance-item');
|
const items = document.querySelectorAll('.utterance-item');
|
||||||
|
let matchedItem = null;
|
||||||
|
|
||||||
items.forEach((item) => {
|
items.forEach((item) => {
|
||||||
const start = parseFloat(item.getAttribute('data-start') || 0);
|
const start = parseFloat(item.getAttribute('data-start') || 0);
|
||||||
const end = parseFloat(item.getAttribute('data-end') || 0);
|
const end = parseFloat(item.getAttribute('data-end') || 0);
|
||||||
if (currentSec >= start && currentSec <= end) {
|
if (currentSec >= start && currentSec <= end) {
|
||||||
if (!item.classList.contains('active-playing')) {
|
matchedItem = item;
|
||||||
items.forEach(i => i.classList.remove('active-playing'));
|
|
||||||
item.classList.add('active-playing');
|
|
||||||
item.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
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() {
|
function removePlayingHighlights() {
|
||||||
@@ -1006,16 +1054,16 @@
|
|||||||
const transcribePromise = fetch('/api/transcribe', {
|
const transcribePromise = fetch('/api/transcribe', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
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 => {
|
}).then(async resp => {
|
||||||
const data = await resp.json();
|
const data = await resp.json();
|
||||||
if (!resp.ok) throw new Error(data.error || 'Server error');
|
if (!resp.ok) throw new Error(data.error || 'Server error');
|
||||||
return data.transcript;
|
return data;
|
||||||
});
|
});
|
||||||
|
|
||||||
const finalTranscriptText = await transcribePromise;
|
const transcribeData = await transcribePromise;
|
||||||
currentTranscript = finalTranscriptText;
|
currentTranscript = transcribeData.transcript || '';
|
||||||
parseAndSetFullTranscript(currentTranscript, totalDurationSec);
|
parseAndSetFullTranscript(currentTranscript, totalDurationSec, transcribeData.entries);
|
||||||
|
|
||||||
recStatusText.textContent = `✅ Transcribed ${file.name} successfully! Generating Summary...`;
|
recStatusText.textContent = `✅ Transcribed ${file.name} successfully! Generating Summary...`;
|
||||||
showToast('Audio transcribed & diarized! Generating AI Summary...');
|
showToast('Audio transcribed & diarized! Generating AI Summary...');
|
||||||
|
|||||||
@@ -621,7 +621,7 @@ ${finalTranscript.slice(0, 4000)}`;
|
|||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
app.post('/api/transcribe', async (req, res) => {
|
app.post('/api/transcribe', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { audio_b64, language_code } = req.body || {};
|
const { audio_b64, language_code, num_speakers } = req.body || {};
|
||||||
if (!audio_b64) return res.status(400).json({ error: 'audio_b64 missing' });
|
if (!audio_b64) return res.status(400).json({ error: 'audio_b64 missing' });
|
||||||
if (!SARVAM_API_KEY) return res.status(500).json({ error: 'SARVAM_API_KEY not configured on server.' });
|
if (!SARVAM_API_KEY) return res.status(500).json({ error: 'SARVAM_API_KEY not configured on server.' });
|
||||||
|
|
||||||
@@ -632,8 +632,11 @@ app.post('/api/transcribe', async (req, res) => {
|
|||||||
// Audio crop logic removed to process FULL audio
|
// Audio crop logic removed to process FULL audio
|
||||||
|
|
||||||
const lang = (language_code && language_code !== 'auto') ? language_code : 'unknown';
|
const lang = (language_code && language_code !== 'auto') ? language_code : 'unknown';
|
||||||
|
const targetSpeakers = (num_speakers && parseInt(num_speakers, 10) > 0)
|
||||||
|
? parseInt(num_speakers, 10)
|
||||||
|
: 2;
|
||||||
|
|
||||||
console.log("1. Initializing Sarvam Batch Job (Transcript + Diarization, Mode: Translate)...");
|
console.log(`1. Initializing Sarvam Batch Job (Transcript + Diarization, Mode: Translate, Num Speakers: ${targetSpeakers})...`);
|
||||||
const initRes = await fetch('https://api.sarvam.ai/speech-to-text/job/v1', {
|
const initRes = await fetch('https://api.sarvam.ai/speech-to-text/job/v1', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
@@ -646,7 +649,8 @@ app.post('/api/transcribe', async (req, res) => {
|
|||||||
mode: "translate",
|
mode: "translate",
|
||||||
with_diarization: true,
|
with_diarization: true,
|
||||||
with_timestamps: true,
|
with_timestamps: true,
|
||||||
language_code: lang
|
language_code: lang,
|
||||||
|
num_speakers: targetSpeakers
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
@@ -727,18 +731,33 @@ app.post('/api/transcribe', async (req, res) => {
|
|||||||
const resultData = await resultRes.json();
|
const resultData = await resultRes.json();
|
||||||
|
|
||||||
let finalTranscript = '';
|
let finalTranscript = '';
|
||||||
|
let structuredEntries = [];
|
||||||
|
|
||||||
// Parse Diarized Transcript natively returned by Sarvam
|
// Parse Diarized Transcript natively returned by Sarvam
|
||||||
if (resultData.diarized_transcript && resultData.diarized_transcript.entries && resultData.diarized_transcript.entries.length > 0) {
|
if (resultData.diarized_transcript && resultData.diarized_transcript.entries && resultData.diarized_transcript.entries.length > 0) {
|
||||||
console.log("Sample Diarization Entry from Sarvam:", resultData.diarized_transcript.entries[0]);
|
console.log("Sample Diarization Entry from Sarvam:", resultData.diarized_transcript.entries[0]);
|
||||||
|
|
||||||
// Step 1: Normalize Speaker IDs and extract plain conversation for NLP
|
// Step 1: Normalize Speaker IDs, timestamps, and extract plain conversation for NLP
|
||||||
const normalizedEntries = await Promise.all(resultData.diarized_transcript.entries.map(async entry => {
|
const normalizedEntries = await Promise.all(resultData.diarized_transcript.entries.map(async entry => {
|
||||||
const rawId = (entry.speaker || entry.speaker_id || entry.speaker_label || '0').toString();
|
const rawId = (entry.speaker || entry.speaker_id || entry.speaker_label || '0').toString();
|
||||||
const speakerId = rawId.toUpperCase().startsWith('SPEAKER') ? rawId : `Speaker_${rawId}`;
|
const speakerId = rawId.toUpperCase().startsWith('SPEAKER') ? rawId : `Speaker_${rawId}`;
|
||||||
let textContent = entry.text || entry.transcript || entry.words || '';
|
let textContent = entry.text || entry.transcript || entry.words || '';
|
||||||
textContent = await ensureEnglishText(textContent);
|
textContent = await ensureEnglishText(textContent);
|
||||||
return { speakerId, textContent };
|
|
||||||
|
const startSec = typeof entry.start_time_seconds === 'number'
|
||||||
|
? entry.start_time_seconds
|
||||||
|
: (parseFloat(entry.start_time_seconds || entry.start_time || entry.start || 0) || 0);
|
||||||
|
|
||||||
|
const endSec = typeof entry.end_time_seconds === 'number'
|
||||||
|
? entry.end_time_seconds
|
||||||
|
: (parseFloat(entry.end_time_seconds || entry.end_time || entry.end || 0) || (startSec + 2.0));
|
||||||
|
|
||||||
|
return {
|
||||||
|
speakerId,
|
||||||
|
textContent,
|
||||||
|
startSec: Number(startSec.toFixed(2)),
|
||||||
|
endSec: Number(endSec.toFixed(2))
|
||||||
|
};
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const plainConversation = normalizedEntries.map(entry => `${entry.speakerId}: ${entry.textContent}`).join('\n');
|
const plainConversation = normalizedEntries.map(entry => `${entry.speakerId}: ${entry.textContent}`).join('\n');
|
||||||
@@ -780,15 +799,24 @@ ${plainConversation.slice(0, 3000)}`;
|
|||||||
console.error("Role Classifier failed, falling back to defaults:", err.message);
|
console.error("Role Classifier failed, falling back to defaults:", err.message);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Step 3: Apply Classifications for UI Output
|
// Step 3: Apply Classifications for UI Output & Structured Entries
|
||||||
finalTranscript = normalizedEntries.map(entry => {
|
structuredEntries = normalizedEntries.map(entry => {
|
||||||
// Use the LLM's classification or fallback to Patient
|
|
||||||
let role = roleMap[entry.speakerId] || 'Patient';
|
let role = roleMap[entry.speakerId] || 'Patient';
|
||||||
if (Object.keys(roleMap).length === 0 && entry.speakerId === firstSpeakerId) {
|
if (Object.keys(roleMap).length === 0 && entry.speakerId === firstSpeakerId) {
|
||||||
role = 'Doctor'; // hardcoded fallback if LLM completely fails
|
role = 'Doctor'; // hardcoded fallback if LLM completely fails
|
||||||
}
|
}
|
||||||
|
|
||||||
return `[${entry.speakerId} | ${role}] ${entry.textContent}`;
|
return {
|
||||||
|
speakerId: entry.speakerId,
|
||||||
|
role: role,
|
||||||
|
text: entry.textContent,
|
||||||
|
startSec: entry.startSec,
|
||||||
|
endSec: entry.endSec
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
finalTranscript = structuredEntries.map(entry => {
|
||||||
|
return `[${entry.speakerId} | ${entry.role}] ${entry.text}`;
|
||||||
}).join('\n\n');
|
}).join('\n\n');
|
||||||
console.log("Sarvam Native Diarization + Role Classification complete!");
|
console.log("Sarvam Native Diarization + Role Classification complete!");
|
||||||
} else {
|
} else {
|
||||||
@@ -797,6 +825,7 @@ ${plainConversation.slice(0, 3000)}`;
|
|||||||
|
|
||||||
res.json({
|
res.json({
|
||||||
transcript: finalTranscript,
|
transcript: finalTranscript,
|
||||||
|
entries: structuredEntries,
|
||||||
chunks: 1,
|
chunks: 1,
|
||||||
language: lang,
|
language: lang,
|
||||||
processedSeconds: dataLength / bytesPerSec
|
processedSeconds: dataLength / bytesPerSec
|
||||||
|
|||||||
Reference in New Issue
Block a user