Ayush Raj




Flask Website with Machine Learning Healthcare Solutions

Online check-ups at your fingertips.

Ayush Raj's photo
Ayush Raj
·Mar 29, 2021·

9 min read

Flask Website with Machine Learning Healthcare Solutions

1. Flask Website with Machine Learning Healthcare Solutions

Flask Website with Machine Learning Healthcare Solutions is a small step to facilitate free online check-ups for multiple diseases . Here we can fill a form or upload a image and the AI algorithm predicts the possibility of a diseases.

Prime Features

  • Very simple form filling interface to get result
  • The AI algorithms have an accuracy of 80-95% percentage .
  • Beautiful responsive interface freshens the mood user
  • It can predict 5 the chances diseases based on input
  • It can also predict possible disease from a variety of symptoms as input

    Github Repo of this website


2. Motivation 💡

Artificial intelligence is changing the way we think about healthcare during the COVID-19 pandemic, opening our eyes to new opportunities to use machine learning to draw useful conclusions faster. While Artificial intelligence(AI) methods have been previously used to augment clinical decisions, there is a significant growth in it's demand . Throughout the patient care pathway, there are opportunities for ML-supported decisions based on collected vitals, laboratory results, medication orders, and comorbidities. With rapidly growing datasets, there also remain important considerations when developing and validating ML models. This motivated me to develop a flask web app to facilitate free online check-ups for many diseases in pandemic area where lockdowns can restrict access to healthcare.

3. Previews of different pages with beautiful GUIs.

Before we dive into the technical aspects of the web app , let's look at the preview of different types of pages . This is the homepage , which has six different sections for checkups and top AI quotes by leading industrialists. A part of which is shown below. Screenshot (49).png Fig 1. Part of home page with cards glowing when hovered over it.

Now if the patient selects test for a particular disease , say diabetes, the web app directs him or her to a form page to fill the details of parameters before a prediction is made.

Screenshot 2021-03-29 154906.png Fig 2. Typical Form page of a disease.

After filling the form , the web app displays it's prediction based on ML/DL models.

Screenshot 2021-03-29 153540.png Fig 3. Typical result page of a disease having a colored table format as output.

4. Technical Aspects

The first step towards the development was the collection of datasets for training different models. For this I used kaggle.

4.1 Datasets

The links of the datasets are given below.

  1. Diabetes Dataset
  2. Liver Dataset
  3. Heart Dataset
  4. Fetal Dataset
  5. Malaria Image Dataset
  6. Disease Symptom Dataset

4.2 Software and frameworks

  1. Jupyter NoteBook (For data pre processing and model development)
  2. Pycharm (for web app development)
  3. Flask ( web development framework)

After the collection of datasets, the second step is training and testing on jupyter or google colab. The datasets 1,2,3,4 and 6 were trained and tested on different machine learning algorithms like random forest, logistic regression ,xgboost , svm . Then the algorithm with the highest accuracy was selected and it's parameter was optimized using grid search . These steps were performed on jupyter notebook. For end to end deployment this model was converted to pickle file.Dataset 5 was trained using deep learning algorithm. We'll go through the sample code for development of fetal health model.

# import libraries
import pandas as pd # for data manipulation or analysis
import numpy as np # for numeric calculation
#read csv file
df = pd.read_csv("datasets/fetal_health.csv")
# taking features in x as parameters except the last column 
x = df.drop(['fetal_health'], axis = 1) 
# last column as result y
y = df['fetal_health']
# split dataset into train and test
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size = 0.3, random_state= 51)

# train and test on different models with accuracy
xx =XGBClassifier();
xx.fit(x_train, y_train)
xx.score(x_test, y_test)

rfc = RandomForestClassifier();
rfc.fit(x_train, y_train)
rfc.score(x_test, y_test)

knn = KNeighborsClassifier();
knn.fit(x_train, y_train)
knn.score(x_test, y_test)

dcc = DecisionTreeClassifier();
dcc.fit(x_train, y_train)
dcc.score(x_test, y_test)

# here xgb gives highest accuracy , so we make(dump) a pickle file named fetal.pkl
import pickle
with open ('models/fetal.pkl','wb') as f:

4.3 Taking Input & Displaying result

The third step is developing front end for input output interface .The basic web GuI of all forms of different diseases are inherited from layout.html to maintain consistency. Input form for Heart Model

{% extends "layout.html" %}

{% block body %}

