from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
# Load model and tokenizer
model_name = "tabularisai/robust-sentiment-analysis"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)
# Function to predict sentiment
def predict_sentiment(text):
inputs = tokenizer(text.lower(), return_tensors="pt", truncation=True, padding=True, max_length=512)
with torch.no_grad():
outputs = model(**inputs)
probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
predicted_class = torch.argmax(probabilities, dim=-1).item()
sentiment_map = {0: "Very Negative", 1: "Negative", 2: "Neutral", 3: "Positive", 4: "Very Positive"}
return sentiment_map[predicted_class]
# Example usage
texts = [
"I absolutely loved this movie! The acting was superb and the plot was engaging.",
"The service at this restaurant was terrible. I'll never go back.",
"The product works as expected. Nothing special, but it gets the job done.",
"I'm somewhat disappointed with my purchase. It's not as good as I hoped.",
"This book changed my life! I couldn't put it down and learned so much."
]
for text in texts:
sentiment = predict_sentiment(text)
print(f"Text: {text}")
print(f"Sentiment: {sentiment}\n")
1. "I absolutely loved this movie! The acting was superb and the plot was engaging."
Predicted Sentiment: Very Positive
2. "The service at this restaurant was terrible. I'll never go back."
Predicted Sentiment: Very Negative
3. "The product works as expected. Nothing special, but it gets the job done."
Predicted Sentiment: Neutral
4. "I'm somewhat disappointed with my purchase. It's not as good as I hoped."
Predicted Sentiment: Negative
5. "This book changed my life! I couldn't put it down and learned so much."
Predicted Sentiment: Very Positive
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tabularis Sentiment Analysis</title>
</head>
<body>
<div id="output"></div>
<script type="module">
import { AutoTokenizer, AutoModel, env } from 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.6.0';
env.allowLocalModels = false;
env.useCDN = true;
const MODEL_NAME = 'tabularisai/robust-sentiment-analysis';
function softmax(arr) {
const max = Math.max(...arr);
const exp = arr.map(x => Math.exp(x - max));
const sum = exp.reduce((acc, val) => acc + val);
return exp.map(x => x / sum);
}
async function analyzeSentiment() {
try {
const tokenizer = await AutoTokenizer.from_pretrained(MODEL_NAME);
const model = await AutoModel.from_pretrained(MODEL_NAME);
const texts = [
"I absolutely loved this movie! The acting was superb and the plot was engaging.",
"The service at this restaurant was terrible. I'll never go back.",
"The product works as expected. Nothing special, but it gets the job done.",
"I'm somewhat disappointed with my purchase. It's not as good as I hoped.",
"This book changed my life! I couldn't put it down and learned so much."
];
const output = document.getElementById('output');
for (const text of texts) {
const inputs = await tokenizer(text, { return_tensors: 'pt' });
const result = await model(inputs);
console.log('Model output:', result);
if (result.output && result.output.data) {
const logitsArray = Array.from(result.output.data);
console.log('Logits array:', logitsArray);
const probabilities = softmax(logitsArray);
const predicted_class = probabilities.indexOf(Math.max(...probabilities));
const sentimentMap = {
0: "Very Negative",
1: "Negative",
2: "Neutral",
3: "Positive",
4: "Very Positive"
};
const sentiment = sentimentMap[predicted_class];
const score = probabilities[predicted_class];
output.innerHTML += `Text: "${text}"<br>`;
output.innerHTML += `Sentiment: ${sentiment}, Score: ${score.toFixed(4)}<br><br>`;
} else {
console.error('Unexpected model output structure:', result);
output.innerHTML += `Unable to process: "${text}"<br><br>`;
}
}
} catch (error) {
console.error('Error:', error);
document.getElementById('output').innerHTML = 'An error occurred. Please check the console for details.';
}
}
analyzeSentiment();
</script>
</body>