Initial commit - Diabetic Dost
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
"""
|
||||
Offline STT Training & Inference Package
|
||||
Includes:
|
||||
- NeMo / PyTorch compatible dataset collator
|
||||
- CTC/Conformer local offline trainer with AMP, CUDA/CPU detection, and checkpointing
|
||||
- Evaluation & inference utilities
|
||||
"""
|
||||
@@ -0,0 +1,232 @@
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import List, Dict, Any, Tuple, Optional
|
||||
import numpy as np
|
||||
|
||||
# Initialize DLL directories for PyTorch on Windows
|
||||
lib_dir = Path(sys.prefix) / "site-packages" / "torch" / "lib"
|
||||
user_lib_dir = Path(os.getenv("APPDATA", "")) / "Python" / f"Python{sys.version_info.major}{sys.version_info.minor}" / "site-packages" / "torch" / "lib"
|
||||
for p in [str(lib_dir), str(user_lib_dir), sys.prefix, os.path.dirname(sys.executable)]:
|
||||
if os.path.exists(p) and hasattr(os, "add_dll_directory"):
|
||||
try:
|
||||
os.add_dll_directory(p)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import torch
|
||||
from torch.utils.data import Dataset
|
||||
|
||||
from audio_pipeline.preprocess import read_audio_file, resample_audio, convert_to_mono, normalize_audio
|
||||
|
||||
|
||||
# Character Vocabulary for Multilingual Indic (Devanagari) + English + Numerals + Punctuation
|
||||
SPECIAL_TOKENS = ["<blank>", "<unk>", "<space>"]
|
||||
DEFAULT_CHARS = (
|
||||
" abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
"0123456789"
|
||||
".,-/:;!?'\""
|
||||
# Devanagari range (Marathi & Hindi)
|
||||
"ऀँंःऄअआइईउऊऋऌऍऎएऐऑऒओऔकखगघङचछजझञटठडढणतथदधनऩपफबभमयरऱलळऴवशषसहऺऻ़ऽािीुूृॄॅॆेैॉॊोौ्"
|
||||
"०१२३४५६७८९"
|
||||
)
|
||||
|
||||
class Vocabulary:
|
||||
"""Character-level vocabulary for CTC ASR."""
|
||||
def __init__(self, char_set: Optional[str] = None):
|
||||
chars = list(char_set or DEFAULT_CHARS)
|
||||
# Deduplicate while preserving order
|
||||
seen = set()
|
||||
unique_chars = []
|
||||
for c in chars:
|
||||
if c not in seen:
|
||||
seen.add(c)
|
||||
unique_chars.append(c)
|
||||
|
||||
self.char2idx: Dict[str, int] = {
|
||||
"<blank>": 0,
|
||||
"<unk>": 1,
|
||||
"<space>": 2,
|
||||
}
|
||||
self.idx2char: Dict[int, str] = {
|
||||
0: "<blank>",
|
||||
1: "<unk>",
|
||||
2: " ",
|
||||
}
|
||||
|
||||
current_idx = 3
|
||||
for c in unique_chars:
|
||||
if c == " ":
|
||||
continue
|
||||
if c not in self.char2idx:
|
||||
self.char2idx[c] = current_idx
|
||||
self.idx2char[current_idx] = c
|
||||
current_idx += 1
|
||||
|
||||
def encode(self, text: str) -> List[int]:
|
||||
ids = []
|
||||
for c in text:
|
||||
if c == " ":
|
||||
ids.append(self.char2idx["<space>"])
|
||||
elif c in self.char2idx:
|
||||
ids.append(self.char2idx[c])
|
||||
else:
|
||||
ids.append(self.char2idx["<unk>"])
|
||||
return ids
|
||||
|
||||
def decode(self, ids: List[int]) -> str:
|
||||
res = []
|
||||
for i in ids:
|
||||
if i == self.char2idx["<blank>"]:
|
||||
continue
|
||||
elif i == self.char2idx["<space>"]:
|
||||
res.append(" ")
|
||||
elif i in self.idx2char:
|
||||
res.append(self.idx2char[i])
|
||||
return "".join(res)
|
||||
|
||||
def decode_ctc(self, ids: List[int]) -> str:
|
||||
"""Greedy CTC collapse: remove consecutive duplicates and blanks."""
|
||||
collapsed = []
|
||||
prev = None
|
||||
for idx in ids:
|
||||
if idx != prev:
|
||||
if idx != self.char2idx["<blank>"]:
|
||||
collapsed.append(idx)
|
||||
prev = idx
|
||||
return self.decode(collapsed)
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self.char2idx)
|
||||
|
||||
|
||||
class ASRDataset(Dataset):
|
||||
"""
|
||||
PyTorch Dataset loading NeMo-style JSONL manifests.
|
||||
Extracts 80-dim log Mel-Filterbank spectrogram features.
|
||||
"""
|
||||
def __init__(
|
||||
self,
|
||||
manifest_path: str,
|
||||
vocab: Vocabulary,
|
||||
sample_rate: int = 16000,
|
||||
n_mels: int = 80,
|
||||
max_duration: float = 30.0
|
||||
):
|
||||
self.manifest_path = manifest_path
|
||||
self.vocab = vocab
|
||||
self.sample_rate = sample_rate
|
||||
self.n_mels = n_mels
|
||||
self.max_duration = max_duration
|
||||
self.samples: List[Dict[str, Any]] = []
|
||||
|
||||
if not os.path.exists(manifest_path):
|
||||
return
|
||||
|
||||
with open(manifest_path, "r", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
item = json.loads(line)
|
||||
if "audio_filepath" in item and ("text" in item or "raw_text" in item):
|
||||
self.samples.append(item)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self.samples)
|
||||
|
||||
def compute_features(self, audio: np.ndarray) -> Any:
|
||||
"""Compute Log-Mel Spectrogram features (Time, Features)."""
|
||||
try:
|
||||
import importlib
|
||||
T = importlib.import_module("torchaudio.transforms")
|
||||
wav_tensor = torch.from_numpy(audio).float().unsqueeze(0) # (1, T)
|
||||
mel_transform = T.MelSpectrogram(
|
||||
sample_rate=self.sample_rate,
|
||||
n_fft=400,
|
||||
win_length=400,
|
||||
hop_length=160,
|
||||
n_mels=self.n_mels
|
||||
)
|
||||
mel = mel_transform(wav_tensor) # (1, n_mels, frames)
|
||||
log_mel = torch.log(mel + 1e-6).squeeze(0).transpose(0, 1) # (frames, n_mels)
|
||||
return log_mel
|
||||
except Exception:
|
||||
# Numpy / Scipy FFT fallback
|
||||
from scipy import signal
|
||||
f, t, Sxx = signal.spectrogram(audio, fs=self.sample_rate, nperseg=400, noverlap=240, nfft=512)
|
||||
log_spec = np.log(Sxx[:self.n_mels, :] + 1e-6).T # (frames, n_mels)
|
||||
return torch.from_numpy(log_spec).float()
|
||||
|
||||
def __getitem__(self, idx: int) -> Dict[str, Any]:
|
||||
item = self.samples[idx]
|
||||
audio_path = item["audio_filepath"]
|
||||
text = item.get("text") or item.get("raw_text", "")
|
||||
|
||||
# Read and preprocess audio
|
||||
try:
|
||||
data, orig_sr = read_audio_file(Path(audio_path))
|
||||
data = convert_to_mono(data)
|
||||
if orig_sr != self.sample_rate:
|
||||
data = resample_audio(data, orig_sr, self.sample_rate)
|
||||
data = normalize_audio(data, 0.95)
|
||||
except Exception as e:
|
||||
# Corrupted fallback to silence
|
||||
data = np.zeros(self.sample_rate, dtype=np.float32)
|
||||
|
||||
features = self.compute_features(data)
|
||||
token_ids = torch.tensor(self.vocab.encode(text), dtype=torch.long)
|
||||
|
||||
return {
|
||||
"features": features, # (frames, n_mels)
|
||||
"targets": token_ids, # (target_len,)
|
||||
"feature_length": features.size(0),
|
||||
"target_length": token_ids.size(0),
|
||||
"text": text,
|
||||
"audio_filepath": audio_path,
|
||||
}
|
||||
|
||||
|
||||
def asr_collate_fn(batch: List[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
"""Collate function with dynamic padding for variable audio and text lengths."""
|
||||
feature_lengths = [b["feature_length"] for b in batch]
|
||||
target_lengths = [b["target_length"] for b in batch]
|
||||
|
||||
max_feat_len = max(feature_lengths)
|
||||
n_mels = batch[0]["features"].size(1)
|
||||
|
||||
batch_size = len(batch)
|
||||
padded_features = torch.zeros(batch_size, max_feat_len, n_mels, dtype=torch.float32)
|
||||
|
||||
all_targets = []
|
||||
texts = []
|
||||
filepaths = []
|
||||
|
||||
for i, item in enumerate(batch):
|
||||
f_len = item["feature_length"]
|
||||
padded_features[i, :f_len, :] = item["features"]
|
||||
all_targets.append(item["targets"])
|
||||
texts.append(item["text"])
|
||||
filepaths.append(item["audio_filepath"])
|
||||
|
||||
# Concatenate targets for CTC Loss or pad
|
||||
max_target_len = max(max(target_lengths), 1)
|
||||
padded_targets = torch.zeros(batch_size, max_target_len, dtype=torch.long)
|
||||
for i, t in enumerate(all_targets):
|
||||
if len(t) > 0:
|
||||
padded_targets[i, :len(t)] = t
|
||||
|
||||
return {
|
||||
"features": padded_features, # (B, T, n_mels)
|
||||
"feature_lengths": torch.tensor(feature_lengths, dtype=torch.long), # (B,)
|
||||
"targets": padded_targets, # (B, L)
|
||||
"target_lengths": torch.tensor(target_lengths, dtype=torch.long), # (B,)
|
||||
"texts": texts,
|
||||
"audio_filepaths": filepaths,
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import os
|
||||
import sys
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any, Optional
|
||||
import numpy as np
|
||||
|
||||
# Initialize DLL directories for PyTorch on Windows
|
||||
lib_dir = Path(sys.prefix) / "site-packages" / "torch" / "lib"
|
||||
user_lib_dir = Path(os.getenv("APPDATA", "")) / "Python" / f"Python{sys.version_info.major}{sys.version_info.minor}" / "site-packages" / "torch" / "lib"
|
||||
for p in [str(lib_dir), str(user_lib_dir), sys.prefix, os.path.dirname(sys.executable)]:
|
||||
if os.path.exists(p) and hasattr(os, "add_dll_directory"):
|
||||
try:
|
||||
os.add_dll_directory(p)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import torch
|
||||
|
||||
from training.dataset import Vocabulary
|
||||
from training.train import DoctorPatientASRModel, load_config
|
||||
from audio_pipeline.preprocess import read_audio_file, convert_to_mono, resample_audio, normalize_audio
|
||||
from audio_pipeline.normalizer import clean_medical_transcript
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
|
||||
logger = logging.getLogger("stt_infer")
|
||||
|
||||
|
||||
class OfflineSTTInference:
|
||||
"""
|
||||
Offline STT Inference engine using trained checkpoint.
|
||||
"""
|
||||
def __init__(self, checkpoint_path: str = "outputs/checkpoints/best_model.pt", device: Optional[str] = None):
|
||||
self.device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))
|
||||
self.checkpoint_path = checkpoint_path
|
||||
|
||||
if not os.path.exists(checkpoint_path):
|
||||
raise FileNotFoundError(f"Model checkpoint not found at: {checkpoint_path}")
|
||||
|
||||
logger.info(f"Loading checkpoint from {checkpoint_path} onto {self.device}")
|
||||
checkpoint = torch.load(checkpoint_path, map_location=self.device)
|
||||
|
||||
# Load vocab
|
||||
self.vocab = Vocabulary()
|
||||
if "vocab" in checkpoint:
|
||||
self.vocab.char2idx = checkpoint["vocab"]
|
||||
self.vocab.idx2char = {v: k for k, v in checkpoint["vocab"].items()}
|
||||
|
||||
self.model = DoctorPatientASRModel(
|
||||
n_mels=80,
|
||||
encoder_dim=256,
|
||||
num_layers=4,
|
||||
vocab_size=len(self.vocab)
|
||||
).to(self.device)
|
||||
|
||||
self.model.load_state_dict(checkpoint["model_state_dict"])
|
||||
self.model.eval()
|
||||
|
||||
def compute_features(self, audio: np.ndarray, sample_rate: int = 16000) -> Any:
|
||||
try:
|
||||
import torchaudio.transforms as T
|
||||
wav_tensor = torch.from_numpy(audio).float().unsqueeze(0)
|
||||
mel_transform = T.MelSpectrogram(
|
||||
sample_rate=sample_rate,
|
||||
n_fft=400,
|
||||
win_length=400,
|
||||
hop_length=160,
|
||||
n_mels=80
|
||||
)
|
||||
mel = mel_transform(wav_tensor)
|
||||
log_mel = torch.log(mel + 1e-6).squeeze(0).transpose(0, 1)
|
||||
return log_mel
|
||||
except Exception:
|
||||
from scipy import signal
|
||||
f, t, Sxx = signal.spectrogram(audio, fs=sample_rate, nperseg=400, noverlap=240, nfft=512)
|
||||
log_spec = np.log(Sxx[:80, :] + 1e-6).T
|
||||
return torch.from_numpy(log_spec).float()
|
||||
|
||||
def transcribe(self, audio_file: str) -> Dict[str, Any]:
|
||||
path = Path(audio_file)
|
||||
data, orig_sr = read_audio_file(path)
|
||||
data = convert_to_mono(data)
|
||||
if orig_sr != 16000:
|
||||
data = resample_audio(data, orig_sr, 16000)
|
||||
data = normalize_audio(data, 0.95)
|
||||
|
||||
features = self.compute_features(data, 16000).unsqueeze(0).to(self.device) # (1, T, 80)
|
||||
lengths = torch.tensor([features.size(1)], dtype=torch.long).to(self.device)
|
||||
|
||||
with torch.no_grad():
|
||||
log_probs, out_lengths, logits = self.model(features, lengths)
|
||||
preds = torch.argmax(logits, dim=-1)
|
||||
pred_ids = preds[0, :out_lengths[0].item()].cpu().tolist()
|
||||
raw_text = self.vocab.decode_ctc(pred_ids)
|
||||
|
||||
norm_res = clean_medical_transcript(raw_text)
|
||||
|
||||
return {
|
||||
"audio_file": str(path.resolve()),
|
||||
"raw_transcription": norm_res["raw_transcript"],
|
||||
"cleaned_transcription": norm_res["cleaned_transcript"],
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser(description="Run Offline STT Inference on Audio File")
|
||||
parser.add_argument("--audio", type=str, required=True, help="Path to audio file")
|
||||
parser.add_argument("--checkpoint", type=str, default="outputs/checkpoints/best_model.pt", help="Path to best_model.pt")
|
||||
args = parser.parse_args()
|
||||
|
||||
engine = OfflineSTTInference(checkpoint_path=args.checkpoint)
|
||||
res = engine.transcribe(args.audio)
|
||||
print("Inference Result:")
|
||||
print("Raw: ", res["raw_transcription"])
|
||||
print("Cleaned:", res["cleaned_transcription"])
|
||||
@@ -0,0 +1,148 @@
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
from pathlib import Path
|
||||
|
||||
# Paths
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent.parent
|
||||
DATA_PATH = BASE_DIR / "data" / "hindi_diabetes_doctor_patient_v2.json"
|
||||
OUTPUT_AUDIO_DIR = BASE_DIR / "datasets" / "processed_audio"
|
||||
MANIFESTS_DIR = BASE_DIR / "datasets" / "manifests"
|
||||
|
||||
OUTPUT_AUDIO_DIR.mkdir(parents=True, exist_ok=True)
|
||||
MANIFESTS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def generate_tone_speech_sample(text: str, filepath: Path, sample_rate: int = 16000):
|
||||
"""
|
||||
Generates synthetic speech acoustic features (modulated waveform) for training
|
||||
when offline/testing to ensure valid audio files exist for every utterance.
|
||||
"""
|
||||
duration = max(1.5, min(8.0, len(text) * 0.08))
|
||||
t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False)
|
||||
|
||||
# Fundamental frequency modulated with formants (synthesizing speech formant harmonics)
|
||||
f0 = 140.0 # Voice pitch
|
||||
f1 = 500.0 # Formant 1
|
||||
f2 = 1500.0 # Formant 2
|
||||
f3 = 2500.0 # Formant 3
|
||||
|
||||
mod = np.sin(2 * np.pi * 3.5 * t) # Syllable rate modulation (~3.5 Hz)
|
||||
carrier = (
|
||||
0.5 * np.sin(2 * np.pi * f0 * t) +
|
||||
0.3 * np.sin(2 * np.pi * f1 * t) +
|
||||
0.15 * np.sin(2 * np.pi * f2 * t) +
|
||||
0.05 * np.sin(2 * np.pi * f3 * t)
|
||||
)
|
||||
waveform = carrier * np.clip(mod + 0.5, 0.0, 1.0)
|
||||
waveform = waveform * 0.7 # Normalize volume
|
||||
|
||||
sf.write(str(filepath), waveform.astype(np.float32), sample_rate)
|
||||
|
||||
def build_dataset_and_manifests():
|
||||
print(f"Loading dataset from: {DATA_PATH}")
|
||||
if not DATA_PATH.exists():
|
||||
alt_path = Path("e:/Diabetes_Dost/Project_1-main/data/hindi_diabetes_doctor_patient_v2.json")
|
||||
if alt_path.exists():
|
||||
data_file = alt_path
|
||||
else:
|
||||
raise FileNotFoundError(f"Cannot find dataset at {DATA_PATH} or {alt_path}")
|
||||
else:
|
||||
data_file = DATA_PATH
|
||||
|
||||
with open(data_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
|
||||
questions = data.get("questions", [])
|
||||
records = []
|
||||
|
||||
patient_responses_map = {
|
||||
"DIA_Q01": ["मुझे पिछले कुछ दिनों से बहुत ज्यादा थकान और प्यास लग रही है", "मेरी शुगर बहुत बढ़ गई है चक्कर आ रहे हैं"],
|
||||
"DIA_Q02": ["हाँ मुझे 5 साल से Type 2 Diabetes है", "मुझे 2 साल पहले पता चला था"],
|
||||
"DIA_Q03": ["सुबह Fasting Blood Sugar 260 mg/dL आई थी", "खाने के बाद PP Sugar 190 थी"],
|
||||
"DIA_Q04": ["हाँ अचानक हाथ कांपने लगे थे और बहुत पसीना आ रहा था", "मुझे हल्का चक्कर और कमजोरी महसूस हो रही है"],
|
||||
"DIA_Q05": ["हाँ बार बार पेशाब आ रही है और नजर धुंधली हो रही है", "बहुत ज्यादा प्यास लग रही है गला सूख रहा है"],
|
||||
"DIA_Q06": ["सुबह नाश्ता नहीं किया था और वॉक करने गया था", "दोपहर में खाना समय पर खाया था"],
|
||||
"DIA_Q07": ["मैं Metformin 500mg सुबह शाम और इंसुलिन लेता हूँ", "Glimepiride 1mg गोली रोज सुबह लेता हूँ"],
|
||||
"DIA_Q08": ["हाँ कल रात की दवा की डोज लेना भूल गया था", "मैंने समय पर सभी दवाएं ली हैं"],
|
||||
"DIA_Q09": ["दवा लेने के बाद कभी कभी उल्टी जैसी महसूस होती है", "कोई एलर्जी या नया लक्षण नहीं हुआ"],
|
||||
"DIA_Q10": ["आमतौर पर शुगर 150 से 200 के बीच रहती है", "हाल ही में शुगर बहुत ऊपर नीचे हो रही है"],
|
||||
"DIA_Q11": ["हाँ पिछले महीने HbA1c टेस्ट कराया था रिजल्ट 7.8 आया था", "HbA1c रिपोर्ट 6.8 प्रतिशत थी"],
|
||||
"DIA_Q12": ["पैरों में सुन्नपन और झनझनाहट रहती है", "आंखों से थोड़ा धुंधला दिखता है"],
|
||||
"DIA_Q13": ["पैर के अंगूठे में छोटा घाव है जो ठीक नहीं हो रहा", "पैर में कोई घाव या सूजन नहीं है"],
|
||||
"DIA_Q14": ["मुझे High Blood Pressure की भी शिकायत है", "मुझे थायरॉयड की समस्या है"],
|
||||
"DIA_Q15": ["मैं रोज दाल रोटी और हरी सब्जियां खाता हूँ मीठा बंद है", "समय पर भोजन करता हूँ"],
|
||||
"DIA_Q16": ["मैं रोज 30 मिनट सुबह वॉक करता हूँ", "नियमित रूप से शाम को घूमता हूँ"],
|
||||
"DIA_Q17": ["मेरी उम्र 52 वर्ष है और पिताजी को भी डायबिटीज थी", "उम्र 45 साल है वजन 70 किलो है"],
|
||||
"DIA_Q18": ["नहीं मैं गर्भवती नहीं हूँ", "ऐसी कोई स्थिति नहीं है"],
|
||||
"DIA_Q19": ["मैं अपनी दवा और डाइट को बेहतर समझना चाहता हूँ", "शुगर कंट्रोल के लिए सलाह चाहिए"],
|
||||
"DIA_Q20": ["नहीं बाकी सब बातें बता दी हैं धन्यवाद", "कोई और समस्या नहीं है"]
|
||||
}
|
||||
|
||||
count = 0
|
||||
for q in questions:
|
||||
qid = q["question_id"]
|
||||
q_text = q["question_hi"]
|
||||
|
||||
# Doctor Question audio
|
||||
doc_audio_file = OUTPUT_AUDIO_DIR / f"{qid}_doctor.wav"
|
||||
generate_tone_speech_sample(q_text, doc_audio_file)
|
||||
records.append({
|
||||
"audio_filepath": str(doc_audio_file).replace("\\", "/"),
|
||||
"text": q_text,
|
||||
"duration": round(float(len(q_text) * 0.08), 2),
|
||||
"question_id": qid,
|
||||
"role": "doctor"
|
||||
})
|
||||
count += 1
|
||||
|
||||
# Patient Answer audio samples
|
||||
answers = patient_responses_map.get(qid, ["हाँ सब ठीक है"])
|
||||
for idx, ans_text in enumerate(answers):
|
||||
pat_audio_file = OUTPUT_AUDIO_DIR / f"{qid}_patient_{idx+1}.wav"
|
||||
generate_tone_speech_sample(ans_text, pat_audio_file)
|
||||
records.append({
|
||||
"audio_filepath": str(pat_audio_file).replace("\\", "/"),
|
||||
"text": ans_text,
|
||||
"duration": round(float(len(ans_text) * 0.08), 2),
|
||||
"question_id": qid,
|
||||
"role": "patient"
|
||||
})
|
||||
count += 1
|
||||
|
||||
print(f"Generated {count} audio samples.")
|
||||
|
||||
# Split 80/20 train/validation
|
||||
np.random.seed(42)
|
||||
indices = np.random.permutation(len(records))
|
||||
split_idx = int(0.8 * len(records))
|
||||
train_records = [records[i] for i in indices[:split_idx]]
|
||||
val_records = [records[i] for i in indices[split_idx:]]
|
||||
|
||||
train_manifest = MANIFESTS_DIR / "train.jsonl"
|
||||
val_manifest = MANIFESTS_DIR / "validation.jsonl"
|
||||
|
||||
with open(train_manifest, "w", encoding="utf-8") as f:
|
||||
for r in train_records:
|
||||
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
||||
|
||||
with open(val_manifest, "w", encoding="utf-8") as f:
|
||||
for r in val_records:
|
||||
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
||||
|
||||
# Also write to backend/datasets/manifests
|
||||
backend_manifest_dir = BASE_DIR / "backend" / "datasets" / "manifests"
|
||||
backend_manifest_dir.mkdir(parents=True, exist_ok=True)
|
||||
with open(backend_manifest_dir / "train.jsonl", "w", encoding="utf-8") as f:
|
||||
for r in train_records:
|
||||
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
||||
with open(backend_manifest_dir / "validation.jsonl", "w", encoding="utf-8") as f:
|
||||
for r in val_records:
|
||||
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
||||
|
||||
print(f"Wrote {len(train_records)} train samples to {train_manifest}")
|
||||
print(f"Wrote {len(val_records)} validation samples to {val_manifest}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
build_dataset_and_manifests()
|
||||
@@ -0,0 +1,356 @@
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any, Optional, List
|
||||
import yaml
|
||||
|
||||
# Initialize DLL directories for PyTorch on Windows
|
||||
lib_dir = Path(sys.prefix) / "site-packages" / "torch" / "lib"
|
||||
user_lib_dir = Path(os.getenv("APPDATA", "")) / "Python" / f"Python{sys.version_info.major}{sys.version_info.minor}" / "site-packages" / "torch" / "lib"
|
||||
for p in [str(lib_dir), str(user_lib_dir), sys.prefix, os.path.dirname(sys.executable)]:
|
||||
if os.path.exists(p) and hasattr(os, "add_dll_directory"):
|
||||
try:
|
||||
os.add_dll_directory(p)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.data import DataLoader
|
||||
|
||||
from training.dataset import Vocabulary, ASRDataset, asr_collate_fn
|
||||
from audio_pipeline.evaluate import calculate_wer_cer
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
|
||||
logger = logging.getLogger("stt_trainer")
|
||||
|
||||
|
||||
def load_config(config_path: str = "config.yaml") -> Dict[str, Any]:
|
||||
if not os.path.exists(config_path):
|
||||
base_dir = Path(__file__).resolve().parent.parent
|
||||
alt_path = base_dir / "config.yaml"
|
||||
if alt_path.exists():
|
||||
config_path = str(alt_path)
|
||||
else:
|
||||
return {}
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
return yaml.safe_load(f) or {}
|
||||
|
||||
|
||||
_ModuleBase = nn.Module if nn is not None else object
|
||||
|
||||
class ConvSubsampling(_ModuleBase):
|
||||
"""2D Convolutional Subsampling layer to compress time by 4x."""
|
||||
def __init__(self, in_channels: int = 80, out_channels: int = 256):
|
||||
if nn is None:
|
||||
return
|
||||
super().__init__()
|
||||
self.conv = nn.Sequential(
|
||||
nn.Conv2d(1, 32, kernel_size=3, stride=2, padding=1),
|
||||
nn.ReLU(),
|
||||
nn.Conv2d(32, 32, kernel_size=3, stride=2, padding=1),
|
||||
nn.ReLU(),
|
||||
)
|
||||
self.out_dim = 32 * (in_channels // 4)
|
||||
self.proj = nn.Linear(self.out_dim, out_channels)
|
||||
|
||||
def forward(self, x: Any, lengths: Any):
|
||||
x = x.unsqueeze(1)
|
||||
x = self.conv(x)
|
||||
b, c, t, d = x.size()
|
||||
x = x.permute(0, 2, 1, 3).contiguous().view(b, t, c * d)
|
||||
out = self.proj(x)
|
||||
out_lengths = ((lengths + 1) // 2 + 1) // 2
|
||||
return out, out_lengths
|
||||
|
||||
|
||||
class DoctorPatientASRModel(_ModuleBase):
|
||||
"""
|
||||
Offline Trainable Acoustic Model for Multilingual Doctor-Patient Conversations.
|
||||
Architecture: ConvSubsampling + BiLSTM/Conformer Encoder + CTC Projection Head.
|
||||
"""
|
||||
def __init__(self, n_mels: int = 80, encoder_dim: int = 256, num_layers: int = 4, vocab_size: int = 200):
|
||||
if nn is None:
|
||||
return
|
||||
super().__init__()
|
||||
self.subsampling = ConvSubsampling(in_channels=n_mels, out_channels=encoder_dim)
|
||||
|
||||
self.lstm = nn.LSTM(
|
||||
input_size=encoder_dim,
|
||||
hidden_size=encoder_dim // 2,
|
||||
num_layers=num_layers,
|
||||
bidirectional=True,
|
||||
batch_first=True,
|
||||
dropout=0.1 if num_layers > 1 else 0.0
|
||||
)
|
||||
|
||||
self.layer_norm = nn.LayerNorm(encoder_dim)
|
||||
self.classifier = nn.Linear(encoder_dim, vocab_size)
|
||||
|
||||
def forward(self, features: Any, lengths: Any):
|
||||
x, out_lengths = self.subsampling(features, lengths)
|
||||
lstm_out, _ = self.lstm(x)
|
||||
norm_out = self.layer_norm(lstm_out)
|
||||
logits = self.classifier(norm_out)
|
||||
log_probs = nn.functional.log_softmax(logits, dim=-1).permute(1, 0, 2)
|
||||
return log_probs, out_lengths, logits
|
||||
|
||||
|
||||
def train_epoch(
|
||||
model: Any,
|
||||
dataloader: Any,
|
||||
optimizer: Any,
|
||||
criterion: Any,
|
||||
device: Any,
|
||||
scaler: Any,
|
||||
grad_accum_steps: int = 1,
|
||||
) -> float:
|
||||
model.train()
|
||||
total_loss = 0.0
|
||||
optimizer.zero_grad()
|
||||
|
||||
for step, batch in enumerate(dataloader):
|
||||
features = batch["features"].to(device)
|
||||
feature_lengths = batch["feature_lengths"].to(device)
|
||||
targets = batch["targets"].to(device)
|
||||
target_lengths = batch["target_lengths"].to(device)
|
||||
|
||||
if scaler is not None and device.type == "cuda":
|
||||
with torch.amp.autocast(device_type="cuda"):
|
||||
log_probs, out_lengths, _ = model(features, feature_lengths)
|
||||
loss = criterion(log_probs, targets, out_lengths, target_lengths)
|
||||
loss = loss / grad_accum_steps
|
||||
scaler.scale(loss).backward()
|
||||
|
||||
if (step + 1) % grad_accum_steps == 0 or (step + 1) == len(dataloader):
|
||||
scaler.unscale_(optimizer)
|
||||
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=5.0)
|
||||
scaler.step(optimizer)
|
||||
scaler.update()
|
||||
optimizer.zero_grad()
|
||||
else:
|
||||
log_probs, out_lengths, _ = model(features, feature_lengths)
|
||||
loss = criterion(log_probs, targets, out_lengths, target_lengths)
|
||||
loss = loss / grad_accum_steps
|
||||
loss.backward()
|
||||
|
||||
if (step + 1) % grad_accum_steps == 0 or (step + 1) == len(dataloader):
|
||||
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=5.0)
|
||||
optimizer.step()
|
||||
optimizer.zero_grad()
|
||||
|
||||
total_loss += loss.item() * grad_accum_steps
|
||||
|
||||
return total_loss / max(1, len(dataloader))
|
||||
|
||||
|
||||
def validate_epoch(
|
||||
model: Any,
|
||||
dataloader: Any,
|
||||
criterion: Any,
|
||||
vocab: Any,
|
||||
device: Any,
|
||||
) -> Dict[str, Any]:
|
||||
model.eval()
|
||||
total_loss = 0.0
|
||||
all_refs = []
|
||||
all_hyps = []
|
||||
|
||||
with torch.no_grad():
|
||||
for batch in dataloader:
|
||||
features = batch["features"].to(device)
|
||||
feature_lengths = batch["feature_lengths"].to(device)
|
||||
targets = batch["targets"].to(device)
|
||||
target_lengths = batch["target_lengths"].to(device)
|
||||
texts = batch["texts"]
|
||||
|
||||
log_probs, out_lengths, logits = model(features, feature_lengths)
|
||||
loss = criterion(log_probs, targets, out_lengths, target_lengths)
|
||||
total_loss += loss.item()
|
||||
|
||||
# Greedy decoding
|
||||
preds = torch.argmax(logits, dim=-1) # (B, T_sub)
|
||||
for i in range(preds.size(0)):
|
||||
seq_len = out_lengths[i].item()
|
||||
pred_ids = preds[i, :seq_len].cpu().tolist()
|
||||
decoded_text = vocab.decode_ctc(pred_ids)
|
||||
all_hyps.append(decoded_text)
|
||||
all_refs.append(texts[i])
|
||||
|
||||
avg_loss = total_loss / max(1, len(dataloader))
|
||||
metrics = calculate_wer_cer(all_refs, all_hyps)
|
||||
|
||||
return {
|
||||
"val_loss": avg_loss,
|
||||
"val_wer": metrics["wer"],
|
||||
"val_cer": metrics["cer"],
|
||||
"references": all_refs,
|
||||
"hypotheses": all_hyps,
|
||||
}
|
||||
|
||||
|
||||
def run_training_pipeline(
|
||||
config_path: str = "config.yaml",
|
||||
resume_path: Optional[str] = None,
|
||||
num_epochs_override: Optional[int] = None
|
||||
) -> Dict[str, Any]:
|
||||
config = load_config(config_path)
|
||||
t_cfg = config.get("training", {})
|
||||
p_cfg = config.get("paths", {})
|
||||
m_cfg = config.get("dataset", {})
|
||||
|
||||
# GPU / Device Auto Detection
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
logger.info(f"Using device: {device} ({torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'CPU'})")
|
||||
|
||||
use_amp = bool(t_cfg.get("mixed_precision", True) and device.type == "cuda")
|
||||
scaler = torch.amp.GradScaler("cuda") if use_amp else None
|
||||
if use_amp:
|
||||
logger.info("Automatic Mixed Precision (AMP) enabled.")
|
||||
|
||||
checkpoint_dir = Path(t_cfg.get("checkpoint_dir", "outputs/checkpoints"))
|
||||
checkpoint_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
logs_dir = Path(p_cfg.get("logs_dir", "outputs/logs"))
|
||||
logs_dir.mkdir(parents=True, exist_ok=True)
|
||||
log_file = logs_dir / "training_metrics.jsonl"
|
||||
|
||||
# Initialize Vocabulary & Datasets
|
||||
vocab = Vocabulary()
|
||||
manifests_dir = m_cfg.get("manifests_dir", "datasets/manifests")
|
||||
train_manifest = str(Path(manifests_dir) / "train.jsonl")
|
||||
val_manifest = str(Path(manifests_dir) / "validation.jsonl")
|
||||
|
||||
train_dataset = ASRDataset(train_manifest, vocab)
|
||||
val_dataset = ASRDataset(val_manifest, vocab)
|
||||
|
||||
if len(train_dataset) == 0:
|
||||
logger.warning("Train dataset manifest is empty. Please run preprocess, transcribe, and build-dataset first.")
|
||||
return {"status": "error", "message": "Train manifest empty"}
|
||||
|
||||
batch_size = min(len(train_dataset), t_cfg.get("batch_size", 4))
|
||||
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, collate_fn=asr_collate_fn)
|
||||
val_loader = DataLoader(val_dataset, batch_size=max(1, min(len(val_dataset), batch_size)), shuffle=False, collate_fn=asr_collate_fn) if len(val_dataset) > 0 else None
|
||||
|
||||
# Model & Optimizer
|
||||
model = DoctorPatientASRModel(
|
||||
n_mels=80,
|
||||
encoder_dim=t_cfg.get("encoder_dim", 256),
|
||||
num_layers=t_cfg.get("num_encoder_layers", 4),
|
||||
vocab_size=len(vocab)
|
||||
).to(device)
|
||||
|
||||
optimizer = torch.optim.AdamW(
|
||||
model.parameters(),
|
||||
lr=float(t_cfg.get("learning_rate", 3e-4)),
|
||||
weight_decay=float(t_cfg.get("weight_decay", 1e-4))
|
||||
)
|
||||
criterion = nn.CTCLoss(blank=vocab.char2idx["<blank>"], zero_infinity=True)
|
||||
|
||||
start_epoch = 1
|
||||
best_wer = float("inf")
|
||||
|
||||
# Check for resume
|
||||
resume_target = resume_path or t_cfg.get("resume_checkpoint")
|
||||
if resume_target and os.path.exists(resume_target):
|
||||
logger.info(f"Resuming training from checkpoint: {resume_target}")
|
||||
checkpoint = torch.load(resume_target, map_location=device)
|
||||
model.load_state_dict(checkpoint["model_state_dict"])
|
||||
optimizer.load_state_dict(checkpoint["optimizer_state_dict"])
|
||||
start_epoch = checkpoint.get("epoch", 0) + 1
|
||||
best_wer = checkpoint.get("best_wer", float("inf"))
|
||||
|
||||
total_epochs = num_epochs_override or t_cfg.get("num_epochs", 15)
|
||||
grad_accum_steps = t_cfg.get("gradient_accumulation_steps", 1)
|
||||
|
||||
logger.info(f"Starting training: {total_epochs} epochs, batch size={batch_size}, vocab size={len(vocab)}")
|
||||
|
||||
training_history = []
|
||||
|
||||
for epoch in range(start_epoch, total_epochs + 1):
|
||||
epoch_start = time.time()
|
||||
train_loss = train_epoch(model, train_loader, optimizer, criterion, device, scaler, grad_accum_steps)
|
||||
|
||||
if val_loader is not None and len(val_dataset) > 0:
|
||||
val_res = validate_epoch(model, val_loader, criterion, vocab, device)
|
||||
val_loss = val_res["val_loss"]
|
||||
val_wer = val_res["val_wer"]
|
||||
val_cer = val_res["val_cer"]
|
||||
else:
|
||||
val_loss = 0.0
|
||||
val_wer = 0.0
|
||||
val_cer = 0.0
|
||||
|
||||
epoch_duration = round(time.time() - epoch_start, 2)
|
||||
|
||||
epoch_metrics = {
|
||||
"epoch": epoch,
|
||||
"train_loss": round(train_loss, 4),
|
||||
"val_loss": round(val_loss, 4),
|
||||
"val_wer": round(val_wer, 4),
|
||||
"val_cer": round(val_cer, 4),
|
||||
"duration_sec": epoch_duration,
|
||||
"device": str(device),
|
||||
}
|
||||
training_history.append(epoch_metrics)
|
||||
|
||||
logger.info(
|
||||
f"Epoch {epoch}/{total_epochs} [{epoch_duration}s] | "
|
||||
f"Train Loss: {train_loss:.4f} | Val Loss: {val_loss:.4f} | "
|
||||
f"Val WER: {val_wer:.4f} | Val CER: {val_cer:.4f}"
|
||||
)
|
||||
|
||||
# Write to log file
|
||||
with open(log_file, "a", encoding="utf-8") as f_log:
|
||||
f_log.write(json.dumps(epoch_metrics) + "\n")
|
||||
|
||||
# Save Regular Checkpoint
|
||||
ckpt_path = checkpoint_dir / f"checkpoint_epoch_{epoch}.pt"
|
||||
torch.save({
|
||||
"epoch": epoch,
|
||||
"model_state_dict": model.state_dict(),
|
||||
"optimizer_state_dict": optimizer.state_dict(),
|
||||
"train_loss": train_loss,
|
||||
"val_loss": val_loss,
|
||||
"val_wer": val_wer,
|
||||
"best_wer": best_wer,
|
||||
"vocab": vocab.char2idx,
|
||||
}, ckpt_path)
|
||||
|
||||
# Save Best Model Checkpoint
|
||||
if val_wer < best_wer or epoch == 1:
|
||||
best_wer = val_wer
|
||||
best_model_path = checkpoint_dir / "best_model.pt"
|
||||
torch.save({
|
||||
"epoch": epoch,
|
||||
"model_state_dict": model.state_dict(),
|
||||
"vocab": vocab.char2idx,
|
||||
"best_wer": best_wer,
|
||||
"val_wer": val_wer,
|
||||
"val_cer": val_cer,
|
||||
}, best_model_path)
|
||||
logger.info(f"--> Saved new BEST model checkpoint to {best_model_path} (WER: {val_wer:.4f})")
|
||||
|
||||
return {
|
||||
"status": "completed",
|
||||
"total_epochs": total_epochs,
|
||||
"best_wer": best_wer,
|
||||
"best_model_path": str(checkpoint_dir / "best_model.pt"),
|
||||
"history": training_history,
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser(description="Offline Doctor-Patient STT Model Trainer")
|
||||
parser.add_argument("--config", type=str, default="config.yaml")
|
||||
parser.add_argument("--resume", type=str, default=None, help="Path to checkpoint.pt to resume")
|
||||
parser.add_argument("--epochs", type=int, default=None, help="Override number of epochs")
|
||||
args = parser.parse_args()
|
||||
|
||||
run_training_pipeline(config_path=args.config, resume_path=args.resume, num_epochs_override=args.epochs)
|
||||
Reference in New Issue
Block a user