[Python] Error trying to post to an api with front-end app and flask

Discussão em 'Python' iniciado por Stack, Fevereiro 13, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following API

    Area,Consumer_profile,Product_category,Product_type,AC_1001_Issue,AC_1002_Issue,AC_1003_Issue,TV_2001_Issue,TV_2002_Issue,TV_2003_Issue,Claim_Value,Service_Centre,Product_Age,Purchased_from,Call_details,Purpose,Fraud,ID
    Rural,Personal,Household,AC,0.0,1.0,2.0,0.0,0.0,0.0,4474.0,12.0,202.0,Manufacturer,30.0,Claim,0,7957.0
    Urban,Personal,Entertainment,TV,0.0,0.0,0.0,1.0,1.0,1.0,25000.0,13.0,60.0,Dealer,1.3,Complaint,0,1396.0
    Rural,Business,Household,AC,0.0,0.0,0.0,0.0,0.0,0.0,10000.0,12.0,3.0,Dealer,2.5,Claim,0,7582.0
    Rural,Personal,Entertainment,TV,0.0,0.0,0.0,1.0,1.0,0.0,4216.0,10.0,672.0,Dealer,25.0,Other,0,5824.0
    Rural,Business,Household,AC,0.0,0.0,0.0,0.0,0.0,0.0,20000.0,13.0,3.0,Manufacturer,6.5,Claim,0,4086.0
    Urban,Personal,Entertainment,TV,0.0,0.0,0.0,0.0,1.0,1.0,4000.0,10.0,275.0,Dealer,11.0,Claim,0,6721.0
    Rural,Business,Entertainment,TV,0.0,0.0,0.0,0.0,0.0,0.0,50000.0,12.0,10.0,Manufacturer,1.6,Claim,0,1185.0
    Urban,Personal,Household,AC,0.0,2.0,1.0,0.0,0.0,0.0,13000.0,13.0,7.0,Manufacturer,1.6,Claim,0,3954.0
    Urban,Business,Household,AC,1.0,0.0,0.0,0.0,0.0,0.0,10000.0,13.0,6.0,Dealer,1.4,Complaint,0,8820.0
    Rural,Business,Entertainment,TV,0.0,0.0,0.0,0.0,0.0,0.0,25000.0,10.0,4.0,Dealer,0.5,Complaint,0,58231.0
    .........
    Urban,Personal,Entertainment,TV,0.0,0.0,0.0,0.0,0.0,0.0,10000.0,14.0,60.0,Dealer,1.4,Complaint,0,6689.0


    Which is available to see here https://www.kaggle.com/datasets/amanneo/df-cleancsv

    I can do requests to my API sucessfully by Postman

    from flask import Flask, request, jsonify
    from flask_cors import CORS
    import joblib
    import traceback
    import pandas as pd
    import sys

    app = Flask(__name__)
    CORS(app)

    @app.route('/predict', methods=['POST'])
    def predict():
    if model:
    try:
    json_ = request.json
    print(json_)
    query = pd.DataFrame(json_)

    query = query.reindex(columns=model_columns)
    """
    for col in numeric_features:
    if query[col].isnull().any():
    query[col].fillna(X[col].mean(), inplace=True)
    """

    query = query.reindex(columns=model_columns, fill_value = 0)

    probabilities = model.predict_proba(query)[:, 1] # Probabilidad de fraude
    predictions = [1 if p >= 0.5 else 0 for p in probabilities]

    response = [{"probability": float(prob), "fraud": int(pred)} for prob, pred in zip(probabilities, predictions)]

    return jsonify(response)

    except Exception as e:
    return jsonify({'trace': traceback.format_exc()})
    else:
    print ('Train the model first')
    return ('No model here to use')

    if __name__ == '__main__':
    try:
    port = int(sys.argv[1])
    except:
    port = 12345

    model = joblib.load("../Models/model.pkl")
    model_columns = joblib.load("../Models/model_columns.pkl")
    # numeric_features = joblib.load("../Models/numeric_features.pkl")

    app.run(port = port, debug = True)


    With this example data

    [
    {
    "Area": "Urban",
    "Consumer_profile": "Personal",
    "Product_category": "Entertainment",
    "Product_type": "TV",
    "AC_1001_Issue": 0.0,
    "AC_1002_Issue": 0.0,
    "AC_1003_Issue": 0.0,
    "TV_2001_Issue": 1.0,
    "TV_2002_Issue": 1.0,
    "TV_2003_Issue": 0.0,
    "Claim_Value": 25000.0,
    "Service_Centre": 13.0,
    "Product_Age": 60.0,
    "Purchased_from": "Dealer",
    "Call_details": 1.3,
    "Purpose": "Complaint"
    },
    {
    "Area": "Rural",
    "Consumer_profile": "Commercial",
    "Product_category": "Appliances",
    "Product_type": "Washing Machine",
    "AC_1001_Issue": 1.0,
    "AC_1002_Issue": 0.0,
    "AC_1003_Issue": 0.0,
    "TV_2001_Issue": 0.0,
    "TV_2002_Issue": 0.0,
    "TV_2003_Issue": 0.0,
    "Claim_Value": 15000.0,
    "Service_Centre": 8.0,
    "Product_Age": 24.0,
    "Purchased_from": "Online",
    "Call_details": 2.0,
    "Purpose": "Repair"
    }
    ]


    I get the following output in Postman (It´s correct):

    [
    {
    "fraud": 0,
    "probability": 0.01
    },
    {
    "fraud": 0,
    "probability": 0.03923567770672705
    }
    ]


    But I´m trying to create a simple front end that can interact with my API and I´m not able to do it. This is mi code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Fraud Detection Form</title>
    <style>
    body { font-family: Arial, sans-serif; background-color: #f0f0f0; padding: 20px; }
    h2 { text-align: center; }
    form { background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); max-width: 600px; margin: 20px auto; }
    label { display: block; margin: 10px 0 5px; }
    input, select { width: 100%; padding: 8px; margin-bottom: 10px; }
    button { background-color: #007BFF; color: #fff; padding: 10px; border: none; border-radius: 4px; cursor: pointer; }
    button:hover { background-color: #0056b3; }
    .result { margin-top: 20px; padding: 10px; border-radius: 4px; text-align: center; }
    .fraud { background-color: #ff4d4d; color: white; }
    .no-fraud { background-color: #4CAF50; color: white; }
    </style>
    </head>
    <body>
    <h2>Warranty Claim Fraud Detection</h2>
    <form id="fraudForm">
    <label for="area">Area:</label>
    <select name="Area" id="area">
    <option value="Urban">Urban</option>
    <option value="Rural">Rural</option>
    </select>

    <label for="consumer_profile">Consumer profile:</label>
    <select name="Consumer_profile" id="consumer_profile">
    <option value="Personal">Personal</option>
    <option value="Business">Business</option>
    </select>

    <label for="product_category">Product category:</label>
    <select name="Product_category" id="product_category">
    <option value="Entertainment">Entertainment</option>
    <option value="Household">Household</option>
    </select>

    <label for="product_type">Product type:</label>
    <select name="Product_type" id="product_type">
    <option value="TV">TV</option>
    <option value="AC">AC</option>
    </select>

    <label>AC 1001 Issue:</label>
    <input type="number" name="AC_1001_Issue" step="0.1" value="0.2" required>

    <label>AC 1002 Issue:</label>
    <input type="number" name="AC_1002_Issue" step="0.1" value="1.5" required>

    <label>AC 1003 Issue:</label>
    <input type="number" name="AC_1003_Issue" step="0.1" value="1.0" required>

    <label>TV 2001 Issue:</label>
    <input type="number" name="TV_2001_Issue" step="0.1" value="1.7" required>

    <label>TV 2002 Issue:</label>
    <input type="number" name="TV_2002_Issue" step="0.1" value="1.0" required>

    <label>TV 2003 Issue:</label>
    <input type="number" name="TV_2003_Issue" step="0.1" value="0.8"required>

    <label>Claim Value:</label>
    <input type="number" name="Claim_Value" step="0.1" value="55555.0" required>

    <label>Service Centre:</label>
    <input type="number" name="Service_Centre" step="0.1" value="50.0" required>

    <label>Product Age (months):</label>
    <input type="number" name="Product_Age" step="0.1" value="890.0" required>

    <label for="purchased_from">Purchased from:</label>
    <select name="Purchased_from" id="purchased_from">
    <option value="Manufacturer">Manufacturer</option>
    <option value="Dealer">Dealer</option>
    </select>

    <label>Call Details:</label>
    <input type="number" name="Call_details" step="0.1" value="0" required>

    <label for="purpose">Purpose:</label>
    <select name="Purpose" id="purpose">
    <option value="Claim">Claim</option>
    <option value="Complaint">Complaint</option>
    </select>

    <button type="submit">Submit</button>
    </form>

    <div id="result"></div>

    <script>
    document.getElementById('fraudForm').addEventListener('submit', async function(event) {
    event.preventDefault();
    const formData = new FormData(this);
    const jsonData = [Object.fromEntries(formData.entries())];

    try {
    const response = await fetch('127.0.0.1:12345/predict', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(jsonData)
    });

    if (!response.ok) throw new Error('Network response was not ok');

    const data = await response.json();
    const resultDiv = document.getElementById('result');
    const result = data[0]; // El primer objeto de la lista de respuesta

    if (result.fraud === 1) {
    resultDiv.textContent = `Fraud detected with probability ${result.probability.toFixed(2)}`;
    resultDiv.className = 'result fraud';
    } else {
    resultDiv.textContent = `No fraud detected with probability ${result.probability.toFixed(2)}`;
    resultDiv.className = 'result no-fraud';
    }
    } catch (error) {
    console.error('Error:', error);
    const resultDiv = document.getElementById('result');
    resultDiv.textContent = 'An error occurred while submitting the form. Please try again.';
    resultDiv.className = 'result fraud';
    }
    });
    </script>

    </body>
    </html>



    I always get an error:

    [​IMG]

    Continue reading...

Compartilhe esta Página