File size: 2,297 Bytes
3a3dfd5
06d6eb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a3dfd5
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
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Sentiment check</title>
  <style>
    body { font-family: system-ui, sans-serif; max-width: 640px; margin: 2rem auto; padding: 0 16px; }
    textarea { width: 100%; box-sizing: border-box; font: inherit; padding: 8px; }
    button { margin-top: 8px; padding: 8px 16px; font: inherit; cursor: pointer; }
    pre { background: #f4f4f5; padding: 12px; border-radius: 6px; min-height: 3em; white-space: pre-wrap; }
    #status { color: #555; font-size: 0.9rem; }
  </style>
</head>
<body>
  <h1>Sentiment check</h1>
  <p id="status">Loading model...</p>
  <label for="text">Text</label>
  <textarea id="text" rows="4"></textarea>
  <button id="run" disabled>Classify</button>
  <h2>Response</h2>
  <pre id="output" data-ready="false"></pre>

  <script type="module">
    import { pipeline } from "https://cdn.jsdelivr.net/npm/@huggingface/transformers@4.3.1";

    const MODEL_ID = "Xenova/distilbert-base-uncased-finetuned-sst-2-english";
    const MAX_CHARS = 1000;
    const status = document.getElementById("status");
    const output = document.getElementById("output");
    const button = document.getElementById("run");

    const classifier = await pipeline("sentiment-analysis", MODEL_ID);
    status.textContent = "Model ready.";
    button.disabled = false;

    function preprocess(text) {
      if (typeof text !== "string" || !text.trim()) throw new Error("Please enter some text.");
      return text.replace(/\s+/g, " ").trim().slice(0, MAX_CHARS);
    }

    async function classify(text) {
      const cleaned = preprocess(text);
      const [result] = await classifier(cleaned);
      return {
        label: result.label.toLowerCase(),
        score: Math.round(result.score * 10000) / 10000,
        chars_used: cleaned.length,
      };
    }

    button.addEventListener("click", async () => {
      output.dataset.ready = "false";
      try {
        output.textContent = JSON.stringify(await classify(document.getElementById("text").value), null, 2);
      } catch (err) {
        output.textContent = JSON.stringify({ error: err.message }, null, 2);
      }
      output.dataset.ready = "true";
    });
  </script>
</body>
</html>