CoolFace
Apppublic

rasmodev/Covid19_Tweet_Sentiment_Analysis_App

sourceHugging Facemitupdated 2y agoView on Hugging Face
0likes
app.py94 linesDownload Raw Back to root
1# Import the key libraries2import gradio as gr3import torch4from transformers import AutoTokenizer, AutoModelForSequenceClassification5from scipy.special import softmax6import nltk7import re8from nltk.corpus import stopwords9from nltk.stem import WordNetLemmatizer10 11 12# Download NLTK resources (if not already downloaded)13nltk.download('stopwords')14nltk.download('wordnet')15 16# Load the tokenizer and model from Hugging Face17model_path = "rasmodev/Covid-19_Sentiment_Analysis_RoBERTa_Model"18tokenizer = AutoTokenizer.from_pretrained(model_path)19model = AutoModelForSequenceClassification.from_pretrained(model_path)20 21# Preprocess text (username and link placeholders, and text preprocessing)22def preprocess(text):23    # Convert text to lowercase24    text = text.lower()25 26    # Remove special characters, numbers, and extra whitespaces27    text = re.sub(r'[^a-zA-Z\s]', '', text)28 29    # Remove stopwords (common words that don't carry much meaning)30    stop_words = set(stopwords.words('english'))31    words = text.split()  # Split text into words32    words = [word for word in words if word not in stop_words]33 34    # Lemmatize words to their base form35    lemmatizer = WordNetLemmatizer()36    words = [lemmatizer.lemmatize(word) for word in words]37 38    # Rejoin the preprocessed words into a single string39    processed_text = ' '.join(words)40 41    # Process placeholders42    new_text = []43    for t in processed_text.split(" "):44        t = '@user' if t.startswith('@') and len(t) > 1 else t45        t = 'http' if t.startswith('http') else t46        new_text.append(t)47 48    return " ".join(new_text)49 50# Perform sentiment analysis51def sentiment_analysis(text):52    text = preprocess(text)53 54    # Tokenize input text55    inputs = tokenizer(text, return_tensors='pt')56 57    # Forward pass through the model58    with torch.no_grad():59        outputs = model(**inputs)60 61    # Get predicted probabilities62    scores_ = outputs.logits[0].detach().numpy()63    scores_ = softmax(scores_)64 65    # Define labels and corresponding colors66    labels = ['Negative', 'Neutral', 'Positive']67    colors = ['red', 'yellow', 'green']68    font_colors = ['white', 'black', 'white']69 70    # Find the label with the highest percentage71    max_label = labels[scores_.argmax()]72    max_percentage = scores_.max() * 10073 74    # Create HTML for the label with the specified style75    label_html = f'<div style="display: flex; justify-content: center;"><button style="text-align: center; font-size: 16px; padding: 10px; border-radius: 15px; background-color: {colors[labels.index(max_label)]}; color: {font_colors[labels.index(max_label)]};">{max_label}({max_percentage:.2f}%)</button></div>'76 77    return label_html78 79# Create a Gradio interface80interface = gr.Interface(81    fn=sentiment_analysis,82    inputs=gr.Textbox(placeholder="Write your tweet here..."),83    outputs=gr.HTML(),84    title="COVID-19 Sentiment Analysis App",85    description="This App Analyzes the sentiment of COVID-19 related tweets. Negative: Indicates a negative sentiment, Neutral: Indicates a neutral sentiment, Positive: Indicates a positive sentiment.",86    theme="default",87    examples=[88        ["Covid vaccines are irrelevant"],89        ["The Vaccine is Good I have had no issues!"]90    ]91)92 93# Launch the Gradio app94interface.launch()