Spaces:
Runtime error
Runtime error
| # 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") | |
| 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." | |
| ) | |
| 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 | |
| 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) | |