coreml.js 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692
  1. var coreml = coreml || {};
  2. var json = json || require('./json');
  3. var protobuf = protobuf || require('./protobuf');
  4. var base = base || require('./base');
  5. coreml.ModelFactory = class {
  6. match(context) {
  7. const stream = context.stream;
  8. const identifier = context.identifier.toLowerCase();
  9. const extension = identifier.split('.').pop().toLowerCase();
  10. const tags = context.tags('pb');
  11. if (tags.get(1) === 0 && tags.get(2) === 2) {
  12. if (extension === 'pb') {
  13. const tags = context.tags('pb+');
  14. const keys = Object.keys(tags).map((key) => parseInt(key, 10));
  15. const match = (key) =>
  16. (key >= 200 && key < 220) ||
  17. (key >= 300 && key < 320) ||
  18. (key >= 400 && key < 420) ||
  19. (key >= 500 && key < 520) ||
  20. (key >= 550 && key < 560) ||
  21. (key >= 600 && key < 620) ||
  22. (key === 900) ||
  23. (key >= 2000 && key < 2010) ||
  24. (key === 3000);
  25. if (!keys.some((key) => match(key))) {
  26. return null;
  27. }
  28. }
  29. return 'coreml.pb';
  30. }
  31. if (identifier === 'manifest.json') {
  32. const obj = context.open('json');
  33. if (obj && obj.rootModelIdentifier && obj.itemInfoEntries) {
  34. const entries = Object.keys(obj.itemInfoEntries).map((key) => obj.itemInfoEntries[key]);
  35. if (entries.filter((entry) => entry.path.toLowerCase().endsWith('.mlmodel').length === 1)){
  36. return 'coreml.manifest';
  37. }
  38. }
  39. }
  40. if (identifier === 'metadata.json') {
  41. const obj = context.open('json');
  42. if (obj && obj.rootModelIdentifier && obj.itemInfoEntries) {
  43. return 'coreml.metadata';
  44. }
  45. }
  46. if (identifier === 'featuredescriptions.json') {
  47. const obj = context.open('json');
  48. if (obj && (obj.Inputs || obj.Outputs)) {
  49. return 'coreml.featuredescriptions';
  50. }
  51. }
  52. if (extension === 'bin' && stream.length > 16) {
  53. const buffer = stream.peek(Math.min(256, stream.length));
  54. for (let i = 0; i < buffer.length - 4; i++) {
  55. const signature = (buffer[i] | buffer[i + 1] << 8 | buffer[i + 2] << 16 | buffer [i + 3] << 24) >>> 0;
  56. if (signature === 0xdeadbeef) {
  57. return 'coreml.weights';
  58. }
  59. }
  60. }
  61. return undefined;
  62. }
  63. open(context, match) {
  64. return context.require('./coreml-proto').then(() => {
  65. return coreml.Metadata.open(context).then((metadata) => {
  66. const openModel = (stream, context, path, format) => {
  67. let model = null;
  68. try {
  69. coreml.proto = protobuf.get('coreml').CoreML.Specification;
  70. const reader = protobuf.BinaryReader.open(stream);
  71. model = coreml.proto.Model.decode(reader);
  72. }
  73. catch (error) {
  74. const message = error && error.message ? error.message : error.toString();
  75. throw new coreml.Error('File format is not coreml.Model (' + message.replace(/\.$/, '') + ').');
  76. }
  77. const weightPaths = new Set();
  78. const walkProgram = (program) => {
  79. for (const entry of Object.entries(program.functions)) {
  80. const func = entry[1];
  81. for (const entry of Object.entries(func.block_specializations)) {
  82. const block = entry[1];
  83. for (const operation of block.operations) {
  84. for (const entry of Object.entries(operation.attributes)) {
  85. const value = entry[1];
  86. if (value.blobFileValue && value.blobFileValue.fileName) {
  87. weightPaths.add(value.blobFileValue.fileName);
  88. }
  89. }
  90. }
  91. }
  92. }
  93. };
  94. const walkModel = (model) => {
  95. if (model.mlProgram) {
  96. walkProgram(model.mlProgram);
  97. }
  98. if (model.pipeline && model.pipeline.models) {
  99. for (const node of model.pipeline.models) {
  100. walkModel(node);
  101. }
  102. }
  103. if (model.pipelineClassifier && model.pipelineClassifier.pipeline && model.pipelineClassifier.pipeline.models) {
  104. for (const node of model.pipelineClassifier.pipeline.models) {
  105. walkModel(node);
  106. }
  107. }
  108. if (model.pipelineRegressor && model.pipelineRegressor.pipeline && model.pipelineRegressor.pipeline.models) {
  109. for (const node of model.pipelineRegressor.pipeline.models) {
  110. walkModel(node);
  111. }
  112. }
  113. };
  114. walkModel(model);
  115. if (weightPaths.size > 0) {
  116. const items = path.split('/');
  117. items.pop();
  118. const folder = items.join('/');
  119. const keys = Array.from(weightPaths);
  120. const paths = keys.map((path) => {
  121. const items = path.split('/');
  122. if (items[0] === '@model_path') {
  123. items[0] = folder;
  124. }
  125. return items.join('/');
  126. });
  127. const promises = paths.map((path) => context.request(path, null));
  128. return Promise.all(promises).then((streams) => {
  129. const weights = new Map();
  130. for (let i = 0; i < keys.length; i++) {
  131. weights.set(keys[i], streams[i]);
  132. }
  133. return new coreml.Model(metadata, format, model, weights);
  134. }).catch((/* err */) => {
  135. return new coreml.Model(metadata, format, model, new Map());
  136. });
  137. }
  138. return new coreml.Model(metadata, format, model, new Map());
  139. };
  140. const openManifest = (obj, context, path) => {
  141. const entries = Object.keys(obj.itemInfoEntries).map((key) => obj.itemInfoEntries[key]);
  142. const entry = entries.filter((entry) => entry.path.toLowerCase().endsWith('.mlmodel'))[0];
  143. const file = path + 'Data/' + entry.path;
  144. return context.request(file, null).then((stream) => {
  145. return openModel(stream, context, file, 'Core ML Package');
  146. });
  147. };
  148. const openManifestStream = (context, path) => {
  149. return context.request(path + 'Manifest.json', null).then((stream) => {
  150. const reader = json.TextReader.open(stream);
  151. const obj = reader.read();
  152. return openManifest(obj, context, path);
  153. });
  154. };
  155. switch (match) {
  156. case 'coreml.pb': {
  157. return openModel(context.stream, context, context.identifier);
  158. }
  159. case 'coreml.manifest': {
  160. const obj = context.open('json');
  161. return openManifest(obj, context, '');
  162. }
  163. case 'coreml.featuredescriptions':
  164. case 'coreml.metadata': {
  165. return openManifestStream(context, '../../');
  166. }
  167. case 'coreml.weights': {
  168. return openManifestStream(context, '../../../');
  169. }
  170. default: {
  171. throw new coreml.Error("Unsupported Core ML format '" + match + "'.");
  172. }
  173. }
  174. });
  175. });
  176. }
  177. };
  178. coreml.Model = class {
  179. constructor(metadata, format, model, weights) {
  180. this._format = (format || 'Core ML') + ' v' + model.specificationVersion.toString();
  181. this._metadata = [];
  182. this._graphs = [ new coreml.Graph(metadata, model, weights) ];
  183. if (model.description && model.description.metadata) {
  184. const properties = model.description.metadata;
  185. if (properties.versionString) {
  186. this._version = properties.versionString;
  187. }
  188. if (properties.shortDescription) {
  189. this._description = properties.shortDescription;
  190. }
  191. if (properties.author) {
  192. this._metadata.push({ name: 'author', value: properties.author });
  193. }
  194. if (properties.license) {
  195. this._metadata.push({ name: 'license', value: properties.license });
  196. }
  197. if (metadata.userDefined && Object.keys(properties.userDefined).length > 0) {
  198. /* empty */
  199. }
  200. }
  201. }
  202. get format() {
  203. return this._format;
  204. }
  205. get version() {
  206. return this._version || null;
  207. }
  208. get description() {
  209. return this._description || null;
  210. }
  211. get metadata() {
  212. return this._metadata;
  213. }
  214. get graphs() {
  215. return this._graphs;
  216. }
  217. };
  218. coreml.Graph = class {
  219. constructor(metadata, model, weights) {
  220. this._metadata = metadata;
  221. this._description = model.description;
  222. this._groups = false;
  223. this._inputs = [];
  224. this._outputs = [];
  225. this._nodes = [];
  226. if (this._description) {
  227. this._inputs = this._description.input.map((input) => {
  228. const argument = new coreml.Argument(input.name, coreml.Utility.featureType(input.type), input.shortDescription, null);
  229. return new coreml.Parameter(input.name, true, [ argument ]);
  230. });
  231. this._outputs = this._description.output.map((output) => {
  232. const argument = new coreml.Argument(output.name, coreml.Utility.featureType(output.type), output.shortDescription, null);
  233. return new coreml.Parameter(output.name, true, [ argument ]);
  234. });
  235. }
  236. this._type = this._loadModel(model, {}, '', weights);
  237. }
  238. get name() {
  239. return '';
  240. }
  241. get type() {
  242. return this._type;
  243. }
  244. get inputs() {
  245. return this._inputs;
  246. }
  247. get outputs() {
  248. return this._outputs;
  249. }
  250. get nodes() {
  251. return this._nodes;
  252. }
  253. get groups() {
  254. return this._groups;
  255. }
  256. _updateOutput(name, newName) {
  257. for (const node of this._nodes) {
  258. for (const output of node.outputs) {
  259. for (const argument of output.arguments) {
  260. if (argument.name === name) {
  261. argument.name = newName;
  262. }
  263. }
  264. }
  265. }
  266. return newName;
  267. }
  268. _updateClassifierOutput(group, classifier) {
  269. let labelProbabilityLayerName = classifier.labelProbabilityLayerName;
  270. if (!labelProbabilityLayerName && this._nodes.length > 0) {
  271. const node = this._nodes.slice(-1).pop();
  272. if (node && node.outputs.length == 1 && node.outputs[0].arguments.length == 1) {
  273. labelProbabilityLayerName = node.outputs[0].arguments[0].name;
  274. }
  275. }
  276. let predictedFeatureName = this._description.predictedFeatureName;
  277. let predictedProbabilitiesName = this._description.predictedProbabilitiesName;
  278. if ((predictedFeatureName || predictedProbabilitiesName) && labelProbabilityLayerName && classifier.ClassLabels) {
  279. predictedFeatureName = predictedFeatureName ? predictedFeatureName : '?';
  280. predictedProbabilitiesName = predictedProbabilitiesName ? predictedProbabilitiesName : '?';
  281. const labelProbabilityInput = this._updateOutput(labelProbabilityLayerName, labelProbabilityLayerName + ':labelProbabilityLayerName');
  282. const type = classifier.ClassLabels;
  283. const inputs = [
  284. new coreml.Parameter('input', true, [ new coreml.Argument(labelProbabilityInput) ])
  285. ];
  286. const outputs = [
  287. new coreml.Parameter('probabilities', true, [ new coreml.Argument(predictedProbabilitiesName) ]),
  288. new coreml.Parameter('feature', true, [ new coreml.Argument(predictedFeatureName) ])
  289. ];
  290. const node = new coreml.Node(this._metadata, this._group, type, null, '', classifier[type], inputs, outputs);
  291. this._nodes.push(node);
  292. }
  293. }
  294. _updatePreprocessing(scope, group, preprocessing) {
  295. if (preprocessing && preprocessing.length > 0) {
  296. const preprocessingInput = this._description.input[0].name;
  297. const inputNodes = [];
  298. for (const node of this._nodes) {
  299. if (node.inputs.some((input) => input.arguments.some((arg) => arg.name == preprocessingInput))) {
  300. inputNodes.push(node);
  301. }
  302. }
  303. let preprocessorOutput = preprocessingInput;
  304. let preprocessorIndex = 0;
  305. for (const p of preprocessing) {
  306. const input = p.featureName ? p.featureName : preprocessorOutput;
  307. preprocessorOutput = preprocessingInput + ':' + preprocessorIndex.toString();
  308. this._createNode(scope, group, p.preprocessor, null, '', p[p.preprocessor], [ input ], [ preprocessorOutput ]);
  309. preprocessorIndex++;
  310. }
  311. for (const node of inputNodes) {
  312. for (const input of node.inputs) {
  313. for (const arg of input.arguments) {
  314. if (arg.name === preprocessingInput) {
  315. arg.name = preprocessorOutput;
  316. }
  317. }
  318. }
  319. }
  320. }
  321. }
  322. _loadModel(model, scope, group, weights) {
  323. this._groups = this._groups | (group.length > 0 ? true : false);
  324. const description = model && model.description && model.description.metadata && model.description.metadata.shortDescription ? model.description.metadata.shortDescription : '';
  325. switch (model.Type) {
  326. case 'neuralNetworkClassifier': {
  327. const neuralNetworkClassifier = model.neuralNetworkClassifier;
  328. for (const layer of neuralNetworkClassifier.layers) {
  329. this._createNode(scope, group, layer.layer, layer.name, group === '' ? '' : description, layer[layer.layer], layer.input, layer.output);
  330. }
  331. this._updateClassifierOutput(group, neuralNetworkClassifier);
  332. this._updatePreprocessing(scope, group, neuralNetworkClassifier.preprocessing);
  333. return 'Neural Network Classifier';
  334. }
  335. case 'neuralNetwork': {
  336. const neuralNetwork = model.neuralNetwork;
  337. for (const layer of neuralNetwork.layers) {
  338. this._createNode(scope, group, layer.layer, layer.name, group === '' ? '' : description, layer[layer.layer], layer.input, layer.output);
  339. }
  340. this._updatePreprocessing(scope, group, neuralNetwork.preprocessing);
  341. return 'Neural Network';
  342. }
  343. case 'neuralNetworkRegressor': {
  344. const neuralNetworkRegressor = model.neuralNetworkRegressor;
  345. for (const layer of neuralNetworkRegressor.layers) {
  346. this._createNode(scope, group, layer.layer, layer.name, description, layer[layer.layer], layer.input, layer.output);
  347. }
  348. this._updatePreprocessing(scope, group, neuralNetworkRegressor);
  349. return 'Neural Network Regressor';
  350. }
  351. case 'pipeline': {
  352. for (let i = 0; i < model.pipeline.models.length; i++) {
  353. this._loadModel(model.pipeline.models[i], scope, (group ? (group + '/') : '') + 'pipeline[' + i.toString() + ']');
  354. }
  355. return 'Pipeline';
  356. }
  357. case 'pipelineClassifier': {
  358. for (let i = 0; i < model.pipelineClassifier.pipeline.models.length; i++) {
  359. this._loadModel(model.pipelineClassifier.pipeline.models[i], scope, (group ? (group + '/') : '') + 'pipelineClassifier[' + i.toString() + ']');
  360. }
  361. return 'Pipeline Classifier';
  362. }
  363. case 'pipelineRegressor': {
  364. for (let i = 0; i < model.pipelineRegressor.pipeline.models.length; i++) {
  365. this._loadModel(model.pipelineRegressor.pipeline.models[i], scope, (group ? (group + '/') : '') + 'pipelineRegressor[' + i.toString() + ']');
  366. }
  367. return 'Pipeline Regressor';
  368. }
  369. case 'glmClassifier': {
  370. this._createNode(scope, group, 'glmClassifier', null, description,
  371. {
  372. classEncoding: model.glmClassifier.classEncoding,
  373. offset: model.glmClassifier.offset,
  374. weights: model.glmClassifier.weights
  375. },
  376. [ model.description.input[0].name ],
  377. [ model.description.predictedProbabilitiesName ]);
  378. this._updateClassifierOutput(group, model.glmClassifier);
  379. return 'Generalized Linear Classifier';
  380. }
  381. case 'glmRegressor': {
  382. this._createNode(scope, group, 'glmRegressor', null, description,
  383. model.glmRegressor,
  384. [ model.description.input[0].name ],
  385. [ model.description.output[0].name ]);
  386. return 'Generalized Linear Regressor';
  387. }
  388. case 'dictVectorizer': {
  389. this._createNode(scope, group, 'dictVectorizer', null, description,
  390. model.dictVectorizer,
  391. [ model.description.input[0].name ],
  392. [ model.description.output[0].name ]);
  393. return 'Dictionary Vectorizer';
  394. }
  395. case 'featureVectorizer': {
  396. this._createNode(scope, group, 'featureVectorizer', null, description,
  397. model.featureVectorizer,
  398. coreml.Graph._formatFeatureDescriptionList(model.description.input),
  399. [ model.description.output[0].name ]);
  400. return 'Feature Vectorizer';
  401. }
  402. case 'treeEnsembleClassifier': {
  403. this._createNode(scope, group, 'treeEnsembleClassifier', null, description,
  404. model.treeEnsembleClassifier.treeEnsemble,
  405. [ model.description.input[0].name ],
  406. [ model.description.output[0].name ]);
  407. this._updateClassifierOutput(group, model.treeEnsembleClassifier);
  408. return 'Tree Ensemble Classifier';
  409. }
  410. case 'treeEnsembleRegressor': {
  411. this._createNode(scope, group, 'treeEnsembleRegressor', null, description,
  412. model.treeEnsembleRegressor.treeEnsemble,
  413. [ model.description.input[0].name ],
  414. [ model.description.output[0].name ]);
  415. return 'Tree Ensemble Regressor';
  416. }
  417. case 'supportVectorClassifier': {
  418. this._createNode(scope, group, 'supportVectorClassifier', null, description,
  419. {
  420. coefficients: model.supportVectorClassifier.coefficients,
  421. denseSupportVectors: model.supportVectorClassifier.denseSupportVectors,
  422. kernel: model.supportVectorClassifier.kernel,
  423. numberOfSupportVectorsPerClass: model.supportVectorClassifier.numberOfSupportVectorsPerClass,
  424. probA: model.supportVectorClassifier.probA,
  425. probB: model.supportVectorClassifier.probB,
  426. rho: model.supportVectorClassifier.rho,
  427. supportVectors: model.supportVectorClassifier.supportVectors
  428. },
  429. [ model.description.input[0].name ],
  430. [ model.description.output[0].name ]);
  431. this._updateClassifierOutput(group, model.supportVectorClassifier);
  432. return 'Support Vector Classifier';
  433. }
  434. case 'supportVectorRegressor': {
  435. this._createNode(scope, group, 'supportVectorRegressor', null, description,
  436. {
  437. coefficients: model.supportVectorRegressor.coefficients,
  438. kernel: model.supportVectorRegressor.kernel,
  439. rho: model.supportVectorRegressor.rho,
  440. supportVectors: model.supportVectorRegressor.supportVectors
  441. },
  442. [ model.description.input[0].name ],
  443. [ model.description.output[0].name ]);
  444. return 'Support Vector Regressor';
  445. }
  446. case 'arrayFeatureExtractor': {
  447. this._createNode(scope, group, 'arrayFeatureExtractor', null, description,
  448. { extractIndex: model.arrayFeatureExtractor.extractIndex },
  449. [ model.description.input[0].name ],
  450. [ model.description.output[0].name ]);
  451. return 'Array Feature Extractor';
  452. }
  453. case 'oneHotEncoder': {
  454. const categoryType = model.oneHotEncoder.CategoryType;
  455. const oneHotEncoderParams = { outputSparse: model.oneHotEncoder.outputSparse };
  456. oneHotEncoderParams[categoryType] = model.oneHotEncoder[categoryType];
  457. this._createNode(scope, group, 'oneHotEncoder', null, description,
  458. oneHotEncoderParams,
  459. [ model.description.input[0].name ],
  460. [ model.description.output[0].name ]);
  461. return 'One Hot Encoder';
  462. }
  463. case 'imputer': {
  464. const imputedValue = model.imputer.ImputedValue;
  465. const replaceValue = model.imputer.ReplaceValue;
  466. const imputerParams = {};
  467. imputerParams[imputedValue] = model.imputer[imputedValue];
  468. imputerParams[replaceValue] = model.imputer[replaceValue];
  469. this._createNode(scope, group, 'oneHotEncoder', null, description,
  470. imputerParams,
  471. [ model.description.input[0].name ],
  472. [ model.description.output[0].name ]);
  473. return 'Imputer';
  474. }
  475. case 'normalizer': {
  476. this._createNode(scope, group, 'normalizer', null, description,
  477. model.normalizer,
  478. [ model.description.input[0].name ],
  479. [ model.description.output[0].name ]);
  480. return 'Normalizer';
  481. }
  482. case 'wordTagger': {
  483. this._createNode(scope, group, 'wordTagger', null, description,
  484. model.wordTagger,
  485. [ model.description.input[0].name ],
  486. [
  487. model.wordTagger.tokensOutputFeatureName,
  488. model.wordTagger.tokenTagsOutputFeatureName,
  489. model.wordTagger.tokenLocationsOutputFeatureName,
  490. model.wordTagger.tokenLengthsOutputFeatureName
  491. ]);
  492. return 'Word Tagger';
  493. }
  494. case 'textClassifier': {
  495. this._createNode(scope, group, 'textClassifier', null, description,
  496. model.textClassifier,
  497. [ model.description.input[0].name ],
  498. [ model.description.output[0].name ]);
  499. return 'Text Classifier';
  500. }
  501. case 'nonMaximumSuppression': {
  502. const nonMaximumSuppressionParams = {
  503. pickTop: model.nonMaximumSuppression.pickTop,
  504. stringClassLabels: model.nonMaximumSuppression.stringClassLabels,
  505. iouThreshold: model.nonMaximumSuppression.iouThreshold,
  506. confidenceThreshold: model.nonMaximumSuppression.confidenceThreshold
  507. };
  508. this._createNode(scope, group, 'nonMaximumSuppression', null, description,
  509. nonMaximumSuppressionParams,
  510. [
  511. model.nonMaximumSuppression.confidenceInputFeatureName,
  512. model.nonMaximumSuppression.coordinatesInputFeatureName,
  513. model.nonMaximumSuppression.iouThresholdInputFeatureName,
  514. model.nonMaximumSuppression.confidenceThresholdInputFeatureName,
  515. ],
  516. [
  517. model.nonMaximumSuppression.confidenceOutputFeatureName,
  518. model.nonMaximumSuppression.coordinatesOutputFeatureName
  519. ]);
  520. return 'Non Maximum Suppression';
  521. }
  522. case 'visionFeaturePrint': {
  523. const visionFeaturePrintParams = {
  524. scene: model.visionFeaturePrint.scene
  525. };
  526. this._createNode(scope, group, 'visionFeaturePrint', null, description,
  527. visionFeaturePrintParams,
  528. [ model.description.input[0].name ],
  529. [ model.description.output[0].name ]);
  530. return 'Vision Feature Print';
  531. }
  532. case 'soundAnalysisPreprocessing': {
  533. this._createNode(scope, group, 'soundAnalysisPreprocessing', null, description,
  534. model.soundAnalysisPreprocessing,
  535. [ model.description.input[0].name ],
  536. [ model.description.output[0].name ]);
  537. return 'Sound Analysis Preprocessing';
  538. }
  539. case 'kNearestNeighborsClassifier': {
  540. this._createNode(scope, group, 'kNearestNeighborsClassifier', null, description,
  541. model.kNearestNeighborsClassifier,
  542. [ model.description.input[0].name ],
  543. [ model.description.output[0].name ]);
  544. this._updateClassifierOutput(group, model.kNearestNeighborsClassifier);
  545. return 'Nearest Neighbors Classifier';
  546. }
  547. case 'itemSimilarityRecommender': {
  548. this._createNode(scope, group, 'itemSimilarityRecommender', null, description,
  549. {
  550. itemStringIds: model.itemSimilarityRecommender.itemStringIds.vector,
  551. itemItemSimilarities: model.itemSimilarityRecommender.itemItemSimilarities
  552. },
  553. model.description.input.map((feature) => feature.name),
  554. model.description.output.map((feature) => feature.name));
  555. return 'Item Similarity Recommender';
  556. }
  557. case 'audioFeaturePrint': {
  558. this._createNode(scope, group, 'audioFeaturePrint', null, description,
  559. model.audioFeaturePrint,
  560. [ model.description.input[0].name ],
  561. [ model.description.output[0].name ]);
  562. return 'Audio Feature Print';
  563. }
  564. case 'linkedModel': {
  565. this._createNode(scope, group, 'linkedModel', null, description,
  566. model.linkedModel.linkedModelFile,
  567. [ model.description.input[0].name ],
  568. [ model.description.output[0].name ]);
  569. return 'Linked Model';
  570. }
  571. case 'customModel': {
  572. this._createNode(scope, group, 'customModel', null, description,
  573. { className: model.customModel.className, parameters: model.customModel.parameters },
  574. [ model.description.input[0].name ],
  575. [ model.description.output[0].name ]);
  576. return 'customModel';
  577. }
  578. case 'mlProgram': {
  579. return this._loadProgram(model.mlProgram, scope, group, weights);
  580. }
  581. default: {
  582. throw new coreml.Error("Unsupported model type '" + JSON.stringify(Object.keys(model)) + "'.");
  583. }
  584. }
  585. }
  586. _loadProgram(program, scope, group, weights) {
  587. // TODO: need to handle functions other than main?
  588. const main = program.functions.main;
  589. // TODO: need to handle more than one block specialization?
  590. const block = main.block_specializations.CoreML5;
  591. const convertValue = (value) => {
  592. switch (value.value) {
  593. case 'immediateValue': {
  594. const tensor = value.immediateValue.tensor;
  595. let values = null;
  596. switch (tensor.value) {
  597. case 'ints':
  598. values = tensor.ints.values;
  599. break;
  600. case 'strings':
  601. values = tensor.strings.values;
  602. break;
  603. case 'bools':
  604. values = tensor.bools.values;
  605. break;
  606. case 'floats':
  607. values = tensor.floats.values;
  608. break;
  609. case 'bytes':
  610. values = tensor.bytes.values;
  611. break;
  612. default:
  613. throw new coreml.Error("Unsupported tensor value '" + tensor.value + "'.");
  614. }
  615. return values;
  616. }
  617. case 'blobFileValue': {
  618. const type = coreml.Utility.valueType(value.type);
  619. const blob = value.blobFileValue;
  620. const offset = blob.offset.toNumber();
  621. const file = blob.fileName;
  622. let data = null;
  623. const stream = weights.get(file);
  624. if (stream) {
  625. stream.seek(offset);
  626. const buffer = stream.read(32);
  627. const reader = new base.BinaryReader(buffer);
  628. const signature = reader.uint32();
  629. if (signature == 0xdeadbeef) {
  630. reader.uint32(); // dataType
  631. const size = reader.uint64();
  632. stream.seek(reader.uint64());
  633. const length = (type.shape.dimensions || []).reduce((a, b) => a * b, 1);
  634. switch (type.dataType) {
  635. case 'float32': {
  636. const buffer = stream.read(size);
  637. data = new Float32Array(buffer.buffer, buffer.byteOffset, length).slice();
  638. break;
  639. }
  640. case 'float16': {
  641. data = stream.read(size);
  642. break;
  643. }
  644. default:
  645. throw new coreml.Error("Unsupported blob data type '" + type.dataType + "'.");
  646. }
  647. }
  648. }
  649. return new coreml.Tensor('Blob', type, data);
  650. }
  651. default: {
  652. throw new coreml.Error("Unsupported value '" + value.value + "'.");
  653. }
  654. }
  655. };
  656. const args = new Map();
  657. const arg = (name) => {
  658. if (!args.has(name)) {
  659. args.set(name, { name: name, to: [], from: [] });
  660. }
  661. return args.get(name);
  662. };
  663. const operations = block.operations.map((op) => {
  664. const operation = {
  665. type: op.type,
  666. attributes: {}
  667. };
  668. for (const entry of Object.entries(op.attributes)) {
  669. const key = entry[0];
  670. const value = entry[1];
  671. operation.attributes[key] = convertValue(value);
  672. }
  673. operation.inputs = Object.entries(op.inputs).map((entry) => {
  674. const key = entry[0];
  675. const input = entry[1];
  676. const args = input.arguments.map((argument) => {
  677. if (argument.name) {
  678. const value = arg(argument.name);
  679. value.to.push(operation);
  680. return value;
  681. }
  682. return { value: argument.value };
  683. });
  684. return {
  685. name: key,
  686. arguments: args
  687. };
  688. });
  689. operation.outputs = op.outputs.map((output) => {
  690. const value = arg(output.name);
  691. value.type = coreml.Utility.valueType(output.type);
  692. value.from.push(operation);
  693. return {
  694. name: 'output',
  695. arguments: [ value ]
  696. };
  697. });
  698. return operation;
  699. });
  700. for (const op of operations) {
  701. if (op.type === 'const' && op.inputs.length === 0 &&
  702. op.outputs.length === 1 && op.outputs[0].arguments.length === 1) {
  703. const argument = op.outputs[0].arguments[0];
  704. if (op.attributes && op.attributes.val) {
  705. const type = argument.type;
  706. const data = op.attributes.val;
  707. if (data instanceof Uint8Array && data.length === 2 &&
  708. type.dataType === 'float16' && type.shape.dimensions.length === 0) {
  709. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  710. argument.value = view.getFloat16(0, true);
  711. }
  712. else {
  713. argument.value = data;
  714. }
  715. argument.const = true;
  716. op.delete = true;
  717. }
  718. }
  719. }
  720. for (const op of operations) {
  721. for (const input of op.inputs) {
  722. if (input.arguments.length > 1 && input.arguments.some((argument) => argument.const)) {
  723. if (input.arguments.every((argument) => argument.value instanceof coreml.Tensor)) {
  724. continue;
  725. }
  726. for (const argument of input.arguments) {
  727. for (const from of argument.from) {
  728. from.delete = false;
  729. }
  730. delete argument.value;
  731. }
  732. }
  733. }
  734. }
  735. for (const op of operations) {
  736. if (op.delete) {
  737. continue;
  738. }
  739. op.inputs = op.inputs.filter((input) => {
  740. if (input.arguments.every((argument) => argument.value === undefined || argument.value instanceof coreml.Tensor)) {
  741. return true;
  742. }
  743. if (input.arguments.length === 1) {
  744. const argument = input.arguments[0];
  745. op.attributes[input.name] = argument.value;
  746. return false;
  747. }
  748. op.attributes[input.name] = input.arguments.map((argument) => argument.value[0]);
  749. return false;
  750. });
  751. }
  752. const tensors = new Map();
  753. const tensor = (arg) => {
  754. if (!tensors.has(arg.name)) {
  755. tensors.set(arg.name, new coreml.Argument(arg.name, arg.type, null, arg.value));
  756. }
  757. return tensors.get(arg.name);
  758. };
  759. for (const op of operations) {
  760. if (op.delete) {
  761. continue;
  762. }
  763. op.inputs = op.inputs.map((input) => new coreml.Parameter(input.name, true, input.arguments.map((argument) => tensor(argument))));
  764. op.outputs = op.outputs.map((output) => new coreml.Parameter(output.name, true, output.arguments.map((argument) => tensor(argument))));
  765. }
  766. for (const op of operations.filter((op) => !op.delete)) {
  767. const type = 'program:' + op.type;
  768. const metadata = this._metadata.type(type);
  769. if (metadata && Array.isArray(metadata.inputs)) {
  770. let index = 1;
  771. const map = new Map(metadata.inputs.map((input) => [ input.name, index++ ]));
  772. op.inputs.sort((a, b) => (map.get(a.name) || map.size) - (map.get(b.name) || map.size));
  773. }
  774. const node = new coreml.Node(this._metadata, group, type, null, null, op.attributes, op.inputs, op.outputs);
  775. this._nodes.push(node);
  776. }
  777. return 'ML Program';
  778. }
  779. _createNode(scope, group, type, name, description, data, inputs, outputs, outputTypes) {
  780. inputs = inputs.map((input) => scope[input] ? scope[input].argument : input);
  781. outputs = outputs.map((output) => {
  782. if (scope[output]) {
  783. scope[output].counter++;
  784. const next = output + '\n' + scope[output].counter.toString(); // custom argument id
  785. scope[output].argument = next;
  786. return next;
  787. }
  788. scope[output] = {
  789. argument: output,
  790. counter: 0
  791. };
  792. return output;
  793. });
  794. const initializers = [];
  795. const attributes = {};
  796. if (data) {
  797. const map = this._initialize(type, data, initializers);
  798. for (const key of Object.keys(data)) {
  799. if (map[key]) {
  800. continue;
  801. }
  802. attributes[key] = data[key];
  803. }
  804. }
  805. const inputParameters = this._metadata.getInputs(type, inputs).map((input) => {
  806. return new coreml.Parameter(input.name, true, input.arguments.map((argument) => {
  807. return new coreml.Argument(argument.name, argument.type, null, null);
  808. }));
  809. });
  810. inputParameters.push(...initializers);
  811. const outputParameters = outputs.map((output, index) => {
  812. const name = this._metadata.getOutputName(type, index);
  813. const outputType = outputTypes ? outputTypes[index] : null;
  814. return new coreml.Parameter(name, true, [ new coreml.Argument(output, outputType, null, null) ]);
  815. });
  816. const node = new coreml.Node(this._metadata, group, type, name, description, attributes, inputParameters, outputParameters);
  817. this._nodes.push(node);
  818. return node;
  819. }
  820. _initializer(type, initializers, kind, name, shape, data) {
  821. let dataType = '?';
  822. let quantization = null;
  823. let values = null;
  824. if (data) {
  825. if (data.floatValue && data.floatValue.length > 0) {
  826. values = data.floatValue;
  827. dataType = 'float32';
  828. }
  829. else if (data.float16Value && data.float16Value.length > 0) {
  830. values = data.float16Value; // byte[]
  831. dataType = 'float16';
  832. }
  833. else if (data.rawValue && data.rawValue.length > 0) {
  834. if (data.quantization) {
  835. values = data.rawValue;
  836. dataType = 'uint' + data.quantization.numberOfBits.toString();
  837. }
  838. else {
  839. shape = [];
  840. }
  841. }
  842. quantization = data.quantization || null;
  843. }
  844. const tensorType = new coreml.TensorType(dataType, new coreml.TensorShape(shape));
  845. const tensor = new coreml.Tensor(kind, tensorType, values, quantization);
  846. const argument = new coreml.Argument('', null, null, tensor);
  847. const visible = this._metadata.visible(type, name);
  848. initializers.push(new coreml.Parameter(name, visible, [ argument ]));
  849. }
  850. _initialize(type, data, initializers) {
  851. switch (type) {
  852. case 'convolution': {
  853. const weightsShape = [ data.outputChannels, data.kernelChannels, data.kernelSize[0], data.kernelSize[1] ];
  854. if (data.isDeconvolution) {
  855. weightsShape[0] = data.kernelChannels;
  856. weightsShape[1] = Math.floor(data.outputChannels / (data.nGroups != 0 ? data.nGroups : 1));
  857. }
  858. this._initializer(type, initializers, 'Weights', 'weights', weightsShape, data.weights);
  859. if (data.hasBias) {
  860. this._initializer(type, initializers, 'Weights', 'bias', [ data.outputChannels ], data.bias);
  861. }
  862. return { 'weights': true, 'bias': data.hasBias };
  863. }
  864. case 'innerProduct':
  865. this._initializer(type, initializers, 'Weights', 'weights', [ data.outputChannels, data.inputChannels ], data.weights);
  866. if (data.hasBias) {
  867. this._initializer(type, initializers, 'Weights', 'bias', [ data.outputChannels ], data.bias);
  868. }
  869. return { 'weights': true, 'bias': data.hasBias };
  870. case 'batchnorm':
  871. this._initializer(type, initializers, 'Weights', 'gamma', [ data.channels ], data.gamma);
  872. this._initializer(type, initializers, 'Weights', 'beta', [ data.channels ], data.beta);
  873. if (data.mean) {
  874. this._initializer(type, initializers, 'Weights', 'mean', [ data.channels ], data.mean);
  875. }
  876. if (data.variance) {
  877. this._initializer(type, initializers, 'Weights', 'variance', [ data.channels ], data.variance);
  878. }
  879. return { 'gamma': true, 'beta': true, 'mean': true, 'variance': true };
  880. case 'embedding':
  881. this._initializer(type, initializers, 'Weights', 'weights', [ data.inputDim, data.outputChannels ], data.weights);
  882. return { 'weights': true };
  883. case 'loadConstant':
  884. case 'loadConstantND':
  885. this._initializer(type, initializers, 'Weights', 'data', data.shape, data.data);
  886. return { 'data': true };
  887. case 'scale':
  888. this._initializer(type, initializers, 'Weights', 'scale', data.shapeScale, data.scale);
  889. if (data.hasBias) {
  890. this._initializer(type, initializers, 'Weights', 'bias', data.shapeBias, data.bias);
  891. }
  892. return { 'scale': true, 'bias': data.hasBias };
  893. case 'bias':
  894. this._initializer(type, initializers, 'Weights', 'bias', data.shape, data.bias);
  895. return { 'bias': true };
  896. case 'simpleRecurrent':
  897. this._initializer(type, initializers, 'Weights', 'weights', [ data.outputVectorSize, data.inputVectorSize ], data.weightMatrix);
  898. this._initializer(type, initializers, 'Weights', 'recurrent', [ data.outputVectorSize, data.inputVectorSize ], data.recursionMatrix);
  899. if (data.hasBiasVectors) {
  900. this._initializer(type, initializers, 'Weights', 'bias', [ data.outputVectorSize ], data.biasVector);
  901. }
  902. return { 'weightMatrix': true, 'recursionMatrix': true, 'biasVector': data.hasBiasVectors };
  903. case 'gru': {
  904. const recursionMatrixShape = [ data.outputVectorSize, data.outputVectorSize ];
  905. const weightMatrixShape = [ data.outputVectorSize, data.inputVectorSize ];
  906. const biasVectorShape = [ data.outputVectorSize ];
  907. this._initializer(type, initializers, 'Weights', 'updateGateWeightMatrix', weightMatrixShape, data.updateGateWeightMatrix);
  908. this._initializer(type, initializers, 'Weights', 'resetGateWeightMatrix', weightMatrixShape, data.resetGateWeightMatrix);
  909. this._initializer(type, initializers, 'Weights', 'outputGateWeightMatrix', weightMatrixShape, data.outputGateWeightMatrix);
  910. this._initializer(type, initializers, 'Weights', 'updateGateRecursionMatrix', recursionMatrixShape, data.updateGateRecursionMatrix);
  911. this._initializer(type, initializers, 'Weights', 'resetGateRecursionMatrix', recursionMatrixShape, data.resetGateRecursionMatrix);
  912. this._initializer(type, initializers, 'Weights', 'outputGateRecursionMatrix', recursionMatrixShape, data.outputGateRecursionMatrix);
  913. if (data.hasBiasVectors) {
  914. this._initializer(type, initializers, 'Weights', 'updateGateBiasVector', biasVectorShape, data.updateGateBiasVector);
  915. this._initializer(type, initializers, 'Weights', 'resetGateBiasVector', biasVectorShape, data.resetGateBiasVector);
  916. this._initializer(type, initializers, 'Weights', 'outputGateBiasVector', biasVectorShape, data.outputGateBiasVector);
  917. }
  918. return {
  919. 'updateGateWeightMatrix': true, 'resetGateWeightMatrix': true, 'outputGateWeightMatrix': true,
  920. 'updateGateRecursionMatrix': true, 'resetGateRecursionMatrix': true, 'outputGateRecursionMatrix': true,
  921. 'updateGateBiasVector': data.hasBiasVectors, 'resetGateBiasVector': data.hasBiasVectors, 'outputGateBiasVector': data.hasBiasVectors
  922. };
  923. }
  924. case 'uniDirectionalLSTM':
  925. case 'biDirectionalLSTM': {
  926. const count = (type == 'uniDirectionalLSTM') ? 1 : 2;
  927. const matrixShape = [ data.outputVectorSize, data.inputVectorSize ];
  928. const vectorShape = [ data.outputVectorSize ];
  929. for (let i = 0; i < count; i++) {
  930. const weights = count == 1 ? data.weightParams : data.weightParams[i];
  931. const suffix = (i == 0) ? '' : '_rev';
  932. this._initializer(type, initializers, 'Weights', 'inputGateWeightMatrix' + suffix, matrixShape, weights.inputGateWeightMatrix);
  933. this._initializer(type, initializers, 'Weights', 'forgetGateWeightMatrix' + suffix, matrixShape, weights.forgetGateWeightMatrix);
  934. this._initializer(type, initializers, 'Weights', 'blockInputWeightMatrix' + suffix, matrixShape, weights.blockInputWeightMatrix);
  935. this._initializer(type, initializers, 'Weights', 'outputGateWeightMatrix' + suffix, matrixShape, weights.outputGateWeightMatrix);
  936. this._initializer(type, initializers, 'Weights', 'inputGateRecursionMatrix' + suffix, matrixShape, weights.inputGateRecursionMatrix);
  937. this._initializer(type, initializers, 'Weights', 'forgetGateRecursionMatrix' + suffix, matrixShape,weights.forgetGateRecursionMatrix);
  938. this._initializer(type, initializers, 'Weights', 'blockInputRecursionMatrix' + suffix, matrixShape, weights.blockInputRecursionMatrix);
  939. this._initializer(type, initializers, 'Weights', 'outputGateRecursionMatrix' + suffix, matrixShape, weights.outputGateRecursionMatrix);
  940. if (data.params.hasBiasVectors) {
  941. this._initializer(type, initializers, 'Weights', 'inputGateBiasVector' + suffix, vectorShape, weights.inputGateBiasVector);
  942. this._initializer(type, initializers, 'Weights', 'forgetGateBiasVector' + suffix, vectorShape, weights.forgetGateBiasVector);
  943. this._initializer(type, initializers, 'Weights', 'blockInputBiasVector' + suffix, vectorShape, weights.blockInputBiasVector);
  944. this._initializer(type, initializers, 'Weights', 'outputGateBiasVector' + suffix, vectorShape, weights.outputGateBiasVector);
  945. }
  946. if (data.params.hasPeepholeVectors) {
  947. this._initializer(type, initializers, 'Weights', 'inputGatePeepholeVector' + suffix, vectorShape, weights.inputGatePeepholeVector);
  948. this._initializer(type, initializers, 'Weights', 'forgetGatePeepholeVector' + suffix, vectorShape, weights.forgetGatePeepholeVector);
  949. this._initializer(type, initializers, 'Weights', 'outputGatePeepholeVector' + suffix, vectorShape, weights.outputGatePeepholeVector);
  950. }
  951. }
  952. return { 'weightParams': true };
  953. }
  954. case 'dictVectorizer':
  955. data.stringToIndex = this._convertVector(data.stringToIndex);
  956. return {};
  957. case 'wordTagger':
  958. data.modelParameterData = Array.from(data.modelParameterData);
  959. data.stringTags = this._convertVector(data.stringTags);
  960. return { tokensOutputFeatureName: true, tokenTagsOutputFeatureName: true, tokenLengthsOutputFeatureName: true, tokenLocationsOutputFeatureName: true };
  961. case 'textClassifier':
  962. data.modelParameterData = Array.from(data.modelParameterData);
  963. data.stringClassLabels = this._convertVector(data.stringClassLabels);
  964. return {};
  965. case 'nonMaximumSuppression':
  966. data.stringClassLabels = this._convertVector(data.stringClassLabels);
  967. return {};
  968. default:
  969. return {};
  970. }
  971. }
  972. _convertVector(value) {
  973. if (value && Object.keys(value).length == 1 && value.vector) {
  974. return value.vector;
  975. }
  976. return value;
  977. }
  978. static _formatFeatureDescriptionList(list) {
  979. return list.map((item) => item.name);
  980. }
  981. };
  982. coreml.Parameter = class {
  983. constructor(name, visible, args) {
  984. this._name = name;
  985. this._visible = visible;
  986. this._arguments = args;
  987. }
  988. get name() {
  989. return this._name;
  990. }
  991. get visible() {
  992. return this._visible;
  993. }
  994. get arguments() {
  995. return this._arguments;
  996. }
  997. };
  998. coreml.Argument = class {
  999. constructor(name, type, description, initializer) {
  1000. if (typeof name !== 'string') {
  1001. throw new coreml.Error("Invalid argument identifier '" + JSON.stringify(name) + "'.");
  1002. }
  1003. this._name = name;
  1004. this._type = type;
  1005. this._description = description || null;
  1006. this._initializer = initializer || null;
  1007. }
  1008. get name() {
  1009. return this._name;
  1010. }
  1011. set name(value) {
  1012. this._name = value;
  1013. }
  1014. get type() {
  1015. if (this._initializer) {
  1016. return this._initializer.type;
  1017. }
  1018. return this._type;
  1019. }
  1020. get description() {
  1021. return this._description;
  1022. }
  1023. get quantization() {
  1024. if (this._initializer) {
  1025. return this._initializer.quantization;
  1026. }
  1027. return null;
  1028. }
  1029. get initializer() {
  1030. return this._initializer;
  1031. }
  1032. };
  1033. coreml.Node = class {
  1034. constructor(metadata, group, type, name, description, attributes, inputs, outputs) {
  1035. if (!type) {
  1036. throw new Error('Undefined node type.');
  1037. }
  1038. if (group) {
  1039. this._group = group;
  1040. }
  1041. this._type = Object.assign({}, metadata.type(type) || { name: type });
  1042. this._type.name = type.split(':').pop();
  1043. this._name = name || '';
  1044. this._description = description || '';
  1045. this._inputs = inputs;
  1046. this._outputs = outputs;
  1047. this._attributes = [];
  1048. if (attributes) {
  1049. for (const key of Object.keys(attributes)) {
  1050. const schema = metadata.attribute(type, key);
  1051. const value = attributes[key];
  1052. const attribute = new coreml.Attribute(schema, key, value);
  1053. this._attributes.push(attribute);
  1054. }
  1055. }
  1056. }
  1057. get type() {
  1058. return this._type;
  1059. }
  1060. get name() {
  1061. return this._name;
  1062. }
  1063. get description() {
  1064. return this._description;
  1065. }
  1066. get metadata() {
  1067. return this._metadata;
  1068. }
  1069. get group() {
  1070. return this._group ? this._group : null;
  1071. }
  1072. get inputs() {
  1073. return this._inputs;
  1074. }
  1075. get outputs() {
  1076. return this._outputs;
  1077. }
  1078. get attributes() {
  1079. return this._attributes;
  1080. }
  1081. };
  1082. coreml.Attribute = class {
  1083. constructor(metadata, name, value) {
  1084. this._name = name;
  1085. this._value = value;
  1086. if (this._value instanceof coreml.Tensor) {
  1087. this._type = 'tensor';
  1088. }
  1089. if (metadata) {
  1090. if (metadata.type) {
  1091. this._type = metadata.type;
  1092. }
  1093. if (this._type && coreml.proto) {
  1094. this._value = coreml.Utility.enum(this._type, this._value);
  1095. }
  1096. if (Object.prototype.hasOwnProperty.call(metadata, 'visible') && !metadata.visible) {
  1097. this._visible = false;
  1098. }
  1099. else if (Object.prototype.hasOwnProperty.call(metadata, 'default')) {
  1100. if (Array.isArray(value)) {
  1101. value = value.map((item) => item.toNumber());
  1102. }
  1103. if (JSON.stringify(metadata.default) == JSON.stringify(value)) {
  1104. this._visible = false;
  1105. }
  1106. }
  1107. }
  1108. }
  1109. get name() {
  1110. return this._name;
  1111. }
  1112. get type() {
  1113. return this._type;
  1114. }
  1115. get value() {
  1116. return this._value;
  1117. }
  1118. get visible() {
  1119. return this._visible == false ? false : true;
  1120. }
  1121. };
  1122. coreml.Tensor = class {
  1123. constructor(kind, type, data, quantization) {
  1124. this._kind = kind;
  1125. this._type = type;
  1126. this._data = data;
  1127. this._quantization = quantization;
  1128. }
  1129. get kind() {
  1130. return this._kind;
  1131. }
  1132. get type() {
  1133. return this._type;
  1134. }
  1135. get quantization() {
  1136. if (this._quantization) {
  1137. if (this._quantization.lookupTableQuantization &&
  1138. this._quantization.lookupTableQuantization.floatValue &&
  1139. this._quantization.lookupTableQuantization.floatValue.length > 0) {
  1140. const map = [];
  1141. for (const key of Object.keys(this._quantization.lookupTableQuantization.floatValue)) {
  1142. map.push(key.toString() + ' = ' + this._quantization.lookupTableQuantization.floatValue[key].toString());
  1143. }
  1144. return map.join('; ');
  1145. }
  1146. return '?';
  1147. }
  1148. return null;
  1149. }
  1150. get state() {
  1151. return this._context().state;
  1152. }
  1153. get value() {
  1154. const context = this._context();
  1155. if (context.state) {
  1156. return null;
  1157. }
  1158. context.limit = Number.MAX_SAFE_INTEGER;
  1159. return this._decode(context, 0);
  1160. }
  1161. toString() {
  1162. const context = this._context();
  1163. if (context.state) {
  1164. return '';
  1165. }
  1166. context.limit = 10000;
  1167. const value = this._decode(context, 0);
  1168. return JSON.stringify(value, null, 4);
  1169. }
  1170. _context() {
  1171. const context = {};
  1172. context.state = null;
  1173. context.index = 0;
  1174. context.count = 0;
  1175. context.dataType = this._type.dataType;
  1176. context.dimensions = this._type.shape.dimensions;
  1177. if (!this._data) {
  1178. context.state = 'Tensor data is empty.';
  1179. return context;
  1180. }
  1181. switch (context.dataType) {
  1182. case 'float32':
  1183. context.data = this._data;
  1184. break;
  1185. case 'float16':
  1186. context.data = new DataView(this._data.buffer, this._data.byteOffset, this._data.byteLength);
  1187. break;
  1188. default:
  1189. if (this._quantization) {
  1190. context.dataType = 'quantization';
  1191. context.bits = this._quantization.numberOfBits.toNumber();
  1192. context.data = new DataView(this._data.buffer, this._data.byteOffset, this._data.byteLength);
  1193. }
  1194. else {
  1195. context.state = 'Tensor data type is not implemented.';
  1196. }
  1197. break;
  1198. }
  1199. return context;
  1200. }
  1201. _decode(context, dimension) {
  1202. const results = [];
  1203. const size = context.dimensions[dimension];
  1204. if (dimension == context.dimensions.length - 1) {
  1205. for (let i = 0; i < size; i++) {
  1206. if (context.count > context.limit) {
  1207. results.push('...');
  1208. return results;
  1209. }
  1210. switch (context.dataType) {
  1211. case 'float32':
  1212. results.push(this._data[context.index]);
  1213. context.index++;
  1214. break;
  1215. case 'float16':
  1216. results.push(context.data.getFloat16(context.index, true));
  1217. context.index += 2;
  1218. break;
  1219. case 'quantization':
  1220. results.push(context.data.getBits(context.index, context.bits));
  1221. context.index++;
  1222. break;
  1223. default:
  1224. break;
  1225. }
  1226. context.count++;
  1227. }
  1228. }
  1229. else {
  1230. for (let j = 0; j < size; j++) {
  1231. if (context.count > context.limit) {
  1232. results.push('...');
  1233. return results;
  1234. }
  1235. results.push(this._decode(context, dimension + 1));
  1236. }
  1237. }
  1238. return results;
  1239. }
  1240. };
  1241. coreml.TensorType = class {
  1242. constructor(dataType, shape) {
  1243. this._dataType = dataType;
  1244. this._shape = shape || new coreml.TensorShape([]);
  1245. }
  1246. get dataType() {
  1247. return this._dataType;
  1248. }
  1249. get shape() {
  1250. return this._shape;
  1251. }
  1252. toString() {
  1253. return this.dataType + this._shape.toString();
  1254. }
  1255. };
  1256. coreml.TensorShape = class {
  1257. constructor(dimensions) {
  1258. this._dimensions = dimensions;
  1259. }
  1260. get dimensions() {
  1261. return this._dimensions;
  1262. }
  1263. toString() {
  1264. if (!this._dimensions || this._dimensions.length == 0) {
  1265. return '';
  1266. }
  1267. return '[' + this._dimensions.map((dimension) => dimension.toString()).join(',') + ']';
  1268. }
  1269. };
  1270. coreml.ListType = class {
  1271. constructor(elementType) {
  1272. this._elementType = elementType;
  1273. }
  1274. toString() {
  1275. return 'list<' + this._elementType.toString() + '>';
  1276. }
  1277. };
  1278. coreml.MapType = class {
  1279. constructor(keyType, valueType) {
  1280. this._keyType = keyType;
  1281. this._valueType = valueType;
  1282. }
  1283. get keyType() {
  1284. return this._keyType;
  1285. }
  1286. get valueType() {
  1287. return this._valueType;
  1288. }
  1289. toString() {
  1290. return 'map<' + this._keyType + ',' + this._valueType.toString() + '>';
  1291. }
  1292. };
  1293. coreml.SequenceType = class {
  1294. constructor(type) {
  1295. this._type = type;
  1296. }
  1297. get type() {
  1298. return this._type;
  1299. }
  1300. toString() {
  1301. return 'sequence<' + this._type + '>';
  1302. }
  1303. };
  1304. coreml.ImageType = class {
  1305. constructor(colorSpace, width, height) {
  1306. this._width = width;
  1307. this._height = height;
  1308. switch (colorSpace) {
  1309. case coreml.proto.ImageFeatureType.ColorSpace.GRAYSCALE:
  1310. this._colorSpace = 'Grayscale';
  1311. break;
  1312. case coreml.proto.ImageFeatureType.ColorSpace.RGB:
  1313. this._colorSpace = 'RGB';
  1314. break;
  1315. case coreml.proto.ImageFeatureType.ColorSpace.BGR:
  1316. this._colorSpace = 'BGR';
  1317. break;
  1318. default:
  1319. throw new coreml.Error("Unsupported image color space '" + colorSpace + "'.");
  1320. }
  1321. }
  1322. toString() {
  1323. return 'image<' + this._colorSpace + ',' + this._width. toString() + 'x' + this._height.toString() + '>';
  1324. }
  1325. };
  1326. coreml.OptionalType = class {
  1327. constructor(type) {
  1328. this._type = type;
  1329. }
  1330. get type() {
  1331. return this._type;
  1332. }
  1333. toString() {
  1334. return 'optional<' + this._type.toString() + '>';
  1335. }
  1336. };
  1337. coreml.Utility = class {
  1338. static enum(name, value) {
  1339. let type = coreml.proto;
  1340. const parts = name.split('.');
  1341. while (type && parts.length > 0) {
  1342. type = type[parts.shift()];
  1343. }
  1344. if (type) {
  1345. coreml.Utility._enumKeyMap = coreml.Utility._enumKeyMap || new Map();
  1346. if (!coreml.Utility._enumKeyMap.has(name)) {
  1347. const map = new Map(Object.entries(type).map((pair) => [ pair[1], pair[0] ]));
  1348. coreml.Utility._enumKeyMap.set(name, map);
  1349. }
  1350. const map = coreml.Utility._enumKeyMap.get(name);
  1351. if (map.has(value)) {
  1352. return map.get(value);
  1353. }
  1354. }
  1355. return value;
  1356. }
  1357. static featureType(type) {
  1358. let result = '?';
  1359. if (type) {
  1360. switch (type.Type) {
  1361. case 'multiArrayType': {
  1362. let shape = new coreml.TensorShape([]);
  1363. if (type.multiArrayType.shape && type.multiArrayType.shape.length > 0) {
  1364. shape = new coreml.TensorShape(type.multiArrayType.shape);
  1365. }
  1366. let dataType = '?';
  1367. switch (type.multiArrayType.dataType) {
  1368. case coreml.proto.ArrayFeatureType.ArrayDataType.INVALID_ARRAY_DATA_TYPE:
  1369. dataType = '?';
  1370. break;
  1371. case coreml.proto.ArrayFeatureType.ArrayDataType.FLOAT32:
  1372. dataType = 'float32';
  1373. break;
  1374. case coreml.proto.ArrayFeatureType.ArrayDataType.INT32:
  1375. dataType = 'int32';
  1376. break;
  1377. case coreml.proto.ArrayFeatureType.ArrayDataType.DOUBLE:
  1378. dataType = 'float64';
  1379. break;
  1380. default:
  1381. throw new coreml.Error("Unsupported array data type '" + type.multiArrayType.dataType + "'.");
  1382. }
  1383. result = new coreml.TensorType(dataType, shape);
  1384. break;
  1385. }
  1386. case 'stringType': {
  1387. result = new coreml.TensorType('string');
  1388. break;
  1389. }
  1390. case 'doubleType': {
  1391. result = new coreml.TensorType('float64');
  1392. break;
  1393. }
  1394. case 'int64Type': {
  1395. result = new coreml.TensorType('int64');
  1396. break;
  1397. }
  1398. case 'dictionaryType': {
  1399. result = new coreml.MapType(type.dictionaryType.KeyType.replace('KeyType', ''), 'float64');
  1400. break;
  1401. }
  1402. case 'sequenceType': {
  1403. result = new coreml.SequenceType(coreml.Utility.featureType(type[type.Type]));
  1404. break;
  1405. }
  1406. case 'imageType': {
  1407. result = new coreml.ImageType(type.imageType.colorSpace, type.imageType.width, type.imageType.height);
  1408. break;
  1409. }
  1410. default: {
  1411. throw new coreml.Error("Unsupported feature type '" + type.Type + "'.");
  1412. }
  1413. }
  1414. if (type.isOptional) {
  1415. result = new coreml.OptionalType(result);
  1416. }
  1417. }
  1418. return result;
  1419. }
  1420. static tensorType(type) {
  1421. if (!coreml.Utility._dataTypes) {
  1422. coreml.Utility._dataTypes = new Map();
  1423. const DataType = coreml.proto.MILSpec.DataType;
  1424. for (const pair of Object.entries(DataType)) {
  1425. if (pair[0] === 'UNUSED_TYPE') {
  1426. continue;
  1427. }
  1428. const name = pair[0] === 'bool' ? 'boolean' : pair[0].toLowerCase();
  1429. coreml.Utility._dataTypes.set(pair[1], name);
  1430. }
  1431. }
  1432. const shape = (type.dimensions.map(dim => dim.constant ? dim.constant.size : '?'));
  1433. const dataType = coreml.Utility._dataTypes.get(type.dataType);
  1434. if (dataType === null) {
  1435. throw new coreml.Error("Unsupported data type '" + type.dataType + "'.");
  1436. }
  1437. return new coreml.TensorType(dataType, new coreml.TensorShape(shape));
  1438. }
  1439. static valueType(type) {
  1440. switch (type.type) {
  1441. case 'tensorType':
  1442. return coreml.Utility.tensorType(type.tensorType);
  1443. case 'listType':
  1444. return new coreml.ListType(coreml.Utility.valueType(type.listType.type));
  1445. default:
  1446. throw new coreml.Error("Unsupported value type '" + type.type + "'.");
  1447. }
  1448. }
  1449. };
  1450. coreml.Metadata = class {
  1451. static open(context) {
  1452. if (coreml.Metadata._metadata) {
  1453. return Promise.resolve(coreml.Metadata._metadata);
  1454. }
  1455. return context.request('coreml-metadata.json', 'utf-8', null).then((data) => {
  1456. coreml.Metadata._metadata = new coreml.Metadata(data);
  1457. return coreml.Metadata._metadata;
  1458. }).catch(() => {
  1459. coreml.Metadata._metadata = new coreml.Metadata(null);
  1460. return coreml.Metadata._metadata;
  1461. });
  1462. }
  1463. constructor(data) {
  1464. this._map = new Map();
  1465. this._attributeCache = new Map();
  1466. this._inputCache = new Map();
  1467. if (data) {
  1468. const metadata = JSON.parse(data);
  1469. this._map = new Map(metadata.map((item) => [ item.name, item ]));
  1470. }
  1471. }
  1472. type(name) {
  1473. return this._map.get(name);
  1474. }
  1475. attribute(type, name) {
  1476. const key = type + ':' + name;
  1477. if (!this._attributeCache.has(key)) {
  1478. this._attributeCache.set(key, null);
  1479. const metadata = this.type(type);
  1480. if (metadata && Array.isArray(metadata.attributes) && metadata.attributes.length > 0) {
  1481. for (const attribute of metadata.attributes) {
  1482. this._attributeCache.set(type + ':' + attribute.name, attribute);
  1483. }
  1484. }
  1485. }
  1486. return this._attributeCache.get(key);
  1487. }
  1488. visible(type, name) {
  1489. const key = type + ':' + name;
  1490. if (!this._inputCache.has(key)) {
  1491. this._inputCache.set(key, null);
  1492. const metadata = this.type(type);
  1493. if (metadata && Array.isArray(metadata.inputs) && metadata.inputs.length > 0) {
  1494. for (const input of metadata.inputs) {
  1495. this._inputCache.set(type + ':' + input.name, input);
  1496. }
  1497. }
  1498. }
  1499. const input = this._inputCache.get(key);
  1500. if (input) {
  1501. return input.visible === false ? false : true;
  1502. }
  1503. return true;
  1504. }
  1505. getInputs(type, inputs) {
  1506. const results = [];
  1507. const schema = this._map.get(type);
  1508. let index = 0;
  1509. while (index < inputs.length) {
  1510. const result = { arguments: [] };
  1511. let count = 1;
  1512. let name = null;
  1513. if (schema && schema.inputs) {
  1514. if (index < schema.inputs.length) {
  1515. const input = schema.inputs[index];
  1516. name = input.name;
  1517. if (schema.inputs[index].option == 'variadic') {
  1518. count = inputs.length - index;
  1519. }
  1520. }
  1521. }
  1522. else if (index == 0) {
  1523. name = 'input';
  1524. }
  1525. result.name = name ? name : '(' + index.toString() + ')';
  1526. const array = inputs.slice(index, index + count);
  1527. for (let j = 0; j < array.length; j++) {
  1528. result.arguments.push({ name: array[j] });
  1529. }
  1530. index += count;
  1531. results.push(result);
  1532. }
  1533. return results;
  1534. }
  1535. getOutputName(type, index) {
  1536. const schema = this._map.get(type);
  1537. if (schema) {
  1538. const outputs = schema.outputs;
  1539. if (outputs && index < outputs.length) {
  1540. const output = outputs[index];
  1541. if (output) {
  1542. const name = output.name;
  1543. if (name) {
  1544. return name;
  1545. }
  1546. }
  1547. }
  1548. }
  1549. if (index == 0) {
  1550. return 'output';
  1551. }
  1552. return '(' + index.toString() + ')';
  1553. }
  1554. };
  1555. coreml.Error = class extends Error {
  1556. constructor(message) {
  1557. super(message);
  1558. this.name = 'Error loading Core ML model.';
  1559. }
  1560. };
  1561. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  1562. module.exports.ModelFactory = coreml.ModelFactory;
  1563. }