Initial commit: Doctor-Patient clinical transcription and structured summary pipeline
This commit is contained in:
+86
@@ -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()
|
||||
Reference in New Issue
Block a user