-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpredict.py
More file actions
456 lines (340 loc) · 13 KB
/
Copy pathpredict.py
File metadata and controls
456 lines (340 loc) · 13 KB
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
import os
import sys
import argparse
import logging
import tempfile
import wave
from pathlib import Path
from typing import Optional, Tuple, Any
import numpy as np
import librosa
from feature_extraction import AudioFeatureExtractor
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
try:
import pyaudio
PYAUDIO_AVAILABLE = True
except ImportError:
PYAUDIO_AVAILABLE = False
logger.debug("PyAudio not available - recording feature disabled")
class Config:
MODELS_DIR = './models'
BEST_MODEL_FILE = './best_model.txt'
USE_PCA = None
SAMPLE_RATE = 22050
N_MFCC = 20
N_CHROMA = 12
CONFIDENCE_DECIMALS = 2
class ModelLoader:
def __init__(self, models_dir: str = Config.MODELS_DIR):
self.models_dir = Path(models_dir)
self.scaler = None
self.pca = None
self.model = None
self.model_name = None
self.use_pca = False
def get_best_model_name(self, best_model_file: str = Config.BEST_MODEL_FILE) -> str:
if not os.path.exists(best_model_file):
raise FileNotFoundError(
f"Best model file not found: {best_model_file}\n"
"Please run train.py and pca_train.py first."
)
with open(best_model_file, 'r') as f:
model_name = f.read().strip()
if not model_name:
raise ValueError("Best model file is empty")
return model_name
def load_scaler(self, model_name: str) -> None:
self.use_pca = '_PCA' in model_name or '_pca' in model_name.lower()
if self.use_pca:
scaler_path = self.models_dir / 'scaler_pca.joblib'
else:
scaler_path = self.models_dir / 'scaler_no_pca.joblib'
if not scaler_path.exists():
raise FileNotFoundError(f"Scaler not found: {scaler_path}")
import joblib
self.scaler = joblib.load(str(scaler_path))
def load_pca(self) -> None:
if not self.use_pca:
return
pca_path = self.models_dir / 'pca_model.joblib'
if not pca_path.exists():
raise FileNotFoundError(f"PCA model not found: {pca_path}")
import joblib
self.pca = joblib.load(str(pca_path))
def load_model(self, model_name: str) -> None:
clean_name = model_name.replace('_PCA', '').replace('_pca', '')
suffix = '_pca.joblib' if self.use_pca else '_no_pca.joblib'
model_path = self.models_dir / f'{clean_name}{suffix}'
if not model_path.exists():
alt_path = self.models_dir / f'{model_name}.joblib'
if alt_path.exists():
model_path = alt_path
else:
raise FileNotFoundError(
f"Model not found: {model_path}\n"
f"Available models in: {self.models_dir}"
)
import joblib
self.model = joblib.load(str(model_path))
self.model_name = model_name
def load_all(self, model_name: Optional[str] = None) -> Tuple[Any, bool]:
if model_name is None:
model_name = self.get_best_model_name()
self.model_name = model_name
self.load_scaler(model_name)
self.load_pca()
self.load_model(model_name)
return self.model, self.use_pca
class ParkinsonPredictor:
def __init__(self, model_name: Optional[str] = None,
models_dir: str = Config.MODELS_DIR):
self.models_dir = models_dir
self.model_name = model_name
self.model = None
self.scaler = None
self.pca = None
self.use_pca = False
self.feature_extractor = None
self._initialized = False
def initialize(self) -> None:
loader = ModelLoader(self.models_dir)
self.model, self.use_pca = loader.load_all(self.model_name)
self.scaler = loader.scaler
self.pca = loader.pca
self.model_name = loader.model_name
self.feature_extractor = AudioFeatureExtractor(
sample_rate=Config.SAMPLE_RATE,
n_mfcc=Config.N_MFCC,
n_chroma=Config.N_CHROMA
)
self._initialized = True
def validate_file(self, filepath: str) -> bool:
if not os.path.exists(filepath):
raise FileNotFoundError(
f"File not found: {filepath}\n"
"Please provide a valid path to a .wav file."
)
if not filepath.lower().endswith('.wav'):
raise ValueError(
f"Unsupported file format: {filepath}\n"
"Only .wav files are supported."
)
if os.path.getsize(filepath) == 0:
raise ValueError(f"File is empty: {filepath}")
return True
def extract_features(self, filepath: str) -> Optional[np.ndarray]:
features = self.feature_extractor.process_file(filepath)
if features is None:
raise RuntimeError(
f"Failed to extract features from: {filepath}\n"
"The audio file may be corrupt or invalid."
)
return features
def preprocess(self, features: np.ndarray) -> np.ndarray:
features = features.reshape(1, -1)
features_scaled = self.scaler.transform(features)
if self.use_pca and self.pca is not None:
features_processed = self.pca.transform(features_scaled)
else:
features_processed = features_scaled
return features_processed
def predict(self, filepath: str) -> Tuple[str, float]:
if not self._initialized:
self.initialize()
self.validate_file(filepath)
features = self.extract_features(filepath)
features_processed = self.preprocess(features)
prediction = self.model.predict(features_processed)[0]
probabilities = self.model.predict_proba(features_processed)[0]
confidence = probabilities[prediction] * 100
label = "Parkinson Detected" if prediction == 1 else "Healthy"
return label, confidence
def predict_with_details(self, filepath: str) -> dict:
if not self._initialized:
self.initialize()
label, confidence = self.predict(filepath)
features = self.feature_extractor.process_file(filepath)
features_processed = self.preprocess(features)
probabilities = self.model.predict_proba(features_processed)[0]
actual_model_name = self.model_name
if not actual_model_name:
try:
with open(Config.BEST_MODEL_FILE, 'r') as f:
actual_model_name = f.read().strip()
except:
actual_model_name = 'SVM'
return {
'file': filepath,
'model': actual_model_name,
'prediction': label,
'confidence': confidence,
'probabilities': {
'healthy': probabilities[0] * 100,
'parkinson': probabilities[1] * 100
},
'use_pca': self.use_pca
}
def format_output(result: dict, verbose: bool = False) -> str:
lines = []
lines.append("PARKINSON'S DISEASE DETECTION - PREDICTION")
lines.append(f"Using Model: {result['model']}")
lines.append(f"Prediction: {result['prediction']}")
lines.append(f"Confidence: {result['confidence']:.{Config.CONFIDENCE_DECIMALS}f}%")
if verbose:
lines.append("-" * 50)
lines.append("Detailed Probabilities:")
lines.append(f" Healthy: {result['probabilities']['healthy']:.2f}%")
lines.append(f" Parkinson: {result['probabilities']['parkinson']:.2f}%")
lines.append(f"PCA Applied: {result['use_pca']}")
return '\n'.join(lines)
def print_result(result: dict, verbose: bool = False) -> None:
print(format_output(result, verbose))
def predict(file_path: str, model_name: Optional[str] = None,
models_dir: str = Config.MODELS_DIR,
verbose: bool = False) -> dict:
predictor = ParkinsonPredictor(model_name, models_dir)
result = predictor.predict_with_details(file_path)
print_result(result, verbose)
return result
def main():
parser = argparse.ArgumentParser(
description='Predict Parkinson\'s disease from voice audio',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python predict.py --file audio.wav
python predict.py -f sample.wav --model RandomForest
python predict.py --file voice.wav --verbose
python predict.py --record # Record from mic and predict
python predict.py --record --duration 5
Models:
- RandomForest (or RandomForest_PCA)
- LogisticRegression (or LogisticRegression_PCA)
- SVM (or SVM_PCA)
If no model is specified, the best model from training is used.
"""
)
parser.add_argument(
'--file', '-f',
type=str,
default=None,
help='Path to the .wav audio file for prediction (not required if using --record)'
)
parser.add_argument(
'--model', '-m',
type=str,
default=None,
help='Model to use (default: best model from best_model.txt)'
)
parser.add_argument(
'--models_dir', '-d',
type=str,
default='./models',
help='Directory containing saved models (default: ./models)'
)
parser.add_argument(
'--verbose', '-v',
action='store_true',
help='Show detailed prediction information'
)
parser.add_argument(
'--record', '-r',
action='store_true',
help='Record from microphone instead of using a file'
)
parser.add_argument(
'--duration',
type=float,
default=3.0,
help='Recording duration in seconds (default: 3)'
)
args = parser.parse_args()
if not args.file and not args.record:
parser.error("Either --file or --record must be provided")
if not os.path.exists(args.models_dir):
logger.error(f"Models directory not found: {args.models_dir}")
logger.error("Please run train.py and pca_train.py first.")
sys.exit(1)
if args.record:
if not PYAUDIO_AVAILABLE:
logger.error("\n" + "=" * 60)
logger.error("PyAudio is not installed!")
logger.error("=" * 60)
logger.error("\nTo install PyAudio:")
logger.error(" macOS: brew install portaudio && pip install pyaudio")
logger.error(" Linux: sudo apt-get install portaudio19-dev && pip install pyaudio")
logger.error(" Windows: pip install pyaudio")
logger.error("=" * 60)
sys.exit(1)
temp_file = None
try:
temp_file = tempfile.NamedTemporaryFile(suffix='.wav', delete=False)
temp_file.close()
logger.info("VOICE RECORDING")
record_audio(args.duration, temp_file.name)
args.file = temp_file.name
logger.info(f"Recording saved to: {temp_file.name}")
except KeyboardInterrupt:
logger.info("\nRecording cancelled by user.")
if temp_file and os.path.exists(temp_file.name):
os.remove(temp_file.name)
sys.exit(130)
try:
result = predict(
file_path=args.file,
model_name=args.model,
models_dir=args.models_dir,
verbose=args.verbose
)
if args.record and temp_file and os.path.exists(temp_file.name):
os.remove(temp_file.name)
if 'Parkinson' in result['prediction']:
sys.exit(1)
else:
sys.exit(0)
except FileNotFoundError as e:
logger.error(f"File Error: {e}")
sys.exit(2)
except ValueError as e:
logger.error(f"Validation Error: {e}")
sys.exit(3)
except RuntimeError as e:
logger.error(f"Processing Error: {e}")
sys.exit(4)
except Exception as e:
logger.error(f"Unexpected Error: {str(e)}")
sys.exit(99)
def record_audio(duration: float, output_path: str, sample_rate: int = 22050) -> None:
audio = pyaudio.PyAudio()
stream = audio.open(
format=pyaudio.paInt16,
channels=1,
rate=sample_rate,
input=True,
frames_per_buffer=1024
)
logger.info(f"Recording for {duration} seconds...")
logger.info("RECORDING! Speak now...")
frames = []
total_chunks = int(sample_rate / 1024 * duration)
for i in range(total_chunks):
data = stream.read(1024, exception_on_overflow=False)
frames.append(data)
# progress = (i + 1) / total_chunks * 100
# if progress % 25 < 10:
# logger.info(f" Recording: {progress:.0f}%")
stream.stop_stream()
stream.close()
audio.terminate()
logger.info("Recording complete!")
with wave.open(output_path, 'wb') as wf:
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(sample_rate)
wf.writeframes(b''.join(frames))
if __name__ == '__main__':
main()