from flask import Flask, render_template, request, jsonify
from sklearn.metrics import accuracy_score
import tensorflow as tf
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
import numpy as np
import base64
import io
import uuid 
import tempfile
import os


app = Flask(__name__)

dic = {0: 'GIANT', 1: 'LEUKOSIT', 2: 'NORMAL'}

# with custom_object_scope({'error_rate': error_rate}):
# model = load_model('static/assets/models/Klasifikasi-Et Exception-96.92.h5')

def error_rate(y_true, y_pred):
    incorrect = tf.not_equal(tf.argmax(y_true, axis=-1), tf.argmax(y_pred, axis=-1))
    return tf.reduce_mean(tf.cast(incorrect, tf.float32))

def load_custom_model(model_path):
    with tf.keras.utils.custom_object_scope({'error_rate': error_rate}):
        model = load_model(model_path)
    return model

model_path = 'static/assets/models/Klasifikasi-Et Exception-97.69.h5'
loaded_model = load_custom_model(model_path)


def predict_label(img_path):
    i = image.load_img(img_path, target_size=(224, 224))
    i = image.img_to_array(i) / 255.0
    i = i.reshape(1, 224, 224, 3)

    p = loaded_model.predict(i)

    
    predicted_class = np.argmax(p, axis=-1)
    
    highest_probability = max(p[0]) * 100
    
    probabilities = (p[0] * 100).tolist()

    print(probabilities)
    
    other_probabilities = {}
    for index, prob in enumerate(probabilities):
        if index != predicted_class[0]:
            other_probabilities[dic[index]] = prob  
    return {
        'label': dic[predicted_class[0]],
        'highest_probability': highest_probability,
        'other_probabilities': other_probabilities
    }



@app.route("/", methods=['GET'])
def main():
    return render_template("index.html")

@app.route("/giant", methods=['GET'])
def giant():
    return render_template("giant.html")

@app.route("/leukosit", methods=['GET'])
def leukosit():
    return render_template("leukosit.html")

@app.route("/normal", methods=['GET'])
def normal():
    return render_template("normal.html")

@app.route("/classification", methods=['GET', 'POST'])
def classification():
    
    temp_dir = "static/assets/temp/"

    try:
        for filename in os.listdir(temp_dir):
            file_path = os.path.join(temp_dir, filename)
            if os.path.isfile(file_path):
                os.remove(file_path)
        
        # Setelah menghapus gambar, tampilkan halaman classification.html
        return render_template("classification.html")

    except Exception as e:
        # Tangani kesalahan jika terjadi
        return f'Terjadi kesalahan: {str(e)}'
    

@app.route("/submit", methods=['POST'])  
def get_output():
    if request.method == 'POST':
        base64data = request.form['image']
        img_data = base64.b64decode(base64data)

        img_filename = str(uuid.uuid4()) + ".jpg"
        img_path = "static/assets/temp/" + img_filename

        with open(img_path, "wb") as f:
            f.write(img_data)

        result = predict_label(img_path)

        return jsonify(
            label=result['label'],
            highest_probability=result['highest_probability'],
            other_probabilities=result['other_probabilities'],
            img_path=img_path
        )



@app.route("/delete_image", methods=['POST'])
def delete_image():
    temp_dir = "static/assets/temp/"

    try:
        for filename in os.listdir(temp_dir):
            file_path = os.path.join(temp_dir, filename)
            if os.path.isfile(file_path):
                os.remove(file_path)

        return jsonify(success=True, message='Semua gambar berhasil dihapus.')

    except Exception as e:
        return jsonify(success=False, message=f'Terjadi kesalahan: {str(e)}')


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







