File size: 1,280 Bytes
1ed908c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useState, useEffect, useRef } from "react";
 
export function useGeoAIWorker() {
  const workerRef = useRef(null);
  const [isReady, setIsReady] = useState(false);
  const [isProcessing, setIsProcessing] = useState(false);
  const [result, setResult] = useState(null);
 
  useEffect(() => {
    workerRef.current = new Worker(new URL("./worker.js", import.meta.url));
 
    workerRef.current.onmessage = e => {
      const { type, payload } = e.data;
 
      switch (type) {
        case "ready":
          setIsReady(true);
          break;
        case "result":
          setResult(payload);
          setIsProcessing(false);
          break;
        case "error":
          console.error("Worker error:", payload);
          setIsProcessing(false);
          break;
      }
    };
 
    return () => workerRef.current?.terminate();
  }, []);
 
  const initialize = (tasks, providerParams) => {
    workerRef.current?.postMessage({
      type: "init",
      payload: { tasks, providerParams },
    });
  };
 
  const runInference = params => {
    if (!isReady) return;
    setIsProcessing(true);
    workerRef.current?.postMessage({
      type: "inference",
      payload: params,
    });
  };
 
  return { isReady, isProcessing, result, initialize, runInference };
}