[af3e0d]: / main.py

Download this file

200 lines (162 with data), 7.0 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
from flask import Flask, jsonify, request
import numpy as np
import joblib
import traceback
from pathlib import Path
from src.preprocessing.preprocessing import create_ordered_medical_pipeline
from src.utils.logger import get_logger
from typing import Dict, Any
# Initialize Flask app
app = Flask(__name__)
class PredictionService:
"""Service for handling model predictions"""
def __init__(self, model_path: str = 'src/models/model.joblib'):
self.model_path = Path(model_path)
self.pipeline = None
self.preprocessor = None
self.logger = get_logger(__name__)
try:
self.initialize()
except Exception as e:
error_traceback = traceback.format_exc()
self.logger.error(f"Initialization failed with error: {str(e)}")
self.logger.error(f"Traceback: {error_traceback}")
raise
def initialize(self):
"""Initialize model pipeline"""
try:
self.logger.info(f"Looking for model at: {self.model_path.absolute()}")
# Load model pipeline
if not self.model_path.exists():
raise FileNotFoundError(f"Model file not found at {self.model_path.absolute()}")
# Load the pipeline
self.pipeline = joblib.load(self.model_path)
self.logger.info("Model pipeline loaded successfully")
# Log pipeline contents
self.logger.info("Pipeline contents:")
for key in self.pipeline.keys():
self.logger.info(f"- Found component: {key}")
# Initialize preprocessor
self.logger.info("Initializing preprocessor...")
self.preprocessor = create_ordered_medical_pipeline()
self.logger.info("Preprocessor initialized successfully")
# Log feature dimensions
self.logger.info(f"Expected feature dimension: {self.pipeline['feature_dim']}")
self.logger.info(f"Vectorizer vocabulary size: {len(self.pipeline['vectorizer'].vocabulary_)}")
except Exception as e:
error_traceback = traceback.format_exc()
self.logger.error(f"Initialization failed with error: {str(e)}")
self.logger.error(f"Traceback: {error_traceback}")
raise
def predict(self, text: str) -> Dict[str, Any]:
"""Make prediction on input text"""
try:
# Validate input
if not isinstance(text, str):
raise ValueError("Input must be a string")
if not text.strip():
raise ValueError("Input text cannot be empty")
# Preprocess text
processed_text = self.preprocessor.process(text)
if isinstance(processed_text, tuple):
processed_text = processed_text[0]
# Extract features using vectorizer
features = self.pipeline['vectorizer'].transform([processed_text])
features = features.toarray()
# Verify feature dimension
if features.shape[1] != self.pipeline['feature_dim']:
raise ValueError(
f"Feature dimension mismatch: got {features.shape[1]}, "
f"expected {self.pipeline['feature_dim']}"
)
# Scale features
features_scaled = self.pipeline['scaler'].transform(features)
# Get the model - the model itself is a VotingClassifier
model = self.pipeline['model']
# Make prediction
prediction = model.predict(features_scaled)[0]
# Get prediction probability if available
confidence = None
if hasattr(model, 'predict_proba'):
probabilities = model.predict_proba(features_scaled)[0]
confidence = float(np.max(probabilities))
# Convert prediction using label encoder if available
if 'metadata' in self.pipeline and 'label_encoder' in self.pipeline['metadata']:
prediction = self.pipeline['metadata']['label_encoder'].inverse_transform([prediction])[0]
return {
'status': 'success',
'prediction': prediction,
'confidence': confidence
}
except Exception as e:
error_traceback = traceback.format_exc()
self.logger.error(f"Prediction failed: {str(e)}")
self.logger.error(f"Traceback: {error_traceback}")
raise
# Initialize service with error handling
try:
prediction_service = PredictionService()
app.logger.info("PredictionService initialized successfully")
except Exception as e:
app.logger.error(f"Failed to initialize PredictionService: {str(e)}")
traceback.print_exc()
prediction_service = None
@app.route("/health")
def health_check():
"""Health check endpoint"""
if prediction_service is None:
return jsonify({
'status': 'unhealthy',
'error': 'Prediction service failed to initialize'
}), 500
health_info = {
'status': 'healthy',
'components': {
'model': prediction_service.pipeline is not None and 'model' in prediction_service.pipeline,
'vectorizer': prediction_service.pipeline is not None and 'vectorizer' in prediction_service.pipeline,
'scaler': prediction_service.pipeline is not None and 'scaler' in prediction_service.pipeline,
'preprocessor': prediction_service.preprocessor is not None
}
}
return jsonify(health_info)
@app.route("/predict", methods=["POST"])
def predict():
"""Prediction endpoint"""
if prediction_service is None:
return jsonify({
'status': 'error',
'message': 'Prediction service is not available'
}), 503
try:
# Get request data
data = request.get_json()
# Validate request data
if not data:
return jsonify({
'status': 'error',
'message': 'No data provided'
}), 400
if 'description' not in data:
return jsonify({
'status': 'error',
'message': 'No description provided'
}), 400
# Get prediction
result = prediction_service.predict(data['description'])
return jsonify(result)
except ValueError as e:
return jsonify({
'status': 'error',
'message': str(e)
}), 400
except Exception as e:
error_traceback = traceback.format_exc()
app.logger.error(f"Prediction failed: {str(e)}")
app.logger.error(f"Traceback: {error_traceback}")
return jsonify({
'status': 'error',
'message': str(e),
'traceback': error_traceback
}), 500
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0', port=5000)