# USAGE
# Start the server:
# 	python ai_server.py
# Submit a request via cURL:
# 	curl -X POST -F image=@nutx.jpg 'http://localhost:5000/predict'
# Submita a request via Python:
#	python simple_request.py

# import the necessary packages
from keras.preprocessing.image import img_to_array
from tensorflow import keras
from PIL import Image
import numpy as np
import flask
import io

# initialize our Flask application and the Keras model
app = flask.Flask(__name__)
model = None
labels = []

@app.before_first_request
def load_model():
	# load the pre-trained Keras model
	global model
	global labels
	print("Info: setting labels...")
	labels = (["aci","allahverdi","fosa","incekara","karkalak","okay28","palaz","sivri","tombul","yassibadem","yuvarlakbadem"])
	print("Info: reading model file...")
	model = keras.models.load_model('nut_model.h5')

def prepare_image(image, target):
	# if the image mode is not RGB, convert it
	if image.mode != "RGB":
		print("INFO: converting to RGB!")
		image = image.convert("RGB")

	# resize the input image and preprocess it
	image = image.resize(target)

	print(image)
	image = img_to_array(image)
	image = np.expand_dims(image, axis=0)/255

	# return the processed image
	return image

@app.route("/predict", methods=["POST"])
def predict():
	# initialize the data dictionary that will be returned from the
	# view
	data = {"success": False}

	# ensure an image was properly uploaded to our endpoint
	if flask.request.method == "POST":
		if flask.request.files.get("image"):
			# read the image in PIL format
			image = flask.request.files["image"].read()
			image = Image.open(io.BytesIO(image))

			# preprocess the image and prepare it for classification
			image = prepare_image(image, target=(150, 150))

			# classify the input image
			if model is None:
				data["message"]="Pre-trained AI model can not be loaded! Please try later!"
				print("Info: model file is not loaded!")
			else:
				# return first three probailities
				top = 3
				preds = model.predict(image)
				for pred in preds:
					top_indices = pred.argsort()[-top:][::-1]
					result = [tuple(labels[i]) + (pred[i],) for i in top_indices]
					results = {}
					for i in top_indices:
						results[labels[i]] = pred[i]
						print("Predicted:", labels[i], " probability=", pred[i])
				data["results"] = results
				# single prediction
				#pred = model.predict_classes(image)
				#print(pred)
				#data["prediction"] = labels[pred[0]]

				# indicate that the request was a success
				data["success"] = True

	# return the data dictionary as a JSON response
	return flask.jsonify(str(data))

# if this is the main thread of execution first load the model and
# then start the server
if __name__ == "__main__":
	print(("* Loading Keras model and Flask starting server..."
		"please wait until server has fully started"))
	load_model()
	app.run()