<div class="container">

    <h1 class="text-center">Heart Disease Prediction</h1>
        <div class="login">
            <form action="{{ url_for('predict_heart') }}" method="POST">
                  <div class=" card-body" >
                      <div class="form-group  row">
                        <div class="col-sm-3">
                            <label for="age">Age</label>
                            <input type="number" class="form-control" id="age" name="age" required>
                        <div class="col-sm-3">
                            <label for="sex">Sex</label>
                            <select class="form-control" id="sex"  name="sex" required>
                              <option disabled selected value> -- Select an Option -- </option>
                              <option value = "1">Male(1)</option>
                              <option value = "0">Female(0)</option>
                      <div class="form-group  row">
                          <div class="col-sm">
                            <label for="cp">Chest Pain Type</label>
                            <select class="form-control" id="cp" name = "cp" required>
                              <option disabled selected value> -- Select an Option -- </option>
                              <option value = "1">Typical Angina(1)</option>
                              <option value = "2">Atypical Angina(2)</option>
                              <option value = "3">Non-anginal Pain(3)</option>
                              <option value = "4">Asymptomatic(4)</option>
                          <div class="col-sm">
                            <label for="trestbps">Resting Blood Pressure in mm Hg</label>
                            <input type="number" class="form-control" id="trestbps" name="trestbps"  required>
                          <div class="col-sm">
                            <label for="chol">Serum Cholestoral in mg/dl</label>
                            <input type="number" class="form-control" id="chol" name="chol" required>


                      <div class="form-group row">
                            <div class="col-sm">
                                <label for="restecg">Resting ECG Results </label>
                                <select class="form-control" id="restecg" name="restecg" required>
                                  <option disabled selected value> -- Select an Option -- </option>
                                  <option value = "0">Normal</option>
                                  <option value = "1">Having ST-T wave abnormality  </option>
                                  <option value = "2"> Probable or definite left ventricular hypertrophy  </option>
                              <div class="col-sm">
                                <label for="thalach">Maximum Heart Rate</label>
                                <input type="number" class="form-control" id="thalach" name="thalach" required>
                              <div class="col-sm">
                                <label for="exang">ST Depression Induced</label>
                                <input type="number" step="any" class="form-control" id="exang" name="exang" required>
                              <div class="col-sm">
                                <label for="exang">Exercise Induced Angina </label>
                                <select class="form-control" id="oldpeak" name="oldpeak" required>
                                  <option disabled selected value> -- Select an Option -- </option>
                                  <option value = "0">No(0)</option>
                                  <option value = "1">Yes(1)</option>
                          <div class="form-group  row">
                          <div class="col-sm">
                            <label for="slope">Slope of the Peak Exercise ST Segment </label>
                            <select class="form-control" id="slope" name="slope" required>
                              <option disabled selected value> -- Select an Option -- </option>
                              <option value = "1">Upsloping</option>
                              <option value = "2">Flat</option>
                              <option value = "3">Downsloping</option>

                          <div class="col-sm">
                            <label for="thal">Thalassemia</label>
                            <select class="form-control" id="thal" name = "thal" required>
                              <option disabled selected value> -- Select an Option -- </option>
                              <option value = "3">Normal(3)</option>
                              <option value = "6">Fixed defect(6)</option>
                              <option value = "7">Reversable defect(7)</option>


                <span ></span>
                <input type="submit" class="btn-primary btn" value="Predict">

{% endblock %}

Output page of heart model , it consists of beautiful table format with message and image for output as seen in figure 2.

{% extends "layout.html" %}

{% block body %}

