import numpy as np
from flask import Flask, request, jsonify, render_template
from PIL import Image
from urllib import request
from io import BytesIO
from keras_preprocessing import image
import urllib.request

import pickle
from keras.models import load_model

# Create flask app
flask_app = Flask(__name__)
model = pickle.load(open("model.pkl", "rb"))
model1 = load_model('imgClassification.h5')

@flask_app.route("/")
def Home():
    return render_template("predi.html")

@flask_app.route("/predict", methods = ["POST"])
def predict():
    float_features = [float(x) for x in urllib.request.form.values()]
    features = [np.array(float_features)]
    prediction = model.predict(features)
    return render_template("index.html", prediction_text = "The flower species is {}".format(prediction))

@flask_app.route("/classify", methods = ["POST"])
def classify():
    image_path = "http://192.168.8.103/saved-photo"
    class_names = ['banana', 'cabbage', 'cucumber', 'mango', 'orange', 'tomato']
    img = Image.open(BytesIO(request.urlopen(image_path).read())).resize((224, 224))
    # img = image.load_img(request.urlopen(image_path), target_size=(224,224,3))
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    images = np.vstack([x])
    pred = model1.predict(images, batch_size=32)
    label = np.argmax(pred, axis=1)
    out = class_names[np.argmax(pred)]
    return render_template("predi.html", prediction_text_class = "The flower species is {}".format(out))

if __name__ == "__main__":
    flask_app.run(debug=True)