@@ -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...');
diff --git a/server.js b/server.js
index 9b49f52..7a57407 100644
--- a/server.js
+++ b/server.js
@@ -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