File size: 6,849 Bytes
85a4687 daa5539 85a4687 daa5539 85a4687 daa5539 85a4687 0b82ec0 85a4687 daa5539 85a4687 daa5539 85a4687 0b82ec0 85a4687 0b82ec0 85a4687 daa5539 85a4687 0b82ec0 85a4687 daa5539 85a4687 daa5539 85a4687 daa5539 85a4687 daa5539 |
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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 |
import { useState, useRef, useEffect, useCallback } from "react";
import { ClassificationOutput, SentimentAnalysisWorkerInput, WorkerMessage } from "../types";
const PLACEHOLDER_TEXTS: string[] = [
"I absolutely love this product! It exceeded all my expectations.",
"This is the worst purchase I've ever made. Complete waste of money.",
"The service was okay, nothing special but not terrible either.",
"Amazing quality and fast delivery. Highly recommended!",
"I'm not sure how I feel about this. It's decent but could be better.",
"Terrible customer service. They were rude and unhelpful.",
"Great value for money. I'm very satisfied with my purchase.",
"The product arrived damaged and the return process was a nightmare.",
"Pretty good overall. A few minor issues but mostly positive experience.",
"Outstanding! This company really knows how to treat their customers.",
].sort(() => Math.random() - 0.5);
function SentimentAnalysis() {
const [text, setText] = useState<string>(PLACEHOLDER_TEXTS.join("\n"));
const [results, setResults] = useState<ClassificationOutput[]>([]);
const [status, setStatus] = useState<string>("idle");
const [progress, setProgress] = useState<number>(0);
// Create a reference to the worker object.
const worker = useRef<Worker | null>(null);
// We use the `useEffect` hook to setup the worker as soon as the component is mounted.
useEffect(() => {
if (!worker.current) {
// Create the worker if it does not yet exist.
worker.current = new Worker(
new URL("../workers/sentiment-analysis.js", import.meta.url),
{
type: "module",
}
);
}
// Create a callback function for messages from the worker thread.
const onMessageReceived = (e: MessageEvent<WorkerMessage>) => {
const status = e.data.status;
if (status === "initiate") {
setStatus("loading");
} else if (status === "ready") {
setStatus("ready");
} else if (status === "progress") {
setStatus("progress");
if (e.data.output.progress && (e.data.output.file as string).startsWith('onnx'))
setProgress(e.data.output.progress)
} else if (status === "output") {
const result = e.data.output!;
setResults((prevResults) => [...prevResults, result]);
} else if (status === "complete") {
setStatus("idle");
setProgress(100)
}
};
// Attach the callback function as an event listener.
worker.current.addEventListener("message", onMessageReceived);
// Define a cleanup function for when the component is unmounted.
return () =>
worker.current?.removeEventListener("message", onMessageReceived);
}, []);
const classify = useCallback(() => {
setStatus("processing");
setResults([]); // Clear previous results
const message: SentimentAnalysisWorkerInput = { text };
worker.current?.postMessage(message);
}, [text]);
const busy: boolean = status !== "idle";
const handleClear = (): void => {
setResults([]);
};
const getSentimentColor = (label: string): string => {
switch (label.toLowerCase()) {
case "positive":
case "label_2":
return "bg-green-100 border-green-300";
case "negative":
case "label_0":
return "bg-red-100 border-red-300";
case "neutral":
case "label_1":
return "bg-yellow-100 border-yellow-300";
default:
return "bg-gray-100 border-gray-300";
}
};
const formatLabel = (label: string): string => {
switch (label) {
case "LABEL_0":
return "Negative";
case "LABEL_1":
return "Neutral";
case "LABEL_2":
return "Positive";
default:
return label;
}
};
return (
<div className="flex flex-col h-screen w-screen p-4">
<h1 className="text-2xl font-bold mb-4">Text Classification</h1>
<div className="flex flex-col lg:flex-row gap-4 h-full">
{/* Input Section */}
<div className="flex flex-col w-full lg:w-1/2">
<label className="text-lg font-medium mb-2">Input Text:</label>
<textarea
className="border border-gray-300 rounded p-3 flex-grow resize-none"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Enter text to classify (one per line)..."
/>
<div className="flex gap-2 mt-4">
<button
className="flex-1 py-2 px-4 bg-blue-500 hover:bg-blue-600 rounded text-white font-medium disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
disabled={busy}
onClick={classify}
>
{!busy
? "Classify Text"
: status === "loading"
? "Model loading..."
: "Processing..."}
</button>
{ status === "progress" &&
<div className="text-sm font-medium">
{progress}%
</div>
}
<button
className="py-2 px-4 bg-gray-500 hover:bg-gray-600 rounded text-white font-medium transition-colors"
onClick={handleClear}
>
Clear Results
</button>
</div>
</div>
{/* Results Section */}
<div className="flex flex-col w-full lg:w-1/2">
<label className="text-lg font-medium mb-2">
Classification Results ({results.length}):
</label>
<div className="border border-gray-300 rounded p-3 flex-grow overflow-y-auto">
{results.length === 0 ? (
<div className="text-gray-500 text-center py-8">
No results yet. Click "Classify Text" to analyze your input.
</div>
) : (
<div className="space-y-3">
{results.map((result, index) => (
<div
key={index}
className={`p-3 rounded border-2 ${getSentimentColor(result.labels[0])}`}
>
<div className="flex justify-between items-start mb-2">
<span className="font-semibold text-sm">
{formatLabel(result.labels[0])}
</span>
<span className="text-sm font-mono">
{(result.scores[0] * 100).toFixed(1)}%
</span>
</div>
<div className="text-sm text-gray-700">
{result.sequence}
</div>
</div>
))}
</div>
)}
</div>
</div>
</div>
</div>
);
}
export default SentimentAnalysis;
|