From f45173873267422781488ae27411640fbf58cb8e Mon Sep 17 00:00:00 2001 From: Ayush <155418492+Ayushshah1109@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:08:14 +0530 Subject: [PATCH] Initial commit: Doctor-Patient clinical transcription and structured summary pipeline --- .env.example | 17 + .gitignore | 52 ++ README.md | 224 +++++ Sarvam Transcripts.xlsx | Bin 0 -> 31902 bytes backend/.env.example | 15 + backend/diarization_pipeline.py | 220 +++++ backend/main.py | 334 +++++++ backend/requirements.txt | 12 + backend/test.wav | Bin 0 -> 32044 bytes backend/test_stt.py | 29 + data/audio/.gitkeep | 1 + data/db.json | 1036 +++++++++++++++++++++ db.js | 541 +++++++++++ frontend/index.html | 341 +++++++ frontend/script.js | 367 ++++++++ frontend/style.css | 380 ++++++++ hybrid_diarization.py | 192 ++++ package-lock.json | 886 ++++++++++++++++++ package.json | 19 + public/app.js | 1253 +++++++++++++++++++++++++ public/favicon.ico | Bin 0 -> 22847 bytes public/favicon.png | Bin 0 -> 22847 bytes public/index.html | 608 +++++++++++++ public/logo.png | Bin 0 -> 22847 bytes public/script.js | 368 ++++++++ public/style.css | 1519 +++++++++++++++++++++++++++++++ run_batch_qwen.js | 181 ++++ run_nemo.py | 86 ++ run_pipeline.py | 137 +++ server.js | 1014 +++++++++++++++++++++ summarize_conversation.py | 58 ++ test.wav | Bin 0 -> 32044 bytes test_anti_hallucination.py | 48 + test_batch.js | 25 + test_batch.py | 25 + test_batch_api.js | 20 + test_batch_create.js | 27 + test_batch_ep.js | 20 + test_batch_flow.js | 110 +++ test_batch_status.js | 23 + test_chat_err.py | 29 + test_chat_sarvam.py | 47 + test_chat_schema.py | 32 + test_conversations_model.py | 43 + test_diarization_pipeline.py | 140 +++ test_diarize_llm.js | 50 + test_diarize_rules.py | 61 ++ test_line_diarize.py | 97 ++ test_llm.js | 53 ++ test_llm.py | 71 ++ test_llm_call.js | 44 + test_prompt.js | 18 + test_role_detection.js | 98 ++ test_sarvam_quota.py | 56 ++ test_stt.js | 36 + test_stt_diarize.py | 52 ++ test_stt_timestamps.py | 46 + test_summary_extract.py | 50 + test_ts.js | 34 + test_verbatim_align.py | 76 ++ 60 files changed, 11321 insertions(+) create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 README.md create mode 100644 Sarvam Transcripts.xlsx create mode 100644 backend/.env.example create mode 100644 backend/diarization_pipeline.py create mode 100644 backend/main.py create mode 100644 backend/requirements.txt create mode 100644 backend/test.wav create mode 100644 backend/test_stt.py create mode 100644 data/audio/.gitkeep create mode 100644 data/db.json create mode 100644 db.js create mode 100644 frontend/index.html create mode 100644 frontend/script.js create mode 100644 frontend/style.css create mode 100644 hybrid_diarization.py create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 public/app.js create mode 100644 public/favicon.ico create mode 100644 public/favicon.png create mode 100644 public/index.html create mode 100644 public/logo.png create mode 100644 public/script.js create mode 100644 public/style.css create mode 100644 run_batch_qwen.js create mode 100644 run_nemo.py create mode 100644 run_pipeline.py create mode 100644 server.js create mode 100644 summarize_conversation.py create mode 100644 test.wav create mode 100644 test_anti_hallucination.py create mode 100644 test_batch.js create mode 100644 test_batch.py create mode 100644 test_batch_api.js create mode 100644 test_batch_create.js create mode 100644 test_batch_ep.js create mode 100644 test_batch_flow.js create mode 100644 test_batch_status.js create mode 100644 test_chat_err.py create mode 100644 test_chat_sarvam.py create mode 100644 test_chat_schema.py create mode 100644 test_conversations_model.py create mode 100644 test_diarization_pipeline.py create mode 100644 test_diarize_llm.js create mode 100644 test_diarize_rules.py create mode 100644 test_line_diarize.py create mode 100644 test_llm.js create mode 100644 test_llm.py create mode 100644 test_llm_call.js create mode 100644 test_prompt.js create mode 100644 test_role_detection.js create mode 100644 test_sarvam_quota.py create mode 100644 test_stt.js create mode 100644 test_stt_diarize.py create mode 100644 test_stt_timestamps.py create mode 100644 test_summary_extract.py create mode 100644 test_ts.js create mode 100644 test_verbatim_align.py diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..67b324a --- /dev/null +++ b/.env.example @@ -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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d2fd046 --- /dev/null +++ b/.gitignore @@ -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/ + diff --git a/README.md b/README.md new file mode 100644 index 0000000..d704506 --- /dev/null +++ b/README.md @@ -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. diff --git a/Sarvam Transcripts.xlsx b/Sarvam Transcripts.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..b1c8cdc40cb632aeecfb3151178fcb84cbe3abf0 GIT binary patch literal 31902 zcmeFYsl;+*GZQHhO+qP}nwtd^SZR56W+ueI-cHfA7W9C1Y%@0`-Rp&!xR{oyn zXa$DAqE7|SBWp-BU-7gMga)c>!2|tDn-8j;pEXuW9>Xk z%ip}nPXwVtR4eudq`56`ru!L-MmyWqpoq~fC79^I@qSf3YR5ZST!`zKAHN@S~4wy=<3eNG(fjv339Yl`F zKT8OQ3&_h>mXzLlkB799AkjqLTWD^2r3!=^%9KV*9ZnzV(!I_U?aV6%#y~p^VF^8O z+q1i1UA^phvMgAQf1;i$wMG-Hsr!6%e7yQ7;-a4vK04V@E%a%%^8^A3gBJe+C|E}~ zqt!6k&G`=VqZZ3d-3=0Kf0FJa;|%X&n{?*ICz!}#5ZTh~m5$|!$aAt&1^JbaPqcIN z%U>Jg_}G;#fFFT~zWt)SAf9(V_6s3Q^b?Z!hF|ZEpL2U(%^zzA-`uC2`!oH30Ra5| z0s|=g|FCRPWgvd~x7K9-Q3w4GOMNF(8)tgD|LFf8j{k!h{J(}?og^zi!~hd^EAbUR z{<^ZAfFLC8E-2AOsNxqOxdq=6TTFtz-A9gtpn??)Ebiaq_cgh>%@cbuPWW=bQXP$i z!cE-jUK5u7;phrZMdp+y=2*QyjOe!Vyz-JMF6Bw#))P-v)m~93J+VtHwsbGjfG|g= zjs=NaiW7#$n;EDzDyz9;^i~VFBBXp>6IS2GUT~2-m+ilnR(1}{AHgYewU~)I?rdbf zUh6Y%L-_oTrK)VfX<2WS=fp+isc&M_|0t5(hy3kBE0;5_M8tyh#xy5BMq2RfuhqNe3)*ttuiM^Mbn8Lfe=T#mR5MYViemq4dxL@TW+W}BjQFcKr5e3 zt>5jdA`p4PglW)tOfV_F&|W@)i8O{;71UYvs&F^A@_^NrKK#+&D78ojxbMfV)dy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*wX~7T z(7No|w{AN*>u2Oii@sh%VIf0uR;#5|bQl}-*^oN~#TL{l;dotBv;%JQsl`H2aT>g{ zpS#VEf@d2Ps4S^_N*?s^dZ@MesAhQy4S~V;D0-0m1naa=Bd(`Ot0y3%I5_sv5Q#pR z!4AOTXc+v{lAUsnXJCx$W|-+lj&m)*j@xOHLpNRimCB2t-MBA4MERjV#LQcw-Q5aC zcgcfaWo^;8>;+Qpj305H&+hvhiSb58UD)fwT{jc&=iYt)!>y;HFT;zD84JbMXTvA_ zf6>-J!RY^HxI_JqB3=u)cV_K>3IF4o`nON~H-hayh5zJu{!7~N z7moW6s^>q&|4tVCmlOoV4DNr6|9?1x|MdAMZth=B83_O9A^tD;+&^9ZNp|{|iwo-i zcKIjg>7NGwWK;ah;QlWJ?{8WBi&XJX=|7|S|0QJt{D0Da2KE2b;om3Ff9XL$#+^Yx t{;%oupYnen0{^>Q@-GML|H%JyKva;1{9C&qAaH+A|GzUfjOTyc{V&)UB%lBQ literal 0 HcmV?d00001 diff --git a/backend/.env.example b/backend/.env.example new file mode 100644 index 0000000..dae1984 --- /dev/null +++ b/backend/.env.example @@ -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 diff --git a/backend/diarization_pipeline.py b/backend/diarization_pipeline.py new file mode 100644 index 0000000..c691407 --- /dev/null +++ b/backend/diarization_pipeline.py @@ -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) + diff --git a/backend/main.py b/backend/main.py new file mode 100644 index 0000000..04b86e1 --- /dev/null +++ b/backend/main.py @@ -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(' bytes: + dl = len(pcm); h = bytearray(44) + h[0:4]=b'RIFF'; struct.pack_into(' 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=["*"] + )], +) diff --git a/backend/requirements.txt b/backend/requirements.txt new file mode 100644 index 0000000..b9e3ca9 --- /dev/null +++ b/backend/requirements.txt @@ -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 diff --git a/backend/test.wav b/backend/test.wav new file mode 100644 index 0000000000000000000000000000000000000000..3f1a79e7e4dab5becbac15d0e10360e6d77ed322 GIT binary patch literal 32044 zcmeIuAqs#%6a>((C)gtxJcnR#!D`Sfh|RWD@aV3=TfCVvOnl3nbALx{<2s#J=~6^A zwa-vT{o6=!>}CJ95FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+ z009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBly zK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAVA<3cmeTf B2iX7s literal 0 HcmV?d00001 diff --git a/backend/test_stt.py b/backend/test_stt.py new file mode 100644 index 0000000..3cf5e12 --- /dev/null +++ b/backend/test_stt.py @@ -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()) diff --git a/data/audio/.gitkeep b/data/audio/.gitkeep new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/data/audio/.gitkeep @@ -0,0 +1 @@ + diff --git a/data/db.json b/data/db.json new file mode 100644 index 0000000..5dbd583 --- /dev/null +++ b/data/db.json @@ -0,0 +1,1036 @@ +{ + "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-00008", + "name": "Om", + "age": 24, + "gender": "Male", + "phone": "6547896547", + "created_at": "2026-09-01T12:31:12.556Z" + }, + { + "patient_id": "PT-2026-00007", + "name": "harshda", + "age": 22, + "gender": "Female", + "phone": "7689345321", + "created_at": "2026-09-01T08:24:14.380Z" + }, + { + "patient_id": "PT-2026-00006", + "name": "sakshi", + "age": 24, + "gender": "Female", + "phone": "9823456543", + "created_at": "2026-09-01T07:32:11.920Z" + }, + { + "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-000011", + "patient_id": "PT-2026-00008", + "patient_name": "Om", + "doctor_id": "DOC-001", + "doctor_name": "Dr. Sharma", + "consultation_date": "2026-09-01", + "time_formatted": "06:01 PM", + "duration_seconds": 93, + "duration_formatted": "01 min 33 sec", + "audio_file": "rec_1788265882869.wav", + "language": "mr-IN", + "transcript": "**Doctor:** नमस्कार, मी आपापसात तुम्हाला नेमका काय त्रास होतो आहे?\n\n**Patient:** नमस्कार Doctor, मला गेल्या 3 दिवसापासून पोटात जास्त दुखत आहे, सुरुवातीला दुखणं कमी होतं, पण कालपासून जास्त जाणवत आहे.\n\n**Doctor:** दुखणं पोटाच्या नेमक्या कोणत्या भागात होतं आणि ताप normal किंवा उलटी सारखे लक्षणं आहेत का?\n\n**Patient:** दुखणं मुख्यतः उजव्या बाजूच्या खालच्या पोटात आहे, काल थोडा ताप होता आणि 2 वेळा माळवा ही झाला.\n\n**Doctor:** तुमची पूर्वी काही surgery झाली आहे का किंवा appendix, gastric problem किंवा इतर कोणता आजार आहे का?\n\n**Patient:** हो Doctor, सुमारे 2 वर्षांपूर्वी पोटाची surgery झाली होती पण त्यानंतर काही विशेषता त्रास झाला नव्हता.\n\n**Doctor:** ठीक आहे, मी तुमची clinical examination करतो. त्यानंतर blood test, CPC आणि CRP तपासणी करावी लागेल. गरज पडल्यास abdominal ultrasound देखील करावा लागेल.\n\n**Patient:** Doctor, हे infection मुळे असू शकत का?\n\n**Doctor:** शक्यता आहे, पण तपासणी आणि report पाहिल्याशिवाय निश्चित ताजकी सांगता येणार नाही. तोपर्यंत भरपूर पाणी प्या आणि हलका आहार घ्या.\n\n**Patient:** ठीक आहे Doctor, दुखण्यासाठी काही medicines घ्यावी का?\n\n**Doctor:** मी आवश्यक त्या medicines घेऊन येतो, पण स्वतःहून antibiotics घेऊ नका. ताप किंवा पोटदुखी अचानक वाढली, पोटा सुख झाल्या किंवा जास्त अशक्तपणा जाणवला. आता ताबडतोब Hospital-मध्ये या.\n\n**Patient:** ठीक आहे Doctor, धन्यवाद.\n\n**Doctor:** ठीक आहे, report घेऊन पुन्हा follow-up-साठी या.", + "speaker_segments": [ + { + "speaker_id": "SPEAKER_0", + "start": 0, + "end": 4.5, + "text": "नमस्कार, मी आपापसात तुम्हाला नेमका काय त्रास होतो आहे?", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 4.5, + "end": 13.9, + "text": "नमस्कार Doctor, मला गेल्या 3 दिवसापासून पोटात जास्त दुखत आहे, सुरुवातीला दुखणं कमी होतं, पण कालपासून जास्त जाणवत आहे.", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 13.9, + "end": 21.3, + "text": "दुखणं पोटाच्या नेमक्या कोणत्या भागात होतं आणि ताप normal किंवा उलटी सारखे लक्षणं आहेत का?", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 21.3, + "end": 29.7, + "text": "दुखणं मुख्यतः उजव्या बाजूच्या खालच्या पोटात आहे, काल थोडा ताप होता आणि 2 वेळा माळवा ही झाला.", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 29.7, + "end": 38.2, + "text": "तुमची पूर्वी काही surgery झाली आहे का किंवा appendix, gastric problem किंवा इतर कोणता आजार आहे का?", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 38.2, + "end": 46.1, + "text": "हो Doctor, सुमारे 2 वर्षांपूर्वी पोटाची surgery झाली होती पण त्यानंतर काही विशेषता त्रास झाला नव्हता.", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 46.1, + "end": 57.5, + "text": "ठीक आहे, मी तुमची clinical examination करतो. त्यानंतर blood test, CPC आणि CRP तपासणी करावी लागेल. गरज पडल्यास abdominal ultrasound देखील करावा लागेल.", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 57.5, + "end": 61, + "text": "Doctor, हे infection मुळे असू शकत का?", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 61, + "end": 70.9, + "text": "शक्यता आहे, पण तपासणी आणि report पाहिल्याशिवाय निश्चित ताजकी सांगता येणार नाही. तोपर्यंत भरपूर पाणी प्या आणि हलका आहार घ्या.", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 70.9, + "end": 74.9, + "text": "ठीक आहे Doctor, दुखण्यासाठी काही medicines घ्यावी का?", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 74.9, + "end": 88.2, + "text": "मी आवश्यक त्या medicines घेऊन येतो, पण स्वतःहून antibiotics घेऊ नका. ताप किंवा पोटदुखी अचानक वाढली, पोटा सुख झाल्या किंवा जास्त अशक्तपणा जाणवला. आता ताबडतोब Hospital-मध्ये या.", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 88.2, + "end": 90.2, + "text": "ठीक आहे Doctor, धन्यवाद.", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 90.2, + "end": 93.7, + "text": "ठीक आहे, report घेऊन पुन्हा follow-up-साठी या.", + "detected_role": "Doctor", + "confidence": 0.835 + } + ], + "summary": { + "chief_complaint": "Patient reports pain in the lower right abdomen for the past 3 days.", + "symptoms": [ + "Pain in the lower right abdomen", + "Fever yesterday", + "2 episodes of loose motions" + ], + "history": "Had a stomach surgery about 2 years ago with no subsequent issues.", + "assessment": "Possibility of an infection; diagnosis is not confirmed without further tests.", + "recommendation": "Drink plenty of water, take a light diet, and do not take antibiotics on your own. Get a clinical examination, blood test (including CPC and CRP), and possibly an abdominal ultrasound. Return to the hospital immediately if fever or stomach pain suddenly increases, if there is abdominal distension, or if there is increased weakness." + }, + "status": "Completed", + "created_at": "2026-09-01T12:31:22.880Z", + "updated_at": "2026-09-01T12:31:22.880Z" + }, + { + "consultation_id": "CONS-2026-000010", + "patient_id": "PT-2026-00008", + "patient_name": "Om", + "doctor_id": "DOC-001", + "doctor_name": "Dr. Sharma", + "consultation_date": "2026-09-01", + "time_formatted": "06:01 PM", + "duration_seconds": 93, + "duration_formatted": "01 min 33 sec", + "audio_file": "rec_1788265881359.wav", + "language": "mr-IN", + "transcript": "**Doctor:** नमस्कार, मी आपापसात तुम्हाला नेमका काय त्रास होतो आहे?\n\n**Patient:** नमस्कार Doctor, मला गेल्या 3 दिवसापासून पोटात जास्त दुखत आहे, सुरुवातीला दुखणं कमी होतं, पण कालपासून जास्त जाणवत आहे.\n\n**Doctor:** दुखणं पोटाच्या नेमक्या कोणत्या भागात होतं आणि ताप normal किंवा उलटी सारखे लक्षणं आहेत का?\n\n**Patient:** दुखणं मुख्यतः उजव्या बाजूच्या खालच्या पोटात आहे, काल थोडा ताप होता आणि 2 वेळा माळवा ही झाला.\n\n**Doctor:** तुमची पूर्वी काही surgery झाली आहे का किंवा appendix, gastric problem किंवा इतर कोणता आजार आहे का?\n\n**Patient:** हो Doctor, सुमारे 2 वर्षांपूर्वी पोटाची surgery झाली होती पण त्यानंतर काही विशेषता त्रास झाला नव्हता.\n\n**Doctor:** ठीक आहे, मी तुमची clinical examination करतो. त्यानंतर blood test, CPC आणि CRP तपासणी करावी लागेल. गरज पडल्यास abdominal ultrasound देखील करावा लागेल.\n\n**Patient:** Doctor, हे infection मुळे असू शकत का?\n\n**Doctor:** शक्यता आहे, पण तपासणी आणि report पाहिल्याशिवाय निश्चित ताजकी सांगता येणार नाही. तोपर्यंत भरपूर पाणी प्या आणि हलका आहार घ्या.\n\n**Patient:** ठीक आहे Doctor, दुखण्यासाठी काही medicines घ्यावी का?\n\n**Doctor:** मी आवश्यक त्या medicines घेऊन येतो, पण स्वतःहून antibiotics घेऊ नका. ताप किंवा पोटदुखी अचानक वाढली, पोटा सुख झाल्या किंवा जास्त अशक्तपणा जाणवला. आता ताबडतोब Hospital-मध्ये या.\n\n**Patient:** ठीक आहे Doctor, धन्यवाद.\n\n**Doctor:** ठीक आहे, report घेऊन पुन्हा follow-up-साठी या.", + "speaker_segments": [ + { + "speaker_id": "SPEAKER_0", + "start": 0, + "end": 4.5, + "text": "नमस्कार, मी आपापसात तुम्हाला नेमका काय त्रास होतो आहे?", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 4.5, + "end": 13.9, + "text": "नमस्कार Doctor, मला गेल्या 3 दिवसापासून पोटात जास्त दुखत आहे, सुरुवातीला दुखणं कमी होतं, पण कालपासून जास्त जाणवत आहे.", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 13.9, + "end": 21.3, + "text": "दुखणं पोटाच्या नेमक्या कोणत्या भागात होतं आणि ताप normal किंवा उलटी सारखे लक्षणं आहेत का?", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 21.3, + "end": 29.7, + "text": "दुखणं मुख्यतः उजव्या बाजूच्या खालच्या पोटात आहे, काल थोडा ताप होता आणि 2 वेळा माळवा ही झाला.", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 29.7, + "end": 38.2, + "text": "तुमची पूर्वी काही surgery झाली आहे का किंवा appendix, gastric problem किंवा इतर कोणता आजार आहे का?", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 38.2, + "end": 46.1, + "text": "हो Doctor, सुमारे 2 वर्षांपूर्वी पोटाची surgery झाली होती पण त्यानंतर काही विशेषता त्रास झाला नव्हता.", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 46.1, + "end": 57.5, + "text": "ठीक आहे, मी तुमची clinical examination करतो. त्यानंतर blood test, CPC आणि CRP तपासणी करावी लागेल. गरज पडल्यास abdominal ultrasound देखील करावा लागेल.", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 57.5, + "end": 61, + "text": "Doctor, हे infection मुळे असू शकत का?", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 61, + "end": 70.9, + "text": "शक्यता आहे, पण तपासणी आणि report पाहिल्याशिवाय निश्चित ताजकी सांगता येणार नाही. तोपर्यंत भरपूर पाणी प्या आणि हलका आहार घ्या.", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 70.9, + "end": 74.9, + "text": "ठीक आहे Doctor, दुखण्यासाठी काही medicines घ्यावी का?", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 74.9, + "end": 88.2, + "text": "मी आवश्यक त्या medicines घेऊन येतो, पण स्वतःहून antibiotics घेऊ नका. ताप किंवा पोटदुखी अचानक वाढली, पोटा सुख झाल्या किंवा जास्त अशक्तपणा जाणवला. आता ताबडतोब Hospital-मध्ये या.", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 88.2, + "end": 90.2, + "text": "ठीक आहे Doctor, धन्यवाद.", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 90.2, + "end": 93.7, + "text": "ठीक आहे, report घेऊन पुन्हा follow-up-साठी या.", + "detected_role": "Doctor", + "confidence": 0.835 + } + ], + "summary": { + "chief_complaint": "Patient reports pain in the lower right abdomen for the past 3 days.", + "symptoms": [ + "Pain in the lower right abdomen", + "Fever yesterday", + "2 episodes of loose motions" + ], + "history": "Had a stomach surgery about 2 years ago with no subsequent issues.", + "assessment": "Possibility of an infection; diagnosis is not confirmed without further tests.", + "recommendation": "Drink plenty of water, take a light diet, and do not take antibiotics on your own. Get a clinical examination, blood test (including CPC and CRP), and possibly an abdominal ultrasound. Return to the hospital immediately if fever or stomach pain suddenly increases, if there is abdominal distension, or if there is increased weakness." + }, + "status": "Completed", + "created_at": "2026-09-01T12:31:21.369Z", + "updated_at": "2026-09-01T12:31:21.369Z" + }, + { + "consultation_id": "CONS-2026-000009", + "patient_id": "PT-2026-00124", + "patient_name": "Sanika Gurav", + "doctor_id": "DOC-001", + "doctor_name": "Dr. Sharma", + "consultation_date": "2026-09-01", + "time_formatted": "06:00 PM", + "duration_seconds": 93, + "duration_formatted": "01 min 33 sec", + "audio_file": "rec_1788265823479.wav", + "language": "mr-IN", + "transcript": "**Doctor:** नमस्कार, मी आपापसात तुम्हाला नेमका काय त्रास होतो आहे?\n\n**Patient:** नमस्कार Doctor, मला गेल्या 3 दिवसापासून पोटात जास्त दुखत आहे, सुरुवातीला दुखणं कमी होतं, पण कालपासून जास्त जाणवत आहे.\n\n**Doctor:** दुखणं पोटाच्या नेमक्या कोणत्या भागात होतं आणि ताप normal किंवा उलटी सारखे लक्षणं आहेत का?\n\n**Patient:** दुखणं मुख्यतः उजव्या बाजूच्या खालच्या पोटात आहे, काल थोडा ताप होता आणि 2 वेळा माळवा ही झाला.\n\n**Doctor:** तुमची पूर्वी काही surgery झाली आहे का किंवा appendix, gastric problem किंवा इतर कोणता आजार आहे का?\n\n**Patient:** हो Doctor, सुमारे 2 वर्षांपूर्वी पोटाची surgery झाली होती पण त्यानंतर काही विशेषता त्रास झाला नव्हता.\n\n**Doctor:** ठीक आहे, मी तुमची clinical examination करतो. त्यानंतर blood test, CPC आणि CRP तपासणी करावी लागेल. गरज पडल्यास abdominal ultrasound देखील करावा लागेल.\n\n**Patient:** Doctor, हे infection मुळे असू शकत का?\n\n**Doctor:** शक्यता आहे, पण तपासणी आणि report पाहिल्याशिवाय निश्चित ताजकी सांगता येणार नाही. तोपर्यंत भरपूर पाणी प्या आणि हलका आहार घ्या.\n\n**Patient:** ठीक आहे Doctor, दुखण्यासाठी काही medicines घ्यावी का?\n\n**Doctor:** मी आवश्यक त्या medicines घेऊन येतो, पण स्वतःहून antibiotics घेऊ नका. ताप किंवा पोटदुखी अचानक वाढली, पोटा सुख झाल्या किंवा जास्त अशक्तपणा जाणवला. आता ताबडतोब Hospital-मध्ये या.\n\n**Patient:** ठीक आहे Doctor, धन्यवाद.\n\n**Doctor:** ठीक आहे, report घेऊन पुन्हा follow-up-साठी या.", + "speaker_segments": [ + { + "speaker_id": "SPEAKER_0", + "start": 0, + "end": 4.5, + "text": "नमस्कार, मी आपापसात तुम्हाला नेमका काय त्रास होतो आहे?", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 4.5, + "end": 13.9, + "text": "नमस्कार Doctor, मला गेल्या 3 दिवसापासून पोटात जास्त दुखत आहे, सुरुवातीला दुखणं कमी होतं, पण कालपासून जास्त जाणवत आहे.", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 13.9, + "end": 21.3, + "text": "दुखणं पोटाच्या नेमक्या कोणत्या भागात होतं आणि ताप normal किंवा उलटी सारखे लक्षणं आहेत का?", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 21.3, + "end": 29.7, + "text": "दुखणं मुख्यतः उजव्या बाजूच्या खालच्या पोटात आहे, काल थोडा ताप होता आणि 2 वेळा माळवा ही झाला.", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 29.7, + "end": 38.2, + "text": "तुमची पूर्वी काही surgery झाली आहे का किंवा appendix, gastric problem किंवा इतर कोणता आजार आहे का?", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 38.2, + "end": 46.1, + "text": "हो Doctor, सुमारे 2 वर्षांपूर्वी पोटाची surgery झाली होती पण त्यानंतर काही विशेषता त्रास झाला नव्हता.", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 46.1, + "end": 57.5, + "text": "ठीक आहे, मी तुमची clinical examination करतो. त्यानंतर blood test, CPC आणि CRP तपासणी करावी लागेल. गरज पडल्यास abdominal ultrasound देखील करावा लागेल.", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 57.5, + "end": 61, + "text": "Doctor, हे infection मुळे असू शकत का?", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 61, + "end": 70.9, + "text": "शक्यता आहे, पण तपासणी आणि report पाहिल्याशिवाय निश्चित ताजकी सांगता येणार नाही. तोपर्यंत भरपूर पाणी प्या आणि हलका आहार घ्या.", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 70.9, + "end": 74.9, + "text": "ठीक आहे Doctor, दुखण्यासाठी काही medicines घ्यावी का?", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 74.9, + "end": 88.2, + "text": "मी आवश्यक त्या medicines घेऊन येतो, पण स्वतःहून antibiotics घेऊ नका. ताप किंवा पोटदुखी अचानक वाढली, पोटा सुख झाल्या किंवा जास्त अशक्तपणा जाणवला. आता ताबडतोब Hospital-मध्ये या.", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 88.2, + "end": 90.2, + "text": "ठीक आहे Doctor, धन्यवाद.", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 90.2, + "end": 93.7, + "text": "ठीक आहे, report घेऊन पुन्हा follow-up-साठी या.", + "detected_role": "Doctor", + "confidence": 0.835 + } + ], + "summary": { + "chief_complaint": "Patient reports pain in the lower right abdomen for the past 3 days.", + "symptoms": [ + "Pain in the lower right abdomen", + "Fever yesterday", + "2 episodes of loose motions" + ], + "history": "Had a stomach surgery about 2 years ago with no subsequent issues.", + "assessment": "Possibility of an infection; diagnosis is not confirmed without further tests.", + "recommendation": "Drink plenty of water, take a light diet, and do not take antibiotics on your own. Get a clinical examination, blood test (including CPC and CRP), and possibly an abdominal ultrasound. Return to the hospital immediately if fever or stomach pain suddenly increases, if there is abdominal distension, or if there is increased weakness." + }, + "status": "Completed", + "created_at": "2026-09-01T12:30:23.490Z", + "updated_at": "2026-09-01T12:30:23.490Z" + }, + { + "consultation_id": "CONS-2026-000008", + "patient_id": "PT-2026-00124", + "patient_name": "Sanika Gurav", + "doctor_id": "DOC-001", + "doctor_name": "Dr. Sharma", + "consultation_date": "2026-09-01", + "time_formatted": "06:00 PM", + "duration_seconds": 93, + "duration_formatted": "01 min 33 sec", + "audio_file": "rec_1788265820100.wav", + "language": "mr-IN", + "transcript": "**Doctor:** नमस्कार, मी आपापसात तुम्हाला नेमका काय त्रास होतो आहे?\n\n**Patient:** नमस्कार Doctor, मला गेल्या 3 दिवसापासून पोटात जास्त दुखत आहे, सुरुवातीला दुखणं कमी होतं, पण कालपासून जास्त जाणवत आहे.\n\n**Doctor:** दुखणं पोटाच्या नेमक्या कोणत्या भागात होतं आणि ताप normal किंवा उलटी सारखे लक्षणं आहेत का?\n\n**Patient:** दुखणं मुख्यतः उजव्या बाजूच्या खालच्या पोटात आहे, काल थोडा ताप होता आणि 2 वेळा माळवा ही झाला.\n\n**Doctor:** तुमची पूर्वी काही surgery झाली आहे का किंवा appendix, gastric problem किंवा इतर कोणता आजार आहे का?\n\n**Patient:** हो Doctor, सुमारे 2 वर्षांपूर्वी पोटाची surgery झाली होती पण त्यानंतर काही विशेषता त्रास झाला नव्हता.\n\n**Doctor:** ठीक आहे, मी तुमची clinical examination करतो. त्यानंतर blood test, CPC आणि CRP तपासणी करावी लागेल. गरज पडल्यास abdominal ultrasound देखील करावा लागेल.\n\n**Patient:** Doctor, हे infection मुळे असू शकत का?\n\n**Doctor:** शक्यता आहे, पण तपासणी आणि report पाहिल्याशिवाय निश्चित ताजकी सांगता येणार नाही. तोपर्यंत भरपूर पाणी प्या आणि हलका आहार घ्या.\n\n**Patient:** ठीक आहे Doctor, दुखण्यासाठी काही medicines घ्यावी का?\n\n**Doctor:** मी आवश्यक त्या medicines घेऊन येतो, पण स्वतःहून antibiotics घेऊ नका. ताप किंवा पोटदुखी अचानक वाढली, पोटा सुख झाल्या किंवा जास्त अशक्तपणा जाणवला. आता ताबडतोब Hospital-मध्ये या.\n\n**Patient:** ठीक आहे Doctor, धन्यवाद.\n\n**Doctor:** ठीक आहे, report घेऊन पुन्हा follow-up-साठी या.", + "speaker_segments": [ + { + "speaker_id": "SPEAKER_0", + "start": 0, + "end": 4.5, + "text": "नमस्कार, मी आपापसात तुम्हाला नेमका काय त्रास होतो आहे?", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 4.5, + "end": 13.9, + "text": "नमस्कार Doctor, मला गेल्या 3 दिवसापासून पोटात जास्त दुखत आहे, सुरुवातीला दुखणं कमी होतं, पण कालपासून जास्त जाणवत आहे.", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 13.9, + "end": 21.3, + "text": "दुखणं पोटाच्या नेमक्या कोणत्या भागात होतं आणि ताप normal किंवा उलटी सारखे लक्षणं आहेत का?", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 21.3, + "end": 29.7, + "text": "दुखणं मुख्यतः उजव्या बाजूच्या खालच्या पोटात आहे, काल थोडा ताप होता आणि 2 वेळा माळवा ही झाला.", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 29.7, + "end": 38.2, + "text": "तुमची पूर्वी काही surgery झाली आहे का किंवा appendix, gastric problem किंवा इतर कोणता आजार आहे का?", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 38.2, + "end": 46.1, + "text": "हो Doctor, सुमारे 2 वर्षांपूर्वी पोटाची surgery झाली होती पण त्यानंतर काही विशेषता त्रास झाला नव्हता.", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 46.1, + "end": 57.5, + "text": "ठीक आहे, मी तुमची clinical examination करतो. त्यानंतर blood test, CPC आणि CRP तपासणी करावी लागेल. गरज पडल्यास abdominal ultrasound देखील करावा लागेल.", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 57.5, + "end": 61, + "text": "Doctor, हे infection मुळे असू शकत का?", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 61, + "end": 70.9, + "text": "शक्यता आहे, पण तपासणी आणि report पाहिल्याशिवाय निश्चित ताजकी सांगता येणार नाही. तोपर्यंत भरपूर पाणी प्या आणि हलका आहार घ्या.", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 70.9, + "end": 74.9, + "text": "ठीक आहे Doctor, दुखण्यासाठी काही medicines घ्यावी का?", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 74.9, + "end": 88.2, + "text": "मी आवश्यक त्या medicines घेऊन येतो, पण स्वतःहून antibiotics घेऊ नका. ताप किंवा पोटदुखी अचानक वाढली, पोटा सुख झाल्या किंवा जास्त अशक्तपणा जाणवला. आता ताबडतोब Hospital-मध्ये या.", + "detected_role": "Doctor", + "confidence": 0.835 + }, + { + "speaker_id": "SPEAKER_1", + "start": 88.2, + "end": 90.2, + "text": "ठीक आहे Doctor, धन्यवाद.", + "detected_role": "Patient", + "confidence": 0.7899999999999999 + }, + { + "speaker_id": "SPEAKER_0", + "start": 90.2, + "end": 93.7, + "text": "ठीक आहे, report घेऊन पुन्हा follow-up-साठी या.", + "detected_role": "Doctor", + "confidence": 0.835 + } + ], + "summary": { + "chief_complaint": "Patient reports pain in the lower right abdomen for the past 3 days.", + "symptoms": [ + "Pain in the lower right abdomen", + "Fever yesterday", + "2 episodes of loose motions" + ], + "history": "Had a stomach surgery about 2 years ago with no subsequent issues.", + "assessment": "Possibility of an infection; diagnosis is not confirmed without further tests.", + "recommendation": "Drink plenty of water, take a light diet, and do not take antibiotics on your own. Get a clinical examination, blood test (including CPC and CRP), and possibly an abdominal ultrasound. Return to the hospital immediately if fever or stomach pain suddenly increases, if there is abdominal distension, or if there is increased weakness." + }, + "status": "Completed", + "created_at": "2026-09-01T12:30:20.137Z", + "updated_at": "2026-09-01T12:30:20.137Z" + }, + { + "consultation_id": "CONS-2026-000007", + "patient_id": "PT-2026-00006", + "patient_name": "sakshi", + "doctor_id": "DOC-001", + "doctor_name": "Dr. Sharma", + "consultation_date": "2026-09-01", + "time_formatted": "01:48 PM", + "duration_seconds": 246, + "duration_formatted": "04 min 06 sec", + "audio_file": "rec_1788250732879.wav", + "language": "mr-IN", + "transcript": "**Doctor:** बरं कधीपासून?\n\n**Patient:** मला आता 2-क महिने झाले. पण आता थोडा कमी आहे पण आहेच. असे बेडके वगैरे नाही पडत. आधीचा काय आजार diabetes वगैरे?\n\n**Doctor:** diabetes आहे. sugar आहे, BP आहे. आता हे PET scan झालं तुमचं?\n\n**Patient:** नाही PET scan नाही झालं. आता या औषधांनी बरं आहे का?\n\n**Doctor:** तुम्हाला दिलेल्या औषधा आता हे कालच कालच दिलेले आहेत.\n\n**Patient:** report मिळाला बरोबर आहे पण हे जे तुम्हाला दिलेले आहेत औषध हे दोनच दोनच दोनच द्यायचे आहेत.\n\n**Doctor:** ह्याचा block आहे का तुमच्याकडे तुकडा दिलाय?\n\n**Patient:** नाही. हा आपल्याला block लागेल अच्छा OK कारण याच्यावरती आपल्याला काही test लागतात OK chemical test म्हणजे तुम्हाला परत biopsy करायची गरज नाही पडणार OK आणि कसं बोलवायचं block त्यांना phone करा OK इथलं तुमचं जे आहे.\n\n**Doctor:** नंबर आहे त्यांना म्हणावं की आम्हाला याचा block पाहिजे.\n\n**Patient:** लिहिलेलं आहे बघा specimen will be discarded after 1 month.\n\n**Doctor:** OK चालेल. त्यामुळे 1 महिन्यापर्यंत असतं ते. OK लगेच घेऊन ठेवा याच्यावरती आपण test पाठवू आणि 1 PET scan.\n\n**Patient:** हे 2 test करून आपण पुढच्या treatment-च्या बद्दल बोलू की काय करायचं.\n\n**Doctor:** सध्या तुम्हाला आता खोकला control मध्ये आहे का?\n\n**Patient:** हो कमी आहे. नाही म्हणजे आहे भरपूर असतं. आहे भरपूर आहे. खोकला control मध्ये नाही आहे आणि जेवण बिलकुल जात नाही.\n\n**Doctor:** इथे कुठे राहता तुम्ही Pune-त?\n\n**Patient:** हे जागेत आहे. तर pet scan मग आज केला तर चालेल आज होणार नाही सकाळी उपाशी पुढे करायला लागतं तुम्हाला appointment घ्यायला लागेल पिंजोडी लावत असेल तर दुसरा 1 option आहे त्या बाजूला बाहेरला Jupiter Hospital आहे तुम्हाला एवढ्या लांब याची गरज नाही उद्याची appointment घ्या जे काही test सांगतो त्या करून घ्या बरं आणि to bring blocks आपल्याला स्वतः आणावं लागतं आणि पण तुमचे नातेवाईक असेच घेऊ शकतात.\n\n**Doctor:** अच्छा आपण पण आणू शकतो basically. Diabetes नाही आहे ना?\n\n**Patient:** आहे आहे. आहे. याच्या गोळ्या control-मध्ये आहेत?\n\n**Doctor:** हो हो. आता test केली तर 175 होते सर sugar. काही त्रास नाही. मी फक्त 1 गोळी घेतो जरा थोडीशी सूज कमी होते आतनं पण थोडीशी sugar वाढू शकते पण फार load असते पण दिले आहेत हा मग मी दुसरा दिले फक्त.\n\n**Patient:** आणि भूक लागत नाही. हो ठीक आहे तर. हे दिलंय त्यांनी तुम्हाला. दिलंय. ठीक आहे तुम्ही बाहेर बसला तरी चालेल मी इथे बघतो. आजार आहे का?\n\n**Doctor:** नाही patient-ला नाही. तर lung-मध्ये cancer आहे. OK. तर त्याचा फक्त कुठला type आहे ते आपल्याला confirm करायचं आहे.\n\n**Patient:** तर त्यासाठी ते chemical test असतं. 2nd PET scan बघून अजून कुठे आहे का?\n\n**Doctor:** फक्त lung-मध्ये आहे का?\n\n**Patient:** lung सोडून बाकीच्या अवयवांमध्ये आहे त्याच्यातून stage कळते.\n\n**Doctor:** OK. जर सगळीकडे spread असेल तर तो cure-च्या level-ला नसतो.\n\n**Patient:** आपल्याला control ठेवायला फक्त chemo किंवा target therapy किंवा immunotherapy हे काय वापरायचे हे आपल्याला त्या block-वरच्या test-मधून ठरवायचे.\n\n**Doctor:** So आता पहिल्यांदा मी तुम्हाला तात्पुरत्या 1-2 दिवसात ती गोळ्या देतोय.\n\n**Patient:** PET scan-मध्ये जर तो तिथल्या रीतच असेल तर मग आपल्याला काही local treatment करायची तरी ठरवायला लागतं आणि जर सगळीकडे असेल तर chemo start करायला लागते side by side बाकीचे test करायचे.\n\n**Doctor:** मग हे लगेच start करायचं ना?\n\n**Patient:** लगेच म्हणजे Monday-पासून आपण पुढच्या गोष्टी करू शकतो.\n\n**Doctor:** सर तुम्हाला इथल्या व्यतिरिक्त तुमचं कुठे आहे म्हणजे मी अव्हाणला पण 1 OPD आहे आणि शुक्रवारी असते पण तोपर्यंत 2 दिवसात report येतील म्हटलेल्या तुम्ही मला phone करा किंवा message करा मी तुम्हाला सांगतो ना चालू ठेवतो का नाही बरं जरा", + "speaker_segments": [ + { + "speaker": "Doctor", + "text": "बरं कधीपासून?" + }, + { + "speaker": "Patient", + "text": "मला आता 2-क महिने झाले. पण आता थोडा कमी आहे पण आहेच. असे बेडके वगैरे नाही पडत. आधीचा काय आजार diabetes वगैरे?" + }, + { + "speaker": "Doctor", + "text": "diabetes आहे. sugar आहे, BP आहे. आता हे PET scan झालं तुमचं?" + }, + { + "speaker": "Patient", + "text": "नाही PET scan नाही झालं. आता या औषधांनी बरं आहे का?" + }, + { + "speaker": "Doctor", + "text": "तुम्हाला दिलेल्या औषधा आता हे कालच कालच दिलेले आहेत." + }, + { + "speaker": "Patient", + "text": "report मिळाला बरोबर आहे पण हे जे तुम्हाला दिलेले आहेत औषध हे दोनच दोनच दोनच द्यायचे आहेत." + }, + { + "speaker": "Doctor", + "text": "ह्याचा block आहे का तुमच्याकडे तुकडा दिलाय?" + }, + { + "speaker": "Patient", + "text": "नाही. हा आपल्याला block लागेल अच्छा OK कारण याच्यावरती आपल्याला काही test लागतात OK chemical test म्हणजे तुम्हाला परत biopsy करायची गरज नाही पडणार OK आणि कसं बोलवायचं block त्यांना phone करा OK इथलं तुमचं जे आहे." + }, + { + "speaker": "Doctor", + "text": "नंबर आहे त्यांना म्हणावं की आम्हाला याचा block पाहिजे." + }, + { + "speaker": "Patient", + "text": "लिहिलेलं आहे बघा specimen will be discarded after 1 month." + }, + { + "speaker": "Doctor", + "text": "OK चालेल. त्यामुळे 1 महिन्यापर्यंत असतं ते. OK लगेच घेऊन ठेवा याच्यावरती आपण test पाठवू आणि 1 PET scan." + }, + { + "speaker": "Patient", + "text": "हे 2 test करून आपण पुढच्या treatment-च्या बद्दल बोलू की काय करायचं." + }, + { + "speaker": "Doctor", + "text": "सध्या तुम्हाला आता खोकला control मध्ये आहे का?" + }, + { + "speaker": "Patient", + "text": "हो कमी आहे. नाही म्हणजे आहे भरपूर असतं. आहे भरपूर आहे. खोकला control मध्ये नाही आहे आणि जेवण बिलकुल जात नाही." + }, + { + "speaker": "Doctor", + "text": "इथे कुठे राहता तुम्ही Pune-त?" + }, + { + "speaker": "Patient", + "text": "हे जागेत आहे. तर pet scan मग आज केला तर चालेल आज होणार नाही सकाळी उपाशी पुढे करायला लागतं तुम्हाला appointment घ्यायला लागेल पिंजोडी लावत असेल तर दुसरा 1 option आहे त्या बाजूला बाहेरला Jupiter Hospital आहे तुम्हाला एवढ्या लांब याची गरज नाही उद्याची appointment घ्या जे काही test सांगतो त्या करून घ्या बरं आणि to bring blocks आपल्याला स्वतः आणावं लागतं आणि पण तुमचे नातेवाईक असेच घेऊ शकतात." + }, + { + "speaker": "Doctor", + "text": "अच्छा आपण पण आणू शकतो basically. Diabetes नाही आहे ना?" + }, + { + "speaker": "Patient", + "text": "आहे आहे. आहे. याच्या गोळ्या control-मध्ये आहेत?" + }, + { + "speaker": "Doctor", + "text": "हो हो. आता test केली तर 175 होते सर sugar. काही त्रास नाही. मी फक्त 1 गोळी घेतो जरा थोडीशी सूज कमी होते आतनं पण थोडीशी sugar वाढू शकते पण फार load असते पण दिले आहेत हा मग मी दुसरा दिले फक्त." + }, + { + "speaker": "Patient", + "text": "आणि भूक लागत नाही. हो ठीक आहे तर. हे दिलंय त्यांनी तुम्हाला. दिलंय. ठीक आहे तुम्ही बाहेर बसला तरी चालेल मी इथे बघतो. आजार आहे का?" + }, + { + "speaker": "Doctor", + "text": "नाही patient-ला नाही. तर lung-मध्ये cancer आहे. OK. तर त्याचा फक्त कुठला type आहे ते आपल्याला confirm करायचं आहे." + }, + { + "speaker": "Patient", + "text": "तर त्यासाठी ते chemical test असतं. 2nd PET scan बघून अजून कुठे आहे का?" + }, + { + "speaker": "Doctor", + "text": "फक्त lung-मध्ये आहे का?" + }, + { + "speaker": "Patient", + "text": "lung सोडून बाकीच्या अवयवांमध्ये आहे त्याच्यातून stage कळते." + }, + { + "speaker": "Doctor", + "text": "OK. जर सगळीकडे spread असेल तर तो cure-च्या level-ला नसतो." + }, + { + "speaker": "Patient", + "text": "आपल्याला control ठेवायला फक्त chemo किंवा target therapy किंवा immunotherapy हे काय वापरायचे हे आपल्याला त्या block-वरच्या test-मधून ठरवायचे." + }, + { + "speaker": "Doctor", + "text": "So आता पहिल्यांदा मी तुम्हाला तात्पुरत्या 1-2 दिवसात ती गोळ्या देतोय." + }, + { + "speaker": "Patient", + "text": "PET scan-मध्ये जर तो तिथल्या रीतच असेल तर मग आपल्याला काही local treatment करायची तरी ठरवायला लागतं आणि जर सगळीकडे असेल तर chemo start करायला लागते side by side बाकीचे test करायचे." + }, + { + "speaker": "Doctor", + "text": "मग हे लगेच start करायचं ना?" + }, + { + "speaker": "Patient", + "text": "लगेच म्हणजे Monday-पासून आपण पुढच्या गोष्टी करू शकतो." + }, + { + "speaker": "Doctor", + "text": "सर तुम्हाला इथल्या व्यतिरिक्त तुमचं कुठे आहे म्हणजे मी अव्हाणला पण 1 OPD आहे आणि शुक्रवारी असते पण तोपर्यंत 2 दिवसात report येतील म्हटलेल्या तुम्ही मला phone करा किंवा message करा मी तुम्हाला सांगतो ना चालू ठेवतो का नाही बरं जरा" + } + ], + "summary": {}, + "status": "Completed", + "created_at": "2026-09-01T08:18:52.892Z", + "updated_at": "2026-09-01T08:18:52.892Z" + }, + { + "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" + } + ] +} \ No newline at end of file diff --git a/db.js b/db.js new file mode 100644 index 0000000..0120a73 --- /dev/null +++ b/db.js @@ -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) + }; + } +}; diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 0000000..055742c --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,341 @@ + + + + + + AI Clinical Assistant — Doctor-Patient Consultation + + + + + + +
+ + + + + +
+
+
+ +

New Consultation

+
+ +
+
+ 🌐 + + ▾ +
+ + + +
+ Dr. Sharma +
+ Dr. Sharma + Cardiologist +
+
+
+
+ +
+
+ +
+
+
+ 📋 +

Consultation Details

+
+ +
+ +
+
+ +
+ 👤 + +
+
+ +
+ +
+ 🪪 + +
+
+ +
+ +
+ 🩺 + + ▾ +
+
+ +
+ +
+ 📅 + +
+
+
+
+ + +
+
+ +
00:00:00
+
+ +
+ 🎙️ + Ready to record consultation... +
+ +
+ +
+ + + +
+ + + + + + + + +
+
+ + +
+
+
+

TRANSCRIPT

+ +
+
+ + + +
+
+ + + +
+ + + +
+ +
+
+
🎙️
+

Recording in progress… Transcript will appear here in real time.

+ Speak into the microphone or click DEMO to see full real-time audio synchronization. +
+
+
+ + +
+
+
+ 📋 +

AI CLINICAL SUMMARY

+
+
+ + + +
+
+ +
+
+
Chief Complaint
+

—

+
+ +
+
Symptoms Discussed
+

—

+
+ +
+
Doctor's Recommendation / Diagnosis
+

—

+
+ +
+
Patient History & Comorbidities
+

—

+
+ +
+
Prescription, Tests & Treatment Plan (Rx)
+

—

+
+
+
+
+
+
+
+ + + +
Notification
+ + + + diff --git a/frontend/script.js b/frontend/script.js new file mode 100644 index 0000000..9f3748e --- /dev/null +++ b/frontend/script.js @@ -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 = '

Recording in progress… press ⏹ Stop & Transcribe when done.

'; + + // 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 = ` +
+ + Processing transcript, please wait… +
`; + } + + // ── 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 = '

Transcription failed. Please try again.

'; + 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 = '

No speech detected in the recording.

'; + 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' + ? `[${escHtml(language)}]` + : ''; + + 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 += ` +
+
+ ${icon} + ${name} + [${ts}] + ${i === 0 ? langTag : ''} +
+
${escHtml(sentence)}
+
`; + }); + + transcriptBody.innerHTML = html; + transcriptBody.scrollTop = transcriptBody.scrollHeight; + } + + // ── Reset / Clear ────────────────────────────────────────────────────────── + function resetAll() { + lastTranscript = ''; + recordedChunks = []; + transcriptBody.innerHTML = '

Transcript will appear here once recording starts…

'; + 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 = ` +
+ Generating summary… +
`; + 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 = ` +
+ Summary + ${escHtml(s.raw_text)} +
`; + } else { + renderSummary(s); + } + } catch (err) { + summaryBody.innerHTML = ` +
+ Error + ${escHtml(err.message)} +
`; + } + + summaryBtn.disabled = false; + } + + function renderSummary(s) { + function listHtml(arr) { + if (!arr || !arr.length) return 'Not mentioned'; + return '
    ' + arr.map(x => `
  • ${escHtml(String(x))}
  • `).join('') + '
'; + } + summaryBody.innerHTML = ` +
+ Chief Complaint + ${escHtml(s.chief_complaint || 'Not mentioned')} +
+
+ Symptoms + ${listHtml(s.symptoms)} +
+
+ Diagnosis + ${escHtml(s.assessment || 'Not mentioned')} +
+
+ Prescription + ${listHtml(s.plan)} +
`; + } + + // ── Event listeners ──────────────────────────────────────────────────────── + startBtn.addEventListener('click', startRecording); + stopBtn.addEventListener('click', stopRecording); + clearBtn.addEventListener('click', resetAll); + summaryBtn.addEventListener('click', generateSummary); + + // ── Init ─────────────────────────────────────────────────────────────────── + checkHealth(); +})(); diff --git a/frontend/style.css b/frontend/style.css new file mode 100644 index 0000000..f8b0f55 --- /dev/null +++ b/frontend/style.css @@ -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; } +} diff --git a/hybrid_diarization.py b/hybrid_diarization.py new file mode 100644 index 0000000..ef54a8a --- /dev/null +++ b/hybrid_diarization.py @@ -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 ") + 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() diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..39c63e1 --- /dev/null +++ b/package-lock.json @@ -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 + } + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..e5e242a --- /dev/null +++ b/package.json @@ -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" + } +} diff --git a/public/app.js b/public/app.js new file mode 100644 index 0000000..bf9cc8f --- /dev/null +++ b/public/app.js @@ -0,0 +1,1253 @@ +/** + * AI Clinical Assistant — Doctor-Patient Conversation + * Real-time Speech-to-Text, Audio Synchronization, and Clinical LLM Pipeline + */ +(function () { + 'use strict'; + + // ── DOM References ──────────────────────────────────────────────────────── + const startBtn = document.getElementById('startBtn'); + const stopBtn = document.getElementById('stopBtn'); + const uploadAudioBtn = document.getElementById('uploadAudioBtn'); + const audioFileInput = document.getElementById('audioFileInput'); + const demoBtn = document.getElementById('demoBtn'); + const timerEl = document.getElementById('timer'); + const recSubStatus = document.getElementById('recSubStatus'); + const recStatusText = document.getElementById('recStatusText'); + const recError = document.getElementById('recError'); + const recordingCard = document.querySelector('.recording-card'); + + // Transcript Elements + const transcriptBody = document.getElementById('transcriptBody'); + const copyTranscriptBtn = document.getElementById('copyTranscriptBtn'); + const clearTranscriptBtn = document.getElementById('clearTranscriptBtn'); + const transcriptSearch = document.getElementById('transcriptSearch'); + const liveRealtimeBadge = document.getElementById('liveRealtimeBadge'); + const filterPills = document.querySelectorAll('.filter-pill'); + + // Audio Player Sync Elements + const audioPlaybackBar = document.getElementById('audioPlaybackBar'); + const playAudioBtn = document.getElementById('playAudioBtn'); + const playIcon = document.getElementById('playIcon'); + const audioScrubber = document.getElementById('audioScrubber'); + const audioCurrentTime = document.getElementById('audioCurrentTime'); + const audioTotalDuration = document.getElementById('audioTotalDuration'); + + // Summary Elements + const summaryBody = document.getElementById('summaryBody'); + const sumChiefComplaint = document.getElementById('sumChiefComplaint'); + const sumSymptoms = document.getElementById('sumSymptoms'); + const sumAssessment = document.getElementById('sumAssessment'); + const sumHistory = document.getElementById('sumHistory'); + const sumPlan = document.getElementById('sumPlan'); + const copySummaryBtn = document.getElementById('copySummaryBtn'); + const printSummaryBtn = document.getElementById('printSummaryBtn'); + const exportJsonBtn = document.getElementById('exportJsonBtn'); + + // Form Inputs + const langSelect = document.getElementById('langSelect'); + const patientInput = document.getElementById('patientName'); + const patientIdInput = document.getElementById('patientId'); + const doctorSelect = document.getElementById('doctorName'); + const dateInput = document.getElementById('consultationDate'); + + // Canvas & Toast + const waveformCanvas = document.getElementById('waveformCanvas'); + const canvasCtx = waveformCanvas ? waveformCanvas.getContext('2d') : null; + const toastBox = document.getElementById('toastBox'); + + // Navigation & Modals + const navItems = document.querySelectorAll('.sidebar-nav .nav-item'); + const tabViews = document.querySelectorAll('.tab-view'); + const pageHeading = document.getElementById('pageHeading'); + const menuToggle = document.getElementById('menuToggle'); + const sidebar = document.getElementById('sidebar'); + + const patientModal = document.getElementById('patientModal'); + const openAddPatientBtn = document.getElementById('openAddPatientBtn'); + const btnAddNewPatientTab = document.getElementById('btnAddNewPatientTab'); + const closePatientModal = document.getElementById('closePatientModal'); + const cancelPatientModal = document.getElementById('cancelPatientModal'); + const savePatientBtn = document.getElementById('savePatientBtn'); + const newPatientName = document.getElementById('newPatientName'); + + // ── Audio Constants & Pipeline State ────────────────────────────────────── + const SAMPLE_RATE = 16000; + const BUFFER_SIZE = 4096; + + let audioCtx = null; + let sourceNode = null; + let processorNode = null; + let analyserNode = null; + let mediaStream = null; + let animationId = null; + let recording = false; + let timerInterval = null; + let secondsElapsed = 0; + let pcmChunks = []; + + // Real-time Recognition & Sync State + let speechRecognizer = null; + let liveUtterances = []; // Array of { id, speaker, role, text, startSec, endSec } + let currentTranscript = ''; + let currentSummaryData = null; + + // Audio Playback Player State + let audioPlayerAudio = null; // HTMLAudioElement or Synthesized Audio + let playerInterval = null; + let activeFilter = 'all'; + + // Initialize Today's Date + if (dateInput) { + const today = new Date(); + const dd = String(today.getDate()).padStart(2, '0'); + const mm = String(today.getMonth() + 1).padStart(2, '0'); + const yyyy = today.getFullYear(); + dateInput.value = `${dd}-${mm}-${yyyy}`; + } + + // ── Helper Utilities ────────────────────────────────────────────────────── + function showToast(msg) { + if (!toastBox) return; + toastBox.textContent = msg; + toastBox.classList.add('show'); + setTimeout(() => { + toastBox.classList.remove('show'); + }, 3000); + } + + function showError(msg) { + if (!recError) return; + recError.textContent = msg; + recError.style.display = 'block'; + } + + function clearError() { + if (!recError) return; + recError.textContent = ''; + recError.style.display = 'none'; + } + + function fmtTime(s) { + const secNum = Math.max(0, Math.floor(s || 0)); + const m = Math.floor(secNum / 60).toString().padStart(2, '0'); + const sec = (secNum % 60).toString().padStart(2, '0'); + return `${m}:${sec}`; + } + + function escapeHtml(str) { + const d = document.createElement('div'); + d.innerText = str || ''; + return d.innerHTML; + } + + // ── Audio Waveform Visualizer ───────────────────────────────────────────── + function drawVisualizer() { + if (!canvasCtx || !analyserNode) return; + const bufferLength = analyserNode.frequencyBinCount; + const dataArray = new Uint8Array(bufferLength); + + function renderFrame() { + if (!recording) { + canvasCtx.clearRect(0, 0, waveformCanvas.width, waveformCanvas.height); + canvasCtx.strokeStyle = '#cbd5e1'; + canvasCtx.lineWidth = 2; + canvasCtx.beginPath(); + canvasCtx.moveTo(0, waveformCanvas.height / 2); + canvasCtx.lineTo(waveformCanvas.width, waveformCanvas.height / 2); + canvasCtx.stroke(); + return; + } + + animationId = requestAnimationFrame(renderFrame); + analyserNode.getByteFrequencyData(dataArray); + + canvasCtx.clearRect(0, 0, waveformCanvas.width, waveformCanvas.height); + const barWidth = (waveformCanvas.width / 32) - 3; + let x = 2; + + for (let i = 0; i < 32; i++) { + const value = dataArray[i * 2] || 0; + const percent = value / 255; + const barHeight = Math.max(4, percent * waveformCanvas.height); + const y = (waveformCanvas.height - barHeight) / 2; + + const gradient = canvasCtx.createLinearGradient(0, y, 0, y + barHeight); + gradient.addColorStop(0, '#2563eb'); + gradient.addColorStop(1, '#10b981'); + + canvasCtx.fillStyle = gradient; + canvasCtx.beginPath(); + canvasCtx.roundRect(x, y, barWidth, barHeight, 3); + canvasCtx.fill(); + + x += barWidth + 3; + } + } + renderFrame(); + } + + // ── WAV Builder & Downsampler (16kHz PCM linear16 mono) ──────────────────── + async function downsampleNative(audioBuffer, targetSampleRate) { + // Native, instantaneous resampling using OfflineAudioContext + const length = Math.ceil(audioBuffer.duration * targetSampleRate); + const offlineCtx = new (window.OfflineAudioContext || window.webkitOfflineAudioContext)( + 1, + length, + targetSampleRate + ); + const source = offlineCtx.createBufferSource(); + source.buffer = audioBuffer; + source.connect(offlineCtx.destination); + source.start(0); + const renderedBuffer = await offlineCtx.startRendering(); + return renderedBuffer.getChannelData(0); + } + + function downsample(input, inputRate, outputRate) { + if (inputRate === outputRate) return input; + const ratio = inputRate / outputRate; + const newLength = Math.round(input.length / ratio); + const result = new Float32Array(newLength); + for (let i = 0; i < newLength; i++) { + const start = Math.round(i * ratio); + const end = Math.round((i + 1) * ratio); + let sum = 0, cnt = 0; + for (let j = start; j < end && j < input.length; j++) { + sum += input[j]; + cnt++; + } + result[i] = cnt > 0 ? sum / cnt : 0; + } + return result; + } + + function buildWav(float32Chunks, sampleRate) { + const totalLen = float32Chunks.reduce((s, c) => s + c.length, 0); + const merged = new Float32Array(totalLen); + let offset = 0; + for (const chunk of float32Chunks) { + merged.set(chunk, offset); + offset += chunk.length; + } + + const pcm16 = new Int16Array(merged.length); + for (let i = 0; i < merged.length; i++) { + const s = Math.max(-1, Math.min(1, merged[i])); + pcm16[i] = s < 0 ? s * 0x8000 : s * 0x7FFF; + } + + const dataBytes = pcm16.length * 2; + const buffer = new ArrayBuffer(44 + dataBytes); + const view = new DataView(buffer); + const numCh = 1; + const bps = 16; + const byteRate = sampleRate * numCh * bps / 8; + const blockAlign = numCh * bps / 8; + + function writeStr(off, str) { + for (let i = 0; i < str.length; i++) view.setUint8(off + i, str.charCodeAt(i)); + } + writeStr(0, 'RIFF'); + view.setUint32(4, 36 + dataBytes, true); + writeStr(8, 'WAVE'); + writeStr(12, 'fmt '); + view.setUint32(16, 16, true); + view.setUint16(20, 1, true); + view.setUint16(22, numCh, true); + view.setUint32(24, sampleRate, true); + view.setUint32(28, byteRate, true); + view.setUint16(32, blockAlign, true); + view.setUint16(34, bps, true); + writeStr(36, 'data'); + view.setUint32(40, dataBytes, true); + + const pcmBytes = new Uint8Array(buffer, 44); + const pcmView = new Uint8Array(pcm16.buffer); + pcmBytes.set(pcmView); + + return buffer; + } + + function bufferToBase64(ab) { + const bytes = new Uint8Array(ab); + let bin = ''; + const CHUNK = 0x8000; + for (let i = 0; i < bytes.length; i += CHUNK) { + bin += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK)); + } + return btoa(bin); + } + + // ── Sarvam WebSocket Live Streaming STT ────────────────────────────────── + // Replaces Web Speech API — streams raw PCM16 audio to our FastAPI + // WebSocket proxy, which forwards it to Sarvam realtime STT. + // Partial results show instantly; final results are added as utterances. + + let sarvamWs = null; // WebSocket to backend proxy + let wsAudioCtx = null; // Separate AudioContext for WS streaming + let wsProcessor = null; + let wsSource = null; + let partialBubbleId = 'partial-bubble-live'; + + function floatTo16BitPCM(float32) { + const buf = new ArrayBuffer(float32.length * 2); + const view = new DataView(buf); + for (let i = 0; i < float32.length; i++) { + const s = Math.max(-1, Math.min(1, float32[i])); + view.setInt16(i * 2, s < 0 ? s * 0x8000 : s * 0x7FFF, true); + } + return buf; + } + + function startSarvamLiveStream(stream) { + const lang = (langSelect && langSelect.value && langSelect.value !== 'auto') ? langSelect.value : 'auto'; + const proto = location.protocol === 'https:' ? 'wss' : 'ws'; + const wsPort = location.port || (location.protocol === 'https:' ? 443 : 3000); + const wsUrl = `${proto}://${location.hostname}:${wsPort}/ws/transcribe?language_code=${lang}`; + + sarvamWs = new WebSocket(wsUrl); + sarvamWs.binaryType = 'arraybuffer'; + + sarvamWs.onopen = () => { + liveRealtimeBadge.style.display = 'inline-flex'; + console.log('[WS] Connected to Sarvam realtime proxy'); + + // Start sending PCM chunks over WebSocket + wsAudioCtx = new (window.AudioContext || window.webkitAudioContext)(); + wsSource = wsAudioCtx.createMediaStreamSource(stream); + wsProcessor = wsAudioCtx.createScriptProcessor(2048, 1, 1); + + wsProcessor.onaudioprocess = (e) => { + if (!recording || !sarvamWs || sarvamWs.readyState !== WebSocket.OPEN) return; + const raw = e.inputBuffer.getChannelData(0); + const resampled = downsample(raw, wsAudioCtx.sampleRate, SAMPLE_RATE); + const pcm16 = floatTo16BitPCM(resampled); + // Sarvam realtime expects: {"event": "audio_input", "audio": ""} + const bytes = new Uint8Array(pcm16); + let bin = ''; + for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]); + const b64 = btoa(bin); + sarvamWs.send(JSON.stringify({ event: 'audio_input', audio: b64 })); + }; + + wsSource.connect(wsProcessor); + wsProcessor.connect(wsAudioCtx.destination); + }; + + sarvamWs.onmessage = (evt) => { + let msg; + try { msg = JSON.parse(evt.data); } catch { return; } + + if (msg.event === 'transcript.partial' && msg.text) { + renderLiveInterimBubble(msg.text); + } else if (msg.event === 'transcript.final' && msg.text && msg.text.trim()) { + // Remove partial bubble and add final utterance + removePartialBubble(); + addLiveUtterance(msg.text.trim(), secondsElapsed); + } else if (msg.event === 'error') { + console.warn('[WS] Sarvam error:', msg.message); + } + }; + + sarvamWs.onerror = (e) => { + console.warn('[WS] WebSocket error:', e); + }; + + sarvamWs.onclose = () => { + liveRealtimeBadge.style.display = 'none'; + stopWsAudioPipeline(); + }; + } + + function stopWsAudioPipeline() { + if (wsProcessor) { try { wsProcessor.disconnect(); } catch(e){} wsProcessor = null; } + if (wsSource) { try { wsSource.disconnect(); } catch(e){} wsSource = null; } + if (wsAudioCtx) { try { wsAudioCtx.close(); } catch(e){} wsAudioCtx = null; } + } + + function stopSarvamLiveStream() { + liveRealtimeBadge.style.display = 'none'; + stopWsAudioPipeline(); + if (sarvamWs) { + if (sarvamWs.readyState === WebSocket.OPEN) { + try { sarvamWs.send(JSON.stringify({ event: 'end' })); } catch(e) {} + setTimeout(() => { try { sarvamWs.close(); } catch(e){} }, 400); + } + sarvamWs = null; + } + removePartialBubble(); + } + + function removePartialBubble() { + const el = document.getElementById(partialBubbleId); + if (el) el.remove(); + } + + // Keep old names so rest of code compiles + function startLiveSpeechRecognizer() {} // replaced by startSarvamLiveStream + function stopLiveSpeechRecognizer() { stopSarvamLiveStream(); } + + function addLiveUtterance(text, timestampSec) { + if (!text) return; + + const role = 'unknown'; + const speaker = 'Live Speaker'; + + const startSec = Math.max(0, timestampSec - 3); + const endSec = timestampSec; + const uttId = 'utt-' + Date.now() + '-' + Math.random().toString(36).substr(2, 4); + + liveUtterances.push({ + id: uttId, + role: role, + speaker: speaker, + text: text, + startSec: startSec, + endSec: endSec + }); + + renderAllUtterances(); + + // Background diarization — real speaker detect करतो + fetch('/api/diarize', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ transcript: text }) + }).then(async resp => { + // BUG 5 FRONTEND FIX: 402 quota error handle करा + if (resp.status === 402) { + console.warn('[Live Diarize] Sarvam quota exhausted'); + return; + } + if (resp.ok) { + const data = await resp.json(); + const diarizedText = data.transcript || ''; + const isPatient = /(पेशंट|patient|रुग्ण)\s*[::\-]/i.test(diarizedText); + const isDoc = /(डॉक्टर|doctor)\s*[::\-]/i.test(diarizedText); + + if (isDoc || isPatient) { + const utt = liveUtterances.find(u => u.id === uttId); + if (utt) { + utt.role = isDoc ? 'doctor' : 'patient'; + // BUG: doctorSelect हा DOM ID नाही — 'doctorName' हा actual ID आहे + const doctorEl = document.getElementById('doctorName'); + const patientEl = document.getElementById('patientName'); + utt.speaker = isDoc + ? (doctorEl ? doctorEl.value || 'Dr. Sharma' : 'Dr. Sharma').split('(')[0].trim() + : (patientEl ? patientEl.value.trim() || 'Patient' : 'Patient'); + renderAllUtterances(); + } + } + } + }).catch(e => console.error("Live diarize error:", e)); + } + + function renderLiveInterimBubble(interimText) { + const existingInterim = document.getElementById('interimBubble'); + const speaker = 'Live Speaker'; + const icon = '🗣️'; + const roleCls = 'unknown'; + + const html = ` +
+
${icon}
+
+
+ ${escapeHtml(speaker)} + [${fmtTime(secondsElapsed)}] + ● Listening Live… +
+
${escapeHtml(interimText)}…
+
+
`; + + if (existingInterim) { + existingInterim.outerHTML = html; + } else { + transcriptBody.insertAdjacentHTML('beforeend', html); + } + transcriptBody.scrollTop = transcriptBody.scrollHeight; + } + + // ── Recording Actions ───────────────────────────────────────────────────── + async function startRecording() { + clearError(); + pcmChunks = []; + liveUtterances = []; + + try { + mediaStream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1, echoCancellation: true } }); + } catch (e) { + showError('Microphone access denied. Please allow microphone permissions in your browser.'); + return; + } + + audioCtx = new (window.AudioContext || window.webkitAudioContext)(); + sourceNode = audioCtx.createMediaStreamSource(mediaStream); + analyserNode = audioCtx.createAnalyser(); + analyserNode.fftSize = 64; + processorNode = audioCtx.createScriptProcessor(BUFFER_SIZE, 1, 1); + + processorNode.onaudioprocess = (e) => { + if (!recording) return; + const raw = e.inputBuffer.getChannelData(0); + const resampled = downsample(raw, audioCtx.sampleRate, SAMPLE_RATE); + pcmChunks.push(new Float32Array(resampled)); + }; + + sourceNode.connect(analyserNode); + sourceNode.connect(processorNode); + processorNode.connect(audioCtx.destination); + + recording = true; + secondsElapsed = 0; + timerEl.textContent = '00:00:00'; + recStatusText.textContent = 'Live recording consultation...'; + recordingCard.classList.add('is-recording'); + + timerInterval = setInterval(() => { + secondsElapsed++; + timerEl.textContent = fmtTime(secondsElapsed); + }, 1000); + + startBtn.disabled = true; + stopBtn.disabled = false; + audioPlaybackBar.style.display = 'none'; + drawVisualizer(); + + transcriptBody.innerHTML = ` +
+
🎙️
+

Live consultation recording started…

+ Speak clearly into the microphone. Words will appear in real time. +
`; + + startSarvamLiveStream(mediaStream); + } + + async function stopAndSummarize() { + if (!recording) return; + recording = false; + + stopLiveSpeechRecognizer(); + if (timerInterval) { clearInterval(timerInterval); timerInterval = null; } + if (animationId) cancelAnimationFrame(animationId); + if (processorNode) { processorNode.disconnect(); processorNode = null; } + if (sourceNode) { sourceNode.disconnect(); sourceNode = null; } + if (audioCtx) { audioCtx.close(); audioCtx = null; } + if (mediaStream) { mediaStream.getTracks().forEach(t => t.stop()); mediaStream = null; } + + recordingCard.classList.remove('is-recording'); + startBtn.disabled = true; + stopBtn.disabled = true; + recStatusText.textContent = 'Processing full transcript & audio sync with Sarvam AI…'; + + if (pcmChunks.length === 0) { + showError('No audio recorded.'); + resetButtons(); + return; + } + + try { + const wavBuffer = buildWav(pcmChunks, SAMPLE_RATE); + const audio_b64 = bufferToBase64(wavBuffer); + const lang = langSelect.value; + + // Setup playable audio blob for synchronized playback + setupAudioPlayer(wavBuffer, secondsElapsed); + + const resp = await fetch('/api/transcribe', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ audio_b64, language_code: lang }) + }); + + const data = await resp.json(); + if (!resp.ok) throw new Error(data.error || 'Server error ' + resp.status); + + currentTranscript = data.transcript || ''; + parseAndSetFullTranscript(currentTranscript, secondsElapsed); + recStatusText.textContent = `Completed in ${fmtTime(secondsElapsed)} • Generating clinical summary…`; + showToast('Full transcript synchronized! Generating summary…'); + + if (currentTranscript.trim()) { + await generateSummary(currentTranscript); + } + + } catch (e) { + const msg = e.message === 'Failed to fetch' + ? 'Connection lost to server (http://localhost:3000). Server may have restarted or timed out. Please try again.' + : e.message; + showError('Transcription: ' + msg); + recStatusText.textContent = 'Error during transcription'; + } + + resetButtons(); + } + + function resetButtons() { + startBtn.disabled = false; + stopBtn.disabled = true; + } + + // ── Parse Full Transcript & Assign Real-time Audio Timestamps ───────────── + function parseAndSetFullTranscript(text, totalDurationSec) { + if (!text || !text.trim()) { + transcriptBody.innerHTML = '

No speech detected in audio.

'; + return; + } + + const patientName = patientInput.value.trim() || 'Patient'; + const doctorName = (doctorSelect.value || 'Dr. Sharma').split('(')[0].trim(); + const duration = Math.max(10, totalDurationSec || 60); + + liveUtterances = []; + + // Strip markdown formatting like ** or * + const plainText = text.replace(/\*/g, '').trim(); + + // Check if text has Doctor/Patient/Relative/Nurse markers OR the new [Speaker_X | Role] format + const hasMarkers = /(?:\[Speaker_\d+\s*\|\s*(?:Doctor|Patient|Relative|Nurse)\])|(?:(?:डॉक्टर|पेशंट|doctor|patient|रुग्ण|relative|नातेवाईक|nurse|परिचारिका|नर्स)\s*[::\-])/i.test(plainText); + + if (hasMarkers) { + // Split the text before each speaker label + const segments = plainText.split(/(?=\[Speaker_\d+\s*\|\s*(?:Doctor|Patient|Relative|Nurse)\]|(?:डॉक्टर|पेशंट|Doctor|Patient|रुग्ण|Relative|नातेवाईक|Nurse|परिचारिका|नर्स)\s*[::\-])/i).map(s => s.trim()).filter(s => s.length > 0); + + let currentOffset = 0; + segments.forEach((segment, idx) => { + const isPatient = /^(?:\[Speaker_\d+\s*\|\s*Patient\])|(?:(?:पेशंट|patient|रुग्ण)\s*[::\-])/i.test(segment); + const isRelative = /^(?:\[Speaker_\d+\s*\|\s*Relative\])|(?:(?:relative|नातेवाईक)\s*[::\-])/i.test(segment); + const isNurse = /^(?:\[Speaker_\d+\s*\|\s*Nurse\])|(?:(?:nurse|परिचारिका|नर्स)\s*[::\-])/i.test(segment); + + let role = 'doctor'; + let speaker = doctorName; + + if (isPatient) { + role = 'patient'; + speaker = patientName; + } else if (isRelative) { + role = 'relative'; + speaker = 'Relative (नातेवाईक)'; + } else if (isNurse) { + role = 'nurse'; + speaker = 'Nurse (परिचारिका)'; + } + + const cleanedText = segment.replace(/^(?:\[Speaker_\d+\s*\|\s*(?:Doctor|Patient|Relative|Nurse)\]\s*)|^(?:(?:डॉक्टर|पेशंट|doctor|patient|रुग्ण|relative|नातेवाईक|nurse|परिचारिका|नर्स)\s*[::\-]\s*)/i, '').trim(); + + // Approximate duration based on word count (avg 2.5 words per second) + const wordCount = cleanedText.split(/\s+/).length; + const segmentDuration = Math.max(2, wordCount / 2.5); + + liveUtterances.push({ + id: 'utt-' + idx, + role: role, + speaker: speaker, + text: cleanedText || segment, + startSec: currentOffset, + endSec: currentOffset + segmentDuration + }); + currentOffset += segmentDuration; + }); + } else { + // Fallback if AI didn't format it properly + liveUtterances.push({ + id: 'utt-0', + role: 'patient', + speaker: 'Transcript (Unlabeled)', + text: plainText, + startSec: 0, + endSec: duration + }); + } + + renderAllUtterances(); + } + + // ── Render All Utterances (Full Transcript with Synchronized Audio) ───────── + function renderAllUtterances() { + if (liveUtterances.length === 0) return; + + const searchTerm = (transcriptSearch.value || '').toLowerCase().trim(); + let html = ''; + + liveUtterances.forEach((utt) => { + // Filter by speaker + if (activeFilter === 'doctor' && utt.role !== 'doctor') return; + if (activeFilter === 'patient' && utt.role !== 'patient') return; + + // Filter by search + if (searchTerm && !utt.text.toLowerCase().includes(searchTerm) && !utt.speaker.toLowerCase().includes(searchTerm)) { + return; + } + + let icon = '🧑'; + let colorCls = 'patient-color'; + + if (utt.role === 'doctor') { + icon = '🧑‍⚕️'; + colorCls = 'doctor-color'; + } else if (utt.role === 'relative') { + icon = '👨‍👩‍👧'; + colorCls = 'relative-color'; + } else if (utt.role === 'nurse') { + icon = '👩‍⚕️'; + colorCls = 'nurse-color'; + } + + html += ` +
+
${icon}
+
+
+ ${escapeHtml(utt.speaker)} + [${fmtTime(utt.startSec)} - ${fmtTime(utt.endSec)}] + English +
+
${escapeHtml(utt.text)}
+
+
`; + }); + + if (!html && searchTerm) { + transcriptBody.innerHTML = `

No dialogue matching "${escapeHtml(searchTerm)}"

`; + return; + } + + transcriptBody.innerHTML = html; + } + + // ── Audio Player & Real-time Karaoke Highlighting ───────────────────────── + function setupAudioPlayer(wavBuffer, durationSec) { + if (audioPlayerAudio) { + audioPlayerAudio.pause(); + audioPlayerAudio = null; + } + clearInterval(playerInterval); + + const blob = new Blob([wavBuffer], { type: 'audio/wav' }); + const audioUrl = URL.createObjectURL(blob); + audioPlayerAudio = new Audio(audioUrl); + + audioPlaybackBar.style.display = 'flex'; + audioScrubber.max = durationSec || 10; + audioScrubber.value = 0; + audioCurrentTime.textContent = '00:00'; + audioTotalDuration.textContent = fmtTime(durationSec); + playIcon.textContent = '▶'; + + audioPlayerAudio.ontimeupdate = () => { + const cur = audioPlayerAudio.currentTime; + audioScrubber.value = cur; + audioCurrentTime.textContent = fmtTime(cur); + syncHighlightUtterance(cur); + }; + + audioPlayerAudio.onended = () => { + playIcon.textContent = '▶'; + removePlayingHighlights(); + }; + } + + function setupDemoAudioPlayer(durationSec) { + audioPlaybackBar.style.display = 'flex'; + audioScrubber.max = durationSec; + audioScrubber.value = 0; + audioCurrentTime.textContent = '00:00'; + audioTotalDuration.textContent = fmtTime(durationSec); + playIcon.textContent = '▶'; + } + + function togglePlayPause() { + if (audioPlayerAudio) { + if (audioPlayerAudio.paused) { + audioPlayerAudio.play(); + playIcon.textContent = '⏸'; + } else { + audioPlayerAudio.pause(); + playIcon.textContent = '▶'; + } + return; + } + + // Simulated playback for demo if no audio file + if (playerInterval) { + clearInterval(playerInterval); + playerInterval = null; + playIcon.textContent = '▶'; + } else { + playIcon.textContent = '⏸'; + const maxTime = parseFloat(audioScrubber.max) || 60; + playerInterval = setInterval(() => { + let cur = parseFloat(audioScrubber.value) + 0.5; + if (cur > maxTime) { + cur = 0; + clearInterval(playerInterval); + playerInterval = null; + playIcon.textContent = '▶'; + removePlayingHighlights(); + } + audioScrubber.value = cur; + audioCurrentTime.textContent = fmtTime(cur); + syncHighlightUtterance(cur); + }, 500); + } + } + + function syncHighlightUtterance(currentSec) { + const items = document.querySelectorAll('.utterance-item'); + items.forEach((item) => { + const start = parseFloat(item.getAttribute('data-start') || 0); + const end = parseFloat(item.getAttribute('data-end') || 0); + if (currentSec >= start && currentSec <= end) { + if (!item.classList.contains('active-playing')) { + items.forEach(i => i.classList.remove('active-playing')); + item.classList.add('active-playing'); + item.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); + } + } + }); + } + + function removePlayingHighlights() { + document.querySelectorAll('.utterance-item').forEach(i => i.classList.remove('active-playing')); + } + + // ── Generate AI Clinical Summary ────────────────────────────────────────── + async function generateSummary(transcriptText) { + if (!transcriptText || !transcriptText.trim()) return; + + sumChiefComplaint.innerHTML = '

Generating with AI (Groq LLM)…

'; + sumSymptoms.innerHTML = '

Detecting symptoms…

'; + sumAssessment.innerHTML = '

Evaluating assessment…

'; + sumHistory.innerHTML = '

Extracting medical history…

'; + sumPlan.innerHTML = '

Structuring prescription & plan…

'; + + try { + const resp = await fetch('/api/summary', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ transcript: transcriptText }) + }); + + const data = await resp.json(); + if (!resp.ok) throw new Error(data.error || 'Summary error ' + resp.status); + + currentSummaryData = data.summary; + renderSummaryCards(currentSummaryData); + recStatusText.textContent = '✅ Clinical Consultation Summarized Successfully'; + showToast('AI Clinical Summary generated!'); + + } catch (e) { + sumChiefComplaint.innerHTML = `

${escapeHtml(e.message)}

`; + sumSymptoms.innerHTML = '

—

'; + sumAssessment.innerHTML = '

—

'; + sumHistory.innerHTML = '

—

'; + sumPlan.innerHTML = '

—

'; + } + } + + function renderSummaryCards(s) { + if (!s) return; + + // 1. Chief Complaint + sumChiefComplaint.innerHTML = `

${escapeHtml(s.chief_complaint || 'Not mentioned')}

`; + + // 2. Symptoms Discussed (Pill Badges) + if (Array.isArray(s.symptoms) && s.symptoms.length > 0) { + sumSymptoms.innerHTML = ` +
+ ${s.symptoms.map(sym => `⚠️ ${escapeHtml(String(sym))}`).join('')} +
`; + } else { + sumSymptoms.innerHTML = `

${escapeHtml(s.symptoms || 'None recorded')}

`; + } + + // 3. Assessment / Recommendation + sumAssessment.innerHTML = `

${escapeHtml(s.assessment || 'Under clinical evaluation')}

`; + + // 4. History + sumHistory.innerHTML = `

${escapeHtml(s.history || 'No prior medical history noted')}

`; + + // 5. Prescription & Plan (Rx) + if (Array.isArray(s.plan) && s.plan.length > 0) { + sumPlan.innerHTML = ` +
    + ${s.plan.map(p => `
  • ${escapeHtml(String(p))}
  • `).join('')} +
`; + } else { + sumPlan.innerHTML = `

${escapeHtml(s.plan || 'Follow standard clinical protocol')}

`; + } + } + + let currentCaseIdx = 0; + const availableCases = ['case-cardiology', 'case-diabetes', 'case-ent']; + + // ── Demo Conversation Loader ────────────────────────────────────────────── + async function loadDemoConversation(caseId) { + let selectedCase = caseId; + if (!selectedCase || typeof selectedCase !== 'string') { + selectedCase = availableCases[currentCaseIdx % availableCases.length]; + currentCaseIdx++; + } + + recStatusText.textContent = `Loading consultation…`; + try { + const resp = await fetch(`/api/demo?case=${encodeURIComponent(selectedCase)}`); + const demo = await resp.json(); + + patientInput.value = demo.patientName; + patientIdInput.value = demo.patientId; + dateInput.value = demo.date; + if (doctorSelect) doctorSelect.value = demo.doctorName || 'Dr. Sharma'; + if (langSelect) langSelect.value = demo.language || 'mr-IN'; + + const dur = demo.durationSec || 200; + timerEl.textContent = fmtTime(dur); + + currentTranscript = demo.transcript; + currentSummaryData = demo.summary; + + parseAndSetFullTranscript(currentTranscript, dur); + setupDemoAudioPlayer(dur); + renderSummaryCards(currentSummaryData); + + recStatusText.textContent = `⚡ Loaded "${demo.title || demo.patientName}" with Full Real-time Sync`; + showToast(`Loaded ${demo.patientName} (${demo.language}) consultation!`); + } catch (e) { + showError('Failed to load demo: ' + e.message); + } + } + + // ── Populate Past Recordings & Archives on startup ──────────────────────── + async function loadArchiveLists() { + try { + const resp = await fetch('/api/demos'); + const data = await resp.json(); + const cases = data.cases || []; + + // Populate Recordings List in Past Recordings tab + const recordingsList = document.getElementById('recordingsList'); + if (recordingsList && cases.length > 0) { + recordingsList.innerHTML = cases.map(c => ` +
+
📁
+
+
+ ${escapeHtml(c.patientName)} (${c.patientId}) + ⏱️ ${fmtTime(c.durationSec)} + ${c.language} +
+
${escapeHtml(c.title)} — ${escapeHtml(c.summary?.chief_complaint || '')}
+
+ +
+ `).join(''); + } + + // Populate Patients Grid in Patients tab + const patientsGrid = document.getElementById('patientsGrid'); + if (patientsGrid && cases.length > 0) { + patientsGrid.innerHTML = cases.map(c => ` +
+
+
+ 👤 +
+

${escapeHtml(c.patientName)}

+ ${c.patientId} • ${c.date} +
+
+ +
+

Recent Diagnosis: ${escapeHtml(c.summary?.assessment || 'Routine Checkup')}

+
+ `).join(''); + } + } catch (e) { + console.warn('Could not populate archive lists:', e); + } + } + + loadArchiveLists(); + + // ── Upload Audio Handler (Real-Time Chunk Streaming) ────────────────────── + uploadAudioBtn.addEventListener('click', () => { + audioFileInput.click(); + }); + + audioFileInput.addEventListener('change', async (e) => { + const file = e.target.files[0]; + if (!file) return; + + clearError(); + recStatusText.textContent = `Decoding audio: ${file.name}…`; + showToast(`Loading audio file: ${file.name}`); + + try { + const arrayBuffer = await file.arrayBuffer(); + const tempAudioCtx = new (window.AudioContext || window.webkitAudioContext)(); + const audioBuffer = await tempAudioCtx.decodeAudioData(arrayBuffer); + + // Fast native resampling instead of slow JS loop + const resampled = await downsampleNative(audioBuffer, SAMPLE_RATE); + const fullWavBuffer = buildWav([resampled], SAMPLE_RATE); + tempAudioCtx.close(); + + const totalDurationSec = audioBuffer.duration; + timerEl.textContent = fmtTime(totalDurationSec); + setupAudioPlayer(fullWavBuffer, totalDurationSec); + + // Call /api/transcribe which runs STT + NVIDIA NeMo Diarization on the server + const audio_b64 = bufferToBase64(fullWavBuffer); + const lang = langSelect.value; + + const transcribePromise = fetch('/api/transcribe', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ audio_b64, language_code: lang }) + }).then(async resp => { + const data = await resp.json(); + if (!resp.ok) throw new Error(data.error || 'Server error'); + return data.transcript; + }); + + const finalTranscriptText = await transcribePromise; + currentTranscript = finalTranscriptText; + parseAndSetFullTranscript(currentTranscript, totalDurationSec); + + recStatusText.textContent = `✅ Transcribed ${file.name} successfully! Generating Summary...`; + showToast('Audio transcribed & diarized! Generating AI Summary...'); + + if (currentTranscript.trim()) { + await generateSummary(currentTranscript); + recStatusText.textContent = `✅ Consultation Processed Successfully!`; + } + } catch (err) { + const msg = err.message === 'Failed to fetch' + ? 'Connection lost to server (http://localhost:3000). Server may have restarted or timed out. Please try again.' + : err.message; + showError('Failed to process uploaded audio: ' + msg); + recStatusText.textContent = 'Error processing uploaded audio file'; + } + audioFileInput.value = ''; + }); + + // ── Scrubber, Filter & Search Handlers ───────────────────────────────────── + if (playAudioBtn) playAudioBtn.addEventListener('click', togglePlayPause); + + if (audioScrubber) { + audioScrubber.addEventListener('input', (e) => { + const targetSec = parseFloat(e.target.value); + if (audioPlayerAudio) { + audioPlayerAudio.currentTime = targetSec; + } + audioCurrentTime.textContent = fmtTime(targetSec); + syncHighlightUtterance(targetSec); + }); + } + + if (transcriptSearch) { + transcriptSearch.addEventListener('input', renderAllUtterances); + } + + filterPills.forEach(pill => { + pill.addEventListener('click', () => { + filterPills.forEach(p => p.classList.remove('active')); + pill.classList.add('active'); + activeFilter = pill.getAttribute('data-filter'); + renderAllUtterances(); + }); + }); + + // ── Copy, Print, & Export Handlers ──────────────────────────────────────── + copyTranscriptBtn.addEventListener('click', () => { + if (!currentTranscript) { + showToast('No transcript to copy!'); + return; + } + navigator.clipboard.writeText(currentTranscript).then(() => { + showToast('📋 Full transcript copied to clipboard!'); + }); + }); + + clearTranscriptBtn.addEventListener('click', () => { + currentTranscript = ''; + currentSummaryData = null; + liveUtterances = []; + if (audioPlayerAudio) { audioPlayerAudio.pause(); audioPlayerAudio = null; } + clearInterval(playerInterval); + audioPlaybackBar.style.display = 'none'; + + transcriptBody.innerHTML = ` +
+
🎙️
+

Recording in progress… Transcript will appear here in real time.

+ Speak into the microphone or click DEMO to see full real-time audio synchronization. +
`; + sumChiefComplaint.innerHTML = '

—

'; + sumSymptoms.innerHTML = '

—

'; + sumAssessment.innerHTML = '

—

'; + sumHistory.innerHTML = '

—

'; + sumPlan.innerHTML = '

—

'; + timerEl.textContent = '00:00:00'; + recStatusText.textContent = 'Ready to record consultation...'; + clearError(); + showToast('Reset consultation workspace.'); + }); + + copySummaryBtn.addEventListener('click', () => { + if (!currentSummaryData) { + showToast('No summary generated yet!'); + return; + } + const textToCopy = `AI CLINICAL SUMMARY +Patient: ${patientInput.value} (ID: ${patientIdInput.value}) +Doctor: ${doctorSelect.value} +Date: ${dateInput.value} + +CHIEF COMPLAINT: +${currentSummaryData.chief_complaint || ''} + +SYMPTOMS: +${Array.isArray(currentSummaryData.symptoms) ? currentSummaryData.symptoms.join(', ') : currentSummaryData.symptoms || ''} + +ASSESSMENT / DIAGNOSIS: +${currentSummaryData.assessment || ''} + +HISTORY: +${currentSummaryData.history || ''} + +PLAN & PRESCRIPTION: +${Array.isArray(currentSummaryData.plan) ? currentSummaryData.plan.join('\n- ') : currentSummaryData.plan || ''} +`; + navigator.clipboard.writeText(textToCopy).then(() => { + showToast('📋 Summary copied to clipboard!'); + }); + }); + + printSummaryBtn.addEventListener('click', () => { + window.print(); + }); + + exportJsonBtn.addEventListener('click', () => { + if (!currentSummaryData) { + showToast('No summary data to export!'); + return; + } + const exportData = { + patientName: patientInput.value, + patientId: patientIdInput.value, + doctor: doctorSelect.value, + date: dateInput.value, + transcript: currentTranscript, + summary: currentSummaryData + }; + const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = `Consultation_${patientIdInput.value}_${dateInput.value}.json`; + a.click(); + URL.revokeObjectURL(url); + showToast('📥 Consultation exported as JSON!'); + }); + + // ── Sidebar Tabs Navigation ─────────────────────────────────────────────── + navItems.forEach(item => { + item.addEventListener('click', (e) => { + e.preventDefault(); + const tabId = item.getAttribute('data-tab'); + + navItems.forEach(i => i.classList.remove('active')); + item.classList.add('active'); + + tabViews.forEach(v => v.classList.remove('active')); + const activeView = document.getElementById(`view-${tabId}`); + if (activeView) activeView.classList.add('active'); + + const label = item.querySelector('.nav-label'); + if (label && pageHeading) { + pageHeading.textContent = label.textContent; + } + + if (window.innerWidth < 768 && sidebar) { + sidebar.classList.remove('open'); + } + }); + }); + + if (menuToggle && sidebar) { + menuToggle.addEventListener('click', () => { + sidebar.classList.toggle('open'); + }); + } + + // ── Patient Modal ───────────────────────────────────────────────────────── + function openModal() { + patientModal.classList.add('open'); + newPatientName.focus(); + } + function closeModal() { + patientModal.classList.remove('open'); + } + + if (openAddPatientBtn) openAddPatientBtn.addEventListener('click', openModal); + if (btnAddNewPatientTab) btnAddNewPatientTab.addEventListener('click', openModal); + if (closePatientModal) closePatientModal.addEventListener('click', closeModal); + if (cancelPatientModal) cancelPatientModal.addEventListener('click', closeModal); + + if (savePatientBtn) { + savePatientBtn.addEventListener('click', () => { + const name = newPatientName.value.trim(); + if (!name) { + alert('Please enter patient name'); + return; + } + patientInput.value = name; + patientIdInput.value = 'PT-2026-' + String(Math.floor(10000 + Math.random() * 90000)); + closeModal(); + showToast(`Selected patient: ${name} (${patientIdInput.value})`); + newPatientName.value = ''; + }); + } + + // ── Event Listeners ─────────────────────────────────────────────────────── + startBtn.addEventListener('click', startRecording); + stopBtn.addEventListener('click', stopAndSummarize); + demoBtn.addEventListener('click', loadDemoConversation); + + // Global window helpers + window.app = { + seekToTime: function(seconds) { + if (audioPlayerAudio) { + audioPlayerAudio.currentTime = seconds; + audioPlayerAudio.play(); + playIcon.textContent = '⏸'; + } else { + audioScrubber.value = seconds; + audioCurrentTime.textContent = fmtTime(seconds); + syncHighlightUtterance(seconds); + } + }, + loadSpecificCase: function(caseId) { + const tab = document.querySelector('[data-tab="new-consultation"]'); + if (tab) tab.click(); + if (demoCaseSelect) demoCaseSelect.value = caseId; + loadDemoConversation(caseId); + }, + loadDemoRecord: function(type) { + const caseMap = { + ramesh: 'case-cardiology', + sunita: 'case-diabetes', + amit: 'case-ent' + }; + const caseId = caseMap[type] || 'case-cardiology'; + this.loadSpecificCase(caseId); + } + }; + +})(); + +// End of application logic. diff --git a/public/favicon.ico b/public/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..df3244f23d83979d665a1c407a1303f9c69e2a31 GIT binary patch literal 22847 zcmV*1KzP52P)bh%K^X|IlUDKKqu8M+!AiAQM z1znLKLE^v+!vrSubbR^7?_aN{p+V*i0>exXedqpf)va6M)TwjooT}>Xaq@+0fddO1 z*kv4WShyBAu)u*`#(@O|+hwd>sCa<`u%KWIQn0{*UC4n21>1$pU8uS%2Obn37ZmJ4 zG0Y2{++7@4P_W&_`Gs~L6dYJkum{C3FLZKuabQ8g?nlmNmT(^L?q;~HHeT$|a#*-_F$We{d_OYS7=tl0n5}kER=^Dd zHWf2Al%U~dl=Eo@y$Slt6O3GW83Vul1wB9b0mak5MSR9LaZmde;n%-MaN{3IL&#i% zqmgp5R4*V+!6w8Q@QoBMP|T+-yVq1wG4u$tnC#|NOn&)vqA#3|x#mWxV@4Y2o7L#d zp~=Fvt2yB8>IU}q`i+r9Z||g$m^;!0V-yoQ$)hPo>#`_F=s(Hd z`yt$qpGNHiAA@&(kjh)$OW{90g#W&eQ25}-82pYbkJKVmMZWyQ+pVPmV+;<4SnIN^ zqj9d5WV!UsA-zMex^7-W^9L8u zIO81p+HIBh36~F&kdkZ7){w&E;o7AfaCT|!yQ1^`zL)2`jDl4W@&H!ahyd)k3jGWT<5lYiz+ zlAm8lypK!uUr%BBORs0@H7|ujA4}noktX5HJ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9LmW6k~3ao|BOvy8Y%{N? z#@wM0v-R1~!q#KMZa~GeSw(UT()pP;X}c|F>sY|9ZTrnCp3Q5OYqp))xJ{o;TL^az2No3U zUh>rnrv=+L2l9?-u|NLB^3zUc_?UE`Kt5^`I{M(+>I)@4JhB;8>1bg;c) zW6X?WD4MK=+n&4->>>^|0#4U+-$$*#%+>h-3EUa zX6u+6+W3xOE4PYoL%SBUu<->vFdT3mm}d6eR#K5>-KNg8ZX<$jBBi&5ByLJ+6w%#~ zMohRaTfK}a+5~}PbqQBoEaWkTc7tN8E;K178AS}PAF!dAQ}#=kc8;GZb1R14kU)WI z$1fJi+cByRl3b)1a^sOpUmfLla)(wkrP|7f9gkSb8>@cbbBHpZwC&?HT(xT`is(Y( z;HtcFeMVEmSV3i)btaPtygu}x?qyU8DOr}>jyzAbT$}-NAZMWL3-`U|fOD@)?!^VI zh-VTo3)c_H@{G0=prAevD1Dhs!f;c;=@Q1S{xzE}xquD-cRsgW`V+QZ z`Af#H`7OnDYv~)^h})RLcOw!fBN+-<-|sT5`etuyfo$A{x$4i!v1e&xUW=*=Y1tmk@2dhGn92AE{(fm5=n6 z>5*c4ibrvaR;{ks!o4dwu%KXf;chOewmW}mmXc_8k8r4^32g}^)oI)6_=0{N^hB)ninq5;>8bT@kfwL*$|v zS*~2ll?o8l8x+Q;X;iehbuq)F|Pc?Cs}jG8LYef|CpZIN+$O(D1`VyN$oD&yOIO{9{>RV|5#6( icK`qY21!IgR09CQ7t#T@MsFPe0000 + + + + + + AI Clinical Assistant — Doctor-Patient Consultation + + + + + + + + + + +
+ + + + + +
+ + +
+
+ +
+ DMH Logo + DMH +
+
+

New Consultation

+
+ +
+ +
+ 🌐 + + ▾ +
+ + + + + +
+
+ + +
+ + +
+ + +
+
+
+ 📋 +

Consultation Details

+
+ +
+ +
+ +
+ +
+ 👤 + +
+
+ + +
+ +
+ 🪪 + +
+
+ + +
+ +
+ 🩺 + + ▾ +
+
+ + +
+ +
+ 📅 + +
+
+
+
+ + +
+ +
+ +
00:00:00
+
+ +
+ 🎙️ + Ready to record consultation... +
+ + +
+ +
+ + + + +
+ + + + + + + + +
+
+ + + +
+
+
+

TRANSCRIPT

+ +
+
+ + + +
+
+ + + + + +
+ + + +
+ + +
+
+
🎙️
+

Recording in progress… Transcript will appear here in real time.

+ Speak into the microphone or click DEMO to see full real-time audio + synchronization. +
+
+
+ + +
+
+
+ 📋 +

AI CLINICAL SUMMARY

+
+
+ + + +
+
+ + +
+ +
+
Chief Complaint
+
+

—

+
+
+ + +
+
Symptoms Discussed
+
+

—

+
+
+ + +
+
Doctor's Recommendation / Diagnosis
+
+

—

+
+
+ + +
+
Patient History & Comorbidities
+
+

—

+
+
+ + +
+
Prescription, Tests & Treatment Plan (Rx)
+
+

—

+
+
+
+
+ +
+ + +
+
+
+
📈
+
+ 142 + Total Consultations +
+
+
+
👥
+
+ 98 + Active Patients +
+
+
+
⏱️
+
+ 486 mins + Audio Transcribed +
+
+
+
⚡
+
+ 99.4% + AI Accuracy Rate +
+
+
+ +
+
+

Recent Clinical Consultations

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PatientIDDoctorLanguageDurationDateAction
Ramesh PatilPT-2026-00124Dr. Sharma (Cardiology)मराठी03:42Today, 10:15 AM
Sunita DeshmukhPT-2026-00123Dr. Kulkarni (General)मराठी04:18Yesterday
Amit VermaPT-2026-00122Dr. Joshi (ENT)हिंदी02:5007-09-2026
+
+
+
+ + +
+
+
+

Archived Doctor-Patient Audio & Transcripts

+
+
+ +
+
+
+ + +
+
+
+

Patient Directory

+ +
+
+ +
+
+
+ + +
+
+
+

Hospital Medical Staff

+
+
+
+
🩺
+

Dr. Sharma

+

Senior Cardiologist

+ Cardiology Dept +
+
+
🩺
+

Dr. Kulkarni

+

Chief Medical Officer

+ General Medicine +
+
+
🩺
+

Dr. Joshi

+

ENT Specialist

+ Otolaryngology +
+
+
🩺
+

Dr. Deshmukh

+

Consultant Neurologist

+ Neurosciences +
+
+
+
+ + +
+
+
+

AI & Speech Engine Configuration

+
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+
+ +
+
+
+ + + + + +
Notification message
+ + + + + \ No newline at end of file diff --git a/public/logo.png b/public/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..df3244f23d83979d665a1c407a1303f9c69e2a31 GIT binary patch literal 22847 zcmV*1KzP52P)bh%K^X|IlUDKKqu8M+!AiAQM z1znLKLE^v+!vrSubbR^7?_aN{p+V*i0>exXedqpf)va6M)TwjooT}>Xaq@+0fddO1 z*kv4WShyBAu)u*`#(@O|+hwd>sCa<`u%KWIQn0{*UC4n21>1$pU8uS%2Obn37ZmJ4 zG0Y2{++7@4P_W&_`Gs~L6dYJkum{C3FLZKuabQ8g?nlmNmT(^L?q;~HHeT$|a#*-_F$We{d_OYS7=tl0n5}kER=^Dd zHWf2Al%U~dl=Eo@y$Slt6O3GW83Vul1wB9b0mak5MSR9LaZmde;n%-MaN{3IL&#i% zqmgp5R4*V+!6w8Q@QoBMP|T+-yVq1wG4u$tnC#|NOn&)vqA#3|x#mWxV@4Y2o7L#d zp~=Fvt2yB8>IU}q`i+r9Z||g$m^;!0V-yoQ$)hPo>#`_F=s(Hd z`yt$qpGNHiAA@&(kjh)$OW{90g#W&eQ25}-82pYbkJKVmMZWyQ+pVPmV+;<4SnIN^ zqj9d5WV!UsA-zMex^7-W^9L8u zIO81p+HIBh36~F&kdkZ7){w&E;o7AfaCT|!yQ1^`zL)2`jDl4W@&H!ahyd)k3jGWT<5lYiz+ zlAm8lypK!uUr%BBORs0@H7|ujA4}noktX5HJF+N2_-F&X(1Wb zb{~>s&FyrO?b(%8APZZUa{kHf<}OVYOeL(YHV@)Bpj|Av8ii?=#zop;h4p<+%4%VCqsqEIpW?b}i7xv!jbdB7 zgL)qgC{-P9rN-7k{b|-%tCdweYVZm@WNw}EcfZ4a-#HVfF^&ut741HTRv8_ax^)S) zO|KOgiFgsIHDe6M7&={L$dZIz1nL#&p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va4Nn8gr7EFpY>mD-qayr@OrreXbt$uDk z$F8~5q)oF{w1e#mX3X{v`e@9ZN;ia63ROiUFf_^SvAU`)_q|kA@41bDXC;a z+a$UDdy&@4?Etg&>@YM2V|ENR^`O4R`UiFYchLErC*L9LmW6k~3ao|BOvy8Y%{N? z#@wM0v-R1~!q#KMZa~GeSw(UT()pP;X}c|F>sY|9ZTrnCp3Q5OYqp))xJ{o;TL^az2No3U zUh>rnrv=+L2l9?-u|NLB^3zUc_?UE`Kt5^`I{M(+>I)@4JhB;8>1bg;c) zW6X?WD4MK=+n&4->>>^|0#4U+-$$*#%+>h-3EUa zX6u+6+W3xOE4PYoL%SBUu<->vFdT3mm}d6eR#K5>-KNg8ZX<$jBBi&5ByLJ+6w%#~ zMohRaTfK}a+5~}PbqQBoEaWkTc7tN8E;K178AS}PAF!dAQ}#=kc8;GZb1R14kU)WI z$1fJi+cByRl3b)1a^sOpUmfLla)(wkrP|7f9gkSb8>@cbbBHpZwC&?HT(xT`is(Y( z;HtcFeMVEmSV3i)btaPtygu}x?qyU8DOr}>jyzAbT$}-NAZMWL3-`U|fOD@)?!^VI zh-VTo3)c_H@{G0=prAevD1Dhs!f;c;=@Q1S{xzE}xquD-cRsgW`V+QZ z`Af#H`7OnDYv~)^h})RLcOw!fBN+-<-|sT5`etuyfo$A{x$4i!v1e&xUW=*=Y1tmk@2dhGn92AE{(fm5=n6 z>5*c4ibrvaR;{ks!o4dwu%KXf;chOewmW}mmXc_8k8r4^32g}^)oI)6_=0{N^hB)ninq5;>8bT@kfwL*$|v zS*~2ll?o8l8x+Q;X;iehbuq)F|Pc?Cs}jG8LYef|CpZIN+$O(D1`VyN$oD&yOIO{9{>RV|5#6( icK`qY21!IgR09CQ7t#T@MsFPe0000 { + '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 = '

Recording in progress… press ⏹ Stop & Transcribe when done.

'; + + // 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 = ` +
+ + Processing transcript, please wait… +
`; + } + + // ── 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 = '

Transcription failed. Please try again.

'; + 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 = '

No speech detected in the recording.

'; + 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' + ? `[${escHtml(language)}]` + : ''; + + 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 += ` +
+
+ ${icon} + ${name} + [${ts}] + ${i === 0 ? langTag : ''} +
+
${escHtml(sentence)}
+
`; + }); + + transcriptBody.innerHTML = html; + transcriptBody.scrollTop = transcriptBody.scrollHeight; + } + + // ── Reset / Clear ────────────────────────────────────────────────────────── + function resetAll() { + lastTranscript = ''; + recordedChunks = []; + transcriptBody.innerHTML = '

Transcript will appear here once recording starts…

'; + 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 = ` +
+ Generating summary… +
`; + 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 = ` +
+ Summary + ${escHtml(s.raw_text)} +
`; + } else { + renderSummary(s); + } + } catch (err) { + summaryBody.innerHTML = ` +
+ Error + ${escHtml(err.message)} +
`; + } + + summaryBtn.disabled = false; + } + + function renderSummary(s) { + function listHtml(arr) { + if (!arr || !arr.length) return 'Not mentioned'; + return '
    ' + arr.map(x => `
  • ${escHtml(String(x))}
  • `).join('') + '
'; + } + summaryBody.innerHTML = ` +
+ Chief Complaint + ${escHtml(s.chief_complaint || 'Not mentioned')} +
+
+ Symptoms + ${listHtml(s.symptoms)} +
+
+ Diagnosis + ${escHtml(s.assessment || 'Not mentioned')} +
+
+ Prescription + ${listHtml(s.plan)} +
`; + } + + // ── Event listeners ──────────────────────────────────────────────────────── + startBtn.addEventListener('click', startRecording); + stopBtn.addEventListener('click', stopRecording); + clearBtn.addEventListener('click', resetAll); + summaryBtn.addEventListener('click', generateSummary); + + // ── Init ─────────────────────────────────────────────────────────────────── + checkHealth(); +})(); diff --git a/public/style.css b/public/style.css new file mode 100644 index 0000000..9b9e9a2 --- /dev/null +++ b/public/style.css @@ -0,0 +1,1519 @@ +/* ══════════════════════════════════════════════════════════════════ + AI CLINICAL ASSISTANT — MODERN CLINICAL DESIGN SYSTEM + ══════════════════════════════════════════════════════════════════ */ + +:root { + /* Color Palette */ + --sidebar-bg: #0b1329; + --sidebar-card: #131d3b; + --sidebar-hover: #17244a; + --sidebar-border: #1e2d56; + --sidebar-text: #94a3b8; + --sidebar-text-active: #ffffff; + + --primary-blue: #2563eb; + --primary-blue-hover: #1d4ed8; + --primary-glow: rgba(37, 99, 235, 0.25); + + --green-rec: #10b981; + --green-rec-hover: #059669; + --red-stop: #f87171; + --red-stop-hover: #ef4444; + --amber-upload: #f59e0b; + --amber-upload-hover: #d97706; + + --bg-app: #f1f5f9; + --card-bg: #ffffff; + --card-border: #e2e8f0; + --card-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.05), 0 1px 2px -1px rgba(0, 0, 0, 0.05); + --card-shadow-hover: 0 4px 6px -1px rgba(0, 0, 0, 0.07), 0 2px 4px -2px rgba(0, 0, 0, 0.05); + + --text-main: #1e293b; + --text-muted: #64748b; + --text-light: #94a3b8; + + --radius-sm: 6px; + --radius-md: 10px; + --radius-lg: 14px; + --radius-full: 9999px; + + --font-sans: 'Plus Jakarta Sans', 'Noto Sans Devanagari', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; + --font-mono: 'JetBrains Mono', monospace; +} + +*, *::before, *::after { + box-sizing: border-box; + margin: 0; + padding: 0; +} + +html, body { + height: 100%; + background-color: var(--bg-app); + color: var(--text-main); + font-family: var(--font-sans); + font-size: 14px; + line-height: 1.5; + -webkit-font-smoothing: antialiased; +} + +/* ══════════════════════════════════════════════════════════════════ + LAYOUT + ══════════════════════════════════════════════════════════════════ */ +.layout-container { + display: flex; + min-height: 100vh; + width: 100%; +} + +/* ══════════════════════════════════════════════════════════════════ + SIDEBAR + ══════════════════════════════════════════════════════════════════ */ +.sidebar { + width: 250px; + min-width: 250px; + background-color: var(--sidebar-bg); + color: var(--sidebar-text); + display: flex; + flex-direction: column; + border-right: 1px solid var(--sidebar-border); + position: sticky; + top: 0; + height: 100vh; + z-index: 100; + transition: transform 0.25s ease, width 0.25s ease; +} + +.sidebar-brand { + padding: 22px 18px 20px; + display: flex; + align-items: center; + gap: 12px; + border-bottom: 1px solid rgba(255, 255, 255, 0.06); +} + +.brand-icon-box { + width: 44px; + height: 44px; + background: #ffffff; + border-radius: var(--radius-md); + display: flex; + align-items: center; + justify-content: center; + padding: 4px; + box-shadow: 0 4px 14px rgba(0, 0, 0, 0.3); + flex-shrink: 0; + overflow: hidden; +} + +.brand-logo-img { + width: 100%; + height: 100%; + object-fit: contain; + display: block; +} + +.brand-title { + font-size: 15px; + font-weight: 700; + color: #ffffff; + letter-spacing: -0.01em; + line-height: 1.2; +} + +.brand-subtitle { + font-size: 11px; + color: #60a5fa; + font-weight: 500; + display: block; + margin-top: 2px; +} + +/* Navigation Links */ +.sidebar-nav { + padding: 16px 12px; + display: flex; + flex-direction: column; + gap: 5px; + flex: 1; + overflow-y: auto; +} + +.nav-item { + display: flex; + align-items: center; + gap: 12px; + padding: 10px 14px; + border-radius: var(--radius-md); + color: #94a3b8; + text-decoration: none; + font-size: 13.5px; + font-weight: 500; + transition: all 0.18s ease; + position: relative; +} + +.nav-item:hover { + background-color: var(--sidebar-hover); + color: #f1f5f9; +} + +.nav-item.active { + background: linear-gradient(90deg, #2563eb, #1d4ed8); + color: #ffffff; + font-weight: 600; + box-shadow: 0 4px 12px rgba(37, 99, 235, 0.35); +} + +.nav-icon { + font-size: 16px; + display: flex; + align-items: center; + justify-content: center; + width: 20px; +} + +.nav-label { + flex: 1; +} + +/* Sidebar Footer / Online Status */ +.sidebar-footer { + padding: 14px 12px 18px; +} + +.system-status-card { + background: var(--sidebar-card); + border: 1px solid var(--sidebar-border); + border-radius: var(--radius-md); + padding: 12px 14px; +} + +.status-indicator-row { + display: flex; + align-items: center; + gap: 8px; + margin-bottom: 4px; +} + +.status-pulse-dot { + width: 8px; + height: 8px; + background-color: #10b981; + border-radius: 50%; + box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.2); + animation: pulse-green 2s infinite ease-in-out; +} + +@keyframes pulse-green { + 0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.6); } + 70% { transform: scale(1); box-shadow: 0 0 0 6px rgba(16, 185, 129, 0); } + 100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); } +} + +.status-title { + font-size: 12px; + font-weight: 700; + color: #ffffff; +} + +.status-meta { + font-size: 11px; + color: #94a3b8; +} + +.status-tag { + font-size: 10px; + color: #38bdf8; + font-weight: 600; + margin-top: 2px; +} + +/* ══════════════════════════════════════════════════════════════════ + MAIN WRAPPER & TOP HEADER + ══════════════════════════════════════════════════════════════════ */ +.main-wrapper { + flex: 1; + display: flex; + flex-direction: column; + min-width: 0; +} + +.top-header { + height: 64px; + background-color: #ffffff; + border-bottom: 1px solid var(--card-border); + display: flex; + align-items: center; + justify-content: space-between; + padding: 0 24px; + position: sticky; + top: 0; + z-index: 90; +} + +.header-left { + display: flex; + align-items: center; + gap: 14px; +} + +.header-logo-badge { + display: flex; + align-items: center; + gap: 8px; + background: #ffffff; + border: 1px solid #e2e8f0; + padding: 4px 10px 4px 6px; + border-radius: 8px; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05); +} + +.header-logo-img { + height: 28px; + width: auto; + max-width: 42px; + object-fit: contain; + display: block; +} + +.header-hospital-name { + font-size: 13px; + font-weight: 800; + color: #dc2626; + letter-spacing: 0.05em; + line-height: 1; +} + +.header-divider-v { + width: 1px; + height: 22px; + background-color: #e2e8f0; +} + +.menu-toggle-btn { + display: none; + background: transparent; + border: none; + color: var(--text-muted); + cursor: pointer; + padding: 6px; + border-radius: var(--radius-sm); +} + +.menu-toggle-btn:hover { + background-color: #f1f5f9; + color: var(--text-main); +} + +.page-title { + font-size: 17px; + font-weight: 700; + color: #0f172a; + letter-spacing: -0.01em; +} + +.header-right { + display: flex; + align-items: center; + gap: 16px; +} + +/* Language Dropdown */ +.lang-selector-wrapper { + position: relative; + display: flex; + align-items: center; + background: #f8fafc; + border: 1px solid #cbd5e1; + border-radius: var(--radius-md); + padding: 0 10px 0 10px; + height: 36px; + cursor: pointer; + transition: border-color 0.15s; +} + +.lang-selector-wrapper:hover { + border-color: #94a3b8; +} + +.lang-globe-icon { + font-size: 14px; + margin-right: 6px; +} + +.lang-dropdown { + appearance: none; + background: transparent; + border: none; + outline: none; + font-family: inherit; + font-size: 12.5px; + font-weight: 600; + color: #334155; + cursor: pointer; + padding-right: 18px; +} + +.dropdown-arrow { + position: absolute; + right: 10px; + font-size: 11px; + color: #64748b; + pointer-events: none; +} + +/* Notification Button */ +.notif-btn { + position: relative; + width: 36px; + height: 36px; + background: #f8fafc; + border: 1px solid #cbd5e1; + border-radius: var(--radius-md); + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; + transition: all 0.15s; +} + +.notif-btn:hover { + background: #f1f5f9; +} + +.notif-icon { + font-size: 16px; +} + +.notif-badge { + position: absolute; + top: -4px; + right: -4px; + background: #ef4444; + color: #ffffff; + font-size: 10px; + font-weight: 700; + width: 17px; + height: 17px; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + border: 2px solid #ffffff; +} + +/* Doctor Profile */ +.doctor-profile-card { + display: flex; + align-items: center; + gap: 10px; + padding-left: 8px; + border-left: 1px solid #e2e8f0; +} + +.doctor-avatar { + width: 38px; + height: 38px; + border-radius: 50%; + object-fit: cover; + border: 2px solid #dbeafe; +} + +.doctor-meta { + display: flex; + flex-direction: column; +} + +.doctor-name { + font-size: 13px; + font-weight: 700; + color: #0f172a; + line-height: 1.2; +} + +.doctor-spec { + font-size: 11px; + color: #64748b; + font-weight: 500; +} + +/* ══════════════════════════════════════════════════════════════════ + CONTENT AREA & CARDS + ══════════════════════════════════════════════════════════════════ */ +.content-area { + padding: 24px; + max-width: 1400px; + width: 100%; + margin: 0 auto; +} + +.tab-view { + display: none; + flex-direction: column; + gap: 18px; +} + +.tab-view.active { + display: flex; +} + +/* Base Card */ +.card { + background-color: var(--card-bg); + border: 1px solid var(--card-border); + border-radius: var(--radius-lg); + padding: 20px 22px; + box-shadow: var(--card-shadow); + transition: box-shadow 0.2s; +} + +.card:hover { + box-shadow: var(--card-shadow-hover); +} + +.card-header-row { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 16px; +} + +.card-title-group { + display: flex; + align-items: center; + gap: 8px; +} + +.card-header-icon { + font-size: 16px; +} + +.card-title { + font-size: 14.5px; + font-weight: 700; + color: #0f172a; + letter-spacing: -0.01em; +} + +.card-title-section { + font-size: 12px; + font-weight: 800; + color: #475569; + letter-spacing: 0.06em; + text-transform: uppercase; +} + +.btn-link-action { + background: transparent; + border: none; + color: var(--primary-blue); + font-family: inherit; + font-size: 13px; + font-weight: 700; + cursor: pointer; + transition: color 0.15s; +} + +.btn-link-action:hover { + color: var(--primary-blue-hover); + text-decoration: underline; +} + +/* ══════════════════════════════════════════════════════════════════ + CARD 1: CONSULTATION DETAILS FORM + ══════════════════════════════════════════════════════════════════ */ +.details-form-grid { + display: grid; + grid-template-columns: repeat(4, 1fr); + gap: 16px; +} + +.form-group { + display: flex; + flex-direction: column; + gap: 6px; +} + +.form-label { + font-size: 11.5px; + font-weight: 600; + color: #64748b; +} + +.input-icon-box { + position: relative; + display: flex; + align-items: center; + background: #f8fafc; + border: 1px solid #cbd5e1; + border-radius: var(--radius-md); + padding: 0 12px; + height: 42px; + transition: border-color 0.15s, box-shadow 0.15s; +} + +.input-icon-box:focus-within { + border-color: var(--primary-blue); + box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.12); + background: #ffffff; +} + +.input-icon { + font-size: 14px; + margin-right: 8px; + opacity: 0.7; +} + +.input-icon-box input, +.input-icon-box select { + width: 100%; + border: none; + outline: none; + background: transparent; + font-family: inherit; + font-size: 13.5px; + color: #0f172a; + font-weight: 500; +} + +.input-icon-box input::placeholder { + color: #94a3b8; + font-weight: 400; +} + +.select-box select { + appearance: none; + cursor: pointer; + padding-right: 18px; +} + +.select-chevron { + position: absolute; + right: 12px; + font-size: 11px; + color: #64748b; + pointer-events: none; +} + +/* ══════════════════════════════════════════════════════════════════ + CARD 2: LIVE RECORDING & CONTROLS + ══════════════════════════════════════════════════════════════════ */ +.recording-card { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 28px 24px; + text-align: center; +} + +.rec-status-line { + display: flex; + align-items: center; + justify-content: center; + gap: 12px; + margin-bottom: 6px; +} + +.rec-pulse-bubble { + width: 12px; + height: 12px; + background-color: #cbd5e1; + border-radius: 50%; + transition: all 0.2s; +} + +.recording-card.is-recording .rec-pulse-bubble { + background-color: #ef4444; + box-shadow: 0 0 0 4px rgba(239, 68, 68, 0.25); + animation: pulse-red 1.2s infinite ease-in-out; +} + +@keyframes pulse-red { + 0% { transform: scale(0.9); box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7); } + 70% { transform: scale(1.1); box-shadow: 0 0 0 8px rgba(239, 68, 68, 0); } + 100% { transform: scale(0.9); box-shadow: 0 0 0 0 rgba(239, 68, 68, 0); } +} + +.timer-display { + font-family: var(--font-mono); + font-size: 34px; + font-weight: 700; + color: #0f172a; + letter-spacing: -0.02em; +} + +.rec-substatus { + font-size: 13px; + color: #64748b; + font-weight: 500; + display: flex; + align-items: center; + gap: 6px; + margin-bottom: 14px; +} + +.recording-card.is-recording .rec-substatus { + color: #2563eb; + font-weight: 600; +} + +.mic-glyph { + font-size: 14px; +} + +/* Audio Waveform Canvas */ +.visualizer-container { + width: 100%; + max-width: 520px; + height: 38px; + margin: 0 auto 20px; + display: flex; + align-items: center; + justify-content: center; + opacity: 0.25; + transition: opacity 0.3s; +} + +.recording-card.is-recording .visualizer-container { + opacity: 1; +} + +#waveformCanvas { + width: 100%; + height: 100%; +} + +.rec-error-banner { + background: #fef2f2; + border: 1px solid #fecaca; + color: #b91c1c; + padding: 8px 16px; + border-radius: var(--radius-md); + font-size: 12.5px; + margin-bottom: 16px; + font-weight: 500; +} + +/* Action Buttons Bar */ +.action-buttons-row { + display: flex; + align-items: center; + justify-content: center; + gap: 12px; + flex-wrap: wrap; +} + +.btn { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 11px 22px; + border-radius: var(--radius-full); + font-family: inherit; + font-size: 13px; + font-weight: 700; + border: none; + cursor: pointer; + transition: all 0.2s ease; + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06); +} + +.btn:disabled { + opacity: 0.55; + cursor: not-allowed; + transform: none !important; + box-shadow: none !important; +} + +/* Start Button */ +.btn-record { + background: linear-gradient(135deg, #10b981, #059669); + color: #ffffff; +} + +.btn-record:not(:disabled):hover { + background: linear-gradient(135deg, #059669, #047857); + box-shadow: 0 4px 14px rgba(16, 185, 129, 0.4); + transform: translateY(-1px); +} + +/* Stop Button */ +.btn-stop { + background: linear-gradient(135deg, #f87171, #ef4444); + color: #ffffff; +} + +.btn-stop:not(:disabled):hover { + background: linear-gradient(135deg, #ef4444, #dc2626); + box-shadow: 0 4px 14px rgba(239, 68, 68, 0.4); + transform: translateY(-1px); +} + +/* Upload Audio Button */ +.btn-upload { + background: #ffffff; + border: 1px solid #fcd34d; + color: #b45309; +} + +.btn-upload:hover { + background: #fffbeb; + border-color: #f59e0b; +} + +/* Demo Button */ +.btn-demo { + background: #ffffff; + border: 1px solid #cbd5e1; + color: #475569; +} + +.btn-demo:hover { + background: #f8fafc; + border-color: #94a3b8; + color: #0f172a; +} + +.btn-icon { + font-size: 13px; +} + +/* ══════════════════════════════════════════════════════════════════ + CARD 3: TRANSCRIPT + ══════════════════════════════════════════════════════════════════ */ +.header-actions { + display: flex; + align-items: center; + gap: 8px; +} + +.btn-sm-action { + background: #f8fafc; + border: 1px solid #e2e8f0; + border-radius: var(--radius-sm); + padding: 5px 10px; + font-size: 12px; + font-weight: 600; + color: #475569; + cursor: pointer; + display: inline-flex; + align-items: center; + gap: 4px; + transition: all 0.15s; +} + +.btn-sm-action:hover { + background: #f1f5f9; + color: #0f172a; +} + +/* Real-time Live Badge */ +.live-realtime-badge { + display: inline-flex; + align-items: center; + gap: 5px; + background: #ecfdf5; + color: #059669; + border: 1px solid #a7f3d0; + font-size: 11px; + font-weight: 700; + padding: 2px 8px; + border-radius: var(--radius-full); +} + +.live-blink-dot { + width: 6px; + height: 6px; + background-color: #10b981; + border-radius: 50%; + animation: pulse-green 1s infinite; +} + +/* Transcript Search */ +.transcript-search-box { + display: flex; + align-items: center; + background: #ffffff; + border: 1px solid #cbd5e1; + border-radius: var(--radius-sm); + padding: 0 8px; + height: 28px; +} + +.transcript-search-box .search-icon { + font-size: 11px; + opacity: 0.6; + margin-right: 4px; +} + +.transcript-search-box input { + border: none; + outline: none; + font-size: 12px; + font-family: inherit; + width: 130px; + background: transparent; + color: #0f172a; +} + +/* Audio Playback & Sync Control Bar */ +.audio-playback-bar { + display: flex; + align-items: center; + gap: 12px; + background: #f1f5f9; + border: 1px solid #cbd5e1; + border-radius: var(--radius-md); + padding: 10px 14px; + margin-bottom: 12px; +} + +.btn-play-pause { + width: 38px; + height: 38px; + border-radius: 50%; + background: linear-gradient(135deg, #2563eb, #1d4ed8); + color: #ffffff; + border: none; + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; + box-shadow: 0 2px 6px rgba(37, 99, 235, 0.3); + transition: transform 0.15s, background 0.15s; + flex-shrink: 0; +} + +.btn-play-pause:hover { + transform: scale(1.05); + background: #1d4ed8; +} + +.audio-progress-container { + flex: 1; + display: flex; + flex-direction: column; + gap: 4px; +} + +.audio-scrubber { + width: 100%; + height: 6px; + accent-color: #2563eb; + cursor: pointer; +} + +.audio-time-row { + display: flex; + justify-content: space-between; + align-items: center; + font-size: 11px; + font-family: var(--font-mono); + color: #64748b; +} + +.sync-hint { + font-family: var(--font-sans); + font-size: 11px; + color: #3b82f6; + font-weight: 600; +} + +/* Filter Bar */ +.transcript-filter-bar { + display: flex; + gap: 6px; + margin-bottom: 12px; +} + +.filter-pill { + background: #ffffff; + border: 1px solid #cbd5e1; + border-radius: var(--radius-full); + padding: 4px 12px; + font-size: 11.5px; + font-weight: 600; + color: #475569; + cursor: pointer; + transition: all 0.15s; +} + +.filter-pill:hover { + background: #f8fafc; + color: #0f172a; +} + +.filter-pill.active { + background: #2563eb; + color: #ffffff; + border-color: #2563eb; +} + +/* Transcript Scroll Viewport */ +.transcript-viewport { + min-height: 180px; + max-height: 440px; + overflow-y: auto; + background: #f8fafc; + border: 1px solid #e2e8f0; + border-radius: var(--radius-md); + padding: 16px; + display: flex; + flex-direction: column; + gap: 12px; + scroll-behavior: smooth; +} + +.transcript-placeholder { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 28px 16px; + text-align: center; + color: #94a3b8; + margin: auto; +} + +.placeholder-icon { + font-size: 26px; + margin-bottom: 8px; + opacity: 0.6; +} + +.transcript-placeholder p { + font-size: 13.5px; + font-weight: 600; + color: #64748b; +} + +.placeholder-sub { + font-size: 12px; + color: #94a3b8; + margin-top: 4px; + max-width: 480px; +} + +/* Dialogue Utterances */ +.utterance-item { + display: flex; + gap: 12px; + padding: 12px 14px; + border-radius: var(--radius-md); + background: #ffffff; + border: 1px solid #e2e8f0; + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03); + cursor: pointer; + transition: all 0.2s ease; +} + +.utterance-item:hover { + border-color: #93c5fd; + box-shadow: 0 3px 8px rgba(37, 99, 235, 0.08); +} + +.utterance-item.doctor { + border-left: 4px solid #2563eb; +} + +.utterance-item.patient { + border-left: 4px solid #10b981; +} + +.utterance-item.relative { + border-left: 4px solid #8b5cf6; +} + +.utterance-item.nurse { + border-left: 4px solid #f59e0b; +} + +/* Active Playing Karaoke Glow */ +.utterance-item.active-playing { + background: #eff6ff !important; + border-color: #3b82f6 !important; + box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.25), 0 4px 12px rgba(37, 99, 235, 0.15) !important; + transform: translateX(4px); +} + +.utterance-avatar { + font-size: 20px; + margin-top: 2px; +} + +.utterance-content { + flex: 1; +} + +.utterance-meta { + display: flex; + align-items: center; + gap: 8px; + margin-bottom: 4px; +} + +.utterance-speaker { + font-size: 12.5px; + font-weight: 700; + color: #0f172a; +} + +.utterance-speaker.doctor-color { color: #2563eb; } +.utterance-speaker.patient-color { color: #059669; } +.utterance-speaker.relative-color { color: #7c3aed; } +.utterance-speaker.nurse-color { color: #d97706; } + +.utterance-time { + font-size: 11px; + font-family: var(--font-mono); + color: #94a3b8; + background: #f1f5f9; + padding: 1px 6px; + border-radius: 4px; +} + +.utterance-lang-badge { + font-size: 10px; + background: #eff6ff; + color: #2563eb; + padding: 2px 6px; + border-radius: 4px; + font-weight: 600; +} + +.utterance-text { + font-size: 13.5px; + color: #1e293b; + line-height: 1.6; +} + +/* Live Interim Text Stream */ +.utterance-item.live-streaming { + opacity: 0.9; + border-style: dashed; +} + +/* ══════════════════════════════════════════════════════════════════ + CARD 4: AI CLINICAL SUMMARY + ══════════════════════════════════════════════════════════════════ */ +.summary-content-grid { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 14px; +} + +.summary-col-card { + background: #f8fafc; + border: 1px solid #e2e8f0; + border-radius: var(--radius-md); + padding: 14px 16px; + display: flex; + flex-direction: column; +} + +.summary-col-card.full-span { + grid-column: 1 / -1; +} + +.summary-col-card.highlight-plan { + background: #f0fdf4; + border-color: #bbf7d0; +} + +.col-card-header { + font-size: 11px; + font-weight: 800; + color: #64748b; + text-transform: uppercase; + letter-spacing: 0.05em; + margin-bottom: 8px; + border-bottom: 1px solid #e2e8f0; + padding-bottom: 6px; +} + +.highlight-plan .col-card-header { + color: #15803d; + border-bottom-color: #bbf7d0; +} + +.col-card-body { + font-size: 13.5px; + color: #1e293b; + line-height: 1.6; +} + +.empty-field { + color: #94a3b8; + font-style: italic; +} + +/* Symptoms Tags List */ +.symptom-tag-list { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.symptom-tag { + background: #fee2e2; + color: #b91c1c; + font-size: 12px; + font-weight: 600; + padding: 4px 10px; + border-radius: var(--radius-full); + display: inline-flex; + align-items: center; + gap: 4px; +} + +.plan-item-list { + list-style: none; + display: flex; + flex-direction: column; + gap: 8px; +} + +.plan-item-list li { + display: flex; + align-items: flex-start; + gap: 8px; + font-size: 13.5px; +} + +.plan-item-list li::before { + content: '✓'; + color: #16a34a; + font-weight: 800; + margin-top: 1px; +} + +/* ══════════════════════════════════════════════════════════════════ + DASHBOARD & OTHER VIEWS + ══════════════════════════════════════════════════════════════════ */ +.dash-stats-grid { + display: grid; + grid-template-columns: repeat(4, 1fr); + gap: 16px; +} + +.dash-stat-card { + background: #ffffff; + border: 1px solid var(--card-border); + border-radius: var(--radius-lg); + padding: 18px 20px; + display: flex; + align-items: center; + gap: 14px; + box-shadow: var(--card-shadow); +} + +.stat-icon-wrap { + width: 44px; + height: 44px; + border-radius: var(--radius-md); + display: flex; + align-items: center; + justify-content: center; + font-size: 20px; +} + +.stat-icon-wrap.blue { background: #dbeafe; color: #2563eb; } +.stat-icon-wrap.green { background: #dcfce7; color: #16a34a; } +.stat-icon-wrap.purple { background: #f3e8ff; color: #9333ea; } +.stat-icon-wrap.amber { background: #fef3c7; color: #d97706; } + +.stat-info { + display: flex; + flex-direction: column; +} + +.stat-num { + font-size: 20px; + font-weight: 800; + color: #0f172a; +} + +.stat-name { + font-size: 12px; + color: #64748b; + font-weight: 500; +} + +.mt-4 { margin-top: 16px; } +.mb-3 { margin-bottom: 12px; } + +/* Data Tables */ +.recent-table-wrap { + overflow-x: auto; +} + +.data-table { + width: 100%; + border-collapse: collapse; + text-align: left; +} + +.data-table th { + background: #f8fafc; + padding: 10px 14px; + font-size: 11.5px; + font-weight: 700; + color: #64748b; + border-bottom: 1px solid #e2e8f0; + text-transform: uppercase; + letter-spacing: 0.04em; +} + +.data-table td { + padding: 12px 14px; + border-bottom: 1px solid #f1f5f9; + font-size: 13px; + color: #334155; +} + +.badge-lang { + background: #eff6ff; + color: #2563eb; + padding: 3px 8px; + border-radius: 4px; + font-size: 11.5px; + font-weight: 600; +} + +.table-btn { + background: #eff6ff; + color: #2563eb; + border: 1px solid #bfdbfe; + padding: 4px 10px; + border-radius: var(--radius-sm); + font-size: 12px; + font-weight: 600; + cursor: pointer; + transition: all 0.15s; +} + +.table-btn:hover { + background: #2563eb; + color: #ffffff; +} + +/* Doctors Grid */ +.doctors-grid { + display: grid; + grid-template-columns: repeat(4, 1fr); + gap: 16px; +} + +.doctor-card-box { + background: #f8fafc; + border: 1px solid #e2e8f0; + border-radius: var(--radius-md); + padding: 18px; + text-align: center; +} + +.doc-badge-avatar { + font-size: 32px; + margin-bottom: 8px; +} + +.doctor-card-box h4 { + font-size: 15px; + color: #0f172a; + margin-bottom: 2px; +} + +.doc-spec { + font-size: 12px; + color: #2563eb; + font-weight: 600; +} + +.doc-dep { + font-size: 11px; + color: #64748b; + display: block; + margin-top: 4px; +} + +/* ══════════════════════════════════════════════════════════════════ + MODAL & TOAST + ══════════════════════════════════════════════════════════════════ */ +.modal-overlay { + position: fixed; + inset: 0; + background: rgba(15, 23, 42, 0.6); + backdrop-filter: blur(4px); + display: none; + align-items: center; + justify-content: center; + z-index: 200; +} + +.modal-overlay.open { + display: flex; +} + +.modal-card { + background: #ffffff; + border-radius: var(--radius-lg); + width: 90%; + max-width: 480px; + padding: 24px; + box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.2); +} + +.modal-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 18px; + padding-bottom: 12px; + border-bottom: 1px solid #e2e8f0; +} + +.modal-header h3 { + font-size: 16px; + font-weight: 700; + color: #0f172a; +} + +.modal-close-btn { + background: transparent; + border: none; + font-size: 20px; + color: #64748b; + cursor: pointer; +} + +.modal-footer { + display: flex; + justify-content: flex-end; + gap: 10px; + margin-top: 20px; + padding-top: 14px; + border-top: 1px solid #e2e8f0; +} + +.btn-cancel { + background: #f1f5f9; + border: none; + padding: 8px 16px; + border-radius: var(--radius-md); + color: #475569; + font-weight: 600; + cursor: pointer; +} + +.btn-save-patient { + background: #2563eb; + border: none; + padding: 8px 18px; + border-radius: var(--radius-md); + color: #ffffff; + font-weight: 700; + cursor: pointer; +} + +.btn-primary-sm { + background: #2563eb; + color: #ffffff; + border: none; + padding: 6px 14px; + border-radius: var(--radius-md); + font-weight: 600; + font-size: 12.5px; + cursor: pointer; +} + +.input-row-flex { + display: flex; + gap: 10px; +} + +.input-row-flex input, +.input-row-flex select, +.modal-body input, +.modal-body select { + background: #f8fafc; + border: 1px solid #cbd5e1; + border-radius: var(--radius-md); + padding: 9px 12px; + font-family: inherit; + font-size: 13px; + color: #0f172a; + outline: none; +} + +.modal-body input:focus, +.modal-body select:focus { + border-color: #2563eb; +} + +/* Toast */ +.toast-notification { + position: fixed; + bottom: 24px; + right: 24px; + background: #0f172a; + color: #ffffff; + padding: 12px 20px; + border-radius: var(--radius-md); + font-size: 13px; + font-weight: 600; + box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.2); + transform: translateY(100px); + opacity: 0; + transition: all 0.3s ease; + z-index: 300; +} + +.toast-notification.show { + transform: translateY(0); + opacity: 1; +} + +/* ══════════════════════════════════════════════════════════════════ + RESPONSIVE DESIGN + ══════════════════════════════════════════════════════════════════ */ +@media (max-width: 1024px) { + .details-form-grid { + grid-template-columns: repeat(2, 1fr); + } + .summary-content-grid { + grid-template-columns: repeat(2, 1fr); + } + .dash-stats-grid { + grid-template-columns: repeat(2, 1fr); + } + .doctors-grid { + grid-template-columns: repeat(2, 1fr); + } +} + +@media (max-width: 768px) { + .menu-toggle-btn { + display: block; + } + .sidebar { + position: fixed; + transform: translateX(-100%); + } + .sidebar.open { + transform: translateX(0); + } + .details-form-grid { + grid-template-columns: 1fr; + } + .summary-content-grid { + grid-template-columns: 1fr; + } + .dash-stats-grid { + grid-template-columns: 1fr; + } + .doctor-profile-card .doctor-meta { + display: none; + } +} diff --git a/run_batch_qwen.js b/run_batch_qwen.js new file mode 100644 index 0000000..24b37bb --- /dev/null +++ b/run_batch_qwen.js @@ -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); diff --git a/run_nemo.py b/run_nemo.py new file mode 100644 index 0000000..9c67b13 --- /dev/null +++ b/run_nemo.py @@ -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() diff --git a/run_pipeline.py b/run_pipeline.py new file mode 100644 index 0000000..0bc478b --- /dev/null +++ b/run_pipeline.py @@ -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()) diff --git a/server.js b/server.js new file mode 100644 index 0000000..9b49f52 --- /dev/null +++ b/server.js @@ -0,0 +1,1014 @@ +require('dotenv').config(); +const express = require('express'); +const path = require('path'); +const http = require('http'); +const fs = require('fs'); +const os = require('os'); +const WebSocket = require('ws'); +const { WebSocketServer } = WebSocket; + +const app = express(); +app.use(express.json({ limit: '100mb' })); +app.use((req, res, next) => { + res.header('Access-Control-Allow-Origin', '*'); + res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); + res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization'); + if (req.method === 'OPTIONS') return res.sendStatus(200); + next(); +}); +app.use(express.static(path.join(__dirname, 'public'))); + +const SARVAM_API_KEY = process.env.SARVAM_API_KEY; +const SARVAM_CHAT_MODEL = process.env.SARVAM_CHAT_MODEL || 'sarvam-105b-conversations'; +const GROQ_API_KEY = process.env.GROQ_API_KEY; +const GROQ_PRIMARY_MODEL = 'openai/gpt-oss-120b'; +const GROQ_FALLBACK_MODEL = 'minimaxai/minimax-m2.7'; +const PORT = process.env.PORT || 3000; + +if (!SARVAM_API_KEY) { + console.warn('WARNING: .env मध्ये SARVAM_API_KEY सेट केलेली नाही.'); +} +if (!GROQ_API_KEY) { + console.warn('WARNING: .env मध्ये GROQ_API_KEY सेट केलेली नाही. Summary local fallback वापरेल.'); +} + +const SUMMARY_SYSTEM_PROMPT = `You are an expert AI Clinical Documentation Assistant. +Analyze the doctor-patient consultation transcript (which may be in Marathi, Hindi, English, or mixed Indic language). +Generate a structured medical summary in clean JSON format matching this schema: +{ + "chief_complaint": "Primary reason for visit and duration", + "symptoms": ["Symptom 1", "Symptom 2"], + "history": "History of present illness, past medical/surgical history, allergy history", + "assessment": "Doctor diagnosis or clinical impression", + "plan": ["Treatment step 1", "Medication Rx with dosage", "Follow-up/Diet instructions"] +} +If a section is not mentioned in the transcript, write "Not mentioned". Respond with pure JSON only, no markdown markers or extra conversational text.`; + +// --------------------------------------------------------------------------- +// Sarvam AI Text Translation Safeguard (Always English Pipeline) +// Uses Sarvam Translate API (mayura:v1) to translate any residual Indic text +// --------------------------------------------------------------------------- +async function ensureEnglishText(text) { + if (!text || typeof text !== 'string' || !text.trim()) return text; + // Check if text contains Devanagari/Indic characters (Marathi/Hindi) + if (!/[\u0900-\u097F]/.test(text)) return text; + if (!SARVAM_API_KEY) return text; + + // Handle multi-line strings with speaker markers + const lines = text.split('\n'); + if (lines.length > 1) { + const translated = await Promise.all(lines.map(async line => { + if (!line.trim() || !/[\u0900-\u097F]/.test(line)) return line; + const speakerPrefixMatch = line.match(/^(\s*(?:\[[^\]]+\]|(?:Doctor|Patient|Relative|Nurse|डॉक्टर|पेशंट|रुग्ण)\s*[::\-])\s*)(.*)$/i); + if (speakerPrefixMatch) { + const prefix = speakerPrefixMatch[1]; + const content = speakerPrefixMatch[2]; + const trans = await ensureEnglishText(content); + return prefix + trans; + } + return await ensureEnglishText(line); + })); + return translated.join('\n'); + } + + try { + const resp = await fetch('https://api.sarvam.ai/translate', { + method: 'POST', + headers: { + 'api-subscription-key': SARVAM_API_KEY, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + input: text, + source_language_code: 'auto', + target_language_code: 'en-IN', + mode: 'formal', + model: 'mayura:v1' + }) + }); + if (resp.ok) { + const data = await resp.json(); + if (data.translated_text && data.translated_text.trim()) { + return data.translated_text.trim(); + } + } + } catch (err) { + console.warn('[ensureEnglishText] Sarvam translation fallback error:', err.message); + } + return text; +} + +// --------------------------------------------------------------------------- +// REST: संभाषणाच्या transcript वरून क्लिनिकल समरी — LOCAL extraction (No LLM API) +// Sarvam API फक्त transcript + diarization साठी वापरली जाते, summary साठी नाही. +// --------------------------------------------------------------------------- + +/** + * extractLocalSummary — Transcript मधून keyword/pattern-based NLP extraction + * Marathi, Hindi, English mixed transcripts support करतो. + */ +function extractLocalSummary(transcript) { + const lines = transcript.split(/\n+/).map(l => l.trim()).filter(l => l.length > 0); + + // ── Keyword dictionaries ── + const symptomKeywords = [ + // English primary patterns + { pattern: /chest\s*pain/i, label: 'Chest pain' }, + { pattern: /numbness|tingling/i, label: 'Numbness / Tingling' }, + { pattern: /shortness\s*of\s*breath|breathless/i, label: 'Shortness of breath' }, + { pattern: /fatigue|tired|exhaust/i, label: 'Fatigue / Weakness' }, + { pattern: /insomnia|trouble\s*sleep|cannot\s*sleep|can't\s*sleep/i, label: 'Insomnia' }, + { pattern: /fever|high\s*temperature/i, label: 'Fever' }, + { pattern: /body\s*ache/i, label: 'Body ache' }, + { pattern: /chills|rigors?/i, label: 'Chills' }, + { pattern: /cough/i, label: 'Cough' }, + { pattern: /sore\s*throat|throat\s*pain/i, label: 'Sore throat' }, + { pattern: /difficulty\s*swallowing|trouble\s*swallowing|dysphagia/i, label: 'Difficulty swallowing (Dysphagia)' }, + { pattern: /hoarseness|voice\s*heavy|lost\s*voice/i, label: 'Hoarseness of voice' }, + { pattern: /headache/i, label: 'Headache' }, + { pattern: /vomit|nausea/i, label: 'Nausea / Vomiting' }, + { pattern: /diarrhea|loose\s*motion/i, label: 'Diarrhea' }, + { pattern: /swelling|swollen/i, label: 'Swelling' }, + { pattern: /burning.*urinat|urinat.*burning|dysuria/i, label: 'Burning urination (Dysuria)' }, + { pattern: /thirst|polydipsia/i, label: 'Excessive thirst (Polydipsia)' }, + { pattern: /pain/i, label: 'Pain' }, + // Marathi & Hindi fallback patterns + { pattern: /छातीत\s*(दुख|वेद|दाब)/i, label: 'Chest pain' }, + { pattern: /मुंग्या/i, label: 'Numbness / Tingling' }, + { pattern: /धाप\s*लाग/i, label: 'Shortness of breath' }, + { pattern: /थकवा/i, label: 'Fatigue' }, + { pattern: /झोप\s*(नाही|येत\s*नाही|लागत\s*नाही)/i, label: 'Insomnia' }, + { pattern: /ताप/i, label: 'Fever' }, + { pattern: /अंगदुखी/i, label: 'Body ache' }, + { pattern: /तहान/i, label: 'Excessive thirst (Polydipsia)' }, + { pattern: /लघवी.*जळजळ|जळजळ.*लघवी/i, label: 'Burning urination (Dysuria)' }, + { pattern: /हुडहुडी/i, label: 'Chills' }, + { pattern: /खोकला|खांसी|कफ/i, label: 'Cough' }, + { pattern: /गळ.*दुख|गले.*दर्द|throat.*pain/i, label: 'Sore throat' }, + { pattern: /निगल|गिलने/i, label: 'Difficulty swallowing (Dysphagia)' }, + { pattern: /आवाज.*बैठ|आवाज.*भारी/i, label: 'Hoarseness of voice' }, + { pattern: /डोके\s*दुख/i, label: 'Headache' }, + { pattern: /उलटी|वांती/i, label: 'Vomiting' }, + { pattern: /जुलाब/i, label: 'Diarrhea' }, + { pattern: /सूज/i, label: 'Swelling' }, + { pattern: /बुखार|बुख़ार/i, label: 'Fever' }, + { pattern: /सीने.*दर्द/i, label: 'Chest pain' }, + { pattern: /सांस.*तकलीफ/i, label: 'Shortness of breath' } + ]; + + const historyKeywords = [ + /(?:history|previously|since|duration|past|years?|months?)\s*.{5,80}/gi, + /(?:blood\s*pressure|hypertension|diabetes|sugar|BP|asthma)\s*.{0,80}/gi, + /(?:medicine|tablet|medication|dose|prescription)\s*.{0,60}/gi, + /(?:type\s*\d)/gi, + /(?:पूर्वी|आधी|पासून|वर्ष|साल)\s*.{5,80}/gi, + /(?:ब्लड\s*प्रेशर|डायबिटीस|मधुमेह|दमा)\s*.{0,80}/gi, + ]; + + const assessmentKeywords = [ + /(?:diagnosis|assessment|impression|diagnosed)[\s::\-]*.{5,120}/gi, + /(?:hypertension|diabetes|UTI|tonsillitis|pharyngitis|angina|ischemic|infection)\s*.{0,80}/gi, + /(?:BP|blood\s*pressure|बीपी)\s*\d{2,3}\s*[\/\\]\s*\d{2,3}/gi, + /(?:tonsil|infection|संसर्ग)\s*.{0,60}/gi, + ]; + + const planKeywords = [ + /(?:ECG|echo|MRI|CT|X-?ray|CBC|Urine|blood\s*test|test|investigation|ईसीजी|इको)\s*.{0,80}/gi, + /(?:Tab(?:let)?|Syr(?:up)?|Cap(?:sule)?|medicine|antibiotic|paracetamol|cefixime|telmisartan|amlodipine|गोळी|औषध)\s*.{0,100}/gi, + /(?:diet|salt|exercise|rest|water|warm\s*water|gargle|पथ्य|आहार|व्यायाम)\s*.{0,80}/gi, + /(?:follow[\s-]*up|visit|see\s*me\s*again|come\s*back|days|फॉलो[\s-]*अप)\s*.{0,80}/gi, + ]; + + // ── Extract ── + const fullText = lines.join(' '); + + // Patient lines (first few patient utterances usually describe chief complaint) + const patientLines = lines.filter(l => /^(?:\[.*Patient\]|पेशंट|patient|रुग्ण)/i.test(l)); + const doctorLines = lines.filter(l => /^(?:\[.*Doctor\]|डॉक्टर|doctor)/i.test(l)); + + // Chief Complaint — first patient utterance + let chiefComplaint = 'Not mentioned'; + if (patientLines.length > 0) { + const firstPatient = patientLines[0].replace(/^(?:\[.*?\]|(?:पेशंट|patient|रुग्ण)\s*[::\-])\s*/i, '').trim(); + chiefComplaint = firstPatient.slice(0, 200) || 'Not mentioned'; + } + + // Symptoms + const symptomsFound = new Set(); + symptomKeywords.forEach(kw => { + if (kw.pattern.test(fullText)) { + symptomsFound.add(kw.label); + } + }); + const symptoms = symptomsFound.size > 0 ? [...symptomsFound] : ['No specific symptoms detected in transcript']; + + // History + const historyMatches = new Set(); + historyKeywords.forEach(re => { + const matches = fullText.match(re); + if (matches) matches.forEach(m => historyMatches.add(m.trim())); + }); + const history = historyMatches.size > 0 ? [...historyMatches].join('; ') : 'No prior medical history mentioned in transcript.'; + + // Assessment — from doctor lines + const assessmentMatches = new Set(); + const doctorText = doctorLines.join(' '); + assessmentKeywords.forEach(re => { + const matches = (doctorText || fullText).match(re); + if (matches) matches.forEach(m => assessmentMatches.add(m.trim())); + }); + const assessment = assessmentMatches.size > 0 ? [...assessmentMatches].join('; ') : 'Clinical assessment — refer to transcript for details.'; + + // Plan + const planMatches = new Set(); + planKeywords.forEach(re => { + const matches = (doctorText || fullText).match(re); + if (matches) matches.forEach(m => planMatches.add(m.trim())); + }); + const plan = planMatches.size > 0 ? [...planMatches] : ['Refer to transcript for treatment plan details.']; + + return { + chief_complaint: chiefComplaint, + symptoms, + history, + assessment, + plan, + extraction_method: 'local_nlp' + }; +} + +/** + * callGroqSummary — Groq API ला call करून LLM summary generate करतो + * @param {string} transcript - consultation transcript + * @param {string} model - Groq model ID + * @returns {object|null} parsed summary or null on failure + */ +async function callGroqSummary(transcript, model) { + const resp = await fetch('https://api.groq.com/openai/v1/chat/completions', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${GROQ_API_KEY}` + }, + body: JSON.stringify({ + model: model, + temperature: 0.2, + messages: [ + { role: 'system', content: SUMMARY_SYSTEM_PROMPT }, + { role: 'user', content: `Consultation Transcript:\n${transcript}` } + ] + }) + }); + + if (!resp.ok) { + const errText = await resp.text(); + console.error(`Groq model ${model} error (${resp.status}):`, errText.slice(0, 300)); + return null; + } + + const data = await resp.json(); + const content = data?.choices?.[0]?.message?.content; + if (!content) { + console.error(`Groq model ${model}: empty response`); + return null; + } + + try { + const cleaned = content.trim().replace(/^```json/i, '').replace(/^```/, '').replace(/```$/, '').trim(); + return JSON.parse(cleaned); + } catch (e) { + console.error(`Groq model ${model}: JSON parse failed, returning raw`); + return { + chief_complaint: 'Extracted from conversation', + symptoms: ['See detailed notes below'], + history: 'Refer to raw transcript', + assessment: 'Consultation reviewed', + plan: [content], + raw_text: content + }; + } +} + +app.post('/api/summary', async (req, res) => { + try { + const { transcript } = req.body || {}; + if (!transcript || !transcript.trim()) { + return res.status(400).json({ error: 'Transcript is empty' }); + } + + // Strategy: Groq LLM (primary model → fallback model) → Local NLP extraction + if (GROQ_API_KEY) { + // Try primary model: openai/gpt-oss-120b + console.log(`1️⃣ Trying Groq LLM: ${GROQ_PRIMARY_MODEL}...`); + let summary = await callGroqSummary(transcript, GROQ_PRIMARY_MODEL); + if (summary) { + summary.model_used = GROQ_PRIMARY_MODEL; + console.log(`✅ Summary generated via ${GROQ_PRIMARY_MODEL}`); + return res.json({ summary, notice: `Generated via Groq ${GROQ_PRIMARY_MODEL}` }); + } + + // Try fallback model: minimaxai/minimax-m2.7 + console.log(`2️⃣ Primary failed. Trying fallback: ${GROQ_FALLBACK_MODEL}...`); + summary = await callGroqSummary(transcript, GROQ_FALLBACK_MODEL); + if (summary) { + summary.model_used = GROQ_FALLBACK_MODEL; + console.log(`✅ Summary generated via ${GROQ_FALLBACK_MODEL}`); + return res.json({ summary, notice: `Generated via Groq ${GROQ_FALLBACK_MODEL}` }); + } + + console.warn('⚠️ Both Groq models failed. Falling back to local NLP extraction...'); + } else { + console.log('No GROQ_API_KEY configured. Using local NLP extraction...'); + } + + // Final fallback: Local keyword-based extraction + console.log('3️⃣ Using local keyword-based NLP extraction...'); + const summary = extractLocalSummary(transcript); + console.log('✅ Local summary extraction complete.'); + res.json({ summary, notice: 'Extracted locally (Groq API unavailable or failed)' }); + + } catch (err) { + console.error('summary error:', err); + // Even if everything crashes, try local extraction + try { + const fallback = extractLocalSummary(req.body?.transcript || ''); + return res.json({ summary: fallback, notice: 'Emergency local fallback' }); + } catch (e2) { + res.status(500).json({ error: err.message || 'Unexpected error' }); + } + } +}); + +app.get('/api/health', (req, res) => { + res.json({ + ok: true, + sarvamKeyConfigured: Boolean(SARVAM_API_KEY), + model: SARVAM_CHAT_MODEL, + sttModel: 'saaras:v4' + }); +}); + +// --------------------------------------------------------------------------- +// REST: Multiple Clinical Cases & Demo Sample Conversations +// --------------------------------------------------------------------------- +const CLINICAL_CASES = [ + { + id: 'case-cardiology', + title: 'Cardiology — Chest Pain & High BP', + patientName: 'Ramesh Patil', + patientId: 'PT-2026-00124', + doctorName: 'Dr. Sharma (Cardiology)', + doctorSpecialty: 'Cardiologist', + language: 'en-IN', + durationSec: 222, + date: new Date().toLocaleDateString('en-GB'), + transcript: `Doctor: Hello Rameshji, please have a seat. What trouble are you experiencing? +Patient: Hello Doctor. For the past three days, I have had chest pain and numbness in my left arm. +Doctor: Okay, do you experience more shortness of breath while walking or climbing stairs? +Patient: Yes Doctor, even a little walking causes breathlessness and severe fatigue. I cannot sleep well at night. +Doctor: Do you have any prior history of high blood pressure or diabetes? +Patient: Yes Doctor, I have had high blood pressure for five years, but I was not taking medicine regularly. +Doctor: Alright, let me check your BP. It is 160/100, which is high. We need to do an immediate ECG and 2D Echo test. In the meantime, I will prescribe medication to lower your blood pressure. +Patient: Sure Doctor, I will get the tests done today. Any dietary restrictions to follow? +Doctor: Yes, reduce salt intake in your diet, avoid oily and fatty foods, do light exercise, and avoid stress. Come back to see me this evening once the test reports arrive.`, + summary: { + chief_complaint: "Chest pain radiating to the left arm and numbness for the past 3 days", + symptoms: [ + "Chest pain", + "Numbness in left arm", + "Shortness of breath on exertion", + "Severe fatigue and insomnia" + ], + history: "5-year history of hypertension, with irregular medication adherence.", + assessment: "Uncontrolled Hypertension (BP: 160/100 mmHg), Suspected Angina / Ischemic Heart Disease. Immediate cardiac evaluation required.", + plan: [ + "Immediate ECG and 2D Echocardiography tests", + "Start anti-hypertensive medication (Telmisartan 40mg + Amlodipine 5mg) immediately", + "Reduce dietary salt intake and avoid oily/fatty foods", + "Avoid physical and emotional stress; follow-up consultation this evening with reports" + ] + } + }, + { + id: 'case-diabetes', + title: 'General Medicine — Diabetes & Fever', + patientName: 'Sunita Deshmukh', + patientId: 'PT-2026-00123', + doctorName: 'Dr. Kulkarni (General Physician)', + doctorSpecialty: 'General Medicine', + language: 'en-IN', + durationSec: 195, + date: new Date().toLocaleDateString('en-GB'), + transcript: `Doctor: Welcome Sunitatai, what problem are you having? +Patient: Doctor, I have had a high fever and body ache for two days. I feel thirsty frequently and have a burning sensation while urinating. +Doctor: Alright, did you measure the fever at home? +Patient: Yes, last night it was 102 degrees with severe chills. +Doctor: Do you have diabetes? Have you checked your sugar levels recently? +Patient: Yes, I have Type 2 Diabetes. Last week my fasting blood sugar was 180. +Doctor: The fever could be due to a urinary tract infection (UTI) and uncontrolled blood sugar. I am prescribing an antibiotic and paracetamol. We will also do a CBC, urine routine, and fasting blood sugar test. +Patient: Okay Doctor, should I drink plenty of water? +Doctor: Yes, drink plenty of water and lemon water. Completely stop sugary foods. Come back with reports in 3 days.`, + summary: { + chief_complaint: "High fever with chills, body ache, and dysuria for 2 days", + symptoms: [ + "High fever (102°F)", + "Body ache and chills", + "Burning urination (Dysuria)", + "Excessive thirst (Polydipsia)" + ], + history: "Type 2 Diabetes Mellitus - recent Fasting Blood Sugar: 180 mg/dL.", + assessment: "Urinary Tract Infection (UTI) with Uncontrolled Diabetes Mellitus & Acute Febrile Illness.", + plan: [ + "Tab Paracetamol 650mg post-meals when fever occurs", + "Tab Cefixime 200mg twice daily for 5 days", + "CBC, Urine Routine & Microscopy, and Fasting Blood Sugar tests", + "Drink 3-4 liters of water daily and maintain strict glycemic control" + ] + } + }, + { + id: 'case-ent', + title: 'ENT — Sore Throat & Severe Cough', + patientName: 'Amit Verma', + patientId: 'PT-2026-00122', + doctorName: 'Dr. Joshi (ENT Specialist)', + doctorSpecialty: 'Otolaryngology', + language: 'en-IN', + durationSec: 160, + date: new Date().toLocaleDateString('en-GB'), + transcript: `Doctor: Hello Amitji, please tell me what trouble you are having. +Patient: Doctor, I have severe pain in my throat and a lot of difficulty swallowing food. I also have a dry cough. +Doctor: How long has this issue been going on? Does your voice feel heavy or hoarse? +Patient: It has been four days, Doctor. My voice has become hoarse and I cannot sleep at night due to coughing. +Doctor: Open your mouth, let me examine your tonsils. The tonsils are quite red and swollen. +Patient: Is it a serious infection, Doctor? +Doctor: It is acute tonsillitis and pharyngitis. Gargle with warm salt water 3 times a day, and strictly avoid cold water and ice cream. I am prescribing an antibiotic and a cough syrup. +Patient: Thank you Doctor, how many days until I feel relief? +Doctor: You will see significant improvement in three days, but be sure to complete the full 5-day course.`, + summary: { + chief_complaint: "Severe throat pain, difficulty swallowing, and dry cough for 4 days", + symptoms: [ + "Severe throat pain", + "Difficulty swallowing (Dysphagia)", + "Hoarseness of voice", + "Nocturnal dry cough" + ], + history: "No significant prior medical illness; symptoms started after intake of cold beverages.", + assessment: "Acute Tonsillitis with Pharyngitis (Upper Respiratory Tract Infection).", + plan: [ + "Tab Amoxicillin + Clavulanate 625mg twice daily for 5 days", + "Syr Cough Relief 10ml at night before sleeping", + "Warm saline gargles 3 times a day", + "Strictly avoid cold foods, sour items, and oily food" + ] + } + } +]; + +app.get('/api/demos', (req, res) => { + res.json({ cases: CLINICAL_CASES }); +}); + +app.get('/api/demo', (req, res) => { + const caseId = req.query.case || 'case-cardiology'; + const selectedCase = CLINICAL_CASES.find(c => c.id === caseId) || CLINICAL_CASES[0]; + res.json(selectedCase); +}); + +// --------------------------------------------------------------------------- +// REST: Single Chunk Streaming STT +// --------------------------------------------------------------------------- +app.post('/api/transcribe-chunk', async (req, res) => { + try { + const { audio_chunk_b64, chunk_index, total_chunks, start_time_sec, language_code } = req.body || {}; + if (!audio_chunk_b64) return res.status(400).json({ error: 'audio_chunk_b64 missing' }); + if (!SARVAM_API_KEY) return res.status(500).json({ error: 'SARVAM_API_KEY not configured on server.' }); + + const wavBuffer = Buffer.from(audio_chunk_b64, 'base64'); + const lang = (language_code && language_code !== 'auto') ? language_code : 'unknown'; + + const formData = new FormData(); + const blob = new Blob([wavBuffer], { type: 'audio/wav' }); + formData.append('file', blob, `chunk_${chunk_index || 0}.wav`); + formData.append('model', 'saaras:v4'); + formData.append('mode', 'translate'); + formData.append('language_code', lang); + const resp = await fetch('https://api.sarvam.ai/speech-to-text', { + method: 'POST', + headers: { 'api-subscription-key': SARVAM_API_KEY }, + body: formData + }); + + if (!resp.ok) { + const errText = await resp.text(); + console.error(`Sarvam STT chunk ${chunk_index} error:`, errText); + // BUG 5 FIX: Quota error पण proper 402 status code पाठवा (200 नाही) + if (errText.includes('insufficient_quota') || errText.includes('No credits available') || resp.status === 402) { + return res.status(402).json({ + transcript: '', + isQuotaError: true, + error: 'Sarvam API credits exhausted. Please recharge your Sarvam account.' + }); + } + return res.status(resp.status).json({ error: `Sarvam STT error: ${errText.slice(0, 400)}` }); + } + + const data = await resp.json(); + let transcriptText = data.transcript || ''; + transcriptText = await ensureEnglishText(transcriptText); + console.log(`✅ Chunk ${chunk_index + 1}/${total_chunks} transcribed (English): "${transcriptText.slice(0, 60)}..."`); + res.json({ + chunk_index: chunk_index || 0, + total_chunks: total_chunks || 1, + transcript: transcriptText, + language_code: 'en-IN' + }); + } catch (err) { + console.error('transcribe-chunk error:', err); + res.status(500).json({ error: err.message || 'Chunk transcription error' }); + } +}); + +// --------------------------------------------------------------------------- +// REST: Hybrid Diarization Endpoint (Production Approach) +// Uses Sarvam STT + Nvidia NeMo via hybrid_diarization.py +// --------------------------------------------------------------------------- +const { exec } = require('child_process'); +const crypto = require('crypto'); + +app.post('/api/hybrid-transcribe', async (req, res) => { + try { + const { audio_b64 } = req.body || {}; + if (!audio_b64) return res.status(400).json({ error: 'audio_b64 missing' }); + + let wavBuffer = Buffer.from(audio_b64, 'base64'); + + // Save to temp file + const tempFileName = `temp_audio/hybrid_${crypto.randomBytes(6).toString('hex')}.wav`; + if (!fs.existsSync('temp_audio')) fs.mkdirSync('temp_audio'); + fs.writeFileSync(tempFileName, wavBuffer); + + console.log(`[Hybrid] Running hybrid_diarization.py on ${tempFileName}...`); + + // Execute python script + // Ensure you have python environment with NeMo set up! + exec(`python hybrid_diarization.py ${tempFileName}`, { maxBuffer: 1024 * 1024 * 10 }, async (error, stdout, stderr) => { + // Clean up temp file + if (fs.existsSync(tempFileName)) fs.unlinkSync(tempFileName); + + if (error) { + console.error(`[Hybrid] Error running python: ${error.message}`); + console.error(`[Hybrid] stderr: ${stderr}`); + return res.status(500).json({ error: 'Hybrid Diarization failed' }); + } + + // Extract the dialogue part from stdout + let finalTranscript = ""; + const splitToken = "--- FINAL HYBRID DIALOGUE ---"; + if (stdout.includes(splitToken)) { + finalTranscript = stdout.split(splitToken)[1].trim(); + } else { + finalTranscript = stdout; + } + + // Step 2: Use LLM to correct Context / Roles and ensure English output + console.log(`[Hybrid] Running LLM Context Correction (English)...`); + const correctionPrompt = `You are a medical NLP assistant. +Below is a transcript diarized by an AI model. The speaker tags might have slight errors. +Based on context (Doctor asks questions/prescribes, Patient describes symptoms), fix any obvious speaker tag errors. +Format the output as a clean dialogue. +Ensure the spoken dialogue is always in clear, fluent English, translating from Marathi or Hindi if any non-English text is present, while strictly preserving medical meaning and intent. +Transcript: +${finalTranscript.slice(0, 4000)}`; + + try { + const llmRes = await fetch('https://api.sarvam.ai/v1/chat/completions', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'api-subscription-key': SARVAM_API_KEY + }, + body: JSON.stringify({ + model: SARVAM_CHAT_MODEL, + temperature: 0.1, + max_tokens: 2000, + messages: [{ role: 'system', content: 'You are a helpful assistant.' }, { role: 'user', content: correctionPrompt }] + }) + }); + const llmData = await llmRes.json(); + const content = llmData?.choices?.[0]?.message?.content; + if (content && content.trim()) { + finalTranscript = content.trim(); + } + } catch (err) { + console.error("[Hybrid] LLM Correction failed, using raw hybrid output:", err.message); + } + + finalTranscript = await ensureEnglishText(finalTranscript); + console.log(`[Hybrid] Success!`); + res.json({ transcript: finalTranscript }); + }); + + } catch (err) { + console.error('hybrid-transcribe error:', err); + res.status(500).json({ error: err.message || 'Unexpected error' }); + } +}); + +// --------------------------------------------------------------------------- +// REST: Full audio (base64 WAV) → Sarvam STT → transcript +// Splits into 25-second chunks to stay within 30s API limit. +// --------------------------------------------------------------------------- +app.post('/api/transcribe', async (req, res) => { + try { + const { audio_b64, language_code } = req.body || {}; + if (!audio_b64) return res.status(400).json({ error: 'audio_b64 missing' }); + if (!SARVAM_API_KEY) return res.status(500).json({ error: 'SARVAM_API_KEY not configured on server.' }); + + let wavBuffer = Buffer.from(audio_b64, 'base64'); + let { dataOffset, dataLength, sampleRate, numChannels, bitsPerSample } = parseWavHeader(wavBuffer); + const bytesPerSec = sampleRate * numChannels * (bitsPerSample / 8); + + // Audio crop logic removed to process FULL audio + + const lang = (language_code && language_code !== 'auto') ? language_code : 'unknown'; + + console.log("1. Initializing Sarvam Batch Job (Transcript + Diarization, Mode: Translate)..."); + const initRes = await fetch('https://api.sarvam.ai/speech-to-text/job/v1', { + method: 'POST', + headers: { + 'api-subscription-key': SARVAM_API_KEY, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + job_parameters: { + model: "saaras:v4", + mode: "translate", + with_diarization: true, + with_timestamps: true, + language_code: lang + } + }) + }); + const initData = await initRes.json(); + if (!initData.job_id) throw new Error("Failed to initialize job: " + JSON.stringify(initData)); + const jobId = initData.job_id; + + console.log("2. Getting Upload URL..."); + const uploadRes = await fetch('https://api.sarvam.ai/speech-to-text/job/v1/upload-files', { + method: 'POST', + headers: { + 'api-subscription-key': SARVAM_API_KEY, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + job_id: jobId, + files: ["audio.wav"] + }) + }); + const uploadData = await uploadRes.json(); + const uploadUrl = uploadData.upload_urls["audio.wav"].file_url; + + console.log("3. Uploading Audio..."); + const putRes = await fetch(uploadUrl, { + method: 'PUT', + headers: { + 'x-ms-blob-type': 'BlockBlob', + 'Content-Type': 'audio/wav' + }, + body: wavBuffer + }); + if (!putRes.ok) throw new Error("Failed to upload audio to blob."); + + console.log("4. Starting Job..."); + await fetch(`https://api.sarvam.ai/speech-to-text/job/v1/${jobId}/start`, { + method: 'POST', + headers: { + 'api-subscription-key': SARVAM_API_KEY, + 'Content-Type': 'application/json' + } + }); + + console.log("5. Polling Status..."); + let statusData; + for (let i = 0; i < 60; i++) { + const statusRes = await fetch(`https://api.sarvam.ai/speech-to-text/job/v1/${jobId}/status`, { + method: 'GET', + headers: { 'api-subscription-key': SARVAM_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") { + throw new Error("Job failed or timed out: " + JSON.stringify(statusData)); + } + + const outFile = statusData.job_details[0].outputs[0].file_name; + console.log("6. Getting Download URL..."); + const dlRes = await fetch('https://api.sarvam.ai/speech-to-text/job/v1/download-files', { + method: 'POST', + headers: { + 'api-subscription-key': SARVAM_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(); + + let finalTranscript = ''; + + // Parse Diarized Transcript natively returned by Sarvam + if (resultData.diarized_transcript && resultData.diarized_transcript.entries && resultData.diarized_transcript.entries.length > 0) { + console.log("Sample Diarization Entry from Sarvam:", resultData.diarized_transcript.entries[0]); + + // Step 1: Normalize Speaker IDs and extract plain conversation for NLP + const normalizedEntries = await Promise.all(resultData.diarized_transcript.entries.map(async entry => { + const rawId = (entry.speaker || entry.speaker_id || entry.speaker_label || '0').toString(); + const speakerId = rawId.toUpperCase().startsWith('SPEAKER') ? rawId : `Speaker_${rawId}`; + let textContent = entry.text || entry.transcript || entry.words || ''; + textContent = await ensureEnglishText(textContent); + return { speakerId, textContent }; + })); + + const plainConversation = normalizedEntries.map(entry => `${entry.speakerId}: ${entry.textContent}`).join('\n'); + const firstSpeakerId = normalizedEntries[0].speakerId; + + // Step 2: Role Classifier using LLM + console.log("8. Running NLP Role Classifier (LLM Context Analysis)..."); + let roleMap = {}; + const classifierPrompt = `You are a medical NLP Role Classifier. +TASK: Analyze this transcript and classify each unique speaker as 'Doctor', 'Patient', 'Relative', or 'Nurse'. +METHOD: Use Keywords (e.g., medicine, checkup = Doctor), Context, and conversational patterns. +OUTPUT: Output ONLY a valid JSON object mapping exact speaker IDs to roles. Example: {"Speaker_1": "Doctor", "Speaker_2": "Patient"}. + +TRANSCRIPT: +${plainConversation.slice(0, 3000)}`; + + try { + const llmRes = await fetch('https://api.sarvam.ai/v1/chat/completions', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'api-subscription-key': SARVAM_API_KEY + }, + body: JSON.stringify({ + model: SARVAM_CHAT_MODEL, + temperature: 0.1, + max_tokens: 300, + messages: [{ role: 'system', content: 'Output JSON only.' }, { role: 'user', content: classifierPrompt }] + }) + }); + const llmData = await llmRes.json(); + const content = llmData?.choices?.[0]?.message?.content || ""; + const match = content.match(/\{[\s\S]*\}/); + if (match) { + roleMap = JSON.parse(match[0]); + console.log("Role Classification Output:", roleMap); + } + } catch (err) { + console.error("Role Classifier failed, falling back to defaults:", err.message); + } + + // Step 3: Apply Classifications for UI Output + finalTranscript = normalizedEntries.map(entry => { + // Use the LLM's classification or fallback to Patient + let role = roleMap[entry.speakerId] || 'Patient'; + if (Object.keys(roleMap).length === 0 && entry.speakerId === firstSpeakerId) { + role = 'Doctor'; // hardcoded fallback if LLM completely fails + } + + return `[${entry.speakerId} | ${role}] ${entry.textContent}`; + }).join('\n\n'); + console.log("Sarvam Native Diarization + Role Classification complete!"); + } else { + finalTranscript = await ensureEnglishText(resultData.transcript || "No transcript found."); + } + + res.json({ + transcript: finalTranscript, + chunks: 1, + language: lang, + processedSeconds: dataLength / bytesPerSec + }); + } catch (err) { + console.error('transcribe error:', err); + res.status(500).json({ error: err.message || 'Unexpected error' }); + } +}); + +// --------------------------------------------------------------------------- +// REST: Standalone Diarization Endpoint +// --------------------------------------------------------------------------- +app.post('/api/diarize', async (req, res) => { + try { + const { transcript } = req.body || {}; + if (!transcript) return res.status(400).json({ error: 'transcript missing' }); + if (!SARVAM_API_KEY) return res.status(500).json({ error: 'SARVAM_API_KEY not configured.' }); + let finalTranscript = transcript; + const DIARIZE_PROMPT = `You are an expert medical conversation diarizer. +TASK: Identify WHO said WHAT in this 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 spoken words in English). +3. "Doctor" = asks questions, examines, prescribes. "Patient" = describes symptoms. +4. The "text" field must ALWAYS be in English. If any input conversation is in Marathi, Hindi, or mixed Indic language, translate it faithfully into English while strictly preserving the original meaning, context, and clinical intent without losing or hallucinating information. + +Example Output: +[ + {"speaker": "Doctor", "text": "What trouble are you experiencing?"}, + {"speaker": "Patient", "text": "I have had a headache for two days."} +] + +NOW DIARIZE THIS: +${transcript}`; + + const diarizeResp = await fetch('https://api.sarvam.ai/v1/chat/completions', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'api-subscription-key': SARVAM_API_KEY + }, + body: JSON.stringify({ + model: SARVAM_CHAT_MODEL, + temperature: 0.1, + max_tokens: 2500, + messages: [ + { role: 'system', content: 'You are a helpful JSON API returning only valid JSON.' }, + { role: 'user', content: DIARIZE_PROMPT } + ] + }) + }); + + if (diarizeResp.ok) { + const diarizeData = await diarizeResp.json(); + let content = diarizeData?.choices?.[0]?.message?.content; + if (content && content.trim()) { + try { + const cleaned = content.trim().replace(/^```(?:json)?/i, '').replace(/```$/, '').trim(); + const parsed = JSON.parse(cleaned); + finalTranscript = parsed.map(item => `${item.speaker}: ${item.text}`).join('\n\n'); + } catch (err) { + console.error("Failed to parse Diarize JSON:", err); + } + } + } else { + const errText = await diarizeResp.text(); + console.error('Sarvam Diarization failed:', errText); + if (errText.includes('insufficient_quota') || errText.includes('No credits available')) { + return res.status(402).json({ error: 'Sarvam API quota exhausted for LLM.' }); + } + return res.status(500).json({ error: 'Diarization API failed.' }); + } + + finalTranscript = await ensureEnglishText(finalTranscript); + res.json({ transcript: finalTranscript }); + } catch (err) { + console.error('diarize error:', err); + res.status(500).json({ error: err.message || 'Unexpected error' }); + } +}); + +// ── WAV helpers ────────────────────────────────────────────────────────────── +function parseWavHeader(buf) { + let offset = 12; + let sampleRate = 16000, numChannels = 1, bitsPerSample = 16; + let dataOffset = 44, dataLength = buf.length - 44; + + while (offset + 8 <= buf.length) { + const chunkId = buf.toString('ascii', offset, offset + 4); + const chunkSize = buf.readUInt32LE(offset + 4); + if (chunkId === 'fmt ') { + numChannels = buf.readUInt16LE(offset + 10); + sampleRate = buf.readUInt32LE(offset + 12); + bitsPerSample = buf.readUInt16LE(offset + 22); + } else if (chunkId === 'data') { + dataOffset = offset + 8; + dataLength = chunkSize; + break; + } + offset += 8 + chunkSize; + } + return { dataOffset, dataLength, sampleRate, numChannels, bitsPerSample }; +} + +function buildWav(pcmData, sampleRate, numChannels, bitsPerSample) { + const dataLen = pcmData.length; + const headerLen = 44; + const buf = Buffer.alloc(headerLen + dataLen); + buf.write('RIFF', 0); buf.writeUInt32LE(36 + dataLen, 4); + buf.write('WAVE', 8); buf.write('fmt ', 12); + buf.writeUInt32LE(16, 16); + buf.writeUInt16LE(1, 20); + buf.writeUInt16LE(numChannels, 22); + buf.writeUInt32LE(sampleRate, 24); + buf.writeUInt32LE(sampleRate * numChannels * bitsPerSample / 8, 28); + buf.writeUInt16LE(numChannels * bitsPerSample / 8, 32); + buf.writeUInt16LE(bitsPerSample, 34); + buf.write('data', 36); buf.writeUInt32LE(dataLen, 40); + pcmData.copy(buf, headerLen); + return buf; +} + +const server = app.listen(PORT, () => { + console.log(`✅ Server चालू आहे: http://localhost:${PORT}`); +}); +server.setTimeout(300000); +server.keepAliveTimeout = 300000; +server.headersTimeout = 310000; + +// --------------------------------------------------------------------------- +// WebSocket Proxy: Browser <-> Sarvam Realtime STT (Mode: Translate) +// Streams 16kHz mono PCM to Sarvam and relays English partial/final transcripts +// --------------------------------------------------------------------------- +const wss = new WebSocketServer({ server, path: '/ws/transcribe' }); + +wss.on('connection', (clientWs, req) => { + if (!SARVAM_API_KEY) { + clientWs.send(JSON.stringify({ event: 'error', message: 'SARVAM_API_KEY not configured.' })); + clientWs.close(); + return; + } + + const urlObj = new URL(req.url, 'http://localhost'); + let lang = urlObj.searchParams.get('language_code') || 'auto'; + if (lang === 'unknown') lang = 'auto'; + + const sarvamWsUrl = `wss://api.sarvam.ai/speech-to-text-realtime/ws?language_code=${encodeURIComponent(lang)}&model=saaras:v3-realtime&encoding=linear16&sample_rate=16000&stream_type=balanced&mode=translate`; + + let sarvamWs = null; + try { + sarvamWs = new WebSocket(sarvamWsUrl, { + headers: { 'api-subscription-key': SARVAM_API_KEY } + }); + } catch (e) { + console.error('[WS Proxy] Error connecting to Sarvam WS:', e.message); + clientWs.send(JSON.stringify({ event: 'error', message: e.message })); + clientWs.close(); + return; + } + + sarvamWs.on('open', () => { + console.log(`[WS Proxy] Connected to Sarvam Realtime STT (mode=translate, language=${lang})`); + }); + + sarvamWs.on('message', async (data) => { + if (clientWs.readyState === 1 /* OPEN */) { + try { + const parsed = JSON.parse(data.toString()); + if ((parsed.event === 'transcript.final' || parsed.event === 'transcript.partial') && parsed.text) { + parsed.text = await ensureEnglishText(parsed.text); + } + clientWs.send(JSON.stringify(parsed)); + } catch { + clientWs.send(data.toString()); + } + } + }); + + sarvamWs.on('error', (err) => { + console.error('[WS Proxy] Sarvam WS error:', err.message); + if (clientWs.readyState === 1 /* OPEN */) { + clientWs.send(JSON.stringify({ event: 'error', message: err.message })); + } + }); + + sarvamWs.on('close', (code, reason) => { + if (clientWs.readyState === 1 /* OPEN */) { + clientWs.close(code, reason); + } + }); + + clientWs.on('message', (msg) => { + if (sarvamWs && sarvamWs.readyState === 1 /* OPEN */) { + try { + const d = JSON.parse(msg.toString()); + if (d.event === 'end' || d.event === 'stop') { + sarvamWs.send(JSON.stringify({ event: 'end' })); + } else { + sarvamWs.send(msg.toString()); + } + } catch { + sarvamWs.send(msg); + } + } + }); + + clientWs.on('close', () => { + if (sarvamWs) { + try { sarvamWs.send(JSON.stringify({ event: 'end' })); } catch (e) {} + setTimeout(() => { try { sarvamWs.close(); } catch (e) {} }, 300); + } + }); +}); diff --git a/summarize_conversation.py b/summarize_conversation.py new file mode 100644 index 0000000..44ed42b --- /dev/null +++ b/summarize_conversation.py @@ -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()) diff --git a/test.wav b/test.wav new file mode 100644 index 0000000000000000000000000000000000000000..3f1a79e7e4dab5becbac15d0e10360e6d77ed322 GIT binary patch literal 32044 zcmeIuAqs#%6a>((C)gtxJcnR#!D`Sfh|RWD@aV3=TfCVvOnl3nbALx{<2s#J=~6^A zwa-vT{o6=!>}CJ95FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+ z009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBly zK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAVA<3cmeTf B2iX7s literal 0 HcmV?d00001 diff --git a/test_anti_hallucination.py b/test_anti_hallucination.py new file mode 100644 index 0000000..d5e0bab --- /dev/null +++ b/test_anti_hallucination.py @@ -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) diff --git a/test_batch.js b/test_batch.js new file mode 100644 index 0000000..8d6150b --- /dev/null +++ b/test_batch.js @@ -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(); diff --git a/test_batch.py b/test_batch.py new file mode 100644 index 0000000..2bb98b0 --- /dev/null +++ b/test_batch.py @@ -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()) diff --git a/test_batch_api.js b/test_batch_api.js new file mode 100644 index 0000000..fb52994 --- /dev/null +++ b/test_batch_api.js @@ -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(); diff --git a/test_batch_create.js b/test_batch_create.js new file mode 100644 index 0000000..0507559 --- /dev/null +++ b/test_batch_create.js @@ -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(); diff --git a/test_batch_ep.js b/test_batch_ep.js new file mode 100644 index 0000000..730e250 --- /dev/null +++ b/test_batch_ep.js @@ -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(); diff --git a/test_batch_flow.js b/test_batch_flow.js new file mode 100644 index 0000000..eeb7fbf --- /dev/null +++ b/test_batch_flow.js @@ -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); diff --git a/test_batch_status.js b/test_batch_status.js new file mode 100644 index 0000000..a488496 --- /dev/null +++ b/test_batch_status.js @@ -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(); diff --git a/test_chat_err.py b/test_chat_err.py new file mode 100644 index 0000000..4b0d007 --- /dev/null +++ b/test_chat_err.py @@ -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')) diff --git a/test_chat_sarvam.py b/test_chat_sarvam.py new file mode 100644 index 0000000..375427b --- /dev/null +++ b/test_chat_sarvam.py @@ -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')) diff --git a/test_chat_schema.py b/test_chat_schema.py new file mode 100644 index 0000000..de8ff0f --- /dev/null +++ b/test_chat_schema.py @@ -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)) diff --git a/test_conversations_model.py b/test_conversations_model.py new file mode 100644 index 0000000..20c4002 --- /dev/null +++ b/test_conversations_model.py @@ -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')) diff --git a/test_diarization_pipeline.py b/test_diarization_pipeline.py new file mode 100644 index 0000000..fdf2a53 --- /dev/null +++ b/test_diarization_pipeline.py @@ -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()) diff --git a/test_diarize_llm.js b/test_diarize_llm.js new file mode 100644 index 0000000..caacafc --- /dev/null +++ b/test_diarize_llm.js @@ -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: +Patient: +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(); diff --git a/test_diarize_rules.py b/test_diarize_rules.py new file mode 100644 index 0000000..9fdcc6b --- /dev/null +++ b/test_diarize_rules.py @@ -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) diff --git a/test_line_diarize.py b/test_line_diarize.py new file mode 100644 index 0000000..5a2cff7 --- /dev/null +++ b/test_line_diarize.py @@ -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: +Patient: +Doctor: +... + +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) diff --git a/test_llm.js b/test_llm.js new file mode 100644 index 0000000..95eb3a0 --- /dev/null +++ b/test_llm.js @@ -0,0 +1,53 @@ +const fs = require('fs'); +require('dotenv').config(); + +const SARVAM_API_KEY = process.env.SARVAM_API_KEY; +if (!SARVAM_API_KEY) { + console.error("No API key"); + process.exit(1); +} + +const rawTranscript = `हा बोलसेनकडे हे गाठ आले त्या हे गाठ झाल्यानंतर मला मुलगा राहिला म्हणजे प्रेग्नेंसी राहिली प्रेग्नेंसी झाल्यानंतर एक चार-पाच वर्षांनी पिशवी काढली म्हणजे गाठच झाली होती ती पिशवीवरती अशी हा मग पिशवी काढून टाकली आणि परत आता हे चार-पाच वर्षांनी परत गाठ आली आहे. म्हणजे त्रास असा मला काहीच होत नाही. फक्त त्या फक्त ती गाठ आली आहे. हा. म्हणजे पोट दुखत नाही काही नाही त्रास. आणि हे पहिलं ऑपरेशन 2012 ला झालं. हो सगळ्यात पहिले. त्याच्यानंतर तेव्हा ते त्यांनी ती गाठ काढली. हो. मग पाच वर्षांनीच प्रेग्नेंसी प्रेग्नेंसी राहिली म्हणजे 17 मध्ये. हा. 12 मध्ये. मग काय झाला लगेच गाठी काढली लगेच गाठी काढली हो आणि युट्रस कधी काढलाय? आता 19 मध्ये काढलाय 19 मध्ये काढलाय 18 19 मध्ये काढलाय आता या गाठीचा काही त्रास नाही गाठी वाढते कमी होते फुगते कधी? नाही फक्त म्हणजे त्रास असा काही नाही फक्त असं असं जाण वाटतो बाकी काही नाही असं दुखत नाही संडास लघवीला काही त्रास नाही काही असं नाही रेग्युलर आहे हे जो काम आहे एकदा पाहूया बाकी डायबिटीज ब्लड प्रेशर काही आहे? नाही मॅडम काही नाही. पॉज करायचं ना? भरपूर मोठी एक गाठ आहे पोटामध्ये. बरं. आता ते तुमचं जे युट्रसचं ऑपरेशन झालं होतं त्याचे नोट्स आहेत का की तेव्हा फक्त युट्रस काढले ओवरीज काढल्या? नाही मॅडम ते एवढं आपलं नाही आहे ते रिपोर्ट्स नाही आहे काय रेकॉर्ड नाही आहे. नाही आहे. आपण एक सोनोग्राफी करून घेऊया. प्रत्येक करून हे ओवरी पासून येणारी गाठ वाटते. म्हणजे कशापासून? म्हणजे अंडाशयावरून येणारी गाठ वाटते. पण नुसतं हात लावून पोटाला मी सांगू शकत नाही की ओवरीची की अजून काही आहे. तर एक सोनोग्राफी करून पाहू आणि मग पुढचा निर्णय घेऊ काय करायचं. ठीक आहे मॅडम. ओके चला. आता इथे बेबींगला लगेच होऊन जाईल सोनोग्राफी करून रिपोर्ट घेऊन या दाखवा. चालेल. हे घेऊन जाऊ मॅडम. हो हो दाखवा. पाणी प्यावं लागेल का? पाणी प्यावं लागेल. किती प्यावं लागेल? त्याला माहिती आहे ते करायला सांगते. तुम्हाला गाईड करते. सो दिस लेडी हेड हिस्ट्री ऑफ लूज मोशन्स फॉलोइंग विच शी वेंट टू अ लोकल जीपी एंड डिटेक्टेड टू हेव अ लार्ज अब्डोमिनल मास एंड वॉज रेफर्ड हियर नो इन्वेस्टिगेशन्स वेअर डन ऑन एग्जामिनेशन देअर इज लास्ट 15 बाय एप्रोक्सीमेटली 15 सेंटीमीटर मास कमिंग आउट ऑफ द पेल्विस रीचिंग अबोव्ह द अंबलिकस. प्रोबेबली ऑफ राईट ओव्हेरियन पॅथोलॉजी. एडवाइज अल्ट्रासाउंड. दमन`; + +const DIARIZE_SYSTEM_PROMPT = `You are a highly accurate medical transcript diarization AI. +Your task is to identify the speakers in a raw medical conversation transcript. +There are only two speakers: 'Doctor' and 'Patient'. +RULES: +1. Prefix every spoken segment with EXACTLY 'Doctor:' or 'Patient:'. +2. DO NOT output any reasoning, explanations, or conversational filler.`; + +async function run() { + console.log("Calling Sarvam..."); + try { + const diarizeResp = await fetch('https://api.sarvam.ai/v1/chat/completions', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'api-subscription-key': SARVAM_API_KEY + }, + body: JSON.stringify({ + model: 'sarvam-105b', + temperature: 0.1, + max_tokens: 2000, + messages: [ + { role: 'system', content: DIARIZE_SYSTEM_PROMPT }, + { role: 'user', content: 'हॅलो डॉक्टर मला कालपासून खूप ताप आहे. बरं, आणखी काही त्रास? डोकं दुखतंय का? हो थोडं डोकंही दुखतंय. ठीक आहे, मी गोळ्या देतो.' }, + { role: 'assistant', content: 'Patient: हॅलो डॉक्टर मला कालपासून खूप ताप आहे.\nDoctor: बरं, आणखी काही त्रास? डोकं दुखतंय का?\nPatient: हो थोडं डोकंही दुखतंय.\nDoctor: ठीक आहे, मी गोळ्या देतो.' }, + { role: 'user', content: rawTranscript } + ] + }) + }); + + if (diarizeResp.ok) { + const data = await diarizeResp.json(); + console.log("Success! Output:\n", JSON.stringify(data, null, 2)); + console.log("\n--- Extracted Lines ---\n", extractedLines?.join('\n')); + } else { + console.error("API Error:", diarizeResp.status, await diarizeResp.text()); + } + } catch (e) { + console.error("Fetch Error:", e); + } +} + +run(); diff --git a/test_llm.py b/test_llm.py new file mode 100644 index 0000000..b2bb498 --- /dev/null +++ b/test_llm.py @@ -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() diff --git a/test_llm_call.js b/test_llm_call.js new file mode 100644 index 0000000..6787286 --- /dev/null +++ b/test_llm_call.js @@ -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); diff --git a/test_prompt.js b/test_prompt.js new file mode 100644 index 0000000..fd49969 --- /dev/null +++ b/test_prompt.js @@ -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); diff --git a/test_role_detection.js b/test_role_detection.js new file mode 100644 index 0000000..1830aaf --- /dev/null +++ b/test_role_detection.js @@ -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 + }; + }); +} \ No newline at end of file diff --git a/test_sarvam_quota.py b/test_sarvam_quota.py new file mode 100644 index 0000000..2aeab7f --- /dev/null +++ b/test_sarvam_quota.py @@ -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) diff --git a/test_stt.js b/test_stt.js new file mode 100644 index 0000000..201a1bd --- /dev/null +++ b/test_stt.js @@ -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(); diff --git a/test_stt_diarize.py b/test_stt_diarize.py new file mode 100644 index 0000000..d67ecd4 --- /dev/null +++ b/test_stt_diarize.py @@ -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) diff --git a/test_stt_timestamps.py b/test_stt_timestamps.py new file mode 100644 index 0000000..b7425fa --- /dev/null +++ b/test_stt_timestamps.py @@ -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')) diff --git a/test_summary_extract.py b/test_summary_extract.py new file mode 100644 index 0000000..1339601 --- /dev/null +++ b/test_summary_extract.py @@ -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) diff --git a/test_ts.js b/test_ts.js new file mode 100644 index 0000000..6211884 --- /dev/null +++ b/test_ts.js @@ -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(); diff --git a/test_verbatim_align.py b/test_verbatim_align.py new file mode 100644 index 0000000..9643c83 --- /dev/null +++ b/test_verbatim_align.py @@ -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))