circle.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. var circle = circle || {};
  2. var flatbuffers = flatbuffers || require('./flatbuffers');
  3. var flexbuffers = flexbuffers || require('./flexbuffers');
  4. var zip = zip || require('./zip');
  5. circle.ModelFactory = class {
  6. match(context) {
  7. const tags = context.tags('flatbuffers');
  8. if (tags.get('file_identifier') === 'CIR0') {
  9. return 'circle.flatbuffers';
  10. }
  11. const obj = context.open('json');
  12. if (obj && obj.subgraphs && obj.operator_codes) {
  13. return 'circle.flatbuffers.json';
  14. }
  15. return undefined;
  16. }
  17. open(context, match) {
  18. return context.require('./circle-schema').then(() => {
  19. circle.schema = flatbuffers.get('circle').circle;
  20. let model = null;
  21. const attachments = new Map();
  22. switch (match) {
  23. case 'circle.flatbuffers.json': {
  24. try {
  25. const obj = context.open('json');
  26. const reader = new flatbuffers.TextReader(obj);
  27. model = circle.schema.Model.createText(reader);
  28. }
  29. catch (error) {
  30. const message = error && error.message ? error.message : error.toString();
  31. throw new circle.Error('File text format is not circle.Model (' + message.replace(/\.$/, '') + ').');
  32. }
  33. break;
  34. }
  35. case 'circle.flatbuffers': {
  36. const stream = context.stream;
  37. try {
  38. const reader = flatbuffers.BinaryReader.open(stream);
  39. model = circle.schema.Model.create(reader);
  40. }
  41. catch (error) {
  42. const message = error && error.message ? error.message : error.toString();
  43. throw new circle.Error('File format is not circle.Model (' + message.replace(/\.$/, '') + ').');
  44. }
  45. try {
  46. const archive = zip.Archive.open(stream);
  47. if (archive) {
  48. for (const entry of archive.entries) {
  49. attachments.set(entry[0], entry[1]);
  50. }
  51. }
  52. }
  53. catch (error) {
  54. // continue regardless of error
  55. }
  56. break;
  57. }
  58. default: {
  59. throw new circle.Error("Unsupported Circle format '" + match + "'.");
  60. }
  61. }
  62. return context.metadata('circle-metadata.json').then((metadata) => {
  63. return new circle.Model(metadata, model);
  64. });
  65. });
  66. }
  67. };
  68. circle.Model = class {
  69. constructor(metadata, model) {
  70. this._graphs = [];
  71. this._format = 'Circle';
  72. this._format = this._format + ' v' + model.version.toString();
  73. this._description = model.description || '';
  74. this._metadata = [];
  75. const builtinOperators = new Map();
  76. const upperCase = new Set([ '2D', 'LSH', 'SVDF', 'RNN', 'L2', 'LSTM' ]);
  77. for (const key of Object.keys(circle.schema.BuiltinOperator)) {
  78. const value = key === 'BATCH_MATMUL' ? 'BATCH_MAT_MUL' : key;
  79. const name = value.split('_').map((s) => (s.length < 1 || upperCase.has(s)) ? s : s[0] + s.substring(1).toLowerCase()).join('');
  80. const index = circle.schema.BuiltinOperator[key];
  81. builtinOperators.set(index, name);
  82. }
  83. const operators = model.operator_codes.map((operator) => {
  84. const code = operator.builtin_code || 0;
  85. const version = operator.version;
  86. const custom = code === circle.schema.BuiltinOperator.CUSTOM;
  87. const name = custom ? operator.custom_code ? operator.custom_code : 'Custom' : builtinOperators.has(code) ? builtinOperators.get(code) : code.toString();
  88. return custom ? { name: name, version: version, custom: true } : { name: name, version: version };
  89. });
  90. let modelMetadata = null;
  91. for (const metadata of model.metadata) {
  92. const buffer = model.buffers[metadata.buffer];
  93. if (buffer) {
  94. switch (metadata.name) {
  95. case 'min_runtime_version': {
  96. const data = buffer.data || new Uint8Array(0);
  97. this._runtime = data ? new TextDecoder().decode(data) : undefined;
  98. break;
  99. }
  100. case 'TFLITE_METADATA': {
  101. const data = buffer.data || new Uint8Array(0);
  102. const reader = flatbuffers.BinaryReader.open(data);
  103. if (circle.schema.ModelMetadata.identifier(reader)) {
  104. modelMetadata = circle.schema.ModelMetadata.create(reader);
  105. if (modelMetadata.name) {
  106. this._name = modelMetadata.name;
  107. }
  108. if (modelMetadata.version) {
  109. this._version = modelMetadata.version;
  110. }
  111. if (modelMetadata.description) {
  112. this._description = this._description ? [ this._description, modelMetadata.description].join(' ') : modelMetadata.description;
  113. }
  114. if (modelMetadata.author) {
  115. this._metadata.push({ name: 'author', value: modelMetadata.author });
  116. }
  117. if (modelMetadata.license) {
  118. this._metadata.push({ name: 'license', value: modelMetadata.license });
  119. }
  120. }
  121. break;
  122. }
  123. default: {
  124. break;
  125. }
  126. }
  127. }
  128. }
  129. const subgraphs = model.subgraphs;
  130. const subgraphsMetadata = modelMetadata ? modelMetadata.subgraph_metadata : null;
  131. for (let i = 0; i < subgraphs.length; i++) {
  132. const subgraph = subgraphs[i];
  133. const name = subgraphs.length > 1 ? i.toString() : '';
  134. const subgraphMetadata = subgraphsMetadata && i < subgraphsMetadata.length ? subgraphsMetadata[i] : null;
  135. this._graphs.push(new circle.Graph(metadata, subgraph, subgraphMetadata, name, operators, model));
  136. }
  137. }
  138. get format() {
  139. return this._format;
  140. }
  141. get runtime() {
  142. return this._runtime;
  143. }
  144. get name() {
  145. return this._name;
  146. }
  147. get version() {
  148. return this._version;
  149. }
  150. get description() {
  151. return this._description;
  152. }
  153. get metadata() {
  154. return this._metadata;
  155. }
  156. get graphs() {
  157. return this._graphs;
  158. }
  159. };
  160. circle.Graph = class {
  161. constructor(metadata, subgraph, subgraphMetadata, name, operators, model) {
  162. this._nodes = [];
  163. this._inputs = [];
  164. this._outputs = [];
  165. this._name = subgraph.name || name;
  166. const tensors = new Map();
  167. const args = (index) => {
  168. if (index === -1) {
  169. return null;
  170. }
  171. if (!tensors.has(index)) {
  172. if (index < subgraph.tensors.length) {
  173. const tensor = subgraph.tensors[index];
  174. const buffer = model.buffers[tensor.buffer];
  175. const is_variable = tensor.is_variable;
  176. const data = buffer ? buffer.data : null;
  177. const initializer = (data && data.length > 0) || is_variable ? new circle.Tensor(index, tensor, buffer, is_variable) : null;
  178. tensors.set(index, new circle.Argument(index, tensor, initializer));
  179. }
  180. else {
  181. tensors.set(index, new circle.Argument(index, { name: '' }, null));
  182. }
  183. }
  184. return tensors.get(index);
  185. };
  186. for (let i = 0; i < subgraph.operators.length; i++) {
  187. const node = subgraph.operators[i];
  188. const index = node.opcode_index;
  189. const operator = index < operators.length ? operators[index] : { name: '(' + index.toString() + ')' };
  190. this._nodes.push(new circle.Node(metadata, node, operator, i.toString(), args));
  191. }
  192. const applyTensorMetadata = (argument, tensorMetadata) => {
  193. if (tensorMetadata) {
  194. const description = tensorMetadata.description;
  195. if (description) {
  196. argument.description = description;
  197. }
  198. const content = tensorMetadata.content;
  199. if (argument.type && content) {
  200. let denotation = null;
  201. const contentProperties = content.content_properties;
  202. if (contentProperties instanceof circle.schema.FeatureProperties) {
  203. denotation = 'Feature';
  204. }
  205. else if (contentProperties instanceof circle.schema.ImageProperties) {
  206. denotation = 'Image';
  207. switch(contentProperties.color_space) {
  208. case 0: denotation += '(Unknown)'; break;
  209. case 1: denotation += '(RGB)'; break;
  210. case 2: denotation += '(Grayscale)'; break;
  211. default: throw circle.Error("Unsupported image color space '" + contentProperties.color_space + "'.");
  212. }
  213. }
  214. else if (contentProperties instanceof circle.schema.BoundingBoxProperties) {
  215. denotation = 'BoundingBox';
  216. }
  217. else if (contentProperties instanceof circle.schema.AudioProperties) {
  218. denotation = 'Audio(' + contentProperties.sample_rate.toString() + ',' + contentProperties.channels.toString() + ')';
  219. }
  220. if (denotation) {
  221. argument.type.denotation = denotation;
  222. }
  223. }
  224. }
  225. };
  226. const inputs = subgraph.inputs;
  227. for (let i = 0; i < inputs.length; i++) {
  228. const input = inputs[i];
  229. const argument = args(input);
  230. if (subgraphMetadata && i < subgraphMetadata.input_tensor_metadata.length) {
  231. applyTensorMetadata(argument, subgraphMetadata.input_tensor_metadata[i]);
  232. }
  233. this._inputs.push(new circle.Parameter(argument ? argument.name : '?', true, argument ? [ argument ] : []));
  234. }
  235. const outputs = subgraph.outputs;
  236. for (let i = 0; i < outputs.length; i++) {
  237. const output = outputs[i];
  238. const argument = args(output);
  239. if (subgraphMetadata && i < subgraphMetadata.output_tensor_metadata.length) {
  240. applyTensorMetadata(argument, subgraphMetadata.output_tensor_metadata[i]);
  241. }
  242. this._outputs.push(new circle.Parameter(argument ? argument.name : '?', true, argument ? [ argument ] : []));
  243. }
  244. }
  245. get name() {
  246. return this._name;
  247. }
  248. get inputs() {
  249. return this._inputs;
  250. }
  251. get outputs() {
  252. return this._outputs;
  253. }
  254. get nodes() {
  255. return this._nodes;
  256. }
  257. };
  258. circle.Node = class {
  259. constructor(metadata, node, type, location, args) {
  260. this._location = location;
  261. this._type = type.custom ? { name: type.name, category: 'custom' } : metadata.type(type.name);
  262. this._inputs = [];
  263. this._outputs = [];
  264. this._attributes = [];
  265. if (node) {
  266. let inputs = [];
  267. let outputs = [];
  268. inputs = Array.from(node.inputs || new Int32Array(0));
  269. outputs = Array.from(node.outputs || new Int32Array(0));
  270. let inputIndex = 0;
  271. while (inputIndex < inputs.length) {
  272. let count = 1;
  273. let inputName = null;
  274. let inputVisible = true;
  275. const inputArguments = [];
  276. if (this._type && this._type.inputs && inputIndex < this._type.inputs.length) {
  277. const input = this._type.inputs[inputIndex];
  278. inputName = input.name;
  279. if (input.option == 'variadic') {
  280. count = inputs.length - inputIndex;
  281. }
  282. if (Object.prototype.hasOwnProperty.call(input, 'visible') && !input.visible) {
  283. inputVisible = false;
  284. }
  285. }
  286. const inputArray = inputs.slice(inputIndex, inputIndex + count);
  287. for (const index of inputArray) {
  288. const argument = args(index);
  289. if (argument) {
  290. inputArguments.push(argument);
  291. }
  292. }
  293. inputIndex += count;
  294. inputName = inputName ? inputName : inputIndex.toString();
  295. this._inputs.push(new circle.Parameter(inputName, inputVisible, inputArguments));
  296. }
  297. for (let k = 0; k < outputs.length; k++) {
  298. const index = outputs[k];
  299. const outputArguments = [];
  300. const argument = args(index);
  301. if (argument) {
  302. outputArguments.push(argument);
  303. }
  304. let outputName = k.toString();
  305. if (this._type && this._type.outputs && k < this._type.outputs.length) {
  306. const output = this._type.outputs[k];
  307. if (output && output.name) {
  308. outputName = output.name;
  309. }
  310. }
  311. this._outputs.push(new circle.Parameter(outputName, true, outputArguments));
  312. }
  313. if (type.custom && node.custom_options.length > 0) {
  314. let decoded = false;
  315. if (node.custom_options_format === circle.schema.CustomOptionsFormat.FLEXBUFFERS) {
  316. try {
  317. const reader = flexbuffers.BinaryReader.open(node.custom_options);
  318. if (reader) {
  319. const custom_options = reader.read();
  320. if (Array.isArray(custom_options)) {
  321. const attribute = new circle.Attribute(null, 'custom_options', custom_options);
  322. this._attributes.push(attribute);
  323. decoded = true;
  324. }
  325. else if (custom_options) {
  326. for (const pair of Object.entries(custom_options)) {
  327. const key = pair[0];
  328. const value = pair[1];
  329. const schema = metadata.attribute(type.name, key);
  330. const attribute = new circle.Attribute(schema, key, value);
  331. this._attributes.push(attribute);
  332. }
  333. decoded = true;
  334. }
  335. }
  336. }
  337. catch (err) {
  338. // continue regardless of error
  339. }
  340. }
  341. if (!decoded) {
  342. const schema = metadata.attribute(type.name, 'custom');
  343. this._attributes.push(new circle.Attribute(schema, 'custom', Array.from(node.custom_options)));
  344. }
  345. }
  346. const options = node.builtin_options;
  347. if (options) {
  348. for (const entry of Object.entries(options)) {
  349. const name = entry[0];
  350. const value = entry[1];
  351. if (name === 'fused_activation_function' && value !== 0) {
  352. const activationFunctionMap = { 1: 'Relu', 2: 'ReluN1To1', 3: 'Relu6', 4: 'Tanh', 5: 'SignBit' };
  353. if (!activationFunctionMap[value]) {
  354. throw new circle.Error("Unsupported activation funtion index '" + JSON.stringify(value) + "'.");
  355. }
  356. const type = activationFunctionMap[value];
  357. this._chain = [ new circle.Node(metadata, null, { name: type }, null, []) ];
  358. }
  359. const schema = metadata.attribute(type.name, name);
  360. this._attributes.push(new circle.Attribute(schema, name, value));
  361. }
  362. }
  363. }
  364. }
  365. get type() {
  366. return this._type;
  367. }
  368. get name() {
  369. return '';
  370. }
  371. get location() {
  372. return this._location;
  373. }
  374. get inputs() {
  375. return this._inputs;
  376. }
  377. get outputs() {
  378. return this._outputs;
  379. }
  380. get chain() {
  381. return this._chain;
  382. }
  383. get attributes() {
  384. return this._attributes;
  385. }
  386. };
  387. circle.Attribute = class {
  388. constructor(metadata, name, value) {
  389. this._name = name;
  390. this._value = ArrayBuffer.isView(value) ? Array.from(value) : value;
  391. this._type = metadata && metadata.type ? metadata.type : null;
  392. if (this._name == 'fused_activation_function') {
  393. this._visible = false;
  394. }
  395. if (this._type) {
  396. this._value = circle.Utility.enum(this._type, this._value);
  397. }
  398. if (metadata) {
  399. if (Object.prototype.hasOwnProperty.call(metadata, 'visible') && !metadata.visible) {
  400. this._visible = false;
  401. }
  402. else if (Object.prototype.hasOwnProperty.call(metadata, 'default')) {
  403. value = this._value;
  404. if (typeof value == 'function') {
  405. value = value();
  406. }
  407. if (value == metadata.default) {
  408. this._visible = false;
  409. }
  410. }
  411. }
  412. }
  413. get name() {
  414. return this._name;
  415. }
  416. get type() {
  417. return this._type;
  418. }
  419. get value() {
  420. return this._value;
  421. }
  422. get visible() {
  423. return this._visible == false ? false : true;
  424. }
  425. };
  426. circle.Parameter = class {
  427. constructor(name, visible, args) {
  428. this._name = name;
  429. this._visible = visible;
  430. this._arguments = args;
  431. }
  432. get name() {
  433. return this._name;
  434. }
  435. get visible() {
  436. return this._visible;
  437. }
  438. get arguments() {
  439. return this._arguments;
  440. }
  441. };
  442. circle.Argument = class {
  443. constructor(index, tensor, initializer) {
  444. const name = tensor.name || '';
  445. this._name = name + '\n' + index.toString();
  446. this._location = index.toString();
  447. this._type = tensor.type !== undefined && tensor.shape !== undefined ? new circle.TensorType(tensor) : null;
  448. this._initializer = initializer;
  449. const quantization = tensor.quantization;
  450. if (quantization) {
  451. const length = Math.max(quantization.scale.length, quantization.zero_point.length, quantization.min.length, quantization.max.length);
  452. const list = [];
  453. for (let i = 0; i < length; i++) {
  454. let value = 'q';
  455. const scale = i < quantization.scale.length ? quantization.scale[i] : 0;
  456. const zeroPoint = (i < quantization.zero_point.length ? quantization.zero_point[i] : 0).toString();
  457. if (scale !== 0 || zeroPoint !== '0') {
  458. value = scale.toString() + ' * ' + (zeroPoint === '0' ? 'q' : ('(q' + (!zeroPoint.startsWith('-') ? ' - ' + zeroPoint : ' + ' + zeroPoint.substring(1)) + ')'));
  459. }
  460. if (i < quantization.min.length) {
  461. value = quantization.min[i].toString() + ' \u2264 ' + value;
  462. }
  463. if (i < quantization.max.length) {
  464. value = value + ' \u2264 ' + quantization.max[i].toString();
  465. }
  466. list.push(value);
  467. }
  468. if (list.length > 0 && !list.every((value) => value === 'q')) {
  469. this._quantization = list;
  470. }
  471. }
  472. }
  473. get name() {
  474. return this._name;
  475. }
  476. get location() {
  477. return this._location;
  478. }
  479. get type() {
  480. return this._type;
  481. }
  482. get quantization() {
  483. return this._quantization;
  484. }
  485. set description(value) {
  486. this._description = value;
  487. }
  488. get description() {
  489. return this._description;
  490. }
  491. get initializer() {
  492. return this._initializer;
  493. }
  494. };
  495. circle.Tensor = class {
  496. constructor(index, tensor, buffer, is_variable) {
  497. this._location = index.toString();
  498. this._type = new circle.TensorType(tensor);
  499. this._is_variable = is_variable;
  500. this._name = tensor.name;
  501. this._data = buffer.data.slice(0);
  502. }
  503. get kind() {
  504. return this._is_variable ? 'Variable' : '';
  505. }
  506. get name() {
  507. return this._name;
  508. }
  509. get location() {
  510. return this._location;
  511. }
  512. get type() {
  513. return this._type;
  514. }
  515. get state() {
  516. return this._context().state;
  517. }
  518. get value() {
  519. const context = this._context();
  520. if (context.state) {
  521. return null;
  522. }
  523. context.limit = Number.MAX_SAFE_INTEGER;
  524. return this._decode(context, 0);
  525. }
  526. toString() {
  527. const context = this._context();
  528. if (context.state) {
  529. return '';
  530. }
  531. context.limit = 10000;
  532. const value = this._decode(context, 0);
  533. return JSON.stringify(value, null, 4);
  534. }
  535. _context() {
  536. const context = {};
  537. context.state = null;
  538. context.index = 0;
  539. context.count = 0;
  540. if (this._data == null || this._data.length === 0) {
  541. context.state = 'Tensor data is empty.';
  542. return context;
  543. }
  544. const dataType = this.type.dataType;
  545. const shape = this.type.shape.dimensions;
  546. context.dataType = dataType;
  547. context.shape = shape;
  548. if (dataType === 'string') {
  549. let offset = 0;
  550. const data = new DataView(this._data.buffer, this._data.byteOffset, this._data.byteLength);
  551. const count = data.getInt32(0, true);
  552. offset += 4;
  553. const offsetTable = [];
  554. for (let j = 0; j < count; j++) {
  555. offsetTable.push(data.getInt32(offset, true));
  556. offset += 4;
  557. }
  558. offsetTable.push(this._data.length);
  559. const stringTable = [];
  560. const utf8Decoder = new TextDecoder('utf-8');
  561. for (let k = 0; k < count; k++) {
  562. const textArray = this._data.subarray(offsetTable[k], offsetTable[k + 1]);
  563. stringTable.push(utf8Decoder.decode(textArray));
  564. }
  565. context.data = stringTable;
  566. }
  567. else {
  568. const itemsize = new Map([
  569. [ 'boolean' ],
  570. [ 'uint8', 1 ], [ 'uint32', 4],
  571. [ 'int8', 1 ], [ 'int16', 2 ], [ 'int32', 4 ], [ 'int64', 8 ],
  572. [ 'float16', 2 ], [ 'float32', 4 ], [ 'float64', 8 ]
  573. ]);
  574. if (!itemsize.has(dataType)) {
  575. throw new circle.Error("Tensor data type '" + this.type.dataType + "' is not implemented.");
  576. }
  577. const size = shape.reduce((a, b) => a * b, 1);
  578. if (this._data.length < itemsize.get(dataType) * size) {
  579. context.state = "Invalid tensor data size.";
  580. return context;
  581. }
  582. context.data = new DataView(this._data.buffer, this._data.byteOffset, this._data.byteLength);
  583. }
  584. return context;
  585. }
  586. _decode(context, dimension) {
  587. const shape = (context.shape.length == 0) ? [ 1 ] : context.shape;
  588. const size = shape[dimension];
  589. const results = [];
  590. if (dimension == shape.length - 1) {
  591. for (let i = 0; i < size; i++) {
  592. if (context.count > context.limit) {
  593. results.push('...');
  594. return results;
  595. }
  596. switch (context.dataType) {
  597. case 'boolean':
  598. results.push(context.data.getUint8(context.index) === 0 ? false : true);
  599. context.index += 1;
  600. context.count++;
  601. break;
  602. case 'uint8':
  603. results.push(context.data.getUint8(context.index));
  604. context.index += 1;
  605. context.count++;
  606. break;
  607. case 'uint32':
  608. results.push(context.data.getUint32(context.index));
  609. context.index += 4;
  610. context.count++;
  611. break;
  612. case 'int8':
  613. results.push(context.data.getInt8(context.index));
  614. context.index += 1;
  615. context.count++;
  616. break;
  617. case 'int16':
  618. results.push(context.data.getInt16(context.index, true));
  619. context.index += 2;
  620. context.count++;
  621. break;
  622. case 'int32':
  623. results.push(context.data.getInt32(context.index, true));
  624. context.index += 4;
  625. context.count++;
  626. break;
  627. case 'int64':
  628. results.push(context.data.getInt64(context.index, true));
  629. context.index += 8;
  630. context.count++;
  631. break;
  632. case 'float16':
  633. results.push(context.data.getFloat16(context.index, true));
  634. context.index += 2;
  635. context.count++;
  636. break;
  637. case 'float32':
  638. results.push(context.data.getFloat32(context.index, true));
  639. context.index += 4;
  640. context.count++;
  641. break;
  642. case 'float64':
  643. results.push(context.data.getFloat64(context.index, true));
  644. context.index += 8;
  645. context.count++;
  646. break;
  647. case 'string':
  648. results.push(context.data[context.index++]);
  649. context.count++;
  650. break;
  651. default:
  652. break;
  653. }
  654. }
  655. }
  656. else {
  657. for (let j = 0; j < size; j++) {
  658. if (context.count > context.limit) {
  659. results.push('...');
  660. return results;
  661. }
  662. results.push(this._decode(context, dimension + 1));
  663. }
  664. }
  665. if (context.shape.length == 0) {
  666. return results[0];
  667. }
  668. return results;
  669. }
  670. };
  671. circle.TensorType = class {
  672. constructor(tensor) {
  673. this._dataType = circle.Utility.dataType(tensor.type);
  674. this._shape = new circle.TensorShape(Array.from(tensor.shape || []));
  675. }
  676. get dataType() {
  677. return this._dataType;
  678. }
  679. get shape() {
  680. return this._shape;
  681. }
  682. set denotation(value) {
  683. this._denotation = value;
  684. }
  685. get denotation() {
  686. return this._denotation;
  687. }
  688. toString() {
  689. return this.dataType + this._shape.toString();
  690. }
  691. };
  692. circle.TensorShape = class {
  693. constructor(dimensions) {
  694. this._dimensions = dimensions;
  695. }
  696. get dimensions() {
  697. return this._dimensions;
  698. }
  699. toString() {
  700. if (!this._dimensions || this._dimensions.length == 0) {
  701. return '';
  702. }
  703. return '[' + this._dimensions.map((dimension) => dimension.toString()).join(',') + ']';
  704. }
  705. };
  706. circle.Utility = class {
  707. static dataType(type) {
  708. if (!circle.Utility._tensorTypeMap) {
  709. circle.Utility._tensorTypeMap = new Map(Object.keys(circle.schema.TensorType).map((key) => [ circle.schema.TensorType[key], key.toLowerCase() ]));
  710. circle.Utility._tensorTypeMap.set(6, 'boolean');
  711. }
  712. return circle.Utility._tensorTypeMap.has(type) ? circle.Utility._tensorTypeMap.get(type) : '?';
  713. }
  714. static enum(name, value) {
  715. const type = name && circle.schema ? circle.schema[name] : undefined;
  716. if (type) {
  717. circle.Utility._enums = circle.Utility._enums || new Map();
  718. if (!circle.Utility._enums.has(name)) {
  719. const map = new Map(Object.keys(type).map((key) => [ type[key], key ]));
  720. circle.Utility._enums.set(name, map);
  721. }
  722. const map = circle.Utility._enums.get(name);
  723. if (map.has(value)) {
  724. return map.get(value);
  725. }
  726. }
  727. return value;
  728. }
  729. };
  730. circle.Error = class extends Error {
  731. constructor(message) {
  732. super(message);
  733. this.name = 'Error loading Circle model.';
  734. }
  735. };
  736. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  737. module.exports.ModelFactory = circle.ModelFactory;
  738. }