from __future__ import division, print_function
import sys
import os
import glob
import re
import numpy as np
import tensorflow as tf
import pathlib
import wget
from tensorflow.keras.applications.resnet50 import preprocess_input
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
from flask import Flask, redirect, url_for, request, render_template
from werkzeug.utils import secure_filename
MODEL_PATH = 'model_resnet.hdf5'
MODEL_URL = 'https://github.com/DARK-art108/Cotton-Leaf-Disease-Prediction/releases/download/v1.0/model_resnet.hdf5'
UPLOAD_FOLDER = os.path.join(os.path.dirname(__file__), 'static', 'uploads')
while not pathlib.Path(MODEL_PATH).is_file():
print(f'Model {MODEL_PATH} not found. Downloading...')
wget.download(MODEL_URL)
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
model = load_model(MODEL_PATH)
def model_predict(img_path, model):
print(img_path)
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = x / 255
x = np.expand_dims(x, axis=0)
preds = model.predict(x)
preds = np.argmax(preds, axis=1)
if preds == 0:
preds = "The leaf is a diseased cotton leaf."
elif preds == 1:
preds = "The leaf is a diseased cotton plant."
elif preds == 2:
preds = "The leaf is a fresh cotton leaf."
else:
preds = "The leaf is a fresh cotton plant."
return preds
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
print(request.files, request.form, request.args)
f = None
if 'image' in request.files: f = request.files['image']
if f:
file_path = os.path.join(
app.config['UPLOAD_FOLDER'], secure_filename(f.filename))
f.save(file_path)
preds = model_predict(file_path, model)
result = preds
return render_template('index.html', result=result, img=secure_filename(f.filename))
return render_template('index.html', result=None, err='Failed to receive file')
return render_template('index.html', result=None)
if __name__ == '__main__':
app.run(port=5001, debug=True)