-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
165 lines (131 loc) Β· 5.43 KB
/
main.py
File metadata and controls
165 lines (131 loc) Β· 5.43 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
#!/usr/bin/env python3
"""
Main Application - ENHANCED VERSION
Symptom-Based Disease Prediction Chatbot with AI and Machine Learning
"""
import os
import sys
import warnings
import argparse
from fastapi import FastAPI
warnings.filterwarnings('ignore')
# Add the current directory to Python path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from data_preprocessing_fixed import DataPreprocessorFixed
from train_with_ai_augmented import EnhancedAITrainingPipeline
from chatbot_interface import ChatbotInterface
from config import (
TRAINING_DATA_PATH,
TRAINING_SAFE_AUGMENTED_DATA_PATH,
MODELS_DIR,
REPORTS_DIR
)
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Healthcare Chatbot API is running."}
def create_directories():
"""Create necessary directories"""
directories = [MODELS_DIR, REPORTS_DIR]
for directory in directories:
if not os.path.exists(directory):
os.makedirs(directory)
print(f"π Created directory: {directory}")
def check_model_files():
"""Check if enhanced model files exist"""
model_file = os.path.join(MODELS_DIR, "enhanced_ai_augmented_model.joblib")
encoder_file = os.path.join(MODELS_DIR, "enhanced_ai_augmented_label_encoder.joblib")
if os.path.exists(model_file) and os.path.exists(encoder_file):
print("β
Enhanced model files found")
return True
else:
print("β οΈ Enhanced model files not found")
return False
def train_enhanced_model():
"""Train the enhanced model if not already trained"""
print("\nπ TRAINING ENHANCED MODEL")
print("=" * 50)
try:
# Initialize and run enhanced training pipeline
pipeline = EnhancedAITrainingPipeline()
pipeline.load_and_preprocess()
pipeline.train_enhanced_model()
results = pipeline.evaluate_enhanced_model()
pipeline.save_enhanced_model()
pipeline.generate_enhanced_report(results)
print("β
Enhanced model training completed successfully!")
return True
except Exception as e:
print(f"β Error during enhanced model training: {e}")
return False
def load_enhanced_model():
"""Load the enhanced trained model"""
print("\nπ LOADING ENHANCED MODEL")
print("=" * 30)
try:
import joblib
# Load enhanced model and encoder
model_path = os.path.join(MODELS_DIR, "enhanced_ai_augmented_model.joblib")
encoder_path = os.path.join(MODELS_DIR, "enhanced_ai_augmented_label_encoder.joblib")
if not os.path.exists(model_path) or not os.path.exists(encoder_path):
print("β Enhanced model files not found. Please train the model first.")
return None, None
model = joblib.load(model_path)
label_encoder = joblib.load(encoder_path)
print("β
Enhanced model loaded successfully!")
return model, label_encoder
except Exception as e:
print(f"β Error loading enhanced model: {e}")
return None, None
def create_model_trainer(model, label_encoder):
"""Create a model trainer object with the loaded model"""
class ModelTrainer:
def __init__(self, model, label_encoder):
self.clf = model
self.label_encoder = label_encoder
return ModelTrainer(model, label_encoder)
def main():
"""Main application function - ENHANCED VERSION"""
# Parse command line arguments
parser = argparse.ArgumentParser(description='Healthcare Chatbot - Disease Prediction System')
args = parser.parse_args()
print("π₯ ENHANCED SYMPTOM-BASED DISEASE PREDICTION CHATBOT")
print("=" * 60)
print("π€ AI-Powered β’ Machine Learning β’ Medical Validation β’ USER MODE")
print("=" * 60)
try:
# Create necessary directories
create_directories()
# Check if enhanced model exists
if not check_model_files():
print("\nπ Enhanced model not found. Starting training...")
if not train_enhanced_model():
print("β Failed to train enhanced model. Exiting.")
return
else:
print("β
Using existing enhanced model")
# Load enhanced model
model, label_encoder = load_enhanced_model()
if model is None:
print("β Failed to load enhanced model. Exiting.")
return
# Initialize data preprocessor
print("\nπ Initializing data preprocessor...")
data_preprocessor = DataPreprocessorFixed()
data_preprocessor.initialize_all(use_augmented=False, use_ai_augmented=False, use_safe_augmented=True)
# Create model trainer
model_trainer = create_model_trainer(model, label_encoder)
# Initialize enhanced chatbot interface
print("\nπ€ Initializing enhanced chatbot interface...")
chatbot = ChatbotInterface(data_preprocessor, model_trainer)
# Start the enhanced chatbot
print("\nπ― Starting Enhanced Healthcare Chatbot...")
print("=" * 60)
chatbot.start_chatbot()
except KeyboardInterrupt:
print("\n\nπ Goodbye! Thank you for using the Enhanced Healthcare Chatbot!")
except Exception as e:
print(f"\nβ An error occurred: {e}")
print("Please check the error and try again.")
if __name__ == "__main__":
main()