import { useState, useRef, useEffect, useCallback } from 'react'; import { ClassificationOutput, TextClassificationWorkerInput, WorkerMessage } from '../types'; import { useModel } from '../contexts/ModelContext'; 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 TextClassification() { const [text, setText] = useState(PLACEHOLDER_TEXTS.join('\n')); const [results, setResults] = useState([]); const { setProgress, status, setStatus, setModel } = useModel(); setModel('Xenova/bert-base-multilingual-uncased-sentiment') // Create a reference to the worker object. const worker = useRef(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/text-classification.js', import.meta.url), { type: 'module' } ); } // Create a callback function for messages from the worker thread. const onMessageReceived = (e: MessageEvent) => { 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') { setStatus('output'); const result = e.data.output!; setResults((prevResults) => [...prevResults, result]); console.log(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: TextClassificationWorkerInput = { text }; worker.current?.postMessage(message); }, [text]); const busy: boolean = status !== 'idle'; const handleClear = (): void => { setResults([]); }; return (

Text Classification

{/* Input Section */}