Вывод HTML-файла не генерируетсяCSS

Разбираемся в CSS
Ответить
Anonymous
 Вывод HTML-файла не генерируется

Сообщение Anonymous »

Вот код для создания HTML-файла, позволяющего предсказать, есть ли у человека диабет или нет, с учетом этих 6 факторов: беременность, уровень глюкозы, кровяное давление, ИМТ, функция DiabetesPedigreeFunction и возраст.
Когда я запускаю HTML-файл , при запуске отображается ошибка, независимо от введенных данных. Есть ли этому причина и самое главное как это исправить? Любая помощь будет очень признательна.
from flask import Flask, request, jsonify
from flask_cors import CORS
import util

app = Flask(import_name=__name__)
CORS(app)

@app.route('/get_num_pregnancies', methods=['GET'])
def get_num_pregancies():
response = jsonify({
'Pregnancies': util.get_demographic_info()
})
response.headers.add('Access-Control-Allow-Origin', '*')
return response
@app.route('/check_for_diabetes', methods=['POST'])
def check_for_diabetes():
try:
Pregnancies = int(request.form['Pregnancies'])
Glucose = int(request.form['Glucose'])
BloodPressure = int(request.form['BloodPressure'])
BMI = float(request.form['BMI'])
DiabetesPedigreeFunction = float(request.form['DiabetesPedigreeFunction'])
Age = int(request.form['Age'])

prediction = util.check_for_diabetes(Pregnancies, Glucose, BloodPressure, BMI, DiabetesPedigreeFunction, Age)

response = jsonify({
'diabetes_prediction': prediction
})
response.headers.add('Access-Control-Allow-Origin', '*')
return response
except Exception as e:
response = jsonify({'error': str(e)})
response.headers.add('Access-Control-Allow-Origin', '*')
return response, 500

if __name__ == '__main__':
print('Starting Python Flask for Diabeties Prediction')
util.load_saved_artifacts()
app.run(debug=True)

import json
import pickle
import numpy as np
from sklearn.preprocessing import StandardScaler

__data_columns = None
__model = None
__scaler = None

def check_for_diabetes(Pregnancies, Glucose, BloodPressure, BMI, DiabetesPedigreeFunction, Age):
global __model
global __data_columns
global __scaler

# Ensure the model and data columns are loaded
if __model is None or __data_columns is None or __scaler is None:
load_saved_artifacts()

# Create a numpy array for the input features
input_features = np.array([[Pregnancies, Glucose, BloodPressure, BMI, DiabetesPedigreeFunction, Age]])

# Scale the input features using the same scaler fitted during training
input_features_scaled = __scaler.transform(input_features)

# Predict the outcome
prediction = __model.predict(input_features_scaled)
return prediction[0]
def get_demographic_info():
return __data_columns[:1]
def load_saved_artifacts():
print('Loading saved artifacts ...start')
global __data_columns
global __model
global __scaler

# Load data columns and model
try:
with open('modeL-json', 'r') as f:
__data_columns = json.load(f)['data_columns']
except FileNotFoundError as e:
print(f"Error: {e}")
return

try:
with open('model-pickle', 'rb') as f:
__model = pickle.load(f)
except FileNotFoundError as e:
print(f"Error: {e}")
return

# Load the scaler used during training
try:
with open('scaler-pickle', 'rb') as f:
__scaler = pickle.load(f)
except FileNotFoundError as e:
print(f"Error: {e}")
return

print('Loading saved artifacts ...done')

if __name__ == '__main__':
load_saved_artifacts()

if __data_columns:
# Test the prediction function
prediction = check_for_diabetes(6, 148, 72, 33.6, 0.627, 50)
print(f"Prediction: {'Diabetic' if prediction == 1 else 'Non-Diabetic'}")
else:
print("Failed to load the data columns.")


function onClickedPredictDiabetes() {
console.log("Predict Diabetes button clicked");

var pregnancies = parseInt(document.getElementById("Pregnancies").value);
var glucose = parseInt(document.getElementById("Glucose").value);
var bloodPressure = parseInt(document.getElementById("BloodPressure").value);
var bmi = parseFloat(document.getElementById("BMI").value);
var diabetesPedigreeFunction = parseFloat(document.getElementById("DiabetesPedigreeFunction").value);
var age = parseInt(document.getElementById("Age").value);

// Update the URL as needed
var url = "http://127.0.0.1:5000/check_for_diabetes"; // Use this if you are running the server locally

$.post(url, {
Pregnancies: pregnancies,
Glucose: glucose,
BloodPressure: bloodPressure,
BMI: bmi,
DiabetesPedigreeFunction: diabetesPedigreeFunction,
Age: age
})
.done(function(data) {
var prediction = data.diabetes_prediction == 1 ? "Diabetic" : "Non-Diabetic";
document.getElementById("predictionResult").innerHTML = "Prediction: " + prediction;
console.log(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log("Error:", textStatus, errorThrown); // Log the error for debugging
document.getElementById("predictionResult").innerHTML = "Prediction: Error predicting diabetes.";
});
}

// No need for onPageLoad function for this context







Diabetes Prediction







Diabetes Prediction Form

Pregnancies


Glucose


Blood Pressure


BMI


Diabetes Pedigree Function


Age


Predict Diabetes



Prediction:







Подробнее здесь: https://stackoverflow.com/questions/786 ... generating
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «CSS»