import time import nltk from nltk.sentiment import SentimentIntensityAnalyzer import gradio as gr from transformers import AutoTokenizer from transformers import AutoModelForSequenceClassification from scipy.special import softmax import nltk import matplotlib.pyplot as plt nltk.download('vader_lexicon') sia = nltk.sentiment.SentimentIntensityAnalyzer() def sentiment_analyzer(text, model_name): positive_score = 0.0 negative_score = 0.0 if model_name == "Vader": sentiment_score = sia.polarity_scores(text) positive_score = sentiment_score['pos'] negative_score = sentiment_score['neg'] elif model_name == "RoBERTa": MODEL = f"cardiffnlp/twitter-roberta-base-sentiment" tokenizer = AutoTokenizer.from_pretrained(MODEL) model = AutoModelForSequenceClassification.from_pretrained(MODEL) encoded_text = tokenizer(text, return_tensors='pt') output = model(**encoded_text) scores = output[0][0].detach().numpy() scores = softmax(scores) scores_dict = { 'roberta_neg' : scores[0], 'roberta_neu' : scores[1], 'roberta_pos' : scores[2] } positive_score = float(scores[2]) negative_score = float(scores[0]) # print(f"Output positive score: {positive_score}") # print(f"Output negative score: {negative_score}") return positive_score, negative_score sentiment_analyzer("I am a goog human being","RoBERTa") input_text = gr.inputs.Textbox(lines=15, label="Input Text") sentiment_model = gr.inputs.Radio(["Vader", "RoBERTa"], label="Choose Sentiment Analyzer") outputs = [gr.Slider(minimum=0, maximum=1, step=0.01, label="Positive Sentiment"), gr.Slider(minimum=0, maximum=1, step=0.01, label="Negative Sentiment")] iface = gr.Interface(fn=sentiment_analyzer, inputs=[input_text, sentiment_model], outputs=outputs) print(time.time()) iface.launch(inline=False)