fix(diarization): synchronize transcript highlighting with acoustic timestamps and pause during silence

This commit is contained in:
Ayush
2026-11-17 17:15:01 +05:30
parent f451738732
commit aaab466480
2 changed files with 105 additions and 28 deletions
+38 -9
View File
@@ -621,7 +621,7 @@ ${finalTranscript.slice(0, 4000)}`;
// ---------------------------------------------------------------------------
app.post('/api/transcribe', async (req, res) => {
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 (!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
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', {
method: 'POST',
headers: {
@@ -646,7 +649,8 @@ app.post('/api/transcribe', async (req, res) => {
mode: "translate",
with_diarization: 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();
let finalTranscript = '';
let structuredEntries = [];
// Parse Diarized Transcript natively returned by Sarvam
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]);
// 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 rawId = (entry.speaker || entry.speaker_id || entry.speaker_label || '0').toString();
const speakerId = rawId.toUpperCase().startsWith('SPEAKER') ? rawId : `Speaker_${rawId}`;
let textContent = entry.text || entry.transcript || entry.words || '';
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');
@@ -780,15 +799,24 @@ ${plainConversation.slice(0, 3000)}`;
console.error("Role Classifier failed, falling back to defaults:", err.message);
}
// Step 3: Apply Classifications for UI Output
finalTranscript = normalizedEntries.map(entry => {
// Use the LLM's classification or fallback to Patient
// Step 3: Apply Classifications for UI Output & Structured Entries
structuredEntries = normalizedEntries.map(entry => {
let role = roleMap[entry.speakerId] || 'Patient';
if (Object.keys(roleMap).length === 0 && entry.speakerId === firstSpeakerId) {
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');
console.log("Sarvam Native Diarization + Role Classification complete!");
} else {
@@ -797,6 +825,7 @@ ${plainConversation.slice(0, 3000)}`;
res.json({
transcript: finalTranscript,
entries: structuredEntries,
chunks: 1,
language: lang,
processedSeconds: dataLength / bytesPerSec