your-repo-name / sentiment.py
shivaji
Upload sentiment.py
0a53d3b verified
## This code runs successfully thanks to geeksforgeeks
from transformers import BertTokenizer, TFBertForSequenceClassification
import os
# import shutil
# import tarfile
import tensorflow as tf
from transformers import BertTokenizer, TFBertForSequenceClassification
import pandas as pd
# from bs4 import BeautifulSoup
import re
# import matplotlib.pyplot as plt
# import plotly.express as px
# import plotly.offline as pyo
# import plotly.graph_objects as go
# from wordcloud import WordCloud, STOPWORDS
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import streamlit as st
path = 'path-to-save'
bert_tokenizer = BertTokenizer.from_pretrained(path +'/Tokenizer')
# Load model
bert_model = TFBertForSequenceClassification.from_pretrained(path +'/Model')
def Get_sentiment(Review, Tokenizer=bert_tokenizer, Model=bert_model):
# Convert Review to a list if it's not already a list
if not isinstance(Review, list):
Review = [Review]
Input_ids, Token_type_ids, Attention_mask = Tokenizer.batch_encode_plus(Review,
padding=True,
truncation=True,
max_length=128,
return_tensors='tf').values()
prediction = Model.predict([Input_ids, Token_type_ids, Attention_mask])
# Use argmax along the appropriate axis to get the predicted labels
pred_labels = tf.argmax(prediction.logits, axis=1)
label = {
1: 'positive',
0: 'Negative'
}
# Convert the TensorFlow tensor to a NumPy array and then to a list to get the predicted sentiment labels
pred_labels = [label[i] for i in pred_labels.numpy().tolist()]
return pred_labels
# Review ='''Bahubali is a blockbuster Indian movie that was released in 2015.
# It is the first part of a two-part epic saga that tells the story of a legendary hero who fights for his kingdom and his love.
# The movie has received rave reviews from critics and audiences alike for its stunning visuals,
# spectacular action scenes, and captivating storyline.'''
Review= st.text_area('Input your text')
if Review:
sentiment_labels = Get_sentiment(Review)
print(sentiment_labels)
st.write(sentiment_labels,Review)