Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 15 additions & 12 deletions electron/README.md
Original file line number Diff line number Diff line change
@@ -1,31 +1,34 @@

# Transformers.js - Sample Electron application

An example project to show how to run 🤗 Transformers in an [Electron](https://www.electronjs.org/) application.

## Getting Started

1. Clone the repo and enter the project directory:
```bash
git clone https://github.com/huggingface/transformers.js-examples.git
cd transformers.js-examples/electron/
```

```bash
git clone https://github.com/huggingface/transformers.js-examples.git
cd transformers.js-examples/electron/
```

1. Install the necessary dependencies:
```bash
npm install
```

```bash
npm install
```

1. Run the application:
```bash
npm run start
```

After a few seconds, a new window should pop up on your screen!
```bash
npm run start
```

After a few seconds, a new window should pop up on your screen!

## Editing the template

All source code can be found in `./src/`:

- `index.js` - Serves as the entry point for the application's main process. When an Electron app is launched, this is the first file that gets executed, and it is responsible for setting up the main process of the application. You will need to restart the application after editing this file for your changes to take effect.
- `preload.js` - Used to preload scripts and modules in a renderer process before any other scripts run. In our case, we use the `contextBridge` API to expose the `classify` function to the renderer, which runs the model in the background. You will need to restart the application after editing this file for your changes to take effect.
- `classify.js` - Contains logic for loading the model and running predictions via the `classify` function. You will need to restart the application after editing this file for your changes to take effect.
Expand Down
16 changes: 8 additions & 8 deletions electron/forge.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const { FusesPlugin } = require('@electron-forge/plugin-fuses');
const { FuseV1Options, FuseVersion } = require('@electron/fuses');
const { FusesPlugin } = require("@electron-forge/plugin-fuses");
const { FuseV1Options, FuseVersion } = require("@electron/fuses");

module.exports = {
packagerConfig: {
Expand All @@ -12,25 +12,25 @@ module.exports = {
rebuildConfig: {},
makers: [
{
name: '@electron-forge/maker-squirrel',
name: "@electron-forge/maker-squirrel",
config: {},
},
{
name: '@electron-forge/maker-zip',
platforms: ['darwin'],
name: "@electron-forge/maker-zip",
platforms: ["darwin"],
},
{
name: '@electron-forge/maker-deb',
name: "@electron-forge/maker-deb",
config: {},
},
{
name: '@electron-forge/maker-rpm',
name: "@electron-forge/maker-rpm",
config: {},
},
],
plugins: [
{
name: '@electron-forge/plugin-auto-unpack-natives',
name: "@electron-forge/plugin-auto-unpack-natives",
config: {},
},
// Fuses are used to enable/disable various Electron functionality
Expand Down
14 changes: 7 additions & 7 deletions electron/src/classify.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ import { pipeline } from "@huggingface/transformers";

let classifierPromise;
async function classify(event, text) {
classifierPromise ??= pipeline(
"text-classification",
"Xenova/distilbert-base-uncased-finetuned-sst-2-english",
{ dtype: "q8" },
);
const classifier = await classifierPromise;
return await classifier(text);
classifierPromise ??= pipeline(
"text-classification",
"Xenova/distilbert-base-uncased-finetuned-sst-2-english",
{ dtype: "q8" },
);
const classifier = await classifierPromise;
return await classifier(text);
}

export { classify };
6 changes: 3 additions & 3 deletions electron/src/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
padding: 0;
margin: 0;
box-sizing: border-box;
font-family: 'Roboto', sans-serif;
font-family: "Roboto", sans-serif;
}

h1 {
Expand Down Expand Up @@ -44,6 +44,6 @@ body {

#output {
font-size: 20px;
font-family: 'Roboto Mono', monospace;
font-family: "Roboto Mono", monospace;
height: 100px;
}
}
26 changes: 13 additions & 13 deletions electron/src/index.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<!DOCTYPE html>
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
Expand All @@ -8,24 +8,24 @@

<body>
<div class="container">
<h1>Transformers.js</h1>
<h2>Run 🤗 Transformers.js in Electron!</h2>
<input id="text" placeholder="Enter text here">
<pre id="output"></pre>
<h1>Transformers.js</h1>
<h2>Run 🤗 Transformers.js in Electron!</h2>
<input id="text" placeholder="Enter text here" />
<pre id="output"></pre>
</div>

<script>
const inputElement = document.getElementById('text');
const outputElement = document.getElementById('output');
const inputElement = document.getElementById("text");
const outputElement = document.getElementById("output");

// 1. Send input data to the worker thread when it changes.
inputElement.addEventListener('input', async (event) => {
// 2. Await the result from the worker thread.
const result = await window.electronAPI.classify(event.target.value);
inputElement.addEventListener("input", async (event) => {
// 2. Await the result from the worker thread.
const result = await window.electronAPI.classify(event.target.value);

// 3. Update the UI.
outputElement.innerText = JSON.stringify(result, null, 2);
// 3. Update the UI.
outputElement.innerText = JSON.stringify(result, null, 2);
});
</script>
</body>
</body>
</html>
20 changes: 10 additions & 10 deletions electron/src/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('node:path');
const { classify } = require('./classify.js');
const { app, BrowserWindow, ipcMain } = require("electron");
const path = require("node:path");
const { classify } = require("./classify.js");

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) {
if (require("electron-squirrel-startup")) {
app.quit();
}

Expand All @@ -13,12 +13,12 @@ const createWindow = () => {
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
preload: path.join(__dirname, "preload.js"),
},
});

// and load the index.html of the app.
mainWindow.loadFile(path.join(__dirname, 'index.html'));
mainWindow.loadFile(path.join(__dirname, "index.html"));

// Open the DevTools.
mainWindow.webContents.openDevTools();
Expand All @@ -31,13 +31,13 @@ app.whenReady().then(() => {
// Add a handler for the `transformers:classify` event. This enables 2-way communication
// between the renderer process (UI) and the main process (processing).
// https://www.electronjs.org/docs/latest/tutorial/ipc#pattern-2-renderer-to-main-two-way
ipcMain.handle('transformers:classify', classify)
ipcMain.handle("transformers:classify", classify);

createWindow();

// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
app.on('activate', () => {
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
Expand All @@ -47,8 +47,8 @@ app.whenReady().then(() => {
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
Expand Down
6 changes: 3 additions & 3 deletions electron/src/preload.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
// See the Electron documentation for details on how to use preload scripts:
// https://www.electronjs.org/docs/latest/tutorial/process-model#preload-scripts

const { contextBridge, ipcRenderer } = require('electron');
const { contextBridge, ipcRenderer } = require("electron");

// Here, we use the `contextBridge` API to expose a custom API to the renderer process.
// This API allows the renderer process to invoke the `transformers:classify` event in the main process.
contextBridge.exposeInMainWorld('electronAPI', {
classify: (text) => ipcRenderer.invoke('transformers:classify', text)
contextBridge.exposeInMainWorld("electronAPI", {
classify: (text) => ipcRenderer.invoke("transformers:classify", text),
});
41 changes: 41 additions & 0 deletions next-vercel-ai-sdk/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*

# env files (can opt-in for committing if needed)
.env*

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
49 changes: 49 additions & 0 deletions next-vercel-ai-sdk/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Transformers.js and Vercel AI SDK example

A modern Transformers.js chat application powered by [@built-in-ai/transformers-js](https://github.com/jakobhoeg/built-in-ai) and [Vercel AI SDK](https://ai-sdk.dev/).
This app demonstrates how to use Transformers.js models with Vercel AI SDK to quickly build a fully functional chat application.

Components to check out for the implementation:

- [page.tsx](./src/app/page.tsx)
- [chat-transport.tsx](./src/app/chat-transport.ts)
- [store.ts](./src/store/store.ts)
- [models.ts](./src/app/models.ts)

## Features

- Run AI models directly in the browser
- Stream and interrupt responses
- Switch between different Transformers.js models
- Upload and process images in conversations
- Render reasoning for reasoning models (Qwen3)

## Tech Stack

- [Next.js 15](https://nextjs.org)
- [Shadcn/ui](https://ui.shadcn.com) for modern, accessible components
- [Zustand](https://github.com/pmndrs/zustand) for lightweight state management
- **AI Integration**:
- [Vercel AI SDK](https://ai-sdk.dev/) for chat interface and streaming
- [@built-in-ai/transformers-js](https://github.com/jakobhoeg/built-in-ai) model provider that works as a model provider for Transformers.js to integreate with Vercel AI SDK.

## Getting Started

1. **Install dependencies**:

```bash
npm install
```

2. **Run the development server**:

```bash
npm run dev
```

3. **Open your browser**:
Navigate to [http://localhost:3000](http://localhost:3000) to see the application.

## Deployment

[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/huggingface/transformers.js-examples/tree/main/next-vercel-ai-sdk)
21 changes: 21 additions & 0 deletions next-vercel-ai-sdk/components.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/app/globals.css",
"baseColor": "zinc",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}
21 changes: 21 additions & 0 deletions next-vercel-ai-sdk/next.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
// (Optional) Export as a static site
// See https://nextjs.org/docs/pages/building-your-application/deploying/static-exports#configuration
output: "export", // Feel free to modify/remove this option

// Override the default webpack configuration
webpack: (config) => {
// Ignore node-specific modules when bundling for the browser
// See https://webpack.js.org/configuration/resolve/#resolvealias
config.resolve.alias = {
...config.resolve.alias,
sharp$: false,
"onnxruntime-node$": false,
};
return config;
},
};

export default nextConfig;
Loading