File size: 2,684 Bytes
282fe26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

# backend_files/app.py
import joblib
import pandas as pd
from flask import Flask, request, jsonify

# Initialize Flask app
app = Flask("ExtraaLearn Lead Conversion Predictor")

# Load the trained lead-conversion model
model = joblib.load("my_model_v1_0.joblib")

@app.get("/")
def home():
    return (
        "Welcome to the ExtraaLearn Lead Conversion Prediction API - "
        "Use POST /v1/lead for single prediction or POST /v1/leadbatch to upload CSV."
    )

@app.post("/v1/lead")
def predict_lead():
    """
    Expects JSON body with the lead features only.
    """
    try:
        lead_json = request.get_json(force=True)
    except Exception as e:
        return jsonify({"error": "Invalid or missing JSON body", "details": str(e)}), 400

    # Features used during model training
    expected_features = [
        "age", "current_occupation", "first_interaction", "profile_completed",
        "website_visits", "time_spent_on_website", "page_views_per_visit",
        "last_activity", "EmailActivity", "PhoneActivity", "WebsiteActivity",
        "print_media_type1", "print_media_type2", "digital_media",
        "educational_channels", "referral"
    ]

    # Build sample
    sample = {f: lead_json.get(f, None) for f in expected_features}
    input_df = pd.DataFrame([sample])

    try:
        raw_pred = model.predict(input_df)[0]  # returns 0 or 1
        label = "Converted" if raw_pred == 1 else "Not Converted"

        return jsonify({"Prediction": label})
    except Exception as e:
        return jsonify({
            "error": "Model prediction failed.",
            "details": str(e),
            "sample_input": sample
        }), 500


@app.post("/v1/leadbatch")
def predict_lead_batch():
    """
    Expects a 'file' in form-data (CSV).
    CSV must contain only model features.
    """
    if "file" not in request.files:
        return jsonify({"error": "No file uploaded. Please attach a CSV with key 'file'."}), 400

    file = request.files["file"]
    if file.filename == "":
        return jsonify({"error": "Empty filename. Please upload a valid CSV file."}), 400

    try:
        df = pd.read_csv(file)
    except Exception as e:
        return jsonify({"error": "Failed to read CSV file.", "details": str(e)}), 400

    try:
        raw_preds = model.predict(df).tolist()
        results = ["Converted" if int(pred) == 1 else "Not Converted" for pred in raw_preds]
        return jsonify({"Predictions": results})
    except Exception as e:
        return jsonify({
            "error": "Batch prediction failed.",
            "details": str(e)
        }), 500


if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=5000)