Compare commits
1
Commits
main
...
aaab466480
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aaab466480 |
+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...');
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user