Spaces:
Running
Running
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Transformers.js Sentiment Analysis</title> | |
<style> | |
body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; } | |
textarea { width: 100%; height: 100px; } | |
button { margin-top: 10px; } | |
#result { margin-top: 20px; } | |
</style> | |
</head> | |
<body> | |
<h1>Transformers.js Sentiment Analysis</h1> | |
<textarea id="input" placeholder="Enter text for sentiment analysis">I love this movie! It's amazing!</textarea> | |
<button id="analyzeButton" disabled>Analyze Sentiment</button> | |
<div id="result"></div> | |
<script type="module"> | |
import { pipeline } from 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.5.0'; | |
let sentimentPipeline; | |
async function loadPipeline() { | |
try { | |
sentimentPipeline = await pipeline('sentiment-analysis'); | |
document.getElementById('analyzeButton').disabled = false; | |
} catch (error) { | |
console.error('Error loading pipeline:', error); | |
document.getElementById('result').innerHTML = `<p>Error: ${error.message}</p>`; | |
} | |
} | |
async function analyzeSentiment() { | |
const input = document.getElementById('input').value; | |
const result = document.getElementById('result'); | |
if (!input.trim()) { | |
result.innerHTML = '<p>Please enter some text to analyze.</p>'; | |
return; | |
} | |
result.innerHTML = '<p>Analyzing...</p>'; | |
try { | |
if (!sentimentPipeline) { | |
throw new Error('Pipeline not loaded. Please wait and try again.'); | |
} | |
// Perform sentiment analysis | |
const sentiment = await sentimentPipeline(input); | |
// Display the result | |
result.innerHTML = ` | |
<h3>Sentiment Analysis Result:</h3> | |
<p>Label: ${sentiment[0].label}</p> | |
<p>Score: ${sentiment[0].score.toFixed(4)}</p> | |
`; | |
} catch (error) { | |
console.error('Error during sentiment analysis:', error); | |
result.innerHTML = `<p>Error: ${error.message}</p>`; | |
} | |
} | |
// Load the pipeline when the page loads | |
loadPipeline(); | |
// Add event listener to the button | |
document.getElementById('analyzeButton').addEventListener('click', analyzeSentiment); | |
</script> | |
</body> | |
</html> |