.center {
  margin: auto;
  width: 50%;

  padding: 10px;
.styled-table {
    border-collapse: collapse;
    margin: 25px 0;
    font-size: 0.9em;
    font-family: sans-serif;
    min-width: 400px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
.styled-table thead tr {
    background-color: #009879;
    color: #ffffff;
    text-align: left;
.styled-table th,
.styled-table td {
    padding: 12px 15px;
.styled-table tbody tr {
    border-bottom: 1px solid #dddddd;
.observe   {
    border-bottom: 1px solid #FFFF00;
     background-color: #FFFF31;
.styled-table tbody tr:nth-of-type(even) {
    background-color: #f3f3f3;

.styled-table tbody tr:last-of-type {
    border-bottom: 2px solid #009879;

.styled-table tbody tr.active-row {
    font-weight: bold;
    color: #009879;


<div class="container" text>

        <!-- Result -->
        <div class="center">

            <table class="styled-table" id="tbl">
        <h1>Report of Patient</h1>



    <td >Sex</td><td>{{a1}}</td>

    <td>Chest Pain Type</td><td>{{a2}}</td>

    <td>Resting Blood Pressure in mm Hg</td><td>{{a3}}</td>

    <td >Serum Cholestoral in mg/dl</td><td>{{a4}}</td>

    <td >Resting ECG Results</td><td>{{a5}}</td>

    <td >Maximum Heart Rate</td><td>{{a6}}</td>

    <td>ST Depression Induced</td><td>{{a7}}</td>
    <td>Exercise Induced Angina</td><td>{{a8}}</td>

    <td>Slope of the Peak Exercise ST Segment</td><td>{{a9}}</td>



        <td class="observe">Obesrvation</td><td class="observe">{{prediction_text}}</td>



    <br >

<button class="btn primary-button" style="color:white; background-color:black;" onclick="window.print()">Print this page</button>


        <!-- Result -->
        <div class="center">
            {% if prediction==1 %}
                <h1>Prediction: <span class='danger'>Oops! You have Heart Disesase.</span></h1>
                <img class="gif" src="{{ url_for('static', filename='sad_emoji.png') }}" alt="Image">
            {% elif prediction==0 %}
                <h1>Prediction: <span class='safe'>Great! You DON'T have Heart Disesase.</span></h1>
                <img class="gif1" src="{{ url_for('static', filename='healthy.gif') }}" alt="Image">
            {% endif %}

{% endblock %}

4.4 Flask Framework Backend

The fourth step is development of backend which involves the integration the pickle file dumped in second step and the front end in the third step with logical coding .Flask is light weight python framework for web api deployment and is ideal for data scienc e projects like this. A sample code for fetal only model is given. For full code check my github repo github.com/ayush-raj8/online_medical_servic..

# Importing essential libraries
from flask import Flask, render_template, request
import pickle
import numpy as np
import pandas as pd

app = Flask(__name__)

def home():
    return render_template('index.html')

def getParameters1():
    parameters = []
    return parameters

def ValuePredictor(to_predict_list, size):
    loaded_model = joblib.load('Models/heart_model')
    to_predict = np.array(to_predict_list).reshape(1,size)
    result = loaded_model.predict(to_predict)
    return result[0]

def heart():
    return render_template('heart.html')

@app.route('/predict_heart', methods=['POST'])
def predict_heart():
    if request.method == 'POST':
        to_predict_list = request.form.to_dict()
        to_predict_list = list(to_predict_list.values())
        to_predict_list = list(map(float, to_predict_list))
        result = ValuePredictor(to_predict_list, 11)
    s = ""
    if (int(result) == 1):
        prediction = 1
        s = "Danger"
        prediction = 0


        a2="Typical Angina"
    elif (int(a[2])==1):
        a2="Atypical Angina"
    elif (int(a[2]) == 1):
        a2="Non-anginal Pain"
    elif (int(a[2]) == 1):

    a5 = ""
    if (int(a[5]) == 0):
        a5 = "Normal"
    elif (int(a[2]) == 1):
        a5 = "Having ST-T wave abnormality "
    elif (int(a[2]) == 2):
        a5 = "Probable or definite left ventricular hypertrophy"

    a8 = ""
    if (int(a[8]) == 0):
        a8 = "No"
    elif (int(a[8]) == 1):
        a8 = "yes "

    a10 = ""
    if (int(a[10]) == 3):
        a10 = "Normal"
    elif (int(a[10]) == 6):
        a10 = "Fixed Defect "
    elif (int(a[10]) == 7):
        a10 = "Reversible Defect"

    a9 = ""
    if (int(a[9]) == 0):
        a9= "Upsloping"
    elif (int(a[2]) == 1):
        a9= "Flat"
    elif (int(a[2]) == 2):
        a9 = "Downsloping"

    return render_template('h_result.html', prediction=prediction,prediction_text=s,a0=a[0],a1=a1,a2=a2,a3=a[3],a4=a[4],a5=a5,a6=a[6],a7=a[7],a8=a8,a9=a[9],a10=a[10])

if __name__ == '__main__':

Note : This is only a part of the entire code , for the entire project code go to my git repo.

4.5 Deployment of this AI project

This is the last step of any AI project i.e. end to end deployment. Deployment of an ML-model simply means the integration of the model into an existing production environment which can take in an input and return an output that can be used in making practical business decisions. There are many platform to do so like Vercel, Netlify, or DigitalOcean and heroku . This model is deployment on heroku . The url is given below online-checkup-ml.herokuapp.com

5.Future Prospects & Conclusion

An extension to this project can be modelling healthcare projects with live data , like using covid 19 data to forecast cases in near future. We can also develop more advanced web app to facilitate healthcare for rural regions. Artificial intelligence is the new wave to technology to embrace. We should develop more and more open source projects for better future.

Did you find this article valuable?

Support Ayush Raj by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
Share this