caffe.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. var caffe = caffe || {};
  2. var protobuf = protobuf || require('./protobuf');
  3. caffe.ModelFactory = class {
  4. match(context) {
  5. const identifier = context.identifier;
  6. const extension = identifier.split('.').pop().toLowerCase();
  7. if (extension == 'caffemodel') {
  8. return 'caffe.pb';
  9. }
  10. if (identifier == 'saved_model.pbtxt' || identifier == 'saved_model.prototxt' ||
  11. identifier.endsWith('predict_net.pbtxt') || identifier.endsWith('predict_net.prototxt') ||
  12. identifier.endsWith('init_net.pbtxt') || identifier.endsWith('init_net.prototxt')) {
  13. return undefined;
  14. }
  15. const tags = context.tags('pbtxt');
  16. if (tags.has('layer') || tags.has('layers')) {
  17. return 'caffe.pbtxt';
  18. }
  19. if (tags.has('net') || tags.has('train_net') || tags.has('net_param')) {
  20. return 'caffe.pbtxt.solver';
  21. }
  22. return undefined;
  23. }
  24. open(context, match) {
  25. return context.require('./caffe-proto').then(() => {
  26. caffe.proto = protobuf.get('caffe').caffe;
  27. const openModel = (context, netParameter) => {
  28. return caffe.Metadata.open(context).then((metadata) => {
  29. return new caffe.Model(metadata, netParameter);
  30. });
  31. };
  32. const openNetParameterText = (context, identifier, buffer) => {
  33. let netParameter = null;
  34. try {
  35. const reader = protobuf.TextReader.open(buffer);
  36. reader.field = function(tag, message) {
  37. const type = message.constructor.name;
  38. if (tag.endsWith('_param') && (type == 'LayerParameter' || type == 'V1LayerParameter' || type == 'V0LayerParameter')) {
  39. message[tag] = caffe.ModelFactory._decodeText(reader);
  40. return;
  41. }
  42. else if (message.constructor.name.endsWith('Parameter') || message.constructor.name === 'ParamSpec') {
  43. if (message[tag]) {
  44. if (!Array.isArray(message[tag])) {
  45. message[tag] = [ message[tag] ];
  46. }
  47. message[tag].push(this.read());
  48. }
  49. else {
  50. message[tag] = this.read();
  51. }
  52. return;
  53. }
  54. throw new Error("Unknown field '" + tag + "'" + this.location());
  55. };
  56. reader.enum = function(type) {
  57. const token = this.token();
  58. this.next();
  59. this.semicolon();
  60. if (!Object.prototype.hasOwnProperty.call(type, token)) {
  61. const value = Number.parseInt(token, 10);
  62. if (!Number.isNaN(token - value)) {
  63. return value;
  64. }
  65. return token;
  66. }
  67. return type[token];
  68. };
  69. if (/MobileNetSSD_train_template.prototxt/.exec(identifier)) {
  70. reader.integer = function() {
  71. const token = this.token();
  72. const value = Number.parseInt(token, 10);
  73. this.next();
  74. this.semicolon();
  75. if (Number.isNaN(token - value)) {
  76. return token;
  77. }
  78. return value;
  79. };
  80. }
  81. netParameter = caffe.proto.NetParameter.decodeText(reader);
  82. }
  83. catch (error) {
  84. const message = error && error.message ? error.message : error.toString();
  85. throw new caffe.Error('File text format is not caffe.NetParameter (' + message.replace(/\.$/, '') + ').');
  86. }
  87. return openModel(context, netParameter);
  88. };
  89. switch (match) {
  90. case 'caffe.pbtxt.solver': {
  91. const stream = context.stream;
  92. const reader = protobuf.TextReader.open(stream);
  93. reader.field = function(tag, message) {
  94. if (message instanceof caffe.proto.SolverParameter) {
  95. message[tag] = this.read();
  96. return;
  97. }
  98. throw new Error("Unknown field '" + tag + "'" + this.location());
  99. };
  100. const solver = caffe.proto.SolverParameter.decodeText(reader);
  101. if (solver.net_param) {
  102. return openModel(context, solver.net_param);
  103. }
  104. let file = solver.net || solver.train_net;
  105. file = file.split('/').pop();
  106. return context.request(file, null).then((stream) => {
  107. const buffer = stream.peek();
  108. return openNetParameterText(context, file, buffer);
  109. }).catch((error) => {
  110. if (error) {
  111. const message = error && error.message ? error.message : error.toString();
  112. throw new caffe.Error("Failed to load '" + file + "' (" + message.replace(/\.$/, '') + ').');
  113. }
  114. });
  115. }
  116. case 'caffe.pbtxt': {
  117. return openNetParameterText(context, context.identifier, context.stream.peek());
  118. }
  119. case 'caffe.pb': {
  120. let netParameter = null;
  121. try {
  122. const stream = context.stream;
  123. const reader = protobuf.BinaryReader.open(stream);
  124. netParameter = caffe.proto.NetParameter.decode(reader);
  125. }
  126. catch (error) {
  127. const message = error && error.message ? error.message : error.toString();
  128. throw new caffe.Error('File format is not caffe.NetParameter (' + message.replace(/\.$/, '') + ').');
  129. }
  130. return openModel(context, netParameter);
  131. }
  132. default: {
  133. throw new caffe.Error("Unsupported Caffe format '" + match + "'.");
  134. }
  135. }
  136. });
  137. }
  138. static _decodeText(reader) {
  139. const message = {};
  140. reader.start();
  141. while (!reader.end()) {
  142. const tag = reader.tag();
  143. const value = reader.read();
  144. if (!message[tag]) {
  145. message[tag] = value;
  146. }
  147. else {
  148. if (!Array.isArray(message[tag])) {
  149. message[tag] = [ message[tag] ];
  150. }
  151. message[tag].push(value);
  152. }
  153. }
  154. return message;
  155. }
  156. };
  157. caffe.Model = class {
  158. constructor(metadata, net) {
  159. this._name = net.name;
  160. if (net.layers && net.layers.length > 0) {
  161. if (net.layers.every((layer) => Object.prototype.hasOwnProperty.call(layer, 'layer'))) {
  162. this._version = 0;
  163. net.layer = net.layers;
  164. }
  165. else {
  166. this._version = 1;
  167. net.layer = net.layers;
  168. }
  169. }
  170. else if (net.layer && net.layer.length > 0) {
  171. this._version = 2;
  172. }
  173. const phases = new Set();
  174. for (const layer of net.layer) {
  175. for (const include of layer.include) {
  176. if (include.phase !== undefined) {
  177. phases.add(include.phase);
  178. }
  179. }
  180. }
  181. if (phases.size === 0) {
  182. phases.add(-1);
  183. }
  184. this._graphs = [];
  185. for (const phase of phases) {
  186. const graph = new caffe.Graph(metadata, phase, net, this._version);
  187. this._graphs.push(graph);
  188. }
  189. }
  190. get format() {
  191. return 'Caffe' + (this._version ? ' v' + this._version.toString() : '');
  192. }
  193. get graphs() {
  194. return this._graphs;
  195. }
  196. };
  197. caffe.Graph = class {
  198. constructor(metadata, phase, net, version) {
  199. switch (phase) {
  200. case 0: this._phase = 'TRAIN'; break;
  201. case 1: this._phase = 'TEST'; break;
  202. case -1: this._phase = ''; break;
  203. default: this._phase = phase.toString(); break;
  204. }
  205. this._nodes = [];
  206. this._inputs = [];
  207. this._outputs = [];
  208. for (const layer of net.layer) {
  209. layer.input = layer.bottom.slice(0);
  210. layer.output = layer.top.slice(0);
  211. layer.chain = [];
  212. }
  213. const layers = [];
  214. for (const layer of net.layer) {
  215. if (phase === -1 || layer.include.every((include) => include.phase === phase)) {
  216. layers.push(layer);
  217. }
  218. }
  219. const scopes = new Map();
  220. let index = 0;
  221. for (const layer of layers) {
  222. layer.input = layer.input.map((input) => scopes.has(input) ? scopes.get(input) : input);
  223. layer.output = layer.output.map((output) => {
  224. const value = scopes.has(output) ? output + '\n' + index.toString() : output;
  225. scopes.set(output, value);
  226. return value;
  227. });
  228. index++;
  229. }
  230. // Graph Inputs
  231. const usedOutputs = new Set();
  232. for (const layer of layers) {
  233. for (const output of layer.output) {
  234. usedOutputs.add(output);
  235. }
  236. }
  237. const unusedInputs = [];
  238. for (const layer of layers) {
  239. for (const input of layer.input) {
  240. if (!usedOutputs.has(input)) {
  241. unusedInputs.push(input);
  242. }
  243. }
  244. }
  245. const nodes = [];
  246. let lastLayer = null;
  247. let lastTop = null;
  248. while (layers.length > 0) {
  249. let layer = layers.shift();
  250. if (layer.output.length == 1 && layer.input.length == 1 &&
  251. layer.output[0].split('\n').shift() == layer.input[0].split('\n').shift() &&
  252. lastLayer &&
  253. lastTop == layer.output[0].split('\n').shift()) {
  254. lastLayer.chain = lastLayer.chain || [];
  255. lastLayer.chain.push(layer);
  256. }
  257. else {
  258. if (layer.type == 'Input' || layer.type == 'Data') {
  259. if (layer.input.length == 0 && layer.output.length == 1 &&
  260. layer.input_param && layer.input_param.shape &&
  261. layer.input_param.shape.length == 1 && layer.input_param.shape[0].dim) {
  262. const shape = new caffe.TensorShape(layer.input_param.shape[0].dim.map((dim) => dim.toNumber()));
  263. const type = new caffe.TensorType(null, shape);
  264. this._inputs.push(new caffe.Parameter(layer.output[0], [ new caffe.Argument(layer.output[0], type) ]));
  265. layer = null;
  266. }
  267. }
  268. if (layer) {
  269. nodes.push(layer);
  270. lastLayer = null;
  271. lastTop = null;
  272. if (layer.output.length == 1) {
  273. lastLayer = layer;
  274. lastTop = layer.output[0].split('\n').shift();
  275. }
  276. }
  277. }
  278. }
  279. if (net.input) {
  280. for (let i = 0; i < net.input.length; i++) {
  281. const input = net.input[i];
  282. if (this._inputs.some((item) => item.name === input)) {
  283. continue;
  284. }
  285. let inputType = null;
  286. if (net.input_shape && i < net.input_shape.length) {
  287. const blobShape = net.input_shape[i];
  288. if (blobShape && blobShape.dim) {
  289. const shape = new caffe.TensorShape(blobShape.dim.map((dim) => dim.toNumber()));
  290. inputType = new caffe.TensorType(null, shape);
  291. }
  292. }
  293. const dim = i * 4;
  294. if (!inputType && net.input_dim && net.input_dim.length >= dim) {
  295. const shape = new caffe.TensorShape(net.input_dim.slice(dim, dim + 4));
  296. inputType = new caffe.TensorType(null, shape);
  297. }
  298. this._inputs.push(new caffe.Parameter(input, [ new caffe.Argument(input, inputType, null) ]));
  299. }
  300. }
  301. for (const layer of nodes) {
  302. const node = new caffe.Node(metadata, layer, version);
  303. if (layer.chain && layer.chain.length > 0) {
  304. for (const chain of layer.chain) {
  305. node.chain.push(new caffe.Node(metadata, chain, version));
  306. }
  307. }
  308. this._nodes.push(node);
  309. }
  310. if (this._inputs.length === 0 && unusedInputs.length === 1) {
  311. this._inputs.push(new caffe.Parameter(unusedInputs[0], [
  312. new caffe.Argument(unusedInputs[0], null)
  313. ]));
  314. }
  315. }
  316. get name() {
  317. return this._phase;
  318. }
  319. get type() {
  320. return '';
  321. }
  322. get inputs() {
  323. return this._inputs;
  324. }
  325. get outputs() {
  326. return this._outputs;
  327. }
  328. get nodes() {
  329. return this._nodes;
  330. }
  331. };
  332. caffe.Parameter = class {
  333. constructor(name, args) {
  334. this._name = name;
  335. this._arguments = args;
  336. }
  337. get name() {
  338. return this._name;
  339. }
  340. get visible() {
  341. return true;
  342. }
  343. get arguments() {
  344. return this._arguments;
  345. }
  346. };
  347. caffe.Argument = class {
  348. constructor(name, type, initializer) {
  349. if (typeof name !== 'string') {
  350. throw new caffe.Error("Invalid argument identifier '" + JSON.stringify(name) + "'.");
  351. }
  352. this._name = name;
  353. this._type = type || null;
  354. this._initializer = initializer || null;
  355. }
  356. get name() {
  357. return this._name;
  358. }
  359. get type() {
  360. return this._type;
  361. }
  362. get initializer() {
  363. return this._initializer;
  364. }
  365. };
  366. caffe.Node = class {
  367. constructor(metadata, layer, version) {
  368. this._chain = [];
  369. this._attributes = [];
  370. let type;
  371. switch (version) {
  372. case 0: {
  373. this._name = layer.layer.name;
  374. type = layer.layer.type;
  375. break;
  376. }
  377. case 1: {
  378. this._name = layer.name;
  379. type = caffe.Utility.layerType(layer.type);
  380. break;
  381. }
  382. case 2: {
  383. this._name = layer.name;
  384. type = layer.type;
  385. break;
  386. }
  387. default: {
  388. throw new new caffe.Error("Unsupported Caffe version '" + version + "'.");
  389. }
  390. }
  391. this._type = metadata.type(type) || { name: type };
  392. let initializers = [];
  393. switch (version) {
  394. case 0: {
  395. for (const name of Object.keys(layer.layer)) {
  396. if (name != 'type' && name != 'name' && name != 'blobs' && name != 'blobs_lr') {
  397. const value = layer.layer[name];
  398. const attribute = new caffe.Attribute(metadata.attribute(type, name), name, value);
  399. this._attributes.push(attribute);
  400. }
  401. }
  402. initializers = layer.layer.blobs.map((blob) => new caffe.Tensor(blob));
  403. break;
  404. }
  405. case 1:
  406. case 2: {
  407. for (const layer_kind of Object.keys(layer)) {
  408. if (layer_kind.endsWith('_param') || layer_kind == 'transform_param') {
  409. const param = layer[layer_kind];
  410. if (type == 'Deconvolution') {
  411. type = 'Convolution';
  412. }
  413. const prototype = Object.getPrototypeOf(param);
  414. for (const name of Object.keys(param)) {
  415. const defaultValue = prototype[name];
  416. const value = param[name];
  417. const attribute = new caffe.Attribute(metadata.attribute(type, name), name, value, defaultValue);
  418. this._attributes.push(attribute);
  419. }
  420. }
  421. }
  422. if (layer.include && layer.include.length > 0) {
  423. const attribute = new caffe.Attribute(metadata.attribute(type, 'include'), 'include', layer.include);
  424. this._attributes.push(attribute);
  425. }
  426. if (layer.exclude && layer.exclude.length > 0) {
  427. const attribute = new caffe.Attribute(metadata.attribute(type, 'exclude'), 'exclude', layer.exclude);
  428. this._attributes.push(attribute);
  429. }
  430. if (this._type == 'Data' && layer.input_param && layer.input_param.shape) {
  431. const attribute = new caffe.Attribute(metadata.attribute(type, 'shape'), 'shape', layer.input_param.shape);
  432. this._attributes.push(attribute);
  433. }
  434. initializers = layer.blobs.map((blob) => new caffe.Tensor(blob));
  435. break;
  436. }
  437. default: {
  438. throw new caffe.Error("Unsupported Caffe version '" + version + "'.");
  439. }
  440. }
  441. this._inputs = [];
  442. const inputs = layer.input.concat(initializers);
  443. let inputIndex = 0;
  444. if (this._type && this._type.inputs) {
  445. for (const inputDef of this._type.inputs) {
  446. if (inputIndex < inputs.length || inputDef.option != 'optional') {
  447. const inputCount = inputDef.option == 'variadic' ? inputs.length - inputIndex : 1;
  448. this._inputs.push(new caffe.Parameter(inputDef.name, inputs.slice(inputIndex, inputIndex + inputCount).filter((input) => input !== '' || inputDef.option != 'optional').map((input) => {
  449. return input instanceof caffe.Tensor ? new caffe.Argument('', input.type, input) : new caffe.Argument(input, null, null);
  450. })));
  451. inputIndex += inputCount;
  452. }
  453. }
  454. }
  455. this._inputs.push(...inputs.slice(inputIndex).map((input) => {
  456. return new caffe.Parameter(inputIndex.toString(), [
  457. input instanceof caffe.Tensor ? new caffe.Argument('', input.type, input) : new caffe.Argument(input, null, null)
  458. ]);
  459. }));
  460. this._outputs = [];
  461. const outputs = layer.output;
  462. let outputIndex = 0;
  463. if (this._type && this._type.outputs) {
  464. for (const outputDef of this._type.outputs) {
  465. if (outputIndex < outputs.length) {
  466. const outputCount = (outputDef.option == 'variadic') ? (outputs.length - outputIndex) : 1;
  467. this._outputs.push(new caffe.Parameter(outputDef.name, outputs.slice(outputIndex, outputIndex + outputCount).map((output) => {
  468. return new caffe.Argument(output, null, null);
  469. })));
  470. outputIndex += outputCount;
  471. }
  472. }
  473. }
  474. this._outputs.push(...outputs.slice(outputIndex).map((output, index) => {
  475. return new caffe.Parameter((outputIndex + index).toString(), [
  476. new caffe.Argument(output, null, null)
  477. ]);
  478. }));
  479. }
  480. get type() {
  481. return this._type;
  482. }
  483. get name() {
  484. return this._name;
  485. }
  486. get inputs() {
  487. return this._inputs;
  488. }
  489. get outputs() {
  490. return this._outputs;
  491. }
  492. get attributes() {
  493. return this._attributes;
  494. }
  495. get chain() {
  496. return this._chain;
  497. }
  498. };
  499. caffe.Attribute = class {
  500. constructor(metadata, name, value, defaultValue) {
  501. this._name = name;
  502. this._value = value;
  503. if (metadata && metadata.type) {
  504. this._type = metadata.type;
  505. }
  506. if (value instanceof caffe.proto.BlobShape) {
  507. this._value = new caffe.TensorShape(value.dim.map((dim) => dim.toNumber()));
  508. this._type = 'shape';
  509. }
  510. if (metadata && Object.prototype.hasOwnProperty.call(metadata, 'visible') && !metadata.visible) {
  511. this._visible = false;
  512. }
  513. if (metadata && Object.prototype.hasOwnProperty.call(metadata, 'default')) {
  514. defaultValue = metadata.default;
  515. }
  516. if (defaultValue !== undefined) {
  517. if (this._value == defaultValue) {
  518. this._visible = false;
  519. }
  520. else if (Array.isArray(this._value) && Array.isArray(defaultValue)) {
  521. if (this._value.length == defaultValue.length &&
  522. this._value.every((item, index) => { return item == defaultValue[index]; })) {
  523. this._visible = false;
  524. }
  525. }
  526. }
  527. if (this._type) {
  528. this._value = caffe.Utility.enum(this._type, this._value);
  529. }
  530. }
  531. get type() {
  532. return this._type;
  533. }
  534. get name() {
  535. return this._name;
  536. }
  537. get value() {
  538. return this._value;
  539. }
  540. get visible() {
  541. return this._visible == false ? false : true;
  542. }
  543. };
  544. caffe.Tensor = class {
  545. constructor(blob) {
  546. this._blob = blob;
  547. let shape = [];
  548. if (Object.prototype.hasOwnProperty.call(blob, 'num') &&
  549. Object.prototype.hasOwnProperty.call(blob, 'channels') &&
  550. Object.prototype.hasOwnProperty.call(blob, 'width') &&
  551. Object.prototype.hasOwnProperty.call(blob, 'height')) {
  552. if (blob.num != 1) {
  553. shape.push(blob.num);
  554. }
  555. if (blob.channels != 1) {
  556. shape.push(blob.channels);
  557. }
  558. if (blob.height != 1) {
  559. shape.push(blob.height);
  560. }
  561. if (blob.width != 1) {
  562. shape.push(blob.width);
  563. }
  564. }
  565. else if (Object.prototype.hasOwnProperty.call(blob, 'shape')) {
  566. shape = blob.shape.dim.map((dim) => dim.toNumber());
  567. }
  568. let dataType = '?';
  569. if (blob.data.length > 0) {
  570. dataType = 'float32';
  571. this._data = blob.data;
  572. }
  573. else if (blob.double_data.length > 0) {
  574. dataType = 'float64';
  575. this._data = blob.double_data;
  576. }
  577. this._type = new caffe.TensorType(dataType, new caffe.TensorShape(shape));
  578. }
  579. get kind() {
  580. return 'Blob';
  581. }
  582. get type() {
  583. return this._type;
  584. }
  585. get state() {
  586. return this._context().state;
  587. }
  588. get value() {
  589. const context = this._context();
  590. if (context.state) {
  591. return null;
  592. }
  593. context.limit = Number.MAX_SAFE_INTEGER;
  594. return this._decode(context, 0);
  595. }
  596. toString() {
  597. const context = this._context();
  598. if (context.state) {
  599. return '';
  600. }
  601. context.limit = 10000;
  602. const value = this._decode(context, 0);
  603. return JSON.stringify(value, null, 4);
  604. }
  605. _context() {
  606. const context = {};
  607. context.state = null;
  608. context.index = 0;
  609. context.count = 0;
  610. context.data = this._data;
  611. context.dimensions = this.type.shape.dimensions;
  612. if (!this._data) {
  613. context.state = 'Tensor data is empty.';
  614. }
  615. return context;
  616. }
  617. _decode(context, dimension) {
  618. const results = [];
  619. const size = context.dimensions[dimension];
  620. if (dimension == context.dimensions.length - 1) {
  621. for (let i = 0; i < size; i++) {
  622. if (context.count > context.limit) {
  623. results.push('...');
  624. return results;
  625. }
  626. results.push(context.data[context.index]);
  627. context.index++;
  628. context.count++;
  629. }
  630. }
  631. else {
  632. for (let j = 0; j < size; j++) {
  633. if (context.count > context.limit) {
  634. results.push('...');
  635. return results;
  636. }
  637. results.push(this._decode(context, dimension + 1));
  638. }
  639. }
  640. return results;
  641. }
  642. };
  643. caffe.TensorType = class {
  644. constructor(dataType, shape) {
  645. this._dataType = dataType;
  646. this._shape = shape;
  647. }
  648. get dataType() {
  649. return this._dataType;
  650. }
  651. get shape() {
  652. return this._shape;
  653. }
  654. toString() {
  655. return (this.dataType || '?') + this._shape.toString();
  656. }
  657. };
  658. caffe.TensorShape = class {
  659. constructor(dimensions) {
  660. this._dimensions = dimensions;
  661. }
  662. get dimensions() {
  663. return this._dimensions;
  664. }
  665. toString() {
  666. return this._dimensions ? ('[' + this._dimensions.map((dimension) => dimension.toString()).join(',') + ']') : '';
  667. }
  668. };
  669. caffe.Utility = class {
  670. static layerType(type) {
  671. type = type || 0;
  672. if (!caffe.Utility._layerTypeMap) {
  673. caffe.Utility._layerTypeMap = new Map();
  674. const known = { 'BNLL': 'BNLL', 'HDF5': 'HDF5', 'LRN': 'LRN', 'RELU': 'ReLU', 'TANH': 'TanH', 'ARGMAX': 'ArgMax', 'MVN': 'MVN', 'ABSVAL': 'AbsVal' };
  675. for (const key of Object.keys(caffe.proto.V1LayerParameter.LayerType)) {
  676. const value = caffe.proto.V1LayerParameter.LayerType[key];
  677. caffe.Utility._layerTypeMap.set(value, key.split('_').map((item) => known[item] || item.substring(0, 1) + item.substring(1).toLowerCase()).join(''));
  678. }
  679. }
  680. return caffe.Utility._layerTypeMap.has(type) ? caffe.Utility._layerTypeMap.get(type) : type.toString();
  681. }
  682. static enum(name, value) {
  683. let type = caffe.proto;
  684. const parts = name.split('.');
  685. while (type && parts.length > 0) {
  686. type = type[parts.shift()];
  687. }
  688. if (type) {
  689. caffe.Utility._enumKeyMap = caffe.Utility._enumKeyMap || new Map();
  690. if (!caffe.Utility._enumKeyMap.has(name)) {
  691. const map = new Map(Object.entries(type).map((pair) => [ pair[1], pair[0] ]));
  692. caffe.Utility._enumKeyMap.set(name, map);
  693. }
  694. const map = caffe.Utility._enumKeyMap.get(name);
  695. if (map.has(value)) {
  696. return map.get(value);
  697. }
  698. }
  699. return value;
  700. }
  701. };
  702. caffe.Metadata = class {
  703. static open(context) {
  704. if (caffe.Metadata._metadata) {
  705. return Promise.resolve(caffe.Metadata._metadata);
  706. }
  707. return context.request('caffe-metadata.json', 'utf-8', null).then((data) => {
  708. caffe.Metadata._metadata = new caffe.Metadata(data);
  709. return caffe.Metadata._metadata;
  710. }).catch(() => {
  711. caffe.Metadata._metadata = new caffe.Metadata(null);
  712. return caffe.Metadata._metadata;
  713. });
  714. }
  715. constructor(data) {
  716. this._map = new Map();
  717. this._attributeCache = new Map();
  718. if (data) {
  719. const metadata = JSON.parse(data);
  720. this._map = new Map(metadata.map((item) => [ item.name, item ]));
  721. }
  722. }
  723. type(name) {
  724. return this._map.get(name);
  725. }
  726. attribute(type, name) {
  727. const key = type + ':' + name;
  728. if (!this._attributeCache.has(key)) {
  729. this._attributeCache.set(key, null);
  730. const metadata = this.type(type);
  731. if (metadata && Array.isArray(metadata.attributes) && metadata.attributes.length > 0) {
  732. for (const attribute of metadata.attributes) {
  733. this._attributeCache.set(type + ':' + attribute.name, attribute);
  734. }
  735. }
  736. }
  737. return this._attributeCache.get(key);
  738. }
  739. };
  740. caffe.Error = class extends Error {
  741. constructor(message) {
  742. super(message);
  743. this.name = 'Error loading Caffe model.';
  744. }
  745. };
  746. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  747. module.exports.ModelFactory = caffe.ModelFactory;
  748. }