Spaces:
Sleeping
Sleeping
refactored for hugging face hosting
Browse filesFiles changed (5)
- README.md+41-33
- agents/symptom_agent.py+2-67
- app.py+49-103
- requirements.txt-4
- transcription/transcriber.py+10-111
123456789101112131415161718191 unmodified line2122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273# Hospital CopilotAI-powered medical documentation assistant for the **Gemma 4 for Good** hackathon.Listens to doctor-patient consultations and automatically generates SOAP notes, patient summaries, symptom extractions, and Twi (Akan) translations — reducing paperwork and language barriers in Ghanaian healthcare.## Features- **Live transcription** via faster-whisper (runs on CPU)- **Symptom extraction** via Gemma 4 E2B (local, Ollama, CPU)- **SOAP note generation** via Gemma 4 27B (Google AI Studio)- **Patient summary** in plain English- **English ↔ Twi translation** for Ghanaian patients- **Patient records** stored in local SQLite## Setup### 1. Install dependencies1 unmodified linepip install -r requirements.txt```### 2. Install Ollama and pull Gemma 4```bash# Install Ollama: https://ollama.comollama pull gemma4:e2b```### 3. Configure environment```bashcp .env.example .env# Edit .env and add your Google AI Studio API key```Get a free API key at https://aistudio.google.com### 4. Run```bashpython app.py```Open http://localhost:7860 in your browser.## Project Structure```hosptial_copilot/├── app.py # Gradio UI + app logic├── agents/│ ├── symptom_agent.py # Local Gemma 4 (Ollama) symptom extractor│ └── cloud_agents.py # Cloud Gemma 4: SOAP, summary, translation├── transcription/│ └── transcriber.py # faster-whisper live mic transcription├── database/│ └── db.py # SQLite helpers├── requirements.txt└── .env.example```## Architecture```Microphone└─► faster-whisper (local, CPU) → raw transcript├─► Gemma 4 E2B via Ollama → symptom JSON (local CPU)└─► Gemma 4 27B via API → SOAP note + summary + Twi translation└─► SQLite → patient records└─► Gradio UI → doctor dashboard```1234567891011121314151617181920212223242526272829301 unmodified line3233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081---title: MediScribe AIemoji: 🏥colorFrom: bluecolorTo: indigosdk: gradiosdk_version: 4.44.0app_file: app.pypinned: false---# MediScribe AIAI-powered medical documentation assistant for the **Gemma 4 for Good** hackathon.Record a doctor-patient consultation via your browser mic. MediScribe transcribes it, repairs ASR errors, extracts structured clinical data, and generates a professional SOAP note and patient summary — powered by Gemma 4.## Features- **Browser mic recording** — no software install needed- **Transcript repair + speaker labelling** via Gemma 4- **Structured symptom extraction** via Gemma 4 function calling- **RAG-grounded SOAP notes** with ICD-10 codes and WHO drug references- **Multimodal document analysis** — upload lab results or prescriptions- **Patient records** stored in SQLite## Setup (local)### 1. Install dependencies1 unmodified linepip install -r requirements.txt```### 2. Configure environment```bashcp .env.example .env# Add your Google AI Studio API key```Get a free key at https://aistudio.google.com### 3. Run```bashpython app.py```## Hugging Face SpacesSet `GEMINI_API_KEY` as a Space secret in Settings → Variables and secrets.## Project Structure```├── app.py # Gradio UI + app logic├── agents/│ ├── symptom_agent.py # Symptom extractor (Gemma 4 function calling)│ └── cloud_agents.py # SOAP, summary, transcript repair, document analysis├── transcription/│ └── transcriber.py # faster-whisper batch transcription├── rag/│ ├── retriever.py # ChromaDB + sentence-transformers RAG│ └── data/ # ICD-10 codes + WHO essential medicines├── database/│ └── db.py # SQLite helpers└── requirements.txt```## Architecture```Browser Mic└─► faster-whisper (CPU) → raw transcript└─► Gemma 4 26B (API) → cleaned transcript + speaker labels├─► Gemma 4 function calling → structured symptom JSON├─► ChromaDB RAG → ICD-10 codes + drug dosages└─► Gemma 4 reasoning mode → SOAP note + patient summary└─► SQLite → patient records```
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081import osimport jsonimport ollamafrom agents.cloud_agents import extract_symptoms_cloudOLLAMA_MODEL = os.getenv("OLLAMA_MODEL", "gemma4:e2b")SYMPTOM_PROMPT = """You are a medical symptom extraction AI. Extract all clinical information from this transcript into valid JSON only.Return ONLY valid JSON — no markdown, no explanation, no code fences:{{"chief_complaint": "main reason for visit","symptoms": ["list", "of", "symptoms"],"duration": "how long symptoms have been present","severity": "mild | moderate | severe","associated_symptoms": ["other symptoms"],"medications_mentioned": ["drugs or treatments mentioned"],"allergies": ["any allergies mentioned"],"vitals_mentioned": {{"temperature": null,"blood_pressure": null,"pulse": null,"weight": null}},"relevant_history": "past medical history","follow_up_actions": ["follow-up steps, tests, referrals"]}}Transcript:{transcript}"""def _extract_via_ollama(transcript: str) -> dict:"""Primary: local Gemma 4 E2B via Ollama."""response = ollama.chat(model=OLLAMA_MODEL,messages=[{"role": "user", "content": SYMPTOM_PROMPT.format(transcript=transcript)}],options={"temperature": 0.1},)raw = response["message"]["content"].strip()# strip markdown fences if presentif "```" in raw:parts = raw.split("```")raw = parts[1] if len(parts) > 1 else parts[0]if raw.startswith("json"):raw = raw[4:]raw = raw.strip()result = json.loads(raw)# must be a dict with at least chief_complaint to be validif not isinstance(result, dict) or "chief_complaint" not in result:raise ValueError("Invalid symptom structure from Ollama")return resultdef extract_symptoms(transcript: str) -> dict:"""Extract structured symptoms from transcript.Tries local Gemma 4 E2B (Ollama) first — fast, private.Falls back to cloud Gemma 4 function calling on any failure — guaranteed valid schema."""if not transcript.strip():return {}try:result = _extract_via_ollama(transcript)print("[Symptoms] Extracted via local Gemma 4 E2B (Ollama)")return resultexcept Exception as e:print(f"[Symptoms] Ollama failed ({e}), falling back to cloud function calling...")try:result = extract_symptoms_cloud(transcript)print("[Symptoms] Extracted via cloud Gemma 4 function calling")return resultexcept Exception as e:print(f"[Symptoms] Cloud fallback also failed: {e}")return {"error": str(e)}12345678910111213141516from agents.cloud_agents import extract_symptoms_clouddef extract_symptoms(transcript: str) -> dict:"""Extract structured symptoms via Gemma 4 function calling."""if not transcript.strip():return {}try:result = extract_symptoms_cloud(transcript)print("[Symptoms] Extracted via cloud Gemma 4 function calling")return resultexcept Exception as e:print(f"[Symptoms] Extraction failed: {e}")return {"error": str(e)}
123414 unmodified lines1920212223242511 unmodified lines3738394041424344454647486 unmodified lines555657585960616263646528 unmodified lines94959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315413 unmodified lines1681691701711721731741751761771781791801811821831841851861877 unmodified lines19519619719819920020120220320420520654 unmodified lines26126226326426526626726826927027127211 unmodified lines2842852862872882892902912922931 unmodified line29529629729829930030130230330430530630730830931031131231331431527 unmodified lines34334434534634734834935035135235335435535635735835936036136217 unmodified lines38038138238338438538620 unmodified lines40740840941041141241341441541641741841942034 unmodified lines4554564574584594604614624634644654664674684694704714 unmodified lines476477478479480481482483484485486487488489490import threadingfrom dotenv import load_dotenvload_dotenv()14 unmodified linesget_note_for_session,get_symptoms_for_session,)from transcription.transcriber import LiveTranscriberfrom agents.symptom_agent import extract_symptoms, format_symptoms_for_displayfrom agents.cloud_agents import generate_soap_note, generate_patient_summary, clean_and_label_transcript, analyze_medical_documentfrom rag.retriever import (11 unmodified lines# ── State ─────────────────────────────────────────────────────────────────────_transcriber: LiveTranscriber | None = None_transcript_parts: list[str] = []_labelled_transcript: str = ""_document_analysis: str = ""_current_session_id: int | None = None_transcript_lock = threading.Lock()# ── Helpers ───────────────────────────────────────────────────────────────────6 unmodified linesreturn int(choice.split("—")[0].strip())def _full_transcript() -> str:with _transcript_lock:return " ".join(_transcript_parts)def _format_icd_panel(codes: list[dict]) -> str:if not codes:return "_No ICD-10 suggestions._"28 unmodified linesreturn gr.update(choices=choices, value=new_val), f"Patient '{name}' registered (ID {pid})."def start_consultation(patient_choice, doctor_name):global _transcriber, _transcript_parts, _current_session_idif not patient_choice:return "No patient selected.", "", gr.update(interactive=False), gr.update(interactive=True)pid = _parse_patient_choice(patient_choice)_current_session_id = create_session(pid, doctor_name or "Doctor")with _transcript_lock:_transcript_parts.clear()global _labelled_transcript, _document_analysis_labelled_transcript = ""_document_analysis = ""def on_text(text):with _transcript_lock:_transcript_parts.append(text)_transcriber = LiveTranscriber(on_text=on_text)_transcriber.start()return ("Recording... speak clearly.","",gr.update(interactive=True),gr.update(interactive=False),)def poll_transcript():return _full_transcript()def stop_consultation():global _transcriber, _labelled_transcriptif _transcriber:_transcriber.stop()_transcriber = Noneraw = _full_transcript()if not raw:return "No audio captured.", "", gr.update(interactive=False), gr.update(interactive=True)if _current_session_id:update_transcript(_current_session_id, raw)_labelled_transcript = clean_and_label_transcript(raw)return ("Consultation ended. Transcript cleaned ✓ Click 'Generate Notes' to proceed.",_labelled_transcript,gr.update(interactive=False),gr.update(interactive=True),)def upload_document(file):13 unmodified linesdef generate_notes():"""RAG retrieval → cloud agents → save to DB."""# Use labelled transcript if available, fall back to rawtranscript = _labelled_transcript or _full_transcript()if not transcript:return "No transcript available.", "No transcript available.", "_No symptoms._", "_No ICD codes._", "_No drug info._", "", ""# 1. Extract symptoms locally (Gemma 4 E2B via Ollama)symptoms = extract_symptoms(transcript)symptoms_md = format_symptoms_for_display(symptoms)# 2. RAG retrievalchief = symptoms.get("chief_complaint", "")sym_list = symptoms.get("symptoms", [])meds_list = symptoms.get("medications_mentioned", [])rag_query = f"{chief} {' '.join(sym_list)}".strip() or transcript[:300]icd_codes = retrieve_icd_codes(rag_query, n=5)drug_info = retrieve_drug_info(meds_list, n=3) if meds_list else []7 unmodified lines# 3. Cloud agentstry:soap = generate_soap_note(transcript, rag_context=rag_context)except Exception as e:soap = f"_SOAP note generation failed: {e}_"try:summary_en = generate_patient_summary(transcript)except Exception as e:summary_en = f"_Summary generation failed: {e}_"54 unmodified lines#header-banner h1 { margin: 0; font-size: 1.9rem; font-weight: 700; letter-spacing: -0.5px; }#header-banner p { margin: 5px 0 0; opacity: 0.85; font-size: 0.95rem; }/* Fix markdown panels — transparent so they inherit theme bg */.gr-markdown, .svelte-1ed2p3z, [data-testid="markdown"] {background: transparent !important;}/* Note cards — rendered SOAP/summary display */.note-card {border: 1px solid #2d4a6e;border-radius: 8px;11 unmodified lines.note-card p { margin: 6px 0; }.note-card ul, .note-card ol { padding-left: 20px; margin: 4px 0; }/* Status bar */.status-bar p { font-weight: 600; color: #4a9eff; font-size: 1rem; }/* RAG accordion open panel */.rag-content {border-left: 3px solid #1a6eb5;padding: 10px 14px;1 unmodified linefont-size: 0.9rem;}/* Tighten up accordion headers */.gr-accordion .label-wrap { font-weight: 600 !important; }/* Recording pulse indicator */@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:0.4} }.recording p { animation: pulse 1.4s ease-in-out infinite; color: #ff4444 !important; font-weight: 700; }"""# ── Layout ────────────────────────────────────────────────────────────────────with gr.Blocks(title="Hospital Copilot") as demo:gr.HTML("""<div id="header-banner"><h1>🏥 Hospital Copilot</h1><p>AI-powered medical documentation · Gemma 4 · RAG-grounded · Ghana</p></div>""")27 unmodified lines# Right column — consultationwith gr.Column(scale=3):status_txt = gr.Markdown("_Ready. Select a patient and click Start._", elem_classes=["status-bar"])with gr.Row():start_btn = gr.Button("▶ Start Consultation", variant="primary", scale=1)stop_btn = gr.Button("⏹ End Consultation", variant="stop", scale=1, interactive=False)live_transcript = gr.Textbox(label="Transcript (cleaned & speaker-labelled after consultation ends)",lines=8, max_lines=16,interactive=False,placeholder="Transcript streams here as you speak. After you click End Consultation, Gemma 4 cleans and labels it automatically.",)timer = gr.Timer(value=2)timer.tick(poll_transcript, outputs=live_transcript)with gr.Accordion("🩺 Extracted Symptoms", open=False):symptoms_live = gr.Markdown("_Will populate after Generate Notes._")17 unmodified linesgenerate_btn = gr.Button("⚡ Generate Notes from Transcript", variant="primary", size="lg")# RAG panels — inside accordions so they don't show as white boxeswith gr.Row():with gr.Accordion("🏷️ ICD-10 Suggestions", open=True):icd_panel = gr.Markdown("_Click Generate Notes to see suggestions._")20 unmodified lineswith gr.Accordion("✏️ Edit Summary", open=False):summary_edit = gr.Textbox(lines=10, interactive=True, show_label=False)start_btn.click(start_consultation,inputs=[patient_dd, doctor_name],outputs=[status_txt, live_transcript, stop_btn, start_btn],)stop_btn.click(stop_consultation,outputs=[status_txt, live_transcript, stop_btn, start_btn],)generate_btn.click(generate_notes,34 unmodified lines# ── Tab 3: About ──────────────────────────────────────────────────with gr.Tab("ℹ️ About"):gr.Markdown("""## Hospital Copilot — Gemma 4 for Good**Reducing doctor burnout. Improving care quality. Built for Ghana.**### How it works1. **Live Transcription** — faster-whisper converts speech to text in real time on CPU2. **Symptom Extraction** — Gemma 4 E2B (local, Ollama) extracts structured clinical JSON3. **RAG Retrieval** — sentence-transformers + ChromaDB matches ICD-10 codes and drug dosages4. **SOAP Note Generation** — Gemma 4 26B (cloud) writes a grounded, accurate medical note5. **Patient Summary** — plain-language summary the patient can take home6. **Structured Records** — everything saved to local SQLite### RAG Knowledge Base| Collection | Entries | Source |4 unmodified lines### Technology Stack| Component | Model | Where ||---|---|---|| Speech-to-Text | faster-whisper (base) | Local CPU || Symptom Extraction | Gemma 4 E2B (Q4_K_M) | Local CPU via Ollama || Embeddings | all-MiniLM-L6-v2 | Local CPU || Vector Store | ChromaDB | Local disk || SOAP / Summary | Gemma 4 26B-IT | Google AI Studio API || Storage | SQLite | Local || UI | Gradio | Desktop |""")if __name__ == "__main__":demo.launch(server_name="0.0.0.0", server_port=7860, share=False, css=CSS)12314 unmodified lines1819202122232411 unmodified lines3637383940414243446 unmodified lines51525354555628 unmodified lines85868788899091929394959697989910010110210310410510610710810911011113 unmodified lines1251261271281291301311321331341351361371381391401411427 unmodified lines15015115215315415515615715815916016154 unmodified lines21621721821922022122222322422511 unmodified lines2372382392402412422432441 unmodified line24624724824925025125225325425525625725825926026127 unmodified lines28929029129229329429529629729829930030130230330430530630730830931031131217 unmodified lines33033133233333433520 unmodified lines35635735835936036136236336436534 unmodified lines4004014024034044054064074084094104114124134144154164174 unmodified lines422423424425426427428429430431432433434435436from dotenv import load_dotenvload_dotenv()14 unmodified linesget_note_for_session,get_symptoms_for_session,)from transcription.transcriber import transcribe_filefrom agents.symptom_agent import extract_symptoms, format_symptoms_for_displayfrom agents.cloud_agents import generate_soap_note, generate_patient_summary, clean_and_label_transcript, analyze_medical_documentfrom rag.retriever import (11 unmodified lines# ── State ─────────────────────────────────────────────────────────────────────_labelled_transcript: str = ""_document_analysis: str = ""_current_session_id: int | None = None# ── Helpers ───────────────────────────────────────────────────────────────────6 unmodified linesreturn int(choice.split("—")[0].strip())def _format_icd_panel(codes: list[dict]) -> str:if not codes:return "_No ICD-10 suggestions._"28 unmodified linesreturn gr.update(choices=choices, value=new_val), f"Patient '{name}' registered (ID {pid})."def transcribe_recording(patient_choice, doctor_name, audio_path):"""Called when the mic recording stops. Transcribes and cleans the audio."""global _current_session_id, _labelled_transcriptif not patient_choice:return "No patient selected.", ""if audio_path is None:return "No audio recorded.", ""pid = _parse_patient_choice(patient_choice)_current_session_id = create_session(pid, doctor_name or "Doctor")_labelled_transcript = ""raw = transcribe_file(audio_path)if not raw:return "No speech detected in the recording.", ""update_transcript(_current_session_id, raw)_labelled_transcript = clean_and_label_transcript(raw)return "Transcript ready ✓ Click 'Generate Notes' to proceed.", _labelled_transcriptdef upload_document(file):13 unmodified linesdef generate_notes():"""RAG retrieval → cloud agents → save to DB."""if not _labelled_transcript:return "No transcript available.", "No transcript available.", "_No symptoms._", "_No ICD codes._", "_No drug info._", "", ""# 1. Extract symptomssymptoms = extract_symptoms(_labelled_transcript)symptoms_md = format_symptoms_for_display(symptoms)# 2. RAG retrievalchief = symptoms.get("chief_complaint", "")sym_list = symptoms.get("symptoms", [])meds_list = symptoms.get("medications_mentioned", [])rag_query = f"{chief} {' '.join(sym_list)}".strip() or _labelled_transcript[:300]icd_codes = retrieve_icd_codes(rag_query, n=5)drug_info = retrieve_drug_info(meds_list, n=3) if meds_list else []7 unmodified lines# 3. Cloud agentstry:soap = generate_soap_note(_labelled_transcript, rag_context=rag_context)except Exception as e:soap = f"_SOAP note generation failed: {e}_"try:summary_en = generate_patient_summary(_labelled_transcript)except Exception as e:summary_en = f"_Summary generation failed: {e}_"54 unmodified lines#header-banner h1 { margin: 0; font-size: 1.9rem; font-weight: 700; letter-spacing: -0.5px; }#header-banner p { margin: 5px 0 0; opacity: 0.85; font-size: 0.95rem; }.gr-markdown, .svelte-1ed2p3z, [data-testid="markdown"] {background: transparent !important;}.note-card {border: 1px solid #2d4a6e;border-radius: 8px;11 unmodified lines.note-card p { margin: 6px 0; }.note-card ul, .note-card ol { padding-left: 20px; margin: 4px 0; }.status-bar p { font-weight: 600; color: #4a9eff; font-size: 1rem; }.rag-content {border-left: 3px solid #1a6eb5;padding: 10px 14px;1 unmodified linefont-size: 0.9rem;}.gr-accordion .label-wrap { font-weight: 600 !important; }"""# ── Layout ────────────────────────────────────────────────────────────────────with gr.Blocks(title="Hospital Copilot", css=CSS) as demo:gr.HTML("""<div id="header-banner"><h1>🏥 MediScribe AI</h1><p>AI-powered medical documentation · Gemma 4 · RAG-grounded · Ghana</p></div>""")27 unmodified lines# Right column — consultationwith gr.Column(scale=3):status_txt = gr.Markdown("_Ready. Select a patient, then record the consultation below._", elem_classes=["status-bar"])gr.Markdown("**Record the consultation** — click the mic to start, click stop when done. ""The transcript will appear automatically.")mic_input = gr.Audio(sources=["microphone"],type="filepath",label="Consultation Recording",)live_transcript = gr.Textbox(label="Transcript (cleaned & speaker-labelled)",lines=8, max_lines=16,interactive=False,placeholder="Record the consultation above. The transcript will appear here after you stop recording.",)with gr.Accordion("🩺 Extracted Symptoms", open=False):symptoms_live = gr.Markdown("_Will populate after Generate Notes._")17 unmodified linesgenerate_btn = gr.Button("⚡ Generate Notes from Transcript", variant="primary", size="lg")with gr.Row():with gr.Accordion("🏷️ ICD-10 Suggestions", open=True):icd_panel = gr.Markdown("_Click Generate Notes to see suggestions._")20 unmodified lineswith gr.Accordion("✏️ Edit Summary", open=False):summary_edit = gr.Textbox(lines=10, interactive=True, show_label=False)mic_input.stop_recording(transcribe_recording,inputs=[patient_dd, doctor_name, mic_input],outputs=[status_txt, live_transcript],)generate_btn.click(generate_notes,34 unmodified lines# ── Tab 3: About ──────────────────────────────────────────────────with gr.Tab("ℹ️ About"):gr.Markdown("""## MediScribe AI — Gemma 4 for Good**Reducing doctor burnout. Improving care quality. Built for Ghana.**### How it works1. **Live Transcription** — Record the consultation via your browser mic. faster-whisper transcribes on CPU.2. **Transcript Repair** — Gemma 4 fixes ASR errors and labels each turn as Doctor or Patient.3. **Symptom Extraction** — Gemma 4 function calling extracts structured clinical JSON.4. **RAG Retrieval** — sentence-transformers + ChromaDB matches ICD-10 codes and drug dosages.5. **SOAP Note Generation** — Gemma 4 (reasoning mode) writes a grounded, accurate medical note.6. **Patient Summary** — plain-language summary the patient can take home.7. **Structured Records** — everything saved to local SQLite.### RAG Knowledge Base| Collection | Entries | Source |4 unmodified lines### Technology Stack| Component | Model | Where ||---|---|---|| Speech-to-Text | faster-whisper (small) | CPU || Symptom Extraction | Gemma 4 26B — function calling | Google AI Studio API || Embeddings | all-MiniLM-L6-v2 | CPU || Vector Store | ChromaDB | Local disk || SOAP / Summary | Gemma 4 26B-IT — reasoning mode | Google AI Studio API || Storage | SQLite | Local || UI | Gradio | Browser |""")if __name__ == "__main__":demo.launch()
1234567891011gradio>=4.44.0faster-whisper>=1.0.0ollama>=0.3.0google-genai>=1.0.0sounddevice>=0.4.6numpy>=1.26.0scipy>=1.13.0python-dotenv>=1.0.0fpdf2>=2.7.9chromadb>=0.5.0sentence-transformers>=3.0.01234567gradio>=4.44.0faster-whisper>=1.0.0google-genai>=1.0.0numpy>=1.26.0python-dotenv>=1.0.0chromadb>=0.5.0sentence-transformers>=3.0.0
123456789101112131415165 unmodified lines222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125import osimport queueimport tempfileimport threadingimport waveimport numpy as npimport sounddevice as sdfrom faster_whisper import WhisperModelSAMPLE_RATE = 16000BLOCK_SECONDS = 3CHANNELS = 1_model: WhisperModel | None = None5 unmodified linesreturn _modelclass LiveTranscriber:"""Streams microphone audio, transcribes in real time, and saves the fullsession to a WAV file for post-hoc speaker diarization."""def __init__(self, on_text):self.on_text = on_textself._audio_q: queue.Queue = queue.Queue()self._stop_event = threading.Event()self._thread: threading.Thread | None = Noneself._stream: sd.InputStream | None = None# accumulate all raw audio for diarizationself._all_audio: list[np.ndarray] = []self._audio_lock = threading.Lock()# path to saved WAV after stop()self.wav_path: str | None = Nonedef _audio_callback(self, indata, frames, time_info, status):chunk = indata.copy()self._audio_q.put(chunk)with self._audio_lock:self._all_audio.append(chunk.flatten())def _process_loop(self):model = _load_model()buffer = np.empty((0,), dtype=np.float32)chunk_size = SAMPLE_RATE * BLOCK_SECONDSwhile not self._stop_event.is_set():try:chunk = self._audio_q.get(timeout=0.5)buffer = np.concatenate([buffer, chunk.flatten()])except queue.Empty:continueif len(buffer) >= chunk_size:audio_chunk = buffer[:chunk_size].astype(np.float32)buffer = buffer[chunk_size:]segments, _ = model.transcribe(audio_chunk,language="en",vad_filter=True,vad_parameters={"min_silence_duration_ms": 300},)text = " ".join(s.text for s in segments).strip()if text:self.on_text(text)# flush remaining audioif len(buffer) > SAMPLE_RATE:segments, _ = _load_model().transcribe(buffer.astype(np.float32), language="en", vad_filter=True)text = " ".join(s.text for s in segments).strip()if text:self.on_text(text)def start(self):self._stop_event.clear()self._all_audio.clear()self._stream = sd.InputStream(samplerate=SAMPLE_RATE,channels=CHANNELS,dtype="float32",blocksize=SAMPLE_RATE,callback=self._audio_callback,)self._stream.start()self._thread = threading.Thread(target=self._process_loop, daemon=True)self._thread.start()def stop(self) -> str | None:"""Stop recording and save full audio to a WAV file. Returns the WAV path."""self._stop_event.set()if self._stream:self._stream.stop()self._stream.close()if self._thread:self._thread.join(timeout=5)with self._audio_lock:all_audio = list(self._all_audio)if not all_audio:return Nonefull_audio = np.concatenate(all_audio).astype(np.float32)pcm = (full_audio * 32767).astype(np.int16)tmp = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)with wave.open(tmp.name, "wb") as wf:wf.setnchannels(CHANNELS)wf.setsampwidth(2)wf.setframerate(SAMPLE_RATE)wf.writeframes(pcm.tobytes())self.wav_path = tmp.namereturn tmp.name1234565 unmodified lines12131415161718192021222324import osfrom faster_whisper import WhisperModel_model: WhisperModel | None = None5 unmodified linesreturn _modeldef transcribe_file(file_path: str) -> str:"""Transcribe an audio file and return the full text."""model = _load_model()segments, _ = model.transcribe(file_path,language="en",vad_filter=True,vad_parameters={"min_silence_duration_ms": 300},)return " ".join(s.text for s in segments).strip()
README.md+41-33
agents/symptom_agent.py+2-67
app.py+49-103
requirements.txt-4
transcription/transcriber.py+10-111