AI powered React Components

Underlying Working

import { pipeline, PipelineType } from "@huggingface/transformers"; type PipelineModel = ReturnType<typeof pipeline>; class PipelineSingleton { static task = "sentiment-analysis" as PipelineType; static model = "Xenova/bert-base-multilingual-uncased-sentiment"; static instance: null | PipelineModel = null; // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type static async getInstance(progress_callback: Function | undefined) { if (this.instance === null) { console.log("Creating Instance"); this.instance = pipeline(this.task, this.model, { progress_callback }); } return this.instance; } }
// Listen for messages from the main thread self.addEventListener("message", async (event) => { console.log("Web worker received", event); (async function () { // Retrieve the classification pipeline. When called for the first time, // this will load the pipeline and save it for future use. const classifier = await PipelineSingleton.getInstance(() => {}); const result = await classifier(event.data.context); // 2. Run model prediction console.log("Service worker result", result); // Send the output back to the main thread self.postMessage({ status: "complete", output: result[0], }); })(); return true; });
const worker = useRef<Worker | null>(null); useEffect(() => { if (!worker.current) { // Create the worker if it does not yet exist. // worker.current = new MyWorker(); worker.current = new Worker( new URL("./worker/worker.ts", import.meta.url), { name: "worker", type: "module", } ); } // Create a callback function for messages from the worker thread. // eslint-disable-next-line @typescript-eslint/no-explicit-any const onMessageReceived = (event: any) => {}; // 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); }, []);
export default defineConfig({ // base: ".", plugins: [react(), libInjectCss()], build: { rollupOptions: { external: ["react", "react/jsx-runtime"], }, lib: { entry: { summarize: resolve( __dirname, "./src/components/Summarize/summarize.tsx" ), sentimentAnalysis: resolve( __dirname, "./src/components/SentimentAnalysis/useSentimentAnalysis.ts" ), }, formats: ["es"], }, }, });
"exports": { "./summarize": { "import": "./dist/summarize.js" }, "./sentimentAnalysis": { "import": "./dist/sentimentAnalysis.js" }, "./css": "./dist/style.css" },

Local Development

For running the components locally:

For Testing the components in s separate repo

For testing the components in a separate repo:

// example new URL( /* @vite-ignore */ "./assets/worker-2oVLSZZP.js", import.meta.url ),

Not done