|
|
|
<!DOCTYPE html> |
|
<html lang="en"> |
|
<head> |
|
<meta charset="UTF-8"> |
|
<meta name="viewport" content="width=device-width, initial-scale=1.0"> |
|
<title>Transformer Sentiment Analyzer</title> |
|
<link rel="stylesheet" href="style.css"> |
|
</head> |
|
<body> |
|
<header> |
|
<h1>Transformer Sentiment Analyzer</h1> |
|
</header> |
|
<main class="container"> |
|
<form id="analyze-form"> |
|
<label for="inputText">Enter text to analyze:</label> |
|
<textarea id="inputText" name="inputText" rows="4" placeholder="Type your text here..." required aria-required="true"></textarea> |
|
<button type="submit" id="analyzeButton">Analyze Sentiment</button> |
|
</form> |
|
<section id="result" aria-live="polite"></section> |
|
</main> |
|
<script type="module" src="index.js"></script> |
|
</body> |
|
</html> |
|
``` |
|
```javascript |
|
// index.js |
|
import { pipeline } from 'https://cdn.jsdelivr.net/npm/@xenova/transformers'; |
|
|
|
const analyzeForm = document.getElementById('analyze-form'); |
|
const inputText = document.getElementById('inputText'); |
|
const resultSection = document.getElementById('result'); |
|
const analyzeButton = document.getElementById('analyzeButton'); |
|
|
|
let sentimentPipeline; |
|
|
|
async function initPipeline() { |
|
analyzeButton.disabled = true; |
|
analyzeButton.textContent = 'Loading model...'; |
|
sentimentPipeline = await pipeline('sentiment-analysis'); |
|
analyzeButton.textContent = 'Analyze Sentiment'; |
|
analyzeButton.disabled = false; |
|
} |
|
|
|
analyzeForm.addEventListener('submit', async (event) => { |
|
event.preventDefault(); |
|
const text = inputText.value.trim(); |
|
if (!text) return; |
|
|
|
analyzeButton.disabled = true; |
|
analyzeButton.textContent = 'Analyzing...'; |
|
resultSection.textContent = ''; |
|
|
|
try { |
|
const output = await sentimentPipeline(text); |
|
const { label, score } = output[0]; |
|
resultSection.textContent = `Sentiment: ${label} (Confidence: ${(score * 100).toFixed(2)}%)`; |
|
} catch (error) { |
|
resultSection.textContent = 'Error analyzing sentiment.'; |
|
} |
|
|
|
analyzeButton.textContent = 'Analyze Sentiment'; |
|
analyzeButton.disabled = false; |
|
}); |
|
|
|
initPipeline(); |