marcuskeenton's picture
Add sentiment demo, integration tests and README
06d6eb0 verified
Raw History Blame Contribute Delete
2.3 kB
<!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>