Skip to content

[Web] Cannot import from web worker #25096

Open
@GregCornis

Description

@GregCornis

Describe the issue

I have a working flow to run a segmentation model on pictures, and I'm trying to move this part of the code to a Web Worker. However, I have an error when creating the session, I believe because the dynamic import fails : WorkerGlobalScope.fetch: /_next/static/media/ort-wasm-simd-threaded.jsep.8296b855.wasm is not a valid URL.

Here is how I'm creating the Worker

  const analyser = useRef<Worker>(undefined);
  useEffect(
    () => { 
      const worker = new Worker(new URL("analyser.ts", import.meta.url)) 
      worker.onmessage = (e) => {
        console.log("Receive message from analyser", e.data);
      };
      worker.postMessage("Hi");
      analyser.current = worker;
      return () => {
        analyser.current?.terminate();
      };
    },
    []
  );

And here is the piece of code from analysis.ts that causes the problem

import { Tensor } from 'onnxruntime-web';
import * as ort from 'onnxruntime-web';
import { Jimp, JimpInstance } from "jimp";
import { Analysis } from "./utils";

self.onmessage = async (e) => {
  console.log("Analyser received", e.data);
  await runAnalysis(e.data, () => {}, () => {console.log("Analysis updated from worker")});
}

export async function runAnalysis(files: File[], setMask: (m: any) => void, setAnalysisResults: (m: Analysis[]) => void) {
  // BREAKS HERE
  const session = await ort.InferenceSession.create('/segmentation.onnx', { executionProviders: ['wasm'], graphOptimizationLevel: 'all' });
  console.log('Inference session created');

  for (const file of files) {
    const { resized, mask } = await runSegmentation(URL.createObjectURL(file), session);
    // SNIP
  }
}

The exact same code works when running not in a web worker, do you know what is happening ?

To reproduce

This is a very basic NextJS project, created with npx create-next-app@latest.
Then simply run npm install onnxruntime-web.
Create a analyse.ts file in the src directory.
Then edit the page.tsx's Home function to add the above code, which creates the Worker and posts a message.

Urgency

No response

ONNX Runtime Installation

Released Package

ONNX Runtime Version or Commit ID

onnxruntime-web@1.22.0

Execution Provider

'wasm'/'cpu' (WebAssembly CPU)

Metadata

Metadata

Assignees

No one assigned

    Labels

    platform:webissues related to ONNX Runtime web; typically submitted using template

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions