Spaces:
Sleeping
Sleeping
File size: 2,583 Bytes
8e5b86d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
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() |