mayurchoubey123 commited on
Commit
b4f480a
1 Parent(s): afc522f

Create mlserve.py

Browse files
Files changed (1) hide show
  1. mlserve.py +82 -0
mlserve.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mlflow.sklearn
2
+ from flask import Flask, request, jsonify
3
+ from joblib import load
4
+ import requests
5
+ import sys
6
+
7
+ def download_model(model_url, local_path):
8
+ """Downloads a model from the specified URL and saves it locally."""
9
+ try:
10
+ response = requests.get(model_url)
11
+ with open(local_path, 'wb') as f:
12
+ f.write(response.content)
13
+ except Exception as e:
14
+ print(f"Error downloading model: {e}")
15
+ raise # Re-raise the exception for proper handling
16
+
17
+ def load_model_and_log(model_path):
18
+ """Loads a pre-trained Scikit-learn model from the specified path and logs it with MLflow."""
19
+ try:
20
+ # Load the model using joblib
21
+ model = load(model_path)
22
+
23
+ # Log the loaded model with MLflow
24
+ mlflow.sklearn.log_model(model, "loaded_model")
25
+
26
+ # Get the active MLflow run (the one you just logged)
27
+ active_run = mlflow.active_run()
28
+
29
+ # Get the run ID
30
+ run_id = active_run.info.run_id
31
+
32
+ print("Run ID:", run_id)
33
+
34
+ return model, run_id
35
+ except Exception as e:
36
+ print(f"Error loading model: {e}")
37
+ raise # Re-raise the exception for proper handling
38
+
39
+ def load_model_from_mlflow(run_id):
40
+ """Loads a model from MLflow based on the provided run ID."""
41
+ try:
42
+ # Load the model from MLflow
43
+ loaded_model = mlflow.sklearn.load_model(f"runs:/{run_id}/loaded_model")
44
+
45
+ return loaded_model
46
+ except Exception as e:
47
+ print(f"Error loading model from MLflow: {e}")
48
+ raise # Re-raise the exception for proper handling
49
+
50
+ def predict(model):
51
+ """Makes predictions using the provided model."""
52
+ try:
53
+ input_data = request.get_json()
54
+ prediction = model.predict(input_data)
55
+ return jsonify({'prediction': prediction.tolist()})
56
+ except Exception as e:
57
+ print(f"Error making prediction: {e}")
58
+ return jsonify({'error': str(e)}), 500 # Internal Server Error
59
+
60
+ app = Flask(__name__)
61
+
62
+ # Get model URL from command line argument
63
+ model_url = sys.argv[1]
64
+
65
+ # Path to save the downloaded model locally
66
+ local_model_path = "/tmp/model.joblib"
67
+
68
+ # Download the model from the specified URL
69
+ download_model(model_url, local_model_path)
70
+
71
+ # Load the model on app startup and log it with MLflow
72
+ model, run_id = load_model_and_log(local_model_path)
73
+
74
+ # Load the model from MLflow based on the run ID
75
+ loaded_model = load_model_from_mlflow(run_id)
76
+
77
+ @app.route('/predict', methods=['POST'])
78
+ def inference():
79
+ return predict(loaded_model)
80
+
81
+ if __name__ == '__main__':
82
+ app.run(host='0.0.0.0', port=5000)