@webwriter/deep-learning-model 0.0.1 → 1.0.2

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.
Files changed (186) hide show
  1. package/.github/workflows/main.yml +8 -0
  2. package/LICENSE +7 -0
  3. package/README.md +290 -0
  4. package/components/dataset-input/dataset-input.styles.ts +20 -0
  5. package/components/dataset-input/dataset-input.ts +196 -0
  6. package/components/inference-fields/class-input.ts +83 -0
  7. package/components/inference-fields/class-output.ts +62 -0
  8. package/components/inference-fields/image-input.ts +182 -0
  9. package/components/inference-fields/image.ts +82 -0
  10. package/components/inference-fields/inference-interfaces.ts +15 -0
  11. package/components/inference-fields/number-input.ts +62 -0
  12. package/components/inference-fields/number-output.ts +56 -0
  13. package/components/model-editor.ts +288 -0
  14. package/components/model-tests/bad-samples.ts +152 -0
  15. package/components/model-tests/loss-distribution.ts +174 -0
  16. package/components/reference-element-select.ts +105 -0
  17. package/custom-elements.json +1470 -0
  18. package/custom.d.ts +180 -0
  19. package/dist/widgets/webwriter-feature-engineering.css +444 -0
  20. package/dist/widgets/webwriter-feature-engineering.js +112763 -0
  21. package/dist/widgets/webwriter-model-designing.css +444 -0
  22. package/dist/widgets/webwriter-model-designing.js +114587 -0
  23. package/dist/widgets/webwriter-model-evaluation.css +444 -0
  24. package/dist/widgets/webwriter-model-evaluation.js +119010 -0
  25. package/dist/widgets/webwriter-model-prediction.css +444 -0
  26. package/dist/widgets/webwriter-model-prediction.js +109251 -0
  27. package/dist/widgets/webwriter-model-training.css +444 -0
  28. package/dist/widgets/webwriter-model-training.js +121465 -0
  29. package/editing-config.json +73 -0
  30. package/icon.svg +1 -0
  31. package/lib/dataset/class.ts +155 -0
  32. package/lib/dataset/dataset.ts +293 -0
  33. package/lib/dataset/feature.ts +110 -0
  34. package/lib/dataset/image.ts +312 -0
  35. package/lib/dataset/linear.ts +120 -0
  36. package/lib/layers/activation.ts +48 -0
  37. package/lib/layers/add.ts +50 -0
  38. package/lib/layers/attention.ts +74 -0
  39. package/lib/layers/concat.ts +50 -0
  40. package/lib/layers/conv.ts +83 -0
  41. package/lib/layers/dropout.ts +44 -0
  42. package/lib/layers/fcl.ts +66 -0
  43. package/lib/layers/flatten.ts +48 -0
  44. package/lib/layers/index.ts +770 -0
  45. package/lib/layers/input.ts +55 -0
  46. package/lib/layers/noise.ts +43 -0
  47. package/lib/layers/output.ts +64 -0
  48. package/lib/layers/reshape.ts +76 -0
  49. package/lib/layers/transposeconv.ts +90 -0
  50. package/lib/tflib.ts +10 -0
  51. package/lit-localize.json +47 -0
  52. package/localization/ar.xlf +553 -0
  53. package/localization/bg.xlf +552 -0
  54. package/localization/cs.xlf +553 -0
  55. package/localization/da.xlf +552 -0
  56. package/localization/de.xlf +552 -0
  57. package/localization/el.xlf +554 -0
  58. package/localization/es.xlf +553 -0
  59. package/localization/et.xlf +553 -0
  60. package/localization/fi.xlf +552 -0
  61. package/localization/fr.xlf +553 -0
  62. package/localization/generated/ar.ts +159 -0
  63. package/localization/generated/bg.ts +158 -0
  64. package/localization/generated/cs.ts +159 -0
  65. package/localization/generated/da.ts +158 -0
  66. package/localization/generated/de.ts +158 -0
  67. package/localization/generated/el.ts +160 -0
  68. package/localization/generated/es.ts +159 -0
  69. package/localization/generated/et.ts +159 -0
  70. package/localization/generated/fi.ts +158 -0
  71. package/localization/generated/fr.ts +159 -0
  72. package/localization/generated/hu.ts +158 -0
  73. package/localization/generated/id.ts +159 -0
  74. package/localization/generated/index.js +3 -0
  75. package/localization/generated/it.ts +159 -0
  76. package/localization/generated/ja.ts +158 -0
  77. package/localization/generated/ko.ts +158 -0
  78. package/localization/generated/locale-codes.js +83 -0
  79. package/localization/generated/lt.ts +158 -0
  80. package/localization/generated/lv.ts +158 -0
  81. package/localization/generated/nb.ts +158 -0
  82. package/localization/generated/nl.ts +158 -0
  83. package/localization/generated/pl.ts +159 -0
  84. package/localization/generated/pt-BR.ts +159 -0
  85. package/localization/generated/pt-PT.ts +159 -0
  86. package/localization/generated/ro.ts +159 -0
  87. package/localization/generated/ru.ts +159 -0
  88. package/localization/generated/sk.ts +159 -0
  89. package/localization/generated/sl.ts +159 -0
  90. package/localization/generated/sv.ts +158 -0
  91. package/localization/generated/tr.ts +158 -0
  92. package/localization/generated/uk.ts +158 -0
  93. package/localization/generated/zh-hans.ts +141 -0
  94. package/localization/generated/zh-hant.ts +141 -0
  95. package/localization/hu.xlf +552 -0
  96. package/localization/id.xlf +553 -0
  97. package/localization/it.xlf +553 -0
  98. package/localization/ja.xlf +552 -0
  99. package/localization/ko.xlf +552 -0
  100. package/localization/lt.xlf +552 -0
  101. package/localization/lv.xlf +552 -0
  102. package/localization/nb.xlf +552 -0
  103. package/localization/nl.xlf +552 -0
  104. package/localization/pkg/ar.xliff +7 -0
  105. package/localization/pkg/bg.xliff +7 -0
  106. package/localization/pkg/cs.xliff +7 -0
  107. package/localization/pkg/da.xliff +7 -0
  108. package/localization/pkg/de.xliff +7 -0
  109. package/localization/pkg/el.xliff +7 -0
  110. package/localization/pkg/es.xliff +7 -0
  111. package/localization/pkg/et.xliff +7 -0
  112. package/localization/pkg/fi.xliff +7 -0
  113. package/localization/pkg/fr.xliff +7 -0
  114. package/localization/pkg/hu.xliff +7 -0
  115. package/localization/pkg/id.xliff +7 -0
  116. package/localization/pkg/it.xliff +7 -0
  117. package/localization/pkg/ja.xliff +7 -0
  118. package/localization/pkg/ko.xliff +7 -0
  119. package/localization/pkg/lt.xliff +7 -0
  120. package/localization/pkg/lv.xliff +7 -0
  121. package/localization/pkg/nb.xliff +7 -0
  122. package/localization/pkg/nl.xliff +7 -0
  123. package/localization/pkg/pl.xliff +7 -0
  124. package/localization/pkg/pt-BR.xliff +7 -0
  125. package/localization/pkg/pt-PT.xliff +7 -0
  126. package/localization/pkg/ro.xliff +7 -0
  127. package/localization/pkg/ru.xliff +7 -0
  128. package/localization/pkg/sk.xliff +7 -0
  129. package/localization/pkg/sl.xliff +7 -0
  130. package/localization/pkg/sv.xliff +7 -0
  131. package/localization/pkg/tr.xliff +7 -0
  132. package/localization/pkg/uk.xliff +7 -0
  133. package/localization/pkg/zh-hans.xliff +7 -0
  134. package/localization/pkg/zh-hant.xliff +7 -0
  135. package/localization/pl.xlf +553 -0
  136. package/localization/pt-BR.xlf +553 -0
  137. package/localization/pt-PT.xlf +553 -0
  138. package/localization/ro.xlf +553 -0
  139. package/localization/ru.xlf +553 -0
  140. package/localization/sk.xlf +553 -0
  141. package/localization/sl.xlf +553 -0
  142. package/localization/snippets/ar.xliff +16 -0
  143. package/localization/snippets/bg.xliff +16 -0
  144. package/localization/snippets/cs.xliff +16 -0
  145. package/localization/snippets/da.xliff +16 -0
  146. package/localization/snippets/de.xliff +16 -0
  147. package/localization/snippets/el.xliff +16 -0
  148. package/localization/snippets/es.xliff +16 -0
  149. package/localization/snippets/et.xliff +16 -0
  150. package/localization/snippets/fi.xliff +16 -0
  151. package/localization/snippets/fr.xliff +16 -0
  152. package/localization/snippets/hu.xliff +16 -0
  153. package/localization/snippets/id.xliff +16 -0
  154. package/localization/snippets/it.xliff +16 -0
  155. package/localization/snippets/ja.xliff +16 -0
  156. package/localization/snippets/ko.xliff +16 -0
  157. package/localization/snippets/lt.xliff +16 -0
  158. package/localization/snippets/lv.xliff +16 -0
  159. package/localization/snippets/nb.xliff +16 -0
  160. package/localization/snippets/nl.xliff +16 -0
  161. package/localization/snippets/pl.xliff +16 -0
  162. package/localization/snippets/pt-BR.xliff +16 -0
  163. package/localization/snippets/pt-PT.xliff +16 -0
  164. package/localization/snippets/ro.xliff +16 -0
  165. package/localization/snippets/ru.xliff +16 -0
  166. package/localization/snippets/sk.xliff +16 -0
  167. package/localization/snippets/sl.xliff +16 -0
  168. package/localization/snippets/sv.xliff +16 -0
  169. package/localization/snippets/tr.xliff +16 -0
  170. package/localization/snippets/uk.xliff +16 -0
  171. package/localization/snippets/zh-hans.xliff +16 -0
  172. package/localization/snippets/zh-hant.xliff +16 -0
  173. package/localization/sv.xlf +552 -0
  174. package/localization/tr.xlf +552 -0
  175. package/localization/uk.xlf +552 -0
  176. package/localization/zh-hans.xlf +552 -0
  177. package/localization/zh-hant.xlf +552 -0
  178. package/package.json +103 -2
  179. package/snippets/MNIST.html +21 -0
  180. package/test.json +63 -0
  181. package/tsconfig.json +8 -0
  182. package/widgets/webwriter-feature-engineering.ts +421 -0
  183. package/widgets/webwriter-model-designing.ts +323 -0
  184. package/widgets/webwriter-model-evaluation.ts +215 -0
  185. package/widgets/webwriter-model-prediction.ts +307 -0
  186. package/widgets/webwriter-model-training.ts +709 -0
