Skip to content

Commit 0bb09f1

Browse files
committed
chore: update README.md
1 parent e954580 commit 0bb09f1

File tree

1 file changed

+143
-78
lines changed

1 file changed

+143
-78
lines changed

README.md

Lines changed: 143 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -4,135 +4,202 @@
44
[![codecov](https://codecov.io/github/daviddaytw/react-native-transformers/graph/badge.svg?token=G3D0Y33SI4)](https://codecov.io/github/daviddaytw/react-native-transformers)
55
[![TypeDoc](https://github.com/daviddaytw/react-native-transformers/actions/workflows/docs.yml/badge.svg)](https://daviddaytw.github.io/react-native-transformers)
66

7-
`react-native-transformers` is a React Native library for running Large Language Models (LLMs) from Hugging Face on your mobile applications locally. It supports both iOS and Android platforms, allowing you to leverage advanced AI models directly on your device without requiring an internet connection.
7+
**Run Hugging Face transformer models directly on your React Native and Expo applications with on-device inference. No cloud service required!**
88

9-
## Features
9+
## Overview
1010

11-
- On-device transformer model support for both text generation and text embedding
12-
- Local inference without internet connectivity
13-
- Compatible with iOS and Android platforms
14-
- Simple API for model loading and inference
15-
- Support for Hugging Face models in ONNX format
16-
- Built on top of ONNX Runtime for efficient model execution
17-
- TypeScript support with full type definitions
11+
`react-native-transformers` empowers your mobile applications with AI capabilities by running transformer models directly on the device. This means your app can generate text, answer questions, and process language without sending data to external servers - enhancing privacy, reducing latency, and enabling offline functionality.
12+
13+
Built on top of ONNX Runtime, this library provides a streamlined API for integrating state-of-the-art language models into your React Native and Expo applications with minimal configuration.
14+
15+
## Key Features
16+
17+
- **On-device inference**: Run AI models locally without requiring an internet connection
18+
- **Privacy-focused**: Keep user data on the device without sending it to external servers
19+
- **Optimized performance**: Leverages ONNX Runtime for efficient model execution on mobile CPUs
20+
- **Simple API**: Easy-to-use interface for model loading and inference
21+
- **Expo compatibility**: Works seamlessly with both Expo managed and bare workflows
1822

1923
## Installation
2024

21-
To use `react-native-transformers`, you need to install `onnxruntime-react-native` as a peer dependency. Follow the steps below:
25+
### 1. Install peer dependencies
2226

23-
### 1. Install the peer dependency:
27+
```sh
28+
npm install onnxruntime-react-native
29+
```
2430

25-
```sh
26-
npm install onnxruntime-react-native
27-
```
31+
### 2. Install react-native-transformers
2832

29-
### 2. Install `react-native-transformers`:
33+
```sh
34+
# React-Native
35+
npm install react-native-transformers
3036

31-
```sh
32-
npm install react-native-transformers
33-
```
37+
# Expo
38+
npx expo install react-native-transformers
39+
```
3440

35-
### 3. Configure React-Native or Expo
41+
### 3. Platform Configuration
3642

3743
<details>
38-
<summary>React Native CLI</summary>
44+
<summary><b>React Native CLI</b></summary>
3945

40-
- Link the `onnxruntime-react-native` library:
46+
Link the `onnxruntime-react-native` library:
4147

42-
```sh
43-
npx react-native link onnxruntime-react-native
44-
```
48+
```sh
49+
npx react-native link onnxruntime-react-native
50+
```
4551
</details>
4652

4753
<details>
48-
<summary>Expo</summary>
54+
<summary><b>Expo</b></summary>
4955

50-
- Install the Expo plugin configuration in `app.json` or `app.config.js`:
56+
Add the Expo plugin configuration in `app.json` or `app.config.js`:
5157

52-
```json
53-
{
54-
"expo": {
55-
"plugins": [
56-
"onnxruntime-react-native"
57-
],
58-
}
59-
}
60-
```
58+
```json
59+
{
60+
"expo": {
61+
"plugins": [
62+
"onnxruntime-react-native"
63+
]
64+
}
65+
}
66+
```
6167
</details>
6268

6369
### 4. Babel Configuration
6470

65-
You need to add the `babel-plugin-transform-import-meta` plugin to your Babel configuration (e.g., `.babelrc` or `babel.config.js`):
66-
67-
```json
68-
{
69-
"plugins": ["babel-plugin-transform-import-meta"]
70-
}
71-
```
71+
Add the `babel-plugin-transform-import-meta` plugin to your Babel configuration:
72+
73+
```js
74+
// babel.config.js
75+
module.exports = {
76+
// ... your existing config
77+
plugins: [
78+
// ... your existing plugins
79+
"babel-plugin-transform-import-meta"
80+
]
81+
};
82+
```
7283

7384
## Usage
7485

75-
### Text Generation Example
86+
### Text Generation
7687

7788
```javascript
78-
import React from "react";
89+
import React, { useState, useEffect } from "react";
7990
import { View, Text, Button } from "react-native";
8091
import { Pipeline } from "react-native-transformers";
8192

8293
export default function App() {
83-
const [output, setOutput] = React.useState("");
94+
const [output, setOutput] = useState("");
95+
const [isLoading, setIsLoading] = useState(false);
96+
const [isModelReady, setIsModelReady] = useState(false);
97+
98+
// Load model on component mount
99+
useEffect(() => {
100+
loadModel();
101+
}, []);
84102

85-
// Function to initialize the model
86103
const loadModel = async () => {
87-
await Pipeline.TextGeneration.init("Felladrin/onnx-Llama-160M-Chat-v1", "onnx/decoder_model_merged.onnx");
104+
setIsLoading(true);
105+
try {
106+
// Load a small Llama model
107+
await Pipeline.TextGeneration.init(
108+
"Felladrin/onnx-Llama-160M-Chat-v1",
109+
"onnx/decoder_model_merged.onnx",
110+
{
111+
// The fetch function is required to download model files
112+
fetch: async (url) => {
113+
// In a real app, you might want to cache the downloaded files
114+
const response = await fetch(url);
115+
return response.url;
116+
}
117+
}
118+
);
119+
setIsModelReady(true);
120+
} catch (error) {
121+
console.error("Error loading model:", error);
122+
alert("Failed to load model: " + error.message);
123+
} finally {
124+
setIsLoading(false);
125+
}
88126
};
89127

90-
// Function to generate text
91128
const generateText = () => {
92-
Pipeline.TextGeneration.generate("Hello world", setOutput);
129+
setOutput("");
130+
// Generate text from the prompt and update the UI as tokens are generated
131+
Pipeline.TextGeneration.generate(
132+
"Write a short poem about programming:",
133+
(text) => setOutput(text)
134+
);
93135
};
94136

95137
return (
96-
<View>
97-
<Button title="Load Model" onPress={loadModel} />
98-
<Button title="Generate Text" onPress={generateText} />
99-
<Text>Output: {output}</Text>
138+
<View style={{ padding: 20 }}>
139+
<Button
140+
title={isModelReady ? "Generate Text" : "Load Model"}
141+
onPress={isModelReady ? generateText : loadModel}
142+
disabled={isLoading}
143+
/>
144+
<Text style={{ marginTop: 20 }}>
145+
{output || "Generated text will appear here"}
146+
</Text>
100147
</View>
101148
);
102149
}
103150
```
104151

105-
### Text Embedding Example
152+
### With Custom Model Download
153+
154+
For Expo applications, use `expo-file-system` to download models with progress tracking:
106155

107156
```javascript
108-
import React from "react";
109-
import { View, Text, Button } from "react-native";
157+
import * as FileSystem from "expo-file-system";
110158
import { Pipeline } from "react-native-transformers";
111159

112-
export default function App() {
113-
const [embedding, setEmbedding] = React.useState([]);
160+
// In your model loading function
161+
await Pipeline.TextGeneration.init("model-repo", "model-file", {
162+
fetch: async (url) => {
163+
const localPath = FileSystem.cacheDirectory + url.split("/").pop();
114164

115-
// Function to initialize the model
116-
const loadModel = async () => {
117-
await Pipeline.TextEmbedding.init("Xenova/all-MiniLM-L6-v2");
118-
};
165+
// Check if file already exists
166+
const fileInfo = await FileSystem.getInfoAsync(localPath);
167+
if (fileInfo.exists) {
168+
console.log("Model already downloaded, using cached version");
169+
return localPath;
170+
}
119171

120-
// Function to generate embeddings
121-
const generateEmbedding = async () => {
122-
const result = await Pipeline.TextEmbedding.generate("Hello world");
123-
setEmbedding(result);
124-
};
172+
// Download file with progress tracking
173+
const downloadResumable = FileSystem.createDownloadResumable(
174+
url,
175+
localPath,
176+
{},
177+
(progress) => {
178+
const percentComplete = progress.totalBytesWritten / progress.totalBytesExpectedToWrite;
179+
console.log(`Download progress: ${(percentComplete * 100).toFixed(1)}%`);
180+
}
181+
);
125182

126-
return (
127-
<View>
128-
<Button title="Load Model" onPress={loadModel} />
129-
<Button title="Generate Embedding" onPress={generateEmbedding} />
130-
<Text>Embedding Length: {embedding.length}</Text>
131-
</View>
132-
);
133-
}
183+
const result = await downloadResumable.downloadAsync();
184+
return result?.uri;
185+
}
186+
});
134187
```
135188
189+
## Supported Models
190+
191+
`react-native-transformers` works with ONNX-formatted models from Hugging Face. Here are some recommended models based on size and performance:
192+
193+
| Model | Type | Size | Description |
194+
|-------|------|------|-------------|
195+
| [Felladrin/onnx-Llama-160M-Chat-v1](https://huggingface.co/Felladrin/onnx-Llama-160M-Chat-v1) | Text Generation | ~300MB | Small Llama model (160M parameters) |
196+
| [microsoft/Phi-3-mini-4k-instruct-onnx-web](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct-onnx-web) | Text Generation | ~1.5GB | Microsoft's Phi-3-mini model |
197+
| [Xenova/distilgpt2_onnx-quantized](https://huggingface.co/Xenova/distilgpt2_onnx-quantized) | Text Generation | ~165MB | Quantized DistilGPT-2 |
198+
| [Xenova/tiny-mamba-onnx](https://huggingface.co/Xenova/tiny-mamba-onnx) | Text Generation | ~85MB | Tiny Mamba model |
199+
| [Xenova/all-MiniLM-L6-v2-onnx](https://huggingface.co/Xenova/all-MiniLM-L6-v2-onnx) | Text Embedding | ~80MB | Sentence embedding model |
200+
201+
## API Reference
202+
136203
For detailed API documentation, please visit our [TypeDoc documentation](https://daviddaytw.github.io/react-native-transformers/).
137204
138205
## Contributing
@@ -154,6 +221,4 @@ This project is licensed under the MIT License. See the [LICENSE](LICENSE) file
154221
- [Expo Plugins Documentation](https://docs.expo.dev/guides/config-plugins/)
155222
- [ONNX Runtime Documentation](https://onnxruntime.ai/)
156223
- [Hugging Face Model Hub](https://huggingface.co/models)
157-
- [Babel Documentation](https://babeljs.io/)
158-
159-
These links provide additional information on how to configure and utilize the various components used by `react-native-transformers`.
224+
- [ONNX Format Documentation](https://onnx.ai/onnx/intro/)

0 commit comments

Comments
 (0)