Spaces:
Runtime error
Runtime error
Download api_deployment.py from M2-DISS/ml-rocks: direct link, hf CLI and curl.
- Browser
- Download file 7.15 kB
-
https://huggingface.co/spaces/M2-DISS/ml-rocks/resolve/main/api_deployment.py
- Command line
-
hf download hf://spaces/M2-DISS/ml-rocks/api_deployment.py
-
curl -L -o api_deployment.py https://huggingface.co/spaces/M2-DISS/ml-rocks/resolve/main/api_deployment.py
7.15 kB
| """ | |
| 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!") | |
| def health_check(): | |
| """Health check endpoint""" | |
| return jsonify({ | |
| 'status': 'healthy', | |
| 'model_loaded': True | |
| }), 200 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| def not_found(error): | |
| return jsonify({ | |
| 'success': False, | |
| 'error': 'Endpoint not found' | |
| }), 404 | |
| 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 | |
| ) | |