Ahtisham1583's picture
Update app.py
0f38151 verified
import gradio as gr
import numpy as np
import pickle
import tensorflow as tf
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.initializers import Orthogonal
from tensorflow.keras.optimizers import Adam
# Load the trained model
custom_objects = {'Orthogonal': Orthogonal, 'Adam': Adam}
model = load_model('sentiment_analysis_model.h5', custom_objects=custom_objects)
# Load the tokenizer
with open('tokenizer.pickle', 'rb') as handle:
tokenizer = pickle.load(handle)
# Define the max sequence length (as used during training)
max_seq_length = 100 # Adjust this based on your training setup
# Sentiment mapping
sentiment_mapping = {0: "Negative", 1: "Neutral", 2: "Positive"}
def classify_sentiment(text):
# Preprocess the text (tokenization, padding, etc.)
text_sequence = tokenizer.texts_to_sequences([text])
padded_sequence = pad_sequences(text_sequence, maxlen=max_seq_length)
# Make prediction using the trained model
prediction = model.predict(padded_sequence)
# Convert prediction to class label
predicted_label = np.argmax(prediction)
# Map class label to sentiment
sentiment = sentiment_mapping[predicted_label]
return sentiment
# Gradio interface
interface = gr.Interface(
fn=classify_sentiment,
inputs=gr.inputs.Textbox(lines=2, placeholder="Enter a sentence..."),
outputs="text",
title="Sentiment Analysis",
description="Enter a sentence to classify its sentiment."
)
if __name__ == "__main__":
interface.launch()