Why am I getting Internal Server Error when I'm using Flask?

Question:

I’m currently working on my machine learning svm_hog model. Now I want to connect my model to my flask. However, everytime I click on the prediction button on my webpage, it brings me to a page that says Internal Server Error. My model works just fine, and I think the problem is in my Flask code but I still get error until now. Below is the code that I use, to run the flask.

flask.py :

import os
from app import app
import urllib.request
from flask import Flask, flash, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
import tkinter as tk
from tkinter import filedialog  
from tkinter import *
from PIL import Image, ImageTk
from tkinter.messagebox import showinfo

ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def predictThis(folder_path):
    from keras.models import load_model
    import numpy as np
    from keras.preprocessing import image
    from numpy import argmax

    model = load_model("HOG_SVM.npy")
    img_width,img_height=550,293
    abnormalities = {0:"normal", 1:"abnormal"}
    test_image = image.load_img(folder_path, target_size=(img_width,img_height))
    test_image = image.img_to_array(test_image)
    test_image = np.expand_dims(test_image,axis=0)
    result = model.predict(test_image)

    category_result = argmax(result)
    return abnormalities[category_result]

app = Flask(__name__)

#flask routing
@app.route("/")
def home():
    return render_template("home.html")

@app.route("/start")
def start():
    return render_template("start.html")

@app.route('/start', methods=['POST'])
def upload_image():
        if 'file' not in request.files:
                flash('No file part')
                return redirect(request.url)
        
        file = request.files['file']

        if file.filename == '':
                flash('No image selected for uploading')
                return redirect(request.url)
            
        if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join('static/upload', filename))
                #print('upload_image filename: ' + filename)
                #flash('Image successfully uploaded and displayed below')

                result = predictThis('static/upload/' + filename)
                if result == 'normal':
                        train = "NORMAL CHEST X RAY"
                elif result == 'abnormal':
                        train = "TUBERCULOSIS CHEST X-RAY"
                        
                return render_template('start.html', output=train, filename=filename)
        else:
                flash('Allowed image types are -> png, jpg, jpeg, gif')
                return redirect(request.url)

@app.route('/display/<filename>')
def display_image(filename):
    #print('display_image filename: ' + filename)
    return redirect(url_for('static', filename='upload/' + filename), code=301)

if __name__=='__main__':
    app.run(debug=True)

My ml model code (HOG_SVM.npy):

from sklearn import svm
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from skimage import color
from imutils.object_detection import non_max_suppression
import imutils
import numpy as np
import argparse
import cv2
import os
import glob
from sklearn import metrics
from PIL import Image 
from numpy import *

# define parameters of HOG feature extraction
orientations = 9
pixels_per_cell = (8, 8)
cells_per_block = (2, 2)
threshold = .3

dataset_path = r"C:UsersuserDesktopTrain" # The path of dataset

# Read the image files:
category_im_listing = os.listdir(dataset_path) # Read all the files in the path
num_category_im = size(category_im_listing) # States the total no. of category
print("There are " + str(num_category_im) + " categories") # Prints the number value of the no.of categories dataset
data= []
labels = []
count = 0

# compute HOG features and label them:
for category in category_im_listing: # Enables reading the files in the pos_im_listing variable one by one
    im_listing = os.listdir(dataset_path + "/" + category)
    num_im = size(im_listing)
    print("There are " + str(num_im) + " images in category " + str(count + 1))
    for file in im_listing:
        img = Image.open(dataset_path + "/" + category + "/" + file) # open the file
        img = img.resize((150,150))
        gray = img.convert('L') # convert the image into single channel 
        # calculate HOG for positive features
        fd = hog(gray, orientations, pixels_per_cell, cells_per_block, block_norm='L2', feature_vector=True) # fd= feature descriptor
        data.append(fd)
        labels.append(count)
    count = count + 1

# encode the labels, converting them from strings to integers
le = LabelEncoder()
labels = le.fit_transform(labels)

# Partitioning the data into training and testing splits, using 80%
# of the data for training and the remaining 20% for testing
print(" Constructing training/testing split...")
(trainData, testData, trainLabels, testLabels) = train_test_split(np.array(data), labels, train_size=0.80, test_size=0.20, random_state=42)

#%% Train the linear SVM
print(" Training Linear SVM classifier with HOG...")
model = svm.LinearSVC(multi_class='ovr')
model.fit(trainData, trainLabels)

#%% Evaluate the classifier
print(" Evaluating classifier on test data ...")
predictions = model.predict(testData)
print(classification_report(testLabels, predictions))
print("Validation Accuracy:",metrics.accuracy_score(testLabels, predictions))

# Save the model:
joblib.dump(model, 'HOG_SVM.npy')

start.html :

<form method="post" action="/start" enctype="multipart/form-data">
                {% if filename %}
                <img src="{{ url_for('display_image', filename=filename) }}" width="250" height="290">
                <label for="actual-btn" class="center">{{output}}</label> 
                {% else %}
                <input class="center" accept="image/*" onchange="loadFile(event)" type="file" name="file" autocomplete="off" required>
                <input type="submit" value="Classify" cass="btn">
                {% endif %} </form>

Update: I modified the app.run() line in the flask.py code into app.run(debug=True) and it shows me this

  * Serving Flask app "__main__" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with windowsapi reloader
An exception has occurred, use %tb to see the full traceback.

SystemExit: 1


C:Usersuseranaconda3libsite-packagesIPythoncoreinteractiveshell.py:3426: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
  warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)

And after I run the %tb, it shows me this

     ---------------------------------------------------------------------------
SystemExit                                Traceback (most recent call last)
<ipython-input-8-869c29e262d1> in <module>
      1 if __name__=='__main__':
----> 2     app.run(debug=True)

~anaconda3libsite-packagesflaskapp.py in run(self, host, port, debug, load_dotenv, **options)
    988 
    989         try:
--> 990             run_simple(host, port, self, **options)
    991         finally:
    992             # reset the first request information if the development server

~anaconda3libsite-packageswerkzeugserving.py in run_simple(hostname, port, application, use_reloader, use_debugger, use_evalex, extra_files, reloader_interval, reloader_type, threaded, processes, request_handler, static_files, passthrough_errors, ssl_context)
   1048         from ._reloader import run_with_reloader
   1049 
-> 1050         run_with_reloader(inner, extra_files, reloader_interval, reloader_type)
   1051     else:
   1052         inner()

~anaconda3libsite-packageswerkzeug_reloader.py in run_with_reloader(main_func, extra_files, interval, reloader_type)
    337             reloader.run()
    338         else:
--> 339             sys.exit(reloader.restart_with_reloader())
    340     except KeyboardInterrupt:
    341         pass

SystemExit: 1
Asked By: jiiehy

||

Answers:

if name==’main‘:

 app.run(debug=True,port=9989,use_reloader=False)
  • Use above code
  • If you are using jupyter notebook for flask app then I will recommend you
    to switch the spyder ,pycharm or Vs code IDE
  • Because you can easily debug things in IDE as compare to Jupyter notebook
Answered By: Nikhil Shingadiya

If you still encounter the same issue try checking open/busy ports.
Here’s the command:
netstat -ab

If the port number you are supplying 9989/5000 try changing port numbers with any of available port. The same error is generated when the port being provided is not accessible.

Answered By: Rupali Tripathi