import numpy as np import tensorflow as tf from tensorflow.keras.preprocessing.sequence import pad_sequences from sklearn.preprocessing import LabelEncoder import gradio as gr import pickle import matplotlib.pyplot as plt from matplotlib import cm import pandas as pd import time import json # 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"]) # Load sample data for examples sample_data = pd.read_csv("sentiment_dataset_1000.csv") def predict_sentiment(text, show_details=False): """ Predict sentiment with detailed analysis """ start_time = time.time() # Preprocess the text sequence = tokenizer.texts_to_sequences([text]) padded = pad_sequences(sequence, maxlen=50) # Make prediction prediction = model.predict(padded, verbose=0)[0] processing_time = time.time() - start_time predicted_class = np.argmax(prediction) sentiment = label_encoder.inverse_transform([predicted_class])[0] confidence = float(prediction[predicted_class]) # Create confidence dictionary confidences = { "Happy": float(prediction[0]), "Sad": float(prediction[1]), "Neutral": float(prediction[2]) } # Create visualization fig = create_confidence_plot(confidences) # Additional analysis word_count = len(text.split()) char_count = len(text) result = { "sentiment": sentiment, "confidence": round(confidence * 100, 2), "confidences": confidences, "processing_time": round(processing_time * 1000, 2), "word_count": word_count, "char_count": char_count, "plot": fig } return result def create_confidence_plot(confidences): """Create a beautiful confidence plot""" labels = list(confidences.keys()) values = list(confidences.values()) colors = cm.get_cmap('RdYlGn')(np.linspace(0.2, 0.8, len(labels))) fig, ax = plt.subplots(figsize=(8, 4)) bars = ax.barh(labels, values, color=colors) # Add value labels for bar in bars: width = bar.get_width() ax.text(width + 0.02, bar.get_y() + bar.get_height()/2, f'{width:.2%}', ha='left', va='center', fontsize=10) ax.set_xlim(0, 1) ax.set_title('Sentiment Confidence Scores', pad=20) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.grid(axis='x', linestyle='--', alpha=0.7) ax.set_facecolor('#f8f9fa') fig.patch.set_facecolor('#f8f9fa') return fig def get_sentiment_emoji(sentiment): """Get emoji for sentiment""" emojis = { "Happy": "😊", "Sad": "😢", "Neutral": "😐" } return emojis.get(sentiment, "") def analyze_text(text): """Main analysis function""" result = predict_sentiment(text) emoji = get_sentiment_emoji(result["sentiment"]) # Create HTML output html_output = f"""
Text: {text[:200]}{'...' if len(text) > 200 else ''}
Sentiment: {result['sentiment']}
Confidence: {result['confidence']}%
Processing Time: {result['processing_time']} ms
Word Count: {result['word_count']}
Character Count: {result['char_count']}