Dama12 commited on
Commit
ab395fd
·
2 Parent(s): 70d16f212fbcdc

Mise à jour du Dockerfile

Browse files
Files changed (1) hide show
  1. allinone.py +442 -0
allinone.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import pandas as pd
2
  import numpy as np
3
  from xgboost import XGBClassifier
@@ -437,4 +438,445 @@ if __name__ == '__main__':
437
 
438
  retrain_thread = threading.Thread(target=retrain_models, daemon=True)
439
  retrain_thread.start()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
440
  app.run(debug=False, host='0.0.0.0', port=5000)
 
1
+ <<<<<<< HEAD
2
  import pandas as pd
3
  import numpy as np
4
  from xgboost import XGBClassifier
 
438
 
439
  retrain_thread = threading.Thread(target=retrain_models, daemon=True)
440
  retrain_thread.start()
441
+ =======
442
+ import pandas as pd
443
+ import numpy as np
444
+ from xgboost import XGBClassifier
445
+ from lightgbm import LGBMClassifier
446
+ from sklearn.ensemble import RandomForestClassifier
447
+ from sklearn.linear_model import LogisticRegression
448
+ from sklearn.svm import SVC
449
+ from sklearn.preprocessing import StandardScaler, LabelEncoder
450
+ from sklearn.model_selection import StratifiedKFold
451
+ from sklearn.metrics import classification_report, recall_score, f1_score
452
+ from sklearn.impute import SimpleImputer
453
+ from imblearn.over_sampling import SMOTE
454
+ from imblearn.under_sampling import RandomUnderSampler
455
+ from imblearn.pipeline import Pipeline
456
+ import joblib
457
+ from flask import Flask, request, jsonify
458
+ from flask_cors import CORS
459
+ import os
460
+ import warnings
461
+ import time
462
+ from tqdm import tqdm
463
+ import threading
464
+ import logging
465
+ from tenacity import retry, wait_fixed, stop_after_attempt
466
+
467
+ warnings.filterwarnings('ignore', category=UserWarning)
468
+ os.environ["LOKY_MAX_CPU_COUNT"] = "1"
469
+
470
+ logging.basicConfig(level=logging.INFO)
471
+ logger = logging.getLogger(__name__)
472
+
473
+ app = Flask(__name__)
474
+ CORS(app)
475
+
476
+ NEW_DATA_FILE = 'new_data.csv'
477
+ DATASET_PATH = "my_datasheet_80000.csv"
478
+ MIN_NEW_SAMPLES_FOR_RETRAIN = 100
479
+
480
+ # Feature sets for each task
481
+ PRIORITY_FEATURES = [
482
+ 'SpO2', 'Frquce_Rprtr(rpm)', 'Pouls', 'PA', 'Temperature', 'SpO2_Severity', 'Tachypnea', 'Bradypnea',
483
+ 'Tachycardia', 'Bradycardia', 'Critical_Signs', 'SpO2_Temp_Ratio', 'Pouls_PA_Ratio', 'Temp_Pouls_Ratio',
484
+ 'SpO2_PA_Diff', 'SpO2_Temp_Diff', 'PA_Pouls_Diff', 'SpO2_Log', 'Temp_Squared', 'Suggested_Priority'
485
+ ]
486
+
487
+ SERVICE_FEATURES = [
488
+ 'Age', 'Sexe', 'Enceinte', 'SpO2', 'Frquce_Rprtr(rpm)', 'Pouls', 'ECG', 'PA', 'Temperature', 'IMC',
489
+ 'Age_Category', 'Temp_Anomaly', 'PA_High', 'PA_Low', 'Pouls_SpO2_Ratio', 'PA_Temp_Ratio', 'IMC_Temp_Ratio'
490
+ ]
491
+
492
+ priority_model = None
493
+ service_model = None
494
+ priority_scaler = None
495
+ service_scaler = None
496
+ priority_imputer = None
497
+ service_imputer = None
498
+ label_encoder_service = LabelEncoder()
499
+
500
+ model_lock = threading.Lock()
501
+
502
+ def enhanced_features(df):
503
+ df['Tachypnea'] = df.apply(lambda row: 1 if (row['Age'] < 1 and row['Frquce_Rprtr(rpm)'] > 40) or
504
+ (row['Age'] < 12 and row['Frquce_Rprtr(rpm)'] > 30) or
505
+ (row['Age'] >= 12 and row['Frquce_Rprtr(rpm)'] > 20) else 0, axis=1)
506
+ df['Bradypnea'] = df.apply(lambda row: 1 if (row['Age'] < 1 and row['Frquce_Rprtr(rpm)'] < 20) or
507
+ (row['Age'] < 12 and row['Frquce_Rprtr(rpm)'] < 12) or
508
+ (row['Age'] >= 12 and row['Frquce_Rprtr(rpm)'] < 8) else 0, axis=1)
509
+ df['Tachycardia'] = df.apply(lambda row: 1 if (row['Age'] < 1 and row['Pouls'] > 160) or
510
+ (row['Age'] < 12 and row['Pouls'] > 120) or
511
+ (row['Age'] >= 12 and row['Pouls'] > 100) else 0, axis=1)
512
+ df['Bradycardia'] = df.apply(lambda row: 1 if (row['Age'] < 1 and row['Pouls'] < 90) or
513
+ (row['Age'] < 12 and row['Pouls'] < 70) or
514
+ (row['Age'] >= 12 and row['Pouls'] < 50) else 0, axis=1)
515
+ df['SpO2_Temp_Ratio'] = df['SpO2'] / (df['Temperature'] + 1e-6)
516
+ df['Pouls_PA_Ratio'] = df['Pouls'] / (df['PA'] + 1e-6)
517
+ df['Temp_Pouls_Ratio'] = df['Temperature'] / (df['Pouls'] + 1e-6)
518
+ df['SpO2_PA_Diff'] = df['SpO2'] - df['PA'] / 10
519
+ df['SpO2_Temp_Diff'] = df['SpO2'] - df['Temperature']
520
+ df['PA_Pouls_Diff'] = df['PA'] - df['Pouls']
521
+ df['IMC_Temp_Ratio'] = df['IMC'] / (df['Temperature'] + 1e-6)
522
+ df['SpO2_Log'] = np.log1p(df['SpO2'])
523
+ df['Temp_Squared'] = df['Temperature'] ** 2
524
+ df['Pouls_SpO2_Ratio'] = df['Pouls'] / (df['SpO2'] + 1e-6)
525
+ df['PA_Temp_Ratio'] = df['PA'] / (df['Temperature'] + 1e-6)
526
+ df['Age_Category'] = pd.cut(df['Age'], bins=[0, 1, 12, 45, 65, 120], labels=[0, 1, 2, 3, 4])
527
+ df['Temp_Anomaly'] = df['Temperature'].apply(lambda x: 1 if x < 35 or x > 38 else 0)
528
+ df['PA_High'] = df['PA'].apply(lambda x: 1 if x > 160 else 0)
529
+ df['PA_Low'] = df['PA'].apply(lambda x: 1 if x < 90 else 0)
530
+ df['SpO2_Severity'] = pd.cut(df['SpO2'], bins=[0, 85, 90, 92, 100], labels=[3, 2, 1, 0])
531
+ df['Critical_Signs'] = ((df['SpO2'] < 85) | (df['Pouls'] > 150) | (df['Temperature'] > 40) |
532
+ (df['PA'] > 200) | (df['PA'] < 70)).astype(int)
533
+ return df
534
+
535
+ def compute_service_and_priority(row):
536
+ age = row['Age']
537
+ spO2 = row['SpO2']
538
+ frq_resp = row['Frquce_Rprtr(rpm)']
539
+ pouls = row['Pouls']
540
+ ecg = row['ECG']
541
+ pa = row['PA']
542
+ temp = row['Temperature']
543
+ enceinte = row['Enceinte']
544
+ imc = row['IMC']
545
+
546
+ if age <= 18:
547
+ service = 'Pédiatriques'
548
+ elif enceinte:
549
+ service = 'Gynécologie/Obstétrique'
550
+ elif ecg == 1 or (pouls < 50 or pouls > 110) or (frq_resp > 20):
551
+ service = 'Neurologie'
552
+ elif spO2 < 92 or frq_resp > 18 or pouls > 100 or pa < 90 or pa > 160:
553
+ service = 'Cardiorespiratoire'
554
+ elif (imc > 30 and (temp > 38 and temp <= 40) and 70 <= pouls <= 90) or \
555
+ (70 <= pouls <= 90 and 110 <= pa <= 130 and spO2 >= 97 and temp <= 37.5):
556
+ service = 'Médecine générale'
557
+ elif temp > 40:
558
+ service = 'Radiothérapie'
559
+ else:
560
+ service = 'Chirurgie'
561
+
562
+ if spO2 < 85 or temp > 40 or pouls > 150 or pa < 70 or pa > 200:
563
+ priorite = 1
564
+ elif spO2 < 88 or temp > 39.5 or pouls > 130 or pa < 80 or pa > 180 or frq_resp > 25:
565
+ priorite = 2
566
+ elif spO2 < 90 or temp > 38.5 or pouls > 110 or pa < 90 or pa > 160 or frq_resp > 20:
567
+ priorite = 3
568
+ elif spO2 < 92 or temp > 38 or pouls > 100 or pa < 100 or pa > 140 or frq_resp > 18:
569
+ priorite = 4
570
+ else:
571
+ priorite = 5
572
+
573
+ return service, priorite
574
+
575
+ def get_smote_strategy(y, max_samples=1000):
576
+ class_counts = pd.Series(y).value_counts()
577
+ strategy = {}
578
+ for cls, count in class_counts.items():
579
+ target = min(max_samples, max(count * 2, 100)) # Ensure reasonable class sizes
580
+ return strategy
581
+
582
+ def train_priority_model():
583
+ global priority_model, priority_scaler, priority_imputer
584
+ try:
585
+ data = pd.read_csv(DATASET_PATH)
586
+ data['Sexe'] = data['Sexe'].map({'Masculin': 0, 'Feminin': 1})
587
+ data['Enceinte'] = data['Enceinte'].astype(int)
588
+ data['ECG'] = data['ECG'].map({'Normal': 0, 'Anormal': 1})
589
+ data = enhanced_features(data)
590
+ data[['Suggested_Service', 'Suggested_Priority']] = data.apply(compute_service_and_priority, axis=1, result_type='expand')
591
+ data['Suggested_Priority'] = data['Suggested_Priority'].astype(int)
592
+
593
+ X = data[PRIORITY_FEATURES]
594
+ y = data['Priorite'].values - 1 # Shift to 0-based indexing
595
+
596
+ priority_imputer = SimpleImputer(strategy='median')
597
+ X_imputed = priority_imputer.fit_transform(X)
598
+ priority_scaler = StandardScaler()
599
+ X_scaled = priority_scaler.fit_transform(X_imputed)
600
+
601
+ models = {
602
+ 'XGBoost': XGBClassifier(n_estimators=100, max_depth=4, learning_rate=0.05, n_jobs=-1, random_state=42),
603
+ 'LightGBM': LGBMClassifier(n_estimators=100, max_depth=2, learning_rate=0.05, min_child_samples=5,
604
+ reg_alpha=0.5, reg_lambda=0.5, n_jobs=-1, random_state=42, verbose=-1),
605
+ 'RandomForest': RandomForestClassifier(n_estimators=100, max_depth=8, n_jobs=-1, random_state=42),
606
+ 'LogisticRegression': LogisticRegression(max_iter=1000, multi_class='multinomial', random_state=42),
607
+ 'SVM': SVC(probability=True, random_state=42)
608
+ }
609
+
610
+ skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
611
+ results = {}
612
+
613
+ for name, model in models.items():
614
+ logger.info(f"\nEvaluating {name} for Priority...")
615
+ scores = {'f1': [], 'recall_p1': [], 'time': []}
616
+ for train_idx, test_idx in tqdm(skf.split(X_scaled, y), total=5):
617
+ X_train, X_test = X_scaled[train_idx], X_scaled[test_idx]
618
+ y_train, y_test = y[train_idx], y[test_idx]
619
+
620
+ min_class_size = pd.Series(y_train).value_counts().min()
621
+ k_neighbors = min(5, max(1, min_class_size - 1))
622
+ pipeline = Pipeline([
623
+ ('under', RandomUnderSampler(sampling_strategy='majority', random_state=42)),
624
+ ('over', SMOTE(sampling_strategy=get_smote_strategy(y_train), random_state=42, k_neighbors=k_neighbors))
625
+ ])
626
+ X_train_res, y_train_res = pipeline.fit_resample(X_train, y_train)
627
+ class_sizes = pd.Series(y_train_res).value_counts().to_dict()
628
+ logger.info(f"{name} - Resampled class sizes: {class_sizes}")
629
+
630
+ start_time = time.time()
631
+ model.fit(X_train_res, y_train_res)
632
+ train_time = time.time() - start_time
633
+
634
+ y_pred = model.predict(X_test)
635
+ scores['f1'].append(f1_score(y_test, y_pred, average='macro'))
636
+ scores['recall_p1'].append(recall_score(y_test, y_pred, labels=[0], average=None, zero_division=0)[0])
637
+ scores['time'].append(train_time)
638
+ logger.info(f"{name} Fold - F1: {scores['f1'][-1]:.3f}, Recall P1: {scores['recall_p1'][-1]:.3f}")
639
+
640
+ results[name] = {
641
+ 'f1': np.mean(scores['f1']),
642
+ 'recall_p1': np.mean(scores['recall_p1']),
643
+ 'time': np.mean(scores['time'])
644
+ }
645
+ if name == 'LightGBM':
646
+ feature_importance = pd.Series(model.feature_importances_, index=PRIORITY_FEATURES).sort_values(ascending=False)
647
+ logger.info(f"LightGBM Priority Feature Importance:\n{feature_importance}")
648
+
649
+ logger.info("\nPriority Model Comparison:")
650
+ for name, res in results.items():
651
+ logger.info(f"{name}: F1={res['f1']:.3f}, Recall P1={res['recall_p1']:.3f}, Time={res['time']:.2f}s")
652
+
653
+ best_model = max(results, key=lambda k: results[k]['f1'] + results[k]['recall_p1'])
654
+ logger.info(f"Best Priority Model: {best_model}")
655
+
656
+ with model_lock:
657
+ priority_model = models[best_model]
658
+ priority_model.fit(X_scaled, y)
659
+
660
+ timestamp = int(time.time())
661
+ joblib.dump(priority_model, f'priority_model_{timestamp}.pkl')
662
+ joblib.dump(priority_scaler, 'priority_scaler.pkl')
663
+ joblib.dump(priority_imputer, 'priority_imputer.pkl')
664
+ logger.info("Priority model saved.")
665
+ except Exception as e:
666
+ logger.error(f"Error in priority training: {e}")
667
+ raise
668
+
669
+ def train_service_model():
670
+ global service_model, service_scaler, service_imputer, label_encoder_service
671
+ try:
672
+ data = pd.read_csv(DATASET_PATH)
673
+ data['Sexe'] = data['Sexe'].map({'Masculin': 0, 'Feminin': 1})
674
+ data['Enceinte'] = data['Enceinte'].astype(int)
675
+ data['ECG'] = data['ECG'].map({'Normal': 0, 'Anormal': 1})
676
+ data = enhanced_features(data)
677
+ data[['Suggested_Service', 'Suggested_Priority']] = data.apply(compute_service_and_priority, axis=1, result_type='expand')
678
+
679
+ X = data[SERVICE_FEATURES]
680
+ y = label_encoder_service.fit_transform(data['Service_Suivant'].fillna('Unknown'))
681
+
682
+ service_imputer = SimpleImputer(strategy='median')
683
+ X_imputed = service_imputer.fit_transform(X)
684
+ service_scaler = StandardScaler()
685
+ X_scaled = service_scaler.fit_transform(X_imputed)
686
+
687
+ models = {
688
+ 'XGBoost': XGBClassifier(n_estimators=100, max_depth=4, learning_rate=0.05, n_jobs=-1, random_state=42),
689
+ 'LightGBM': LGBMClassifier(n_estimators=100, max_depth=2, learning_rate=0.05, min_child_samples=5,
690
+ reg_alpha=0.5, reg_lambda=0.5, n_jobs=-1, random_state=42, verbose=-1),
691
+ 'RandomForest': RandomForestClassifier(n_estimators=100, max_depth=8, n_jobs=-1, random_state=42),
692
+ 'LogisticRegression': LogisticRegression(max_iter=1000, multi_class='multinomial', random_state=42),
693
+ 'SVM': SVC(probability=True, random_state=42)
694
+ }
695
+
696
+ skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
697
+ results = {}
698
+
699
+ for name, model in models.items():
700
+ logger.info(f"\nEvaluating {name} for Service...")
701
+ scores = {'f1': [], 'time': []}
702
+ for train_idx, test_idx in tqdm(skf.split(X_scaled, y), total=5):
703
+ X_train, X_test = X_scaled[train_idx], X_scaled[test_idx]
704
+ y_train, y_test = y[train_idx], y[test_idx]
705
+
706
+ min_class_size = pd.Series(y_train).value_counts().min()
707
+ k_neighbors = min(5, max(1, min_class_size - 1))
708
+ pipeline = Pipeline([
709
+ ('under', RandomUnderSampler(sampling_strategy='majority', random_state=42)),
710
+ ('over', SMOTE(sampling_strategy=get_smote_strategy(y_train), random_state=42, k_neighbors=k_neighbors))
711
+ ])
712
+ X_train_res, y_train_res = pipeline.fit_resample(X_train, y_train)
713
+ class_sizes = pd.Series(y_train_res).value_counts().to_dict()
714
+ logger.info(f"{name} - Resampled class sizes: {class_sizes}")
715
+
716
+ start_time = time.time()
717
+ model.fit(X_train_res, y_train_res)
718
+ train_time = time.time() - start_time
719
+
720
+ y_pred = model.predict(X_test)
721
+ scores['f1'].append(f1_score(y_test, y_pred, average='macro'))
722
+ scores['time'].append(train_time)
723
+
724
+ results[name] = {
725
+ 'f1': np.mean(scores['f1']),
726
+ 'time': np.mean(scores['time'])
727
+ }
728
+ if name == 'LightGBM':
729
+ feature_importance = pd.Series(model.feature_importances_, index=SERVICE_FEATURES).sort_values(ascending=False)
730
+ logger.info(f"LightGBM Service Feature Importance:\n{feature_importance}")
731
+
732
+ logger.info("\nService Model Comparison:")
733
+ for name, res in results.items():
734
+ logger.info(f"{name}: F1={res['f1']:.3f}, Time={res['time']:.2f}s")
735
+
736
+ best_model = max(results, key=lambda k: results[k]['f1'])
737
+ logger.info(f"Best Service Model: {best_model}")
738
+
739
+ with model_lock:
740
+ service_model = models[best_model]
741
+ service_model.fit(X_scaled, y)
742
+
743
+ timestamp = int(time.time())
744
+ joblib.dump(service_model, f'service_model_{timestamp}.pkl')
745
+ joblib.dump(service_scaler, 'service_scaler.pkl')
746
+ joblib.dump(service_imputer, 'service_imputer.pkl')
747
+ joblib.dump(label_encoder_service, 'label_encoder_service.pkl')
748
+ logger.info("Service model saved.")
749
+ except Exception as e:
750
+ logger.error(f"Error in service training: {e}")
751
+ raise
752
+
753
+ @retry(wait=wait_fixed(2), stop=stop_after_attempt(3))
754
+ def retrain_models():
755
+ global priority_model, service_model, priority_scaler, service_scaler, priority_imputer, service_imputer, label_encoder_service
756
+ while True:
757
+ time.sleep(3600)
758
+ if os.path.exists(NEW_DATA_FILE) and os.path.getsize(NEW_DATA_FILE) > 0:
759
+ try:
760
+ new_data = pd.read_csv(NEW_DATA_FILE)
761
+ if len(new_data) >= MIN_NEW_SAMPLES_FOR_RETRAIN:
762
+ orig_data = pd.read_csv(DATASET_PATH)
763
+ orig_data['Sexe'] = orig_data['Sexe'].map({'Masculin': 0, 'Feminin': 1})
764
+ orig_data['Enceinte'] = orig_data['Enceinte'].astype(int)
765
+ orig_data['ECG'] = orig_data['ECG'].map({'Normal': 0, 'Anormal': 1})
766
+ new_data = enhanced_features(new_data)
767
+ combined_data = pd.concat([orig_data, new_data], ignore_index=True)
768
+
769
+ # Priority retraining
770
+ X_priority = combined_data[PRIORITY_FEATURES]
771
+ y_priority = combined_data['Priorite'].values - 1
772
+ X_priority_imputed = priority_imputer.transform(X_priority)
773
+ X_priority_scaled = priority_scaler.transform(X_priority_imputed)
774
+ with model_lock:
775
+ priority_model.fit(X_priority_scaled, y_priority)
776
+
777
+ # Service retraining
778
+ X_service = combined_data[SERVICE_FEATURES]
779
+ y_service = label_encoder_service.transform(combined_data['Service_Suivant'].fillna('Unknown'))
780
+ X_service_imputed = service_imputer.transform(X_service)
781
+ X_service_scaled = service_scaler.transform(X_service_imputed)
782
+ with model_lock:
783
+ service_model.fit(X_service_scaled, y_service)
784
+
785
+ timestamp = int(time.time())
786
+ joblib.dump(priority_model, f'priority_model_{timestamp}.pkl')
787
+ joblib.dump(service_model, f'service_model_{timestamp}.pkl')
788
+ new_data.to_csv(f'archive_new_data_{timestamp}.csv', index=False)
789
+ open(NEW_DATA_FILE, 'w').close()
790
+ logger.info("Models retrained and saved.")
791
+ except Exception as e:
792
+ logger.error(f"Error in retrain: {e}")
793
+
794
+ @app.route('/predict', methods=['POST'])
795
+ def predict():
796
+ global priority_model, service_model, priority_scaler, service_scaler, priority_imputer, service_imputer, label_encoder_service
797
+ try:
798
+ data = request.get_json()
799
+ required_fields = ['age', 'sexe', 'enceinte', 'spo2', 'freq_resp', 'pouls', 'ecg', 'pa', 'temperature', 'imc']
800
+ missing_fields = [field for field in required_fields if field not in data]
801
+ if missing_fields:
802
+ return jsonify({'error': f'Missing fields: {", ".join(missing_fields)}'}), 400
803
+
804
+ input_data = {
805
+ 'Age': float(data['age']),
806
+ 'Sexe': 0 if data['sexe'].lower() == 'masculin' else 1,
807
+ 'Enceinte': 1 if bool(data['enceinte']) else 0,
808
+ 'SpO2': float(data['spo2']),
809
+ 'Frquce_Rprtr(rpm)': float(data['freq_resp']),
810
+ 'Pouls': float(data['pouls']),
811
+ 'ECG': 0 if data['ecg'].lower() == 'normal' else 1,
812
+ 'PA': float(data['pa']),
813
+ 'Temperature': float(data['temperature']),
814
+ 'IMC': float(data['imc']),
815
+ }
816
+
817
+ input_df = pd.DataFrame([input_data])
818
+ input_df = enhanced_features(input_df)
819
+ suggested_service, suggested_priority = compute_service_and_priority(input_df.iloc[0])
820
+ input_df['Suggested_Priority'] = suggested_priority
821
+
822
+ with model_lock:
823
+ # Priority prediction
824
+ priority_input = input_df[PRIORITY_FEATURES]
825
+ priority_imputed = priority_imputer.transform(priority_input)
826
+ priority_scaled = priority_scaler.transform(priority_imputed)
827
+ priority_probs = priority_model.predict_proba(priority_scaled)[0]
828
+ priority_pred = np.argmax(priority_probs) + 1
829
+ priority_conf = float(max(priority_probs))
830
+
831
+ # Service prediction
832
+ service_input = input_df[SERVICE_FEATURES]
833
+ service_imputed = service_imputer.transform(service_input)
834
+ service_scaled = service_scaler.transform(service_imputed)
835
+ service_probs = service_model.predict_proba(service_scaled)[0]
836
+ service_pred_idx = np.argmax(service_probs)
837
+ service_pred = label_encoder_service.inverse_transform([service_pred_idx])[0]
838
+ service_conf = float(max(service_probs))
839
+
840
+ # Fallback to rule-based logic if confidence is low or critical conditions apply
841
+ if priority_conf < 0.7 or input_df['Critical_Signs'][0] == 1:
842
+ priority_pred = suggested_priority
843
+ if service_conf < 0.7 or input_df['Enceinte'][0] == 1:
844
+ service_pred = suggested_service if input_df['Enceinte'][0] == 0 else 'Gynécologie/Obstétrique'
845
+
846
+ input_df['Priorite'] = priority_pred
847
+ input_df['Service_Suivant'] = service_pred
848
+ if not os.path.exists(NEW_DATA_FILE):
849
+ input_df.to_csv(NEW_DATA_FILE, index=False)
850
+ else:
851
+ input_df.to_csv(NEW_DATA_FILE, mode='a', header=False, index=False)
852
+
853
+ logger.info(f"Predicted: service={service_pred}, priority={priority_pred}, service_conf={service_conf}, priority_conf={priority_conf}")
854
+ return jsonify({
855
+ 'priority': int(priority_pred),
856
+ 'service_suivant': service_pred,
857
+ 'priority_confidence': priority_conf,
858
+ 'service_confidence': service_conf
859
+ })
860
+ except Exception as e:
861
+ logger.error(f"Prediction error: {str(e)}")
862
+ return jsonify({'error': str(e)}), 500
863
+
864
+ if __name__ == '__main__':
865
+ FORCE_RETRAIN = True
866
+ if FORCE_RETRAIN or not (os.path.exists('priority_model.pkl') and os.path.exists('service_model.pkl')):
867
+ train_priority_model()
868
+ train_service_model()
869
+ else:
870
+ with model_lock:
871
+ priority_model = joblib.load('priority_model.pkl')
872
+ service_model = joblib.load('service_model.pkl')
873
+ priority_scaler = joblib.load('priority_scaler.pkl')
874
+ service_scaler = joblib.load('service_scaler.pkl')
875
+ priority_imputer = joblib.load('priority_imputer.pkl')
876
+ service_imputer = joblib.load('service_imputer.pkl')
877
+ label_encoder_service = joblib.load('label_encoder_service.pkl')
878
+
879
+ retrain_thread = threading.Thread(target=retrain_models, daemon=True)
880
+ retrain_thread.start()
881
+ >>>>>>> 12fbcdcf1e034f735bed38d79600e83ccc29f849
882
  app.run(debug=False, host='0.0.0.0', port=5000)