File size: 2,081 Bytes
03bbb65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!-- index.html -->
<!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();