Spaces:
Running
on
Zero
Running
on
Zero
File size: 4,253 Bytes
ef71985 e766350 ef71985 7997069 e766350 88d5272 ef71985 f94dad6 e766350 a5c3607 88d5272 e766350 88d5272 e766350 88d5272 4565078 e766350 4565078 e766350 4565078 e766350 0e52f59 88d5272 4565078 0e52f59 88d5272 e766350 1c5142c e766350 88d5272 e766350 88d5272 0e52f59 88d5272 4565078 88d5272 e766350 88d5272 4565078 e766350 4565078 88d5272 0e52f59 e766350 88d5272 4565078 88d5272 4565078 88d5272 0e52f59 88d5272 0e52f59 1c5142c e766350 2b2e1ae 1c5142c 88d5272 4565078 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 |
import gradio as gr
import spaces
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
# Initialize device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# Load model and tokenizer
model_name = "tabularisai/robust-sentiment-analysis"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name).to(device)
# Define sentiment mapping
SENTIMENT_MAP = {
0: "Very Negative",
1: "Negative",
2: "Neutral",
3: "Positive",
4: "Very Positive"
}
@spaces.GPU
def analyze_sentiment(text, show_probabilities=False):
"""
Analyzes the sentiment of the input text.
"""
try:
# Preprocess text - convert to lowercase
text = text.lower()
# Tokenize and prepare input
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=512).to(device)
with torch.no_grad():
outputs = model(**inputs)
probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1).cpu().numpy()[0]
predicted_class = probabilities.argmax()
predicted_sentiment = SENTIMENT_MAP[predicted_class]
confidence = probabilities[predicted_class]
# Prepare the result with emoji indicators
sentiment_emojis = {
"Very Negative": "π‘",
"Negative": "π",
"Neutral": "π",
"Positive": "π",
"Very Positive": "π€©"
}
result = f"**{sentiment_emojis[predicted_sentiment]} Overall Sentiment: {predicted_sentiment}**\n"
result += f"Confidence: {confidence:.2%}\n\n"
if show_probabilities:
result += "### Detailed Analysis:\n"
for cls, prob in zip(SENTIMENT_MAP.values(), probabilities):
emoji = sentiment_emojis[cls]
result += f"{emoji} {cls}: {prob:.2%}\n"
return result
except Exception as e:
return f"An error occurred during sentiment analysis: {str(e)}"
# Create Gradio interface using Blocks for better layout control
with gr.Blocks(theme=gr.themes.Soft()) as demo:
gr.Markdown("# π Sentiment Analysis Wizard")
gr.Markdown(
"""
Discover the emotional tone behind any text with our advanced AI model! This app uses a state-of-the-art language model to analyze the sentiment of your text, classifying it into one of five categories: **Very Negative**, **Negative**, **Neutral**, **Positive**, or **Very Positive**.
"""
)
with gr.Row():
with gr.Column(scale=2):
input_text = gr.Textbox(
lines=10,
placeholder="Enter text for sentiment analysis...",
label="βοΈ Input Text"
)
with gr.Row():
show_probs = gr.Checkbox(
label="π― Show probabilities for each class",
value=False
)
analyze_button = gr.Button("β¨ Analyze Sentiment", variant="primary")
with gr.Column(scale=1):
output = gr.Markdown(label="Result")
with gr.Accordion("π Examples", open=False):
examples = [
["I absolutely loved this movie! The acting was superb and the plot was engaging.", True],
["The service at this restaurant was terrible. I'll never go back.", False],
["The product works as expected. Nothing special, but it gets the job done.", True],
["I'm somewhat disappointed with my purchase. It's not as good as I hoped.", False],
["This book changed my life! I couldn't put it down and learned so much.", True]
]
gr.Examples(
examples=examples,
inputs=[input_text, show_probs],
label="Try these examples"
)
analyze_button.click(
fn=analyze_sentiment,
inputs=[input_text, show_probs],
outputs=output
)
gr.Markdown(
"""
---
**Developed by tabularis.ai with β€οΈ using Gradio and Transformers by Hugging Face**
"""
)
# Launch the interface
demo.launch() |