File size: 7,149 Bytes
095fc22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Flask API for Leachate Prediction Model
Deploy this as a REST API service
"""

from flask import Flask, request, jsonify
from flask_cors import CORS
import pandas as pd
from inference import LeachatePredictionModel
import logging

# Initialize Flask app
app = Flask(__name__)
CORS(app)  # Enable CORS for web access

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Load model at startup
logger.info("Loading model...")
model = LeachatePredictionModel(model_dir='model_artifacts')
logger.info("Model loaded successfully!")


@app.route('/health', methods=['GET'])
def health_check():
    """Health check endpoint"""
    return jsonify({
        'status': 'healthy',
        'model_loaded': True
    }), 200


@app.route('/model/info', methods=['GET'])
def get_model_info():
    """Get model information and performance metrics"""
    try:
        info = model.get_model_info()
        return jsonify({
            'success': True,
            'data': info
        }), 200
    except Exception as e:
        logger.error(f"Error getting model info: {str(e)}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/predict/volume', methods=['POST'])
def predict_volume():
    """
    Stage 1: Predict leachate volume only
    
    Expected JSON format:
    {
        "SiO2_rock": 45.2,
        "Al2O3_rock": 12.3,
        "Type_event_encoded": 0,
        "Event_quantity": 25.5,
        "Temp": 15.3,
        ...
    }
    """
    try:
        # Get input data
        input_data = request.get_json()
        
        if not input_data:
            return jsonify({
                'success': False,
                'error': 'No input data provided'
            }), 400
        
        # Make prediction
        result = model.predict_volume(input_data)
        
        return jsonify({
            'success': True,
            'data': result
        }), 200
        
    except ValueError as e:
        logger.error(f"Validation error: {str(e)}")
        return jsonify({
            'success': False,
            'error': f'Validation error: {str(e)}'
        }), 400
    except Exception as e:
        logger.error(f"Prediction error: {str(e)}")
        return jsonify({
            'success': False,
            'error': f'Prediction error: {str(e)}'
        }), 500


@app.route('/predict/chemistry', methods=['POST'])
def predict_chemistry():
    """
    Stage 2: Predict chemistry composition
    
    Expected JSON format:
    {
        "SiO2_rock": 45.2,
        "Al2O3_rock": 12.3,
        "Volume_leachate": 50.0,
        "Type_event_encoded": 0,
        ...
    }
    """
    try:
        # Get input data
        input_data = request.get_json()
        
        if not input_data:
            return jsonify({
                'success': False,
                'error': 'No input data provided'
            }), 400
        
        # Make prediction
        result = model.predict_chemistry(input_data)
        
        return jsonify({
            'success': True,
            'data': result
        }), 200
        
    except ValueError as e:
        logger.error(f"Validation error: {str(e)}")
        return jsonify({
            'success': False,
            'error': f'Validation error: {str(e)}'
        }), 400
    except Exception as e:
        logger.error(f"Prediction error: {str(e)}")
        return jsonify({
            'success': False,
            'error': f'Prediction error: {str(e)}'
        }), 500


@app.route('/predict/full', methods=['POST'])
def predict_full():
    """
    Full two-stage prediction: Volume → Chemistry
    
    Expected JSON format:
    {
        "SiO2_rock": 45.2,
        "Al2O3_rock": 12.3,
        "Type_event_encoded": 0,
        "Event_quantity": 25.5,
        "Temp": 15.3,
        ...
    }
    """
    try:
        # Get input data
        input_data = request.get_json()
        
        if not input_data:
            return jsonify({
                'success': False,
                'error': 'No input data provided'
            }), 400
        
        # Make prediction
        result = model.predict(input_data)
        
        return jsonify({
            'success': True,
            'data': result
        }), 200
        
    except ValueError as e:
        logger.error(f"Validation error: {str(e)}")
        return jsonify({
            'success': False,
            'error': f'Validation error: {str(e)}'
        }), 400
    except Exception as e:
        logger.error(f"Prediction error: {str(e)}")
        return jsonify({
            'success': False,
            'error': f'Prediction error: {str(e)}'
        }), 500


@app.route('/predict/batch', methods=['POST'])
def predict_batch():
    """
    Batch predictions for multiple samples
    
    Expected JSON format:
    {
        "samples": [
            {"SiO2_rock": 45.2, "Al2O3_rock": 12.3, ...},
            {"SiO2_rock": 48.1, "Al2O3_rock": 13.1, ...},
            ...
        ]
    }
    """
    try:
        # Get input data
        data = request.get_json()
        
        if not data or 'samples' not in data:
            return jsonify({
                'success': False,
                'error': 'No samples provided. Expected format: {"samples": [...]}'
            }), 400
        
        samples = data['samples']
        
        if not isinstance(samples, list):
            return jsonify({
                'success': False,
                'error': 'Samples must be a list'
            }), 400
        
        # Process each sample
        results = []
        errors = []
        
        for idx, sample in enumerate(samples):
            try:
                result = model.predict(sample)
                results.append({
                    'sample_id': idx,
                    'prediction': result
                })
            except Exception as e:
                errors.append({
                    'sample_id': idx,
                    'error': str(e)
                })
        
        return jsonify({
            'success': True,
            'data': {
                'results': results,
                'errors': errors,
                'total_samples': len(samples),
                'successful': len(results),
                'failed': len(errors)
            }
        }), 200
        
    except Exception as e:
        logger.error(f"Batch prediction error: {str(e)}")
        return jsonify({
            'success': False,
            'error': f'Batch prediction error: {str(e)}'
        }), 500


@app.errorhandler(404)
def not_found(error):
    return jsonify({
        'success': False,
        'error': 'Endpoint not found'
    }), 404


@app.errorhandler(500)
def internal_error(error):
    return jsonify({
        'success': False,
        'error': 'Internal server error'
    }), 500


if __name__ == '__main__':
    # Run the Flask app
    # For production, use a proper WSGI server like gunicorn
    app.run(
        host='0.0.0.0',  # Listen on all interfaces
        port=5000,
        debug=False  # Set to False in production
    )