Initial commit: Doctor-Patient clinical transcription and structured summary pipeline

This commit is contained in:
Ayush
2026-11-16 19:22:04 +05:30
commit f451738732
60 changed files with 11321 additions and 0 deletions
+17
View File
@@ -0,0 +1,17 @@
# ====================================================================
# Doctor-Patient Clinical Transcription & Summary - Environment Config
# ====================================================================
# Sarvam AI API Key (Required for STT, Translation, and Native Diarization)
# Get your key from: https://dashboard.sarvam.ai
SARVAM_API_KEY=your_sarvam_api_key_here
# Optional: Sarvam Chat Model (Default: sarvam-105b-conversations)
SARVAM_CHAT_MODEL=sarvam-105b-conversations
# Optional: Groq API Key (Used as high-performance clinical summary fallback)
# Get your key from: https://console.groq.com
GROQ_API_KEY=your_groq_api_key_here
# Server Port (Default: 3000)
PORT=3000
+52
View File
@@ -0,0 +1,52 @@
# Node.js dependencies
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Python virtual environments & packages
venv/
.venv/
env/
venv_new/
backend/venv/
pkgs/
sarvamai_src/
backend/pretrained_models/
__pycache__/
backend/__pycache__/
*.py[cod]
*$py.class
*.whl
get-pip.py
# Environment variables & secrets
.env
.env.local
backend/.env
# Temporary audio files & user recordings
temp_audio/
backend/temp_audio/
data/audio/*
!data/audio/.gitkeep
*.wav
!test.wav
!backend/test.wav
# Logs & scratch
*.log
server_log.txt
debug.log
.system_generated/
scratch/
# Operating System files
.DS_Store
Thumbs.db
desktop.ini
# IDE & Editor files
.vscode/
.idea/
+224
View File
@@ -0,0 +1,224 @@
# AI Clinical Assistant — Doctor-Patient Consultation Transcription & Summary
An intelligent, real-time clinical speech-to-text transcription and structured medical summary pipeline tailored for doctor-patient consultations in multilingual environments (Marathi, Hindi, and English).
Powered by **Sarvam AI** for multilingual speech recognition, real-time WebSocket streaming, translation, and native speaker diarization, combined with high-performance LLMs (**Groq** / **Sarvam**) for clinical role classification and structured SOAP-format medical documentation.
---
## Key Features
- **Multilingual Speech-to-Text with Automatic English Translation**:
- Accepts audio spoken in **Marathi**, **Hindi**, or **English**.
- Always outputs clean, professional **English transcriptions** preserving medical accuracy, context, and intent.
- Employs Sarvam AI's `saaras:v4` translation mode with automated fallback pipelines.
- **Speaker Diarization & Role Classification**:
- Automatically separates distinct speakers (Doctor vs. Patient).
- Uses Sarvam Native Diarization paired with intelligent LLM context analysis for robust role classification.
- Hybrid speaker embedding fallback support.
- **Structured Clinical Summary (SOAP Format)**:
- Generates comprehensive medical summaries structured into:
- **Chief Complaint**
- **Symptoms & Observations**
- **Medical History**
- **Clinical Assessment**
- **Treatment Plan & Follow-up**
- Multi-tier LLM fallback pipeline (`llama-3.3-70b-versatile`, `openai/gpt-oss-120b`, `sarvam-105b-conversations`).
- **Real-Time Live Streaming & Batch Upload**:
- Live audio capture from the browser microphone streamed over WebSocket (16kHz mono linear16 PCM).
- Chunked file upload processing and full-file batch transcription.
- **Doctor & Patient Record Management**:
- Local database storage for consultation sessions, doctor profiles, and patient history.
---
## Architecture Overview
```
+-------------------------------------------------------------------------+
| Web Browser |
| - Live Microphone Audio (16kHz Mono PCM) |
| - Audio File Uploads (WAV/MP3) |
| - Real-time Transcript Viewer & SOAP Summary Display |
+-------------------------------------------------------------------------+
| ^
WebSocket / HTTP POST | Server Responses
v |
+-------------------------------------------------------------------------+
| Node.js Backend (server.js) |
| - Express HTTP Endpoints & WebSocket Server Proxy |
| - Audio Chunking & Format Normalization |
| - Multi-model LLM Fallback Coordinator |
+-------------------------------------------------------------------------+
| |
(Speech & Diarization) (LLM Inference)
v v
+-------------------------------+ +---------------------------+
| Sarvam AI APIs | | Groq APIs |
| - saaras:v4-realtime (WS STT) | | - llama-3.3-70b-versatile |
| - Batch Audio Diarization | | - openai/gpt-oss-120b |
| - Mayura v1 (Translation) | | - Clinical Summarization |
| - Sarvam 105B LLM | +---------------------------+
+-------------------------------+
```
---
## Project Structure
```
.
├── server.js # Main Express & WebSocket backend server
├── package.json # Node.js project manifest & dependencies
├── .env.example # Environment variables template
├── .gitignore # Git ignore rules for clean repository
├── db.js # Consultation, doctor, and patient data manager
├── hybrid_diarization.py # Python hybrid speaker diarization helper
├── public/ # Web application frontend assets
│ ├── index.html # Clinical assistant dashboard UI
│ ├── app.js # Microphone capture, WebSocket client, UI logic
│ ├── style.css # Modern clinical UI styles & themes
│ ├── logo.png # Application branding logo
│ └── favicon.png # Browser favicon
├── backend/ # Optional standalone Python/FastAPI service
│ ├── main.py # Starlette/FastAPI implementation
│ ├── diarization_pipeline.py # Voice embeddings & diarization logic
│ ├── requirements.txt # Python backend dependencies
│ └── .env.example # Python backend environment template
└── data/ # Data directory
└── db.json # Seed database for patients & consultations
```
---
## Prerequisites
Before setting up the project, make sure you have:
- **Node.js**: `v18.0.0` or higher ([Download Node.js](https://nodejs.org/))
- **npm**: `v9.0.0` or higher (bundled with Node.js)
- **Sarvam AI API Key**: Required for STT, translation, and diarization ([Get API Key](https://dashboard.sarvam.ai))
- **Groq API Key** *(Optional)*: Recommended for high-speed clinical summary generation ([Get API Key](https://console.groq.com))
- *(Optional)* **Python**: `3.10+` if running the hybrid diarization module or FastAPI backend
---
## Quick Start & Installation
### 1. Clone the Repository
```bash
git clone https://gitea.aiindia.ai/AyushS/Doctor_Patient_Summary.git
cd Doctor_Patient_Summary
```
### 2. Configure Environment Variables
Copy the example configuration file and enter your API keys:
```bash
cp .env.example .env
```
Open `.env` in any text editor and configure your credentials:
```env
# Sarvam AI API Key (Required)
SARVAM_API_KEY=sk_your_sarvam_api_key_here
# Sarvam Chat Model (Default: sarvam-105b-conversations)
SARVAM_CHAT_MODEL=sarvam-105b-conversations
# Groq API Key (Recommended for fast clinical summary generation)
GROQ_API_KEY=gsk_your_groq_api_key_here
# Server Port (Default: 3000)
PORT=3000
```
### 3. Install Dependencies
Install the required Node.js packages:
```bash
npm install
```
### 4. Start the Application
Start the server:
```bash
# Production mode
npm start
# Development mode (with live reload)
npm run dev
```
### 5. Access the Web Application
Open your browser and navigate to:
```
http://localhost:3000
```
---
## Audio Format Requirements
When streaming or uploading audio directly:
- **Encoding**: 16-bit linear PCM (`audio/wav`)
- **Sample Rate**: 16,000 Hz (16 kHz)
- **Channels**: 1 (Mono)
- The frontend microphone capture automatically records and downsamples to 16kHz mono PCM before sending to the backend.
---
## API Endpoints Reference
### HTTP REST Endpoints
| Method | Endpoint | Description |
|---|---|---|
| `GET` | `/api/health` | Healthcheck endpoint reporting service status. |
| `POST` | `/api/transcribe` | Batch transcription with Sarvam native speaker diarization. |
| `POST` | `/api/transcribe-chunk` | Transcribes audio chunks with automatic English translation. |
| `POST` | `/api/hybrid-transcribe` | Hybrid acoustic + Sarvam STT transcription pipeline. |
| `POST` | `/api/diarize` | NLP-based speaker role classification (Doctor vs. Patient). |
| `POST` | `/api/summary` | Generates a structured clinical SOAP summary from transcripts. |
### WebSocket Endpoint
| Endpoint | Protocol | Description |
|---|---|---|
| `/ws/transcribe` | `WSS / WS` | Full-duplex real-time audio streaming proxy to Sarvam AI. |
---
## How It Works
1. **Audio Ingestion**:
- The user records live via the microphone or uploads an audio file of a doctor-patient conversation.
2. **Translation & Diarization**:
- Speech chunks are transcribed by Sarvam AI in `translate` mode, ensuring Marathi, Hindi, or English speech is accurately rendered in English.
- Speaker diarization partitions the audio timeline into individual speaker turns.
3. **Role Classification**:
- The conversational turns are analyzed by an LLM prompt trained to identify medical inquiries and clinical advice from patient complaints.
4. **Clinical SOAP Summary**:
- The complete diarized dialogue is passed to the clinical summarization engine, producing structured records ready for medical documentation.
---
## Troubleshooting
- **Microphone Access Denied**: Ensure browser permissions allow microphone input for `http://localhost:3000`.
- **401 Unauthorized from Sarvam**: Verify that `SARVAM_API_KEY` in `.env` is valid and active.
- **Summary Generation Timeout**: If Groq is not configured, ensure `SARVAM_API_KEY` has quota for Sarvam chat completions. Adding a `GROQ_API_KEY` provides ultra-fast summary fallbacks.
---
## License
This project is licensed under the MIT License.
Binary file not shown.
+15
View File
@@ -0,0 +1,15 @@
# ====================================================================
# Backend Python API - Environment Configuration
# ====================================================================
# Sarvam AI API Key (Required)
# Get your key from: https://dashboard.sarvam.ai
SARVAM_API_KEY=your_sarvam_api_key_here
# Sarvam Chat Model (Default: sarvam-105b)
SARVAM_CHAT_MODEL=sarvam-105b
# Optional: Groq LLM API Key (Fallback for fast summary)
# Get your key from: https://console.groq.com
GROQ_API_KEY=your_groq_api_key_here
GROQ_MODEL=llama-3.3-70b-versatile
+220
View File
@@ -0,0 +1,220 @@
import os
from pathlib import Path
# ── Optional Heavy ML Imports (GPU/ML packages) ────────────────────────────────
# Pyannote, torch, speechbrain हे optional आहेत.
# Install नसल्यास server crash होत नाही — gracefully LLM fallback वापरतो.
try:
import torch # type: ignore
import torchaudio # type: ignore
import numpy as np # type: ignore
_TORCH_AVAILABLE = True
except ImportError:
_TORCH_AVAILABLE = False
print("[diarization_pipeline] WARNING: torch/torchaudio not installed. Acoustic diarization disabled.")
try:
from pyannote.audio import Pipeline as PyannotePipeline # type: ignore
_PYANNOTE_AVAILABLE = True
except ImportError:
_PYANNOTE_AVAILABLE = False
print("[diarization_pipeline] WARNING: pyannote.audio not installed. Acoustic diarization disabled.")
try:
from speechbrain.pretrained import EncoderClassifier # type: ignore
_SPEECHBRAIN_AVAILABLE = True
except ImportError:
_SPEECHBRAIN_AVAILABLE = False
print("[diarization_pipeline] WARNING: speechbrain not installed. Speaker embeddings disabled.")
class AcousticDiarizer:
def __init__(self, hf_token: str = None):
self.hf_token = hf_token or os.getenv("HF_TOKEN")
if not self.hf_token:
print("WARNING: HF_TOKEN not set. Pyannote may fail if models are not cached.")
# 1. Load Pyannote Diarization Pipeline
self.diarization_pipeline = None
if _PYANNOTE_AVAILABLE and _TORCH_AVAILABLE:
try:
self.diarization_pipeline = PyannotePipeline.from_pretrained(
"pyannote/speaker-diarization-3.1",
use_auth_token=self.hf_token
)
# Move to GPU if available
if torch.cuda.is_available():
self.diarization_pipeline.to(torch.device("cuda"))
except Exception as e:
print(f"Failed to load Pyannote Diarization: {e}")
self.diarization_pipeline = None
else:
print("[AcousticDiarizer] Pyannote/torch unavailable — using LLM fallback.")
# 2. Load SpeechBrain ECAPA-TDNN for Speaker Embeddings (Role Assignment)
self.embedding_model = None
if _SPEECHBRAIN_AVAILABLE and _TORCH_AVAILABLE:
try:
self.embedding_model = EncoderClassifier.from_hparams(
source="speechbrain/spkrec-ecapa-voxceleb",
savedir="pretrained_models/spkrec-ecapa-voxceleb",
run_opts={"device": "cuda" if torch.cuda.is_available() else "cpu"}
)
except Exception as e:
print(f"Failed to load SpeechBrain: {e}")
self.embedding_model = None
else:
print("[AcousticDiarizer] SpeechBrain unavailable — speaker embeddings disabled.")
def run_diarization(self, audio_path: str):
"""Runs Pyannote diarization and returns list of segments."""
if not self.diarization_pipeline:
raise RuntimeError("Diarization pipeline is not initialized.")
# Pyannote expects 16kHz mono. It handles resampling internally, but best to ensure.
diarization = self.diarization_pipeline(audio_path)
segments = []
for turn, _, speaker in diarization.itertracks(yield_label=True):
segments.append({
"start": turn.start,
"end": turn.end,
"speaker_id": speaker
})
return segments
def extract_embedding(self, audio_path: str, start: float, end: float):
"""Extracts speaker embedding for a specific segment."""
if not self.embedding_model or not _TORCH_AVAILABLE:
return None
signal, fs = torchaudio.load(audio_path)
# Resample to 16kHz if necessary
if fs != 16000:
resampler = torchaudio.transforms.Resample(fs, 16000)
signal = resampler(signal)
fs = 16000
# Ensure mono
if signal.shape[0] > 1:
signal = signal.mean(dim=0, keepdim=True)
start_sample = int(start * fs)
end_sample = int(end * fs)
segment = signal[:, start_sample:end_sample]
# BUG 15 FIX: Very short segments पण gracefully handle करा
min_samples = int(fs * 0.5) # 0.5 seconds minimum
if segment.shape[1] < min_samples:
return None
with torch.no_grad():
embeddings = self.embedding_model.encode_batch(segment)
embeddings = embeddings.squeeze().cpu().numpy()
return embeddings
def assign_roles_heuristically(self, segments: list) -> dict:
"""
Assigns 'Doctor' and 'Patient' roles based on conversational dynamics.
Heuristics:
1. Doctor usually initiates the conversation or speaks first.
2. Doctor usually has more short turns (asking questions).
3. Patient usually has longer narrative turns (describing symptoms).
"""
if not segments:
return {}
speaker_stats = {}
for seg in segments:
spk = seg["speaker_id"]
dur = seg["end"] - seg["start"]
if spk not in speaker_stats:
speaker_stats[spk] = {"count": 0, "total_duration": 0, "first_appearance": seg["start"]}
speaker_stats[spk]["count"] += 1
speaker_stats[spk]["total_duration"] += dur
if not speaker_stats:
return {}
# If only one speaker detected
if len(speaker_stats) == 1:
spk = list(speaker_stats.keys())[0]
return {spk: "Doctor"} # Fallback
# Sort speakers by first appearance
speakers = sorted(speaker_stats.keys(), key=lambda x: speaker_stats[x]["first_appearance"])
# Sort speakers by number of turns
speakers_by_turns = sorted(speaker_stats.keys(), key=lambda x: speaker_stats[x]["count"], reverse=True)
mapping = {}
# Primary Heuristic: The speaker with the most back-and-forth turns is usually the doctor
# Secondary: Doctor usually speaks first.
doctor_candidate = speakers_by_turns[0]
mapping[doctor_candidate] = "Doctor"
# BUG 6 FIX: Comment म्हणतो 'Patient_{i}' पण code सगळ्यांना 'Patient' करतो
# Multiple speakers असल्यास योग्य index द्या
non_doctor_speakers = [s for s in speaker_stats.keys() if s != doctor_candidate]
for i, spk in enumerate(non_doctor_speakers):
if len(non_doctor_speakers) == 1:
mapping[spk] = "Patient" # एकटाच Patient असल्यास plain "Patient"
else:
mapping[spk] = f"Patient_{i + 1}" # Patient_1, Patient_2, ... (Relative etc.)
return mapping
def align_stt_with_diarization(self, stt_words: list, diarization_segments: list, role_mapping: dict):
"""
Aligns STT word/segment timestamps with the acoustic diarization segments.
stt_words: [{'text': 'hello', 'start': 0.5, 'end': 1.0}, ...]
"""
aligned_transcript = []
for stt in stt_words:
midpoint = (stt["start"] + stt["end"]) / 2.0
# Find the diarization segment that covers this midpoint
assigned_speaker = "Unknown"
assigned_role = "Unknown"
for d_seg in diarization_segments:
if d_seg["start"] <= midpoint <= d_seg["end"]:
assigned_speaker = d_seg["speaker_id"]
assigned_role = role_mapping.get(assigned_speaker, "Unknown")
break
aligned_transcript.append({
"text": stt["text"],
"start": stt["start"],
"end": stt["end"],
"speaker": assigned_speaker,
"role": assigned_role
})
# Group contiguous words by role
final_blocks = []
current_role = None
current_text = []
for item in aligned_transcript:
if item["role"] != current_role:
if current_text:
final_blocks.append(f"{current_role}: {' '.join(current_text)}")
current_role = item["role"]
current_text = [item["text"]]
else:
current_text.append(item["text"])
if current_text:
final_blocks.append(f"{current_role}: {' '.join(current_text)}")
return "\n\n".join(final_blocks)
+334
View File
@@ -0,0 +1,334 @@
"""
AI Medical Assistant — FastAPI backend
Uses starlette directly to avoid pydantic_core binary incompatibility on Python 3.14
"""
import os, sys, json, re, struct, asyncio, base64
from pathlib import Path
# ── Patch sys.path (optional local vendored packages) ────────────────────────
_root = Path(__file__).resolve().parent.parent
_pkgs = str(_root / "pkgs")
_src = str(_root / "sarvamai_src")
if os.path.isdir(_pkgs) and _pkgs not in sys.path:
sys.path.insert(0, _pkgs)
if os.path.isdir(_src) and _src not in sys.path:
sys.path.append(_src)
# ── Imports ───────────────────────────────────────────────────────────────────
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
from starlette.routing import Route, WebSocketRoute, Mount
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.staticfiles import StaticFiles
from starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketState
import httpx
import websockets as ws_lib
from dotenv import load_dotenv
load_dotenv()
SARVAM_API_KEY = os.getenv("SARVAM_API_KEY", "")
SARVAM_CHAT_MODEL = os.getenv("SARVAM_CHAT_MODEL", "sarvam-105b")
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
GROQ_MODEL = os.getenv("GROQ_MODEL", "llama-3.3-70b-versatile")
TEMP_DIR = Path("temp_audio")
TEMP_DIR.mkdir(exist_ok=True)
# ── Helpers ───────────────────────────────────────────────────────────────────
def parse_wav(buf: bytes):
offset, sr, nc, bps = 12, 16000, 1, 16
do, dl = 44, len(buf) - 44
while offset + 8 <= len(buf):
cid = buf[offset:offset+4]
sz = struct.unpack('<I', buf[offset+4:offset+8])[0]
if cid == b'fmt ':
nc = struct.unpack('<H', buf[offset+10:offset+12])[0]
sr = struct.unpack('<I', buf[offset+12:offset+16])[0]
bps = struct.unpack('<H', buf[offset+22:offset+24])[0]
elif cid == b'data':
do, dl = offset + 8, sz; break
offset += 8 + sz
return do, dl, sr, nc, bps
def make_wav(pcm: bytes, sr, nc, bps) -> bytes:
dl = len(pcm); h = bytearray(44)
h[0:4]=b'RIFF'; struct.pack_into('<I',h,4,36+dl)
h[8:12]=b'WAVE'; h[12:16]=b'fmt '
struct.pack_into('<I',h,16,16); struct.pack_into('<H',h,20,1)
struct.pack_into('<H',h,22,nc); struct.pack_into('<I',h,24,sr)
struct.pack_into('<I',h,28,sr*nc*bps//8); struct.pack_into('<H',h,32,nc*bps//8)
struct.pack_into('<H',h,34,bps); h[36:40]=b'data'; struct.pack_into('<I',h,40,dl)
return bytes(h) + pcm
def chunk_wav(wav: bytes, chunk_sec=24):
do, dl, sr, nc, bps = parse_wav(wav)
bps_rate = sr * nc * (bps // 8)
cb = bps_rate * chunk_sec
if dl <= cb or bps_rate == 0: return [wav]
pcm = wav[do:do+dl]
return [make_wav(pcm[i:i+cb], sr, nc, bps) for i in range(0, len(pcm), cb)]
def clean_text(text: str) -> str:
if not text: return text
text = re.sub(r'\b(\w+)(\s+\1)+\b', r'\1', text, flags=re.IGNORECASE|re.UNICODE)
for n in range(8, 1, -1):
text = re.sub(r'((?:\S+\s+){'+str(n-1)+r'}\S+)(\s+\1)+',
r'\1', text, flags=re.IGNORECASE|re.UNICODE)
sents = re.split(r'(?<=[.!?।])\s+', text.strip())
seen, seen_n = [], []
for s in sents:
s = s.strip()
if not s: continue
n = re.sub(r'\s+',' ', s.lower().strip())
dup = any(n==p or (len(min(n,p,key=len))>10 and
min(n,p,key=len) in max(n,p,key=len)) for p in seen_n)
if not dup: seen.append(s); seen_n.append(n)
return ' '.join(seen)
async def ensure_english_text(client: httpx.AsyncClient, text: str) -> str:
if not text or not re.search(r'[\u0900-\u097F]', text):
return text
if not SARVAM_API_KEY:
return text
try:
resp = await client.post(
"https://api.sarvam.ai/translate",
headers={"api-subscription-key": SARVAM_API_KEY, "Content-Type": "application/json"},
json={
"input": text,
"source_language_code": "auto",
"target_language_code": "en-IN",
"mode": "formal",
"model": "mayura:v1"
},
timeout=15.0
)
if resp.is_success:
t = resp.json().get("translated_text", "")
if t and t.strip():
return t.strip()
except Exception as e:
print(f"[ensure_english_text] {e}")
return text
# ── Route Handlers ────────────────────────────────────────────────────────────
async def health(request: Request):
return JSONResponse({"ok": True, "ready": bool(SARVAM_API_KEY),
"sarvamKeyConfigured": bool(SARVAM_API_KEY)})
async def transcribe(request: Request):
if not SARVAM_API_KEY:
return JSONResponse({"error": "SARVAM_API_KEY not configured."}, status_code=500)
audio_bytes = b""; lang = "unknown"
ct = request.headers.get("content-type", "")
if "multipart" in ct:
form = await request.form()
f = form.get("file")
if f: audio_bytes = await f.read()
lang = form.get("language_code", "unknown") or "unknown"
else:
try:
body = await request.json()
if body.get("audio_b64"):
audio_bytes = base64.b64decode(body["audio_b64"])
lang = body.get("language_code") or "unknown"
except: pass
if not audio_bytes:
return JSONResponse({"error": "No audio provided."}, status_code=400)
if lang == "auto": lang = "unknown"
chunks = chunk_wav(audio_bytes)
parts, detected = [], lang
headers = {"api-subscription-key": SARVAM_API_KEY}
async with httpx.AsyncClient(timeout=90) as client:
for i, chunk in enumerate(chunks):
resp = await client.post(
"https://api.sarvam.ai/speech-to-text",
headers=headers,
files={"file": (f"chunk_{i}.wav", chunk, "audio/wav")},
data={"model":"saaras:v4","mode":"translate",
"language_code":lang,"with_timestamps":"false"},
)
if not resp.is_success:
return JSONResponse({"error": f"Sarvam STT error: {resp.text[:300]}"},
status_code=resp.status_code)
d = resp.json()
t = (d.get("transcript") or "").strip()
if t: parts.append(t)
if d.get("language_code") and detected == "unknown":
detected = d["language_code"]
raw_transcript = clean_text(" ".join(parts).strip())
transcript = await ensure_english_text(client, raw_transcript)
return JSONResponse({"success": True, "transcript": transcript, "language": "en-IN"})
async def summary(request: Request):
if not SARVAM_API_KEY:
return JSONResponse({"error": "SARVAM_API_KEY not configured in .env"}, status_code=500)
body = await request.json()
transcript = (body.get("transcript") or "").strip()
if not transcript:
return JSONResponse({"error": "transcript is empty"}, status_code=400)
PROMPT = (
"You are a clinical documentation assistant for Indian hospitals. "
"Read the doctor-patient conversation below (may be Marathi, Hindi, English, or code-mixed). "
"Extract clinical information and return ONLY a valid JSON object with exactly these keys:\n"
"- chief_complaint: main reason for visit (string)\n"
"- symptoms: list of symptoms mentioned (array of strings)\n"
"- history: relevant past medical history (string)\n"
"- assessment: doctor's diagnosis or assessment (string)\n"
"- plan: prescription, tests, or treatment steps (array of strings)\n\n"
"Rules:\n"
"1. Output ONLY raw JSON — no markdown, no explanation, no extra text.\n"
"2. Write 'Not mentioned' for any field not found in the conversation.\n"
"3. Keep the original language of the content (do not translate).\n"
"4. Do NOT give medical advice — only extract what was said."
)
async with httpx.AsyncClient(timeout=60) as client:
resp = await client.post(
"https://api.sarvam.ai/v2/chat/completions",
headers={
"Content-Type": "application/json",
"api-subscription-key": SARVAM_API_KEY,
},
json={
"model": "sarvam-105b",
"temperature": 0.1,
"max_tokens": 1000,
"response_format": {"type": "json_object"},
"messages": [
{"role": "system", "content": PROMPT},
{"role": "user", "content": transcript},
],
},
)
if not resp.is_success:
return JSONResponse(
{"error": f"Sarvam API error: {resp.text[:400]}"},
status_code=resp.status_code
)
content = resp.json().get("choices",[{}])[0].get("message",{}).get("content","")
try:
cleaned = re.sub(r'^```json|^```|```$','',content.strip(),flags=re.MULTILINE).strip()
parsed = json.loads(cleaned)
except:
parsed = {"raw_text": content}
return JSONResponse({"summary": parsed})
async def ws_transcribe(websocket: WebSocket):
await websocket.accept()
if not SARVAM_API_KEY:
await websocket.send_json({"event":"error","message":"SARVAM_API_KEY not configured."})
await websocket.close(); return
lang = websocket.query_params.get("language_code","auto")
if lang == "unknown":
lang = "auto"
sarvam_url = (
"wss://api.sarvam.ai/speech-to-text-realtime/ws"
f"?language_code={lang}"
"&model=saaras:v3-realtime"
"&encoding=linear16&sample_rate=16000"
"&stream_type=balanced&mode=translate"
)
try:
async with ws_lib.connect(
sarvam_url,
additional_headers={"api-subscription-key": SARVAM_API_KEY},
ping_interval=20, ping_timeout=20,
) as sarvam_ws:
async def b2s():
try:
while True:
msg = await websocket.receive()
if msg["type"] == "websocket.disconnect": break
if "text" in msg and msg["text"]:
d = json.loads(msg["text"])
if d.get("event") in ("end","stop"):
await sarvam_ws.send(json.dumps({"event":"end"})); break
elif d.get("event") == "audio_input":
await sarvam_ws.send(json.dumps(d))
except Exception as e: print(f"[b2s] {e}")
finally:
try: await sarvam_ws.send(json.dumps({"event":"end"}))
except: pass
async def s2b():
try:
async with httpx.AsyncClient(timeout=10.0) as http_client:
async for raw in sarvam_ws:
if websocket.client_state != WebSocketState.CONNECTED: break
if isinstance(raw,(bytes,bytearray)): continue
try: p = json.loads(raw)
except: continue
evt = p.get("event","")
if evt in ("transcript.partial","transcript.final"):
text_val = p.get("text","")
if evt == "transcript.final" and text_val:
text_val = await ensure_english_text(http_client, text_val)
await websocket.send_json({
"event": evt,
"text": text_val,
"language": "en-IN",
})
elif evt == "error":
await websocket.send_json({
"event":"error",
"message":p.get("message",""),
"code":p.get("code",""),
})
except Exception as e: print(f"[s2b] {e}")
finally:
try: await websocket.send_json({"event":"done"})
except: pass
await asyncio.gather(b2s(), s2b())
except Exception as e:
try: await websocket.send_json({"event":"error","message":str(e)})
except: pass
finally:
try: await websocket.close()
except: pass
# ── App ───────────────────────────────────────────────────────────────────────
static_dir = _root / "public"
routes = [
Route("/api/health", health, methods=["GET"]),
Route("/health", health, methods=["GET"]),
Route("/api/transcribe", transcribe, methods=["POST"]),
Route("/transcribe", transcribe, methods=["POST"]),
Route("/api/summary", summary, methods=["POST"]),
WebSocketRoute("/ws/transcribe", ws_transcribe),
]
if static_dir.exists():
routes.append(Mount("/", app=StaticFiles(directory=str(static_dir), html=True), name="static"))
app = Starlette(
routes=routes,
middleware=[Middleware(CORSMiddleware,
allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]
)],
)
+12
View File
@@ -0,0 +1,12 @@
fastapi==0.111.0
uvicorn==0.30.1
python-multipart==0.0.9
httpx==0.27.0
python-dotenv==1.0.1
pydantic==2.7.4
pyannote.audio==3.1.1
speechbrain==0.5.16
torchaudio>=2.0.0
torch>=2.0.0
scipy
numpy
BIN
View File
Binary file not shown.
+29
View File
@@ -0,0 +1,29 @@
import asyncio
import httpx
import os
import base64
from dotenv import load_dotenv
load_dotenv()
SARVAM_API_KEY = os.getenv("SARVAM_API_KEY", "")
async def test():
with open("test.wav", "rb") as f:
audio_data = f.read()
async with httpx.AsyncClient(timeout=60) as client:
submit_resp = await client.post(
"https://api.sarvam.ai/speech-to-text",
headers={"api-subscription-key": SARVAM_API_KEY},
files={"file": ("test.wav", audio_data, "audio/wav")},
data={
"model": "saaras:v4",
"mode": "codemix",
"with_timestamps": "true",
"with_diarization": "true",
}
)
print(submit_resp.status_code)
print(submit_resp.json())
asyncio.run(test())
+1
View File
@@ -0,0 +1 @@
+1036
View File
File diff suppressed because one or more lines are too long
+541
View File
@@ -0,0 +1,541 @@
const fs = require('fs');
const path = require('path');
const DATA_DIR = path.join(__dirname, 'data');
const AUDIO_DIR = path.join(DATA_DIR, 'audio');
const DB_FILE = path.join(DATA_DIR, 'db.json');
// Ensure directories exist
if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
if (!fs.existsSync(AUDIO_DIR)) fs.mkdirSync(AUDIO_DIR, { recursive: true });
const INITIAL_DB = {
doctors: [
{
doctor_id: "DOC-001",
name: "Dr. Sharma",
department: "Cardiology / Oncology",
specialization: "Clinical Specialist",
phone: "+91 98230 11223",
created_at: "2026-01-01T00:00:00.000Z"
},
{
doctor_id: "DOC-002",
name: "Dr. Mehta",
department: "Internal Medicine",
specialization: "General Physician",
phone: "+91 98230 44556",
created_at: "2026-01-10T00:00:00.000Z"
},
{
doctor_id: "DOC-003",
name: "Dr. Patil",
department: "Surgical Oncology",
specialization: "Surgeon",
phone: "+91 98230 77889",
created_at: "2026-02-01T00:00:00.000Z"
}
],
patients: [
{
patient_id: "PT-2026-00124",
name: "Sanika Gurav",
age: 34,
gender: "Female",
phone: "+91 98765 43210",
created_at: "2026-08-15T09:00:00.000Z"
},
{
patient_id: "PT-2026-00125",
name: "Rahul Patil",
age: 42,
gender: "Male",
phone: "+91 98765 88990",
created_at: "2026-08-20T10:30:00.000Z"
},
{
patient_id: "PT-2026-00126",
name: "Amit Singh",
age: 51,
gender: "Male",
phone: "+91 98765 11223",
created_at: "2026-08-22T11:15:00.000Z"
},
{
patient_id: "PT-2026-00127",
name: "Priya Reddy",
age: 29,
gender: "Female",
phone: "+91 98765 33445",
created_at: "2026-08-25T14:00:00.000Z"
},
{
patient_id: "PT-2026-00128",
name: "Vikram Kumar",
age: 63,
gender: "Male",
phone: "+91 98765 55667",
created_at: "2026-08-28T16:45:00.000Z"
}
],
consultations: [
{
consultation_id: "CONS-2026-000001",
patient_id: "PT-2026-00124",
patient_name: "Sanika Gurav",
doctor_id: "DOC-001",
doctor_name: "Dr. Sharma",
consultation_date: "2026-09-01",
time_formatted: "10:30 AM",
duration_seconds: 755,
duration_formatted: "12 min 35 sec",
audio_file: null,
language: "mr-IN",
transcript: "**Doctor:** नमस्कार. या, बसा. तुम्हाला नेमका काय त्रास होतो आहे?\n\n**Patient:** नमस्कार डॉक्टर. मला गेल्या तीन दिवसांपासून पोटात दुखत आहे आणि पोटावरच्या surgery च्या जखमेजवळून थोडंसं पाणी येत आहे.\n\n**Doctor:** ठीक आहे. तुमची surgery कधी झाली होती?\n\n**Patient:** साधारण दोन आठवड्यांपूर्वी appendix ची laparoscopic surgery झाली होती.\n\n**Doctor:** जखमेतून येणारं पाणी कसं आहे? पारदर्शक आहे की पिवळसर? त्याला वास येतो का?\n\n**Patient:** सुरुवातीला थोडंसं पारदर्शक होतं, पण कालपासून पिवळसर दिसत आहे. हलका वाससुद्धा येतो.\n\n**Doctor:** जखमेच्या आसपास लालसरपणा, सूज किंवा जास्त गरमपणा जाणवतो का?\n\n**Patient:** हो डॉक्टर, थोडी सूज आली आहे आणि त्या जागेला स्पर्श केला की दुखतं.\n\n**Doctor:** ताप येतो आहे का?\n\n**Patient:** काल रात्री 101 डिग्रीपर्यंत ताप होता. Paracetamol घेतल्यानंतर कमी झाला.\n\n**Doctor:** उलटी, मळमळ किंवा भूक कमी लागणे असे काही आहे का?",
speaker_segments: [
{ speaker: "Doctor", text: "नमस्कार. या, बसा. तुम्हाला नेमका काय त्रास होतो आहे?" },
{ speaker: "Patient", text: "नमस्कार डॉक्टर. मला गेल्या तीन दिवसांपासून पोटात दुखत आहे आणि पोटावरच्या surgery च्या जखमेजवळून थोडंसं पाणी येत आहे." },
{ speaker: "Doctor", text: "ठीक आहे. तुमची surgery कधी झाली होती?" },
{ speaker: "Patient", text: "साधारण दोन आठवड्यांपूर्वी appendix ची laparoscopic surgery झाली होती." },
{ speaker: "Doctor", text: "जखमेतून येणारं पाणी कसं आहे? पारदर्शक आहे की पिवळसर? त्याला वास येतो का?" },
{ speaker: "Patient", text: "सुरुवातीला थोडंसं पारदर्शक होतं, पण कालपासून पिवळसर दिसत आहे. हलका वाससुद्धा येतो." },
{ speaker: "Doctor", text: "जखमेच्या आसपास लालसरपणा, सूज किंवा जास्त गरमपणा जाणवतो का?" },
{ speaker: "Patient", text: "हो डॉक्टर, थोडी सूज आली आहे आणि त्या जागेला स्पर्श केला की दुखतं." },
{ speaker: "Doctor", text: "ताप येतो आहे का?" },
{ speaker: "Patient", text: "काल रात्री 101 डिग्रीपर्यंत ताप होता. Paracetamol घेतल्यानंतर कमी झाला." },
{ speaker: "Doctor", text: "उलटी, मळमळ किंवा भूक कमी लागणे असे काही आहे का?" }
],
summary: {
chief_complaint: "Abdominal pain and discharge near surgery site for 3 days",
symptoms: ["Abdominal pain", "Mild fever (101°F)", "Yellowish discharge with mild odor", "Tenderness and localized swelling"],
history: "Laparoscopic appendectomy performed 2 weeks ago",
assessment: "Post-operative surgical site superficial seroma / mild wound infection",
recommendation: "Wound cleaning and dressing, oral antibiotics course, follow-up in 3 days"
},
status: "Completed",
created_at: "2026-09-01T10:30:00.000Z",
updated_at: "2026-09-01T10:45:00.000Z"
},
{
consultation_id: "CONS-2026-000002",
patient_id: "PT-2026-00125",
patient_name: "Rahul Patil",
doctor_id: "DOC-001",
doctor_name: "Dr. Sharma",
consultation_date: "2026-08-31",
time_formatted: "09:15 AM",
duration_seconds: 500,
duration_formatted: "08 min 20 sec",
audio_file: null,
language: "mr-IN",
transcript: "**Doctor:** राहुलजी, आज कसे आहात? BP च्या गोळ्या नियमित घेताय ना?\n\n**Patient:** हो डॉक्टर, पण कालपासून छातीत किंचित जडपणा वाटतोय.",
speaker_segments: [
{ speaker: "Doctor", text: "राहुलजी, आज कसे आहात? BP च्या गोळ्या नियमित घेताय ना?" },
{ speaker: "Patient", text: "हो डॉक्टर, पण कालपासून छातीत किंचित जडपणा वाटतोय." }
],
summary: {
chief_complaint: "Mild chest heaviness and hypertension review",
symptoms: ["Chest heaviness", "Mild fatigue"],
history: "Hypertension for 5 years on Telmisartan 40mg",
assessment: "Essential Hypertension with exertional discomfort",
recommendation: "ECG, 2D Echo recommended, continue regular anti-hypertensives"
},
status: "Processing",
created_at: "2026-08-31T09:15:00.000Z",
updated_at: "2026-08-31T09:25:00.000Z"
},
{
consultation_id: "CONS-2026-000003",
patient_id: "PT-2026-00126",
patient_name: "Amit Singh",
doctor_id: "DOC-001",
doctor_name: "Dr. Sharma",
consultation_date: "2026-08-28",
time_formatted: "04:40 PM",
duration_seconds: 910,
duration_formatted: "15 min 10 sec",
audio_file: null,
language: "hi-IN",
transcript: "**Doctor:** अमितजी, आपकी शुगर रिपोर्ट देखी। फास्टिंग 140 आई है।\n\n**Patient:** जी डॉक्टर साहब, मीठा कम कर दिया है फिर भी थोड़ा ज्यादा है।",
speaker_segments: [
{ speaker: "Doctor", text: "अमितजी, आपकी शुगर रिपोर्ट देखी। फास्टिंग 140 आई है।" },
{ speaker: "Patient", text: "जी डॉक्टर साहब, मीठा कम कर दिया है फिर भी थोड़ा ज्यादा है।" }
],
summary: {
chief_complaint: "Diabetes follow up and elevated fasting blood glucose",
symptoms: ["Increased thirst", "Occasional weakness"],
history: "Type 2 Diabetes Mellitus for 3 years",
assessment: "Uncontrolled Fasting Hyperglycemia",
recommendation: "Adjust Metformin dosage to 500mg BD, dietary counseling, HbA1c test"
},
status: "Completed",
created_at: "2026-08-28T16:40:00.000Z",
updated_at: "2026-08-28T17:00:00.000Z"
},
{
consultation_id: "CONS-2026-000004",
patient_id: "PT-2026-00127",
patient_name: "Priya Reddy",
doctor_id: "DOC-002",
doctor_name: "Dr. Mehta",
consultation_date: "2026-08-25",
time_formatted: "11:20 AM",
duration_seconds: 605,
duration_formatted: "10 min 05 sec",
audio_file: null,
language: "en-IN",
transcript: "**Doctor:** Good morning Priya. Are you still experiencing seasonal allergies and throat irritation?\n\n**Patient:** Yes doctor, especially in the mornings with dry coughing.",
speaker_segments: [
{ speaker: "Doctor", text: "Good morning Priya. Are you still experiencing seasonal allergies and throat irritation?" },
{ speaker: "Patient", text: "Yes doctor, especially in the mornings with dry coughing." }
],
summary: {
chief_complaint: "Morning allergic rhinitis and dry cough",
symptoms: ["Sneezing", "Dry cough", "Throat itchiness"],
history: "Seasonal pollen allergies",
assessment: "Allergic Rhinitis with Pharyngeal irritation",
recommendation: "Antihistamine (Levocetirizine 5mg) at night, saline nasal spray, steam inhalation"
},
status: "Doctor Reviewed",
created_at: "2026-08-25T11:20:00.000Z",
updated_at: "2026-08-25T11:35:00.000Z"
},
{
consultation_id: "CONS-2026-000005",
patient_id: "PT-2026-00128",
patient_name: "Vikram Kumar",
doctor_id: "DOC-001",
doctor_name: "Dr. Sharma",
consultation_date: "2026-08-20",
time_formatted: "03:30 PM",
duration_seconds: 585,
duration_formatted: "09 min 45 sec",
audio_file: null,
language: "mr-IN",
transcript: "**Doctor:** विक्रमजी, गुडघ्यांचे दुखणे कसे आहे आता?\n\n**Patient:** फिजिओथेरपीनंतर थोडा आराम आहे डॉक्टर, पण जिने चढताना त्रास होतो.",
speaker_segments: [
{ speaker: "Doctor", text: "विक्रमजी, गुडघ्यांचे दुखणे कसे आहे आता?" },
{ speaker: "Patient", text: "फिजिओथेरपीनंतर थोडा आराम आहे डॉक्टर, पण जिने चढताना त्रास होतो." }
],
summary: {
chief_complaint: "Bilateral knee osteoarthritis follow-up",
symptoms: ["Joint stiffness", "Pain while climbing stairs"],
history: "Osteoarthritis for 4 years, post knee physiotherapy",
assessment: "Bilateral Knee Osteoarthritis Grade II",
recommendation: "Continue quadriceps strengthening exercises, Calcium + Vit D3 supplements"
},
status: "Completed",
created_at: "2026-08-20T15:30:00.000Z",
updated_at: "2026-08-20T15:45:00.000Z"
},
{
consultation_id: "CONS-2026-000006",
patient_id: "PT-2026-00124",
patient_name: "Sanika Gurav",
doctor_id: "DOC-001",
doctor_name: "Dr. Sharma",
consultation_date: "2026-08-28",
time_formatted: "11:00 AM",
duration_seconds: 480,
duration_formatted: "08 min 00 sec",
audio_file: null,
language: "mr-IN",
transcript: "**Doctor:** सानिकाजी, शस्त्रक्रियेनंतरची पहिली तपासणी करूया.\n\n**Patient:** हो डॉक्टर, जखम कोरडी वाटत आहे.",
speaker_segments: [
{ speaker: "Doctor", text: "सानिकाजी, शस्त्रक्रियेनंतरची पहिली तपासणी करूया." },
{ speaker: "Patient", text: "हो डॉक्टर, जखम कोरडी वाटत आहे." }
],
summary: {
chief_complaint: "Post-op laparoscopic appendectomy 1-week follow-up",
symptoms: ["Mild incision site discomfort"],
history: "Recent appendectomy",
assessment: "Healing surgical wound",
recommendation: "Keep dressing clean and dry, return if fever or pain occurs"
},
status: "Completed",
created_at: "2026-08-28T11:00:00.000Z",
updated_at: "2026-08-28T11:15:00.000Z"
}
]
};
function readDB() {
try {
if (!fs.existsSync(DB_FILE)) {
writeDB(INITIAL_DB);
return INITIAL_DB;
}
const data = fs.readFileSync(DB_FILE, 'utf8');
return JSON.parse(data);
} catch (err) {
console.error('Error reading DB, resetting to initial:', err);
writeDB(INITIAL_DB);
return INITIAL_DB;
}
}
function writeDB(data) {
try {
fs.writeFileSync(DB_FILE, JSON.stringify(data, null, 2), 'utf8');
} catch (err) {
console.error('Error writing to DB file:', err);
}
}
// Ensure DB is initialized
readDB();
module.exports = {
AUDIO_DIR,
// ── Patients ──
getPatients: (search = '') => {
const db = readDB();
if (!search) return db.patients;
const s = search.toLowerCase();
return db.patients.filter(p =>
p.name.toLowerCase().includes(s) ||
p.patient_id.toLowerCase().includes(s) ||
(p.phone && p.phone.includes(s))
);
},
getPatientById: (patient_id) => {
const db = readDB();
return db.patients.find(p => p.patient_id === patient_id) || null;
},
createPatient: (patientData) => {
const db = readDB();
// BUG 4 FIX: count-based ID नाही — delete नंतर collision होते
// max existing ID + 1 वापरा
const existingNums = db.patients.map(p => {
const parts = p.patient_id.split('-');
return parseInt(parts[parts.length - 1]) || 0;
});
const nextNum = (existingNums.length > 0 ? Math.max(...existingNums) : 0) + 1;
const newId = patientData.patient_id || `PT-2026-${String(nextNum).padStart(5, '0')}`;
const newPatient = {
patient_id: newId,
name: patientData.name || 'Unnamed Patient',
age: Number(patientData.age) || 30,
gender: patientData.gender || 'Other',
phone: patientData.phone || '',
created_at: new Date().toISOString()
};
// Check if exists
const idx = db.patients.findIndex(p => p.patient_id === newId);
if (idx >= 0) {
db.patients[idx] = { ...db.patients[idx], ...newPatient };
} else {
db.patients.unshift(newPatient);
}
writeDB(db);
return newPatient;
},
updatePatient: (patient_id, updateData) => {
const db = readDB();
const idx = db.patients.findIndex(p => p.patient_id === patient_id);
if (idx === -1) return null;
db.patients[idx] = { ...db.patients[idx], ...updateData };
writeDB(db);
return db.patients[idx];
},
// ── Doctors ──
getDoctors: () => {
const db = readDB();
return db.doctors;
},
getDoctorById: (doctor_id) => {
const db = readDB();
return db.doctors.find(d => d.doctor_id === doctor_id) || null;
},
createDoctor: (doctorData) => {
const db = readDB();
// BUG 4 FIX: max ID + 1 approach for doctors too
const existingNums = db.doctors.map(d => {
const parts = d.doctor_id.split('-');
return parseInt(parts[parts.length - 1]) || 0;
});
const nextNum = (existingNums.length > 0 ? Math.max(...existingNums) : 0) + 1;
const newId = doctorData.doctor_id || `DOC-${String(nextNum).padStart(3, '0')}`;
const newDoctor = {
doctor_id: newId,
name: doctorData.name,
department: doctorData.department || 'General Medicine',
specialization: doctorData.specialization || 'Consultant',
phone: doctorData.phone || '',
created_at: new Date().toISOString()
};
db.doctors.push(newDoctor);
writeDB(db);
return newDoctor;
},
// ── Consultations ──
getConsultations: (filters = {}) => {
const db = readDB();
let list = [...db.consultations];
if (filters.patient_id) {
list = list.filter(c => c.patient_id === filters.patient_id);
}
if (filters.doctor_id) {
list = list.filter(c => c.doctor_id === filters.doctor_id);
}
if (filters.status && filters.status !== 'All' && filters.status !== 'all') {
list = list.filter(c => c.status.toLowerCase() === filters.status.toLowerCase());
}
if (filters.date) {
list = list.filter(c => c.consultation_date === filters.date);
}
if (filters.date_range) {
const today = new Date().toISOString().slice(0, 10);
if (filters.date_range === 'Today' || filters.date_range === 'today') {
list = list.filter(c => c.consultation_date === today);
} else if (filters.date_range === 'This Week' || filters.date_range === 'this_week') {
const d = new Date();
d.setDate(d.getDate() - 7);
const weekAgo = d.toISOString().slice(0, 10);
list = list.filter(c => c.consultation_date >= weekAgo);
} else if (filters.date_range === 'This Month' || filters.date_range === 'this_month') {
const d = new Date();
d.setDate(d.getDate() - 30);
const monthAgo = d.toISOString().slice(0, 10);
list = list.filter(c => c.consultation_date >= monthAgo);
}
}
if (filters.search) {
const s = filters.search.toLowerCase();
list = list.filter(c =>
(c.patient_name && c.patient_name.toLowerCase().includes(s)) ||
(c.doctor_name && c.doctor_name.toLowerCase().includes(s)) ||
(c.patient_id && c.patient_id.toLowerCase().includes(s)) ||
(c.consultation_id && c.consultation_id.toLowerCase().includes(s)) ||
(c.transcript && c.transcript.toLowerCase().includes(s))
);
}
// Sort newest first
list.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
return list;
},
getConsultationById: (consultation_id) => {
const db = readDB();
return db.consultations.find(c => c.consultation_id === consultation_id) || null;
},
createConsultation: (consultationData) => {
const db = readDB();
// BUG 4 FIX: max ID + 1 approach for consultations too
const existingNums = db.consultations.map(c => {
const parts = c.consultation_id.split('-');
return parseInt(parts[parts.length - 1]) || 0;
});
const nextNum = (existingNums.length > 0 ? Math.max(...existingNums) : 0) + 1;
const newId = consultationData.consultation_id || `CONS-2026-${String(nextNum).padStart(6, '0')}`;
// Calculate duration format
const durSecs = Number(consultationData.duration_seconds) || 0;
const mins = Math.floor(durSecs / 60);
const secs = durSecs % 60;
const durFormatted = `${String(mins).padStart(2, '0')} min ${String(secs).padStart(2, '0')} sec`;
const now = new Date();
const timeFormatted = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true });
const newConsultation = {
consultation_id: newId,
patient_id: consultationData.patient_id || 'PT-2026-00124',
patient_name: consultationData.patient_name || 'Sanika Gurav',
doctor_id: consultationData.doctor_id || 'DOC-001',
doctor_name: consultationData.doctor_name || 'Dr. Sharma',
consultation_date: consultationData.consultation_date || now.toISOString().slice(0, 10),
time_formatted: consultationData.time_formatted || timeFormatted,
duration_seconds: durSecs,
duration_formatted: consultationData.duration_formatted || durFormatted,
audio_file: consultationData.audio_file || null,
language: consultationData.language || 'mr-IN',
transcript: consultationData.transcript || '',
speaker_segments: consultationData.speaker_segments || [],
summary: consultationData.summary || {
chief_complaint: 'Consultation conducted',
symptoms: [],
history: 'Not specified',
assessment: 'Clinical evaluation',
recommendation: 'Follow standard care'
},
status: consultationData.status || 'Completed',
created_at: now.toISOString(),
updated_at: now.toISOString()
};
// Auto-create patient if not present in DB
const patientExists = db.patients.some(p => p.patient_id === newConsultation.patient_id);
if (!patientExists) {
db.patients.unshift({
patient_id: newConsultation.patient_id,
name: newConsultation.patient_name,
age: 30,
gender: 'Other',
phone: '',
created_at: now.toISOString()
});
}
db.consultations.unshift(newConsultation);
writeDB(db);
return newConsultation;
},
updateConsultation: (consultation_id, updateData) => {
const db = readDB();
const idx = db.consultations.findIndex(c => c.consultation_id === consultation_id);
if (idx === -1) return null;
db.consultations[idx] = {
...db.consultations[idx],
...updateData,
updated_at: new Date().toISOString()
};
writeDB(db);
return db.consultations[idx];
},
deleteConsultation: (consultation_id) => {
const db = readDB();
const idx = db.consultations.findIndex(c => c.consultation_id === consultation_id);
if (idx === -1) return false;
db.consultations.splice(idx, 1);
writeDB(db);
return true;
},
// ── Dashboard Stats ──
getDashboardStats: () => {
const db = readDB();
const totalPatients = db.patients.length;
const todayStr = new Date().toISOString().slice(0, 10);
const todayConsultations = db.consultations.filter(c => c.consultation_date === todayStr).length;
const pendingSummaries = db.consultations.filter(c => c.status === 'Processing' || c.status === 'Pending Review').length;
const totalRecordingSecs = db.consultations.reduce((acc, c) => acc + (c.duration_seconds || 0), 0);
const totalRecordingMins = Math.round(totalRecordingSecs / 60);
return {
total_patients: totalPatients,
today_consultations: todayConsultations,
pending_summaries: pendingSummaries,
total_recording_minutes: totalRecordingMins || 320,
recent_consultations: db.consultations.slice(0, 5)
};
}
};
+341
View File
@@ -0,0 +1,341 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Clinical Assistant — Doctor-Patient Consultation</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=Noto+Sans+Devanagari:wght@400;500;600;700&family=JetBrains+Mono:wght@500;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="layout-container">
<!-- SIDEBAR NAVIGATION -->
<aside class="sidebar" id="sidebar">
<div class="sidebar-brand">
<div class="brand-icon-box">
<svg class="brand-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z"/>
<path d="M12 5v14M5 12h14" stroke="#ffffff" stroke-width="1.5" stroke-linecap="round"/>
</svg>
</div>
<div class="brand-text">
<h1 class="brand-title">AI Clinical Assistant</h1>
<span class="brand-subtitle">Doctor-Patient Conversation</span>
</div>
</div>
<nav class="sidebar-nav">
<a href="#dashboard" class="nav-item" data-tab="dashboard">
<span class="nav-icon">📊</span>
<span class="nav-label">Dashboard</span>
</a>
<a href="#new-consultation" class="nav-item active" data-tab="new-consultation">
<span class="nav-icon">🎙️</span>
<span class="nav-label">New Consultation</span>
</a>
<a href="#past-recordings" class="nav-item" data-tab="past-recordings">
<span class="nav-icon">📁</span>
<span class="nav-label">Past Recordings</span>
</a>
<a href="#patients" class="nav-item" data-tab="patients">
<span class="nav-icon">👥</span>
<span class="nav-label">Patients</span>
</a>
<a href="#doctors" class="nav-item" data-tab="doctors">
<span class="nav-icon">🩺</span>
<span class="nav-label">Doctors</span>
</a>
<a href="#transcripts" class="nav-item" data-tab="transcripts">
<span class="nav-icon">📄</span>
<span class="nav-label">Transcripts</span>
</a>
<a href="#clinical-summaries" class="nav-item" data-tab="clinical-summaries">
<span class="nav-icon">📋</span>
<span class="nav-label">Clinical Summaries</span>
</a>
<a href="#settings" class="nav-item" data-tab="settings">
<span class="nav-icon">⚙️</span>
<span class="nav-label">Settings</span>
</a>
</nav>
<div class="sidebar-footer">
<div class="system-status-card">
<div class="status-indicator-row">
<span class="status-pulse-dot"></span>
<span class="status-title">System Online</span>
</div>
<div class="status-meta">Sarvam AI Cloud (v3 STT)</div>
<div class="status-tag">Online Mode • Ready</div>
</div>
</div>
</aside>
<!-- MAIN APP WRAPPER -->
<div class="main-wrapper">
<header class="top-header">
<div class="header-left">
<button class="menu-toggle-btn" id="menuToggle" aria-label="Toggle Navigation">
<svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2.2" fill="none">
<line x1="3" y1="12" x2="21" y2="12"></line>
<line x1="3" y1="6" x2="21" y2="6"></line>
<line x1="3" y1="18" x2="21" y2="18"></line>
</svg>
</button>
<h2 class="page-title" id="pageHeading">New Consultation</h2>
</div>
<div class="header-right">
<div class="lang-selector-wrapper">
<span class="lang-globe-icon">🌐</span>
<select id="langSelect" class="lang-dropdown">
<option value="auto" selected>Auto (मराठी / Hindi / English)</option>
<option value="mr-IN">मराठी (mr-IN)</option>
<option value="hi-IN">हिंदी (hi-IN)</option>
<option value="en-IN">English (en-IN)</option>
</select>
<span class="dropdown-arrow">▾</span>
</div>
<button class="notif-btn" id="notifBtn" title="Notifications">
<span class="notif-icon">🔔</span>
<span class="notif-badge">3</span>
</button>
<div class="doctor-profile-card">
<img class="doctor-avatar" src="https://images.unsplash.com/photo-1622253692010-333f2da6031d?w=100&auto=format&fit=crop&q=80" alt="Dr. Sharma">
<div class="doctor-meta">
<span class="doctor-name">Dr. Sharma</span>
<span class="doctor-spec">Cardiologist</span>
</div>
</div>
</div>
</header>
<main class="content-area">
<section class="tab-view active" id="view-new-consultation">
<!-- CARD 1: CONSULTATION DETAILS -->
<div class="card details-card">
<div class="card-header-row">
<div class="card-title-group">
<span class="card-header-icon">📋</span>
<h3 class="card-title">Consultation Details</h3>
</div>
<button class="btn-link-action" id="openAddPatientBtn">
<span>+ Add New Patient</span>
</button>
</div>
<div class="details-form-grid">
<div class="form-group">
<label for="patientName" class="form-label">Patient Name</label>
<div class="input-icon-box">
<span class="input-icon">👤</span>
<input type="text" id="patientName" placeholder="Select or type patient name..." value="Ramesh Patil" autocomplete="off">
</div>
</div>
<div class="form-group">
<label for="patientId" class="form-label">Patient ID</label>
<div class="input-icon-box">
<span class="input-icon">🪪</span>
<input type="text" id="patientId" value="PT-2026-00124" readonly>
</div>
</div>
<div class="form-group">
<label for="doctorName" class="form-label">Doctor Name</label>
<div class="input-icon-box select-box">
<span class="input-icon">🩺</span>
<select id="doctorName">
<option value="Dr. Sharma" selected>Dr. Sharma</option>
<option value="Dr. Kulkarni">Dr. Kulkarni</option>
<option value="Dr. Joshi">Dr. Joshi</option>
</select>
<span class="select-chevron">▾</span>
</div>
</div>
<div class="form-group">
<label for="consultationDate" class="form-label">Date</label>
<div class="input-icon-box">
<span class="input-icon">📅</span>
<input type="text" id="consultationDate" value="09-09-2026">
</div>
</div>
</div>
</div>
<!-- CARD 2: LIVE RECORDING & CONTROLS -->
<div class="card recording-card">
<div class="rec-status-line">
<span class="rec-pulse-bubble" id="recPulse"></span>
<div class="timer-display" id="timer">00:00:00</div>
</div>
<div class="rec-substatus" id="recSubStatus">
<span class="mic-glyph">🎙️</span>
<span id="recStatusText">Ready to record consultation...</span>
</div>
<div class="visualizer-container" id="visualizerContainer">
<canvas id="waveformCanvas" width="560" height="42"></canvas>
</div>
<div class="rec-error-banner" id="recError" style="display:none;"></div>
<div class="action-buttons-row">
<button class="btn btn-record" id="startBtn">
<span class="btn-icon">▶</span>
<span class="btn-text">START RECORDING</span>
</button>
<button class="btn btn-stop" id="stopBtn" disabled>
<span class="btn-icon">⏹</span>
<span class="btn-text">STOP &amp; AUTO-SUMMARIZE</span>
</button>
<button class="btn btn-upload" id="uploadAudioBtn">
<span class="btn-icon">📁</span>
<span class="btn-text">UPLOAD AUDIO</span>
</button>
<input type="file" id="audioFileInput" accept="audio/*,.wav,.mp3,.m4a,.ogg,.webm" style="display:none;">
<button class="btn btn-demo" id="demoBtn">
<span class="btn-icon">⚡</span>
<span class="btn-text">DEMO</span>
</button>
</div>
</div>
<!-- CARD 3: TRANSCRIPT (FULL & REAL-TIME AUDIO SYNCHRONIZED) -->
<div class="card transcript-card">
<div class="card-header-row">
<div class="card-title-group">
<h3 class="card-title-section">TRANSCRIPT</h3>
<span class="live-realtime-badge" id="liveRealtimeBadge" style="display:none;">
<span class="live-blink-dot"></span> LIVE SYNC
</span>
</div>
<div class="header-actions">
<div class="transcript-search-box">
<span class="search-icon">🔍</span>
<input type="text" id="transcriptSearch" placeholder="Search dialogue..." autocomplete="off">
</div>
<button class="btn-sm-action" id="copyTranscriptBtn">
<span class="sm-icon">📋</span> Copy
</button>
<button class="btn-sm-action" id="clearTranscriptBtn">
<span class="sm-icon">↺</span> Reset
</button>
</div>
</div>
<div class="audio-playback-bar" id="audioPlaybackBar" style="display:none;">
<button class="btn-play-pause" id="playAudioBtn" title="Play / Pause Audio">
<span id="playIcon">▶</span>
</button>
<div class="audio-progress-container">
<input type="range" class="audio-scrubber" id="audioScrubber" min="0" max="100" value="0" step="0.1">
<div class="audio-time-row">
<span id="audioCurrentTime">00:00</span>
<span class="sync-hint">💡 Click any dialogue line to jump audio</span>
<span id="audioTotalDuration">00:00</span>
</div>
</div>
</div>
<div class="transcript-filter-bar">
<button class="filter-pill active" data-filter="all">All Dialogue</button>
<button class="filter-pill" data-filter="doctor">🧑‍⚕️ Doctor</button>
<button class="filter-pill" data-filter="patient">🧑 Patient</button>
</div>
<div class="transcript-viewport" id="transcriptBody">
<div class="transcript-placeholder" id="transcriptPlaceholder">
<div class="placeholder-icon">🎙️</div>
<p>Recording in progress… Transcript will appear here in real time.</p>
<span class="placeholder-sub">Speak into the microphone or click DEMO to see full real-time audio synchronization.</span>
</div>
</div>
</div>
<!-- CARD 4: AI CLINICAL SUMMARY -->
<div class="card summary-card" id="summaryCard">
<div class="card-header-row">
<div class="card-title-group">
<span class="card-header-icon">📋</span>
<h3 class="card-title-section">AI CLINICAL SUMMARY</h3>
</div>
<div class="header-actions">
<button class="btn-sm-action" id="copySummaryBtn">
<span class="sm-icon">📋</span> Copy Summary
</button>
<button class="btn-sm-action" id="printSummaryBtn">
<span class="sm-icon">🖨️</span> Print / PDF
</button>
<button class="btn-sm-action" id="exportJsonBtn">
<span class="sm-icon">📥</span> Export JSON
</button>
</div>
</div>
<div class="summary-content-grid" id="summaryBody">
<div class="summary-col-card">
<div class="col-card-header">Chief Complaint</div>
<div class="col-card-body" id="sumChiefComplaint"><p class="empty-field">—</p></div>
</div>
<div class="summary-col-card">
<div class="col-card-header">Symptoms Discussed</div>
<div class="col-card-body" id="sumSymptoms"><p class="empty-field">—</p></div>
</div>
<div class="summary-col-card">
<div class="col-card-header">Doctor's Recommendation / Diagnosis</div>
<div class="col-card-body" id="sumAssessment"><p class="empty-field">—</p></div>
</div>
<div class="summary-col-card full-span">
<div class="col-card-header">Patient History &amp; Comorbidities</div>
<div class="col-card-body" id="sumHistory"><p class="empty-field">—</p></div>
</div>
<div class="summary-col-card full-span highlight-plan">
<div class="col-card-header">Prescription, Tests &amp; Treatment Plan (Rx)</div>
<div class="col-card-body" id="sumPlan"><p class="empty-field">—</p></div>
</div>
</div>
</div>
</section>
</main>
</div>
</div>
<div class="modal-overlay" id="patientModal">
<div class="modal-card">
<div class="modal-header">
<h3>Add New Patient</h3>
<button class="modal-close-btn" id="closePatientModal">&times;</button>
</div>
<div class="modal-body">
<div class="form-group mb-3">
<label class="form-label">Full Name</label>
<input type="text" id="newPatientName" placeholder="e.g. Ramesh Patil">
</div>
</div>
<div class="modal-footer">
<button class="btn-cancel" id="cancelPatientModal">Cancel</button>
<button class="btn-save-patient" id="savePatientBtn">Save Patient</button>
</div>
</div>
</div>
<div class="toast-notification" id="toastBox">Notification</div>
<script src="script.js"></script>
</body>
</html>
+367
View File
@@ -0,0 +1,367 @@
(() => {
'use strict';
// ── Config ─────────────────────────────────────────────────────────────────
// Point this to wherever your FastAPI backend is running
const BACKEND = 'http://127.0.0.1:8080';
// ── DOM refs (matching existing HTML IDs exactly) ──────────────────────────
const startBtn = document.getElementById('startBtn');
const stopBtn = document.getElementById('stopBtn');
const timerEl = document.getElementById('timer');
const liveBadge = document.getElementById('liveBadge');
const serverStatus = document.getElementById('serverStatus');
const recError = document.getElementById('recError');
const transcriptBody = document.getElementById('transcriptBody');
const summaryBtn = document.getElementById('summaryBtn');
const clearBtn = document.getElementById('clearBtn');
const summaryCard = document.getElementById('summaryCard');
const summaryBody = document.getElementById('summaryBody');
// ── State ──────────────────────────────────────────────────────────────────
let mediaRecorder = null;
let recordedChunks = [];
let timerInterval = null;
let secondsElapsed = 0;
let lastTranscript = '';
// ── Helpers ────────────────────────────────────────────────────────────────
function fmtTime(s) {
const h = String(Math.floor(s / 3600)).padStart(2, '0');
const m = String(Math.floor((s % 3600) / 60)).padStart(2, '0');
const sec = String(s % 60).padStart(2, '0');
return `${h}:${m}:${sec}`;
}
function escHtml(str) {
const d = document.createElement('div');
d.innerText = str;
return d.innerHTML;
}
function showError(msg) {
recError.textContent = msg;
recError.style.display = 'block';
}
function clearError() {
recError.textContent = '';
recError.style.display = 'none';
}
function setStatus(msg, type = '') {
serverStatus.textContent = msg;
serverStatus.className = 'status-text' + (type ? ` ${type}` : '');
}
// ── Health check on load ───────────────────────────────────────────────────
async function checkHealth() {
try {
const res = await fetch(`${BACKEND}/api/health`);
const data = await res.json();
if (data.sarvam_key_configured) {
setStatus('✔ Backend ready — Sarvam API key configured', 'ok');
} else {
setStatus('✘ Backend running but SARVAM_API_KEY is not set', 'bad');
startBtn.disabled = true;
}
} catch {
setStatus('✘ Cannot reach backend at ' + BACKEND, 'bad');
startBtn.disabled = true;
}
}
// ── Choose best supported MIME type ───────────────────────────────────────
function getSupportedMimeType() {
const types = [
'audio/webm;codecs=opus',
'audio/webm',
'audio/ogg;codecs=opus',
'audio/ogg',
'audio/mp4',
];
return types.find(t => MediaRecorder.isTypeSupported(t)) || '';
}
// ── Start recording ────────────────────────────────────────────────────────
async function startRecording() {
clearError();
recordedChunks = [];
// Request microphone
let stream;
try {
stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
} catch (err) {
if (err.name === 'NotAllowedError' || err.name === 'PermissionDeniedError') {
showError('Microphone permission denied. Please allow microphone access in your browser settings.');
} else if (err.name === 'NotFoundError') {
showError('No microphone found. Please connect a microphone and try again.');
} else {
showError(`Microphone error: ${err.message}`);
}
return;
}
// Create MediaRecorder
const mimeType = getSupportedMimeType();
try {
mediaRecorder = new MediaRecorder(stream, mimeType ? { mimeType } : {});
} catch (err) {
showError(`Could not start MediaRecorder: ${err.message}`);
stream.getTracks().forEach(t => t.stop());
return;
}
mediaRecorder.ondataavailable = (e) => {
if (e.data && e.data.size > 0) recordedChunks.push(e.data);
};
mediaRecorder.onerror = (e) => {
showError(`Recording error: ${e.error?.message || 'Unknown error'}`);
};
mediaRecorder.start(250); // collect data every 250 ms
// Update UI → recording state
startBtn.disabled = true;
stopBtn.disabled = false;
liveBadge.classList.add('on');
summaryBtn.disabled = true;
summaryCard.style.display = 'none';
lastTranscript = '';
transcriptBody.innerHTML = '<p class="placeholder-text">Recording in progress… press ⏹ Stop &amp; Transcribe when done.</p>';
// Start timer
secondsElapsed = 0;
timerEl.textContent = '🔴 ' + fmtTime(0);
timerInterval = setInterval(() => {
secondsElapsed++;
timerEl.textContent = '🔴 ' + fmtTime(secondsElapsed);
}, 1000);
setStatus('🎙️ Recording…');
}
// ── Stop recording → send to backend ──────────────────────────────────────
function stopRecording() {
if (!mediaRecorder || mediaRecorder.state === 'inactive') return;
// Stop timer
clearInterval(timerInterval);
timerInterval = null;
// Stop all mic tracks
mediaRecorder.stream.getTracks().forEach(t => t.stop());
// When recorder finishes flushing, send the audio
mediaRecorder.onstop = async () => {
await sendAudioToBackend();
};
mediaRecorder.stop();
// Update UI → processing state
startBtn.disabled = true;
stopBtn.disabled = true;
liveBadge.classList.remove('on');
timerEl.textContent = '⏳ ' + fmtTime(secondsElapsed);
setStatus('Processing transcript…');
transcriptBody.innerHTML = `
<div class="processing-row">
<span class="spinner"></span>
Processing transcript, please wait…
</div>`;
}
// ── Upload audio blob → /api/transcribe ────────────────────────────────────
async function sendAudioToBackend() {
if (recordedChunks.length === 0) {
showError('No audio was recorded. Please try again.');
resetButtons();
return;
}
const mimeType = recordedChunks[0].type || 'audio/webm';
const extension = mimeType.includes('ogg') ? 'ogg' : mimeType.includes('mp4') ? 'mp4' : 'webm';
const audioBlob = new Blob(recordedChunks, { type: mimeType });
const formData = new FormData();
formData.append('file', audioBlob, `recording.${extension}`);
try {
const res = await fetch(`${BACKEND}/api/transcribe`, {
method: 'POST',
body: formData,
// Do NOT set Content-Type header — browser sets it automatically with boundary
});
let data;
try {
data = await res.json();
} catch {
throw new Error(`Server returned non-JSON response (HTTP ${res.status})`);
}
if (!res.ok) {
throw new Error(data.detail || data.error || `HTTP ${res.status}`);
}
lastTranscript = (data.transcript || '').trim();
renderTranscript(lastTranscript, data.language || '');
timerEl.textContent = '✅ ' + fmtTime(secondsElapsed);
setStatus('✔ Transcript ready', 'ok');
if (lastTranscript) summaryBtn.disabled = false;
} catch (err) {
// Classify the error for the user
let msg = err.message || 'Unknown error';
if (err instanceof TypeError && msg.includes('fetch')) {
msg = `Cannot reach backend at ${BACKEND}. Is the server running?`;
}
showError('Transcription failed: ' + msg);
transcriptBody.innerHTML = '<p class="placeholder-text">Transcription failed. Please try again.</p>';
timerEl.textContent = '🔴 ' + fmtTime(secondsElapsed);
setStatus('Transcription failed', 'bad');
}
resetButtons();
}
function resetButtons() {
startBtn.disabled = false;
stopBtn.disabled = true;
}
// ── Render transcript in existing #transcriptBody ─────────────────────────
function renderTranscript(text, language) {
if (!text) {
transcriptBody.innerHTML = '<p class="placeholder-text">No speech detected in the recording.</p>';
return;
}
// Split on sentence boundaries and render each as an utterance block
// (Doctor / Patient alternating — best-effort without diarization)
const sentences = text.match(/[^.!?।\n]+[.!?।\n]*/g) || [text];
const langTag = language && language !== 'unknown'
? `<span class="utt-ts">[${escHtml(language)}]</span>`
: '';
let html = '';
sentences.forEach((sentence, i) => {
sentence = sentence.trim();
if (!sentence) return;
const isDoc = i % 2 === 0;
const icon = isDoc ? '🧑‍⚕️' : '🧑';
const name = isDoc ? 'Doctor' : 'Patient';
const cls = isDoc ? '' : 'patient';
const ts = fmtTime(Math.round((i / sentences.length) * secondsElapsed));
html += `
<div class="utt">
<div class="utt-meta">
<span class="utt-icon">${icon}</span>
<span class="utt-name ${cls}">${name}</span>
<span class="utt-ts">[${ts}]</span>
${i === 0 ? langTag : ''}
</div>
<div class="utt-text">${escHtml(sentence)}</div>
</div>`;
});
transcriptBody.innerHTML = html;
transcriptBody.scrollTop = transcriptBody.scrollHeight;
}
// ── Reset / Clear ──────────────────────────────────────────────────────────
function resetAll() {
lastTranscript = '';
recordedChunks = [];
transcriptBody.innerHTML = '<p class="placeholder-text">Transcript will appear here once recording starts…</p>';
summaryCard.style.display = 'none';
summaryBtn.disabled = true;
timerEl.textContent = '🔴 00:00:00';
clearError();
setStatus('');
}
// ── Generate AI Summary ────────────────────────────────────────────────────
async function generateSummary() {
if (!lastTranscript.trim()) return;
summaryCard.style.display = 'block';
summaryBody.innerHTML = `
<div class="summary-loading">
<span class="spinner"></span> Generating summary…
</div>`;
summaryBtn.disabled = true;
try {
const res = await fetch(`${BACKEND}/api/summary`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ transcript: lastTranscript }),
});
let data;
try { data = await res.json(); } catch { throw new Error('Non-JSON response from backend'); }
if (!res.ok) throw new Error(data.detail || data.error || `HTTP ${res.status}`);
const s = data.summary;
if (s.raw_text) {
summaryBody.innerHTML = `
<div class="summary-row">
<span class="s-key">Summary</span>
<span class="s-val">${escHtml(s.raw_text)}</span>
</div>`;
} else {
renderSummary(s);
}
} catch (err) {
summaryBody.innerHTML = `
<div class="summary-row">
<span class="s-key">Error</span>
<span class="s-val" style="color:var(--red)">${escHtml(err.message)}</span>
</div>`;
}
summaryBtn.disabled = false;
}
function renderSummary(s) {
function listHtml(arr) {
if (!arr || !arr.length) return 'Not mentioned';
return '<ul>' + arr.map(x => `<li>${escHtml(String(x))}</li>`).join('') + '</ul>';
}
summaryBody.innerHTML = `
<div class="summary-row">
<span class="s-key">Chief Complaint</span>
<span class="s-val">${escHtml(s.chief_complaint || 'Not mentioned')}</span>
</div>
<div class="summary-row">
<span class="s-key">Symptoms</span>
<span class="s-val">${listHtml(s.symptoms)}</span>
</div>
<div class="summary-row">
<span class="s-key">Diagnosis</span>
<span class="s-val">${escHtml(s.assessment || 'Not mentioned')}</span>
</div>
<div class="summary-row">
<span class="s-key">Prescription</span>
<span class="s-val">${listHtml(s.plan)}</span>
</div>`;
}
// ── Event listeners ────────────────────────────────────────────────────────
startBtn.addEventListener('click', startRecording);
stopBtn.addEventListener('click', stopRecording);
clearBtn.addEventListener('click', resetAll);
summaryBtn.addEventListener('click', generateSummary);
// ── Init ───────────────────────────────────────────────────────────────────
checkHealth();
})();
+380
View File
@@ -0,0 +1,380 @@
/* ─── Reset ──────────────────────────────────────────────── */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
/* ─── Tokens ─────────────────────────────────────────────── */
:root {
--bg: #f0f2f5;
--surface: #ffffff;
--surface2: #f5f7fa;
--border: #dde1ea;
--border-hi: #c8cdd8;
--text: #1a1d2e;
--text-dim: #5a6080;
--text-muted: #a0a8c0;
--accent: #3b6ff0;
--green: #1fad6a;
--green-bg: #e6f9f1;
--red: #e03c3c;
--red-bg: #fdeaea;
--yellow: #d4a000;
--radius-lg: 12px;
--radius-sm: 8px;
--gap: 12px;
}
/* ─── Base ───────────────────────────────────────────────── */
html, body {
min-height: 100vh;
background: var(--bg);
color: var(--text);
font-family: 'Inter', 'Noto Sans Devanagari', sans-serif;
font-size: 14px;
line-height: 1.6;
}
/* ─── Container ──────────────────────────────────────────── */
.container {
max-width: 760px;
margin: 0 auto;
padding: 32px 16px 72px;
display: flex;
flex-direction: column;
gap: var(--gap);
}
/* ─── Panel (shared card shell) ──────────────────────────── */
.panel {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
overflow: hidden;
}
/* ─── Header ─────────────────────────────────────────────── */
.header {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
padding: 18px 22px;
display: flex;
align-items: center;
gap: 12px;
font-size: 17px;
font-weight: 700;
letter-spacing: .01em;
}
.header-icon { font-size: 22px; }
/* ─── Names panel ────────────────────────────────────────── */
.names-panel {
display: flex;
align-items: stretch;
gap: 0;
}
.name-group {
flex: 1;
display: flex;
flex-direction: column;
gap: 5px;
padding: 16px 20px;
}
.divider-v {
width: 1px;
background: var(--border);
align-self: stretch;
}
label {
font-size: 10px;
font-weight: 700;
letter-spacing: .08em;
text-transform: uppercase;
color: var(--text-dim);
}
input[type="text"],
select {
background: var(--surface2);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
color: var(--text);
font-family: inherit;
font-size: 13px;
padding: 8px 11px;
width: 100%;
outline: none;
transition: border-color .15s;
}
input[type="text"]::placeholder { color: var(--text-muted); }
input[type="text"]:focus,
select:focus { border-color: var(--accent); }
select { cursor: pointer; }
select option { background: var(--surface2); }
/* ─── Recording panel ────────────────────────────────────── */
.rec-panel {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
padding: 28px 24px 24px;
text-align: center;
}
/* Live badge */
.live-badge {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
font-weight: 700;
letter-spacing: .1em;
color: var(--red);
opacity: 0;
transition: opacity .3s;
}
.live-badge.on { opacity: 1; }
.live-dot {
width: 9px; height: 9px;
border-radius: 50%;
background: var(--red);
animation: blink 1s ease-in-out infinite;
}
@keyframes blink { 50% { opacity: .2; } }
/* Timer */
.timer {
font-size: 28px;
font-weight: 700;
font-variant-numeric: tabular-nums;
letter-spacing: .03em;
}
/* Status text */
.status-text {
font-size: 12px;
color: var(--text-dim);
}
.status-text.ok { color: var(--green); }
.status-text.bad { color: var(--red); }
/* Error box */
.rec-error {
width: 100%;
background: var(--red-bg);
border: 1px solid #5a1e1e;
border-radius: var(--radius-sm);
color: var(--red);
font-size: 12.5px;
padding: 9px 14px;
text-align: left;
}
/* Rec buttons row */
.rec-btns {
display: flex;
gap: 10px;
flex-wrap: wrap;
justify-content: center;
}
/* ─── Buttons ────────────────────────────────────────────── */
.btn {
font-family: inherit;
font-size: 13px;
font-weight: 700;
letter-spacing: .05em;
padding: 11px 24px;
border: none;
border-radius: var(--radius-sm);
cursor: pointer;
transition: filter .15s, transform .1s;
white-space: nowrap;
}
.btn:active { transform: scale(.97); }
.btn:disabled { opacity: .4; cursor: not-allowed; transform: none; }
.btn-start {
background: var(--green);
color: #ffffff;
}
.btn-start:not(:disabled):hover { filter: brightness(1.1); }
.btn-stop {
background: var(--red);
color: #fff;
}
.btn-stop:not(:disabled):hover { filter: brightness(1.1); }
.btn-generate {
background: var(--accent);
color: #fff;
font-size: 14px;
padding: 13px 32px;
flex: 1;
}
.btn-generate:not(:disabled):hover { filter: brightness(1.1); }
.btn-reset {
background: transparent;
color: var(--text-dim);
border: 1px solid var(--border-hi);
padding: 13px 20px;
}
.btn-reset:hover { color: var(--text); border-color: var(--text-dim); }
/* ─── Panel heading (TRANSCRIPT / MEDICAL SUMMARY) ───────── */
.panel-heading {
background: var(--surface2);
border-bottom: 1px solid var(--border);
padding: 10px 20px;
font-size: 11px;
font-weight: 700;
letter-spacing: .12em;
color: var(--text-dim);
text-transform: uppercase;
}
/* ─── Transcript panel ───────────────────────────────────── */
.transcript-panel { /* uses .panel */ }
.transcript-scroll {
padding: 18px 20px;
min-height: 160px;
max-height: 380px;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 18px;
}
.placeholder-text {
color: var(--text-muted);
font-size: 13px;
}
/* Processing state */
.processing-row {
display: flex;
align-items: center;
gap: 10px;
color: var(--text-dim);
font-size: 13px;
}
/* Utterance block */
.utt {
display: flex;
flex-direction: column;
gap: 4px;
}
.utt-meta {
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
}
.utt-icon { font-size: 16px; }
.utt-name {
font-size: 13px;
font-weight: 600;
color: var(--accent);
}
.utt-name.patient { color: var(--green); }
.utt-ts {
font-size: 11px;
color: var(--text-muted);
font-variant-numeric: tabular-nums;
}
.utt-text {
font-size: 14.5px;
line-height: 1.7;
color: var(--text);
padding-left: 22px;
}
/* ─── Generate panel ─────────────────────────────────────── */
.generate-panel {
display: flex;
gap: 10px;
align-items: center;
padding: 16px 20px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
}
/* ─── Summary panel ──────────────────────────────────────── */
.summary-panel { /* uses .panel */ }
.summary-body {
padding: 4px 0;
}
.summary-row {
display: flex;
gap: 0;
border-bottom: 1px solid var(--border);
}
.summary-row:last-child { border-bottom: none; }
.s-key {
flex: 0 0 160px;
padding: 13px 20px;
font-size: 11px;
font-weight: 700;
letter-spacing: .06em;
text-transform: uppercase;
color: var(--accent);
background: var(--surface2);
border-right: 1px solid var(--border);
}
.s-val {
flex: 1;
padding: 13px 20px;
font-size: 14px;
color: var(--text);
line-height: 1.65;
}
.s-val ul {
padding-left: 18px;
margin: 0;
}
/* Loading spinner */
.spinner {
display: inline-block;
width: 14px; height: 14px;
border: 2px solid var(--border-hi);
border-top-color: var(--accent);
border-radius: 50%;
animation: spin .7s linear infinite;
flex-shrink: 0;
}
@keyframes spin { to { transform: rotate(360deg); } }
.summary-loading {
display: flex;
align-items: center;
gap: 10px;
padding: 18px 20px;
color: var(--text-dim);
font-size: 13px;
}
/* ─── Scrollbar ──────────────────────────────────────────── */
::-webkit-scrollbar { width: 4px; }
::-webkit-scrollbar-track { background: var(--surface2); }
::-webkit-scrollbar-thumb { background: var(--border-hi); border-radius: 99px; }
/* ─── Responsive ─────────────────────────────────────────── */
@media (max-width: 520px) {
.names-panel { flex-direction: column; }
.divider-v { width: 100%; height: 1px; align-self: auto; }
.header { font-size: 14px; }
.timer { font-size: 22px; }
.s-key { flex: 0 0 120px; }
}
+192
View File
@@ -0,0 +1,192 @@
import sys
import json
import warnings
import urllib.request
import io
import os
import wave
warnings.filterwarnings("ignore")
import shutil
original_rmtree = shutil.rmtree
def safe_rmtree(path, ignore_errors=False, onerror=None, onexc=None, **kwargs):
try:
if sys.version_info >= (3, 12):
original_rmtree(path, ignore_errors=True, onexc=onexc, **kwargs)
else:
original_rmtree(path, ignore_errors=True, onerror=onerror, **kwargs)
except Exception:
pass
shutil.rmtree = safe_rmtree
def get_sarvam_transcript(audio_path):
api_key = None
if os.path.exists('.env'):
with open('.env', encoding='utf-8') as f:
for line in f:
if line.startswith('SARVAM_API_KEY='):
api_key = line.strip().split('=', 1)[1].strip('"\' ')
if not api_key:
raise ValueError("SARVAM_API_KEY not found in .env")
with open(audio_path, 'rb') as f:
wav_bytes = f.read()
boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW'
filename = os.path.basename(audio_path)
body = (
f'--{boundary}\r\n'
f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n'
f'Content-Type: audio/wav\r\n\r\n'
).encode('utf-8') + wav_bytes + (
f'\r\n--{boundary}\r\n'
f'Content-Disposition: form-data; name="model"\r\n\r\n'
f'saaras:v4\r\n'
f'--{boundary}\r\n'
f'Content-Disposition: form-data; name="mode"\r\n\r\n'
f'translate\r\n'
f'--{boundary}\r\n'
f'Content-Disposition: form-data; name="with_timestamps"\r\n\r\n'
f'true\r\n'
f'--{boundary}--\r\n'
).encode('utf-8')
req = urllib.request.Request(
'https://api.sarvam.ai/speech-to-text',
data=body,
headers={
'api-subscription-key': api_key,
'Content-Type': f'multipart/form-data; boundary={boundary}'
}
)
with urllib.request.urlopen(req) as resp:
return json.loads(resp.read().decode('utf-8'))
def get_nemo_segments(audio_path):
try:
from nemo.collections.asr.models import SortformerEncLabelModel
except ImportError:
raise RuntimeError("NeMo not installed")
diar_model = SortformerEncLabelModel.from_pretrained("nvidia/diar_sortformer_4spk-v1").eval()
from omegaconf import OmegaConf
OmegaConf.set_struct(diar_model.cfg, False)
if hasattr(diar_model.cfg, 'num_workers'):
diar_model.cfg.num_workers = 0
if 'validation_ds' in diar_model.cfg and hasattr(diar_model.cfg.validation_ds, 'num_workers'):
diar_model.cfg.validation_ds.num_workers = 0
if 'test_ds' in diar_model.cfg and hasattr(diar_model.cfg.test_ds, 'num_workers'):
diar_model.cfg.test_ds.num_workers = 0
predicted_segments = diar_model.diarize(audio=[audio_path], batch_size=1, num_workers=0)
if isinstance(predicted_segments, tuple):
predicted_segments = predicted_segments[0]
segments = predicted_segments[0] if len(predicted_segments) > 0 else []
out_segments = []
for seg in segments:
try:
start = float(seg[0])
end = float(seg[1])
spk = int(seg[2])
out_segments.append([start, end, spk])
except:
pass
return out_segments
def align_words_to_segments(sarvam_res, nemo_segments):
if "timestamps" not in sarvam_res:
return []
ts = sarvam_res["timestamps"]
words = ts.get("words", [])
starts = ts.get("start_time_seconds", [])
ends = ts.get("end_time_seconds", [])
aligned_dialogue = []
current_spk = None
current_sentence = []
for i in range(len(words)):
word = words[i]
w_start = starts[i]
w_end = ends[i]
w_mid = (w_start + w_end) / 2.0
# Find which segment contains the word's midpoint
assigned_spk = None
for seg in nemo_segments:
seg_start, seg_end, spk_id = seg
if seg_start <= w_mid <= seg_end:
assigned_spk = spk_id
break
# If midpoint doesn't fall strictly into any segment, find the closest one
if assigned_spk is None and nemo_segments:
closest_spk = None
min_dist = float('inf')
for seg in nemo_segments:
seg_start, seg_end, spk_id = seg
# distance to segment
if w_mid < seg_start:
dist = seg_start - w_mid
elif w_mid > seg_end:
dist = w_mid - seg_end
else:
dist = 0
if dist < min_dist:
min_dist = dist
closest_spk = spk_id
assigned_spk = closest_spk
if assigned_spk is None:
assigned_spk = "Unknown"
else:
assigned_spk = f"Speaker {assigned_spk}"
if current_spk is None:
current_spk = assigned_spk
if assigned_spk != current_spk:
aligned_dialogue.append((current_spk, " ".join(current_sentence)))
current_spk = assigned_spk
current_sentence = [word]
else:
current_sentence.append(word)
if current_sentence:
aligned_dialogue.append((current_spk, " ".join(current_sentence)))
return aligned_dialogue
def main():
if len(sys.argv) < 2:
print("Usage: python hybrid_diarization.py <audio_file.wav>")
sys.exit(1)
audio_path = sys.argv[1]
print(f"[*] Calling Sarvam STT API for transcription... (with_timestamps=true)")
sarvam_res = get_sarvam_transcript(audio_path)
print("[+] Sarvam STT finished.")
print(f"[*] Running local Nvidia Sortformer model for diarization...")
nemo_segments = get_nemo_segments(audio_path)
print(f"[+] Nvidia Diarization finished. Found {len(nemo_segments)} segments.")
print(f"[*] Aligning Sarvam transcript words with Nvidia speaker segments...")
dialogue = align_words_to_segments(sarvam_res, nemo_segments)
print("\n--- FINAL HYBRID DIALOGUE ---\n")
for spk, text in dialogue:
print(f"**{spk}:** {text}")
print()
if __name__ == "__main__":
main()
+886
View File
@@ -0,0 +1,886 @@
{
"name": "sarvam-doctor-patient-demo",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sarvam-doctor-patient-demo",
"version": "1.0.0",
"dependencies": {
"dotenv": "^16.4.5",
"express": "^4.19.2",
"ws": "^8.18.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/accepts": {
"version": "1.3.8",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
"integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",
"license": "MIT",
"dependencies": {
"mime-types": "~2.1.34",
"negotiator": "0.6.3"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/array-flatten": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
"license": "MIT"
},
"node_modules/body-parser": {
"version": "1.20.9",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.9.tgz",
"integrity": "sha512-FISIQxV5u91Y9gvuFq3q/tA/qTqLJn3AhRcEvyozyhJTh5OBFFtv827AdHU7Rbyct4r+Ba1/99oFa1Y3yuFsdw==",
"license": "MIT",
"dependencies": {
"bytes": "~3.1.2",
"content-type": "~1.0.5",
"debug": "2.6.9",
"depd": "2.0.0",
"destroy": "~1.2.0",
"http-errors": "~2.0.1",
"iconv-lite": "~0.4.24",
"on-finished": "~2.4.1",
"qs": "~6.16.0",
"raw-body": "~2.5.3",
"type-is": "~1.6.18",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.8",
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/body-parser/node_modules/qs": {
"version": "6.16.2",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.16.2.tgz",
"integrity": "sha512-VYdnB5S7/0IeXzBacUtwNAaM6d7Y/PgYnNC7bJCI6meqA/OgnsQbZMtVW8Dt2D1PHgbHGtYmhSoEIgvt7xZ2ZA==",
"license": "BSD-3-Clause",
"dependencies": {
"es-define-property": "^1.0.1",
"side-channel": "^1.1.1"
},
"engines": {
"node": ">=0.6"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
"integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/call-bound": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
"integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"get-intrinsic": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/content-disposition": {
"version": "0.5.4",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
"integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==",
"license": "MIT",
"dependencies": {
"safe-buffer": "5.2.1"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/content-type": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
"integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/cookie": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/cookie-signature": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz",
"integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==",
"license": "MIT"
},
"node_modules/debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"license": "MIT",
"dependencies": {
"ms": "2.0.0"
}
},
"node_modules/depd": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
"integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/destroy": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
"integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
"license": "MIT",
"engines": {
"node": ">= 0.8",
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/dotenv": {
"version": "16.6.1",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",
"integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://dotenvx.com"
}
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.1",
"es-errors": "^1.3.0",
"gopd": "^1.2.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
"license": "MIT"
},
"node_modules/encodeurl": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
"integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-errors": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-object-atoms": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",
"integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/escape-html": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
"license": "MIT"
},
"node_modules/etag": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
"integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/express": {
"version": "4.22.2",
"resolved": "https://registry.npmjs.org/express/-/express-4.22.2.tgz",
"integrity": "sha512-IuL+Elrou2ZvCFHs18/CIzy2Nzvo25nZ1/D2eIZlz7c+QUayAcYoiM2BthCjs+EBHVpjYjcuLDAiCWgeIX3X1Q==",
"license": "MIT",
"dependencies": {
"accepts": "~1.3.8",
"array-flatten": "1.1.1",
"body-parser": "~1.20.5",
"content-disposition": "~0.5.4",
"content-type": "~1.0.4",
"cookie": "~0.7.1",
"cookie-signature": "~1.0.6",
"debug": "2.6.9",
"depd": "2.0.0",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"finalhandler": "~1.3.1",
"fresh": "~0.5.2",
"http-errors": "~2.0.0",
"merge-descriptors": "1.0.3",
"methods": "~1.1.2",
"on-finished": "~2.4.1",
"parseurl": "~1.3.3",
"path-to-regexp": "~0.1.12",
"proxy-addr": "~2.0.7",
"qs": "~6.15.1",
"range-parser": "~1.2.1",
"safe-buffer": "5.2.1",
"send": "~0.19.0",
"serve-static": "~1.16.2",
"setprototypeof": "1.2.0",
"statuses": "~2.0.1",
"type-is": "~1.6.18",
"utils-merge": "1.0.1",
"vary": "~1.1.2"
},
"engines": {
"node": ">= 0.10.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/finalhandler": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz",
"integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==",
"license": "MIT",
"dependencies": {
"debug": "2.6.9",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"on-finished": "~2.4.1",
"parseurl": "~1.3.3",
"statuses": "~2.0.2",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/forwarded": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
"integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/fresh": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
"integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-intrinsic": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"es-define-property": "^1.0.1",
"es-errors": "^1.3.0",
"es-object-atoms": "^1.1.1",
"function-bind": "^1.1.2",
"get-proto": "^1.0.1",
"gopd": "^1.2.0",
"has-symbols": "^1.1.0",
"hasown": "^2.0.2",
"math-intrinsics": "^1.1.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
"license": "MIT",
"dependencies": {
"dunder-proto": "^1.0.1",
"es-object-atoms": "^1.0.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/has-symbols": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/hasown": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
"integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
"license": "MIT",
"dependencies": {
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/http-errors": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
"integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
"license": "MIT",
"dependencies": {
"depd": "~2.0.0",
"inherits": "~2.0.4",
"setprototypeof": "~1.2.0",
"statuses": "~2.0.2",
"toidentifier": "~1.0.1"
},
"engines": {
"node": ">= 0.8"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/iconv-lite": {
"version": "0.4.24",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
"license": "MIT",
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC"
},
"node_modules/ipaddr.js": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
"license": "MIT",
"engines": {
"node": ">= 0.10"
}
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
"integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/merge-descriptors": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz",
"integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/methods": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
"integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
"integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",
"license": "MIT",
"bin": {
"mime": "cli.js"
},
"engines": {
"node": ">=4"
}
},
"node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"license": "MIT",
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
"license": "MIT"
},
"node_modules/negotiator": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
"integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/object-inspect": {
"version": "1.13.4",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
"integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/on-finished": {
"version": "2.4.1",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
"integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
"license": "MIT",
"dependencies": {
"ee-first": "1.1.1"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
"integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/path-to-regexp": {
"version": "0.1.13",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz",
"integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==",
"license": "MIT"
},
"node_modules/proxy-addr": {
"version": "2.0.8",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz",
"integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==",
"license": "MIT",
"dependencies": {
"forwarded": "0.2.0",
"ipaddr.js": "1.9.1"
},
"engines": {
"node": ">= 0.10"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/qs": {
"version": "6.15.4",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.15.4.tgz",
"integrity": "sha512-d1zNHS+ltAfSgTmYjzXXH9gy9d6pEb33n0ZtUUkukA8UHhFSjv2mSYRiePyjbRiJh0g5sFJbMdAtMIg01Xf5/w==",
"license": "BSD-3-Clause",
"dependencies": {
"es-define-property": "^1.0.1",
"side-channel": "^1.1.1"
},
"engines": {
"node": ">=0.6"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/range-parser": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
"integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/raw-body": {
"version": "2.5.3",
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz",
"integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==",
"license": "MIT",
"dependencies": {
"bytes": "~3.1.2",
"http-errors": "~2.0.1",
"iconv-lite": "~0.4.24",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/send": {
"version": "0.19.2",
"resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz",
"integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==",
"license": "MIT",
"dependencies": {
"debug": "2.6.9",
"depd": "2.0.0",
"destroy": "1.2.0",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"fresh": "~0.5.2",
"http-errors": "~2.0.1",
"mime": "1.6.0",
"ms": "2.1.3",
"on-finished": "~2.4.1",
"range-parser": "~1.2.1",
"statuses": "~2.0.2"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/send/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/serve-static": {
"version": "1.16.3",
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz",
"integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==",
"license": "MIT",
"dependencies": {
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"parseurl": "~1.3.3",
"send": "~0.19.1"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/setprototypeof": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
"license": "ISC"
},
"node_modules/side-channel": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",
"integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.4",
"side-channel-list": "^1.0.1",
"side-channel-map": "^1.0.1",
"side-channel-weakmap": "^1.0.2"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-list": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",
"integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.4"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-map": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
"integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.5",
"object-inspect": "^1.13.3"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-weakmap": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
"integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.5",
"object-inspect": "^1.13.3",
"side-channel-map": "^1.0.1"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/statuses": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
"integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/toidentifier": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
"integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
"license": "MIT",
"engines": {
"node": ">=0.6"
}
},
"node_modules/type-is": {
"version": "1.6.18",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
"integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
"license": "MIT",
"dependencies": {
"media-typer": "0.3.0",
"mime-types": "~2.1.24"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/unpipe": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
"integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/utils-merge": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
"integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==",
"license": "MIT",
"engines": {
"node": ">= 0.4.0"
}
},
"node_modules/vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
"integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/ws": {
"version": "8.21.3",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz",
"integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
}
}
}
+19
View File
@@ -0,0 +1,19 @@
{
"name": "doctor-patient-clinical-summary",
"version": "1.0.0",
"description": "Multilingual Doctor-Patient Speech-to-Text Transcription and Structured Clinical Summary Pipeline using Sarvam AI and Groq LLMs",
"main": "server.js",
"scripts": {
"start": "node server.js",
"dev": "node --watch server.js",
"test": "node test_batch.js"
},
"dependencies": {
"dotenv": "^16.4.5",
"express": "^4.19.2",
"ws": "^8.18.0"
},
"engines": {
"node": ">=18"
}
}
+1253
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

+608
View File
@@ -0,0 +1,608 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Clinical Assistant — Doctor-Patient Consultation</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=Noto+Sans+Devanagari:wght@400;500;600;700&family=JetBrains+Mono:wght@500;700&display=swap"
rel="stylesheet">
<link rel="icon" type="image/png" href="favicon.png">
<link rel="shortcut icon" type="image/png" href="favicon.png">
<link rel="apple-touch-icon" href="favicon.png">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="layout-container">
<!-- ══════════════════════════════════════════════════
SIDEBAR NAVIGATION
═══════════════════════════════════════════════════ -->
<aside class="sidebar" id="sidebar">
<!-- Brand -->
<div class="sidebar-brand">
<div class="brand-icon-box">
<img src="logo.png" alt="DMH Logo" class="brand-logo-img">
</div>
<div class="brand-text">
<h1 class="brand-title">DMH Clinical AI</h1>
<span class="brand-subtitle">Deenanath Mangeshkar Hospital</span>
</div>
</div>
<!-- Navigation Menu -->
<nav class="sidebar-nav">
<a href="#dashboard" class="nav-item" data-tab="dashboard">
<span class="nav-icon">📊</span>
<span class="nav-label">Dashboard</span>
</a>
<a href="#new-consultation" class="nav-item active" data-tab="new-consultation">
<span class="nav-icon">🎙️</span>
<span class="nav-label">New Consultation</span>
<span class="nav-indicator"></span>
</a>
<a href="#past-recordings" class="nav-item" data-tab="past-recordings">
<span class="nav-icon">📁</span>
<span class="nav-label">Past Recordings</span>
</a>
<a href="#patients" class="nav-item" data-tab="patients">
<span class="nav-icon">👥</span>
<span class="nav-label">Patients</span>
</a>
<a href="#doctors" class="nav-item" data-tab="doctors">
<span class="nav-icon">🩺</span>
<span class="nav-label">Doctors</span>
</a>
<a href="#transcripts" class="nav-item" data-tab="transcripts">
<span class="nav-icon">📄</span>
<span class="nav-label">Transcripts</span>
</a>
<a href="#clinical-summaries" class="nav-item" data-tab="clinical-summaries">
<span class="nav-icon">📋</span>
<span class="nav-label">Clinical Summaries</span>
</a>
<a href="#settings" class="nav-item" data-tab="settings">
<span class="nav-icon">⚙️</span>
<span class="nav-label">Settings</span>
</a>
</nav>
<!-- Sidebar Footer / System Status -->
<div class="sidebar-footer">
<div class="system-status-card">
<div class="status-indicator-row">
<span class="status-pulse-dot"></span>
<span class="status-title">System Online</span>
</div>
<div class="status-meta">Sarvam AI Cloud (v3 STT)</div>
<div class="status-tag">Online Mode • Ready</div>
</div>
</div>
</aside>
<!-- ══════════════════════════════════════════════════
MAIN APP WRAPPER
═══════════════════════════════════════════════════ -->
<div class="main-wrapper">
<!-- Top Header -->
<header class="top-header">
<div class="header-left">
<button class="menu-toggle-btn" id="menuToggle" aria-label="Toggle Navigation">
<svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2.2" fill="none">
<line x1="3" y1="12" x2="21" y2="12"></line>
<line x1="3" y1="6" x2="21" y2="6"></line>
<line x1="3" y1="18" x2="21" y2="18"></line>
</svg>
</button>
<div class="header-logo-badge" title="Deenanath Mangeshkar Hospital">
<img src="logo.png" alt="DMH Logo" class="header-logo-img">
<span class="header-hospital-name">DMH</span>
</div>
<div class="header-divider-v"></div>
<h2 class="page-title" id="pageHeading">New Consultation</h2>
</div>
<div class="header-right">
<!-- Language Selector -->
<div class="lang-selector-wrapper">
<span class="lang-globe-icon">🌐</span>
<select id="langSelect" class="lang-dropdown">
<option value="auto" selected>Auto (मराठी / Hindi / English)</option>
<option value="mr-IN">मराठी (mr-IN)</option>
<option value="hi-IN">हिंदी (hi-IN)</option>
<option value="en-IN">English (en-IN)</option>
<option value="gu-IN">ગુજરાતી (gu-IN)</option>
<option value="kn-IN">ಕನ್ನಡ (kn-IN)</option>
<option value="ta-IN">தமிழ் (ta-IN)</option>
</select>
<span class="dropdown-arrow">▾</span>
</div>
<!-- Notification Bell -->
<button class="notif-btn" id="notifBtn" title="Notifications">
<span class="notif-icon">🔔</span>
<span class="notif-badge">3</span>
</button>
<!-- Doctor Profile Removed as requested -->
</div>
</header>
<!-- Main Content Area -->
<main class="content-area">
<!-- ══════════════════════════════════════════════════
TAB 1: NEW CONSULTATION (PRIMARY WORKFLOW)
═══════════════════════════════════════════════════ -->
<section class="tab-view active" id="view-new-consultation">
<!-- ── CARD 1: CONSULTATION DETAILS ── -->
<div class="card details-card">
<div class="card-header-row">
<div class="card-title-group">
<span class="card-header-icon">📋</span>
<h3 class="card-title">Consultation Details</h3>
</div>
<button class="btn-link-action" id="openAddPatientBtn">
<span>+ Add New Patient</span>
</button>
</div>
<div class="details-form-grid">
<!-- Patient Name -->
<div class="form-group">
<label for="patientName" class="form-label">Patient Name</label>
<div class="input-icon-box">
<span class="input-icon">👤</span>
<input type="text" id="patientName" placeholder="Select or type patient name..." value="Ramesh Patil"
autocomplete="off">
</div>
</div>
<!-- Patient ID -->
<div class="form-group">
<label for="patientId" class="form-label">Patient ID</label>
<div class="input-icon-box">
<span class="input-icon">🪪</span>
<input type="text" id="patientId" value="PT-2026-00124" readonly>
</div>
</div>
<!-- Doctor Name -->
<div class="form-group">
<label for="doctorName" class="form-label">Doctor Name</label>
<div class="input-icon-box select-box">
<span class="input-icon">🩺</span>
<select id="doctorName">
<option value="Dr. Sharma" selected>Dr. Sharma (Cardiology)</option>
<option value="Dr. Kulkarni">Dr. Kulkarni (General Physician)</option>
<option value="Dr. Joshi">Dr. Joshi (ENT Specialist)</option>
<option value="Dr. Deshmukh">Dr. Deshmukh (Neurologist)</option>
</select>
<span class="select-chevron">▾</span>
</div>
</div>
<!-- Date -->
<div class="form-group">
<label for="consultationDate" class="form-label">Date</label>
<div class="input-icon-box">
<span class="input-icon">📅</span>
<input type="text" id="consultationDate" value="09-09-2026">
</div>
</div>
</div>
</div>
<!-- ── CARD 2: LIVE RECORDING & CONTROLS ── -->
<div class="card recording-card">
<!-- Pulse & Status -->
<div class="rec-status-line">
<span class="rec-pulse-bubble" id="recPulse"></span>
<div class="timer-display" id="timer">00:00:00</div>
</div>
<div class="rec-substatus" id="recSubStatus">
<span class="mic-glyph">🎙️</span>
<span id="recStatusText">Ready to record consultation...</span>
</div>
<!-- Real-time Audio Waveform -->
<div class="visualizer-container" id="visualizerContainer">
<canvas id="waveformCanvas" width="560" height="42"></canvas>
</div>
<div class="rec-error-banner" id="recError" style="display:none;"></div>
<!-- Action Buttons Bar -->
<div class="action-buttons-row">
<button class="btn btn-record" id="startBtn">
<span class="btn-icon">▶</span>
<span class="btn-text">START RECORDING</span>
</button>
<button class="btn btn-stop" id="stopBtn" disabled>
<span class="btn-icon">⏹</span>
<span class="btn-text">STOP &amp; AUTO-SUMMARIZE</span>
</button>
<button class="btn btn-upload" id="uploadAudioBtn">
<span class="btn-icon">📁</span>
<span class="btn-text">UPLOAD AUDIO</span>
</button>
<input type="file" id="audioFileInput" accept="audio/*,.wav,.mp3,.m4a,.ogg,.webm" style="display:none;">
<button class="btn btn-demo" id="demoBtn">
<span class="btn-icon">⚡</span>
<span class="btn-text">DEMO</span>
</button>
</div>
</div>
<!-- ── CARD 3: TRANSCRIPT ── -->
<!-- ── CARD 3: TRANSCRIPT (FULL & REAL-TIME AUDIO SYNCHRONIZED) ── -->
<div class="card transcript-card">
<div class="card-header-row">
<div class="card-title-group">
<h3 class="card-title-section">TRANSCRIPT</h3>
<span class="live-realtime-badge" id="liveRealtimeBadge" style="display:none;">
<span class="live-blink-dot"></span> LIVE SYNC
</span>
</div>
<div class="header-actions">
<div class="transcript-search-box">
<span class="search-icon">🔍</span>
<input type="text" id="transcriptSearch" placeholder="Search dialogue..." autocomplete="off">
</div>
<button class="btn-sm-action" id="copyTranscriptBtn" title="Copy Full Transcript">
<span class="sm-icon">📋</span> Copy
</button>
<button class="btn-sm-action" id="clearTranscriptBtn" title="Reset/Clear">
<span class="sm-icon">↺</span> Reset
</button>
</div>
</div>
<!-- Real-time Audio Playback & Sync Control Bar -->
<div class="audio-playback-bar" id="audioPlaybackBar" style="display:none;">
<button class="btn-play-pause" id="playAudioBtn" title="Play / Pause Audio">
<span id="playIcon">▶</span>
</button>
<div class="audio-progress-container">
<input type="range" class="audio-scrubber" id="audioScrubber" min="0" max="100" value="0" step="0.1">
<div class="audio-time-row">
<span id="audioCurrentTime">00:00</span>
<span class="sync-hint">💡 Click any dialogue line to jump audio</span>
<span id="audioTotalDuration">00:00</span>
</div>
</div>
</div>
<!-- Speaker Filter Pills -->
<div class="transcript-filter-bar">
<button class="filter-pill active" data-filter="all">All Dialogue</button>
<button class="filter-pill" data-filter="doctor">🧑‍⚕️ Doctor</button>
<button class="filter-pill" data-filter="patient">🧑 Patient</button>
</div>
<!-- Full Transcript Scroll Viewport -->
<div class="transcript-viewport" id="transcriptBody">
<div class="transcript-placeholder" id="transcriptPlaceholder">
<div class="placeholder-icon">🎙️</div>
<p>Recording in progress… Transcript will appear here in real time.</p>
<span class="placeholder-sub">Speak into the microphone or click DEMO to see full real-time audio
synchronization.</span>
</div>
</div>
</div>
<!-- ── CARD 4: AI CLINICAL SUMMARY ── -->
<div class="card summary-card" id="summaryCard">
<div class="card-header-row">
<div class="card-title-group">
<span class="card-header-icon">📋</span>
<h3 class="card-title-section">AI CLINICAL SUMMARY</h3>
</div>
<div class="header-actions">
<button class="btn-sm-action" id="copySummaryBtn">
<span class="sm-icon">📋</span> Copy Summary
</button>
<button class="btn-sm-action" id="printSummaryBtn">
<span class="sm-icon">🖨️</span> Print / PDF
</button>
<button class="btn-sm-action" id="exportJsonBtn">
<span class="sm-icon">📥</span> Export JSON
</button>
</div>
</div>
<!-- Summary Content Grid -->
<div class="summary-content-grid" id="summaryBody">
<!-- Chief Complaint -->
<div class="summary-col-card">
<div class="col-card-header">Chief Complaint</div>
<div class="col-card-body" id="sumChiefComplaint">
<p class="empty-field">—</p>
</div>
</div>
<!-- Symptoms Discussed -->
<div class="summary-col-card">
<div class="col-card-header">Symptoms Discussed</div>
<div class="col-card-body" id="sumSymptoms">
<p class="empty-field">—</p>
</div>
</div>
<!-- Doctor's Recommendation -->
<div class="summary-col-card">
<div class="col-card-header">Doctor's Recommendation / Diagnosis</div>
<div class="col-card-body" id="sumAssessment">
<p class="empty-field">—</p>
</div>
</div>
<!-- Medical History -->
<div class="summary-col-card full-span">
<div class="col-card-header">Patient History &amp; Comorbidities</div>
<div class="col-card-body" id="sumHistory">
<p class="empty-field">—</p>
</div>
</div>
<!-- Prescription & Plan -->
<div class="summary-col-card full-span highlight-plan">
<div class="col-card-header">Prescription, Tests &amp; Treatment Plan (Rx)</div>
<div class="col-card-body" id="sumPlan">
<p class="empty-field">—</p>
</div>
</div>
</div>
</div>
</section>
<!-- ══════════════════════════════════════════════════
TAB 2: DASHBOARD VIEW
═══════════════════════════════════════════════════ -->
<section class="tab-view" id="view-dashboard">
<div class="dash-stats-grid">
<div class="dash-stat-card">
<div class="stat-icon-wrap blue">📈</div>
<div class="stat-info">
<span class="stat-num">142</span>
<span class="stat-name">Total Consultations</span>
</div>
</div>
<div class="dash-stat-card">
<div class="stat-icon-wrap green">👥</div>
<div class="stat-info">
<span class="stat-num">98</span>
<span class="stat-name">Active Patients</span>
</div>
</div>
<div class="dash-stat-card">
<div class="stat-icon-wrap purple">⏱️</div>
<div class="stat-info">
<span class="stat-num">486 mins</span>
<span class="stat-name">Audio Transcribed</span>
</div>
</div>
<div class="dash-stat-card">
<div class="stat-icon-wrap amber">⚡</div>
<div class="stat-info">
<span class="stat-num">99.4%</span>
<span class="stat-name">AI Accuracy Rate</span>
</div>
</div>
</div>
<div class="card mt-4">
<div class="card-header-row">
<h3 class="card-title">Recent Clinical Consultations</h3>
</div>
<div class="recent-table-wrap">
<table class="data-table">
<thead>
<tr>
<th>Patient</th>
<th>ID</th>
<th>Doctor</th>
<th>Language</th>
<th>Duration</th>
<th>Date</th>
<th>Action</th>
</tr>
</thead>
<tbody id="recentTableBody">
<tr>
<td><strong>Ramesh Patil</strong></td>
<td>PT-2026-00124</td>
<td>Dr. Sharma (Cardiology)</td>
<td><span class="badge-lang">मराठी</span></td>
<td>03:42</td>
<td>Today, 10:15 AM</td>
<td><button class="table-btn" onclick="app.loadDemoRecord('ramesh')">View Summary</button></td>
</tr>
<tr>
<td><strong>Sunita Deshmukh</strong></td>
<td>PT-2026-00123</td>
<td>Dr. Kulkarni (General)</td>
<td><span class="badge-lang">मराठी</span></td>
<td>04:18</td>
<td>Yesterday</td>
<td><button class="table-btn" onclick="app.loadDemoRecord('sunita')">View Summary</button></td>
</tr>
<tr>
<td><strong>Amit Verma</strong></td>
<td>PT-2026-00122</td>
<td>Dr. Joshi (ENT)</td>
<td><span class="badge-lang">हिंदी</span></td>
<td>02:50</td>
<td>07-09-2026</td>
<td><button class="table-btn" onclick="app.loadDemoRecord('amit')">View Summary</button></td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
<!-- ══════════════════════════════════════════════════
TAB 3: PAST RECORDINGS VIEW
═══════════════════════════════════════════════════ -->
<section class="tab-view" id="view-past-recordings">
<div class="card">
<div class="card-header-row">
<h3 class="card-title">Archived Doctor-Patient Audio &amp; Transcripts</h3>
</div>
<div class="recordings-list" id="recordingsList">
<!-- Dynamically populated or demo records -->
</div>
</div>
</section>
<!-- ══════════════════════════════════════════════════
TAB 4: PATIENTS VIEW
═══════════════════════════════════════════════════ -->
<section class="tab-view" id="view-patients">
<div class="card">
<div class="card-header-row">
<h3 class="card-title">Patient Directory</h3>
<button class="btn-primary-sm" id="btnAddNewPatientTab">+ Add Patient</button>
</div>
<div class="patients-grid" id="patientsGrid">
<!-- Patient Cards -->
</div>
</div>
</section>
<!-- ══════════════════════════════════════════════════
TAB 5: DOCTORS VIEW
═══════════════════════════════════════════════════ -->
<section class="tab-view" id="view-doctors">
<div class="card">
<div class="card-header-row">
<h3 class="card-title">Hospital Medical Staff</h3>
</div>
<div class="doctors-grid">
<div class="doctor-card-box">
<div class="doc-badge-avatar">🩺</div>
<h4>Dr. Sharma</h4>
<p class="doc-spec">Senior Cardiologist</p>
<span class="doc-dep">Cardiology Dept</span>
</div>
<div class="doctor-card-box">
<div class="doc-badge-avatar">🩺</div>
<h4>Dr. Kulkarni</h4>
<p class="doc-spec">Chief Medical Officer</p>
<span class="doc-dep">General Medicine</span>
</div>
<div class="doctor-card-box">
<div class="doc-badge-avatar">🩺</div>
<h4>Dr. Joshi</h4>
<p class="doc-spec">ENT Specialist</p>
<span class="doc-dep">Otolaryngology</span>
</div>
<div class="doctor-card-box">
<div class="doc-badge-avatar">🩺</div>
<h4>Dr. Deshmukh</h4>
<p class="doc-spec">Consultant Neurologist</p>
<span class="doc-dep">Neurosciences</span>
</div>
</div>
</div>
</section>
<!-- ══════════════════════════════════════════════════
TAB 6: SETTINGS VIEW
═══════════════════════════════════════════════════ -->
<section class="tab-view" id="view-settings">
<div class="card">
<div class="card-header-row">
<h3 class="card-title">AI &amp; Speech Engine Configuration</h3>
</div>
<div class="settings-form-box">
<div class="form-group mb-3">
<label class="form-label">Sarvam Speech-to-Text Model</label>
<input type="text" value="saaras:v4 (16kHz PCM, Real-time Indic)" readonly>
</div>
<div class="form-group mb-3">
<label class="form-label">Sarvam Clinical LLM Model</label>
<input type="text" value="sarvam-105b (Medical Reasoning & Extraction)" readonly>
</div>
<div class="form-group mb-3">
<label class="form-label">Default Consultation Language</label>
<select class="form-control">
<option selected>Marathi (mr-IN)</option>
<option>Hindi (hi-IN)</option>
<option>English (en-IN)</option>
</select>
</div>
<div class="form-group">
<label class="form-label">Microphone Audio Input Device</label>
<select class="form-control" id="audioDeviceSelect">
<option value="default">Default System Microphone</option>
</select>
</div>
</div>
</div>
</section>
</main>
</div>
</div>
<!-- ══════════════════════════════════════════════════
MODAL: ADD NEW PATIENT
═══════════════════════════════════════════════════ -->
<div class="modal-overlay" id="patientModal">
<div class="modal-card">
<div class="modal-header">
<h3>Add New Patient</h3>
<button class="modal-close-btn" id="closePatientModal">&times;</button>
</div>
<div class="modal-body">
<div class="form-group mb-3">
<label class="form-label">Full Name</label>
<input type="text" id="newPatientName" placeholder="e.g. Ramesh Patil">
</div>
<div class="form-group mb-3">
<label class="form-label">Age &amp; Gender</label>
<div class="input-row-flex">
<input type="number" id="newPatientAge" placeholder="Age" style="width:100px;">
<select id="newPatientGender" style="flex:1;">
<option>Male</option>
<option>Female</option>
<option>Other</option>
</select>
</div>
</div>
<div class="form-group mb-3">
<label class="form-label">Contact Number</label>
<input type="tel" id="newPatientPhone" placeholder="+91 98765 43210">
</div>
<div class="form-group">
<label class="form-label">Known Allergies / Medical Conditions</label>
<input type="text" id="newPatientMedicalNotes" placeholder="e.g. Hypertension, Penicillin Allergy">
</div>
</div>
<div class="modal-footer">
<button class="btn-cancel" id="cancelPatientModal">Cancel</button>
<button class="btn-save-patient" id="savePatientBtn">Save &amp; Select Patient</button>
</div>
</div>
</div>
<!-- Toast Container -->
<div class="toast-notification" id="toastBox">Notification message</div>
<script src="app.js"></script>
</body>
</html>
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

+368
View File
@@ -0,0 +1,368 @@
(() => {
'use strict';
// ── Config ─────────────────────────────────────────────────────────────────
// Point this to wherever your FastAPI or Express backend is running
// Empty string '' means same-origin (the Node.js server)
const BACKEND = '';
// ── DOM refs (matching existing HTML IDs exactly) ──────────────────────────
const startBtn = document.getElementById('startBtn');
const stopBtn = document.getElementById('stopBtn');
const timerEl = document.getElementById('timer');
const liveBadge = document.getElementById('liveBadge');
const serverStatus = document.getElementById('serverStatus');
const recError = document.getElementById('recError');
const transcriptBody = document.getElementById('transcriptBody');
const summaryBtn = document.getElementById('summaryBtn');
const clearBtn = document.getElementById('clearBtn');
const summaryCard = document.getElementById('summaryCard');
const summaryBody = document.getElementById('summaryBody');
// ── State ──────────────────────────────────────────────────────────────────
let mediaRecorder = null;
let recordedChunks = [];
let timerInterval = null;
let secondsElapsed = 0;
let lastTranscript = '';
// ── Helpers ────────────────────────────────────────────────────────────────
function fmtTime(s) {
const h = String(Math.floor(s / 3600)).padStart(2, '0');
const m = String(Math.floor((s % 3600) / 60)).padStart(2, '0');
const sec = String(s % 60).padStart(2, '0');
return `${h}:${m}:${sec}`;
}
function escHtml(str) {
const d = document.createElement('div');
d.innerText = str;
return d.innerHTML;
}
function showError(msg) {
recError.textContent = msg;
recError.style.display = 'block';
}
function clearError() {
recError.textContent = '';
recError.style.display = 'none';
}
function setStatus(msg, type = '') {
serverStatus.textContent = msg;
serverStatus.className = 'status-text' + (type ? ` ${type}` : '');
}
// ── Health check on load ───────────────────────────────────────────────────
async function checkHealth() {
try {
const res = await fetch(`${BACKEND}/api/health`);
const data = await res.json();
if (data.sarvam_key_configured || data.ok) {
setStatus('✔ Backend ready', 'ok');
} else {
setStatus('✘ Backend configuration error', 'bad');
startBtn.disabled = true;
}
} catch {
setStatus('✘ Cannot reach backend at ' + BACKEND, 'bad');
startBtn.disabled = true;
}
}
// ── Choose best supported MIME type ───────────────────────────────────────
function getSupportedMimeType() {
const types = [
'audio/webm;codecs=opus',
'audio/webm',
'audio/ogg;codecs=opus',
'audio/ogg',
'audio/mp4',
];
return types.find(t => MediaRecorder.isTypeSupported(t)) || '';
}
// ── Start recording ────────────────────────────────────────────────────────
async function startRecording() {
clearError();
recordedChunks = [];
// Request microphone
let stream;
try {
stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
} catch (err) {
if (err.name === 'NotAllowedError' || err.name === 'PermissionDeniedError') {
showError('Microphone permission denied. Please allow microphone access in your browser settings.');
} else if (err.name === 'NotFoundError') {
showError('No microphone found. Please connect a microphone and try again.');
} else {
showError(`Microphone error: ${err.message}`);
}
return;
}
// Create MediaRecorder
const mimeType = getSupportedMimeType();
try {
mediaRecorder = new MediaRecorder(stream, mimeType ? { mimeType } : {});
} catch (err) {
showError(`Could not start MediaRecorder: ${err.message}`);
stream.getTracks().forEach(t => t.stop());
return;
}
mediaRecorder.ondataavailable = (e) => {
if (e.data && e.data.size > 0) recordedChunks.push(e.data);
};
mediaRecorder.onerror = (e) => {
showError(`Recording error: ${e.error?.message || 'Unknown error'}`);
};
mediaRecorder.start(250); // collect data every 250 ms
// Update UI → recording state
startBtn.disabled = true;
stopBtn.disabled = false;
liveBadge.classList.add('on');
summaryBtn.disabled = true;
summaryCard.style.display = 'none';
lastTranscript = '';
transcriptBody.innerHTML = '<p class="placeholder-text">Recording in progress… press ⏹ Stop &amp; Transcribe when done.</p>';
// Start timer
secondsElapsed = 0;
timerEl.textContent = '🔴 ' + fmtTime(0);
timerInterval = setInterval(() => {
secondsElapsed++;
timerEl.textContent = '🔴 ' + fmtTime(secondsElapsed);
}, 1000);
setStatus('🎙️ Recording…');
}
// ── Stop recording → send to backend ──────────────────────────────────────
function stopRecording() {
if (!mediaRecorder || mediaRecorder.state === 'inactive') return;
// Stop timer
clearInterval(timerInterval);
timerInterval = null;
// Stop all mic tracks
mediaRecorder.stream.getTracks().forEach(t => t.stop());
// When recorder finishes flushing, send the audio
mediaRecorder.onstop = async () => {
await sendAudioToBackend();
};
mediaRecorder.stop();
// Update UI → processing state
startBtn.disabled = true;
stopBtn.disabled = true;
liveBadge.classList.remove('on');
timerEl.textContent = '⏳ ' + fmtTime(secondsElapsed);
setStatus('Processing transcript…');
transcriptBody.innerHTML = `
<div class="processing-row">
<span class="spinner"></span>
Processing transcript, please wait…
</div>`;
}
// ── Upload audio blob → /api/transcribe ────────────────────────────────────
async function sendAudioToBackend() {
if (recordedChunks.length === 0) {
showError('No audio was recorded. Please try again.');
resetButtons();
return;
}
const mimeType = recordedChunks[0].type || 'audio/webm';
const extension = mimeType.includes('ogg') ? 'ogg' : mimeType.includes('mp4') ? 'mp4' : 'webm';
const audioBlob = new Blob(recordedChunks, { type: mimeType });
const formData = new FormData();
formData.append('file', audioBlob, `recording.${extension}`);
try {
const res = await fetch(`${BACKEND}/api/transcribe`, {
method: 'POST',
body: formData,
// Do NOT set Content-Type header — browser sets it automatically with boundary
});
let data;
try {
data = await res.json();
} catch {
throw new Error(`Server returned non-JSON response (HTTP ${res.status})`);
}
if (!res.ok) {
throw new Error(data.detail || data.error || `HTTP ${res.status}`);
}
lastTranscript = (data.transcript || '').trim();
renderTranscript(lastTranscript, data.language || '');
timerEl.textContent = '✅ ' + fmtTime(secondsElapsed);
setStatus('✔ Transcript ready', 'ok');
if (lastTranscript) summaryBtn.disabled = false;
} catch (err) {
// Classify the error for the user
let msg = err.message || 'Unknown error';
if (err instanceof TypeError && msg.includes('fetch')) {
msg = `Cannot reach backend at ${BACKEND}. Is the server running?`;
}
showError('Transcription failed: ' + msg);
transcriptBody.innerHTML = '<p class="placeholder-text">Transcription failed. Please try again.</p>';
timerEl.textContent = '🔴 ' + fmtTime(secondsElapsed);
setStatus('Transcription failed', 'bad');
}
resetButtons();
}
function resetButtons() {
startBtn.disabled = false;
stopBtn.disabled = true;
}
// ── Render transcript in existing #transcriptBody ─────────────────────────
function renderTranscript(text, language) {
if (!text) {
transcriptBody.innerHTML = '<p class="placeholder-text">No speech detected in the recording.</p>';
return;
}
// Split on sentence boundaries and render each as an utterance block
// (Doctor / Patient alternating — best-effort without diarization)
const sentences = text.match(/[^.!?।\n]+[.!?।\n]*/g) || [text];
const langTag = language && language !== 'unknown'
? `<span class="utt-ts">[${escHtml(language)}]</span>`
: '';
let html = '';
sentences.forEach((sentence, i) => {
sentence = sentence.trim();
if (!sentence) return;
const isDoc = i % 2 === 0;
const icon = isDoc ? '🧑‍⚕️' : '🧑';
const name = isDoc ? 'Doctor' : 'Patient';
const cls = isDoc ? '' : 'patient';
const ts = fmtTime(Math.round((i / sentences.length) * secondsElapsed));
html += `
<div class="utt">
<div class="utt-meta">
<span class="utt-icon">${icon}</span>
<span class="utt-name ${cls}">${name}</span>
<span class="utt-ts">[${ts}]</span>
${i === 0 ? langTag : ''}
</div>
<div class="utt-text">${escHtml(sentence)}</div>
</div>`;
});
transcriptBody.innerHTML = html;
transcriptBody.scrollTop = transcriptBody.scrollHeight;
}
// ── Reset / Clear ──────────────────────────────────────────────────────────
function resetAll() {
lastTranscript = '';
recordedChunks = [];
transcriptBody.innerHTML = '<p class="placeholder-text">Transcript will appear here once recording starts…</p>';
summaryCard.style.display = 'none';
summaryBtn.disabled = true;
timerEl.textContent = '🔴 00:00:00';
clearError();
setStatus('');
}
// ── Generate AI Summary ────────────────────────────────────────────────────
async function generateSummary() {
if (!lastTranscript.trim()) return;
summaryCard.style.display = 'block';
summaryBody.innerHTML = `
<div class="summary-loading">
<span class="spinner"></span> Generating summary…
</div>`;
summaryBtn.disabled = true;
try {
const res = await fetch(`${BACKEND}/api/summary`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ transcript: lastTranscript }),
});
let data;
try { data = await res.json(); } catch { throw new Error('Non-JSON response from backend'); }
if (!res.ok) throw new Error(data.detail || data.error || `HTTP ${res.status}`);
const s = data.summary;
if (s.raw_text) {
summaryBody.innerHTML = `
<div class="summary-row">
<span class="s-key">Summary</span>
<span class="s-val">${escHtml(s.raw_text)}</span>
</div>`;
} else {
renderSummary(s);
}
} catch (err) {
summaryBody.innerHTML = `
<div class="summary-row">
<span class="s-key">Error</span>
<span class="s-val" style="color:var(--red)">${escHtml(err.message)}</span>
</div>`;
}
summaryBtn.disabled = false;
}
function renderSummary(s) {
function listHtml(arr) {
if (!arr || !arr.length) return 'Not mentioned';
return '<ul>' + arr.map(x => `<li>${escHtml(String(x))}</li>`).join('') + '</ul>';
}
summaryBody.innerHTML = `
<div class="summary-row">
<span class="s-key">Chief Complaint</span>
<span class="s-val">${escHtml(s.chief_complaint || 'Not mentioned')}</span>
</div>
<div class="summary-row">
<span class="s-key">Symptoms</span>
<span class="s-val">${listHtml(s.symptoms)}</span>
</div>
<div class="summary-row">
<span class="s-key">Diagnosis</span>
<span class="s-val">${escHtml(s.assessment || 'Not mentioned')}</span>
</div>
<div class="summary-row">
<span class="s-key">Prescription</span>
<span class="s-val">${listHtml(s.plan)}</span>
</div>`;
}
// ── Event listeners ────────────────────────────────────────────────────────
startBtn.addEventListener('click', startRecording);
stopBtn.addEventListener('click', stopRecording);
clearBtn.addEventListener('click', resetAll);
summaryBtn.addEventListener('click', generateSummary);
// ── Init ───────────────────────────────────────────────────────────────────
checkHealth();
})();
+1519
View File
File diff suppressed because it is too large Load Diff
+181
View File
@@ -0,0 +1,181 @@
const fs = require('fs');
const path = require('path');
const dotenv = require('dotenv');
dotenv.config();
const API_KEY = process.env.SARVAM_API_KEY;
const BASE_URL = 'https://api.sarvam.ai';
const AUDIO_FILE = 'dummy.wav';
async function main() {
if (!fs.existsSync(AUDIO_FILE)) {
console.error("Audio file not found!");
return;
}
console.log("1. Initialize Batch Job...");
const initRes = await fetch(`${BASE_URL}/speech-to-text/job/v1`, {
method: 'POST',
headers: {
'api-subscription-key': API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({
job_parameters: {
model: "saaras:v4",
mode: "transcribe",
with_diarization: true,
with_timestamps: true,
language_code: "unknown"
}
})
});
const initData = await initRes.json();
const jobId = initData.job_id;
console.log("2. Get Upload Link...");
const uploadRes = await fetch(`${BASE_URL}/speech-to-text/job/v1/upload-files`, {
method: 'POST',
headers: {
'api-subscription-key': API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({
job_id: jobId,
files: [AUDIO_FILE]
})
});
const uploadData = await uploadRes.json();
const uploadUrl = uploadData.upload_urls[AUDIO_FILE].file_url;
console.log("3. Upload File...");
const fileContent = fs.readFileSync(path.join(__dirname, AUDIO_FILE));
const putRes = await fetch(uploadUrl, {
method: 'PUT',
headers: {
'x-ms-blob-type': 'BlockBlob',
'Content-Type': 'audio/wav'
},
body: fileContent
});
console.log("Upload Status:", putRes.status);
console.log("4. Start Job...");
await fetch(`${BASE_URL}/speech-to-text/job/v1/${jobId}/start`, {
method: 'POST',
headers: {
'api-subscription-key': API_KEY,
'Content-Type': 'application/json'
}
});
console.log("5. Polling Status...");
let statusData;
for (let i = 0; i < 30; i++) {
const statusRes = await fetch(`${BASE_URL}/speech-to-text/job/v1/${jobId}/status`, {
method: 'GET',
headers: {
'api-subscription-key': API_KEY
}
});
statusData = await statusRes.json();
console.log(` State: ${statusData.job_state}`);
if (statusData.job_state === "Completed" || statusData.job_state === "Failed") break;
await new Promise(r => setTimeout(r, 5000));
}
if (statusData.job_state === 'Completed') {
const outFile = statusData.job_details[0].outputs[0].file_name;
console.log("6. Get Download Links for", outFile);
const dlRes = await fetch(`${BASE_URL}/speech-to-text/job/v1/download-files`, {
method: 'POST',
headers: {
'api-subscription-key': API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({
job_id: jobId,
files: [outFile]
})
});
const dlData = await dlRes.json();
const dlUrl = dlData.download_urls[outFile].file_url;
console.log("7. Downloading Result...");
const resultRes = await fetch(dlUrl);
const resultData = await resultRes.json();
// Parse words
let conversationText = "";
if (resultData.timestamps && resultData.timestamps.words) {
const words = resultData.timestamps.words;
const speakers = resultData.timestamps.speaker || [];
let currentSpk = null;
let currentSentence = [];
let convLines = [];
for (let i = 0; i < words.length; i++) {
const word = words[i];
let spk = "Unknown";
if (speakers && speakers.length > i) {
spk = speakers[i];
} else if (resultData.words && resultData.words[i] && resultData.words[i].speaker) {
spk = resultData.words[i].speaker; // fallback
}
if (currentSpk === null) currentSpk = spk;
if (spk !== currentSpk) {
convLines.push(`**Speaker ${currentSpk}:** ${currentSentence.join(' ')}`);
currentSpk = spk;
currentSentence = [word];
} else {
currentSentence.push(word);
}
}
if (currentSentence.length > 0) {
convLines.push(`**Speaker ${currentSpk}:** ${currentSentence.join(' ')}`);
}
conversationText = convLines.join('\n');
} else {
// Fallback for batch output format
if (resultData.transcript) {
conversationText = resultData.transcript;
}
}
console.log("\n8. Getting Summary from NVIDIA Nemotron (OpenRouter)...");
const prompt = `Please summarize the following conversation:\n\n${conversationText}\n\nSummary:`;
try {
const nemotronRes = await fetch('https://openrouter.ai/api/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer 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`
},
body: JSON.stringify({
model: 'nvidia/nemotron-3-ultra-550b-a55b:free', // Using user provided model
messages: [
{ role: "user", content: prompt }
]
})
});
const nemotronData = await nemotronRes.json();
console.log("\n--- SUMMARY ---");
if (nemotronData.choices && nemotronData.choices.length > 0) {
console.log(nemotronData.choices[0].message.content);
} else {
console.log("No summary generated or error occurred:", nemotronData);
}
} catch(err) {
console.error("Failed to call Nemotron", err);
}
} else {
console.log("Job failed:", statusData);
}
}
main().catch(console.error);
+86
View File
@@ -0,0 +1,86 @@
import sys
import json
import warnings
import os
from dotenv import load_dotenv
warnings.filterwarnings("ignore")
def main():
if len(sys.argv) < 3:
print(json.dumps({"error": "No audio file or output file provided"}))
sys.exit(1)
audio_path = sys.argv[1]
out_path = sys.argv[2]
def write_output(data):
with open(out_path, 'w', encoding='utf-8') as f:
json.dump(data, f)
try:
# Load environment variables to get HF_TOKEN
load_dotenv("backend/.env")
hf_token = os.getenv("HF_TOKEN")
if not hf_token:
write_output({"error": "HF_TOKEN not found in backend/.env"})
sys.exit(1)
hf_token = hf_token.strip()
try:
import torch # type: ignore
from pyannote.audio import Pipeline # type: ignore
except ImportError:
write_output({"error": "Pyannote or Torch not installed"})
sys.exit(1)
# Load Pyannote Diarization Pipeline
pipeline = Pipeline.from_pretrained(
"pyannote/speaker-diarization-3.1",
token=hf_token
)
if torch.cuda.is_available():
pipeline.to(torch.device("cuda"))
import soundfile as sf
import numpy as np
# Load audio using soundfile to bypass torchaudio/torchcodec FFmpeg dependency
audio_data, sample_rate = sf.read(audio_path, dtype='float32')
# Ensure audio is 2D (channels, frames)
if len(audio_data.shape) == 1:
audio_data = audio_data.reshape(1, -1)
else:
audio_data = audio_data.T
waveform = torch.from_numpy(audio_data)
audio_in_memory = {"waveform": waveform, "sample_rate": sample_rate}
# Run Diarization
diarization = pipeline(audio_in_memory, num_speakers=2)
if hasattr(diarization, "speaker_diarization"):
diarization = diarization.speaker_diarization
# Pyannote output is Annotation, iterate and extract segments
out_segments = []
speaker_map = {}
speaker_idx = 0
for turn, _, speaker in diarization.itertracks(yield_label=True):
if speaker not in speaker_map:
speaker_map[speaker] = speaker_idx
speaker_idx += 1
out_segments.append([turn.start, turn.end, speaker_map[speaker]])
write_output({"segments": out_segments})
except Exception as e:
write_output({"error": str(e)})
if __name__ == "__main__":
main()
+137
View File
@@ -0,0 +1,137 @@
import os
import json
import urllib.request
import asyncio
SARVAM_API_KEY = None
if os.path.exists('.env'):
with open('.env', encoding='utf-8') as f:
for line in f:
if line.startswith('SARVAM_API_KEY='):
SARVAM_API_KEY = line.strip().split('=', 1)[1].strip('"\' ')
async def main():
audio_file = "test.wav"
if not os.path.exists(audio_file):
print(f"File {audio_file} not found. Trying dummy.wav...")
audio_file = "dummy.wav"
if not os.path.exists(audio_file):
print("No audio file found!")
return
print(f"Processing {audio_file} with Sarvam API...")
with open(audio_file, "rb") as f:
audio_data = f.read()
boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW'
body = (
f'--{boundary}\r\n'
f'Content-Disposition: form-data; name="file"; filename="audio.wav"\r\n'
f'Content-Type: audio/wav\r\n\r\n'
).encode('utf-8') + audio_data + (
f'\r\n--{boundary}\r\n'
f'Content-Disposition: form-data; name="model"\r\n\r\n'
f'saaras:v4\r\n'
f'--{boundary}\r\n'
f'Content-Disposition: form-data; name="mode"\r\n\r\n'
f'translate\r\n'
f'--{boundary}\r\n'
f'Content-Disposition: form-data; name="with_diarization"\r\n\r\n'
f'true\r\n'
f'--{boundary}--\r\n'
).encode('utf-8')
req = urllib.request.Request(
"https://api.sarvam.ai/speech-to-text",
data=body,
headers={
"api-subscription-key": SARVAM_API_KEY or "",
"Content-Type": f"multipart/form-data; boundary={boundary}"
}
)
try:
with urllib.request.urlopen(req) as resp:
res = json.loads(resp.read().decode('utf-8'))
except Exception as e:
print("Sarvam API Error:", e)
return
print("Sarvam API Error:", resp.status_code, resp.text)
# Let's try just speech-to-text if translate fails
print("Falling back to speech-to-text...")
resp = await client.post(
"https://api.sarvam.ai/speech-to-text",
headers={"api-subscription-key": SARVAM_API_KEY},
files={"file": ("audio.wav", audio_data, "audio/wav")},
data={
"model": "saaras:v4",
"with_diarization": "true"
}
)
if resp.status_code != 200:
print("Fallback Sarvam API Error:", resp.status_code, resp.text)
return
res = resp.json()
print("\n--- Sarvam Output ---\n")
# Determine format
transcript_text = res.get("transcript", "")
print("Transcript:", transcript_text)
# Diarization logic might be in "words" array or "transcript" format
conversation = transcript_text
if "words" in res and res["words"]:
words = res["words"]
current_speaker = None
sentences = []
current_sentence = []
for w in words:
speaker = w.get("speaker", "Unknown")
word = w.get("word", "")
if speaker != current_speaker:
if current_speaker is not None:
sentences.append(f"Speaker {current_speaker}: {' '.join(current_sentence)}")
current_speaker = speaker
current_sentence = [word]
else:
current_sentence.append(word)
if current_sentence:
sentences.append(f"Speaker {current_speaker}: {' '.join(current_sentence)}")
conversation = "\n".join(sentences)
print("\n--- Diarized Conversation ---")
print(conversation)
# 2. Summarization using Qwen2.5 (Ollama)
if not conversation:
print("No transcription found to summarize.")
return
print("\n--- Requesting Summary from Qwen2.5 ---")
prompt = f"Please summarize the following conversation:\n\n{conversation}"
ollama_resp = await client.post(
"http://localhost:11434/api/generate",
json={
"model": "qwen2.5",
"prompt": prompt,
"stream": False
}
)
if ollama_resp.status_code == 200:
summary = ollama_resp.json().get("response", "")
print("\n--- Summary ---")
print(summary)
else:
print("Ollama Error:", ollama_resp.status_code, ollama_resp.text)
if __name__ == "__main__":
asyncio.run(main())
+1014
View File
File diff suppressed because it is too large Load Diff
+58
View File
@@ -0,0 +1,58 @@
import asyncio
import urllib.request
import json
import sys
import hybrid_diarization
async def summarize_with_qwen(conversation_text):
print("\n[*] Sending to local Qwen2.5 for summarization...")
prompt = f"Please summarize the following conversation:\n\n{conversation_text}\n\nSummary:"
data = json.dumps({
"model": "qwen2.5",
"prompt": prompt,
"stream": False
}).encode('utf-8')
req = urllib.request.Request(
"http://localhost:11434/api/generate",
data=data,
headers={'Content-Type': 'application/json'}
)
try:
with urllib.request.urlopen(req) as response:
result = json.loads(response.read().decode('utf-8'))
return result.get("response", "")
except Exception as e:
return f"Exception calling Ollama: {e}"
async def main():
audio_path = "test.wav"
print(f"[*] Calling Sarvam STT API for transcription... (with_timestamps=true)")
sarvam_res = hybrid_diarization.get_sarvam_transcript(audio_path)
print(f"[*] Running local Nvidia Sortformer model for diarization...")
nemo_segments = hybrid_diarization.get_nemo_segments(audio_path)
print(f"[*] Aligning Sarvam transcript words with Nvidia speaker segments...")
dialogue = hybrid_diarization.align_words_to_segments(sarvam_res, nemo_segments)
print("\n--- FINAL HYBRID DIALOGUE ---\n")
conv_lines = []
for spk, text in dialogue:
line = f"**{spk}:** {text}"
print(line)
conv_lines.append(line)
conversation_text = "\n".join(conv_lines)
if conversation_text:
summary = await summarize_with_qwen(conversation_text)
print("\n--- SUMMARY (Qwen2.5) ---\n")
print(summary)
else:
print("\nNo dialogue found to summarize.")
if __name__ == "__main__":
asyncio.run(main())
BIN
View File
Binary file not shown.
+48
View File
@@ -0,0 +1,48 @@
import os, urllib.request, json, sys
sys.stdout.reconfigure(encoding='utf-8')
api_key = None
with open('.env') as f:
for line in f:
if line.startswith('SARVAM_API_KEY='):
api_key = line.strip().split('=', 1)[1].strip('"\' ')
test_text = """नमस्कार या बसा काय त्रास होतोय तुम्हाला नमस्कार डॉक्टर मला गेले दोन दिवस झाले खोकला येतोय ताप आहे का हो थोडा ताप आहे ठीक आहे औषध देतो 3 दिवस घ्या"""
DIARIZE_PROMPT = """You are a STRICT verbatim medical conversation diarization assistant.
Your task is to split the exact transcribed words into Doctor and Patient speaking turns.
ABSOLUTE ANTI-HALLUCINATION RULES:
1. ZERO HALLUCINATIONS: Do NOT invent, assume, add, or alter ANY words. All output words must come directly from the transcript verbatim.
2. DOCTOR TURNS:
- Greeting and opening: "नमस्कार या बसा काय त्रास होतोय तुम्हाला"
- Diagnostic questions: "ताप आहे का", "कधीपासून", "कुठे दुखतंय", "काय खाल्ले होते"
- Advice and prescription: "ठीक आहे औषध देतो", "3 दिवस घ्या", "तपासून पाहतो", "सोनोग्राफी करू"
3. PATIENT TURNS:
- Symptoms and complaints: "मला गेले दोन दिवस झाले खोकला येतोय", "पोटात दुखत आहे"
- Answers to doctor: "हो थोडा ताप आहे", "नाही", "दोन दिवसांपासून"
4. OUTPUT FORMAT: Output ONLY "**Doctor:** " and "**Patient:** " turns with exact words from transcript."""
req = urllib.request.Request(
'https://api.sarvam.ai/v1/chat/completions',
data=json.dumps({
'model': 'sarvam-105b-conversations',
'temperature': 0.0,
'max_tokens': 1500,
'messages': [
{'role': 'system', 'content': DIARIZE_PROMPT},
{'role': 'user', 'content': f"Transcript:\n{test_text.strip()}"}
]
}).encode('utf-8'),
headers={
'Content-Type': 'application/json',
'api-subscription-key': api_key
}
)
try:
with urllib.request.urlopen(req) as resp:
res = json.loads(resp.read().decode('utf-8'))
print("Diarization Output:\n" + res['choices'][0]['message']['content'])
except Exception as e:
print("Error:", e)
+25
View File
@@ -0,0 +1,25 @@
const fs = require('fs');
const dotenv = require('dotenv');
dotenv.config();
async function test() {
const formData = new FormData();
formData.append('model', 'saaras:v4');
formData.append('with_diarization', 'true');
// Create a dummy text file to pass validation if needed
formData.append('file', new Blob(['test'], { type: 'audio/wav' }), 'test.wav');
const res = await fetch('https://api.sarvam.ai/speech-to-text', {
method: 'POST',
headers: {
'api-subscription-key': process.env.SARVAM_API_KEY
},
body: formData
});
console.log(res.status);
console.log(await res.text());
}
test();
+25
View File
@@ -0,0 +1,25 @@
import asyncio
import httpx
import os
import base64
from dotenv import load_dotenv
load_dotenv()
SARVAM_API_KEY = os.getenv("SARVAM_API_KEY", "")
async def test_batch():
async with httpx.AsyncClient() as client:
# Step 1: create job
create_resp = await client.post(
"https://api.sarvam.ai/v1/speech-to-text",
headers={"api-subscription-key": SARVAM_API_KEY},
json={
"model": "saaras:v4",
"with_diarization": True
}
)
print("Create Job:")
print(create_resp.status_code)
print(create_resp.text)
asyncio.run(test_batch())
+20
View File
@@ -0,0 +1,20 @@
const fs = require('fs');
const dotenv = require('dotenv');
dotenv.config();
async function test() {
const formData = new FormData();
formData.append('model', 'saaras:v4');
formData.append('with_diarization', 'true');
// Need a valid audio file to upload
const buf = fs.readFileSync('./backend/test.wav'); // We need a real wav or we can create a valid one
formData.append('file', new Blob([buf], { type: 'audio/wav' }), 'test.wav');
// Let's try POST to https://api.sarvam.ai/speech-to-text/batch or something?
// Wait, the python sdk uses `client.speech_to_text_job.create_job`
// The url is probably something like https://api.sarvam.ai/v1/speech-to-text/jobs or /v1/stt/batch
// Let's search npm for sarvamai or check the sdk source.
}
test();
+27
View File
@@ -0,0 +1,27 @@
const fs = require('fs');
const dotenv = require('dotenv');
dotenv.config();
async function test() {
const ep = 'https://api.sarvam.ai/speech-to-text/job/v1';
console.log("Creating Job...");
let res = await fetch(ep, {
method: 'POST',
headers: {
'api-subscription-key': process.env.SARVAM_API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({
files: ["test.wav"],
job_parameters: {
model: "saaras:v4",
with_diarization: true
}
})
});
console.log(res.status);
let data = await res.json();
console.log(JSON.stringify(data, null, 2));
}
test();
+20
View File
@@ -0,0 +1,20 @@
const fs = require('fs');
const dotenv = require('dotenv');
dotenv.config();
async function test() {
const ep = 'https://api.sarvam.ai/speech-to-text/job';
console.log("Testing POST empty JSON");
let res = await fetch(ep, {
method: 'POST',
headers: {
'api-subscription-key': process.env.SARVAM_API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({})
});
console.log(res.status);
console.log(await res.text());
}
test();
+110
View File
@@ -0,0 +1,110 @@
const fs = require('fs');
const path = require('path');
const dotenv = require('dotenv');
dotenv.config();
const API_KEY = process.env.SARVAM_API_KEY;
const BASE_URL = 'https://api.sarvam.ai';
async function main() {
console.log("1. Initialize Job...");
const initRes = await fetch(`${BASE_URL}/speech-to-text/job/v1`, {
method: 'POST',
headers: {
'api-subscription-key': API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({
job_parameters: {
model: "saaras:v4",
mode: "transcribe",
with_diarization: true,
with_timestamps: true,
language_code: "unknown"
}
})
});
const initData = await initRes.json();
console.log(initData);
const jobId = initData.job_id;
console.log("\n2. Get Upload Links...");
const uploadRes = await fetch(`${BASE_URL}/speech-to-text/job/v1/upload-files`, {
method: 'POST',
headers: {
'api-subscription-key': API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({
job_id: jobId,
files: ["test.wav"]
})
});
const uploadData = await uploadRes.json();
console.log(uploadData);
const uploadUrl = uploadData.upload_urls["test.wav"].file_url;
console.log("\n3. Upload File...");
const fileContent = fs.readFileSync(path.join(__dirname, 'test.wav')); // we need a small wav file
const putRes = await fetch(uploadUrl, {
method: 'PUT',
headers: {
'x-ms-blob-type': 'BlockBlob',
'Content-Type': 'audio/wav'
},
body: fileContent
});
console.log("Upload Status:", putRes.status);
console.log("\n4. Start Job...");
const startRes = await fetch(`${BASE_URL}/speech-to-text/job/v1/${jobId}/start`, {
method: 'POST',
headers: {
'api-subscription-key': API_KEY,
'Content-Type': 'application/json'
}
});
const startData = await startRes.json();
console.log(startData);
console.log("\n5. Poll Status...");
let statusData;
for (let i = 0; i < 30; i++) {
const statusRes = await fetch(`${BASE_URL}/speech-to-text/job/v1/${jobId}/status`, {
method: 'GET',
headers: {
'api-subscription-key': API_KEY
}
});
statusData = await statusRes.json();
console.log(`Poll ${i}:`, statusData.job_state);
if (statusData.job_state === "Completed" || statusData.job_state === "Failed") break;
await new Promise(r => setTimeout(r, 5000));
}
if (statusData.job_state === 'Completed') {
const outFile = statusData.job_details[0].outputs[0].file_name;
console.log("\n6. Get Download Links...", outFile);
const dlRes = await fetch(`${BASE_URL}/speech-to-text/job/v1/download-files`, {
method: 'POST',
headers: {
'api-subscription-key': API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({
job_id: jobId,
files: [outFile]
})
});
const dlData = await dlRes.json();
const dlUrl = dlData.download_urls[outFile].file_url;
console.log("\n7. Download Result...");
const resultRes = await fetch(dlUrl);
const resultData = await resultRes.json();
console.log(JSON.stringify(resultData).slice(0, 500) + '...');
}
}
main().catch(console.error);
+23
View File
@@ -0,0 +1,23 @@
const fs = require('fs');
const dotenv = require('dotenv');
dotenv.config();
async function test() {
const job_id = '20260901_ab0c2cab-1810-4448-b1af-b3e6785e3987';
const eps = [
`https://api.sarvam.ai/speech-to-text/job/v1/status?job_id=${job_id}`
];
for (let ep of eps) {
console.log("Testing GET", ep);
let res = await fetch(ep, {
method: 'GET',
headers: {
'api-subscription-key': process.env.SARVAM_API_KEY
}
});
console.log(res.status);
console.log(await res.text());
}
}
test();
+29
View File
@@ -0,0 +1,29 @@
import os, json, urllib.request, urllib.error
_env_path = os.path.join(os.path.dirname(__file__), '.env')
if os.path.exists(_env_path):
with open(_env_path) as f:
for line in f:
if '=' in line and not line.startswith('#'):
k, v = line.strip().split('=', 1)
os.environ.setdefault(k, v)
SARVAM_API_KEY = os.getenv("SARVAM_API_KEY", "")
payload = json.dumps({
"model": "sarvam-2b",
"messages": [{"role": "user", "content": "hello"}]
}).encode('utf-8')
req = urllib.request.Request(
'https://api.sarvam.ai/v1/chat/completions',
data=payload,
headers={'Content-Type': 'application/json', 'api-subscription-key': SARVAM_API_KEY}
)
try:
with urllib.request.urlopen(req, timeout=30) as resp:
print(resp.read().decode('utf-8'))
except urllib.error.HTTPError as e:
print("STATUS:", e.code)
print("BODY:", e.read().decode('utf-8'))
+47
View File
@@ -0,0 +1,47 @@
import os, json, urllib.request, urllib.error
_env_path = os.path.join(os.path.dirname(__file__), '.env')
if os.path.exists(_env_path):
with open(_env_path) as f:
for line in f:
if '=' in line and not line.startswith('#'):
k, v = line.strip().split('=', 1)
os.environ.setdefault(k, v)
SARVAM_API_KEY = os.getenv("SARVAM_API_KEY", "")
sample_text = """आपण हे dissection accelerated हे केले तुम्ही आधी इथं पहिल्यांदा सरांना दाखवले फक्त त्याच्या आधी हो इथं आधी पहिल्यापासून इथं treatment चालू आता एक फक्त आपल्या इथला एक नवीन हे चालू आहे EMR की जे directly audio connect करून इथं notes करतात त्याचं experimentation चालू आहे त्यासाठी फक्त जर तुमची परवानगी असेल तर आपलं जे conversation आहे ते record करतायत. चालेल तुम्हाला IT team-चं? म्हणजे आपण जे बोलतोय ना तेच फक्त record करणार जसं AI असतं ना AI घेऊन direct notes generate करतील असं त्यांचा प्रयोग चाललाय. अच्छा अच्छा. त्या intention-साठी आहे बाकी काही नाही. ठीक आहे. Okay that's okay. आधी तुमची treatment 4 cycle chemo झालेले आहेत. हो. 2006-मध्ये त्याच्यानंतर त्याच्यानंतर 1 वर्षाने. MRI 5 वर्षांनी MRI आणि बाकी mammography आणि sonography दर वर्षाला. म्हणजे 2007 पासून continuous follow-up आहे सरांचा. आणि आता त्रास काय व्हायला लागला तुम्हाला? त्रास काहीच नव्हता follow-up-ला आलो होतो आम्ही."""
prompt = """You are a medical conversation transcript editor.
Given a consultation transcript between a Doctor and Patient in Marathi/English, split it into alternating speaker turns.
Output strict JSON array with this schema:
[
{"speaker": "Doctor", "text": "..."},
{"speaker": "Patient", "text": "..."}
]
Do not output anything other than JSON array."""
payload = json.dumps({
"model": "sarvam-105b",
"temperature": 0.1,
"max_tokens": 2048,
"messages": [
{"role": "system", "content": prompt},
{"role": "user", "content": sample_text}
]
}).encode('utf-8')
req = urllib.request.Request(
'https://api.sarvam.ai/v1/chat/completions',
data=payload,
headers={'Content-Type': 'application/json', 'api-subscription-key': SARVAM_API_KEY}
)
try:
with urllib.request.urlopen(req, timeout=40) as resp:
data = json.loads(resp.read().decode('utf-8'))
import sys
sys.stdout.buffer.write(json.dumps(data, ensure_ascii=False, indent=2).encode('utf-8'))
except urllib.error.HTTPError as e:
print("STATUS:", e.code)
print("BODY:", e.read().decode('utf-8'))
+32
View File
@@ -0,0 +1,32 @@
import os
import json
import urllib.request
_env_path = os.path.join(os.path.dirname(__file__), '.env')
if os.path.exists(_env_path):
with open(_env_path) as f:
for line in f:
if '=' in line and not line.startswith('#'):
k, v = line.strip().split('=', 1)
os.environ.setdefault(k, v)
SARVAM_API_KEY = os.getenv("SARVAM_API_KEY", "")
payload = json.dumps({
"model": "sarvam-2b", # let's test sarvam-2b vs sarvam-105b
"temperature": 0.1,
"max_tokens": 1000,
"messages": [
{"role": "user", "content": "Doctor: Hello. Patient: Hi. Split into turns."}
]
}).encode('utf-8')
req = urllib.request.Request(
'https://api.sarvam.ai/v1/chat/completions',
data=payload,
headers={'Content-Type': 'application/json', 'api-subscription-key': SARVAM_API_KEY}
)
with urllib.request.urlopen(req, timeout=30) as resp:
data = json.loads(resp.read().decode('utf-8'))
print(json.dumps(data, indent=2))
+43
View File
@@ -0,0 +1,43 @@
import os, json, urllib.request, urllib.error
_env_path = os.path.join(os.path.dirname(__file__), '.env')
if os.path.exists(_env_path):
with open(_env_path) as f:
for line in f:
if '=' in line and not line.startswith('#'):
k, v = line.strip().split('=', 1)
os.environ.setdefault(k, v)
SARVAM_API_KEY = os.getenv("SARVAM_API_KEY", "")
sample_text = """आपण हे dissection accelerated हे केले तुम्ही आधी इथं पहिल्यांदा सरांना दाखवले फक्त त्याच्या आधी हो इथं आधी पहिल्यापासून इथं treatment चालू आता एक फक्त आपल्या इथला एक नवीन हे चालू आहे EMR की जे directly audio connect करून इथं notes करतात त्याचं experimentation चालू आहे त्यासाठी फक्त जर तुमची परवानगी असेल तर आपलं जे conversation आहे ते record करतायत. चालेल तुम्हाला IT team-चं? म्हणजे आपण जे बोलतोय ना तेच फक्त record करणार जसं AI असतं ना AI घेऊन direct notes generate करतील असं त्यांचा प्रयोग चाललाय. अच्छा अच्छा. त्या intention-साठी आहे बाकी काही नाही. ठीक आहे. Okay that's okay. आधी तुमची treatment 4 cycle chemo झालेले आहेत. हो."""
prompt = """Format the conversation into Doctor and Patient turns:
Doctor: ...
Patient: ..."""
payload = json.dumps({
"model": "sarvam-105b-conversations",
"temperature": 0.1,
"max_tokens": 1000,
"messages": [
{"role": "system", "content": prompt},
{"role": "user", "content": sample_text}
]
}).encode('utf-8')
req = urllib.request.Request(
'https://api.sarvam.ai/v1/chat/completions',
data=payload,
headers={'Content-Type': 'application/json', 'api-subscription-key': SARVAM_API_KEY}
)
try:
with urllib.request.urlopen(req, timeout=30) as resp:
data = json.loads(resp.read().decode('utf-8'))
import sys
sys.stdout.buffer.write(data['choices'][0]['message']['content'].encode('utf-8'))
sys.stdout.buffer.write(b"\n")
except urllib.error.HTTPError as e:
print("STATUS:", e.code)
print("BODY:", e.read().decode('utf-8'))
+140
View File
@@ -0,0 +1,140 @@
import asyncio
import httpx # type: ignore
import os
import json
from dotenv import load_dotenv # type: ignore
# Optional: You might need to install these:
# pip install nemo_toolkit[asr] torch torchaudio
try:
from nemo.collections.asr.models import SortformerEncLabelModel # type: ignore
NEMO_AVAILABLE = True
except ImportError:
NEMO_AVAILABLE = False
print("Warning: NeMo toolkit not found. Please install using: pip install nemo_toolkit[asr]")
load_dotenv('backend/.env')
SARVAM_API_KEY = os.getenv("SARVAM_API_KEY", "")
async def get_sarvam_transcription(audio_file_path):
"""
Calls Sarvam AI real-time API with timestamps enabled
"""
try:
with open(audio_file_path, "rb") as f:
audio_data = f.read()
print("Fetching transcription from Sarvam AI...")
async with httpx.AsyncClient(timeout=120) as client:
resp = await client.post(
"https://api.sarvam.ai/speech-to-text",
headers={"api-subscription-key": SARVAM_API_KEY},
files={"file": ("audio.wav", audio_data, "audio/wav")},
data={
"model": "saaras:v4", # Update model if needed
"mode": "codemix",
"with_timestamps": "true",
"with_diarization": "false", # Diarization is done locally
}
)
if resp.status_code != 200:
print("Sarvam API Error:", resp.status_code, resp.text)
return None
print("Successfully fetched transcription.")
return resp.json()
except Exception as e:
print(f"Exception during Sarvam API call: {e}")
return None
def get_nemo_diarization(audio_file_path):
"""
Runs NVIDIA Sortformer for Speaker Diarization locally
"""
if not NEMO_AVAILABLE:
print("Cannot run diarization. NeMo is not installed.")
return []
print("Loading NVIDIA Sortformer model...")
# Load the pre-trained Sortformer model
diar_model = SortformerEncLabelModel.from_pretrained("nvidia/diar_sortformer_4spk-v1").eval()
print("Running diarization...")
predicted_segments = diar_model.diarize(audio=[audio_file_path], batch_size=1)
# Extract segments for the first file
# Format of segment in predicted_segments[0]: [start_time, end_time, speaker_id]
if isinstance(predicted_segments, tuple):
predicted_segments = predicted_segments[0]
return predicted_segments[0] if len(predicted_segments) > 0 else []
def align_transcription_and_diarization(sarvam_data, nemo_segments):
"""
Aligns the word-level timestamps from Sarvam API with the speaker segments from NeMo
"""
if not sarvam_data or 'words' not in sarvam_data:
print("No words found in Sarvam transcription.")
return
words = sarvam_data['words']
aligned_transcript = []
print("\n--- Merged Output ---")
current_speaker = None
speaker_sentence = []
for word_info in words:
word = word_info.get('word', '')
word_start = word_info.get('start_time', 0)
word_end = word_info.get('end_time', 0)
# Find which speaker was speaking during this word's time
assigned_speaker = "Unknown"
for segment in nemo_segments:
seg_start, seg_end, spk_id = segment
# Simple overlap check: if the midpoint of the word falls in the segment
midpoint = (word_start + word_end) / 2
if seg_start <= midpoint <= seg_end:
assigned_speaker = f"Speaker {int(spk_id)}"
break
# Group words by speaker for clean display
if assigned_speaker != current_speaker:
if current_speaker is not None:
print(f"[{current_speaker}]: {' '.join(speaker_sentence)}")
current_speaker = assigned_speaker
speaker_sentence = [word]
else:
speaker_sentence.append(word)
# Print the last sentence
if current_speaker is not None and speaker_sentence:
print(f"[{current_speaker}]: {' '.join(speaker_sentence)}")
async def main():
audio_path = "backend/test.wav" # Ensure this path is correct
if not os.path.exists(audio_path):
# Fallback to test.wav in current directory
audio_path = "test.wav"
if not os.path.exists(audio_path):
print(f"Audio file '{audio_path}' not found!")
return
# 1. Run Sarvam API
sarvam_result = await get_sarvam_transcription(audio_path)
# 2. Run Local NVIDIA Model
nemo_segments = get_nemo_diarization(audio_path)
# 3. Align and Print Result
if sarvam_result and nemo_segments:
align_transcription_and_diarization(sarvam_result, nemo_segments)
else:
print("Could not complete alignment due to missing data.")
if __name__ == "__main__":
asyncio.run(main())
+50
View File
@@ -0,0 +1,50 @@
require('dotenv').config();
async function test() {
const transcript = 'हा डॉक्टर बोलसेन इकडे हे गाठ आले त्या हे गाठ झाल्यानंतर मला मुलगा राहिला म्हणजे प्रेग्नेंसी राहिली प्रेग्नेंसी झाल्यानंतर एक चार पाच वर्षांनी पिशवी काढली म्हणजे गाठच झाली होती ती पिशवी वरती अशी हा मग पिशवी काढून टाकली आणि परत आता हे चार पाच वर्षांनी परत गाठ आली आहे.';
const prompt = `You are an expert medical conversation diarizer for Indian languages (Marathi, Hindi, English).
TASK: Identify WHO said WHAT in this doctor-patient conversation.
STRICT RULES:
1. Output ONLY plain text dialogue. No markdown, no explanation.
2. Format each line exactly as:
Doctor: <exact words>
Patient: <exact words>
3. "Doctor" = person who asks questions, examines, diagnoses, prescribes medicine.
4. "Patient" = person who describes symptoms, answers questions.
5. Group all consecutive sentences spoken by the same person into a single paragraph. Do not falsely alternate speakers.
6. Do NOT change, translate, summarize, or rephrase the original text. Keep the exact words.
EXAMPLE:
Input: "काय त्रास होत आहे? डोके दुखत आहे. किती दिवसांपासून? तीन दिवस."
Output:
Doctor: काय त्रास होत आहे?
Patient: डोके दुखत आहे.
Doctor: किती दिवसांपासून?
Patient: तीन दिवस.
NOW DIARIZE THIS:
${transcript}`;
const r = await fetch('https://api.sarvam.ai/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'api-subscription-key': process.env.SARVAM_API_KEY
},
body: JSON.stringify({
model: 'sarvam-105b',
temperature: 0.1,
max_tokens: 2000,
messages: [{role:'user', content:prompt}]
})
});
const data = await r.json();
console.log(JSON.stringify(data, null, 2));
}
test();
+61
View File
@@ -0,0 +1,61 @@
import os, urllib.request, json, sys
sys.stdout.reconfigure(encoding='utf-8')
api_key = None
with open('.env') as f:
for line in f:
if line.startswith('SARVAM_API_KEY='):
api_key = line.strip().split('=', 1)[1].strip('"\' ')
test_text = """
नमस्कार या बसा काय त्रास होतोय तुम्हाला नमस्कार डॉक्टर मला गेले तीन दिवस झाले खूप पोटात दुखत आहे आणि काल रात्रीपासून थोडी उलटी पण झाली ठीक आहे पोटात नेमके कुठे दुखते आहे वरच्या भागात की खालच्या भागात खालच्या भागात उजव्या बाजूला खूप जास्त दुखते आहे काही खाल्ल्यावर जास्त दुखते का हो जेवण केले की त्रास वाढतो ताप किंवा चक्कर येते का हो थोडा बारीक ताप आहे ठीक आहे मी तपासून पाहतो तुम्ही आधी कोणती औषधे घेतली होती का नाही काहीच घेतले नाही ठीक आहे आपण एक सोनोग्राफी आणि ब्लड टेस्ट करू आणि तोपर्यंत मी वेदना कमी करण्यासाठी औषध देतो
"""
DIARIZE_SYSTEM_PROMPT = """You are an expert Marathi, Hindi, and English medical conversation diarization AI.
Your task is to accurately separate a continuous medical consultation transcript into clear speaking turns for Doctor and Patient.
SPEAKER IDENTIFICATION RULES:
1. **Doctor**:
- Greets and invites the patient ("या, बसा", "काय त्रास होतोय?")
- Asks diagnostic questions ("कधीपासून दुखतंय?", "ताप आहे का?", "कुठे दुखतंय?", "काही खाल्ल्यावर त्रास होतो का?")
- Inquires about past history / medications ("आधी कोणती औषधे घेतली का?")
- Gives medical instructions, advice, prescriptions, and orders tests ("तपासून पाहतो", "सोनोग्राफी करू", "गोळ्या लिहून देतो", "3 दिवस घ्या").
2. **Patient**:
- Describes complaints, pain, and symptoms ("पोटात दुखत आहे", "उलटी झाली", "खोकला येतोय", "ताप आलाय")
- Answers the doctor's questions ("खालच्या भागात उजव्या बाजूला", "हो जेवण केले की वाढतो", "नाही काही घेतले नाही", "दोन दिवसांपासून")
- Gives short confirmations ("हो डॉक्टर", "नाही", "ठीक आहे").
OUTPUT FORMAT:
Output ONLY alternating speaking turns starting strictly with "**Doctor:** " or "**Patient:** ".
Do NOT add extra narration, thoughts, or markdown headings.
Example output format:
**Doctor:** [Doctor statement or question]
**Patient:** [Patient statement or answer]
**Doctor:** [Doctor statement or question]
**Patient:** [Patient statement or answer]"""
req = urllib.request.Request(
'https://api.sarvam.ai/v1/chat/completions',
data=json.dumps({
'model': 'sarvam-105b-conversations',
'temperature': 0.1,
'max_tokens': 2000,
'messages': [
{'role': 'system', 'content': DIARIZE_SYSTEM_PROMPT},
{'role': 'user', 'content': f"Transcript:\n{test_text.strip()}"}
]
}).encode('utf-8'),
headers={
'Content-Type': 'application/json',
'api-subscription-key': api_key
}
)
try:
with urllib.request.urlopen(req) as resp:
res = json.loads(resp.read().decode('utf-8'))
print("Diarization Result:\n" + res['choices'][0]['message']['content'])
except Exception as e:
print("Error:", e)
+97
View File
@@ -0,0 +1,97 @@
import os
import json
import sys
import urllib.request
import urllib.error
# --- .env load ---
_env_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env')
if os.path.exists(_env_path):
with open(_env_path, encoding='utf-8') as f:
for line in f:
line = line.strip()
if '=' in line and not line.startswith('#'):
k, v = line.split('=', 1)
os.environ.setdefault(k.strip(), v.strip())
SARVAM_API_KEY = os.getenv("SARVAM_API_KEY", "")
if not SARVAM_API_KEY:
sys.exit("ERROR: SARVAM_API_KEY not found in .env")
sample_text = """आपण हे dissection accelerated हे केले ते. तुम्ही आधी इथं पहिल्यांदा सरांना दाखवले फक्त त्याच्या आधी हो इथं आधी पहिल्यापासून इथं treatment चालू पहिल्यापासून इथं treatment चालू. आता 1 फक्त आपल्या इथला 1 नवीन हे चालू आहे EMR की जे directly audio connect करून इथं notes करतात तर त्याचं experimentation चालू आहे. त्यासाठी फक्त जर तुमची परवानगी असेल तर आपलं जे conversation आहे ते record करतायेत चालेल तुम्हाला IT team-चं? पण आपण जे बोलतोय ना तेच फक्त record करणार जसं AI असतं ना AI घेऊन direct notes generate करतील असं त्यांचा प्रयोग चाललाय. अच्छा अच्छा. त्या intention-साठी आहे बाकी काही नाही. ठीक आहे. OK that's OK. आधी तुमची treatment 4 cycle chemo झालेले आहेत. हो. 2006-मध्ये त्याच्यानंतर त्याच्यानंतर 1 वर्षाने MRI, 5 वर्षाने MRI आणि बाकी mammography आणि sonography दर वर्षाला. म्हणजे 2007-पासून continuous follow-up आहे. आणि आता त्रास काय व्हायला लागला तुम्हाला? त्रास काहीच नव्हता, follow-up-ला आलो होतो मी."""
system_prompt = """You are an expert Marathi medical consultation diarization system.
You will receive a raw, unlabeled Marathi conversation between a Doctor and a Patient.
Your job: label EACH utterance as either "Doctor:" or "Patient:".
CONTEXT CUES:
- Doctor: explains treatment, asks questions, mentions chemo/MRI/surgery/medicines/reports, gives advice, uses medical terminology, refers to "तुमची treatment", "आपण करतो".
- Patient: answers questions, describes symptoms, says "हो", "नाही", "अच्छा", "ठीक आहे", "त्रास काहीच नव्हता", came for follow-up after 4 cycles of chemo since 2006.
- Consent/permission questions about recording → Doctor asking.
- Short confirmations like "हो", "अच्छा अच्छा", "ठीक आहे", "OK that's OK" → Patient responding.
OUTPUT FORMAT (strict, one utterance per line):
Doctor: <exact original Marathi text>
Patient: <exact original Marathi text>
Doctor: <exact original Marathi text>
...
RULES:
- Every single line MUST start with either "Doctor: " or "Patient: ".
- Do NOT add explanations, headings, summaries, or blank lines.
- Do NOT merge multiple turns into one line.
- Do NOT translate or paraphrase — preserve original Marathi/English text exactly.
- Split at natural turn boundaries (question → answer, statement → reaction).
"""
payload = json.dumps({
"model": "sarvam-105b-conversations",
"temperature": 0.1,
"max_tokens": 8192,
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": f"Conversation:\n{sample_text}"}
]
}).encode('utf-8')
req = urllib.request.Request(
'https://api.sarvam.ai/v1/chat/completions',
data=payload,
headers={
'Content-Type': 'application/json',
'api-subscription-key': SARVAM_API_KEY
}
)
try:
with urllib.request.urlopen(req, timeout=120) as resp:
data = json.loads(resp.read().decode('utf-8'))
choice = data.get('choices', [{}])[0]
finish_reason = choice.get('finish_reason', 'unknown')
msg = choice.get('message', {})
content = msg.get('content', None)
reasoning = msg.get('reasoning_content', None)
if not content:
# Model used all tokens for reasoning, no final answer generated
print(f"[WARNING] content=None, finish_reason={finish_reason}", file=sys.stderr)
if reasoning:
print("\n===== MODEL REASONING (no final output) =====\n", file=sys.stderr)
sys.stderr.buffer.write(reasoning[:2000].encode('utf-8'))
sys.stderr.buffer.write(b"\n")
sys.exit(f"ERROR: Model returned empty content. Try increasing max_tokens or simplifying the prompt.")
print("\n===== DIARIZED TRANSCRIPT =====\n")
sys.stdout.buffer.write(content.encode('utf-8'))
sys.stdout.buffer.write(b"\n")
print(f"\n[finish_reason: {finish_reason} | tokens used: {data.get('usage', {}).get('total_tokens', '?')}]")
except urllib.error.HTTPError as e:
body = e.read().decode('utf-8')
print(f"\nHTTP ERROR {e.code}: {body}", file=sys.stderr)
sys.exit(1)
except urllib.error.URLError as e:
print(f"\nCONNECTION ERROR: {e.reason}", file=sys.stderr)
sys.exit(1)
except (KeyError, IndexError) as e:
print(f"\nUNEXPECTED RESPONSE FORMAT: {e}", file=sys.stderr)
sys.exit(1)
+53
View File
File diff suppressed because one or more lines are too long
+71
View File
@@ -0,0 +1,71 @@
import os
import sys
import json
import urllib.request
# Load env from .env file manually (no external deps needed)
_env_path = os.path.join(os.path.dirname(__file__), '.env')
if os.path.exists(_env_path):
with open(_env_path) as f:
for line in f:
line = line.strip()
if line and not line.startswith('#') and '=' in line:
k, v = line.split('=', 1)
os.environ.setdefault(k.strip(), v.strip())
SARVAM_API_KEY = os.getenv("SARVAM_API_KEY", "")
def test():
prompt = """You are a medical transcription editor. You will receive a transcript of a doctor-patient conversation with acoustic timestamps.
Your task is to identify the speakers, group consecutive speech from the same speaker into single segments, and output a strict JSON array.
RULES:
1. Identify who is speaking ("Doctor" or "Patient"). Do not use generic labels like "speaker_0".
2. Group consecutive lines by the same speaker into one block.
3. The "start" timestamp should be the start time of the first phrase in the block.
4. The "end" timestamp should be the end time of the last phrase in the block.
5. Filter out obvious ASR hallucinations like "subscribe", "leave a comment", "follow the channel".
6. Return EXACTLY and ONLY a JSON array, no markdown, no other text.
Example Input:
[00:00:00 - 00:00:04] नमस्कार तुम्हाला काय त्रास होतो आहे?
[00:00:04 - 00:00:09] डॉक्टर मला दोन दिवसांपासून खूप ताप आहे.
[00:00:09 - 00:00:11] बरं, खोकला आहे का?
Example Output:
[
{ "speaker": "Doctor", "start": "00:00:00", "end": "00:00:04", "text": "नमस्कार तुम्हाला काय त्रास होतो आहे?" },
{ "speaker": "Patient", "start": "00:00:04", "end": "00:00:09", "text": "डॉक्टर मला दोन दिवसांपासून खूप ताप आहे." },
{ "speaker": "Doctor", "start": "00:00:09", "end": "00:00:11", "text": "बरं, खोकला आहे का?" }
]"""
transcript = """[00:00:00 - 00:00:05] नमस्कार या बसा तुम्हाला काय त्रास होतो?
[00:00:05 - 00:00:10] मला कालपासून ताप आहे."""
payload = json.dumps({
"model": "sarvam-105b",
"temperature": 0.1,
"messages": [
{"role": "system", "content": prompt},
{"role": "user", "content": transcript}
]
}).encode('utf-8')
req = urllib.request.Request(
'https://api.sarvam.ai/v1/chat/completions',
data=payload,
headers={
'Content-Type': 'application/json',
'api-subscription-key': SARVAM_API_KEY
}
)
with urllib.request.urlopen(req, timeout=60) as resp:
body = resp.read().decode('utf-8')
data = json.loads(body)
content = data['choices'][0]['message']['content']
sys.stdout.buffer.write(("STATUS: " + str(resp.status) + "\n").encode('utf-8'))
sys.stdout.buffer.write(("OUTPUT:\n" + content + "\n").encode('utf-8'))
sys.stdout.flush()
test()
+44
View File
@@ -0,0 +1,44 @@
const fs = require('fs');
async function testLLM() {
const partText = "काय त्रास होतोय? नाही ऍक्च्युली डॉक्टर रेगन कडे स्पाइनची सर्जरी करायची आहे फिटनेस सर्टिफिकेट हवं बरं";
const DIARIZE_PROMPT = `You are an expert medical conversation diarizer.
TASK: Identify WHO said WHAT in this short segment of a doctor-patient conversation.
STRICT RULES:
1. Output ONLY a valid JSON array. No markdown, no explanations, no reasoning.
2. Each object must have "speaker" (either "Doctor" or "Patient") and "text" (the exact spoken words).
3. Do not translate. Keep the exact text.
Example Output:
[
{"speaker": "Doctor", "text": "काय त्रास होत आहे?"},
{"speaker": "Patient", "text": "डोके दुखत आहे."}
]
NOW DIARIZE THIS SEGMENT:
${partText}`;
console.log("Sending request to Sarvam...");
const diarizeResp = await fetch('https://api.sarvam.ai/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'api-subscription-key': 'sk_25ncib43_YUPtWHky8c1lSG2TOrVsdK8K'
},
body: JSON.stringify({
model: 'sarvam-105b',
temperature: 0.1,
max_tokens: 800,
messages: [
{ role: 'system', content: 'You are a helpful JSON API returning only valid JSON.' },
{ role: 'user', content: DIARIZE_PROMPT }
]
})
});
const data = await diarizeResp.json();
console.log(data?.choices?.[0]?.message?.content || JSON.stringify(data));
}
testLLM().catch(console.error);
+18
View File
@@ -0,0 +1,18 @@
require('dotenv').config();
fetch('https://api.sarvam.ai/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'api-subscription-key': process.env.SARVAM_API_KEY
},
body: JSON.stringify({
model: 'sarvam-105b',
temperature: 0.1,
messages: [
{role: 'system', content: 'You are an expert medical conversation diarizer for Indian languages. Output ONLY a valid JSON array. Format: [{"speaker":"doctor", "text":"..."}]'},
{role: 'user', content: 'आपण हे डिसिक्शन एक्सेलरी हे केले... चालेल तुम्हाला आयटी टीमचं? चालेल.'}
]
})
}).then(r => r.json()).then(d => {
console.log(JSON.stringify(d, null, 2));
}).catch(console.error);
+98
View File
@@ -0,0 +1,98 @@
function detectSpeakerRoles(speakerTurns, fullContext = '') {
if (!Array.isArray(speakerTurns) || speakerTurns.length === 0) {
return [];
}
const speakerStats = {};
for (const turn of speakerTurns) {
const sid = (turn.speaker_id || 'SPEAKER_0').toUpperCase(); // ✅ normalize
if (!speakerStats[sid]) {
speakerStats[sid] = { sid, turns: [], allText: '', doctorScore: 0, patientScore: 0 };
}
speakerStats[sid].turns.push(turn);
speakerStats[sid].allText += (speakerStats[sid].allText ? ' ' : '') + (turn.text || '');
}
// BUG 8 FIX: patterns empty होते — score नेहमी 0, role नेहमी 'Unknown'
// आता real Marathi/Hindi/English doctor/patient keywords वापरतो
const doctorPatterns = [
// Marathi doctor keywords
/\b(?:औषध|गोळ्या|लिहून|तपासणी|diagnos|ECG|echo|test|रिपोर्ट|report|prescription|उपचार|treatment)\b/i,
/\b(?:तुम्हाला काय|काय त्रास|बीपी|BP|रक्तदाब|शुगर|साखर|injection|surgery|शस्त्रक्रिया)\b/i,
/\b(?:follow.?up|फॉलो|consult|अँटीबायोटिक|antibiotic|paracetamol|tablet|syrup)\b/i,
// Hindi doctor keywords
/\b(?:दवाई|दवा|इलाज|जांच|बताइए|लिख रहा|लिखता|कितने दिन|कब से)\b/i,
];
const patientPatterns = [
// Marathi patient keywords
/\b(?:दुखतंय|त्रास|जड|ताप|खोकला|खाज|मुंग्या|धाप|थकवा|झोप|जळजळ|सूज)\b/i,
/\b(?:हो डॉक्टर|नाही डॉक्टर|ठीक आहे डॉक्टर|चालेल डॉक्टर|काय करू)\b/i,
/\b(?:गेल्या|दिवसांपासून|आठवड्यांपासून|महिन्यांपासून|वर्षांपासून)\b/i,
// Hindi patient keywords
/\b(?:जी डॉक्टर|हाँ डॉक्टर|दर्द|बुखार|खांसी|सांस|थकान|उल्टी|चक्कर)\b/i,
// English patient keywords
/\b(?:yes doctor|no doctor|i have|i feel|i am feeling|pain|fever|cough)\b/i,
];
const doctorQuestionWords = /\b(?:का|काय|कुठे|कधी|कसे|किती)\b/g;
for (const sid in speakerStats) {
const text = speakerStats[sid].allText;
for (const pat of doctorPatterns) {
const m = text.match(new RegExp(pat.source, 'gi'));
if (m) speakerStats[sid].doctorScore += m.length * 3;
}
for (const pat of patientPatterns) {
const m = text.match(new RegExp(pat.source, 'gi'));
if (m) speakerStats[sid].patientScore += m.length * 3;
}
// ✅ Marathi question words, not '?'
const qWords = (text.match(doctorQuestionWords) || []).length;
speakerStats[sid].doctorScore += qWords * 1.5;
}
const roleMapping = {};
for (const sid in speakerStats) {
const s = speakerStats[sid];
const total = s.doctorScore + s.patientScore;
let detected_role = 'Unknown';
let confidence = 0.50;
if (total > 0) {
const docRatio = s.doctorScore / total;
const patRatio = s.patientScore / total;
const margin = Math.abs(docRatio - patRatio);
if (docRatio >= 0.65 && s.doctorScore >= 3) {
detected_role = 'Doctor';
confidence = Math.min(0.98, 0.50 + docRatio * 0.50);
} else if (patRatio >= 0.65 && s.patientScore >= 3) {
detected_role = 'Patient';
confidence = Math.min(0.98, 0.50 + patRatio * 0.50);
} else {
detected_role = 'Unknown';
confidence = Math.max(0.30, 0.50 - margin * 0.30); // ✅ lower when uncertain
}
}
roleMapping[sid] = {
detected_role,
confidence: Number(confidence.toFixed(2))
};
}
return speakerTurns.map(turn => {
const sid = (turn.speaker_id || 'SPEAKER_0').toUpperCase(); // ✅ match key
const mapping = roleMapping[sid] || { detected_role: 'Unknown', confidence: 0.50 };
return {
speaker_id: turn.speaker_id || 'SPEAKER_0',
start: turn.start ?? 0.0,
end: turn.end ?? 0.0,
text: turn.text,
detected_role: mapping.detected_role,
confidence: mapping.confidence
};
});
}
+56
View File
@@ -0,0 +1,56 @@
import os, urllib.request, json, wave, io
api_key = None
if os.path.exists('.env'):
with open('.env') as f:
for line in f:
if line.startswith('SARVAM_API_KEY='):
api_key = line.strip().split('=', 1)[1].strip('"\' ')
print("Testing with API Key:", api_key[:8] + "..." if api_key else "None")
# Make a small 1s 16kHz mono wav
wav_io = io.BytesIO()
with wave.open(wav_io, 'wb') as wf:
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(16000)
wf.writeframes(b'\x00\x00' * 16000)
wav_bytes = wav_io.getvalue()
for model_name in ['saaras:v4', 'saarika:v2.5']:
print(f"\n--- Testing model: {model_name} ---")
boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW'
body = (
f'--{boundary}\r\n'
f'Content-Disposition: form-data; name="file"; filename="audio.wav"\r\n'
f'Content-Type: audio/wav\r\n\r\n'
).encode('utf-8') + wav_bytes + (
f'\r\n--{boundary}\r\n'
f'Content-Disposition: form-data; name="model"\r\n\r\n'
f'{model_name}\r\n'
f'--{boundary}\r\n'
f'Content-Disposition: form-data; name="language_code"\r\n\r\n'
f'unknown\r\n'
f'--{boundary}--\r\n'
).encode('utf-8')
req = urllib.request.Request(
'https://api.sarvam.ai/speech-to-text',
data=body,
headers={
'api-subscription-key': api_key,
'Content-Type': f'multipart/form-data; boundary={boundary}'
}
)
try:
with urllib.request.urlopen(req) as resp:
res_json = json.loads(resp.read().decode('utf-8'))
print("Success! Response:", res_json)
except urllib.error.HTTPError as e:
print("HTTP Error:", e.code)
print("Response text:", e.read().decode('utf-8'))
except Exception as e:
print("Error:", e)
+36
View File
@@ -0,0 +1,36 @@
const fs = require('fs');
const path = require('path');
const dotenv = require('dotenv');
dotenv.config({ path: path.join(__dirname, '.env') });
const SARVAM_API_KEY = process.env.SARVAM_API_KEY;
async function test() {
const filePath = path.join(__dirname, 'backend', 'test.wav');
if (!fs.existsSync(filePath)) {
console.error("test.wav not found");
return;
}
const audioBuffer = fs.readFileSync(filePath);
const formData = new FormData();
formData.append('file', new Blob([audioBuffer], { type: 'audio/wav' }), 'test.wav');
formData.append('model', 'saaras:v4');
formData.append('mode', 'codemix');
formData.append('with_timestamps', 'true');
formData.append('with_diarization', 'true');
try {
const resp = await fetch('https://api.sarvam.ai/speech-to-text', {
method: 'POST',
headers: { 'api-subscription-key': SARVAM_API_KEY },
body: formData
});
console.log(resp.status);
const data = await resp.text();
console.log(data);
} catch (err) {
console.error(err);
}
}
test();
+52
View File
@@ -0,0 +1,52 @@
import os, urllib.request, json, wave, io
api_key = None
with open('.env', encoding='utf-8') as f:
for line in f:
if line.startswith('SARVAM_API_KEY='):
api_key = line.strip().split('=', 1)[1].strip('"\' ')
wav_io = io.BytesIO()
with wave.open(wav_io, 'wb') as wf:
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(16000)
wf.writeframes(b'\x00\x00' * 16000)
wav_bytes = wav_io.getvalue()
boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW'
body = (
f'--{boundary}\r\n'
f'Content-Disposition: form-data; name="file"; filename="audio.wav"\r\n'
f'Content-Type: audio/wav\r\n\r\n'
).encode('utf-8') + wav_bytes + (
f'\r\n--{boundary}\r\n'
f'Content-Disposition: form-data; name="model"\r\n\r\n'
f'saaras:v4\r\n'
f'--{boundary}\r\n'
f'Content-Disposition: form-data; name="language_code"\r\n\r\n'
f'unknown\r\n'
f'--{boundary}\r\n'
f'Content-Disposition: form-data; name="with_diarization"\r\n\r\n'
f'true\r\n'
f'--{boundary}--\r\n'
).encode('utf-8')
req = urllib.request.Request(
'https://api.sarvam.ai/speech-to-text',
data=body,
headers={
'api-subscription-key': api_key,
'Content-Type': f'multipart/form-data; boundary={boundary}'
}
)
try:
with urllib.request.urlopen(req) as resp:
res = json.loads(resp.read().decode('utf-8'))
print("Keys returned by STT:", list(res.keys()))
print("Full response:", res)
except urllib.error.HTTPError as e:
print("HTTP Error:", e.code, e.read().decode('utf-8'))
except Exception as e:
print("Error:", e)
+46
View File
@@ -0,0 +1,46 @@
import urllib.request, json, wave, io, os
api_key = None
with open('.env', encoding='utf-8') as f:
for line in f:
if line.startswith('SARVAM_API_KEY='):
api_key = line.strip().split('=', 1)[1].strip('"\' ')
wav_io = io.BytesIO()
with wave.open(wav_io, 'wb') as wf:
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(16000)
wf.writeframes(b'\x00\x00' * 16000)
wav_bytes = wav_io.getvalue()
boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW'
body = (
f'--{boundary}\r\n'
f'Content-Disposition: form-data; name="file"; filename="audio.wav"\r\n'
f'Content-Type: audio/wav\r\n\r\n'
).encode('utf-8') + wav_bytes + (
f'\r\n--{boundary}\r\n'
f'Content-Disposition: form-data; name="model"\r\n\r\n'
f'saaras:v4\r\n'
f'--{boundary}\r\n'
f'Content-Disposition: form-data; name="with_timestamps"\r\n\r\n'
f'true\r\n'
f'--{boundary}--\r\n'
).encode('utf-8')
req = urllib.request.Request(
'https://api.sarvam.ai/speech-to-text',
data=body,
headers={
'api-subscription-key': api_key,
'Content-Type': f'multipart/form-data; boundary={boundary}'
}
)
try:
with urllib.request.urlopen(req) as resp:
res = json.loads(resp.read().decode('utf-8'))
print(json.dumps(res, indent=2))
except urllib.error.HTTPError as e:
print(e.read().decode('utf-8'))
+50
View File
@@ -0,0 +1,50 @@
import os, urllib.request, json
api_key = None
with open('.env') as f:
for line in f:
if line.startswith('SARVAM_API_KEY='):
api_key = line.strip().split('=', 1)[1].strip('"\' ')
sample_transcript = """
Doctor: नमस्कार, काय त्रास होतोय तुम्हाला?
Patient: डॉक्टर मला गेले दोन दिवस झाले खूप खोकला आणि घशात खवखव होते आहे.
Doctor: ताप येतोय का?
Patient: हो, काल रात्री थोडा ताप आला होता.
Doctor: ठीक आहे, मी तुम्हाला खोकल्याचे औषध आणि ताप कमी करण्यासाठी गोळ्या लिहून देतो, 3 दिवस घ्या.
"""
prompt = """You are an expert clinical documentation AI. Read the doctor-patient conversation transcript below carefully.
Extract the clinical summary strictly based on what was discussed in the transcript.
Output ONLY valid JSON with no extra explanation or thought tags, formatted exactly as:
{
"chief_complaint": "Brief 1-line chief complaint based on transcript",
"symptoms": ["List of all symptoms specifically mentioned in transcript"],
"history": "Past history if mentioned, or 'Not mentioned'",
"assessment": "Clinical assessment or condition discussed",
"recommendation": "Doctor's exact advice, medication, or instructions from transcript"
}"""
req = urllib.request.Request(
'https://api.sarvam.ai/v1/chat/completions',
data=json.dumps({
'model': 'sarvam-105b-conversations',
'temperature': 0.1,
'max_tokens': 1000,
'messages': [
{'role': 'system', 'content': prompt},
{'role': 'user', 'content': f"Transcript:\n{sample_transcript}"}
]
}).encode('utf-8'),
headers={
'Content-Type': 'application/json',
'api-subscription-key': api_key
}
)
try:
with urllib.request.urlopen(req) as resp:
res = json.loads(resp.read().decode('utf-8'))
print("Response:", res['choices'][0]['message']['content'])
except Exception as e:
print("Error:", e)
+34
View File
@@ -0,0 +1,34 @@
const fs = require('fs');
const dotenv = require('dotenv');
dotenv.config();
async function test() {
const formData = new FormData();
formData.append('model', 'saaras:v4');
formData.append('with_timestamps', 'true');
// Create a 1 sec silent wav file
const buf = Buffer.alloc(44 + 16000 * 2);
buf.write('RIFF', 0); buf.writeUInt32LE(36 + 16000 * 2, 4);
buf.write('WAVE', 8); buf.write('fmt ', 12);
buf.writeUInt32LE(16, 16);
buf.writeUInt16LE(1, 20); buf.writeUInt16LE(1, 22);
buf.writeUInt32LE(16000, 24); buf.writeUInt32LE(32000, 28);
buf.writeUInt16LE(2, 32); buf.writeUInt16LE(16, 34);
buf.write('data', 36); buf.writeUInt32LE(16000 * 2, 40);
formData.append('file', new Blob([buf], { type: 'audio/wav' }), 'test.wav');
const res = await fetch('https://api.sarvam.ai/speech-to-text', {
method: 'POST',
headers: {
'api-subscription-key': process.env.SARVAM_API_KEY
},
body: formData
});
console.log(res.status);
console.log(await res.text());
}
test();
+76
View File
@@ -0,0 +1,76 @@
import re
def align_verbatim_transcript(raw_transcript, llm_output):
"""
Guarantees that the final dialogue text contains ONLY the exact original words
from raw_transcript in exact original order, with only 'Doctor:' and 'Patient:' speaker tags inserted.
"""
raw_words = raw_transcript.strip().split()
# Extract speaker turns and their text from llm output
lines = llm_output.split('\n')
turns = []
for line in lines:
line = line.strip()
doc_m = re.match(r'^\*{0,2}Doctor\*{0,2}\s*:\s*(.*)', line, re.I)
pat_m = re.match(r'^\*{0,2}Patient\*{0,2}\s*:\s*(.*)', line, re.I)
if doc_m:
turns.append(('Doctor', doc_m.group(1).strip()))
elif pat_m:
turns.append(('Patient', pat_m.group(1).strip()))
if not turns:
return f"**Doctor:** {raw_transcript}"
# Verify and reconstruct using strict raw words
aligned_turns = []
raw_idx = 0
for speaker, text in turns:
turn_words = text.split()
if not turn_words:
continue
# Match as many words as possible from raw_words
matched = []
while raw_idx < len(raw_words):
raw_w = raw_words[raw_idx]
clean_raw = re.sub(r'[^\w\s]', '', raw_w).lower()
# Check if this raw word matches something in this turn
found = False
for tw in turn_words:
clean_tw = re.sub(r'[^\w\s]', '', tw).lower()
if clean_raw == clean_tw:
found = True
break
if found or len(matched) < len(turn_words):
matched.append(raw_w)
raw_idx += 1
if len(matched) >= len(turn_words):
break
else:
break
if matched:
aligned_turns.append((speaker, ' '.join(matched)))
# Append any remaining raw words to the last speaker turn
if raw_idx < len(raw_words):
remaining = ' '.join(raw_words[raw_idx:])
if aligned_turns:
aligned_turns[-1] = (aligned_turns[-1][0], aligned_turns[-1][1] + ' ' + remaining)
else:
aligned_turns.append(('Doctor', remaining))
# Format result
formatted = '\n\n'.join(f"**{sp}:** {txt}" for sp, txt in aligned_turns)
return formatted
raw = "नमस्कार या बसा काय त्रास होतोय तुम्हाला मला गेले दोन दिवस झाले पोटात दुखत आहे"
llm_out = """**Doctor:** नमस्कार या बसा काय त्रास होतोय तुम्हाला?
**Patient:** मला गेले दोन दिवस झाले पोटात दुखत आहे."""
print("Result:")
print(align_verbatim_transcript(raw, llm_out))