sentiment / app.py
Amiruzzaman's picture
Update app.py
2ea0633 verified
import streamlit as st
import numpy as np
from tensorflow.keras.models import load_model
import pickle
from tensorflow.keras.preprocessing.sequence import pad_sequences
# Load the model and tokenizer
model = load_model('sentiment_model.h5')
with open('tokenizer.pkl', 'rb') as file:
tokenizer = pickle.load(file)
with open('label_map.pkl', 'rb') as file:
label_map = pickle.load(file)
def preprocess_text(text, tokenizer, max_len):
sequence = tokenizer.texts_to_sequences([text])
padded_sequence = pad_sequences(sequence, maxlen=max_len)
return padded_sequence
def predict_sentiment(text, model, tokenizer, max_len, label_map):
processed_text = preprocess_text(text, tokenizer, max_len)
prediction = model.predict(processed_text)
predicted_class = np.argmax(prediction, axis=1)[0]
predicted_label = label_map[predicted_class]
return predicted_label
# Streamlit app
def main():
st.title("Sentiment Analysis")
st.write("Enter a text to predict its sentiment.")
# Input text from user
input_text = st.text_area("Input Text", "Type your text here...")
if st.button("Predict Sentiment"):
if input_text:
max_len = 100 # Set this to the max length used during training
sentiment = predict_sentiment(input_text, model, tokenizer, max_len, label_map)
st.write(f"The predicted sentiment for the text is: **{sentiment}**")
else:
st.write("Please enter some text to analyze.")
st.header("Sample Texts")
st.write("<span style='color:green; font-weight:bold'>Positive:</span> Going to finish up Borderlands 2 today.", unsafe_allow_html=True)
st.write("<span style='color:yellow; font-weight:bold'>Neutral:</span> Check out this epic streamer", unsafe_allow_html=True)
st.write("<span style='color:red; font-weight:bold'>Negative:</span> The biggest disappointment of my life came a year ago.", unsafe_allow_html=True)
st.write("<span style='color:cyan; font-weight:bold'>Irrelevant:</span> Stupid 19-year-olds who write bad poetry need to get away from the computer and talk to real people who don't believe in vampires.", unsafe_allow_html=True)
if __name__ == "__main__":
main()