Spaces:
Sleeping
Sleeping
import numpy as np | |
import pandas as pd | |
import tensorflow as tf | |
from tensorflow.keras.preprocessing.text import Tokenizer | |
from tensorflow.keras.preprocessing.sequence import pad_sequences | |
from sklearn.preprocessing import LabelEncoder | |
import gradio as gr | |
import pickle | |
import os | |
# Load model and tokenizer | |
model = tf.keras.models.load_model('sentiment_rnn.h5') | |
# Load tokenizer | |
with open('tokenizer.pkl', 'rb') as f: | |
tokenizer = pickle.load(f) | |
# Initialize label encoder | |
label_encoder = LabelEncoder() | |
label_encoder.fit(["Happy", "Sad", "Neutral"]) | |
def predict_sentiment(text): | |
""" | |
Predict sentiment for a given text | |
""" | |
# Preprocess the text | |
sequence = tokenizer.texts_to_sequences([text]) | |
padded = pad_sequences(sequence, maxlen=50) | |
# Make prediction | |
prediction = model.predict(padded, verbose=0)[0] | |
predicted_class = np.argmax(prediction) | |
sentiment = label_encoder.inverse_transform([predicted_class])[0] | |
confidence = float(prediction[predicted_class]) | |
# Create confidence dictionary for all classes | |
confidences = { | |
"Happy": float(prediction[0]), | |
"Sad": float(prediction[1]), | |
"Neutral": float(prediction[2]) | |
} | |
return sentiment, confidences | |
# Create Gradio interface | |
with gr.Blocks(title="Sentiment Analysis with RNN") as demo: | |
gr.Markdown("# Sentiment Analysis with RNN") | |
gr.Markdown("Enter text to analyze its sentiment (Happy, Sad, or Neutral)") | |
with gr.Row(): | |
text_input = gr.Textbox(label="Input Text", placeholder="Type your text here...") | |
sentiment_output = gr.Label(label="Predicted Sentiment") | |
confidence_output = gr.Label(label="Confidence Scores") | |
submit_btn = gr.Button("Analyze Sentiment") | |
examples = gr.Examples( | |
examples=[ | |
["I'm feeling great today!"], | |
["My dog passed away..."], | |
["The office is closed tomorrow."], | |
["This is the best day ever!"], | |
["I feel miserable."], | |
["There are 12 books on the shelf."] | |
], | |
inputs=text_input | |
) | |
def analyze_text(text): | |
sentiment, confidences = predict_sentiment(text) | |
return sentiment, confidences | |
submit_btn.click( | |
fn=analyze_text, | |
inputs=text_input, | |
outputs=[sentiment_output, confidence_output] | |
) | |
text_input.submit( | |
fn=analyze_text, | |
inputs=text_input, | |
outputs=[sentiment_output, confidence_output] | |
) | |
# Launch the app | |
if __name__ == "__main__": | |
demo.launch() |