feat(diarization): Sub-Phase 3B.2 - intent-based turn attribution, 1-click role picker menu, and high-contrast color palette
This commit is contained in:
@@ -789,11 +789,15 @@ MANDATORY CLINICAL RULES:
|
||||
2. If 2 speakers are detected: One MUST be 'Doctor' and the other MUST be 'Patient'.
|
||||
3. If 3 or more speakers are detected: Assign 'Doctor' (the medical professional) and 'Patient' (the person being treated) first. Only assign 'Relative' if a speaker speaks on behalf of the patient in third person ('my mother has fever', 'he didn't eat'). Only assign 'Nurse' if taking vitals or assisting.
|
||||
|
||||
ROLE CRITERIA:
|
||||
ROLE CRITERIA & CONTEXTUAL BOUNDARIES:
|
||||
- 'Doctor': Asks diagnostic questions, conducts clinical examination, explains medical conditions, prescribes medicines/tests/dosages, gives medical advice.
|
||||
- 'Patient': Describes their own symptoms ("I had fever", "now there is no pain"), answers doctor questions about pain/duration, asks about treatment/diet for themselves ("What will I do with the rest of the pills?").
|
||||
- 'Relative': Speaks on behalf of the patient (e.g., 'my father has fever', 'she cannot sleep', 'he is not eating'), accompanies the patient, or asks caretaking questions.
|
||||
- 'Nurse': Reports vital signs (BP, pulse, SPO2, temperature), assists doctor or coordinates patient logistics.
|
||||
- 'Relative': Accompanying family member (spouse, parent, child). Speaks about the patient's personal home life, sleep, eating habits, or home-observed symptoms ("my mother has fever", "he cannot sleep", "he is not eating").
|
||||
- 'Nurse': Clinic/hospital staff handling operational tasks, patient navigation, room instructions ("come inside", "are you with them", "sit here", "go inside now", "next patient / next song"), taking vitals (BP, SpO2, pulse, temperature), or checking medical files.
|
||||
|
||||
CRITICAL DISTINCTION (NURSE vs RELATIVE):
|
||||
- Procedural, logistical, clinic-room, or patient flow instructions ("are you with them", "go inside", "look", "next patient", "take chart") = 'Nurse'.
|
||||
- Family health, home care, home symptoms, or diet discussions = 'Relative'.
|
||||
|
||||
CRITICAL INSTRUCTION:
|
||||
Return ONLY a valid JSON object where keys are the EXACT speaker IDs listed above and values are the roles.
|
||||
@@ -951,6 +955,104 @@ ${plainConversation.slice(0, 4000)}`;
|
||||
return roleMap;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Intent-Based Conversational Dialogue Turn Refinement
|
||||
// Resolves acoustic cluster collapse, mono mic bleed, and Marathi pro-drop
|
||||
// by analyzing human conversational intent rather than brittle keyword matching
|
||||
// ---------------------------------------------------------------------------
|
||||
async function refineTurnsWithIntent(normalizedEntries, roleMap) {
|
||||
if (!normalizedEntries || normalizedEntries.length === 0) return [];
|
||||
|
||||
// Default baseline mapping using roleMap and rule-based heuristic
|
||||
const fallbackRoles = normalizedEntries.map(entry => {
|
||||
const base = roleMap[entry.speakerId] || 'Patient';
|
||||
return refineTurnRole(base, entry.textContent);
|
||||
});
|
||||
|
||||
if (!GROQ_API_KEY && !SARVAM_API_KEY) {
|
||||
return fallbackRoles;
|
||||
}
|
||||
|
||||
const turnsText = normalizedEntries.map((t, idx) => {
|
||||
const base = roleMap[t.speakerId] || 'Speaker';
|
||||
return `[Turn ${idx}] (${t.speakerId} | Baseline: ${base}): "${(t.textContent || '').replace(/"/g, "'")}"`;
|
||||
}).join('\n');
|
||||
|
||||
const intentPrompt = `You are an expert Clinical Consultation Dialogue Analyzer.
|
||||
Below is a transcribed clinical consultation.
|
||||
Because acoustic diarization can bleed or miscluster across noisy microphones, some utterances spoken by the patient, relative, or nurse may have been grouped under the Doctor's track (or vice versa).
|
||||
|
||||
ROLES & CONTEXTUAL BOUNDARIES:
|
||||
- 'Doctor': Medical professional examining, inquiring, reassuring, explaining medical condition, prescribing medicines/dosages, giving medical advice.
|
||||
- 'Patient': Person receiving medical care, describing personal bodily sensations/symptoms/fever/pain, answering questions about their physical health, or asking about their medication/diet/what they should do.
|
||||
- 'Relative': Accompanying family member (spouse, parent, child). Speaks about the patient's personal home life, sleep, eating habits, or home-observed symptoms ('my husband has pain', 'she hasn't eaten since yesterday').
|
||||
- 'Nurse': Clinic or hospital staff handling operational tasks, patient navigation, room instructions ("come inside", "are you with them, go inside", "look", "sit on bed", "next patient / next song"), taking vitals (BP, SpO2, pulse, temperature), or checking medical charts.
|
||||
|
||||
CRUCIAL DISTINCTION (NURSE vs RELATIVE):
|
||||
- If the speaker gives logistical, clinic-room, or procedural instructions ("are you with them, go inside", "look", "wait outside", "next patient", "give file"), classify as 'Nurse'.
|
||||
- If the speaker discusses family health, personal care, home lifestyle, or expresses emotional concern for the patient, classify as 'Relative'.
|
||||
|
||||
CONVERSATION TURNS:
|
||||
${turnsText.slice(0, 5000)}
|
||||
|
||||
TASK:
|
||||
Classify each turn index based on the TRUE CONVERSATIONAL INTENT.
|
||||
- If an utterance is reporting personal symptoms, sensations, or asking what to do with treatment, classify as 'Patient'.
|
||||
- If an utterance is medical reassurance, diagnosis, or prescription instructions, classify as 'Doctor'.
|
||||
- If an utterance is clinic navigation/room coordination ("are you with them", "go inside", "look"), classify as 'Nurse'.
|
||||
- If an utterance is home/family health history, classify as 'Relative'.
|
||||
|
||||
OUTPUT FORMAT:
|
||||
Output ONLY a valid JSON array of strings containing the exact role for each turn index from 0 to ${normalizedEntries.length - 1}.
|
||||
Example: ["Doctor", "Patient", "Patient", "Nurse", "Doctor"]`;
|
||||
|
||||
// Try Groq Primary (openai/gpt-oss-120b)
|
||||
if (GROQ_API_KEY) {
|
||||
try {
|
||||
console.log(`[IntentClassifier] Refining ${normalizedEntries.length} turns with Groq (${GROQ_PRIMARY_MODEL})...`);
|
||||
const gRes = await fetch('https://api.groq.com/openai/v1/chat/completions', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${GROQ_API_KEY}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: GROQ_PRIMARY_MODEL,
|
||||
temperature: 0.1,
|
||||
messages: [
|
||||
{ role: 'system', content: 'You are a strict clinical dialogue role analyzer. Output JSON array only.' },
|
||||
{ role: 'user', content: intentPrompt }
|
||||
]
|
||||
})
|
||||
});
|
||||
if (gRes.ok) {
|
||||
const gData = await gRes.json();
|
||||
const content = gData?.choices?.[0]?.message?.content || '';
|
||||
const match = content.match(/\[[\s\S]*\]/);
|
||||
if (match) {
|
||||
const parsed = JSON.parse(match[0]);
|
||||
if (Array.isArray(parsed) && parsed.length === normalizedEntries.length) {
|
||||
console.log(`✅ [IntentClassifier] Successfully refined ${parsed.length} turns via Groq.`);
|
||||
return parsed.map((r, i) => {
|
||||
const val = (r || '').toString().toLowerCase();
|
||||
if (val.includes('doc')) return 'Doctor';
|
||||
if (val.includes('relat') || val.includes('fam')) return 'Relative';
|
||||
if (val.includes('nurse')) return 'Nurse';
|
||||
return 'Patient';
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn(`[IntentClassifier] Groq intent error:`, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to heuristic roles
|
||||
console.log(`[IntentClassifier] Using heuristic turn role fallback.`);
|
||||
return fallbackRoles;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// REST: Full audio (base64 WAV) → Sarvam STT → transcript
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -1110,11 +1212,12 @@ app.post('/api/transcribe', async (req, res) => {
|
||||
const roleMap = await classifyConversationRoles(normalizedEntries, uniqueSpeakerIds);
|
||||
console.log("Final Speaker Role Mapping:", roleMap);
|
||||
|
||||
// Step 3: Apply Classifications for UI Output & Structured Entries with Turn-Level Semantic Refinement
|
||||
structuredEntries = normalizedEntries.map(entry => {
|
||||
const baseRole = roleMap[entry.speakerId] || 'Patient';
|
||||
// Apply turn-level semantic guardrail to catch symptom/medication bleed
|
||||
const finalRole = refineTurnRole(baseRole, entry.textContent);
|
||||
// Step 3: Apply Intent-Based Turn Alignment (resolves acoustic cluster bleed & natural speech misattribution)
|
||||
console.log("9. Refining Turn Roles using Conversational Intent Analysis...");
|
||||
const turnRoles = await refineTurnsWithIntent(normalizedEntries, roleMap);
|
||||
|
||||
structuredEntries = normalizedEntries.map((entry, idx) => {
|
||||
const finalRole = turnRoles[idx] || roleMap[entry.speakerId] || 'Patient';
|
||||
|
||||
return {
|
||||
speakerId: entry.speakerId,
|
||||
@@ -1270,7 +1373,8 @@ module.exports = {
|
||||
app,
|
||||
classifyConversationRoles,
|
||||
classifyRolesWithRules,
|
||||
refineTurnRole
|
||||
refineTurnRole,
|
||||
refineTurnsWithIntent
|
||||
};
|
||||
|
||||
let server;
|
||||
|
||||
Reference in New Issue
Block a user