| import gradio as gr | |
| from transformers import AutoModelForSequenceClassification, AutoTokenizer, AutoConfig | |
| import numpy as np | |
| from scipy.special import softmax | |
| def preprocess(text): | |
| new_text = [] | |
| for t in text.split(" "): | |
| t = '@user' if t.startswith('@') and len(t) > 1 else t | |
| t = 'http' if t.startswith('http') else t | |
| new_text.append(t) | |
| return " ".join(new_text) | |
| MODEL = "cardiffnlp/twitter-roberta-base-sentiment-latest" | |
| tokenizer = AutoTokenizer.from_pretrained(MODEL) | |
| config = AutoConfig.from_pretrained(MODEL) | |
| model = AutoModelForSequenceClassification.from_pretrained(MODEL, output_attentions=False, output_hidden_states=False) | |
| def predict_sentiment(text): | |
| text = preprocess(text) | |
| encoded_input = tokenizer(text, return_tensors='pt') | |
| output = model(**encoded_input) | |
| scores = output.logits[0].detach().numpy() | |
| scores = softmax(scores) | |
| ranking = np.argsort(scores)[::-1] | |
| results = [] | |
| for i in range(scores.shape[0]): | |
| label = config.id2label[ranking[i]] | |
| score = np.round(float(scores[ranking[i]]), 4) | |
| results.append(f"{label}: {score}") | |
| return "\n".join(results) | |
| examples = [ | |
| ["I feel happy!"], | |
| ["Had a lovely day at the park π³"], | |
| ["Feeling down after today's news π"], | |
| ["Just landed a new job, super excited!!"] | |
| ] | |
| footer_text = """ | |
| <b>About the Model</b><br> | |
| This sentiment analysis model is based on the roberta-base architecture and has been fine-tuned for sentiment analysis on tweets. For more information, check out the model's repository on Hugging Face: | |
| <a href="https://huggingface.co/cardiffnlp/twitter-roberta-base-sentiment-latest" target="_blank">cardiffnlp/twitter-roberta-base-sentiment-latest</a>. | |
| """ | |
| iface = gr.Interface(fn=predict_sentiment, | |
| inputs=gr.components.Textbox(lines=2, placeholder="Enter Text Here..."), | |
| outputs="text", | |
| title="Sentiment Analysis", | |
| description="This model predicts the sentiment of a given text. Enter text to see its sentiment.", | |
| examples=examples, | |
| article=footer_text) | |
| if __name__ == "__main__": | |
| iface.launch() | |