@zh-keyboard/recognizer 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,190 @@
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
+ Copyright 2025 dusionlike
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,72 @@
1
+ # @zh-keyboard/recognizer | 中文手写识别模块
2
+
3
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
4
+
5
+ 中文虚拟键盘组件库的手写识别模块
6
+
7
+ ## 功能特点
8
+
9
+ - ✏️ 实时手写汉字识别
10
+ - 🔧 可自定义识别模型和字典
11
+ - 🚀 识别速度快,纯cpu模式200ms内,可选webgl加速
12
+ - 📚 内置支持GB2312标准中的3755个一级汉字的识别支持
13
+ - 🔄 更多文字识别支持(包括二级汉字、生僻字等)暂不开放
14
+
15
+ ## 🤝 手写识别模型说明
16
+
17
+ **手写识别模型由我的一个朋友提供**
18
+
19
+ 如果您需要包括二级汉字、生僻字等的更完整的手写识别模型,以及更多的定制服务,请扫描下方二维码添加我朋友的QQ进行咨询:
20
+
21
+ <img src="qrcode.jpg" alt="联系二维码" width="50%">
22
+
23
+ ## 安装
24
+
25
+ ```bash
26
+ # 使用npm
27
+ npm install @zh-keyboard/recognizer
28
+
29
+ # 或使用pnpm
30
+ pnpm add @zh-keyboard/recognizer
31
+ ```
32
+
33
+ ## 基本用法
34
+
35
+ ```typescript
36
+ import { ZhkRecognizer } from '@zh-keyboard/recognizer'
37
+
38
+ // 创建识别器实例
39
+ const recognizer = new ZhkRecognizer({
40
+ modelPath: '/models/handwrite/model.json', // TensorFlow.js模型路径
41
+ dictPath: '/models/dict.txt', // 汉字字典路径
42
+ backend: 'webgl' // 可选:'webgl'或'cpu',默认为'cpu'
43
+ })
44
+
45
+ // 初始化识别器(加载模型和字典)
46
+ await recognizer.initialize()
47
+
48
+ // 使用识别器识别手写汉字
49
+ // strokeData格式:[x1, y1, isEnd1, x2, y2, isEnd2, ...]
50
+ // isEnd为0表示笔画继续,为1表示笔画结束
51
+ const strokeData = [10, 10, 0, 20, 20, 1,]
52
+ const results = await recognizer.recognize(strokeData)
53
+
54
+ // 识别结果是按置信度排序的汉字数组
55
+ console.log('识别结果:', results) // 例如 ['中', '申', '由', ...]
56
+
57
+ // 使用完毕后释放资源
58
+ await recognizer.close()
59
+ ```
60
+
61
+ ## 参数
62
+
63
+ - `options`: 配置对象
64
+ - `modelPath`: 模型文件路径,指向TensorFlow.js模型的json文件
65
+ - `dictPath`: 字典文件路径,文本文件,每行一个汉字
66
+ - `backend`: 可选,TensorFlow.js后端类型,可选值为'webgl'或'cpu',默认为'cpu'
67
+
68
+ ## 性能优化
69
+
70
+ - 在支持WebGL的设备上使用'webgl'后端可以显著提高识别速度
71
+ - 初始化时会自动进行模型预热,减少首次识别的延迟
72
+ - 如果在移动设备上使用,建议使用较小的模型以提高响应速度
@@ -0,0 +1,32 @@
1
+ import { HandwritingRecognizer } from "@zh-keyboard/core";
2
+
3
+ //#region src/index.d.ts
4
+ interface RecognizerOptions {
5
+ /**
6
+ * 模型路径
7
+ */
8
+ modelPath: string;
9
+ /**
10
+ * 字典路径
11
+ */
12
+ dictPath: string;
13
+ /**
14
+ * 后端类型
15
+ */
16
+ backend?: 'webgl' | 'cpu';
17
+ }
18
+ declare class ZhkRecognizer implements HandwritingRecognizer {
19
+ private model?;
20
+ private dict;
21
+ private canvas;
22
+ private ctx;
23
+ private modelPath;
24
+ private dictPath;
25
+ private backend;
26
+ constructor(options: RecognizerOptions);
27
+ initialize(): Promise<boolean>;
28
+ recognize(strokeData: number[]): Promise<string[]>;
29
+ close(): Promise<void>;
30
+ } //#endregion
31
+ export { RecognizerOptions, ZhkRecognizer };
32
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1,32 @@
1
+ import { HandwritingRecognizer } from "@zh-keyboard/core";
2
+
3
+ //#region src/index.d.ts
4
+ interface RecognizerOptions {
5
+ /**
6
+ * 模型路径
7
+ */
8
+ modelPath: string;
9
+ /**
10
+ * 字典路径
11
+ */
12
+ dictPath: string;
13
+ /**
14
+ * 后端类型
15
+ */
16
+ backend?: 'webgl' | 'cpu';
17
+ }
18
+ declare class ZhkRecognizer implements HandwritingRecognizer {
19
+ private model?;
20
+ private dict;
21
+ private canvas;
22
+ private ctx;
23
+ private modelPath;
24
+ private dictPath;
25
+ private backend;
26
+ constructor(options: RecognizerOptions);
27
+ initialize(): Promise<boolean>;
28
+ recognize(strokeData: number[]): Promise<string[]>;
29
+ close(): Promise<void>;
30
+ } //#endregion
31
+ export { RecognizerOptions, ZhkRecognizer };
32
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ //#region rolldown:runtime
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
23
+
24
+ //#endregion
25
+ const __tensorflow_tfjs = __toESM(require("@tensorflow/tfjs"));
26
+
27
+ //#region src/index.ts
28
+ var ZhkRecognizer = class {
29
+ model;
30
+ dict = [];
31
+ canvas;
32
+ ctx;
33
+ modelPath;
34
+ dictPath;
35
+ backend;
36
+ constructor(options) {
37
+ this.modelPath = options.modelPath;
38
+ this.dictPath = options.dictPath;
39
+ this.backend = options.backend || "cpu";
40
+ this.canvas = document.createElement("canvas");
41
+ this.canvas.width = this.canvas.height = 64;
42
+ this.ctx = this.canvas.getContext("2d", { willReadFrequently: true });
43
+ }
44
+ async initialize() {
45
+ const text = await fetch(this.dictPath).then((r) => r.text());
46
+ this.dict = text.split("\n");
47
+ this.model = await __tensorflow_tfjs.loadGraphModel(this.modelPath);
48
+ if (this.backend === "webgl") {
49
+ await __tensorflow_tfjs.setBackend("webgl");
50
+ await __tensorflow_tfjs.ready();
51
+ await this.recognize([
52
+ 10,
53
+ 10,
54
+ 0,
55
+ 20,
56
+ 20,
57
+ 1
58
+ ]);
59
+ } else await __tensorflow_tfjs.setBackend("cpu");
60
+ return true;
61
+ }
62
+ async recognize(strokeData) {
63
+ if (!this.model) throw new Error("Model not initialized");
64
+ const { canvas, ctx, model, dict } = this;
65
+ ctx.fillStyle = "white";
66
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
67
+ const n = strokeData.length / 3;
68
+ const strokes = Array.from({ length: n }, (_, i) => ({
69
+ x: strokeData[3 * i],
70
+ y: strokeData[3 * i + 1],
71
+ isEnd: strokeData[3 * i + 2] === 1
72
+ }));
73
+ let minX = Infinity;
74
+ let minY = Infinity;
75
+ let maxX = -Infinity;
76
+ let maxY = -Infinity;
77
+ for (const { x, y } of strokes) {
78
+ if (x < minX) minX = x;
79
+ if (x > maxX) maxX = x;
80
+ if (y < minY) minY = y;
81
+ if (y > maxY) maxY = y;
82
+ }
83
+ const w = maxX - minX || 1;
84
+ const h = maxY - minY || 1;
85
+ const cx = (minX + maxX) / 2;
86
+ const cy = (minY + maxY) / 2;
87
+ const scale = Math.min(canvas.width * .9 / w, canvas.height * .9 / h);
88
+ ctx.strokeStyle = "black";
89
+ ctx.lineWidth = 2;
90
+ ctx.lineCap = "round";
91
+ ctx.lineJoin = "round";
92
+ let last = null;
93
+ for (const s of strokes) {
94
+ const x = canvas.width / 2 + (s.x - cx) * scale;
95
+ const y = canvas.height / 2 + (s.y - cy) * scale;
96
+ if (last && !last.isEnd) {
97
+ ctx.beginPath();
98
+ ctx.moveTo(canvas.width / 2 + (last.x - cx) * scale, canvas.height / 2 + (last.y - cy) * scale);
99
+ ctx.lineTo(x, y);
100
+ ctx.stroke();
101
+ } else {
102
+ ctx.beginPath();
103
+ ctx.moveTo(x, y);
104
+ }
105
+ last = s;
106
+ }
107
+ return __tensorflow_tfjs.tidy(() => {
108
+ const image = __tensorflow_tfjs.browser.fromPixels(canvas, 3).toFloat().div(255).expandDims();
109
+ const probs = model.predict(image).dataSync();
110
+ const idxs = Array.from(probs.keys()).sort((a, b) => probs[b] - probs[a]).slice(0, 10);
111
+ __tensorflow_tfjs.dispose(image);
112
+ return idxs.map((i) => i < dict.length ? dict[i] : "").filter(Boolean);
113
+ });
114
+ }
115
+ async close() {
116
+ this.model?.dispose();
117
+ this.model = void 0;
118
+ }
119
+ };
120
+
121
+ //#endregion
122
+ exports.ZhkRecognizer = ZhkRecognizer
123
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["options: RecognizerOptions","strokeData: number[]","last: { x: number, y: number, isEnd: boolean } | null"],"sources":["../src/index.ts"],"sourcesContent":["import type { HandwritingRecognizer } from '@zh-keyboard/core'\r\nimport * as tf from '@tensorflow/tfjs'\r\n\r\nexport interface RecognizerOptions {\r\n /**\r\n * 模型路径\r\n */\r\n modelPath: string\r\n /**\r\n * 字典路径\r\n */\r\n dictPath: string\r\n /**\r\n * 后端类型\r\n */\r\n backend?: 'webgl' | 'cpu'\r\n}\r\n\r\nexport class ZhkRecognizer implements HandwritingRecognizer {\r\n private model?: tf.GraphModel\r\n private dict: string[] = []\r\n private canvas: HTMLCanvasElement\r\n private ctx: CanvasRenderingContext2D\r\n private modelPath: string\r\n private dictPath: string\r\n private backend: 'webgl' | 'cpu'\r\n\r\n constructor(options: RecognizerOptions) {\r\n this.modelPath = options.modelPath\r\n this.dictPath = options.dictPath\r\n this.backend = options.backend || 'cpu'\r\n this.canvas = document.createElement('canvas')\r\n this.canvas.width = this.canvas.height = 64\r\n this.ctx = this.canvas.getContext('2d', { willReadFrequently: true })!\r\n }\r\n\r\n async initialize() {\r\n const text = await fetch(this.dictPath).then(r => r.text())\r\n this.dict = text.split('\\n')\r\n this.model = await tf.loadGraphModel(this.modelPath)\r\n // 如果后端为webgl,则需要进行预热\r\n if (this.backend === 'webgl') {\r\n await tf.setBackend('webgl')\r\n await tf.ready()\r\n await this.recognize([10, 10, 0, 20, 20, 1])\r\n } else {\r\n await tf.setBackend('cpu')\r\n }\r\n return true\r\n }\r\n\r\n async recognize(strokeData: number[]): Promise<string[]> {\r\n if (!this.model) {\r\n throw new Error('Model not initialized')\r\n }\r\n const { canvas, ctx, model, dict } = this\r\n ctx.fillStyle = 'white'\r\n ctx.fillRect(0, 0, canvas.width, canvas.height)\r\n\r\n const n = strokeData.length / 3\r\n const strokes = Array.from({ length: n }, (_, i) => ({\r\n x: strokeData[3 * i],\r\n y: strokeData[3 * i + 1],\r\n isEnd: strokeData[3 * i + 2] === 1,\r\n }))\r\n\r\n let minX = Infinity\r\n let minY = Infinity\r\n let maxX = -Infinity\r\n let maxY = -Infinity\r\n for (const { x, y } of strokes) {\r\n if (x < minX) {\r\n minX = x\r\n }\r\n if (x > maxX) {\r\n maxX = x\r\n }\r\n if (y < minY) {\r\n minY = y\r\n }\r\n if (y > maxY) {\r\n maxY = y\r\n }\r\n }\r\n\r\n const w = maxX - minX || 1\r\n const h = maxY - minY || 1\r\n const cx = (minX + maxX) / 2\r\n const cy = (minY + maxY) / 2\r\n const scale = Math.min(canvas.width * 0.9 / w, canvas.height * 0.9 / h)\r\n\r\n ctx.strokeStyle = 'black'\r\n ctx.lineWidth = 2\r\n ctx.lineCap = 'round'\r\n ctx.lineJoin = 'round'\r\n\r\n let last: { x: number, y: number, isEnd: boolean } | null = null\r\n for (const s of strokes) {\r\n const x = canvas.width / 2 + (s.x - cx) * scale\r\n const y = canvas.height / 2 + (s.y - cy) * scale\r\n if (last && !last.isEnd) {\r\n ctx.beginPath()\r\n ctx.moveTo(canvas.width / 2 + (last.x - cx) * scale, canvas.height / 2 + (last.y - cy) * scale)\r\n ctx.lineTo(x, y)\r\n ctx.stroke()\r\n } else {\r\n ctx.beginPath()\r\n ctx.moveTo(x, y)\r\n }\r\n last = s\r\n }\r\n\r\n return tf.tidy(() => {\r\n const image = tf.browser.fromPixels(canvas, 3)\r\n .toFloat()\r\n .div(255)\r\n .expandDims()\r\n\r\n const probs = (model!.predict(image) as tf.Tensor).dataSync()\r\n const idxs = Array.from(probs.keys()).sort((a, b) => probs[b] - probs[a]).slice(0, 10)\r\n\r\n tf.dispose(image)\r\n return idxs.map(i => (i < dict.length ? dict[i] : '')).filter(Boolean)\r\n })\r\n }\r\n\r\n async close() {\r\n this.model?.dispose()\r\n this.model = undefined\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,IAAa,gBAAb,MAA4D;CAC1D,AAAQ;CACR,AAAQ,OAAiB,CAAE;CAC3B,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CAER,YAAYA,SAA4B;AACtC,OAAK,YAAY,QAAQ;AACzB,OAAK,WAAW,QAAQ;AACxB,OAAK,UAAU,QAAQ,WAAW;AAClC,OAAK,SAAS,SAAS,cAAc,SAAS;AAC9C,OAAK,OAAO,QAAQ,KAAK,OAAO,SAAS;AACzC,OAAK,MAAM,KAAK,OAAO,WAAW,MAAM,EAAE,oBAAoB,KAAM,EAAC;CACtE;CAED,MAAM,aAAa;EACjB,MAAM,OAAO,MAAM,MAAM,KAAK,SAAS,CAAC,KAAK,OAAK,EAAE,MAAM,CAAC;AAC3D,OAAK,OAAO,KAAK,MAAM,KAAK;AAC5B,OAAK,QAAQ,MAAM,kBAAG,eAAe,KAAK,UAAU;AAEpD,MAAI,KAAK,YAAY,SAAS;AAC5B,SAAM,kBAAG,WAAW,QAAQ;AAC5B,SAAM,kBAAG,OAAO;AAChB,SAAM,KAAK,UAAU;IAAC;IAAI;IAAI;IAAG;IAAI;IAAI;GAAE,EAAC;EAC7C,MACC,OAAM,kBAAG,WAAW,M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I,MAAM,MAAM;AAC/F,QAAI,OAAO,GAAG,EAAE;AAChB,QAAI,QAAQ;GACb,OAAM;AACL,QAAI,WAAW;AACf,QAAI,OAAO,GAAG,EAAE;GACjB;AACD,UAAO;EACR;AAED,SAAO,kBAAG,KAAK,MAAM;GACnB,MAAM,QAAQ,kBAAG,QAAQ,WAAW,QAAQ,EAAE,CAC3C,SAAS,CACT,IAAI,IAAI,CACR,YAAY;GAEf,MAAM,QAAQ,AAAC,MAAO,QAAQ,MAAM,CAAe,UAAU;GAC7D,MAAM,OAAO,MAAM,KAAK,MAAM,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,MAAM,MAAM,KAAK,MAAM,GAAG,CAAC,MAAM,GAAG,GAAG;AAEtF,qBAAG,QAAQ,MAAM;AACjB,UAAO,KAAK,IAAI,OAAM,IAAI,KAAK,SAAS,KAAK,KAAK,GAAI,CAAC,OAAO,QAAQ;EACvE,EAAC;CACH;CAED,MAAM,QAAQ;AACZ,OAAK,OAAO,SAAS;AACrB,OAAK;CACN;AACF"}
package/dist/index.mjs ADDED
@@ -0,0 +1,99 @@
1
+ import * as tf from "@tensorflow/tfjs";
2
+
3
+ //#region src/index.ts
4
+ var ZhkRecognizer = class {
5
+ model;
6
+ dict = [];
7
+ canvas;
8
+ ctx;
9
+ modelPath;
10
+ dictPath;
11
+ backend;
12
+ constructor(options) {
13
+ this.modelPath = options.modelPath;
14
+ this.dictPath = options.dictPath;
15
+ this.backend = options.backend || "cpu";
16
+ this.canvas = document.createElement("canvas");
17
+ this.canvas.width = this.canvas.height = 64;
18
+ this.ctx = this.canvas.getContext("2d", { willReadFrequently: true });
19
+ }
20
+ async initialize() {
21
+ const text = await fetch(this.dictPath).then((r) => r.text());
22
+ this.dict = text.split("\n");
23
+ this.model = await tf.loadGraphModel(this.modelPath);
24
+ if (this.backend === "webgl") {
25
+ await tf.setBackend("webgl");
26
+ await tf.ready();
27
+ await this.recognize([
28
+ 10,
29
+ 10,
30
+ 0,
31
+ 20,
32
+ 20,
33
+ 1
34
+ ]);
35
+ } else await tf.setBackend("cpu");
36
+ return true;
37
+ }
38
+ async recognize(strokeData) {
39
+ if (!this.model) throw new Error("Model not initialized");
40
+ const { canvas, ctx, model, dict } = this;
41
+ ctx.fillStyle = "white";
42
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
43
+ const n = strokeData.length / 3;
44
+ const strokes = Array.from({ length: n }, (_, i) => ({
45
+ x: strokeData[3 * i],
46
+ y: strokeData[3 * i + 1],
47
+ isEnd: strokeData[3 * i + 2] === 1
48
+ }));
49
+ let minX = Infinity;
50
+ let minY = Infinity;
51
+ let maxX = -Infinity;
52
+ let maxY = -Infinity;
53
+ for (const { x, y } of strokes) {
54
+ if (x < minX) minX = x;
55
+ if (x > maxX) maxX = x;
56
+ if (y < minY) minY = y;
57
+ if (y > maxY) maxY = y;
58
+ }
59
+ const w = maxX - minX || 1;
60
+ const h = maxY - minY || 1;
61
+ const cx = (minX + maxX) / 2;
62
+ const cy = (minY + maxY) / 2;
63
+ const scale = Math.min(canvas.width * .9 / w, canvas.height * .9 / h);
64
+ ctx.strokeStyle = "black";
65
+ ctx.lineWidth = 2;
66
+ ctx.lineCap = "round";
67
+ ctx.lineJoin = "round";
68
+ let last = null;
69
+ for (const s of strokes) {
70
+ const x = canvas.width / 2 + (s.x - cx) * scale;
71
+ const y = canvas.height / 2 + (s.y - cy) * scale;
72
+ if (last && !last.isEnd) {
73
+ ctx.beginPath();
74
+ ctx.moveTo(canvas.width / 2 + (last.x - cx) * scale, canvas.height / 2 + (last.y - cy) * scale);
75
+ ctx.lineTo(x, y);
76
+ ctx.stroke();
77
+ } else {
78
+ ctx.beginPath();
79
+ ctx.moveTo(x, y);
80
+ }
81
+ last = s;
82
+ }
83
+ return tf.tidy(() => {
84
+ const image = tf.browser.fromPixels(canvas, 3).toFloat().div(255).expandDims();
85
+ const probs = model.predict(image).dataSync();
86
+ const idxs = Array.from(probs.keys()).sort((a, b) => probs[b] - probs[a]).slice(0, 10);
87
+ tf.dispose(image);
88
+ return idxs.map((i) => i < dict.length ? dict[i] : "").filter(Boolean);
89
+ });
90
+ }
91
+ async close() {
92
+ this.model?.dispose();
93
+ this.model = void 0;
94
+ }
95
+ };
96
+
97
+ //#endregion
98
+ export { ZhkRecognizer };
99
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["options: RecognizerOptions","strokeData: number[]","last: { x: number, y: number, isEnd: boolean } | null"],"sources":["../src/index.ts"],"sourcesContent":["import type { HandwritingRecognizer } from '@zh-keyboard/core'\r\nimport * as tf from '@tensorflow/tfjs'\r\n\r\nexport interface RecognizerOptions {\r\n /**\r\n * 模型路径\r\n */\r\n modelPath: string\r\n /**\r\n * 字典路径\r\n */\r\n dictPath: string\r\n /**\r\n * 后端类型\r\n */\r\n backend?: 'webgl' | 'cpu'\r\n}\r\n\r\nexport class ZhkRecognizer implements HandwritingRecognizer {\r\n private model?: tf.GraphModel\r\n private dict: string[] = []\r\n private canvas: HTMLCanvasElement\r\n private ctx: CanvasRenderingContext2D\r\n private modelPath: string\r\n private dictPath: string\r\n private backend: 'webgl' | 'cpu'\r\n\r\n constructor(options: RecognizerOptions) {\r\n this.modelPath = options.modelPath\r\n this.dictPath = options.dictPath\r\n this.backend = options.backend || 'cpu'\r\n this.canvas = document.createElement('canvas')\r\n this.canvas.width = this.canvas.height = 64\r\n this.ctx = this.canvas.getContext('2d', { willReadFrequently: true })!\r\n }\r\n\r\n async initialize() {\r\n const text = await fetch(this.dictPath).then(r => r.text())\r\n this.dict = text.split('\\n')\r\n this.model = await tf.loadGraphModel(this.modelPath)\r\n // 如果后端为webgl,则需要进行预热\r\n if (this.backend === 'webgl') {\r\n await tf.setBackend('webgl')\r\n await tf.ready()\r\n await this.recognize([10, 10, 0, 20, 20, 1])\r\n } else {\r\n await tf.setBackend('cpu')\r\n }\r\n return true\r\n }\r\n\r\n async recognize(strokeData: number[]): Promise<string[]> {\r\n if (!this.model) {\r\n throw new Error('Model not initialized')\r\n }\r\n const { canvas, ctx, model, dict } = this\r\n ctx.fillStyle = 'white'\r\n ctx.fillRect(0, 0, canvas.width, canvas.height)\r\n\r\n const n = strokeData.length / 3\r\n const strokes = Array.from({ length: n }, (_, i) => ({\r\n x: strokeData[3 * i],\r\n y: strokeData[3 * i + 1],\r\n isEnd: strokeData[3 * i + 2] === 1,\r\n }))\r\n\r\n let minX = Infinity\r\n let minY = Infinity\r\n let maxX = -Infinity\r\n let maxY = -Infinity\r\n for (const { x, y } of strokes) {\r\n if (x < minX) {\r\n minX = x\r\n }\r\n if (x > maxX) {\r\n maxX = x\r\n }\r\n if (y < minY) {\r\n minY = y\r\n }\r\n if (y > maxY) {\r\n maxY = y\r\n }\r\n }\r\n\r\n const w = maxX - minX || 1\r\n const h = maxY - minY || 1\r\n const cx = (minX + maxX) / 2\r\n const cy = (minY + maxY) / 2\r\n const scale = Math.min(canvas.width * 0.9 / w, canvas.height * 0.9 / h)\r\n\r\n ctx.strokeStyle = 'black'\r\n ctx.lineWidth = 2\r\n ctx.lineCap = 'round'\r\n ctx.lineJoin = 'round'\r\n\r\n let last: { x: number, y: number, isEnd: boolean } | null = null\r\n for (const s of strokes) {\r\n const x = canvas.width / 2 + (s.x - cx) * scale\r\n const y = canvas.height / 2 + (s.y - cy) * scale\r\n if (last && !last.isEnd) {\r\n ctx.beginPath()\r\n ctx.moveTo(canvas.width / 2 + (last.x - cx) * scale, canvas.height / 2 + (last.y - cy) * scale)\r\n ctx.lineTo(x, y)\r\n ctx.stroke()\r\n } else {\r\n ctx.beginPath()\r\n ctx.moveTo(x, y)\r\n }\r\n last = s\r\n }\r\n\r\n return tf.tidy(() => {\r\n const image = tf.browser.fromPixels(canvas, 3)\r\n .toFloat()\r\n .div(255)\r\n .expandDims()\r\n\r\n const probs = (model!.predict(image) as tf.Tensor).dataSync()\r\n const idxs = Array.from(probs.keys()).sort((a, b) => probs[b] - probs[a]).slice(0, 10)\r\n\r\n tf.dispose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AAO,MAAM,KAAK,MAAM,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,MAAM,MAAM,KAAK,MAAM,GAAG,CAAC,MAAM,GAAG,GAAG;AAEtF,MAAG,QAAQ,MAAM;AACjB,UAAO,KAAK,IAAI,OAAM,IAAI,KAAK,SAAS,KAAK,KAAK,GAAI,CAAC,OAAO,QAAQ;EACvE,EAAC;CACH;CAED,MAAM,QAAQ;AACZ,OAAK,OAAO,SAAS;AACrB,OAAK;CACN;AACF"}
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@zh-keyboard/recognizer",
3
+ "version": "0.1.0",
4
+ "description": "中文手写汉字识别器组件",
5
+ "author": "dusionlike",
6
+ "license": "Apache 2.0",
7
+ "keywords": [
8
+ "键盘",
9
+ "中文",
10
+ "虚拟键盘",
11
+ "手写识别",
12
+ "汉字识别",
13
+ "中文输入法",
14
+ "组件"
15
+ ],
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.mjs",
20
+ "require": "./dist/index.js"
21
+ }
22
+ },
23
+ "main": "dist/index.js",
24
+ "module": "dist/index.mjs",
25
+ "types": "dist/index.d.ts",
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "dependencies": {
30
+ "@tensorflow/tfjs": "^4.22.0",
31
+ "@zh-keyboard/core": "0.1.0"
32
+ },
33
+ "devDependencies": {
34
+ "tsdown": "^0.11.1",
35
+ "typescript": "^5.0.0",
36
+ "vitest": "^1.0.0"
37
+ },
38
+ "scripts": {
39
+ "dev": "tsdown --watch",
40
+ "build": "tsdown",
41
+ "test": "vitest run"
42
+ }
43
+ }