File size: 1,248 Bytes
1db8d78
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
// 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;
});