Vokturz commited on
Commit
9e0c594
·
1 Parent(s): 415aaef

remove unnecessary elements

Browse files
Files changed (2) hide show
  1. public/manifest.json +0 -2
  2. react.md +0 -524
public/manifest.json CHANGED
@@ -8,12 +8,10 @@
8
  "type": "image/x-icon"
9
  },
10
  {
11
- "src": "logo192.png",
12
  "type": "image/png",
13
  "sizes": "192x192"
14
  },
15
  {
16
- "src": "logo512.png",
17
  "type": "image/png",
18
  "sizes": "512x512"
19
  }
 
8
  "type": "image/x-icon"
9
  },
10
  {
 
11
  "type": "image/png",
12
  "sizes": "192x192"
13
  },
14
  {
 
15
  "type": "image/png",
16
  "sizes": "512x512"
17
  }
react.md DELETED
@@ -1,524 +0,0 @@
1
- # Building a React application
2
-
3
- In this tutorial, we'll be building a simple React application that performs multilingual translation using Transformers.js! The final product will look something like this:
4
-
5
- ![Demo](https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/react-translator-demo.gif)
6
-
7
- Useful links:
8
-
9
- - [Demo site](https://huggingface.co/spaces/Xenova/react-translator)
10
- - [Source code](https://github.com/huggingface/transformers.js-examples/tree/main/react-translator)
11
-
12
- ## Prerequisites
13
-
14
- - [Node.js](https://nodejs.org/en/) version 18+
15
- - [npm](https://www.npmjs.com/) version 9+
16
-
17
- ## Step 1: Initialise the project
18
-
19
- 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 React application with minimal configuration. Run the following command in your terminal:
20
-
21
- ```bash
22
- npm create vite@latest react-translator -- --template react
23
- ```
24
-
25
- If prompted to install `create-vite`, type <kbd>y</kbd> and press <kbd>Enter</kbd>.
26
-
27
- Next, enter the project directory and install the necessary development dependencies:
28
-
29
- ```bash
30
- cd react-translator
31
- npm install
32
- ```
33
-
34
- To test that our application is working, we can run the following command:
35
-
36
- ```bash
37
- npm run dev
38
- ```
39
-
40
- Visiting the URL shown in the terminal (e.g., [http://localhost:5173/](http://localhost:5173/)) should show the default "React + Vite" landing page.
41
- You can stop the development server by pressing <kbd>Ctrl</kbd> + <kbd>C</kbd> in the terminal.
42
-
43
- ## Step 2: Install and configure Transformers.js
44
-
45
- 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:
46
-
47
- ```bash
48
- npm install @huggingface/transformers
49
- ```
50
-
51
- 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:
52
-
53
- 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.
54
- 2. Since the model is quite large (>1 GB), we don't want to download it until the user clicks the "Translate" button.
55
-
56
- 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) and some [React hooks](https://react.dev/reference/react).
57
-
58
- 1. Create a file called `worker.js` in the `src` directory. This script will do all the heavy-lifing 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 use 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:
59
-
60
- ```javascript
61
- import { pipeline, TextStreamer } from '@huggingface/transformers';
62
-
63
- class MyTranslationPipeline {
64
- static task = 'translation';
65
- static model = 'Xenova/nllb-200-distilled-600M';
66
- static instance = null;
67
-
68
- static async getInstance(progress_callback = null) {
69
- this.instance ??= pipeline(this.task, this.model, { progress_callback });
70
- return this.instance;
71
- }
72
- }
73
- ```
74
-
75
- 2. Modify `App.jsx` in the `src` directory. This file is automatically created when initializing our React project, and will contain some boilerplate code. Inside the `App` function, let's create the web worker and store a reference to it using the `useRef` hook:
76
-
77
- ```jsx
78
- // Remember to import the relevant hooks
79
- import { useEffect, useRef, useState } from 'react'
80
- import './App.css'
81
-
82
- function App() {
83
- // Create a reference to the worker object.
84
- const worker = useRef(null);
85
-
86
- // We use the `useEffect` hook to setup the worker as soon as the `App` component is mounted.
87
- useEffect(() => {
88
- // Create the worker if it does not yet exist.
89
- worker.current ??= new Worker(new URL('./worker.js', import.meta.url), {
90
- type: 'module'
91
- });
92
-
93
- // Create a callback function for messages from the worker thread.
94
- const onMessageReceived = (e) => {
95
- // TODO: Will fill in later
96
- };
97
-
98
- // Attach the callback function as an event listener.
99
- worker.current.addEventListener('message', onMessageReceived);
100
-
101
- // Define a cleanup function for when the component is unmounted.
102
- return () => worker.current.removeEventListener('message', onMessageReceived);
103
- });
104
-
105
- return (
106
- // TODO: Rest of our app goes here...
107
- )
108
- }
109
-
110
- export default App
111
-
112
- ```
113
-
114
- ## Step 3: Design the user interface
115
-
116
- <Tip>
117
-
118
- We recommend starting the development server again with `npm run dev`
119
- (if not already running) so that you can see your changes in real-time.
120
-
121
- </Tip>
122
-
123
- First, let's define our components. Create a folder called `components` in the `src` directory, and create the following files:
124
-
125
- 1. `LanguageSelector.jsx`: 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).
126
-
127
- ```jsx
128
- const LANGUAGES = {
129
- "Acehnese (Arabic script)": "ace_Arab",
130
- "Acehnese (Latin script)": "ace_Latn",
131
- "Afrikaans": "afr_Latn",
132
- ...
133
- "Zulu": "zul_Latn",
134
- }
135
-
136
- export default function LanguageSelector({ type, onChange, defaultLanguage }) {
137
- return (
138
- <div className='language-selector'>
139
- <label>{type}: </label>
140
- <select onChange={onChange} defaultValue={defaultLanguage}>
141
- {Object.entries(LANGUAGES).map(([key, value]) => {
142
- return <option key={key} value={value}>{key}</option>
143
- })}
144
- </select>
145
- </div>
146
- )
147
- }
148
- ```
149
-
150
- 2. `Progress.jsx`: This component will display the progress for downloading each model file.
151
- ```jsx
152
- export default function Progress({ text, percentage }) {
153
- percentage = percentage ?? 0;
154
- return (
155
- <div className="progress-container">
156
- <div className="progress-bar" style={{ width: `${percentage}%` }}>
157
- {text} ({`${percentage.toFixed(2)}%`})
158
- </div>
159
- </div>
160
- );
161
- }
162
- ```
163
-
164
- We can now use these components in `App.jsx` by adding these imports to the top of the file:
165
-
166
- ```jsx
167
- import LanguageSelector from './components/LanguageSelector';
168
- import Progress from './components/Progress';
169
- ```
170
-
171
- Let's also add some state variables to keep track of a few things in our application, like model loading, languages, input text, and output text. Add the following code to the beginning of the `App` function in `src/App.jsx`:
172
-
173
- ```jsx
174
- function App() {
175
- // Model loading
176
- const [ready, setReady] = useState(null);
177
- const [disabled, setDisabled] = useState(false);
178
- const [progressItems, setProgressItems] = useState([]);
179
-
180
- // Inputs and outputs
181
- const [input, setInput] = useState('I love walking my dog.');
182
- const [sourceLanguage, setSourceLanguage] = useState('eng_Latn');
183
- const [targetLanguage, setTargetLanguage] = useState('fra_Latn');
184
- const [output, setOutput] = useState('');
185
-
186
- // rest of the code...
187
- }
188
- ```
189
-
190
- Next, we can add our custom components to the main `App` component. We will also add two `textarea` elements for input and output text, and a `button` to trigger the translation. Modify the `return` statement to look like this:
191
-
192
- ```jsx
193
- return (
194
- <>
195
- <h1>Transformers.js</h1>
196
- <h2>ML-powered multilingual translation in React!</h2>
197
-
198
- <div className="container">
199
- <div className="language-container">
200
- <LanguageSelector
201
- type={'Source'}
202
- defaultLanguage={'eng_Latn'}
203
- onChange={(x) => setSourceLanguage(x.target.value)}
204
- />
205
- <LanguageSelector
206
- type={'Target'}
207
- defaultLanguage={'fra_Latn'}
208
- onChange={(x) => setTargetLanguage(x.target.value)}
209
- />
210
- </div>
211
-
212
- <div className="textbox-container">
213
- <textarea
214
- value={input}
215
- rows={3}
216
- onChange={(e) => setInput(e.target.value)}
217
- ></textarea>
218
- <textarea value={output} rows={3} readOnly></textarea>
219
- </div>
220
- </div>
221
-
222
- <button disabled={disabled} onClick={translate}>
223
- Translate
224
- </button>
225
-
226
- <div className="progress-bars-container">
227
- {ready === false && <label>Loading models... (only run once)</label>}
228
- {progressItems.map((data) => (
229
- <div key={data.file}>
230
- <Progress text={data.file} percentage={data.progress} />
231
- </div>
232
- ))}
233
- </div>
234
- </>
235
- );
236
- ```
237
-
238
- Don't worry about the `translate` function for now. We will define it in the next section.
239
-
240
- Finally, we can add some CSS to make our app look a little nicer. Modify the following files in the `src` directory:
241
-
242
- 1. `index.css`:
243
- <details>
244
- <summary>View code</summary>
245
-
246
- ```css
247
- :root {
248
- font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
249
- line-height: 1.5;
250
- font-weight: 400;
251
- color: #213547;
252
- background-color: #ffffff;
253
-
254
- font-synthesis: none;
255
- text-rendering: optimizeLegibility;
256
- -webkit-font-smoothing: antialiased;
257
- -moz-osx-font-smoothing: grayscale;
258
- -webkit-text-size-adjust: 100%;
259
- }
260
-
261
- body {
262
- margin: 0;
263
- display: flex;
264
- place-items: center;
265
- min-width: 320px;
266
- min-height: 100vh;
267
- }
268
-
269
- h1 {
270
- font-size: 3.2em;
271
- line-height: 1;
272
- }
273
-
274
- h1,
275
- h2 {
276
- margin: 8px;
277
- }
278
-
279
- select {
280
- padding: 0.3em;
281
- cursor: pointer;
282
- }
283
-
284
- textarea {
285
- padding: 0.6em;
286
- }
287
-
288
- button {
289
- padding: 0.6em 1.2em;
290
- cursor: pointer;
291
- font-weight: 500;
292
- }
293
-
294
- button[disabled] {
295
- cursor: not-allowed;
296
- }
297
-
298
- select,
299
- textarea,
300
- button {
301
- border-radius: 8px;
302
- border: 1px solid transparent;
303
- font-size: 1em;
304
- font-family: inherit;
305
- background-color: #f9f9f9;
306
- transition: border-color 0.25s;
307
- }
308
-
309
- select:hover,
310
- textarea:hover,
311
- button:not([disabled]):hover {
312
- border-color: #646cff;
313
- }
314
-
315
- select:focus,
316
- select:focus-visible,
317
- textarea:focus,
318
- textarea:focus-visible,
319
- button:focus,
320
- button:focus-visible {
321
- outline: 4px auto -webkit-focus-ring-color;
322
- }
323
- ```
324
-
325
- </details>
326
-
327
- 1. `App.css`
328
- <details>
329
- <summary>View code</summary>
330
-
331
- ```css
332
- #root {
333
- max-width: 1280px;
334
- margin: 0 auto;
335
- padding: 2rem;
336
- text-align: center;
337
- }
338
-
339
- .language-container {
340
- display: flex;
341
- gap: 20px;
342
- }
343
-
344
- .textbox-container {
345
- display: flex;
346
- justify-content: center;
347
- gap: 20px;
348
- width: 800px;
349
- }
350
-
351
- .textbox-container > textarea,
352
- .language-selector {
353
- width: 50%;
354
- }
355
-
356
- .language-selector > select {
357
- width: 150px;
358
- }
359
-
360
- .progress-container {
361
- position: relative;
362
- font-size: 14px;
363
- color: white;
364
- background-color: #e9ecef;
365
- border: solid 1px;
366
- border-radius: 8px;
367
- text-align: left;
368
- overflow: hidden;
369
- }
370
-
371
- .progress-bar {
372
- padding: 0 4px;
373
- z-index: 0;
374
- top: 0;
375
- width: 1%;
376
- overflow: hidden;
377
- background-color: #007bff;
378
- white-space: nowrap;
379
- }
380
-
381
- .progress-text {
382
- z-index: 2;
383
- }
384
-
385
- .selector-container {
386
- display: flex;
387
- gap: 20px;
388
- }
389
-
390
- .progress-bars-container {
391
- padding: 8px;
392
- height: 140px;
393
- }
394
-
395
- .container {
396
- margin: 25px;
397
- display: flex;
398
- flex-direction: column;
399
- gap: 10px;
400
- }
401
- ```
402
-
403
- </details>
404
-
405
- ## Step 4: Connecting everything together
406
-
407
- Now that we have a basic user interface set up, we can finally connect everything together.
408
-
409
- First, let's define the `translate` function, which will be called when the user clicks the `Translate` button. This sends a message (containing the input text, source language, and target language) to the worker thread for processing. We will also disable the button so the user doesn't click it multiple times. Add the following code just before the `return` statement in the `App` function:
410
-
411
- ```jsx
412
- const translate = () => {
413
- setDisabled(true);
414
- setOutput('');
415
- worker.current.postMessage({
416
- text: input,
417
- src_lang: sourceLanguage,
418
- tgt_lang: targetLanguage
419
- });
420
- };
421
- ```
422
-
423
- 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`.
424
-
425
- ```javascript
426
- // Listen for messages from the main thread
427
- self.addEventListener('message', async (event) => {
428
- // Retrieve the translation pipeline. When called for the first time,
429
- // this will load the pipeline and save it for future use.
430
- const translator = await MyTranslationPipeline.getInstance((x) => {
431
- // We also add a progress callback to the pipeline so that we can
432
- // track model loading.
433
- self.postMessage(x);
434
- });
435
-
436
- // Capture partial output as it streams from the pipeline
437
- const streamer = new TextStreamer(translator.tokenizer, {
438
- skip_prompt: true,
439
- skip_special_tokens: true,
440
- callback_function: function (text) {
441
- self.postMessage({
442
- status: 'update',
443
- output: text
444
- });
445
- }
446
- });
447
-
448
- // Actually perform the translation
449
- const output = await translator(event.data.text, {
450
- tgt_lang: event.data.tgt_lang,
451
- src_lang: event.data.src_lang,
452
-
453
- // Allows for partial output to be captured
454
- streamer
455
- });
456
-
457
- // Send the output back to the main thread
458
- self.postMessage({
459
- status: 'complete',
460
- output
461
- });
462
- });
463
- ```
464
-
465
- Finally, let's fill in our `onMessageReceived` function in `src/App.jsx`, which will update the application state in response to messages from the worker thread. Add the following code inside the `useEffect` hook we defined earlier:
466
-
467
- ```jsx
468
- const onMessageReceived = (e) => {
469
- switch (e.data.status) {
470
- case 'initiate':
471
- // Model file start load: add a new progress item to the list.
472
- setReady(false);
473
- setProgressItems((prev) => [...prev, e.data]);
474
- break;
475
-
476
- case 'progress':
477
- // Model file progress: update one of the progress items.
478
- setProgressItems((prev) =>
479
- prev.map((item) => {
480
- if (item.file === e.data.file) {
481
- return { ...item, progress: e.data.progress };
482
- }
483
- return item;
484
- })
485
- );
486
- break;
487
-
488
- case 'done':
489
- // Model file loaded: remove the progress item from the list.
490
- setProgressItems((prev) =>
491
- prev.filter((item) => item.file !== e.data.file)
492
- );
493
- break;
494
-
495
- case 'ready':
496
- // Pipeline ready: the worker is ready to accept messages.
497
- setReady(true);
498
- break;
499
-
500
- case 'update':
501
- // Generation update: update the output text.
502
- setOutput((o) => o + e.data.output);
503
- break;
504
-
505
- case 'complete':
506
- // Generation complete: re-enable the "Translate" button
507
- setDisabled(false);
508
- break;
509
- }
510
- };
511
- ```
512
-
513
- You can now run the application with `npm run dev` and perform multilingual translation directly in your browser!
514
-
515
- ## (Optional) Step 5: Build and deploy
516
-
517
- To build your application, simply run `npm run build`. This will bundle your application and output the static files to the `dist` folder.
518
-
519
- 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).
520
-
521
- 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.
522
- 2. Go to "Files" &rarr; "Add file" &rarr; "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".
523
-
524
- **That's it!** Your application should now be live at `https://huggingface.co/spaces/<your-username>/<your-space-name>`!