From c9de1e71a9b5cfc620ee9c553110c514df7f9671 Mon Sep 17 00:00:00 2001 From: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> Date: Tue, 17 Mar 2026 00:45:08 -0700 Subject: [PATCH 1/4] docs: add Svelte tutorial for Transformers.js Add a step-by-step tutorial showing how to build a multilingual translation app using Svelte and Vite with Transformers.js. The tutorial mirrors the existing React tutorial structure and covers project setup, Web Worker usage for ML inference, UI components, and deployment to Hugging Face Spaces. Closes #171 --- .../transformers/docs/source/_toctree.yml | 2 + .../docs/source/tutorials/svelte.md | 483 ++++++++++++++++++ 2 files changed, 485 insertions(+) create mode 100644 packages/transformers/docs/source/tutorials/svelte.md diff --git a/packages/transformers/docs/source/_toctree.yml b/packages/transformers/docs/source/_toctree.yml index 76d779249..3fc96818d 100644 --- a/packages/transformers/docs/source/_toctree.yml +++ b/packages/transformers/docs/source/_toctree.yml @@ -13,6 +13,8 @@ title: Building a Vanilla JS Application - local: tutorials/react title: Building a React Application + - local: tutorials/svelte + title: Building a Svelte Application - local: tutorials/next title: Building a Next.js Application - local: tutorials/browser-extension diff --git a/packages/transformers/docs/source/tutorials/svelte.md b/packages/transformers/docs/source/tutorials/svelte.md new file mode 100644 index 000000000..39e5c5fdb --- /dev/null +++ b/packages/transformers/docs/source/tutorials/svelte.md @@ -0,0 +1,483 @@ +# Building a Svelte application + +In this tutorial, we'll be building a simple [Svelte](https://svelte.dev/) application that performs multilingual translation using Transformers.js! The final product will look something like this: + +![Demo](https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/react-translator-demo.gif) + +Useful links: + +- [Source code](https://github.com/huggingface/transformers.js/tree/main/examples/svelte-translator) + +## Prerequisites + +- [Node.js](https://nodejs.org/en/) version 18+ +- [npm](https://www.npmjs.com/) version 9+ + +## Step 1: Initialise the project + +For this tutorial, we will use [Vite](https://vitejs.dev/) to initialise our project. Vite is a build tool that allows us to quickly set up a Svelte application with minimal configuration. Run the following command in your terminal: + +```bash +npm create vite@latest svelte-translator -- --template svelte +``` + +If prompted to install `create-vite`, type y and press Enter. + +Next, enter the project directory and install the necessary development dependencies: + +```bash +cd svelte-translator +npm install +``` + +To test that our application is working, we can run the following command: + +```bash +npm run dev +``` + +Visiting the URL shown in the terminal (e.g., [http://localhost:5173/](http://localhost:5173/)) should show the default "Svelte + Vite" landing page. +You can stop the development server by pressing Ctrl + C in the terminal. + +## Step 2: Install and configure Transformers.js + +Now we get to the fun part: adding machine learning to our application! First, install Transformers.js from [NPM](https://www.npmjs.com/package/@huggingface/transformers) with the following command: + +```bash +npm install @huggingface/transformers +``` + +For this application, we will use the [Xenova/nllb-200-distilled-600M](https://huggingface.co/Xenova/nllb-200-distilled-600M) model, which can perform multilingual translation among 200 languages. Before we start, there are 2 things we need to take note of: + +1. ML inference can be quite computationally intensive, so it's better to load and run the models in a separate thread from the main (UI) thread. +2. Since the model is quite large (>1 GB), we don't want to download it until the user clicks the "Translate" button. + +We can achieve both of these goals by using a [Web Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers). + +Create a file called `worker.js` in the `src` directory. This script will do all the heavy-lifting for us, including loading and running of the translation pipeline. To ensure the model is only loaded once, we will create the `MyTranslationPipeline` class which uses the [singleton pattern](https://en.wikipedia.org/wiki/Singleton_pattern) to lazily create a single instance of the pipeline when `getInstance` is first called, and use this pipeline for all subsequent calls: + +```javascript +import { pipeline, TextStreamer } from "@huggingface/transformers"; + +class MyTranslationPipeline { + static task = "translation"; + static model = "Xenova/nllb-200-distilled-600M"; + static instance = null; + + static async getInstance(progress_callback = null) { + this.instance ??= pipeline(this.task, this.model, { progress_callback }); + return this.instance; + } +} +``` + +## Step 3: Design the user interface + + + +We recommend starting the development server again with `npm run dev` +(if not already running) so that you can see your changes in real-time. + + + +First, let's create some child components. Create a folder called `lib` in the `src` directory, and create the following files: + +1. `LanguageSelector.svelte`: This component will allow the user to select the input and output languages. Check out the full list of languages [here](https://github.com/huggingface/transformers.js-examples/tree/main/react-translator/src/components/LanguageSelector.jsx). + + ```svelte + + +
+ + +
+ ``` + +2. `Progress.svelte`: This component will display the progress for downloading each model file. + + ```svelte + + +
+
+ {text} ({percentage.toFixed(2)}%) +
+
+ ``` + +Now let's update `App.svelte` in the `src` directory. Replace its contents with the following, which sets up our state variables and renders the UI: + +```svelte + + +
+

