2
0

caffe.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  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 context.metadata('caffe-metadata.json').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) => {
  523. return item == defaultValue[index];
  524. })) {
  525. this._visible = false;
  526. }
  527. }
  528. }
  529. if (this._type) {
  530. this._value = caffe.Utility.enum(this._type, this._value);
  531. }
  532. }
  533. get type() {
  534. return this._type;
  535. }
  536. get name() {
  537. return this._name;
  538. }
  539. get value() {
  540. return this._value;
  541. }
  542. get visible() {
  543. return this._visible == false ? false : true;
  544. }
  545. };
  546. caffe.Tensor = class {
  547. constructor(blob) {
  548. this._blob = blob;
  549. let shape = [];
  550. if (Object.prototype.hasOwnProperty.call(blob, 'num') &&
  551. Object.prototype.hasOwnProperty.call(blob, 'channels') &&
  552. Object.prototype.hasOwnProperty.call(blob, 'width') &&
  553. Object.prototype.hasOwnProperty.call(blob, 'height')) {
  554. if (blob.num != 1) {
  555. shape.push(blob.num);
  556. }
  557. if (blob.channels != 1) {
  558. shape.push(blob.channels);
  559. }
  560. if (blob.height != 1) {
  561. shape.push(blob.height);
  562. }
  563. if (blob.width != 1) {
  564. shape.push(blob.width);
  565. }
  566. }
  567. else if (Object.prototype.hasOwnProperty.call(blob, 'shape')) {
  568. shape = blob.shape.dim.map((dim) => dim.toNumber());
  569. }
  570. let dataType = '?';
  571. if (blob.data.length > 0) {
  572. dataType = 'float32';
  573. this._data = blob.data;
  574. }
  575. else if (blob.double_data.length > 0) {
  576. dataType = 'float64';
  577. this._data = blob.double_data;
  578. }
  579. this._type = new caffe.TensorType(dataType, new caffe.TensorShape(shape));
  580. }
  581. get kind() {
  582. return 'Blob';
  583. }
  584. get type() {
  585. return this._type;
  586. }
  587. get state() {
  588. return this._context().state;
  589. }
  590. get value() {
  591. const context = this._context();
  592. if (context.state) {
  593. return null;
  594. }
  595. context.limit = Number.MAX_SAFE_INTEGER;
  596. return this._decode(context, 0);
  597. }
  598. toString() {
  599. const context = this._context();
  600. if (context.state) {
  601. return '';
  602. }
  603. context.limit = 10000;
  604. const value = this._decode(context, 0);
  605. return JSON.stringify(value, null, 4);
  606. }
  607. _context() {
  608. const context = {};
  609. context.state = null;
  610. context.index = 0;
  611. context.count = 0;
  612. context.data = this._data;
  613. context.dimensions = this.type.shape.dimensions;
  614. if (!this._data) {
  615. context.state = 'Tensor data is empty.';
  616. }
  617. return context;
  618. }
  619. _decode(context, dimension) {
  620. const results = [];
  621. const size = context.dimensions[dimension];
  622. if (dimension == context.dimensions.length - 1) {
  623. for (let i = 0; i < size; i++) {
  624. if (context.count > context.limit) {
  625. results.push('...');
  626. return results;
  627. }
  628. results.push(context.data[context.index]);
  629. context.index++;
  630. context.count++;
  631. }
  632. }
  633. else {
  634. for (let j = 0; j < size; j++) {
  635. if (context.count > context.limit) {
  636. results.push('...');
  637. return results;
  638. }
  639. results.push(this._decode(context, dimension + 1));
  640. }
  641. }
  642. return results;
  643. }
  644. };
  645. caffe.TensorType = class {
  646. constructor(dataType, shape) {
  647. this._dataType = dataType;
  648. this._shape = shape;
  649. }
  650. get dataType() {
  651. return this._dataType;
  652. }
  653. get shape() {
  654. return this._shape;
  655. }
  656. toString() {
  657. return (this.dataType || '?') + this._shape.toString();
  658. }
  659. };
  660. caffe.TensorShape = class {
  661. constructor(dimensions) {
  662. this._dimensions = dimensions;
  663. }
  664. get dimensions() {
  665. return this._dimensions;
  666. }
  667. toString() {
  668. return this._dimensions ? ('[' + this._dimensions.map((dimension) => dimension.toString()).join(',') + ']') : '';
  669. }
  670. };
  671. caffe.Utility = class {
  672. static layerType(type) {
  673. type = type || 0;
  674. if (!caffe.Utility._layerTypeMap) {
  675. caffe.Utility._layerTypeMap = new Map();
  676. const known = { 'BNLL': 'BNLL', 'HDF5': 'HDF5', 'LRN': 'LRN', 'RELU': 'ReLU', 'TANH': 'TanH', 'ARGMAX': 'ArgMax', 'MVN': 'MVN', 'ABSVAL': 'AbsVal' };
  677. for (const key of Object.keys(caffe.proto.V1LayerParameter.LayerType)) {
  678. const value = caffe.proto.V1LayerParameter.LayerType[key];
  679. caffe.Utility._layerTypeMap.set(value, key.split('_').map((item) => known[item] || item.substring(0, 1) + item.substring(1).toLowerCase()).join(''));
  680. }
  681. }
  682. return caffe.Utility._layerTypeMap.has(type) ? caffe.Utility._layerTypeMap.get(type) : type.toString();
  683. }
  684. static enum(name, value) {
  685. let type = caffe.proto;
  686. const parts = name.split('.');
  687. while (type && parts.length > 0) {
  688. type = type[parts.shift()];
  689. }
  690. if (type) {
  691. caffe.Utility._enumKeyMap = caffe.Utility._enumKeyMap || new Map();
  692. if (!caffe.Utility._enumKeyMap.has(name)) {
  693. const map = new Map(Object.entries(type).map((pair) => [ pair[1], pair[0] ]));
  694. caffe.Utility._enumKeyMap.set(name, map);
  695. }
  696. const map = caffe.Utility._enumKeyMap.get(name);
  697. if (map.has(value)) {
  698. return map.get(value);
  699. }
  700. }
  701. return value;
  702. }
  703. };
  704. caffe.Error = class extends Error {
  705. constructor(message) {
  706. super(message);
  707. this.name = 'Error loading Caffe model.';
  708. }
  709. };
  710. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  711. module.exports.ModelFactory = caffe.ModelFactory;
  712. }