@@ -0,0 +1,770 @@
1
+ import { SlInput, SlSelect } from '@shoelace-style/shoelace';
2
+ import Drawflow, { DrawflowConnectionDetail } from 'drawflow';
3
+ import { TransformedDataset } from '../dataset/dataset';
4
+ import { msg } from '@lit/localize';
5
+
6
+ import type * as TF from "@tensorflow/tfjs";
7
+ import getTF from "../tflib";
8
+ let tf: typeof TF;
9
+ (async () => {tf = await getTF()})()
10
+
11
+ type NonEmptyArray<T> = [T, ...T[]];
12
+ type Constructor<T> = new (...args: any[]) => T;
13
+
14
+
15
+ export const SIZE_SEP = "×";
16
+
17
+ export async function createLayer(name, ...args) {
18
+ const module = await import('./' + name + ".ts");
19
+ const LayerClass = module.ExportLayer;
20
+ return new LayerClass(...args);
21
+ }
22
+
23
+ /** Contains the model editor of the model design widget. Wrapper Class for easier control of Drawflow. */
24
+ export class Editor {
25
+ private editor: Drawflow;
26
+ private layers: Record<number, Layer> = {};
27
+
28
+ /** The editMode from the model design widget. */
29
+ public readonly editMode: string;
30
+
31
+ /** The max model params from the model design widget. */
32
+ public readonly maxModelParams: number;
33
+
34
+ /** The max layer params from the model design widget. */
35
+ public readonly maxLayerParams: number;
36
+
37
+ /** Called with the new selection state whenever a layer or connection is selected or unselected. */
38
+ public onSelectionChanged: ((selected: boolean) => void) | null = null;
39
+
40
+ constructor(container: HTMLDivElement, editMode:string = "edit", maxModelParams:number, maxLayerParams:number) {
41
+ let that = this;
42
+ this.editMode = editMode;
43
+ this.maxModelParams = maxModelParams;
44
+ this.maxLayerParams = maxLayerParams;
45
+ this.editor = new Drawflow(container);
46
+ this.editor.reroute = false;
47
+ this.editor.start();
48
+ this.editor.zoom_max = 1.6;
49
+ this.editor.zoom_min = 0.5;
50
+ this.editor.zoom_value = 0.5;
51
+ this.editor.editor_mode = editMode == "edit" ? "edit": "fixed";
52
+ this.editor.on("connectionCreated", function ({ output_id, input_id, output_class, input_class }) {
53
+ let outNode = that.editor.getNodeFromId(output_id);
54
+ let inNode = that.editor.getNodeFromId(input_id);
55
+
56
+ let outLayer = that.getLayer(outNode.id);
57
+ let inLayer = that.getLayer(inNode.id);
58
+
59
+ if (inNode.inputs[input_class].connections.length == 2) {
60
+ that.editor.removeSingleConnection(output_id, input_id, output_class, input_class);
61
+ return;
62
+ }
63
+
64
+ inLayer.trigger("connect", { layer: outLayer, output: output_class, input: input_class });
65
+ })
66
+ this.editor.on("connectionRemoved", function ({ output_id, input_id, output_class, input_class }) {
67
+ let outNode = that.editor.getNodeFromId(output_id);
68
+ let inNode = that.editor.getNodeFromId(input_id);
69
+
70
+ let outLayer = that.getLayer(outNode.id);
71
+ let inLayer = that.getLayer(inNode.id);
72
+
73
+ if (inNode.inputs[input_class].connections.length == 1)
74
+ return;
75
+
76
+ inLayer.trigger("disconnect", { layer: outLayer, output: output_class, input: input_class });
77
+ })
78
+ this.editor.on("nodeRemoved", function (id) {
79
+ delete that.layers[id];
80
+ })
81
+
82
+ const notifySelectionChanged = function () {
83
+ setTimeout(function () {
84
+ if (that.onSelectionChanged)
85
+ that.onSelectionChanged(that.hasSelection());
86
+ });
87
+ };
88
+ this.editor.on("nodeSelected", notifySelectionChanged);
89
+ this.editor.on("nodeUnselected", notifySelectionChanged);
90
+ this.editor.on("connectionSelected", notifySelectionChanged);
91
+ this.editor.on("connectionUnselected", notifySelectionChanged);
92
+ this.editor.on("nodeRemoved", notifySelectionChanged);
93
+ this.editor.on("connectionRemoved", notifySelectionChanged);
94
+
95
+ // Workaround for the fact that Drawflow does not support shadow DOM.
96
+ // This allows touch events to work correctly in the model design widget.
97
+ const nativeElementFromPoint = document.elementFromPoint.bind(document);
98
+ container.addEventListener("touchend", function () {
99
+ const root = container.getRootNode() as any;
100
+ if (root === document || typeof root.elementFromPoint !== "function")
101
+ return;
102
+ (document as any).elementFromPoint = function (x: number, y: number): Element {
103
+ let el = root.elementFromPoint(x, y) as Element | null;
104
+ while (el && (el as any).shadowRoot && (el as any).shadowRoot.elementFromPoint) {
105
+ const inner = (el as any).shadowRoot.elementFromPoint(x, y) as Element | null;
106
+ if (inner == null || inner === el)
107
+ break;
108
+ el = inner;
109
+ }
110
+ return el ?? nativeElementFromPoint(x, y);
111
+ };
112
+ setTimeout(function () { (document as any).elementFromPoint = nativeElementFromPoint; });
113
+ }, true);
114
+ }
115
+
116
+ /**
117
+ * Removes the currently selected node (layer) or connection from the editor.
118
+ */
119
+ public removeSelectedNode() {
120
+ let editor = this.editor as any;
121
+ if (editor.node_selected != null)
122
+ editor.removeNodeId(editor.node_selected.id);
123
+ else if (editor.connection_selected != null)
124
+ editor.removeConnection();
125
+ }
126
+ /** Whether something is currently selected in the editor. */
127
+ public hasSelection(): boolean {
128
+ let editor = this.editor as any;
129
+ return editor.node_selected != null || editor.connection_selected != null;
130
+ }
131
+ /** Returns the average position of the layer nodes. Used to center the view. */
132
+ getAveragePosition() {
133
+ let pos: { x: number, y: number } = { x: 0, y: 0 };
134
+ let count = 0;
135
+ for (let layer of Object.values(this.layers)) {
136
+ pos.x += layer.getNode().pos_x;
137
+ pos.y += layer.getNode().pos_y;
138
+ count++;
139
+ }
140
+ if (count > 0) {
141
+ pos.x /= count;
142
+ pos.y /= count;
143
+ }
144
+ return pos;
145
+ }
146
+ getNumberOfParameters() {
147
+ let sum = 0;
148
+ Object.values(this.layers).forEach(element => {
149
+ sum += element.getNumberOfParameters();
150
+ });
151
+ return sum;
152
+ }
153
+ getNumberOfOperations() {
154
+ return Object.values(this.layers).filter(l => ["Input", "Output"].indexOf(l.type) == -1).length;
155
+ }
156
+ public createLayer(name, fields) {
157
+ createLayer(name, fields, this);
158
+ }
159
+ /**
160
+ * Returns a list of layers with the dependencies for inputs.
161
+ */
162
+ public export() {
163
+ let layers = Object.values(this.layers).map(value => value.getState()).sort((a, b) => a.id - b.id)
164
+ let currentId = 1;
165
+ for (let layer of layers) {
166
+ let lastId = layer.id;
167
+ layer.id = currentId;
168
+ for (let connectedAsInputLayer of layers) {
169
+ let connections: Record<string, DrawflowConnectionDetail> = connectedAsInputLayer.inputConnections
170
+ if (Object.keys(connections).length == 0)
171
+ continue;
172
+ for (let connection of Object.values(connections)) {
173
+ if (parseInt(connection.node) == lastId)
174
+ connection.node = String(currentId);
175
+ }
176
+ }
177
+ currentId++;
178
+ }
179
+ return layers;
180
+ }
181
+
182
+ /**
183
+ * Sets the model editor state to the layers of the input.
184
+ * @param layers The list of layers created by export.
185
+ * @param fields A tensor dataset which is used to get the names and input/output dimensions.
186
+ */
187
+ public async import(layers:any[], fields:TransformedDataset) {
188
+ let that = this;
189
+ return new Promise(async function(res, rej) {
190
+ let createdLayers = [];
191
+ layers = layers.sort(function (a, b) {
192
+ return parseInt(a.id) - parseInt(b.id);
193
+ })
194
+ for (let layer of layers) {
195
+ let createdLayer = await createLayer(layer.type, fields, that);
196
+ createdLayer.setState(layer);
197
+ createdLayers.push(createdLayer);
198
+ }
199
+ setTimeout(function () {
200
+ for (let layer of layers) {
201
+ for (let input in layer.inputConnections) {
202
+ let connection = layer.inputConnections[input];
203
+ if (connection != null) {
204
+ that.editor.addConnection(connection.node, layer.id, connection.input, input)
205
+ }
206
+ }
207
+ }
208
+ for (let layer of createdLayers)
209
+ if (layer.type == "input")
210
+ layer.update();
211
+
212
+ setTimeout(function() {
213
+ for (let layer of layers) {
214
+ for (let input in layer.inputConnections) {
215
+ let connection = layer.inputConnections[input];
216
+ if (connection != null) {
217
+ that.editor.addConnection(connection.node, layer.id, connection.input, input)
218
+ }
219
+ }
220
+ }
221
+ setTimeout(function() {
222
+ for (let layer of layers) {
223
+ that.updateConnectionNodes(layer);
224
+ }
225
+ })
226
+ res(null);
227
+ }, 100)
228
+ }, 100)
229
+ })
230
+ }
231
+ public updateConnectionNodes(layer: Layer) {
232
+ this.editor.updateConnectionNodes('node-'+layer.id);
233
+ }
234
+ public getOutputs():Array<Layer> {
235
+ return Object.values(this.layers).filter(l => l.getState().type == "output");
236
+ }
237
+ public getInputs():Array<Layer> {
238
+ return Object.values(this.layers).filter(l => l.getState().type == "input");
239
+ }
240
+ public registerLayer(layer: Layer) {
241
+ this.layers[layer.id] = layer;
242
+ }
243
+ public getLayer(id: number) {
244
+ return this.layers[id];
245
+ }
246
+ public getLayerFromNodeId(id: number) {
247
+ return Object.values<Layer>(this.layers).filter(l => l.id == id)[0];
248
+ }
249
+ public getNodeFromId(id: number) {
250
+ return this.editor.getNodeFromId(id);
251
+ }
252
+ public addLayer(inputs, outputs): number {
253
+ return this.editor.addNode('layer', inputs, outputs, -this.editor.canvas_x + this.editor.precanvas.clientWidth / 2 - 50, -this.editor.canvas_y + this.editor.precanvas.clientHeight / 2 - 50, 'layer', {}, "", false) as number;
254
+ }
255
+ public getNodeElement(id:number):HTMLDivElement {
256
+ return this.editor.container.querySelector("#node-" + id) as HTMLDivElement;
257
+ }
258
+ public addNodeInput(id:number) {
259
+ return this.editor.addNodeInput(id);
260
+ }
261
+ public addNodeOutput(id:number) {
262
+ return this.editor.addNodeInput(id);
263
+ }
264
+ public removeNodeInput(id:number, input:string) {
265
+ return this.editor.removeNodeInput(id, input);
266
+ }
267
+ public removeNodeOutput(id:number, input:string) {
268
+ return this.editor.removeNodeInput(id, input);
269
+ }
270
+ public zoomIn() {
271
+ this.editor.zoom *= 1.1;
272
+ this.editor.zoom_refresh();
273
+ }
274
+ public zoomOut() {
275
+ this.editor.zoom /= 1.1;
276
+ this.editor.zoom_refresh();
277
+ }
278
+ public zoomReset() {
279
+ this.editor.zoom = 1;
280
+ let pos = this.getAveragePosition();
281
+ this.editor.canvas_x = -pos.x + this.editor.precanvas.clientWidth / 2;
282
+ this.editor.canvas_y = -pos.y + this.editor.precanvas.clientHeight / 2;
283
+ this.editor.zoom_refresh();
284
+ }
285
+ }
286
+
287
+ /** Base Layer class */
288
+ export abstract class Layer {
289
+ public id: number;
290
+ public elem: HTMLElement;
291
+ private inputsDiv: HTMLDivElement;
292
+ private outputsDiv: HTMLDivElement;
293
+ private events = {};
294
+ public readonly type: string;
295
+ public readonly editor: Editor;
296
+ private hasCyclicReference = false;
297
+ private hasUpdatedOutputsThisUpdate = false;
298
+
299
+ /**
300
+ * Creates the drawflow node and sets the name and number of input/output fields
301
+ * @param inputs The number of possible input connections
302
+ * @param outputs The number of possible output connections
303
+ * @param name The name/type of the layer.
304
+ * @param editor Reference to the model editor used for settings.
305
+ */
306
+ constructor(inputs: number, outputs: number, name: string, editor: Editor) {
307
+ this.editor = editor;
308
+ this.id = editor.addLayer(inputs, outputs);
309
+ this.type = name || "Layer";
310
+
311
+ let nodeElement = editor.getNodeElement(this.id);
312
+ this.inputsDiv = nodeElement.getElementsByClassName("inputs")[0] as HTMLDivElement;
313
+ this.outputsDiv = nodeElement.getElementsByClassName("outputs")[0] as HTMLDivElement;
314
+ editor.registerLayer(this);
315
+
316
+ let elem = document.createElement("div");
317
+ let header = document.createElement("p");
318
+ header.innerText = this.getDisplayName();
319
+
320
+ let nodeContentElement = nodeElement.getElementsByClassName("drawflow_content_node")[0] as HTMLDivElement;
321
+ nodeContentElement.append(header);
322
+ nodeContentElement.append(elem);
323
+ this.elem = elem;
324
+
325
+ let that = this;
326
+ this.on("connect", function ({ layer, output, input }) {
327
+ that.update();
328
+ })
329
+ this.on("disconnect", function ({ layer, output, input }) {
330
+ let inputElem = that.getNodeInputElement(input)
331
+ if (inputElem != null)
332
+ inputElem.innerText = "";
333
+ that.update();
334
+ })
335
+ }
336
+
337
+ /**
338
+ * Allows subclasses to add a number input field to the node.
339
+ * @param label Label of the sl-input element
340
+ * @param min Min possible value
341
+ * @param max Max possible value
342
+ * @returns sl-input element that was added to the drawflow node.
343
+ */
344
+ protected addNumberInput(label:string, min: number, max:number):SlInput {
345
+ let that = this;
346
+
347
+ let input = document.createElement("sl-input");
348
+ input.type = "number";
349
+ input.min = String(min);
350
+ input.value = String(max);
351
+ input.addEventListener("sl-change", function () {
352
+ if (parseInt(input.value) > max) {
353
+ input.value = String(max);
354
+ input.oninput(null);
355
+ input.onchange(null);
356
+ }
357
+ if (isNaN(parseInt(input.value)) || parseInt(input.value) < min) {
358
+ input.value = String(min);
359
+ input.oninput(null);
360
+ input.onchange(null);
361
+ }
362
+ });
363
+ input.addEventListener("keypress", function(e) {
364
+ if (e.key == "Delete") {
365
+ e.stopPropagation()
366
+ return false;
367
+ }
368
+ })
369
+ input.addEventListener("keydown", function(e) {
370
+ if (e.key == "Delete") {
371
+ e.stopPropagation()
372
+ return false;
373
+ }
374
+ })
375
+ input.addEventListener("keyup", function(e) {
376
+ if (e.key == "Delete") {
377
+ e.stopPropagation()
378
+ return false;
379
+ }
380
+ })
381
+ input.label = label;
382
+ input.size = "small";
383
+ input.disabled = this.editor.editMode == "read"
384
+ this.elem.append(input);
385
+ return input;
386
+ }
387
+
388
+ /**
389
+ * Allows subclasses to add a select field to the node.
390
+ * @param label Label of the sl-select element
391
+ * @param options list of sl-options
392
+ * @returns sl-select element that was added to the drawflow node.
393
+ */
394
+ protected addSelect(label:string, options: string[]):SlSelect {
395
+ let select = document.createElement("sl-select");
396
+ for (let act of options) {
397
+ let option = document.createElement("sl-option");
398
+ option.value = act;
399
+ option.innerText = act;
400
+ select.append(option)
401
+ }
402
+ select.label = label;
403
+ select.size = "small";
404
+ select.disabled = this.editor.editMode == "read"
405
+ this.elem.append(select);
406
+ return select;
407
+ }
408
+
409
+ /**
410
+ * Allows subclasses to add a custom element to the node.
411
+ * @param label Label of the custom element
412
+ * @returns A paragraph wrapping the element that was added to the drawflow node.
413
+ */
414
+ protected addCustomElement(label:string, elem: HTMLElement):HTMLParagraphElement {
415
+ let p = document.createElement("p");
416
+ p.classList.add("label");
417
+ p.innerHTML = label;
418
+ p.append(elem);
419
+ this.elem.append(p);
420
+ return p;
421
+ }
422
+
423
+ /**
424
+ * Allows subclasses to add a span element to the node.
425
+ * @param label Label of the span element
426
+ * @returns A paragraph wrapping the span that was added to the drawflow node.
427
+ */
428
+ protected addTextElement(label:string, elem: HTMLSpanElement):HTMLParagraphElement {
429
+ let p = document.createElement("p");
430
+ p.innerHTML = label;
431
+ p.append(elem);
432
+ this.elem.append(p);
433
+ return p;
434
+ }
435
+ public getNode() {
436
+ return this.editor.getNodeFromId(this.id);
437
+ }
438
+ /**
439
+ * Allows to register a listener to an event for this layer
440
+ * @param event the name of the event
441
+ * @param callback listener
442
+ */
443
+ public on(event: string | "connect" | "disconnect", callback: Function) {
444
+ if (this.events[event] == null)
445
+ this.events[event] = [];
446
+ this.events[event].push(callback);
447
+ }
448
+ /**
449
+ * Triggers all listeners for the event
450
+ * @param event the name of the event
451
+ * @param params event data
452
+ */
453
+ public trigger(event: string, params: Record<string, any>) {
454
+ if (this.events[event] == null)
455
+ return;
456
+ for (let cb of this.events[event])
457
+ cb(params);
458
+ }
459
+ /**
460
+ * Adds a node on the left side of the layer for an input.
461
+ */
462
+ protected addInput() {
463
+ this.editor.addNodeInput(this.id);
464
+ }
465
+ /**
466
+ * Adds a node on the right side of the layer for an output.
467
+ */
468
+ protected addOutput() {
469
+ this.editor.addNodeOutput(this.id);
470
+ }
471
+ /**
472
+ * Removes all the inputs on the left side of the layer.
473
+ */
474
+ protected removeInputs() {
475
+ let node = this.getNode();
476
+ for (let input in node.inputs)
477
+ this.editor.removeNodeInput(node.id, "input_1");
478
+ }
479
+ /**
480
+ * Removes all the outputs on the right side of the layer.
481
+ */
482
+ protected removeOutputs() {
483
+ let node = this.getNode();
484
+ for (let output in node.outputs)
485
+ this.editor.removeNodeOutput(node.id, "output_1");
486
+ }
487
+ /**
488
+ * @returns the html element that wraps the entire layer.
489
+ */
490
+ protected getNodeElement() {
491
+ return this.elem?.parentElement?.parentElement;
492
+ }
493
+ /**
494
+ * @param input Typically named "input_1", "input_2", ...
495
+ * @returns the html element where the shape of the input with the name of the input.
496
+ */
497
+ protected getNodeInputElement(input: string) {
498
+ return this.inputsDiv.getElementsByClassName(input)[0] as HTMLElement;
499
+ }
500
+ /**
501
+ * @returns all the html elements where the shape of the inputs as innerHTML.
502
+ */
503
+ protected getNodeInputElements() {
504
+ return this.inputsDiv.children;
505
+ }
506
+ /**
507
+ * @returns all the html elements of the outputs for the connected inputs.
508
+ */
509
+ protected getConnectedInputElements() {
510
+ let ret: Record<string, HTMLElement> = {};
511
+ let inputs = this.getNodeInputElements();
512
+ for (let i = 1; i <= inputs.length; i++) {
513
+ let inputName = "input_" + i;
514
+ let connection = this.getNode().inputs[inputName].connections[0];
515
+ if (connection != null)
516
+ ret[inputName] = this.editor.getLayerFromNodeId(parseInt(connection.node)).getNodeOutputElement(connection.input);
517
+ }
518
+ return ret;
519
+ }
520
+ /**
521
+ * @returns all the layers and the name of the output for the connected inputs.
522
+ */
523
+ public getInputLayers() {
524
+ let ret: Record<string, {outputField: string, outputOfLayer: Layer}> = {};
525
+ let inputs = this.getNodeInputElements();
526
+ for (let i = 1; i <= inputs.length; i++) {
527
+ let inputName = "input_" + i;
528
+ let connection = this.getNode().inputs[inputName].connections[0];
529
+ if (connection != null)
530
+ ret[inputName] = {outputField: connection.input, outputOfLayer:this.editor.getLayerFromNodeId(parseInt(connection.node))};
531
+ }
532
+ return ret;
533
+ }
534
+ /**
535
+ * @param output Typically named "output_1", "output_2", ...
536
+ * @returns the html element of the output node.
537
+ */
538
+ protected getNodeOutputElement(output: string) {
539
+ return this.outputsDiv.getElementsByClassName(output)[0] as HTMLElement;
540
+ }
541
+ /**
542
+ * @returns all the html elements for the output nodes.
543
+ */
544
+ protected getNodeOutputElements() {
545
+ return this.outputsDiv.children;
546
+ }
547
+ /**
548
+ * @param outputname name of the output node. Typically "output_1", "output_2", ...
549
+ * @returns all connected layers for that output node.
550
+ */
551
+ protected getConnectedLayersForOutput(outputname: string) {
552
+ let that = this;
553
+ let output = this.getNode().outputs[outputname];
554
+ return output.connections.map(function (value) {
555
+ return that.editor.getLayerFromNodeId(parseInt(value.node));
556
+ })
557
+ }
558
+ /**
559
+ * @returns the number of trainable parameters for trainable layers.
560
+ */
561
+ public getNumberOfParameters(): number {
562
+ return 0;
563
+ }
564
+ /**
565
+ * @returns the save state for the layer. Used in the setState method when loading the design again.
566
+ */
567
+ public getState(): Record<string, any> {
568
+ let node = this.getNode();
569
+ let elem = this.getNodeElement();
570
+ let inputs = this.getNode().inputs;
571
+ let keepInputs: Record<string, DrawflowConnectionDetail> = {}
572
+ for (let i in inputs) {
573
+ if (inputs[i].connections.length != 0)
574
+ keepInputs[i] = inputs[i].connections[0];
575
+ }
576
+ return {
577
+ id: node.id,
578
+ posX: parseInt(elem.style.left),
579
+ posY: parseInt(elem.style.top),
580
+ inputConnections: keepInputs,
581
+ type: this.type,
582
+ valid: this.valid()
583
+ }
584
+ }
585
+ /**
586
+ * Uses the state produced by getState to restore the settings of the layer.
587
+ * @param state produced by getState when saving.
588
+ */
589
+ public setState(state: Record<string, any>) {
590
+ let elem = this.getNodeElement();
591
+ elem.style.left = state.posX + "px";
592
+ elem.style.top = state.posY + "px";
593
+ }
594
+ /**
595
+ * Checks for all the inputs that the dimension in it's html is the same as the dimension of the connected output.
596
+ * @returns whether all dimension match.
597
+ */
598
+ public checkInputs() {
599
+ let that = this;
600
+ let inputs = this.getNode().inputs
601
+ for (let i in inputs) {
602
+ let input = inputs[i];
603
+ let inputName = i;
604
+ let inputElem = this.getNodeInputElement(inputName);
605
+ if (input.connections.length == 0 || inputElem == null || inputElem.innerText == "") {
606
+ if (inputElem == null)
607
+ this.addInput();
608
+ setTimeout(function() {
609
+ let elem = that.getNodeInputElement(inputName);
610
+ if (elem == null)
611
+ return;
612
+ elem.classList.remove("invalid");
613
+ elem.classList.remove("valid");
614
+ })
615
+ continue;
616
+ }
617
+ let layer = this.editor.getLayerFromNodeId(parseInt(input.connections[0].node));
618
+ let output = input.connections[0].input;
619
+ let outputElem = layer?.getNodeOutputElement(output);
620
+ if (outputElem == null)
621
+ continue;
622
+ if (outputElem.innerText != inputElem.innerText) {
623
+ inputElem.classList.add("invalid");
624
+ inputElem.classList.remove("valid");
625
+ inputElem.title = "data has wrong dimensions";
626
+ return false;
627
+ } else {
628
+ inputElem.classList.remove("invalid");
629
+ inputElem.classList.add("valid");
630
+ inputElem.title = "";
631
+ }
632
+ }
633
+ return true;
634
+ }
635
+ /**
636
+ * Reads the dimensions of the connected output into the input for all the inputs.
637
+ */
638
+ protected updateInputLabels() {
639
+ let outputElems = this.getConnectedInputElements();
640
+ for (let o in outputElems) {
641
+ this.getNodeInputElement(o).innerText = outputElems[o].innerText;
642
+ }
643
+ this.checkInputs();
644
+ this.showValid();
645
+ }
646
+ /**
647
+ * Calls the update method for all the connected output layers. This propagates changes in output dimension through the network.
648
+ */
649
+ protected notifyOutputChange() {
650
+ if (this.hasUpdatedOutputsThisUpdate) {
651
+ this.hasCyclicReference = true;
652
+ this.showValid();
653
+ return;
654
+ }
655
+ this.hasUpdatedOutputsThisUpdate = true;
656
+ this.showValid();
657
+ let outputs = this.getNode().outputs
658
+ for (let o in outputs) {
659
+ let outputs = this.getConnectedLayersForOutput(o);
660
+ for (let out of outputs) {
661
+ if (out != this) {
662
+ out.update();
663
+ out.editor.updateConnectionNodes(out);
664
+ } else {
665
+ this.hasCyclicReference = true;
666
+ }
667
+ }
668
+ }
669
+ this.hasUpdatedOutputsThisUpdate = false;
670
+ this.hasCyclicReference = false;
671
+ }
672
+ /**
673
+ * Uses the result of the valid() method to display it to the layer html.
674
+ */
675
+ protected showValid() {
676
+ let valid = this.valid();
677
+ let elem = this.getNodeElement();
678
+ if (elem == null)
679
+ return;
680
+ if (!valid) {
681
+ elem.classList.add("invalid");
682
+ if (this.hasCyclicReference)
683
+ elem.setAttribute("title", msg("Has a cyclic reference."));
684
+ } else {
685
+ elem.classList.remove("invalid");
686
+ }
687
+ }
688
+ /**
689
+ * Contains any code that should run when any of the inputs is updated.
690
+ * When you want to read the new input dimensions use updateInputLabels().
691
+ * When you have changed the output dimensions use notifyOutputChange to send the update through the network.
692
+ */
693
+ protected abstract update(): void;
694
+ /**
695
+ * Is called when a forward pass of the model is performed using tensorflow. Only called once during model building.
696
+ * @param inputs The Symbolic Tensors provided by the prevoious layers.
697
+ * @returns
698
+ */
699
+ public abstract forward(inputs: Record<string, TF.SymbolicTensor>): Record<string, TF.SymbolicTensor>;
700
+ /**
701
+ * Checks the state of the layer for inconsistencies and returns false when anything will cause an error when training.
702
+ */
703
+ public valid() {
704
+ return this.checkInputs() && !this.hasCyclicReference;
705
+ }
706
+
707
+ /**
708
+ * @returns The display name of the layer shown in the node header.
709
+ */
710
+ protected getDisplayName(): string {
711
+ return this.type;
712
+ }
713
+ }
714
+
715
+ /** Extends the Base Layer with management for a dynamic number of inputs. */
716
+ export abstract class DynamicInputLayer extends Layer {
717
+ constructor(outputs: number, name: string, editor:Editor) {
718
+ super(1, outputs, name, editor);
719
+ }
720
+ update() {
721
+ this.updateInputLabels();
722
+ this.cleanEmptyInputs();
723
+ if (!this.hasFreeInput())
724
+ this.addInput();
725
+
726
+ let dims = this.getOutputDim();
727
+ let outputs = dims.length; // The main dimension is the number of individual outputs
728
+ for (let out = 0; out < outputs; out++)
729
+ this.getNodeOutputElement("output_" + (out + 1)).innerText = dims[out].join(SIZE_SEP)
730
+ this.notifyOutputChange();
731
+ }
732
+ /**
733
+ * @returns whether there is a node that is not connected.
734
+ */
735
+ hasFreeInput() {
736
+ let hasFreeInput = false;
737
+ for (let input of this.getNodeInputElements()) {
738
+ if ((input as HTMLElement).innerText == "")
739
+ hasFreeInput = true;
740
+ }
741
+ return hasFreeInput;
742
+ }
743
+ /**
744
+ * Removes empty input nodes.
745
+ * @returns whether there was a node that is not connected.
746
+ */
747
+ cleanEmptyInputs() {
748
+ let hasFreeInput = false;
749
+ for (let input of this.getNodeInputElements()) {
750
+ if ((input as HTMLElement).innerText == "")
751
+ this.editor.removeNodeInput(this.getNode().id, input.classList.value.split(" ")[1])
752
+ }
753
+ return hasFreeInput;
754
+ }
755
+ getState() {
756
+ let state = super.getState();
757
+ state.numberOfInputs = this.getNodeInputElements.length;
758
+ state.dim = this.getOutputDim();
759
+ return state;
760
+ }
761
+ setState(state) {
762
+ super.setState(state);
763
+ for (let i = 1; i < state.numberOfInputs; i++)
764
+ this.addInput();
765
+ }
766
+ /**
767
+ * @returns the combined output shapes for the layer operation on the inputs.
768
+ */
769
+ abstract getOutputDim(): NonEmptyArray<number>[];
770
+ }