File size: 5,974 Bytes
a8e4c2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213

import numpy as np
import pandas as pd
from scipy.signal import resample
from sklearn.preprocessing import scale
import soundfile as sf
from gemini import query_gemini_rest
import librosa
import tempfile


EXPECTED_LEN = 256
STEP = 128

PCG_LABELS = [
    "Normal",
    "Aortic Stenosis",
    "Mitral Stenosis",
    "Mitral Valve Prolapse",
    "Pericardial Murmurs"
]

LABELS_EMG = ["healthy", "myopathy", "neuropathy"]

def load_uploaded_file(file, signal_type="ECG") -> np.ndarray:
    name = file.name.lower()

 
    if signal_type in ("ECG", "EMG"):
        text = file.read().decode("utf-8").strip()
        if "," in text:
            vals = [float(x) for x in text.split(",") if x.strip()]
        else:
            vals = [float(x) for x in text.splitlines() if x.strip()]
        return np.array(vals, dtype=np.float32)

 
    if signal_type == "VAG":
        if name.endswith(".csv"):
            df = pd.read_csv(file)
            features = [
                "rms_amplitude",
                "peak_frequency",
                "spectral_entropy",
                "zero_crossing_rate",
                "mean_frequency",
            ]
            return df[features].iloc[0].values.astype(np.float32)

        elif name.endswith(".npy"):
            return np.load(file)

        elif name.endswith(".wav"):
            data, _ = sf.read(file)
            return data.astype(np.float32)

        raise ValueError("Unsupported VAG file format.")

  
    if signal_type == "PCG" and name.endswith((".wav", ".flac", ".mp3")):
        data, _ = sf.read(file)
        if data.ndim > 1:         
            data = data[:, 0]
        return data.astype(np.float32)

    raise ValueError("Unsupported file format.")


def preprocess_signal(x: np.ndarray) -> np.ndarray:
    if x.size != EXPECTED_LEN:
        x = resample(x, EXPECTED_LEN)
    return scale(x).astype(np.float32)   


def segment_signal(raw: np.ndarray) -> np.ndarray:
    raw = preprocess_signal(raw)        
    seg = raw.reshape(EXPECTED_LEN, 1)    
    return seg[np.newaxis, ...]            



PCG_INPUT_LEN = 995        

def preprocess_pcg_waveform(wave: np.ndarray) -> np.ndarray:

    if wave.ndim > 1:
        wave = wave.mean(axis=1)

  
    if len(wave) < PCG_INPUT_LEN:
        wave = np.pad(wave, (0, PCG_INPUT_LEN - len(wave)))
    else:
        wave = wave[:PCG_INPUT_LEN]

    
    wave = (wave - np.mean(wave)) / (np.std(wave) + 1e-8)
    return wave.astype(np.float32)

def analyze_pcg_signal(file, model, gemini_key=None):
    
    signal, _ = sf.read(file)                      
    signal = preprocess_pcg_waveform(signal)       

    input_data = signal.reshape(1, PCG_INPUT_LEN, 1)  
    preds = model.predict(input_data, verbose=0)[0]

    labels = [
        "Normal",
        "Aortic Stenosis",
        "Mitral Stenosis",
        "Mitral Valve Prolapse",
        "Pericardial Murmurs",
    ]
    idx = int(np.argmax(preds))
    confidence = float(preds[idx])
    label = labels[idx]

    gem_txt = None
    if gemini_key:
        gem_txt = query_gemini_rest("PCG", label, confidence, gemini_key)

    return label, label, confidence, gem_txt




def pcg_to_features(file_obj, target_sr=16000, n_mels=128, n_frames=112):
    
    with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
        tmp.write(file_obj.read())
        tmp_path = tmp.name

   
    y, sr = librosa.load(tmp_path, sr=target_sr, mono=True)

    
    mel = librosa.feature.melspectrogram(y=y, sr=sr, n_fft=512, hop_length=256, n_mels=n_mels)
    logmel = librosa.power_to_db(mel, ref=np.max) 
    if logmel.shape[1] < n_frames:
        
        pad_width = n_frames - logmel.shape[1]
        pad = np.zeros((n_mels, pad_width))
        logmel = np.hstack((logmel, pad))
    else:
        logmel = logmel[:, :n_frames]

    
    feat = logmel.flatten().astype(np.float32)

    return feat[np.newaxis, ...]


def analyze_emg_signal(file, model, gemini_key=""):
    raw  = load_uploaded_file(file, signal_type="EMG")    
    
    WINDOW = 1000

    wins = []
    if len(raw) < WINDOW:                                
        pad = np.pad(raw, (0, WINDOW - len(raw)))
        wins.append(((pad - pad.mean()) / (pad.std()+1e-6)).reshape(WINDOW, 1))
    else:                                                 
        for i in range(0, len(raw) - WINDOW + 1, WINDOW):
            win = raw[i:i+WINDOW]
            win = (win - win.mean()) / (win.std() + 1e-6)
            wins.append(win.reshape(WINDOW, 1))
    X = np.array(wins, dtype=np.float32)

    preds = model.predict(X, verbose=0)
    classes = np.argmax(preds, axis=1)
    final   = int(np.bincount(classes).argmax())          
    conf    = float(preds[:, final].mean())               
    human   = LABELS_EMG[final]

    gemini_txt = None
    if gemini_key:
        gemini_txt = query_gemini_rest("EMG", human, conf, gemini_key)

    return human, conf, gemini_txt



FEATURE_COLS = [
    "rms_amplitude",
    "peak_frequency",
    "spectral_entropy",
    "zero_crossing_rate",
    "mean_frequency",
]

def vag_to_features(file_obj) -> np.ndarray:
    df = pd.read_csv(file_obj)
    x = df[FEATURE_COLS].iloc[0].values.astype(np.float32)
    return x.reshape(1, -1)


def predict_vag_from_features(file_obj, model_bundle, gemini_key=""):
    model   = model_bundle["model"]
    scaler  = model_bundle["scaler"]
    encoder = model_bundle["encoder"]

    x   = vag_to_features(file_obj)
    x_s = scaler.transform(x)
    prob = model.predict_proba(x_s)[0]
    idx  = int(np.argmax(prob))
    conf = float(prob[idx])
    label = encoder.inverse_transform([idx])[0].title()

    gem_note = (
        query_gemini_rest("VAG", label, conf, gemini_key)
        if gemini_key else None
    )
    return label, label, conf, gem_note