File size: 2,044 Bytes
4820019
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import joblib
import pandas as pd
from flask import Flask, request, jsonify

app = Flask(__name__)

# Load the serialized model and its components
try:
    model = joblib.load('extraalearn_best_model.joblib')
except FileNotFoundError:
    print("Error: 'extraalearn_best_model.joblib' not found. Ensure it's in the same directory.")
    model = None

@app.route('/predict', methods=['POST'])
def predict():
    """
    Predicts lead conversion based on input data.
    Input data should be a JSON object with lead features.
    """
    if not model:
        return jsonify({'error': 'Model not loaded. Check server logs.'}), 500

    try:
        # Get the JSON data from the request
        data = request.get_json(force=True)
        
        # Convert the dictionary to a DataFrame. The feature names must match the training data.
        input_df = pd.DataFrame([data])
        
        # Ensure the columns are in the correct order for the pipeline
        required_columns = ['age', 'current_occupation', 'first_interaction', 
                            'profile_completed', 'website_visits', 'time_spent_on_website', 
                            'page_views_per_visit', 'last_activity', 'print_media_type1', 
                            'print_media_type2', 'digital_media', 'educational_channels', 
                            'referral']
        input_df = input_df[required_columns]

        # Make prediction
        prediction = model.predict(input_df)[0]
        prediction_proba = model.predict_proba(input_df)[0].tolist()

        # Return the result
        result = {
            'prediction': int(prediction),
            'prediction_label': 'Converted' if prediction == 1 else 'Not Converted',
            'probabilities': {
                'Not Converted': prediction_proba[0],
                'Converted': prediction_proba[1]
            }
        }
        return jsonify(result)

    except Exception as e:
        return jsonify({'error': str(e)}), 400

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)