Transformers.js

+

ML-powered multilingual translation in Svelte!

+ +
+
+ sourceLanguage = e.target.value} + /> + targetLanguage = e.target.value} + /> +
+ +
+ + +
+
+ + + +
+ {#if ready === false} + + {/if} + {#each progressItems as data (data.file)} +
+ +
+ {/each} +
+
+``` + +Don't worry about the `translate` function for now. We will define it in the next section. + +Next, let's add some CSS to make our app look a little nicer. Modify the following files in the `src` directory: + +1. `app.css`: +
+ View code + + ```css + :root { + font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; + line-height: 1.5; + font-weight: 400; + color: #213547; + background-color: #ffffff; + + font-synthesis: none; + text-rendering: optimizeLegibility; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + -webkit-text-size-adjust: 100%; + } + + body { + margin: 0; + display: flex; + place-items: center; + min-width: 320px; + min-height: 100vh; + } + + h1 { + font-size: 3.2em; + line-height: 1; + } + + h1, + h2 { + margin: 8px; + } + + select { + padding: 0.3em; + cursor: pointer; + } + + textarea { + padding: 0.6em; + } + + button { + padding: 0.6em 1.2em; + cursor: pointer; + font-weight: 500; + } + + button[disabled] { + cursor: not-allowed; + } + + select, + textarea, + button { + border-radius: 8px; + border: 1px solid transparent; + font-size: 1em; + font-family: inherit; + background-color: #f9f9f9; + transition: border-color 0.25s; + } + + select:hover, + textarea:hover, + button:not([disabled]):hover { + border-color: #646cff; + } + + select:focus, + select:focus-visible, + textarea:focus, + textarea:focus-visible, + button:focus, + button:focus-visible { + outline: 4px auto -webkit-focus-ring-color; + } + ``` + +
+ +2. Add the following styles. You can either put them in `app.css` or in a ` +``` + +The `translate` function is just a placeholder for now. We will replace it in the next section. Some styles use `:global(...)` because styles in Svelte components are scoped, and those selectors target elements inside the child components. ## Step 4: Connecting everything together Now that we have a basic user interface set up, we can finally connect everything together. -First, let's set up the Web Worker and the `translate` function. Add the following to the ` ``` -Now, let's add an event listener in `src/worker.js` to listen for messages from the main thread. We will send back messages (e.g., for model loading progress and text streaming) to the main thread with `self.postMessage`. +SvelteKit server-renders pages by default, so creating the worker inside `onMount` keeps it browser-only and avoids running Web Worker code during SSR. + +Now, let's add an event listener in `src/routes/worker.js` to listen for messages from the main thread. We will send back messages (e.g., for model loading progress and text streaming) to the main thread with `self.postMessage`. ```javascript // Listen for messages from the main thread @@ -473,11 +469,12 @@ You can now run the application with `npm run dev` and perform multilingual tran ## (Optional) Step 5: Build and deploy -To build your application, simply run `npm run build`. This will bundle your application and output the static files to the `dist` folder. +To build your application, run `npm run build`. You can then run `npm run preview` to preview the production build locally. For this demo, we will deploy our application as a static [Hugging Face Space](https://huggingface.co/docs/hub/spaces), but you can deploy it anywhere you like! If you haven't already, you can create a free Hugging Face account [here](https://huggingface.co/join). 1. Visit [https://huggingface.co/new-space](https://huggingface.co/new-space) and fill in the form. Remember to select "Static" as the space type. -2. Go to "Files" → "Add file" → "Upload files". Drag the `index.html` file and `public/` folder from the `dist` folder into the upload box and click "Upload". After they have uploaded, scroll down to the button and click "Commit changes to main". +2. SvelteKit's default adapter does not create a `dist` folder for static hosting. To deploy this as a Static Space, configure [`@sveltejs/adapter-static`](https://svelte.dev/docs/kit/adapter-static), then run `npm run build`. +3. Go to "Files" → "Add file" → "Upload files". Drag the files generated by the static adapter into the upload box and click "Upload". After they have uploaded, scroll down to the button and click "Commit changes to main". **That's it!** Your application should now be live at `https://huggingface.co/spaces//`! From 55dea85c891c295e638c444d0536c43e2e770a43 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 16 Aug 2026 20:10:33 +0000 Subject: [PATCH 4/4] docs: update Svelte tutorial for v5 runes and progress_total - Migrate to Svelte 5 runes: $props(), $state(), onevent handlers - Replace onDestroy with cleanup function returned from onMount - Use progress_total callback instead of per-file progress tracking - Update source link to HuggingFace Spaces demo - Update language list link to NLLB documentation - Keep style:width directive for CSP compliance Addresses review feedback from @pngwn, @nico-martin, and @Jerboas86 Co-authored-by: Matt Van Horn --- .../docs/source/tutorials/svelte.md | 93 +++++++------------ 1 file changed, 36 insertions(+), 57 deletions(-) diff --git a/packages/transformers/docs/source/tutorials/svelte.md b/packages/transformers/docs/source/tutorials/svelte.md index 9be9d6181..c19e263f6 100644 --- a/packages/transformers/docs/source/tutorials/svelte.md +++ b/packages/transformers/docs/source/tutorials/svelte.md @@ -6,7 +6,7 @@ In this tutorial, we'll be building a simple [Svelte](https://svelte.dev/) appli Useful links: -- [Source code](https://github.com/huggingface/transformers.js/tree/main/examples/svelte-translator) +- [Demo on Hugging Face Spaces](https://huggingface.co/spaces/Xenova/svelte-translator) ## Prerequisites @@ -89,13 +89,11 @@ We recommend starting the development server again with `npm run dev` First, let's create some child components. Create a folder called `lib` in the `src` directory, and create the following files: -1. `LanguageSelector.svelte`: This component will allow the user to select the input and output languages. Check out the full list of languages [here](https://github.com/huggingface/transformers.js-examples/tree/main/react-translator/src/components/LanguageSelector.jsx). +1. `LanguageSelector.svelte`: This component will allow the user to select the input and output languages. Check out the full list of languages in the [NLLB language codes](https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200). ```svelte
@@ -139,15 +136,15 @@ Now let's update `src/routes/+page.svelte`. Replace its contents with the follow import Progress from '$lib/Progress.svelte'; // Model loading - let ready = null; - let disabled = false; - let progressItems = []; + let ready = $state(null); + let disabled = $state(false); + let loadProgress = $state(0); // Inputs and outputs - let input = 'I love walking my dog.'; - let sourceLanguage = 'eng_Latn'; - let targetLanguage = 'fra_Latn'; - let output = ''; + let input = $state('I love walking my dog.'); + let sourceLanguage = $state('eng_Latn'); + let targetLanguage = $state('fra_Latn'); + let output = $state(''); function translate() {} @@ -161,12 +158,12 @@ Now let's update `src/routes/+page.svelte`. Replace its contents with the follow sourceLanguage = e.target.value} + onchange={(e) => sourceLanguage = e.target.value} /> targetLanguage = e.target.value} + onchange={(e) => targetLanguage = e.target.value} />
@@ -176,17 +173,13 @@ Now let's update `src/routes/+page.svelte`. Replace its contents with the follow - +
{#if ready === false} + {/if} - {#each progressItems as data (data.file)} -
- -
- {/each}
@@ -344,20 +337,20 @@ First, let's set up the Web Worker and the `translate` function. Replace the ` - import { onMount, onDestroy } from 'svelte'; + import { onMount } from 'svelte'; import LanguageSelector from '$lib/LanguageSelector.svelte'; import Progress from '$lib/Progress.svelte'; // Model loading - let ready = null; - let disabled = false; - let progressItems = []; + let ready = $state(null); + let disabled = $state(false); + let loadProgress = $state(0); // Inputs and outputs - let input = 'I love walking my dog.'; - let sourceLanguage = 'eng_Latn'; - let targetLanguage = 'fra_Latn'; - let output = ''; + let input = $state('I love walking my dog.'); + let sourceLanguage = $state('eng_Latn'); + let targetLanguage = $state('fra_Latn'); + let output = $state(''); let worker; @@ -367,32 +360,17 @@ First, let's set up the Web Worker and the `translate` function. Replace the ` { - worker?.removeEventListener('message', onMessageReceived); + return () => { + worker?.removeEventListener('message', onMessageReceived); + }; }); function onMessageReceived(e) { switch (e.data.status) { - case 'initiate': + case 'progress_total': ready = false; - progressItems = [...progressItems, e.data]; - break; - - case 'progress': - progressItems = progressItems.map((item) => { - if (item.file === e.data.file) { - return { ...item, progress: e.data.progress }; - } - return item; - }); - break; - - case 'done': - progressItems = progressItems.filter( - (item) => item.file !== e.data.file, - ); + loadProgress = e.data.progress; break; case 'ready': @@ -421,7 +399,7 @@ First, let's set up the Web Worker and the `translate` function. Replace the ` ``` -SvelteKit server-renders pages by default, so creating the worker inside `onMount` keeps it browser-only and avoids running Web Worker code during SSR. +SvelteKit server-renders pages by default, so creating the worker inside `onMount` keeps it browser-only and avoids running Web Worker code during SSR. In Svelte 5, you can return a cleanup function from `onMount` instead of using `onDestroy`. Now, let's add an event listener in `src/routes/worker.js` to listen for messages from the main thread. We will send back messages (e.g., for model loading progress and text streaming) to the main thread with `self.postMessage`. @@ -431,9 +409,10 @@ self.addEventListener("message", async (event) => { // Retrieve the translation pipeline. When called for the first time, // this will load the pipeline and save it for future use. const translator = await MyTranslationPipeline.getInstance((x) => { - // We also add a progress callback to the pipeline so that we can - // track model loading. - self.postMessage(x); + // Forward only progress_total events to show overall download progress + if (x.status === "progress_total") { + self.postMessage(x); + } }); // Capture partial output as it streams from the pipeline