CoolFace
Apppublic

RACHIDZIDANI/Spam_Ham_classification

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py47 linesDownload Raw Back to root
1from utils import model_predict 2from flask import Flask, render_template, request, jsonify  # Import Flask functions for form handling, rendering, and JSON responses3 4# Initialize Flask app5app = Flask(__name__)6 7@app.route("/")8def home():9    return render_template("index.html")  # Load the correct template file10 11@app.route('/predict', methods=['POST'])  # POST method should be used for form submissions12def predict():13    """14    Handles form submission and returns prediction.15    """16    email = request.form.get('email')  # Get form data by key 'email'17    18    if not email:  19        return render_template("index.html", error="Please provide an email.")  # Send an error if no email is provided20 21    prediction = model_predict(email)  # Make the prediction using the model22    return render_template("index.html", prediction=prediction, email=email)  # Return the prediction and input email to the template23 24# Create an API endpoint25@app.route('/api/predict', methods=['POST'])  # POST method for the API endpoint26def predict_api():27    """28    API endpoint that accepts a JSON payload and returns a prediction.29    """30    try:31        data = request.get_json()  # Extract JSON data from the request32        email = data.get('email')  # Get email from JSON payload33        34        if not email:  35            return jsonify({'error': 'No email provided'}), 400  # Return error message if email is missing36 37        prediction = model_predict(email)  # Make the prediction using the model38        return jsonify({'prediction': prediction, 'email': email})  # Return JSON response with prediction and email39 40    except Exception as e:  # Catch any potential exceptions41        return jsonify({'error': str(e)}), 400   # Return error message if something goes wrong42 43# Run the application only in the main thread44if __name__ == "__main__":45    # Make sure the app runs in the main thread and avoids any issues with signal handling46    app.run(host="0.0.0.0", port=7860, debug=True)  # Run the app on host 0.0.0.0 and port 5000 without debug mode47