#Importing Necessary libraries
import streamlit as st
import numpy as np
from PIL import Image
from tensorflow.keras.datasets import imdb
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.applications.inception_v3 import preprocess_input
import tensorflow as tf
import pickle
from tensorflow.keras.preprocessing import sequence


# Load the tokenizer using pickle
with open(r'tokenizer_rnn.pkl', 'rb') as handle:
    tokenizer_rnn = pickle.load(handle)
    
with open(r'tokenizer_dnn.pkl', 'rb') as handle:
    tokenizer_dnn = pickle.load(handle)
    
with open(r'tokenizer_per.pkl', 'rb') as handle:
    tokenizer_per = pickle.load(handle)
    
with open(r'tokenizer_backpropagation.pkl', 'rb') as handle:
    tokenizer_back = pickle.load(handle)

# Load saved models
image_model = load_model('tumor_detection_model.h5')
#dnn_model = tf.keras.models.load_model('dnn_model_imdb.h5')
loaded_model = tf.keras.models.load_model('spam_model.h5') 
lstm_model = tf.keras.models.load_model('lstm_model.h5') 
dnn_model = tf.keras.models.load_model('spam_dnn_model.h5') 

with open('spam_perceptron_model.pkl', 'rb') as model_file:
    loaded_perceptron = pickle.load(model_file)

with open('spam_backpropagation_model.pkl', 'rb') as model_file:
    lbackprop_model = pickle.load(model_file)

 
# Streamlit app     
st.title("Classification App")

# Sidebar
task = st.sidebar.selectbox("Select Task", ["Tumor Detection", "Sentiment Classification"])

def preprocess_text(text):
    tokenizer = Tokenizer()
    tokenizer.fit_on_texts([text])
    sequences = tokenizer.texts_to_sequences([text])
    preprocessed_text = pad_sequences(sequences, maxlen=4)

    return preprocessed_text


def predict_dnn(text_input):
    encoded_input = tokenizer_dnn.texts_to_sequences([text_input])
    padded_input = pad_sequences(encoded_input, maxlen=200, padding='post')
    prediction = dnn_model.predict(padded_input)
    prediction_value = prediction[0]
    # Adjust the threshold based on your model and problem
    if prediction_value > 0.5:
        return "Spam"
    else:
        return "Ham"

def predict_lstm(text_input):
    words = 5000
    max_review_length=500
    word_index = imdb.get_word_index()
    text_input = text_input.lower().split()
    text_input = [word_index[word] if word in word_index and word_index[word] < words else 0 for word in text_input]
    text_input = sequence.pad_sequences([text_input], maxlen=max_review_length)
    prediction = lstm_model.predict(text_input)
    print("Raw Prediction:", prediction)
    if prediction > 0.5:
        return "Positive"
    else:
        return "Negative"  


def predict_rnn(input_text):
    encoded_input = tokenizer_rnn.texts_to_sequences([input_text])
    padded_input = tf.keras.preprocessing.sequence.pad_sequences(encoded_input, maxlen=10, padding='post')
    prediction = loaded_model.predict(padded_input)
    if prediction > 0.5:
        return "Spam"
    else:
        return "Ham"


def predict_perceptron(text_input):
    encoded_input = tokenizer_per.texts_to_sequences([text_input])
    padded_input = pad_sequences(encoded_input, maxlen=200, padding='post')
    prediction = loaded_perceptron.predict(padded_input)
    prediction_value = prediction[0]

    # Adjust the threshold based on your model and problem
    if prediction_value > 0.5:
        return "Spam"
    else:
        return "Ham"
    
    
def predict_backpropogation(text_input):
    encoded_input = tokenizer_back.texts_to_sequences([text_input])
    padded_input = pad_sequences(encoded_input, maxlen=200, padding='post')
    prediction = lbackprop_model.predict(padded_input)
    prediction_value = prediction[0]

    # Adjust the threshold based on your model and problem
    if prediction_value > 0.5:
        return "Spam"
    else:
        return "Ham"

# make a prediction for CNN
def preprocess_image(image):
    image = image.resize((299, 299))
    image_array = np.array(image)
    preprocessed_image = preprocess_input(image_array)

    return preprocessed_image


def make_prediction_cnn(image, image_model):
    img = image.resize((128, 128))
    img_array = np.array(img)
    img_array = img_array.reshape((1, img_array.shape[0], img_array.shape[1], img_array.shape[2]))

    preprocessed_image = preprocess_input(img_array)
    prediction = image_model.predict(preprocessed_image)

    if prediction > 0.5:
        st.write("Tumor Detected")
    else:
        st.write("No Tumor")

if task == "Sentiment Classification":
    st.subheader("Choose Model")
    model_choice = st.radio("Select Model", ["DNN (Email)", "RNN (Email)", "Perceptron (Email)", "Backpropagation (Email)","LSTM (Movie_Review)"])

    st.subheader("Text Input")
    text_input = st.text_area("Enter Text")

    if st.button("Predict"):
        # Preprocess the text
        preprocessed_text = preprocess_text(text_input)
        if model_choice == "DNN (Email)":
            if text_input:
                prediction_result = predict_dnn(text_input)
                st.write(f"The message is classified as: {prediction_result}")
        elif model_choice == "RNN (Email)":
            if text_input:
                prediction_result = predict_rnn(text_input)
                st.write(f"The message is classified as: {prediction_result}")
            else:
                st.write("Please enter some text for prediction")
        elif model_choice == "LSTM (Movie_Review)":
            if text_input:
                prediction_result = predict_lstm(text_input)
                st.write(f"The sentiment is: {prediction_result}")
            else:
                st.write("Please enter some text for prediction")
        elif model_choice == "Perceptron (Email)":
            if text_input:
                prediction_result = predict_perceptron(text_input)
                st.write(f"The message is classified as: {prediction_result}")
            else:
                st.write("Please enter some text for prediction")
        elif model_choice == "Backpropagation (Email)":
            if text_input:
                prediction_result = predict_backpropogation(text_input)
                st.write(f"The message is classified as: {prediction_result}")
            else:
                st.write("Please enter some text for prediction")
            
else:
    st.subheader("Choose Model")
    model_choice = st.radio("Select Model", ["CNN"])

    st.subheader("Image Input")
    image_input = st.file_uploader("Choose an image...", type="jpg")

    if image_input is not None:
        image = Image.open(image_input)
        st.image(image, caption="Uploaded Image.", use_column_width=True)

        # Preprocess the image
        preprocessed_image = preprocess_image(image)

        if st.button("Predict"):
            if model_choice == "CNN":
                make_prediction_cnn(image, image_model)