├── .gitignore
├── icons
└── tensorflow_logo.png
├── .github
├── dependabot.yaml
└── workflows
│ ├── ci.yml
│ └── npm-publish.yml
├── .pre-commit-config.yaml
├── package.json
├── examples
├── local_test.json
└── basic.json
├── README.md
├── teachable_machine.html
├── CHANGELOG.md
├── teachable_machine.js
└── LICENSE
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | *.DS*
3 | .vscode
4 |
--------------------------------------------------------------------------------
/icons/tensorflow_logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bonastreyair/node-red-contrib-teachable-machine/HEAD/icons/tensorflow_logo.png
--------------------------------------------------------------------------------
/.github/dependabot.yaml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | - package-ecosystem: github-actions
4 | directory: /
5 | schedule:
6 | interval: weekly
7 | - package-ecosystem: npm
8 | directory: /
9 | schedule:
10 | interval: weekly
11 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 | on:
3 | push:
4 | branches:
5 | - main
6 | pull_request:
7 | jobs:
8 | install:
9 | runs-on: ubuntu-latest
10 | steps:
11 | - name: Checkout repository
12 | uses: actions/checkout@v6
13 | - name: Setup node
14 | uses: actions/setup-node@v6
15 | with:
16 | node-version: 12
17 | registry-url: https://registry.npmjs.org/
18 | - name: npm install
19 | run: npm install
20 |
--------------------------------------------------------------------------------
/.github/workflows/npm-publish.yml:
--------------------------------------------------------------------------------
1 | name: Publish npm package
2 | on:
3 | release:
4 | types: [created]
5 | jobs:
6 | publish:
7 | runs-on: ubuntu-latest
8 | steps:
9 | - name: Checkout repository
10 | uses: actions/checkout@v6
11 | - name: Setup node
12 | uses: actions/setup-node@v6
13 | with:
14 | node-version: 12
15 | registry-url: https://registry.npmjs.org/
16 | - name: Publish npm package
17 | run: npm publish
18 | env:
19 | NODE_AUTH_TOKEN: ${{secrets.npm_token}}
20 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | repos:
2 | - repo: https://github.com/pre-commit/pre-commit-hooks
3 | rev: v6.0.0
4 | hooks:
5 | - id: trailing-whitespace
6 | - id: check-added-large-files
7 | - id: check-yaml
8 | - id: end-of-file-fixer
9 | - id: check-json
10 | - id: pretty-format-json
11 | args: [--autofix, --no-sort-keys]
12 | - repo: https://github.com/standard/standard
13 | rev: v17.1.2
14 | hooks:
15 | - id: standard
16 | - repo: https://github.com/google/yamlfmt
17 | rev: v0.20.0
18 | hooks:
19 | - id: yamlfmt
20 | - repo: https://github.com/executablebooks/mdformat
21 | rev: 1.0.0
22 | hooks:
23 | - id: mdformat
24 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "node-red-contrib-teachable-machine",
3 | "version": "1.4.1",
4 | "description": "Simplifies integration with Teachable Machine models from Google",
5 | "dependencies": {
6 | "node-fetch": "3.3.2",
7 | "@tensorflow/tfjs-node": "4.22.0",
8 | "pureimage": "0.4.18"
9 | },
10 | "engines": {
11 | "node": ">=16.20.0"
12 | },
13 | "keywords": [
14 | "node-red",
15 | "tensorflow",
16 | "tensorflowjs",
17 | "classification",
18 | "teachable machine",
19 | "google"
20 | ],
21 | "license": "Apache-2.0",
22 | "node-red": {
23 | "version": ">=2.1.0",
24 | "nodes": {
25 | "teachable machine": "teachable_machine.js"
26 | }
27 | },
28 | "repository": {
29 | "type": "git",
30 | "url": "https://github.com/bonastreyair/node-red-contrib-teachable-machine"
31 | },
32 | "author": {
33 | "name": "Yair Bonastre",
34 | "email": "bonastreyair@gmail.com"
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/examples/local_test.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "id": "456d4286.6d5b2c",
4 | "type": "debug",
5 | "z": "17514116325f40c5",
6 | "name": "",
7 | "active": true,
8 | "tosidebar": true,
9 | "console": false,
10 | "tostatus": false,
11 | "complete": "true",
12 | "targetType": "full",
13 | "x": 650,
14 | "y": 540,
15 | "wires": []
16 | },
17 | {
18 | "id": "91ebc5b6.8ccdd8",
19 | "type": "teachable machine",
20 | "z": "17514116325f40c5",
21 | "name": "",
22 | "mode": "online",
23 | "modelUri": "https://teachablemachine.withgoogle.com/models/49PRz_c_9/",
24 | "localModel": "teachable_model",
25 | "output": "best",
26 | "activeThreshold": false,
27 | "threshold": 80,
28 | "activeMaxResults": false,
29 | "maxResults": 3,
30 | "passThrough": true,
31 | "x": 490,
32 | "y": 540,
33 | "wires": [
34 | [
35 | "456d4286.6d5b2c"
36 | ]
37 | ]
38 | },
39 | {
40 | "id": "01e26608fa047b50",
41 | "type": "camera",
42 | "z": "17514116325f40c5",
43 | "name": "",
44 | "x": 310,
45 | "y": 540,
46 | "wires": [
47 | [
48 | "91ebc5b6.8ccdd8"
49 | ]
50 | ]
51 | },
52 | {
53 | "id": "e5021a59647a2f5e",
54 | "type": "fileinject",
55 | "z": "17514116325f40c5",
56 | "name": "",
57 | "x": 300,
58 | "y": 580,
59 | "wires": [
60 | [
61 | "91ebc5b6.8ccdd8"
62 | ]
63 | ]
64 | },
65 | {
66 | "id": "309069d9154be5ef",
67 | "type": "inject",
68 | "z": "17514116325f40c5",
69 | "name": "reload",
70 | "props": [
71 | {
72 | "p": "reload",
73 | "v": "true",
74 | "vt": "bool"
75 | }
76 | ],
77 | "repeat": "",
78 | "crontab": "",
79 | "once": false,
80 | "onceDelay": 0.1,
81 | "topic": "",
82 | "x": 310,
83 | "y": 500,
84 | "wires": [
85 | [
86 | "91ebc5b6.8ccdd8"
87 | ]
88 | ]
89 | }
90 | ]
91 |
--------------------------------------------------------------------------------
/examples/basic.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "id": "9b0a1240.fe6c2",
4 | "type": "http request",
5 | "z": "17514116325f40c5",
6 | "name": "random image",
7 | "method": "GET",
8 | "ret": "bin",
9 | "paytoqs": false,
10 | "url": "https://loremflickr.com/320/240/sport",
11 | "tls": "",
12 | "persist": false,
13 | "proxy": "",
14 | "authType": "",
15 | "x": 280,
16 | "y": 120,
17 | "wires": [
18 | [
19 | "91ebc5b6.8ccdd8"
20 | ]
21 | ]
22 | },
23 | {
24 | "id": "9cbe3704.6bb118",
25 | "type": "inject",
26 | "z": "17514116325f40c5",
27 | "name": "new",
28 | "repeat": "",
29 | "crontab": "",
30 | "once": false,
31 | "onceDelay": 0.1,
32 | "topic": "",
33 | "payload": "",
34 | "payloadType": "date",
35 | "x": 130,
36 | "y": 120,
37 | "wires": [
38 | [
39 | "9b0a1240.fe6c2"
40 | ]
41 | ]
42 | },
43 | {
44 | "id": "456d4286.6d5b2c",
45 | "type": "debug",
46 | "z": "17514116325f40c5",
47 | "name": "",
48 | "active": true,
49 | "tosidebar": true,
50 | "console": false,
51 | "tostatus": false,
52 | "complete": "true",
53 | "targetType": "full",
54 | "x": 650,
55 | "y": 120,
56 | "wires": []
57 | },
58 | {
59 | "id": "91ebc5b6.8ccdd8",
60 | "type": "teachable machine",
61 | "z": "17514116325f40c5",
62 | "name": "",
63 | "mode": "online",
64 | "modelUri": "https://teachablemachine.withgoogle.com/models/49PRz_c_9/",
65 | "localModel": "teachable_model",
66 | "output": "best",
67 | "activeThreshold": false,
68 | "threshold": 80,
69 | "activeMaxResults": false,
70 | "maxResults": 3,
71 | "passThrough": true,
72 | "x": 490,
73 | "y": 120,
74 | "wires": [
75 | [
76 | "456d4286.6d5b2c"
77 | ]
78 | ]
79 | },
80 | {
81 | "id": "994234755381c0c0",
82 | "type": "inject",
83 | "z": "17514116325f40c5",
84 | "name": "reload",
85 | "props": [
86 | {
87 | "p": "reload",
88 | "v": "true",
89 | "vt": "bool"
90 | }
91 | ],
92 | "repeat": "",
93 | "crontab": "",
94 | "once": false,
95 | "onceDelay": 0.1,
96 | "topic": "",
97 | "x": 310,
98 | "y": 80,
99 | "wires": [
100 | [
101 | "91ebc5b6.8ccdd8"
102 | ]
103 | ]
104 | }
105 | ]
106 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # node-red-contrib-teachable-machine
2 |
3 | [](https://nodered.org)
4 | [](https://results.pre-commit.ci/latest/github/bonastreyair/node-red-contrib-teachable-machine/main)
5 | [](https://github.com/bonastreyair/node-red-contrib-teachable-machine/actions?workflow=CI)
6 | [](https://www.npmjs.com/package/node-red-contrib-teachable-machine)
7 | [](https://www.npmjs.com/package/node-red-contrib-teachable-machine)
8 | [](https://packagequality.com/#?package=node-red-contrib-teachable-machine)
9 | [](https://standardjs.com)
10 | [](https://codeclimate.com/github/bonastreyair/node-red-contrib-teachable-machine/maintainability)
11 | [](https://github.com/bonastreyair/node-red-contrib-teachable-machine/blob/master/LICENSE)
12 | [](https://www.paypal.me/bonastreyair)
13 |
14 | A [Node-RED](https://nodered.org) node based in [tensorflow.js](https://www.tensorflow.org/js) that enables to run custom image classification trained models using [Teachable Machine](https://teachablemachine.withgoogle.com/train/image) tool. All notable changes to this project will be documented in the [CHANGELOG.md](https://github.com/bonastreyair/node-red-contrib-teachable-machine/blob/main/CHANGELOG.md) file.
15 |
16 |
17 |
18 |
19 |
20 | ## Install
21 |
22 | You have two options to install the node.
23 |
24 | - Use `Manage palette` option in `Node-RED` Menu (recommended)
25 | 
26 |
27 | - Run the following command in your `Node-RED` user directory - typically `~/.node-red`
28 |
29 | ```bash
30 | npm install node-red-contrib-teachable-machine
31 | ```
32 |
33 | **Note:** If you run the command you will need to restart `Node-RED` after installation. If installation goes wrong please open a [new issue](https://github.com/bonastreyair/node-red-contrib-teachable-machine/issues).
34 |
35 | ## Node usage
36 |
37 | ### Step 1
38 |
39 | Go to [Teachable Machine](https://teachablemachine.withgoogle.com/train/image) and follow the steps to train your custom classification model. Once trained click on the `Export Model` button.
40 |
41 | 
42 |
43 | ### Step 2
44 |
45 | Select `Tensorflow.js` format and upload your trained model (for free). Once it is uploaded, copy the generated URL.
46 |
47 | 
48 |
49 | Once the URL is generated it will show the stored files.
50 |
51 | 
52 |
53 | ### Step 3
54 |
55 | #### **Online Mode**
56 |
57 | Select Online Mode and paste the saved URL in the node configuration. That URL hosts all the information to load your trained model. Make sure you copy all the given URL including the `https://...` and the `/` in the end.
58 |
59 | 
60 |
61 | #### **Local Mode**
62 |
63 | Download all three files from the generated URL and save them locally in a folder maintaning the original filenames.
64 |
65 | Select Local Mode and write down the absolute path of the folder that contain the three downloaded files in the node configuration. Make sure it ends with a `/` noting it is a folder.
66 |
67 | 
68 |
69 | ### Step 4
70 |
71 | In `Node-RED` send a buffered image (jpeg or png) to the node. Check the example in the `Import` section.
72 |
73 | ## Node Status Information
74 |
75 | ### Shape
76 |
77 | - ■ `dot`: node is idle
78 | - □ `ring`: node is working
79 |
80 | ### Color
81 |
82 | - 🟩 `green`: model is available
83 | - 🟨 `yellow`: preparing model
84 | - 🟥 `red`: node error
85 |
86 | ## Requirements
87 |
88 | - `Node-RED v2.1.0+`
89 | - `Node.js v16.20.0+`
90 |
91 | *Warning:* Only the official Docker `nodered/node-red` [image](https://hub.docker.com/r/nodered/node-red/) based on [Debian](https://www.debian.org) `v3.1.0+` image works since it needs `ld-linux-x86-64.so.2`. This necessary library is not present in the default [Alpine](https://hub.docker.com/_/alpine) Docker image version.
92 |
--------------------------------------------------------------------------------
/teachable_machine.html:
--------------------------------------------------------------------------------
1 |
2 |
56 |
57 |
58 |
102 |
103 |
104 |
137 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | All notable changes to this project will be documented in this file following a [Semantic Versioning](https://semver.org/spec/v2.0.0.html). The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
4 |
5 | ## [1.4.0] - 2022-11-30
6 |
7 | ### Added
8 |
9 | - Local Mode Support
10 |
11 | ### Changed
12 |
13 | - Improved code structure
14 | - Upgrade pre-commit dependencies
15 | - Dependency change from `@tensorflow/tfjs` to `@tensorflow/tfjs-node`
16 | - Upgraded `node-fetch` to version `3.3.0`
17 | - Upgraded `pureimage` to version `0.3.14`
18 |
19 | ## [1.3.1] - 2021-10-09
20 |
21 | ### Added
22 |
23 | - Using `pre-commit.ci` with its own badge
24 | - New `Code Climate` mantainability score badge
25 |
26 | ### Changed
27 |
28 | - Improved status node information
29 | - shape:
30 | - ■ `dot`: node is idle
31 | - □ `ring`: node is working
32 | - color:
33 | - 🟩 `green`: model is available
34 | - 🟨 `yellow`: preparing model
35 | - 🟥 `red`: node error
36 |
37 | ### Fixed
38 |
39 | - Node hungs when using a bad image buffer, even with PNG images - [#21](https://github.com/bonastreyair/node-red-contrib-teachable-machine/issues/21)
40 |
41 | ## [1.3.0] - 2021-09-24
42 |
43 | ### Added
44 |
45 | - Model reload option flag during running time - [#22](https://github.com/bonastreyair/node-red-contrib-teachable-machine/issues/22) - Thanks [@acejacek](https://github.com/acejacek) for the suggestion and the PR
46 | - `pre-commit` common checks with `standard`, `yamlfmt` and `mdformat` style checks
47 | - GitHub Actions **CI** test with badge
48 | - **npm** quality badge to the `README` file
49 | - Automatic dependency checks with **dependabot**
50 |
51 | ### Changed
52 |
53 | - Upgraded `node-fetch` to version `3.0.0`
54 | - Upgraded `pureimage` to version `0.3.5`
55 | - Upgraded `package-lock.json` file format to `v7`
56 | - Updated the `basic` example with the new reload option flag
57 |
58 | ## [1.2.2] - 2020-10-24
59 |
60 | ### Changed
61 |
62 | - Upgraded `@tensorflow/tfjs-node` to version `1.4.0` to help Raspberry Pi installation - [#18](https://github.com/bonastreyair/node-red-contrib-teachable-machine/issues/18)
63 |
64 | ## [1.2.1] - 2020-10-24
65 |
66 | ### Added
67 |
68 | - `package-lock.json` to ensure always exact versions during installation
69 |
70 | ### Fixed
71 |
72 | - Output API was changed by mistake, now msg.payload still outputs `class` and `score` keys for each classification as in `v1.1.0+` releases
73 | - When selecting all predictions without filter only one result was showing up
74 |
75 | ## [1.2.0] - 2020-10-23
76 |
77 | ### Added
78 |
79 | - Compatibility with official Node-RED Dockerized image based on [Alpine](https://hub.docker.com/_/alpine) image
80 | - Compatibility with Raspberry Pi
81 | - `pureimage` npm package dependency to manage buffer images using pure javascript - [#17](https://github.com/bonastreyair/node-red-contrib-teachable-machine/issues/17)
82 | - `node-fetch` npm package dependency to manage http request to obtain the model info
83 |
84 | ### Removed
85 |
86 | - `@teachablemachine/image` npm package dependency
87 | - `jsdom` npm package dependency
88 | - `canvas` npm package dependency
89 |
90 | ## [1.1.5] - 2020-09-08
91 |
92 | ### Fixed
93 |
94 | - Error when installing nodes - [#15](https://github.com/bonastreyair/node-red-contrib-teachable-machine/issues/15)
95 |
96 | ### Changed
97 |
98 | - Upgrade `jsdom` version from `16.2.2` to `16.4.0`
99 |
100 | ## [1.1.4] - 2020-06-05
101 |
102 | ### Fixed
103 |
104 | - Better usage of `HTMLVideoElement` class imported from `dom.window`
105 | - Better accuracy representation in the node status without decimals
106 |
107 | ### Changed
108 |
109 | - Some variable types from `const` to `var`
110 |
111 | ## [1.1.3] - 2020-06-05
112 |
113 | ### Fixed
114 |
115 | - Prediction does not work when save_image's box is checked - [#14](https://github.com/bonastreyair/node-red-contrib-teachable-machine/issues/14)
116 |
117 | ### Changed
118 |
119 | - Dependancy is now `@tensorflow/tfjs 1.3.1` instead of `@tensorflow/tfjs-node 1.4.0`, to match teachable machine correct dependencies
120 |
121 | ## [1.1.2] - 2020-05-03
122 |
123 | ### Added
124 |
125 | - PayPal donation badge in `README` file
126 |
127 | ### Fixed
128 |
129 | - `className` key (when `Best prediction` option) fixed to `class` in the results
130 | - Refinements on `README` file
131 | - Alignment HTML icons in node configuration
132 |
133 | ## [1.1.1] - 2020-04-24
134 |
135 | ### Added
136 |
137 | - New configuration checkbox to pass through the input image in `msg.image`
138 |
139 | ### Changed
140 |
141 | - `probability` key changed to `score` in the results
142 | - Updated example with new configuration parameter
143 |
144 | ### Fixed
145 |
146 | - Selecting `Best prediction` option made the `Name` disappear
147 |
148 | ## [1.1.0] - 2020-04-22
149 |
150 | ### Changed
151 |
152 | - Updated image on how to use Teachable Machine and configuration node on Step 3
153 | - Use standard image treatment for `README` instead of HTML
154 | - Upgraded `@tensorflow/tfjs-node` to version `1.4.0` to enable coexistantce with [tfjs-nodes](https://github.com/dceejay/tfjs-nodes) nodes - [#8](https://github.com/bonastreyair/node-red-contrib-teachable-machine/issues/8)
155 |
156 | ## [1.0.1] - 2020-04-15
157 |
158 | ### Changed
159 |
160 | - Updated information help node
161 |
162 | ## [1.0.0] - 2020-04-15
163 |
164 | ### Added
165 |
166 | - Total npm downloads badge
167 | - Online/Local options in configuration node (Local still not functional)
168 | - Internal common functions to set node status
169 | - New Filters configurations when `All predictions` Output mode is selected
170 | - Threshold in % - (0 -> 100%)
171 | - Max. results - (1 -> 5)
172 | - General code optimitzations
173 | - [Mentions](https://github.com/bonastreyair/node-red-contrib-teachable-machine#mentions) section in `README` file
174 |
175 | ### Changed
176 |
177 | - Icon updated to **Tensorflow 2.0** new logo
178 | - Updated configuration node
179 | - Using all `README` badges from [Shields.io](https://shields.io/)
180 | - Outputs is always an array of results even if `Best prediction` is selected
181 |
182 | ## [0.1.3] - 2020-04-12
183 |
184 | ### Added
185 |
186 | - Use of badges in `README` file
187 | - New images for _Installation_ and _Node usage_ in `README`
188 | - `JavaScript` code has been standarized following [Standard JS](https://standardjs.com/index.html)
189 |
190 | ### Changed
191 |
192 | - Information on HTML node [#5](https://github.com/bonastreyair/node-red-contrib-teachable-machine/issues/5)
193 |
194 | ### Fixed
195 |
196 | - Typos on `README`
197 | - `basic` example with issues to load
198 | - Errors not shown on console or in `Node-RED`
199 |
200 | ## [0.1.2] - 2020-04-12
201 |
202 | ### Added
203 |
204 | - Improvements on `README` file
205 |
206 | ### Fixed
207 |
208 | - Loading model error `response.arrayBuffer is not a function` [#3](https://github.com/bonastreyair/node-red-contrib-teachable-machine/issues/3)
209 |
210 | ## [0.1.1] - 2020-04-11
211 |
212 | ### Added
213 |
214 | - Comments in the code
215 |
216 | ### Changed
217 |
218 | - Downgraded `@tensorflow/tfjs-node` from version `1.4.0` to `1.3.1` for better compatibility
219 | - Output has changed from `checkbox` to a `list`, you can now select `Best predictions` or `All predictions`
220 | - Code cleaning
221 |
222 | ### Fixed
223 |
224 | - WebGL loading error in JSDOM
225 | - When installing the node -> `npm WARN @teachablemachine/image@0.8.4 requires a peer of @tensorflow/tfjs@1.3.1 but none is installed`
226 |
227 | ## 0.1.0 - 2020-04-11
228 |
229 | ### Added
230 |
231 | - Functional using **Teachable Machine** Online Model URL
232 | - Option to select **Top-1** or all results
233 | - `CHANGELOG.md` file
234 | - `README.md` file
235 |
236 | [0.1.1]: https://github.com/bonastreyair/node-red-contrib-teachable-machine/compare/v0.1.0...v0.1.1
237 | [0.1.2]: https://github.com/bonastreyair/node-red-contrib-teachable-machine/compare/v0.1.1...v0.1.2
238 | [0.1.3]: https://github.com/bonastreyair/node-red-contrib-teachable-machine/compare/v0.1.2...v0.1.3
239 | [1.0.0]: https://github.com/bonastreyair/node-red-contrib-teachable-machine/compare/v0.1.3...v1.0.0
240 | [1.0.1]: https://github.com/bonastreyair/node-red-contrib-teachable-machine/compare/v1.0.0...v1.0.1
241 | [1.1.0]: https://github.com/bonastreyair/node-red-contrib-teachable-machine/compare/v1.0.1...v1.1.0
242 | [1.1.1]: https://github.com/bonastreyair/node-red-contrib-teachable-machine/compare/v1.1.0...v1.1.1
243 | [1.1.2]: https://github.com/bonastreyair/node-red-contrib-teachable-machine/compare/v1.1.1...v1.1.2
244 | [1.1.3]: https://github.com/bonastreyair/node-red-contrib-teachable-machine/compare/v1.1.2...v1.1.3
245 | [1.1.4]: https://github.com/bonastreyair/node-red-contrib-teachable-machine/compare/v1.1.3...v1.1.4
246 | [1.1.5]: https://github.com/bonastreyair/node-red-contrib-teachable-machine/compare/v1.1.4...v1.1.5
247 | [1.2.0]: https://github.com/bonastreyair/node-red-contrib-teachable-machine/compare/v1.1.5...v1.2.0
248 | [1.2.1]: https://github.com/bonastreyair/node-red-contrib-teachable-machine/compare/v1.2.0...v1.2.1
249 | [1.2.2]: https://github.com/bonastreyair/node-red-contrib-teachable-machine/compare/v1.2.1...v1.2.2
250 | [1.3.0]: https://github.com/bonastreyair/node-red-contrib-teachable-machine/compare/v1.2.2...v1.3.0
251 | [1.3.1]: https://github.com/bonastreyair/node-red-contrib-teachable-machine/compare/v1.3.0...v1.3.1
252 | [1.4.0]: https://github.com/bonastreyair/node-red-contrib-teachable-machine/compare/v1.3.1...v1.4.0
253 |
--------------------------------------------------------------------------------
/teachable_machine.js:
--------------------------------------------------------------------------------
1 | module.exports = function (RED) {
2 | /* Initial Setup */
3 | const { Readable } = require('stream')
4 | const fs = require('fs')
5 | const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args))
6 | const tf = require('@tensorflow/tfjs-node')
7 | const PImage = require('pureimage')
8 |
9 | function isPng (buffer) {
10 | if (!buffer || buffer.length < 8) {
11 | return false
12 | }
13 |
14 | return buffer[0] === 0x89 &&
15 | buffer[1] === 0x50 &&
16 | buffer[2] === 0x4E &&
17 | buffer[3] === 0x47 &&
18 | buffer[4] === 0x0D &&
19 | buffer[5] === 0x0A &&
20 | buffer[6] === 0x1A &&
21 | buffer[7] === 0x0A
22 | }
23 |
24 | function teachableMachine (config) {
25 | /* Node-RED Node Code Creation */
26 | RED.nodes.createNode(this, config)
27 | const node = this
28 |
29 | const nodeStatus = {
30 | MODEL: {
31 | LOADING: { fill: 'yellow', shape: 'ring', text: 'loading...' },
32 | RELOADING: { fill: 'yellow', shape: 'ring', text: 'reloading...' },
33 | READY: { fill: 'green', shape: 'dot', text: 'ready' },
34 | DECODING: { fill: 'green', shape: 'ring', text: 'decoding...' },
35 | PREPROCESSING: { fill: 'green', shape: 'ring', text: 'preprocessing...' },
36 | INFERENCING: { fill: 'green', shape: 'ring', text: 'inferencing...' },
37 | POSTPROCESSING: { fill: 'green', shape: 'ring', text: 'postprocessing...' },
38 | RESULT: (text) => { return { fill: 'green', shape: 'dot', text } }
39 | },
40 | ERROR: (text) => { node.error(text); return { fill: 'red', shape: 'dot', text } },
41 | CLOSE: {}
42 | }
43 |
44 | class ModelManager {
45 | constructor () {
46 | this.ready = false
47 | this.labels = []
48 | }
49 |
50 | async load (uri) {
51 | if (this.ready) {
52 | node.status(nodeStatus.MODEL.RELOADING)
53 | } else {
54 | node.status(nodeStatus.MODEL.LOADING)
55 | }
56 |
57 | this.model = await this.getModel(uri)
58 | this.labels = await this.getLabels(uri)
59 |
60 | this.input = {
61 | height: this.model.inputs[0].shape[1],
62 | width: this.model.inputs[0].shape[2],
63 | channels: this.model.inputs[0].shape[3]
64 | }
65 |
66 | this.ready = true
67 | return this.model
68 | }
69 |
70 | async getModel (uri) {
71 | throw new Error('getModel(uri) needs to be implemented')
72 | }
73 |
74 | async getLabels (uri) {
75 | throw new Error('getLabels(uri) needs to be implemented')
76 | }
77 | }
78 |
79 | class OnlineModelManager extends ModelManager {
80 | async getModel (uri) {
81 | return await tf.loadLayersModel(uri + 'model.json')
82 | }
83 |
84 | async getLabels (uri) {
85 | const response = await fetch(uri + 'metadata.json')
86 | return JSON.parse(await response.text()).labels
87 | }
88 | }
89 |
90 | class LocalModelManager extends ModelManager {
91 | async getModel (uri) {
92 | return await tf.loadLayersModel('file://' + uri + 'model.json')
93 | }
94 |
95 | async getLabels (uri) {
96 | const file = fs.readFileSync(uri + 'metadata.json')
97 | return JSON.parse(file).labels
98 | }
99 | }
100 |
101 | const modelManagerFactory = {
102 | online: new OnlineModelManager(),
103 | local: new LocalModelManager()
104 | }
105 |
106 | function nodeInit () {
107 | node.modelManager = modelManagerFactory[config.mode]
108 | if (config.modelUri !== '') {
109 | loadModel(config.modelUri)
110 | }
111 | }
112 |
113 | /**
114 | * Loads the Model trained from the Teachable Machine web.
115 | * @param uri where to load the model from
116 | */
117 | async function loadModel (uri) {
118 | try {
119 | node.model = await node.modelManager.load(uri)
120 | node.status(nodeStatus.MODEL.READY)
121 | } catch (error) {
122 | node.status(nodeStatus.ERROR(error))
123 | }
124 | }
125 |
126 | async function decodeImageBuffer (imageBuffer) {
127 | node.status(nodeStatus.MODEL.DECODING)
128 | const stream = new Readable({
129 | read () {
130 | this.push(imageBuffer)
131 | this.push(null)
132 | }
133 | })
134 | if (isPng(imageBuffer)) {
135 | return await PImage.decodePNGFromStream(stream)
136 | } else {
137 | return await PImage.decodeJPEGFromStream(stream)
138 | }
139 | }
140 |
141 | /**
142 | * Preprocess an image to be later passed to a model.predict().
143 | * @param image image in a bitmap format
144 | * @param inputShape input shape object of the model that contains height, width and channels
145 | */
146 | async function preprocess (image, inputShape) {
147 | node.status(nodeStatus.MODEL.PREPROCESSING)
148 | return tf.tidy(() => {
149 | // tf.browser.fromPixels() returns a Tensor from an image element.
150 | const resizedImage = tf.image.resizeNearestNeighbor(
151 | tf.browser.fromPixels(image).toFloat(),
152 | [inputShape.height, inputShape.width]
153 | )
154 |
155 | // Normalize the image from [0, 255] to [-1, 1].
156 | const offset = tf.scalar(127.5)
157 | const normalizedImage = resizedImage.sub(offset).div(offset)
158 |
159 | // Reshape to a single-element batch so we can pass it to predict.
160 | return normalizedImage.reshape([1, inputShape.height, inputShape.width, inputShape.channels])
161 | })
162 | }
163 |
164 | /**
165 | * Infers an image buffer to obtain classification predictions.
166 | * @param imageBuffer image buffer in png or jpeg format
167 | * @returns outputs of the model
168 | */
169 | async function inferImageBuffer (imageBuffer) {
170 | let image
171 | try {
172 | image = await decodeImageBuffer(imageBuffer)
173 | } catch (error) {
174 | node.error(error)
175 | return null
176 | }
177 | const inputs = await preprocess(image, node.modelManager.input)
178 | node.status(nodeStatus.MODEL.INFERENCING)
179 | return await node.model.predict(inputs)
180 | }
181 |
182 | /**
183 | * Computes the probabilities of the topK classes given logits by computing
184 | * softmax to get probabilities and then sorting the probabilities.
185 | * @param logits Tensor representing the logits from MobileNet.
186 | * @param topK The number of top predictions to show.
187 | */
188 | async function getTopKClasses (logits, topK) {
189 | const values = await logits.data()
190 | topK = Math.min(topK, values.length)
191 |
192 | const valuesAndIndices = []
193 | for (let i = 0; i < values.length; i++) {
194 | valuesAndIndices.push({ value: values[i], index: i })
195 | }
196 | valuesAndIndices.sort((a, b) => {
197 | return b.value - a.value
198 | })
199 | const topkValues = new Float32Array(topK)
200 | const topkIndices = new Int32Array(topK)
201 | for (let i = 0; i < topK; i++) {
202 | topkValues[i] = valuesAndIndices[i].value
203 | topkIndices[i] = valuesAndIndices[i].index
204 | }
205 |
206 | const topClassesAndProbs = []
207 | for (let i = 0; i < topkIndices.length; i++) {
208 | topClassesAndProbs.push({
209 | class: node.modelManager.labels[topkIndices[i]],
210 | score: topkValues[i]
211 | })
212 | }
213 | return topClassesAndProbs
214 | }
215 |
216 | /**
217 | * Post processes the outputs depending on the node configuration.
218 | * @param outputs
219 | * @returns a list of predictions
220 | */
221 | async function postprocess (outputs) {
222 | const predictions = await getTopKClasses(outputs, node.modelManager.labels.length)
223 |
224 | const bestProbability = predictions[0].score.toFixed(2) * 100
225 | const bestPredictionText = bestProbability.toString() + '% - ' + predictions[0].class
226 |
227 | if (config.output === 'best') {
228 | node.status(nodeStatus.MODEL.RESULT(bestPredictionText))
229 | return [predictions[0]]
230 | } else if (config.output === 'all') {
231 | let filteredPredictions = predictions
232 | filteredPredictions = config.activeThreshold ? filteredPredictions.filter(prediction => prediction.score > config.threshold / 100) : filteredPredictions
233 | filteredPredictions = config.activeMaxResults ? filteredPredictions.slice(0, config.maxResults) : filteredPredictions
234 |
235 | if (filteredPredictions.length > 0) {
236 | node.status(nodeStatus.MODEL.RESULT(bestPredictionText))
237 | } else {
238 | const statusText = 'score < ' + config.threshold + '%'
239 | node.status(nodeStatus.MODEL.RESULT(statusText))
240 | return []
241 | }
242 | return filteredPredictions
243 | }
244 | }
245 |
246 | /* Main Node Logic */
247 |
248 | nodeInit()
249 |
250 | node.on('input', async function (msg) {
251 | if (msg.reload) { await loadModel(config.modelUri); return }
252 | if (!node.modelManager.ready) { node.status(nodeStatus.ERROR('model not ready')); return }
253 | if (config.passThrough) { msg.image = msg.payload }
254 | const outputs = await inferImageBuffer(msg.payload)
255 | if (outputs === null) { node.status(nodeStatus.MODEL.READY); return }
256 | msg.payload = await postprocess(outputs)
257 | msg.classes = node.modelManager.labels
258 | node.send(msg)
259 | })
260 |
261 | node.on('close', function () {
262 | node.status(nodeStatus.CLOSE)
263 | })
264 | }
265 | RED.nodes.registerType('teachable machine', teachableMachine)
266 | }
267 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------