tf.js 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508
  1. /* jshint esversion: 6 */
  2. // Experimental
  3. var tf = tf || {};
  4. var base = base || require('./base');
  5. var json = json || require('./json');
  6. var protobuf = protobuf || require('./protobuf');
  7. tf.ModelFactory = class {
  8. match(context) {
  9. return this._format(context).length > 0;
  10. }
  11. open(context) {
  12. return context.require('./tf-proto').then(() => {
  13. tf.proto = protobuf.get('tf');
  14. const openModel = (saved_model, format, producer, bundle) => {
  15. return tf.Metadata.open(context).then((metadata) => {
  16. return new tf.Model(metadata, saved_model, format, producer, bundle);
  17. });
  18. };
  19. const openSavedModel = (saved_model, format, producer) => {
  20. if (saved_model.meta_graphs.length === 1 &&
  21. saved_model.meta_graphs[0].object_graph_def &&
  22. saved_model.meta_graphs[0].object_graph_def.nodes &&
  23. saved_model.meta_graphs[0].object_graph_def.nodes.length > 0) {
  24. const identifier = 'variables/variables.index';
  25. return context.request(identifier, null).then((stream) => {
  26. return tf.TensorBundle.open(stream, identifier, context).then((bundle) => {
  27. return openModel(saved_model, format, producer, bundle);
  28. });
  29. }).catch(() => {
  30. return openModel(saved_model, format, producer, null);
  31. });
  32. }
  33. if (saved_model && saved_model.meta_graphs && saved_model.meta_graphs.length > 0 &&
  34. saved_model.meta_graphs[0].meta_info_def &&
  35. Object.prototype.hasOwnProperty.call(saved_model.meta_graphs[0].meta_info_def, 'tensorflow_version')) {
  36. producer = 'TensorFlow v' + saved_model.meta_graphs[0].meta_info_def.tensorflow_version;
  37. }
  38. return openModel(saved_model, format, producer, null);
  39. };
  40. const openBundle = (context, stream, identifier) => {
  41. return tf.TensorBundle.open(stream, identifier, context).then((bundle) => {
  42. return openModel(null, 'TensorFlow Tensor Bundle v' + bundle.format.toString(), null, bundle);
  43. }).catch((error) => {
  44. context.exception(error, false);
  45. const message = error && error.message ? error.message : error.toString();
  46. throw new tf.Error(message.replace(/\.$/, '') + " in '" + identifier + "'.");
  47. });
  48. };
  49. const openData = (context) => {
  50. const identifier = context.identifier;
  51. const base = identifier.split('.');
  52. base.pop();
  53. const file = base.join('.') + '.index';
  54. return context.request(file, null).then((stream) => {
  55. return open(stream, file, context);
  56. }).catch((/* error */) => {
  57. const file = base.join('.') + '.ckpt';
  58. return context.request(file, null).then((stream) => {
  59. open(stream, file, context);
  60. });
  61. });
  62. };
  63. const openEventFile = () => {
  64. let format = 'TensorFlow Event File';
  65. let producer = null;
  66. const stream = context.stream;
  67. const eventFileReader = tf.EventFileReader.open(stream);
  68. const saved_model = new tf.proto.tensorflow.SavedModel();
  69. for (;;) {
  70. const event = eventFileReader.read();
  71. if (!event) {
  72. break;
  73. }
  74. switch (event.what) {
  75. case 'file_version': {
  76. const formats = new Map([
  77. [ 'brain.Event:1', 'TensorFlow Event File v1' ],
  78. [ 'brain.Event:2', 'TensorFlow Event File v2' ]
  79. ]);
  80. if (!formats.has(event.file_version)) {
  81. throw new tf.Error("Unknown event file version '" + event.file_version + "'.");
  82. }
  83. format = formats.get(event.file_version);
  84. break;
  85. }
  86. case 'graph_def': {
  87. const buffer = event.graph_def;
  88. const reader = protobuf.BinaryReader.open(buffer);
  89. const graph_def = tf.proto.tensorflow.GraphDef.decode(reader);
  90. const meta_graph = new tf.proto.tensorflow.MetaGraphDef();
  91. meta_graph.meta_info_def = new tf.proto.tensorflow.MetaGraphDef.MetaInfoDef();
  92. meta_graph.meta_info_def.any_info = event.wall_time.toString();
  93. meta_graph.graph_def = graph_def;
  94. saved_model.meta_graphs.push(meta_graph);
  95. break;
  96. }
  97. }
  98. }
  99. if (saved_model.meta_graphs.every((meta_graph) => meta_graph.graph_def.node.every((node) => node.op.startsWith('aten::') || node.op.startsWith('prim::') || node.op === 'IO Node'))) {
  100. producer = 'PyTorch';
  101. return context.request('pytorch-metadata.json', 'utf-8', null).then((data) => {
  102. const metadata = new Map();
  103. for (const item of JSON.parse(data)) {
  104. const index = item.name.indexOf(':');
  105. const key = (index !== -1) ? item.name.substring(0, index) : item.name;
  106. const name = key.replace(/^torch\./, 'aten::');
  107. if (!metadata.has(name)) {
  108. metadata.set(name, []);
  109. }
  110. metadata.get(name).push(item);
  111. }
  112. for (const meta_graph of saved_model.meta_graphs) {
  113. for (const node of meta_graph.graph_def.node) {
  114. node.__metadata__ = Array.from(metadata.get(node.op) || []);
  115. }
  116. }
  117. return openModel(saved_model, format, producer, null);
  118. }).catch(() => {
  119. return openModel(saved_model, format, producer, null);
  120. });
  121. }
  122. return openSavedModel(saved_model, format, producer);
  123. };
  124. const openJson = (context) => {
  125. try {
  126. const obj = context.open('json');
  127. const format = 'TensorFlow.js ' + (obj.format || 'graph-model');
  128. const producer = obj.convertedBy || obj.generatedBy || '';
  129. const meta_graph = new tf.proto.tensorflow.MetaGraphDef();
  130. meta_graph.graph_def = tf.JsonReader.decodeGraphDef(obj.modelTopology);
  131. const saved_model = new tf.proto.tensorflow.SavedModel();
  132. saved_model.meta_graphs.push(meta_graph);
  133. const nodes = new Map();
  134. for (const node of meta_graph.graph_def.node) {
  135. node.input = node.input || [];
  136. if (node.op === 'Const') {
  137. nodes.set(node.name, node);
  138. }
  139. }
  140. const shards = new Map();
  141. const manifests = Array.isArray(obj.weightsManifest) ? obj.weightsManifest : [];
  142. for (const manifest of manifests) {
  143. for (const path of manifest.paths) {
  144. if (!shards.has(path)) {
  145. shards.set(path, context.request(path, null));
  146. }
  147. }
  148. }
  149. const openShards = (shards) => {
  150. const dtype_size_map = new Map([ [ 'float16', 2 ], [ 'float32', 4 ], [ 'float64', 8 ], [ 'int8', 1 ], [ 'int16', 2 ], [ 'int32', 4 ], [ 'int64', 8 ], [ 'uint8', 1 ], [ 'uint16', 2 ], [ 'uint32', 4 ], [ 'uint64', 8 ], [ 'bool', 1 ] ]);
  151. for (const manifest of manifests) {
  152. let buffer = null;
  153. if (Array.isArray(manifest.paths) && manifest.paths.length > 0 && manifest.paths.every((path) => shards.has(path))) {
  154. const list = manifest.paths.map((path) => shards.get(path));
  155. const size = list.reduce((a, b) => a + b.length, 0);
  156. buffer = new Uint8Array(size);
  157. let offset = 0;
  158. for (const item of list) {
  159. buffer.set(item, offset);
  160. offset += item.length;
  161. }
  162. }
  163. let offset = 0;
  164. for (const weight of manifest.weights) {
  165. const dtype = weight.quantization && weight.quantization.dtype ? weight.quantization.dtype : weight.dtype;
  166. if (!dtype_size_map.has(dtype)) {
  167. throw new tf.Error("Unknown weight data type size '" + dtype + "'.");
  168. }
  169. const itemsize = dtype_size_map.get(dtype);
  170. const size = weight.shape.reduce((a, b) => a * b, 1);
  171. const length = itemsize * size;
  172. const tensor_content = buffer ? buffer.slice(offset, offset + length) : null;
  173. offset += length;
  174. if (nodes.has(weight.name)) {
  175. const node = nodes.get(weight.name);
  176. node.attr.value.tensor.dtype = tf.Utility.dataTypeKey(dtype);
  177. node.attr.value.tensor.tensor_content = tensor_content;
  178. }
  179. }
  180. }
  181. return openSavedModel(saved_model, format, producer, null);
  182. };
  183. return Promise.all(shards.values()).then((streams) => {
  184. for (const key of shards.keys()) {
  185. shards.set(key, streams.shift().peek());
  186. }
  187. return openShards(shards);
  188. }).catch(() => {
  189. shards.clear();
  190. return openShards(shards);
  191. });
  192. }
  193. catch (error) {
  194. throw new tf.Error('File text format is not TensorFlow.js graph-model (' + error.message + ').');
  195. }
  196. };
  197. const openTextGraphDef = (context) => {
  198. try {
  199. const stream = context.stream;
  200. const reader = protobuf.TextReader.open(stream);
  201. const graph_def = tf.proto.tensorflow.GraphDef.decodeText(reader);
  202. const meta_graph = new tf.proto.tensorflow.MetaGraphDef();
  203. meta_graph.graph_def = graph_def;
  204. const saved_model = new tf.proto.tensorflow.SavedModel();
  205. saved_model.meta_graphs.push(meta_graph);
  206. const format = 'TensorFlow Graph';
  207. return openSavedModel(saved_model, format, null);
  208. }
  209. catch (error) {
  210. const message = error && error.message ? error.message : error.toString();
  211. throw new tf.Error('File text format is not tensorflow.GraphDef (' + message.replace(/\.$/, '') + ').');
  212. }
  213. };
  214. const openTextMetaGraphDef = (context) => {
  215. try {
  216. const stream = context.stream;
  217. const reader = protobuf.TextReader.open(stream);
  218. const meta_graph = tf.proto.tensorflow.MetaGraphDef.decodeText(reader);
  219. const saved_model = new tf.proto.tensorflow.SavedModel();
  220. saved_model.meta_graphs.push(meta_graph);
  221. const format = 'TensorFlow MetaGraph';
  222. return openSavedModel(saved_model, format, null);
  223. }
  224. catch (error) {
  225. throw new tf.Error('File text format is not tensorflow.MetaGraphDef (' + error.message + ').');
  226. }
  227. };
  228. const openTextSavedModel = (context) => {
  229. try {
  230. const stream = context.stream;
  231. const reader = protobuf.TextReader.open(stream);
  232. const saved_model = tf.proto.tensorflow.SavedModel.decodeText(reader);
  233. let format = 'TensorFlow Saved Model';
  234. if (saved_model && Object.prototype.hasOwnProperty.call(saved_model, 'saved_model_schema_version')) {
  235. format = format + ' v' + saved_model.saved_model_schema_version.toString();
  236. }
  237. return openSavedModel(saved_model, format, null);
  238. }
  239. catch (error) {
  240. throw new tf.Error('File text format is not tensorflow.SavedModel (' + error.message + ').');
  241. }
  242. };
  243. const openBinaryProto = (stream, identifier) => {
  244. let saved_model = null;
  245. let format = null;
  246. const extension = identifier.split('.').pop().toLowerCase();
  247. try {
  248. if (identifier.endsWith('saved_model.pb')) {
  249. const reader = protobuf.BinaryReader.open(stream);
  250. saved_model = tf.proto.tensorflow.SavedModel.decode(reader);
  251. format = 'TensorFlow Saved Model';
  252. if (saved_model && Object.prototype.hasOwnProperty.call(saved_model, 'saved_model_schema_version')) {
  253. format = format + ' v' + saved_model.saved_model_schema_version.toString();
  254. }
  255. }
  256. }
  257. catch (error) {
  258. const signature = [ 0x08, 0x01, 0x12 ];
  259. if (signature.length < stream.length && stream.peek(3).every((value, index) => value === signature[index])) {
  260. const message = error && error.message ? error.message : error.toString();
  261. throw new tf.Error('File format is not tensorflow.SavedModel (' + message.replace(/\.$/, '') + ').');
  262. }
  263. }
  264. try {
  265. if (!saved_model && extension == 'meta') {
  266. const reader = protobuf.BinaryReader.open(stream);
  267. const meta_graph = tf.proto.tensorflow.MetaGraphDef.decode(reader);
  268. saved_model = new tf.proto.tensorflow.SavedModel();
  269. saved_model.meta_graphs.push(meta_graph);
  270. format = 'TensorFlow MetaGraph';
  271. }
  272. }
  273. catch (error) {
  274. const message = error && error.message ? error.message : error.toString();
  275. throw new tf.Error('File format is not tensorflow.MetaGraphDef (' + message.replace(/\.$/, '') + ').');
  276. }
  277. try {
  278. if (!saved_model) {
  279. const reader = protobuf.BinaryReader.open(stream);
  280. const graph_def = tf.proto.tensorflow.GraphDef.decode(reader);
  281. const meta_graph = new tf.proto.tensorflow.MetaGraphDef();
  282. meta_graph.graph_def = graph_def;
  283. saved_model = new tf.proto.tensorflow.SavedModel();
  284. saved_model.meta_graphs.push(meta_graph);
  285. format = 'TensorFlow Graph';
  286. }
  287. }
  288. catch (error) {
  289. const message = error && error.message ? error.message : error.toString();
  290. throw new tf.Error('File format is not tensorflow.GraphDef (' + message.replace(/\.$/, '') + ').');
  291. }
  292. return openSavedModel(saved_model, format, null);
  293. };
  294. const openSavedMetadata = (context) => {
  295. /*
  296. const stream = context.stream;
  297. const reader = protobuf.BinaryReader.open(stream);
  298. const saved_metadata = tf.proto.third_party.tensorflow.python.keras.protobuf.SavedMetadata.decode(reader);
  299. debugger;
  300. */
  301. const identifier = 'saved_model.pb';
  302. return context.request(identifier, null).then((stream) => {
  303. return openBinaryProto(stream, identifier);
  304. });
  305. };
  306. switch (this._format(context)) {
  307. case 'tf.bundle':
  308. return openBundle(context, context.stream, context.identifier);
  309. case 'tf.data':
  310. return openData(context);
  311. case 'tf.events':
  312. return openEventFile(context);
  313. case 'tf.json':
  314. return openJson(context);
  315. case 'tf.pbtxt.GraphDef':
  316. return openTextGraphDef(context);
  317. case 'tf.pbtxt.MetaGraphDef':
  318. return openTextMetaGraphDef(context);
  319. case 'tf.pbtxt.SavedModel':
  320. return openTextSavedModel(context);
  321. case 'tf.pb':
  322. return openBinaryProto(context.stream, context.identifier);
  323. case 'tf.pb.keras.SavedMetadata':
  324. return openSavedMetadata(context);
  325. default:
  326. throw new tf.Error('Unknown format.');
  327. }
  328. });
  329. }
  330. _format(context) {
  331. const identifier = context.identifier;
  332. const extension = identifier.split('.').pop().toLowerCase();
  333. if (extension === 'meta') {
  334. const tags = context.tags('pb');
  335. if (tags.size !== 0) {
  336. return 'tf.pb';
  337. }
  338. }
  339. if (extension === 'pbtxt' || extension === 'prototxt' || extension === 'pt') {
  340. if (identifier.endsWith('predict_net.pbtxt') || identifier.endsWith('predict_net.prototxt') ||
  341. identifier.endsWith('init_net.pbtxt') || identifier.endsWith('init_net.prototxt')) {
  342. return '';
  343. }
  344. const tags = context.tags('pbtxt');
  345. if (['input_stream', 'output_stream', 'input_side_packet', 'output_side_packet'].some((key) => tags.has(key) || tags.has('node.' + key))) {
  346. return '';
  347. }
  348. if (tags.has('saved_model_schema_version') || tags.has('meta_graphs')) {
  349. return 'tf.pbtxt.SavedModel';
  350. }
  351. if (tags.has('graph_def')) {
  352. return 'tf.pbtxt.MetaGraphDef';
  353. }
  354. if (tags.has('node')) {
  355. return 'tf.pbtxt.GraphDef';
  356. }
  357. }
  358. if (extension === 'pb' || extension === 'pbtxt' || extension === 'prototxt' || extension === 'graphdef') {
  359. if (identifier.endsWith('predict_net.pb') || identifier.endsWith('init_net.pb')) {
  360. return '';
  361. }
  362. if (identifier == 'tfhub_module.pb') {
  363. const stream = context.stream;
  364. const signature = [ 0x08, 0x03 ];
  365. if (signature.length === stream.length && stream.peek(signature.length).every((value, index) => value === signature[index])) {
  366. return '';
  367. }
  368. }
  369. const tags = context.tags('pb');
  370. if (tags.size > 0) {
  371. if (!Array.from(tags).some((pair) => pair[0] >= 5 || pair[1] === 5)) {
  372. if (tags.size === 1 && tags.get(1) === 2) {
  373. const tags = context.tags('pb+');
  374. const match = (tags, schema) => {
  375. for (const pair of schema) {
  376. const key = pair[0];
  377. const inner = pair[1];
  378. if (!tags.has(key)) {
  379. continue;
  380. }
  381. else if (inner === false) {
  382. return false;
  383. }
  384. if (Array.isArray(inner)) {
  385. const value = tags.get(key);
  386. if (!(value instanceof Map) || !match(value, inner)) {
  387. return false;
  388. }
  389. }
  390. else if (inner !== tags.get(key)) {
  391. return false;
  392. }
  393. }
  394. return true;
  395. };
  396. // mediapipe.BoxDetectorIndex
  397. if (match(tags, [[1,[[1,[[1,[[1,5],[2,5],[3,5],[4,5],[6,0],[7,5],[8,5],[10,5],[11,0],[12,0]]],[2,5],[3,[]]]],[2,false],[3,false],[4,false],[5,false]]],[2,false],[3,false]] )) {
  398. return '';
  399. }
  400. // third_party.tensorflow.python.keras.protobuf.SavedMetadata
  401. if (match(tags, [[1,[[1,[[1,0],[2,0]]],[2,0],[3,2],[4,2],[5,2]]]])) {
  402. return 'tf.pb.keras.SavedMetadata';
  403. }
  404. }
  405. if (tags.get(1) !== 2) {
  406. return 'tf.pb';
  407. }
  408. const decode = (buffer, value) => {
  409. const reader = protobuf.BinaryReader.open(buffer);
  410. const length = reader.length;
  411. while (reader.position < length) {
  412. const tag = reader.uint32();
  413. const number = tag >>> 3;
  414. const type = tag & 7;
  415. if (value === number) {
  416. return type === 2 ? reader.bytes() : null;
  417. }
  418. else {
  419. reader.skipType(type);
  420. }
  421. }
  422. return null;
  423. };
  424. const stream = context.stream;
  425. const buffer = stream.peek();
  426. const nodeBuffer = decode(buffer, 1);
  427. if (nodeBuffer) {
  428. const nameBuffer = decode(nodeBuffer, 1);
  429. if (nameBuffer) {
  430. const decoder = new TextDecoder('utf-8');
  431. const name = decoder.decode(nameBuffer);
  432. if (Array.from(name).filter((c) => c <= ' ').length < 256) {
  433. return 'tf.pb';
  434. }
  435. }
  436. }
  437. }
  438. }
  439. else {
  440. const tags = context.tags('pbtxt');
  441. if (['input_stream', 'output_stream', 'input_side_packet', 'output_side_packet'].some((key) => tags.has(key) || tags.has('node.' + key))) {
  442. return false;
  443. }
  444. if (tags.has('node')) {
  445. return 'tf.pbtxt.GraphDef';
  446. }
  447. if (tags.has('graph_def')) {
  448. return 'tf.pbtxt.MetaGraphDef';
  449. }
  450. if (tags.has('saved_model_schema_version') || tags.has('meta_graphs')) {
  451. return 'tf.pbtxt.SavedModel';
  452. }
  453. }
  454. }
  455. if (extension === 'json') {
  456. const obj = context.open('json');
  457. if (obj && obj.modelTopology && (obj.format === 'graph-model' || Array.isArray(obj.modelTopology.node))) {
  458. return 'tf.json';
  459. }
  460. }
  461. if (extension === 'index' || extension === 'ckpt') {
  462. const stream = context.stream;
  463. if (stream.length > 8) {
  464. stream.seek(-8);
  465. const buffer = stream.read(8);
  466. stream.seek(0);
  467. const signature = [ 0x57, 0xfb, 0x80, 0x8b, 0x24, 0x75, 0x47, 0xdb ];
  468. if (buffer.every((value, index) => value === signature[index])) {
  469. return 'tf.bundle';
  470. }
  471. }
  472. }
  473. if (/.data-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9]$/.exec(identifier)) {
  474. return 'tf.data';
  475. }
  476. if (/^events.out.tfevents./.exec(identifier)) {
  477. const stream = context.stream;
  478. if (tf.EventFileReader.open(stream)) {
  479. return 'tf.events';
  480. }
  481. }
  482. return '';
  483. }
  484. };
  485. tf.Model = class {
  486. constructor(metadata, model, format, producer, bundle) {
  487. this._format = format;
  488. this._producer = producer || '';
  489. this._graphs = [];
  490. if (model) {
  491. for (let i = 0; i < model.meta_graphs.length; i++) {
  492. const meta_graph = model.meta_graphs[i];
  493. const name = (meta_graph.meta_info_def && meta_graph.meta_info_def.any_info) ? meta_graph.meta_info_def.any_info.toString() : ((model.meta_graphs.length > 1) ? i.toString() : '-');
  494. const graph = new tf.Graph(metadata, meta_graph, name, bundle);
  495. this._graphs.push(graph);
  496. }
  497. }
  498. else {
  499. this._graphs.push(new tf.Graph(metadata, null, '', bundle));
  500. }
  501. }
  502. get format() {
  503. return this._format;
  504. }
  505. get producer() {
  506. return this._producer;
  507. }
  508. get description() {
  509. return null;
  510. }
  511. get graphs() {
  512. return this._graphs;
  513. }
  514. };
  515. tf.Graph = class {
  516. constructor(metadata, meta_graph, name, bundle) {
  517. this._version = null;
  518. this._name = name;
  519. this._inputs = [];
  520. this._outputs = [];
  521. this._nodes = [];
  522. if (meta_graph && meta_graph.graph_def) {
  523. const graph = meta_graph.graph_def;
  524. if (graph.versions) {
  525. this._version = 'v' + graph.versions.producer.toString();
  526. }
  527. else if (graph.version) {
  528. this._version = graph.version;
  529. }
  530. else if (meta_graph.meta_info_def && meta_graph.meta_info_def.tensorflow_version) {
  531. this._version = meta_graph.meta_info_def.tensorflow_version;
  532. }
  533. if (meta_graph.meta_info_def && meta_graph.meta_info_def.tags) {
  534. this._tags = meta_graph.meta_info_def.tags.join(', ');
  535. }
  536. metadata = new tf.GraphMetadata(metadata, graph.library);
  537. const nodes = graph.node;
  538. if (nodes) {
  539. const node_map = new Map();
  540. const namespaces = new Set();
  541. for (const node of nodes) {
  542. const nodeName = node.name;
  543. node_map.set(nodeName, node);
  544. if (node.op != 'Const') {
  545. const index = nodeName.lastIndexOf('/');
  546. if (index != -1) {
  547. const namespace = nodeName.substring(0, index);
  548. namespaces.add(namespace);
  549. }
  550. }
  551. node.output = [];
  552. }
  553. for (const node of nodes) {
  554. const inputs = node.input;
  555. node.input = [];
  556. node.controlDependencies = [];
  557. for (const input of inputs) {
  558. const split = input.split(':', 2);
  559. const input_name = split[0];
  560. const input_index = split.length == 1 ? 0 : parseInt(split[1]);
  561. const from_name = input_name.startsWith('^') ? input_name.substring(1) : input_name;
  562. const from = node_map.get(from_name);
  563. const output_name = input_index == 0 ? from_name : from_name + ':' + input_index.toString();
  564. const input_arg = from ? { name: output_name, from: from } : { name: output_name };
  565. if (input_name.startsWith('^')) {
  566. node.controlDependencies.push(input_arg);
  567. }
  568. else {
  569. node.input.push(input_arg);
  570. }
  571. if (from) {
  572. for (let i = from.output.length; i <= input_index; i++) {
  573. from.output.push({ name: i === 0 ? from_name : from_name + ':' + i.toString(), to: [] });
  574. }
  575. from.output[input_index].to.push(node);
  576. }
  577. }
  578. }
  579. const initializers = new Map();
  580. const map_tensor = (name, node, kind) => {
  581. if (node && node.op === 'Const' && node.input.length === 0 && node.output.length === 1 && node.output[0].to.length === 1 && node.controlDependencies.length === 0) {
  582. const value = node.attr.value;
  583. if (value && Object.prototype.hasOwnProperty.call(value, 'tensor')) {
  584. const tensor = new tf.Tensor(value.tensor, name, kind);
  585. return new tf.Argument(name, tensor.type, tensor);
  586. }
  587. }
  588. return null;
  589. };
  590. const map_resource = (name, node, tensor) => {
  591. if (node.op === 'Placeholder' && node.input.length === 0 && node.output.length === 1 && node.output[0].to.length === 1 && node.controlDependencies.length === 0) {
  592. const dtype = node.attr.dtype.type;
  593. if (dtype === tf.proto.tensorflow.DataType.DT_RESOURCE) {
  594. return new tf.Argument(name, null, tensor);
  595. }
  596. }
  597. return null;
  598. };
  599. for (const node of node_map.values()) {
  600. if (node.op === 'Identity' && node.input.length === 1 && node.output.length === 1 && node.output[0].to.length === 1 && node.controlDependencies.length === 0) {
  601. const initializer = map_tensor(node.name, node.input[0].from, 'Identity Constant');
  602. if (initializer) {
  603. initializers.set(initializer.name, initializer);
  604. node_map.delete(initializer.name);
  605. node_map.delete(node.input[0].name);
  606. }
  607. const identity = node.input[0].from;
  608. if (identity && identity.op === 'Identity' && identity.input.length === 1 && identity.output.length === 1 && node.output[0].to.length === 1 && node.controlDependencies.length === 0) {
  609. const initializer = map_tensor(node.name, identity.input[0].from, 'Identity Constant');
  610. if (initializer) {
  611. initializers.set(initializer.name, initializer);
  612. node_map.delete(initializer.name);
  613. node_map.delete(initializer.name);
  614. node_map.delete(identity.name);
  615. node_map.delete(node.name);
  616. }
  617. }
  618. }
  619. }
  620. for (const node of node_map.values()) {
  621. const initializer = map_tensor(node.name, node, 'Const');
  622. if (initializer) {
  623. initializers.set(initializer.name, initializer);
  624. node_map.delete(node.name);
  625. node_map.delete(initializer.name);
  626. }
  627. }
  628. for (const node of node_map.values()) {
  629. if (node.op === 'ReadVariableOp' && node.input.length === 1 && node.output.length === 1 && node.output[0].to.length === 1 && node.controlDependencies.length === 0) {
  630. if (node.attr && node.attr.dtype && node.attr._output_shapes && node.attr._output_shapes.list && node.attr._output_shapes.list.shape) {
  631. const tensor = new tf.proto.tensorflow.TensorProto();
  632. tensor.dtype = node.attr.dtype.type;
  633. tensor.tensor_shape = node.attr._output_shapes.list.shape[0];
  634. const initializer = map_resource(node.name, node.input[0].from, new tf.Tensor(tensor, name, 'Resource Variable'));
  635. if (initializer) {
  636. initializers.set(initializer.name, initializer);
  637. node_map.delete(initializer.name);
  638. node_map.delete(node.input[0].name);
  639. }
  640. }
  641. }
  642. }
  643. const input_map = new Map();
  644. for (const node of node_map.values()) {
  645. if (node.op == 'Placeholder' && node.input.length === 0 && node.output.length === 1 && node.output[0].to.length === 1 && node.controlDependencies.length === 0) {
  646. const dtype = node.attr.dtype;
  647. const shape = node.attr.shape;
  648. if (dtype && dtype.type && shape && shape.shape) {
  649. const name = node.name;
  650. const type = new tf.TensorType(dtype.type, shape.shape);
  651. const argument = new tf.Argument(name, type, null);
  652. input_map.set(name, new tf.Parameter(name, [ argument ]));
  653. node_map.delete(name);
  654. }
  655. }
  656. }
  657. const updatePyTorch = (node_map) => {
  658. for (const node of node_map.values()) {
  659. if (node.op === 'prim::Constant' && node.input.length === 0 && node.controlDependencies.length === 0 && node.attr && Object.keys(node.attr).length === 1 && node.attr.attr && node.attr.attr.s) {
  660. const value = tf.Utility.decodeText(node.attr.attr.s);
  661. const match = /{\s*value\s*:\s*(.*)\s*}/.exec(value);
  662. if (match) {
  663. node.value = match[1].trim();
  664. }
  665. const empty = /{\s*}/.exec(value);
  666. if (empty) {
  667. node.value = null;
  668. }
  669. }
  670. if (node.op === 'prim::GetAttr' && node.input.length === 1 && node.controlDependencies.length === 0 && node.attr && Object.keys(node.attr).length === 1 && node.attr.attr && node.attr.attr.s) {
  671. const value = tf.Utility.decodeText(node.attr.attr.s);
  672. const match = /{\s*name\s*:\s*([A-za-z0-9_]*)\s*}/.exec(value);
  673. if (match) {
  674. node.value = match[1].trim();
  675. }
  676. }
  677. if (node.op === 'IO Node' && node.controlDependencies.length === 0) {
  678. const shape = node.attr && node.attr._output_shapes && node.attr._output_shapes.list && node.attr._output_shapes.list.shape ? node.attr._output_shapes.list.shape[0] : null;
  679. const type = shape ? new tf.TensorType('?', shape) : null;
  680. if (node.input.length === 0 && node.output.length === 1) {
  681. this._inputs.push(new tf.Parameter(node.name, [
  682. new tf.Argument(node.output[0].name, type, null)
  683. ]));
  684. node_map.delete(node.name);
  685. }
  686. if (node.input.length === 1 && node.output.length === 0) {
  687. this._outputs.push(new tf.Parameter(node.name, [
  688. new tf.Argument(node.input[0].name, type, null)
  689. ]));
  690. node_map.delete(node.name);
  691. }
  692. }
  693. if (Object.keys(node.attr).length === 2 &&
  694. node.attr.attr && node.attr.attr.s && node.attr._output_shapes) {
  695. const value = tf.Utility.decodeText(node.attr.attr.s);
  696. if (/\s*/.exec(value) || /{\s*}/.exec(value)) {
  697. node.attr = {};
  698. delete node._output_shapes;
  699. }
  700. }
  701. }
  702. const remove_input = (input, node) => {
  703. const from = input.from;
  704. if (from) {
  705. for (const output of from.output) {
  706. output.to = output.to.filter((to) => to !== node);
  707. }
  708. if (from.output.every((output) => output.to.length === 0) && from.controlDependencies.length === 0) {
  709. from.remove = true;
  710. }
  711. delete input.from;
  712. }
  713. };
  714. for (const node of node_map.values()) {
  715. if (node.op === 'prim::ListConstruct' && node.input.every((input) => input.from.value !== undefined) && node.controlDependencies.length === 0) {
  716. node.value = node.input.map((input) => input.from.value);
  717. for (const input of node.input) {
  718. remove_input(input, node);
  719. }
  720. node.input = [];
  721. }
  722. }
  723. for (const node of node_map.values()) {
  724. const remove = new Set();
  725. for (let i = 0; i < node.input.length; i++) {
  726. const input = node.input[i];
  727. const from = input.from;
  728. if (from) {
  729. if (from.op === 'prim::GetAttr' && from.input.length === 1 && from.output.length === 1 && from.controlDependencies.length === 0 && from.value !== undefined) {
  730. remove_input(input, node);
  731. input.label = from.value;
  732. const tensor = new tf.Tensor(null, input.name, from.op);
  733. const argument = new tf.Argument(input.name, null, tensor);
  734. initializers.set(input.name, argument);
  735. }
  736. if (from.op === 'prim::Constant' && from.input.length === 0 && from.controlDependencies.length === 0 && from.value !== undefined) {
  737. input.constant = from.value;
  738. remove_input(input, node);
  739. remove.add(input.name);
  740. }
  741. if (from.op === 'prim::ListConstruct' && from.output.length === 1 && from.controlDependencies.length === 0 && from.value !== undefined) {
  742. input.list = from.value;
  743. remove_input(input, node);
  744. remove.add(input.name);
  745. }
  746. }
  747. }
  748. if (node.__metadata__) {
  749. for (const metadata of node.__metadata__) {
  750. const parameters = Array.prototype.slice.call(metadata.inputs || []).concat(Array.prototype.slice.call(metadata.attributes || []));
  751. let match = true;
  752. const inputs = Array.from(node.input);
  753. if (inputs.length > parameters.length) {
  754. match = false;
  755. }
  756. while (inputs.length > 0 && match) {
  757. match = false;
  758. const input = inputs.shift();
  759. delete input.metadata;
  760. const parameter = parameters.shift();
  761. switch (parameter.type) {
  762. case 'Tensor': {
  763. if ((input.constant === undefined && input.list === undefined) || input.constant === null) {
  764. input.metadata = parameter;
  765. match = true;
  766. }
  767. else {
  768. inputs.unshift(input);
  769. match = true;
  770. }
  771. break;
  772. }
  773. case 'int64': {
  774. const value = parseInt(input.constant);
  775. if (input.constant !== undefined && Number.isInteger(value)) {
  776. input.attr = new tf.proto.tensorflow.AttrValue();
  777. input.attr.i = value;
  778. input.attr.metadata = parameter;
  779. match = true;
  780. }
  781. break;
  782. }
  783. case 'float32': {
  784. const value = parseFloat(input.constant);
  785. if (input.constant !== undefined && !isNaN(value)) {
  786. input.attr = new tf.proto.tensorflow.AttrValue();
  787. input.attr.f = value;
  788. input.attr.metadata = parameter;
  789. match = true;
  790. }
  791. break;
  792. }
  793. case 'int64[]': {
  794. if (Array.isArray(input.list)) {
  795. const list = input.list.map((item) => parseInt(item));
  796. if (list.every((value) => Number.isInteger(value))) {
  797. input.attr = new tf.proto.tensorflow.AttrValue();
  798. input.attr.list = new tf.proto.tensorflow.ListValue();
  799. input.attr.list.i = list;
  800. input.attr.metadata = parameter;
  801. match = true;
  802. }
  803. }
  804. break;
  805. }
  806. case 'boolean': {
  807. if (input.constant === 'false' || input.constant === '0') {
  808. input.attr = new tf.proto.tensorflow.AttrValue();
  809. input.attr.b = false;
  810. input.attr.metadata = parameter;
  811. match = true;
  812. }
  813. else if (input.constant === 'true' || input.constant === '1') {
  814. input.attr = new tf.proto.tensorflow.AttrValue();
  815. input.attr.b = true;
  816. input.attr.metadata = parameter;
  817. match = true;
  818. }
  819. break;
  820. }
  821. case 'Scalar': {
  822. const value = parseInt(input.constant);
  823. if (input.constant !== undefined && Number.isInteger(value)) {
  824. input.attr = new tf.proto.tensorflow.AttrValue();
  825. input.attr.i = value;
  826. input.attr.metadata = parameter;
  827. match = true;
  828. }
  829. break;
  830. }
  831. default:
  832. break;
  833. }
  834. }
  835. if (match) {
  836. node.metadata = metadata;
  837. break;
  838. }
  839. else {
  840. for (const input of node.input) {
  841. delete input.metadata;
  842. delete input.attr;
  843. }
  844. }
  845. }
  846. }
  847. node.input = node.input.filter((input, index) => {
  848. if (input.attr) {
  849. const name = input.attr.metadata ? input.attr.metadata.name : index.toString();
  850. node.attr[name] = input.attr;
  851. }
  852. else if (input.constant !== undefined && input.constant !== null) {
  853. const attr = new tf.proto.tensorflow.AttrValue();
  854. attr.s = input.constant;
  855. node.attr[index.toString()] = attr;
  856. }
  857. else if (input.list !== undefined) {
  858. const attr = new tf.proto.tensorflow.AttrValue();
  859. attr.list = new tf.proto.tensorflow.ListValue();
  860. attr.list.s = input.list;
  861. node.attr[index.toString()] = attr;
  862. }
  863. return !remove.has(input.name);
  864. });
  865. }
  866. for (const node of node_map.values()) {
  867. if (node.op === 'prim::GetAttr' && node.remove) {
  868. node_map.delete(node.name);
  869. }
  870. if (node.op === 'prim::Constant' && node.remove) {
  871. node_map.delete(node.name);
  872. }
  873. if (node.op === 'prim::ListConstruct' && node.remove) {
  874. node_map.delete(node.name);
  875. }
  876. }
  877. };
  878. updatePyTorch(node_map);
  879. for (const input of input_map.values()) {
  880. this._inputs.push(input);
  881. }
  882. for (const node of node_map.values()) {
  883. this._nodes.push(new tf.Node(metadata, namespaces, node, node.op, node.name, initializers, null));
  884. }
  885. }
  886. }
  887. else if (bundle) {
  888. const nodeNames = [];
  889. const nodeMap = new Map();
  890. for (const tensor of bundle.tensors) {
  891. const parts = tensor.name.split('/');
  892. if (bundle.format === 2) {
  893. if (tensor.name === '_CHECKPOINTABLE_OBJECT_GRAPH' ||
  894. tensor.name.startsWith('optimizer/') ||
  895. tensor.name.startsWith('keras_api/metrics/') ||
  896. tensor.name.endsWith('/ExponentialMovingAverage') ||
  897. tensor.name.indexOf('.OPTIMIZER_SLOT') !== -1) {
  898. continue;
  899. }
  900. if (tensor.name.endsWith('/.ATTRIBUTES/VARIABLE_VALUE')) {
  901. parts.pop();
  902. parts.pop();
  903. }
  904. }
  905. const tensorName = parts.pop();
  906. const nodeName = parts.join('/');
  907. if (!nodeMap.has(nodeName)) {
  908. nodeNames.push(nodeName);
  909. nodeMap.set(nodeName, []);
  910. }
  911. nodeMap.get(nodeName).push({ name: tensorName, value: tensor });
  912. }
  913. const namespaces = new Set();
  914. for (const name of nodeNames) {
  915. this._nodes.push(new tf.Node(metadata, namespaces, null, 'Node', name, null, nodeMap.get(name)));
  916. }
  917. }
  918. }
  919. get name() {
  920. return this._name;
  921. }
  922. get version() {
  923. return this._version;
  924. }
  925. get tags() {
  926. return this._tags;
  927. }
  928. get groups() {
  929. return false;
  930. // TODO return true;
  931. }
  932. get inputs() {
  933. return this._inputs;
  934. }
  935. get outputs() {
  936. return this._outputs;
  937. }
  938. get nodes() {
  939. return this._nodes;
  940. }
  941. get metadata() {
  942. return this._metadata;
  943. }
  944. };
  945. tf.Parameter = class {
  946. constructor(name, args) {
  947. this._name = name;
  948. this._arguments = args;
  949. }
  950. get name() {
  951. return this._name;
  952. }
  953. get visible() {
  954. return true;
  955. }
  956. get arguments() {
  957. return this._arguments;
  958. }
  959. };
  960. tf.Argument = class {
  961. constructor(name, type, initializer) {
  962. if (typeof name !== 'string') {
  963. throw new tf.Error("Invalid argument identifier '" + JSON.stringify(name) + "'.");
  964. }
  965. this._name = name;
  966. this._type = type || null;
  967. this._initializer = initializer || null;
  968. }
  969. get name() {
  970. return this._name;
  971. }
  972. get type() {
  973. if (this._initializer) {
  974. return this._initializer.type;
  975. }
  976. return this._type;
  977. }
  978. get initializer() {
  979. return this._initializer;
  980. }
  981. };
  982. tf.Function = class {
  983. constructor(metadata, func) {
  984. this._name = func.signature.name;
  985. this._version = null;
  986. this._tags = null;
  987. this._inputs = [];
  988. this._outputs = [];
  989. this._nodes = [];
  990. const input_arg = func.signature.input_arg;
  991. const output_arg = func.signature.output_arg;
  992. const ret = func.ret;
  993. if (input_arg) {
  994. for (const input of input_arg) {
  995. const argument = new tf.Argument(input.name, new tf.TensorType(input.type, null), null);
  996. this._inputs.push(new tf.Parameter(input.name, [ argument ]));
  997. }
  998. }
  999. const output_arg_map = new Map();
  1000. if (output_arg) {
  1001. const ret_map = new Map();
  1002. for (const key of Object.keys(ret)) {
  1003. const value = func.ret[key];
  1004. const split = value.split(':', 2);
  1005. ret_map.set(key, split[0]);
  1006. }
  1007. for (const output of output_arg) {
  1008. const name = ret_map.get(output.name);
  1009. this._outputs.push(new tf.Parameter(output.name, [
  1010. new tf.Argument(name, new tf.TensorType(output.type, null), null)
  1011. ]));
  1012. output_arg_map.set(name, output.name);
  1013. }
  1014. }
  1015. const namespaces = new Set();
  1016. const nodes = func.node_def;
  1017. if (nodes) {
  1018. const node_map = new Map();
  1019. for (const node of nodes) {
  1020. const nodeName = node.name;
  1021. node_map.set(nodeName, node);
  1022. if (node.op != 'Const') {
  1023. const lastIndex = nodeName.lastIndexOf('/');
  1024. if (lastIndex != -1) {
  1025. const namespace = nodeName.substring(0, lastIndex);
  1026. namespaces.add(namespace);
  1027. }
  1028. }
  1029. node.output = [];
  1030. }
  1031. for (const node of nodes) {
  1032. const inputs = node.input;
  1033. node.input = [];
  1034. node.controlDependencies = [];
  1035. for (const input of inputs) {
  1036. const split = input.split(':', 3);
  1037. const input_name = split[0];
  1038. const input_index = split.length == 1 ? 0 : parseInt(split[split.length - 1]);
  1039. const from_name = input_name.startsWith('^') ? input_name.substring(1) : input_name;
  1040. const from = node_map.get(from_name);
  1041. const output_name = from_name + (input_index == 0 ? '' : ':' + input_index.toString());
  1042. const input_arg = from ? { name: output_name, from: from } : { name: output_name };
  1043. if (input_name.startsWith('^')) {
  1044. node.controlDependencies.push(input_arg);
  1045. }
  1046. else {
  1047. node.input.push(input_arg);
  1048. }
  1049. if (from) {
  1050. for (let i = from.output.length; i <= input_index; i++) {
  1051. from.output.push({ name: i === 0 ? from_name : from_name + ':' + i.toString(), to: [] });
  1052. }
  1053. from.output[input_index].to.push(node);
  1054. }
  1055. }
  1056. }
  1057. for (const node of nodes) {
  1058. if (output_arg_map.has(node.name)) {
  1059. node.output.push({ name: node.name, to: [] });
  1060. }
  1061. }
  1062. const initializers = new Map();
  1063. const map_tensor = (name, node, kind) => {
  1064. if (node && node.op === 'Const' && node.input.length === 0 && node.output.length === 1 && node.output[0].to.length === 1 && node.controlDependencies.length === 0) {
  1065. const value = node.attr.value;
  1066. if (value && Object.prototype.hasOwnProperty.call(value, 'tensor')) {
  1067. const tensor = new tf.Tensor(value.tensor, name, kind);
  1068. return new tf.Argument(name, tensor.type, tensor);
  1069. }
  1070. }
  1071. return null;
  1072. };
  1073. const map_resource = (name, node, tensor) => {
  1074. if (node && node.op === 'Placeholder' && node.input.length === 0 && node.output.length === 1 && node.output[0].to.length === 1 && node.controlDependencies.length === 0) {
  1075. const dtype = node.attr.dtype.type;
  1076. if (dtype === tf.proto.tensorflow.DataType.DT_RESOURCE) {
  1077. return new tf.Argument(name, null, tensor);
  1078. }
  1079. }
  1080. return null;
  1081. };
  1082. for (const node of node_map.values()) {
  1083. if (node.op === 'Identity' && node.input.length === 1 && node.output.length === 1 && node.output[0].to.length === 1 && node.controlDependencies.length === 0) {
  1084. const initializer = map_tensor(node.name, node.input[0].from, 'Identity Constant');
  1085. if (initializer) {
  1086. initializers.set(initializer.name, initializer);
  1087. node_map.delete(initializer.name);
  1088. node_map.delete(node.input[0].name);
  1089. }
  1090. const identity = node.input[0];
  1091. if (identity.op === 'Identity' && identity.input.length === 1 && identity.output.length === 1 && node.output[0].to.length === 1 && node.controlDependencies.length === 0) {
  1092. const initializer = map_tensor(node.name, identity.input[0], 'Identity Constant');
  1093. if (initializer) {
  1094. initializers.set(initializer.name, initializer);
  1095. node_map.delete(initializer.name);
  1096. node_map.delete(initializer.name);
  1097. node_map.delete(identity.name);
  1098. node_map.delete(node.name);
  1099. }
  1100. }
  1101. }
  1102. }
  1103. for (const node of node_map.values()) {
  1104. const initializer = map_tensor(node.name, node, 'Const');
  1105. if (initializer) {
  1106. initializers.set(initializer.name, initializer);
  1107. node_map.delete(node.name);
  1108. node_map.delete(initializer.name);
  1109. }
  1110. }
  1111. for (const node of node_map.values()) {
  1112. if (node.op === 'ReadVariableOp' && node.input.length === 1 && node.output.length === 1 && node.output[0].to.length === 1 && node.controlDependencies.length === 0 &&
  1113. node.attr && node.attr && node.attr.dtype && node.attr._output_shapes && node.attr._output_shapes.list && node.attr._output_shapes.list.shape) {
  1114. const tensor = new tf.proto.tensorflow.TensorProto();
  1115. tensor.dtype = node.attr.dtype.type;
  1116. tensor.tensor_shape = node.attr._output_shapes.list.shape[0];
  1117. const initializer = map_resource(node.name, node.input[0], new tf.Tensor(tensor, name, 'Resource Variable'));
  1118. if (initializer) {
  1119. initializers.set(initializer.name, initializer);
  1120. node_map.delete(initializer.name);
  1121. node_map.delete(node.input[0].name);
  1122. }
  1123. }
  1124. }
  1125. for (const node of node_map.values()) {
  1126. this._nodes.push(new tf.Node(metadata, namespaces, node, node.op, node.name, initializers, null));
  1127. }
  1128. }
  1129. }
  1130. get type() {
  1131. return 'function';
  1132. }
  1133. get name() {
  1134. return this._name;
  1135. }
  1136. get version() {
  1137. return this._version;
  1138. }
  1139. get tags() {
  1140. return this._tags;
  1141. }
  1142. get groups() {
  1143. return false;
  1144. // TODO return true;
  1145. }
  1146. get inputs() {
  1147. return this._inputs;
  1148. }
  1149. get outputs() {
  1150. return this._outputs;
  1151. }
  1152. get nodes() {
  1153. return this._nodes;
  1154. }
  1155. };
  1156. tf.Node = class {
  1157. constructor(metadata, namespaces, node, op, name, initializers, tensors) {
  1158. this._type = Object.assign({}, node && node.metadata ? node.metadata : metadata.type(op) || { name: op });
  1159. this._type.identifier = this._type.name;
  1160. this._type.name = op;
  1161. this._name = name;
  1162. this._attributes = [];
  1163. this._inputs = [];
  1164. this._outputs = [];
  1165. this._group = '';
  1166. if (namespaces.has(name)) {
  1167. this._group = name;
  1168. }
  1169. else {
  1170. const lastIndex = name.lastIndexOf('/');
  1171. if (lastIndex != -1) {
  1172. const namespace = name.substring(0, lastIndex);
  1173. if (namespaces.has(namespace)) {
  1174. this._group = namespace;
  1175. }
  1176. }
  1177. }
  1178. if (node) {
  1179. if (node.device !== undefined) {
  1180. this._device = node.device;
  1181. }
  1182. if (node.attr) {
  1183. this._attributes = Object.keys(node.attr).map((name) => {
  1184. const value = node.attr[name];
  1185. return new tf.Attribute(metadata, op, name, value);
  1186. });
  1187. }
  1188. let inputIndex = 0;
  1189. const inputs = node.input.filter((input) => !input.name.startsWith('^'));
  1190. if (this._type && this._type.inputs) {
  1191. for (const input of this._type.inputs) {
  1192. let inputCount = 1;
  1193. if (input.numberAttr) {
  1194. const inputNumber = node.attr[input.numberAttr];
  1195. if (inputNumber && inputNumber.i) {
  1196. inputCount = inputNumber.i;
  1197. }
  1198. }
  1199. else if (input.typeListAttr) {
  1200. const inputTypeListAttr = node.attr[input.typeListAttr];
  1201. if (inputTypeListAttr && inputTypeListAttr.list && inputTypeListAttr.list.type) {
  1202. inputCount = inputTypeListAttr.list.type.length;
  1203. }
  1204. }
  1205. const inputArguments = inputs.slice(inputIndex, inputIndex + inputCount).map((input) => {
  1206. return initializers.has(input.name) ? initializers.get(input.name) : new tf.Argument(input.name, null, null);
  1207. });
  1208. this._inputs.push(new tf.Parameter(input.name, inputArguments));
  1209. inputIndex += inputCount;
  1210. }
  1211. }
  1212. this._inputs.push(...inputs.slice(inputIndex).map((input, index) => {
  1213. return new tf.Parameter(input.label ? input.label : (inputIndex + index).toString(), [
  1214. initializers.has(input.name) ? initializers.get(input.name) : new tf.Argument(input.name, null, null)
  1215. ]);
  1216. }));
  1217. let outputIndex = 0;
  1218. const outputs = node.output;
  1219. if (this._type && this._type.outputs) {
  1220. for (const output of this._type.outputs) {
  1221. let outputCount = 1;
  1222. if (output.numberAttr) {
  1223. const outputNumber = node.attr[output.numberAttr];
  1224. if (outputNumber && outputNumber.i) {
  1225. outputCount = outputNumber.i;
  1226. }
  1227. }
  1228. else if (output.typeListAttr) {
  1229. const outputTypeListAttr = node.attr[output.typeListAttr];
  1230. if (outputTypeListAttr && outputTypeListAttr.list && outputTypeListAttr.list.type) {
  1231. outputCount = outputTypeListAttr.list.type.length;
  1232. }
  1233. }
  1234. const outputArguments = outputs.slice(outputIndex, outputIndex + outputCount).map((output) => {
  1235. return new tf.Argument(output.name ? output.name : '-', null, null);
  1236. });
  1237. this._outputs.push(new tf.Parameter(output.name, outputArguments));
  1238. outputIndex += outputCount;
  1239. }
  1240. }
  1241. this._outputs.push(...outputs.slice(outputIndex).map((output, index) => {
  1242. return new tf.Parameter((outputIndex + index).toString(), [
  1243. new tf.Argument(output.name ? output.name : '-', null, null)
  1244. ]);
  1245. }));
  1246. this._controlDependencies = node.controlDependencies.map((input) => input.name);
  1247. }
  1248. else if (tensors) {
  1249. for (const tensor of tensors) {
  1250. this._inputs.push(new tf.Parameter(tensor.name, [
  1251. new tf.Argument(tensor.value.name, null, tensor.value)
  1252. ]));
  1253. }
  1254. }
  1255. }
  1256. get type() {
  1257. return this._type;
  1258. }
  1259. get name() {
  1260. return this._name;
  1261. }
  1262. get device() {
  1263. return this._device || null;
  1264. }
  1265. get group() {
  1266. return this._group;
  1267. }
  1268. get description() {
  1269. return '';
  1270. }
  1271. get inputs() {
  1272. return this._inputs;
  1273. }
  1274. get outputs() {
  1275. return this._outputs;
  1276. }
  1277. get controlDependencies() {
  1278. return this._controlDependencies;
  1279. }
  1280. get attributes() {
  1281. return this._attributes;
  1282. }
  1283. };
  1284. tf.Attribute = class {
  1285. constructor(metadata, op, name, value) {
  1286. this._name = name;
  1287. this._value = null;
  1288. this._type = null;
  1289. const schema = value && value.metadata ? value.metadata : metadata.attribute(op, name);
  1290. const visible = metadata.visible(op, name);
  1291. if (Object.prototype.hasOwnProperty.call(value, 'tensor')) {
  1292. this._type = 'tensor';
  1293. this._value = new tf.Tensor(value.tensor);
  1294. }
  1295. else if (schema && schema.type) {
  1296. this._type = schema.type;
  1297. }
  1298. switch (value.value) {
  1299. case 'type':
  1300. this._type = 'type';
  1301. this._value = tf.Utility.dataType(value.type);
  1302. break;
  1303. case 'i':
  1304. this._value = value.i;
  1305. break;
  1306. case 'f':
  1307. this._value = value.f;
  1308. break;
  1309. case 'b':
  1310. this._value = value.b;
  1311. break;
  1312. case 'shape':
  1313. this._type = 'shape';
  1314. this._value = new tf.TensorShape(value.shape);
  1315. break;
  1316. case 's':
  1317. this._value = tf.Utility.decodeText(value.s);
  1318. break;
  1319. case 'func': {
  1320. this._type = 'function';
  1321. this._value = metadata.type(value.func.name);
  1322. break;
  1323. }
  1324. case 'list': {
  1325. const list = value.list;
  1326. if (list.s && list.s.length > 0) {
  1327. this._value = list.s.map((s) => tf.Utility.decodeText(s));
  1328. }
  1329. else if (list.i && list.i.length > 0) {
  1330. this._value = list.i;
  1331. }
  1332. else if (list.f && list.f.length > 0) {
  1333. this._value = list.f;
  1334. }
  1335. else if (list.type && list.type.length > 0) {
  1336. this._type = 'type[]';
  1337. this._value = list.type.map((type) => tf.Utility.dataType(type));
  1338. }
  1339. else if (list.shape && list.shape.length > 0) {
  1340. this._type = 'shape[]';
  1341. this._value = list.shape.map((shape) => new tf.TensorShape(shape));
  1342. }
  1343. else if (list.func && list.func.length > 0) {
  1344. this._type = 'function[]';
  1345. this._value = list.func.map((func) => metadata.type(func.name));
  1346. }
  1347. else {
  1348. this._value = [];
  1349. }
  1350. break;
  1351. }
  1352. }
  1353. if (schema) {
  1354. if (Object.prototype.hasOwnProperty.call(schema, 'visible') && !schema.visible) {
  1355. this._visible = false;
  1356. }
  1357. else if (Object.prototype.hasOwnProperty.call(schema, 'default')) {
  1358. const equals = (value, defaultValue) => {
  1359. if (!Array.isArray(defaultValue) && defaultValue === Object(defaultValue)) {
  1360. switch (defaultValue.type) {
  1361. case 'type':
  1362. defaultValue = tf.Utility.dataType(defaultValue.value);
  1363. break;
  1364. case 'shape':
  1365. case 'tensor':
  1366. defaultValue = defaultValue.value;
  1367. break;
  1368. default:
  1369. throw new tf.Error(JSON.stringify(defaultValue));
  1370. }
  1371. }
  1372. switch (typeof value) {
  1373. case 'boolean':
  1374. case 'number':
  1375. case 'string':
  1376. return value === defaultValue;
  1377. }
  1378. if (value instanceof base.Int64 || value instanceof base.Uint64) {
  1379. return value.toNumber() === defaultValue;
  1380. }
  1381. return false;
  1382. };
  1383. const value = this._value;
  1384. const defaultValue = schema.default;
  1385. if (Array.isArray(value) && Array.isArray(defaultValue)) {
  1386. if (value.length === defaultValue.length && value.every((item, index) => equals(item, defaultValue[index]))) {
  1387. this._visible = false;
  1388. }
  1389. }
  1390. else {
  1391. if (equals(value, defaultValue)) {
  1392. this._visible = false;
  1393. }
  1394. }
  1395. }
  1396. }
  1397. if (name == '_output_shapes') {
  1398. this._visible = false;
  1399. this._type = 'shape[]';
  1400. }
  1401. if (name == '_class') {
  1402. this._visible = false;
  1403. }
  1404. if (visible === false) {
  1405. this._visible = false;
  1406. }
  1407. }
  1408. get name() {
  1409. return this._name;
  1410. }
  1411. get type() {
  1412. return this._type;
  1413. }
  1414. get value() {
  1415. return this._value;
  1416. }
  1417. get visible() {
  1418. return this._visible == false ? false : true;
  1419. }
  1420. };
  1421. tf.Tensor = class {
  1422. constructor(tensor, name, kind) {
  1423. this._name = name;
  1424. this._kind = kind || null;
  1425. if (tensor) {
  1426. this._type = new tf.TensorType(tensor.dtype, tensor.tensor_shape || tensor.tensorShape);
  1427. this._tensor = tensor;
  1428. if (Object.prototype.hasOwnProperty.call(tensor, 'tensor_content')) {
  1429. this._buffer = tensor.tensor_content;
  1430. }
  1431. else {
  1432. const DataType = tf.proto.tensorflow.DataType;
  1433. switch (tensor.dtype) {
  1434. case DataType.DT_FLOAT:
  1435. this._data = tensor.float_val || null;
  1436. break;
  1437. case DataType.DT_DOUBLE:
  1438. this._data = tensor.double_val || null;
  1439. break;
  1440. case DataType.DT_INT8:
  1441. case DataType.DT_UINT8:
  1442. case DataType.DT_INT32:
  1443. this._data = tensor.int_val || null;
  1444. break;
  1445. case DataType.DT_UINT32:
  1446. this._data = tensor.uint32_val || null;
  1447. break;
  1448. case DataType.DT_INT64:
  1449. this._data = tensor.int64_val || null;
  1450. break;
  1451. case DataType.DT_UINT64:
  1452. this._data = tensor.uint64_val || null;
  1453. break;
  1454. case DataType.DT_BOOL:
  1455. this._data = tensor.bool_val || null;
  1456. break;
  1457. case DataType.DT_STRING:
  1458. this._data = tensor.string_val || null;
  1459. break;
  1460. }
  1461. }
  1462. }
  1463. else {
  1464. this._type = new tf.TensorType('?', null);
  1465. this._tensor = null;
  1466. }
  1467. }
  1468. get name() {
  1469. return this._name;
  1470. }
  1471. get type() {
  1472. return this._type;
  1473. }
  1474. get kind() {
  1475. return this._kind;
  1476. }
  1477. set kind(value) {
  1478. this._kind = value;
  1479. }
  1480. get state() {
  1481. return this._context().state;
  1482. }
  1483. get value() {
  1484. const context = this._context();
  1485. if (context.state) {
  1486. return null;
  1487. }
  1488. context.limit = Number.MAX_SAFE_INTEGER;
  1489. return this._decode(context, 0);
  1490. }
  1491. toString() {
  1492. const context = this._context();
  1493. if (context.state) {
  1494. return '';
  1495. }
  1496. context.limit = 10000;
  1497. const value = this._decode(context, 0);
  1498. return tf.Tensor._stringify(value, '', ' ');
  1499. }
  1500. _context() {
  1501. const context = {};
  1502. context.state = null;
  1503. context.index = 0;
  1504. context.count = 0;
  1505. context.size = 1;
  1506. if (!this._tensor) {
  1507. context.state = 'Tensor has content.';
  1508. return context;
  1509. }
  1510. if (!this._tensor.dtype) {
  1511. context.state = 'Tensor has no data type.';
  1512. return context;
  1513. }
  1514. const shape = this._tensor.tensor_shape || this._tensor.tensorShape;
  1515. if (!shape || !shape.dim) {
  1516. context.state = 'Tensor has no dimensions.';
  1517. return context;
  1518. }
  1519. for (const dim of shape.dim) {
  1520. context.size = context.size * (dim.size ? dim.size : 0);
  1521. }
  1522. if (this._buffer) {
  1523. const DataType = tf.proto.tensorflow.DataType;
  1524. switch (this._tensor.dtype) {
  1525. case DataType.DT_FLOAT:
  1526. case DataType.DT_DOUBLE:
  1527. case DataType.DT_QINT8:
  1528. case DataType.DT_QUINT8:
  1529. case DataType.DT_INT8:
  1530. case DataType.DT_UINT8:
  1531. case DataType.DT_INT16:
  1532. case DataType.DT_UINT16:
  1533. case DataType.DT_INT32:
  1534. case DataType.DT_UINT32:
  1535. case DataType.DT_INT64:
  1536. case DataType.DT_UINT64:
  1537. context.rawData = new DataView(this._buffer.buffer, this._buffer.byteOffset, this._buffer.byteLength);
  1538. break;
  1539. }
  1540. }
  1541. else if (this._data) {
  1542. if (this._data.length == context.size) {
  1543. context.data = this._data;
  1544. }
  1545. else if (this._data.length === 1) {
  1546. context.data = new Array(context.size).fill(this._data[0]);
  1547. }
  1548. else {
  1549. context.state = "Tensor has no data.";
  1550. return context;
  1551. }
  1552. }
  1553. else {
  1554. context.state = "Tensor has no data.";
  1555. return context;
  1556. }
  1557. if (!context.data && !context.rawData) {
  1558. context.state = "Tensor data type '" + this.type.dataType + "' is not implemented.";
  1559. return context;
  1560. }
  1561. context.shape = shape.dim.map((dim) => dim.size);
  1562. return context;
  1563. }
  1564. _decode(context, dimension) {
  1565. let shape = context.shape;
  1566. if (shape.length == 0) {
  1567. shape = [ 1 ];
  1568. }
  1569. const results = [];
  1570. const size = shape[dimension];
  1571. if (dimension == shape.length - 1) {
  1572. for (let i = 0; i < size; i++) {
  1573. if (context.count > context.limit) {
  1574. results.push('...');
  1575. return results;
  1576. }
  1577. if (context.data) {
  1578. const value = context.data[context.index++];
  1579. results.push((this._tensor.dtype == tf.proto.tensorflow.DataType.DT_STRING) ? tf.Utility.decodeText(value) : value);
  1580. context.count++;
  1581. }
  1582. else {
  1583. if (context.rawData) {
  1584. switch (this._tensor.dtype) {
  1585. case tf.proto.tensorflow.DataType.DT_FLOAT:
  1586. results.push(context.rawData.getFloat32(context.index, true));
  1587. context.index += 4;
  1588. context.count++;
  1589. break;
  1590. case tf.proto.tensorflow.DataType.DT_DOUBLE:
  1591. results.push(context.rawData.getFloat64(context.index, true));
  1592. context.index += 8;
  1593. context.count++;
  1594. break;
  1595. case tf.proto.tensorflow.DataType.DT_INT8:
  1596. results.push(context.rawData.getInt8(context.index));
  1597. context.index += 1;
  1598. context.count++;
  1599. break;
  1600. case tf.proto.tensorflow.DataType.DT_UINT8:
  1601. results.push(context.rawData.getUint8(context.index));
  1602. context.index += 1;
  1603. context.count++;
  1604. break;
  1605. case tf.proto.tensorflow.DataType.DT_INT16:
  1606. results.push(context.rawData.getInt16(context.index));
  1607. context.index += 2;
  1608. context.count++;
  1609. break;
  1610. case tf.proto.tensorflow.DataType.DT_UINT16:
  1611. results.push(context.rawData.getUint16(context.index));
  1612. context.index += 2;
  1613. context.count++;
  1614. break;
  1615. case tf.proto.tensorflow.DataType.DT_INT32:
  1616. results.push(context.rawData.getInt32(context.index, true));
  1617. context.index += 4;
  1618. context.count++;
  1619. break;
  1620. case tf.proto.tensorflow.DataType.DT_UINT32:
  1621. results.push(context.rawData.getUint32(context.index, true));
  1622. context.index += 4;
  1623. context.count++;
  1624. break;
  1625. case tf.proto.tensorflow.DataType.DT_INT64:
  1626. results.push(context.rawData.getInt64(context.index, true));
  1627. context.index += 8;
  1628. context.count++;
  1629. break;
  1630. case tf.proto.tensorflow.DataType.DT_UINT64:
  1631. results.push(context.rawData.getUint64(context.index, true));
  1632. context.index += 8;
  1633. context.count++;
  1634. break;
  1635. case tf.proto.tensorflow.DataType.DT_QINT8:
  1636. results.push(context.rawData.getInt8(context.index, true));
  1637. context.index += 1;
  1638. context.count++;
  1639. break;
  1640. case tf.proto.tensorflow.DataType.DT_QUINT8:
  1641. results.push(context.rawData.getUint8(context.index, true));
  1642. context.index += 1;
  1643. context.count++;
  1644. break;
  1645. default:
  1646. throw new tf.Error("Unsupported data type '" + this._tensor.dtype + "'.");
  1647. }
  1648. }
  1649. }
  1650. }
  1651. }
  1652. else {
  1653. for (let j = 0; j < size; j++) {
  1654. if (context.count > context.limit) {
  1655. results.push('...');
  1656. return results;
  1657. }
  1658. results.push(this._decode(context, dimension + 1, shape));
  1659. }
  1660. }
  1661. if (context.shape.length == 0) {
  1662. return results[0];
  1663. }
  1664. return results;
  1665. }
  1666. static _stringify(value, indentation, indent) {
  1667. if (Array.isArray(value)) {
  1668. const result = [];
  1669. result.push(indentation + '[');
  1670. const items = value.map((item) => tf.Tensor._stringify(item, indentation + indent, indent));
  1671. if (items.length > 0) {
  1672. result.push(items.join(',\n'));
  1673. }
  1674. result.push(indentation + ']');
  1675. return result.join('\n');
  1676. }
  1677. if (typeof value == 'string') {
  1678. return indentation + value;
  1679. }
  1680. if (value == Infinity) {
  1681. return indentation + 'Infinity';
  1682. }
  1683. if (value == -Infinity) {
  1684. return indentation + '-Infinity';
  1685. }
  1686. if (isNaN(value)) {
  1687. return indentation + 'NaN';
  1688. }
  1689. return indentation + value.toString();
  1690. }
  1691. };
  1692. tf.TensorType = class {
  1693. constructor(dtype, shape) {
  1694. this._dtype = dtype;
  1695. this._shape = new tf.TensorShape(shape);
  1696. }
  1697. get dataType() {
  1698. return this._dtype ? tf.Utility.dataType(this._dtype) : '?';
  1699. }
  1700. get shape() {
  1701. return this._shape;
  1702. }
  1703. toString() {
  1704. return this.dataType + this._shape.toString();
  1705. }
  1706. };
  1707. tf.TensorShape = class {
  1708. constructor(shape) {
  1709. this._shape = shape;
  1710. }
  1711. get dimensions() {
  1712. if (this._shape && this._shape.dim) {
  1713. if (this._shape.unknown_rank) {
  1714. return null;
  1715. }
  1716. if (this._shape.dim.length == 0) {
  1717. return [];
  1718. }
  1719. if (this._shape.dim.length == 1 && !this._shape.dim[0].size) {
  1720. return [ 0 ];
  1721. }
  1722. return this._shape.dim.map((dim) => (dim.size && dim.size != -1) ? dim.size : '?');
  1723. }
  1724. return null;
  1725. }
  1726. toString() {
  1727. if (this._shape && this._shape.dim) {
  1728. if (this._shape.unknown_rank) {
  1729. return '[-]';
  1730. }
  1731. if (this._shape.dim.length == 0) {
  1732. return '';
  1733. }
  1734. if (this._shape.dim.length == 1 && !this._shape.dim[0].size) {
  1735. return '[0]';
  1736. }
  1737. return '[' + this._shape.dim.map((dim) => (dim.size && dim.size != -1) ? dim.size.toString() : '?').join(',') + ']';
  1738. }
  1739. return '?';
  1740. }
  1741. };
  1742. tf.TensorBundle = class {
  1743. static open(stream, identifier, context) {
  1744. const format = !identifier.toLowerCase().endsWith('.index') ? 1 : 2;
  1745. const table = new tf.TensorBundle.Table(stream);
  1746. if (!table.entries.has('')) {
  1747. throw new tf.Error('Bundle header not available.');
  1748. }
  1749. if (format === 1) {
  1750. return Promise.resolve(new tf.TensorBundle(format, table.entries, []));
  1751. }
  1752. const buffer = table.entries.get('');
  1753. const reader = protobuf.BinaryReader.open(buffer);
  1754. const header = tf.proto.tensorflow.BundleHeaderProto.decode(reader);
  1755. const numShards = header.num_shards;
  1756. const promises = [];
  1757. for (let i = 0; i < numShards; i++) {
  1758. const shardIndex = ('0000' + i).slice(-5);
  1759. const shardCount = ('0000' + numShards).slice(-5);
  1760. const filename = identifier.split('.');
  1761. filename.pop();
  1762. const basename = filename.join('.');
  1763. const name = basename + '.data-' + shardIndex + '-of-' + shardCount;
  1764. promises.push(context.request(name, null));
  1765. }
  1766. return Promise.all(promises).then((streams) => {
  1767. return new tf.TensorBundle(format, table.entries, streams);
  1768. }).catch((error) => {
  1769. context.exception(error, false);
  1770. return new tf.TensorBundle(format, table.entries, null);
  1771. });
  1772. }
  1773. constructor(format, entries, streams) {
  1774. this._format = format;
  1775. this._tensors = [];
  1776. switch (format) {
  1777. case 1: {
  1778. const buffer = entries.get('');
  1779. const reader = protobuf.BinaryReader.open(buffer);
  1780. const header = tf.proto.tensorflow.SavedTensorSlices.decode(reader);
  1781. const data = new Map();
  1782. for (const pair of entries) {
  1783. if (pair[0] !== '' && pair[0] !== 'global_step') {
  1784. const buffer = pair[1];
  1785. const reader = protobuf.BinaryReader.open(buffer);
  1786. const slices = tf.proto.tensorflow.SavedTensorSlices.decode(reader);
  1787. const name = slices.data.name;
  1788. const tensor = slices.data.data;
  1789. if (!data.has(name)) {
  1790. if (tensor.tensor_content && tensor.tensor_content.length > 0) {
  1791. data.set(name, { key: 'tensor_content', value: tensor.tensor_content });
  1792. }
  1793. else {
  1794. const keys = Object.keys(tensor).filter((key) => key.endsWith('_val') && tensor[key] && tensor[key].length > 0);
  1795. data.set(name, keys.length == 1 ? { key: keys[0], value: tensor[keys[0]] } : null);
  1796. }
  1797. }
  1798. else {
  1799. const item = data.get(name);
  1800. if (item !== null) {
  1801. if (tensor[item.key] && tensor[item.key].length > 0) {
  1802. item.value = item.value.concat(tensor[item.key]);
  1803. }
  1804. else {
  1805. data.set(name, null);
  1806. }
  1807. }
  1808. }
  1809. }
  1810. }
  1811. for (const meta of header.meta.tensor) {
  1812. if (meta.name !== 'global_step') {
  1813. const tensor = new tf.proto.tensorflow.TensorProto();
  1814. tensor.dtype = meta.type;
  1815. tensor.tensor_shape = meta.shape;
  1816. const item = data.get(meta.name);
  1817. if (item) {
  1818. tensor[item.key] = item.value;
  1819. }
  1820. this._tensors.push(new tf.Tensor(tensor, meta.name, null));
  1821. }
  1822. }
  1823. break;
  1824. }
  1825. case 2: {
  1826. entries.forEach((buffer, name) => {
  1827. if (name !== '') {
  1828. const reader = protobuf.BinaryReader.open(buffer);
  1829. const entry = tf.proto.tensorflow.BundleEntryProto.decode(reader);
  1830. const tensor = new tf.proto.tensorflow.TensorProto();
  1831. tensor.dtype = entry.dtype;
  1832. tensor.tensor_shape = entry.shape;
  1833. const offset = Number.isInteger(entry.offset) ? entry.offset : entry.offset.toNumber();
  1834. const size = Number.isInteger(entry.size) ? entry.size : entry.size.toNumber();
  1835. if (streams) {
  1836. const stream = streams[entry.shard_id];
  1837. stream.seek(offset);
  1838. tensor.tensor_content = stream.peek(size);
  1839. }
  1840. this._tensors.push(new tf.Tensor(tensor, name, null));
  1841. }
  1842. });
  1843. break;
  1844. }
  1845. }
  1846. }
  1847. get format() {
  1848. return this._format;
  1849. }
  1850. get tensors() {
  1851. return this._tensors;
  1852. }
  1853. };
  1854. tf.TensorBundle.Table = class {
  1855. constructor(stream) {
  1856. // https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/lib/io/table.cc
  1857. this.entries = new Map();
  1858. if (stream.length <= 54) {
  1859. throw new tf.Error('Invalid index file size.');
  1860. }
  1861. stream.seek(-48);
  1862. const buffer = stream.peek(48);
  1863. const reader = new tf.BinaryReader(buffer);
  1864. reader.seek(-8);
  1865. const signature = [ 0x57, 0xfb, 0x80, 0x8b, 0x24, 0x75, 0x47, 0xdb ];
  1866. if (!reader.read(8).every((value, index) => value === signature[index])) {
  1867. throw new tf.Error('Invalid table signature.');
  1868. }
  1869. reader.seek(-48); // kEncodedLength
  1870. reader.varint64(); // metaindex offset
  1871. reader.varint64(); // metaindex size
  1872. const indexOffset = reader.varint64();
  1873. const indexSize = reader.varint64();
  1874. const indexBlock = new tf.TensorBundle.Table.Block(stream, indexOffset, indexSize);
  1875. for (const entry of indexBlock.entries) {
  1876. const valueReader = new tf.BinaryReader(entry[1]);
  1877. const offset = valueReader.varint64();
  1878. const size = valueReader.varint64();
  1879. const block = new tf.TensorBundle.Table.Block(stream, offset, size);
  1880. for (const pair of block.entries) {
  1881. this.entries.set(pair[0], pair[1]);
  1882. }
  1883. }
  1884. stream.seek(0);
  1885. }
  1886. };
  1887. tf.TensorBundle.Table.Block = class {
  1888. constructor(stream, offset, size) {
  1889. // https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/lib/io/block.cc
  1890. this.entries = new Map();
  1891. stream.seek(offset);
  1892. const buffer = stream.read(size); // blockContents
  1893. const compression = stream.byte();
  1894. stream.skip(4); // crc32
  1895. let reader = new tf.BinaryReader(buffer);
  1896. switch (compression) {
  1897. case 0: // kNoCompression
  1898. break;
  1899. case 1: // kSnappyCompression
  1900. reader = new tf.BinaryReader(reader.unsnappy());
  1901. break;
  1902. default:
  1903. throw new tf.Error("Unsupported block compression '" + compression + "'.");
  1904. }
  1905. reader.seek(-4);
  1906. const numRestarts = reader.int32();
  1907. reader.seek(-4 - (4 * numRestarts));
  1908. const restartOffsets = [];
  1909. for (let i = 0; i < numRestarts; i++) {
  1910. restartOffsets.push(reader.int32());
  1911. }
  1912. const textDecoder = new TextDecoder();
  1913. for (let i = 0; i < numRestarts; i++) {
  1914. reader.seek(restartOffsets[i]);
  1915. let key = '';
  1916. while (reader.position < reader.length) {
  1917. const sharedSize = reader.varint32(); // index shared size
  1918. const nonSharedSize = reader.varint32(); // index non shared size
  1919. const valueSize = reader.varint32();
  1920. if (sharedSize === 0 && nonSharedSize === 0 && valueSize === 0) {
  1921. break;
  1922. }
  1923. key = key.substring(0, sharedSize);
  1924. key = key + textDecoder.decode(reader.read(nonSharedSize));
  1925. const value = reader.read(valueSize);
  1926. this.entries.set(key, value);
  1927. }
  1928. }
  1929. }
  1930. };
  1931. tf.BinaryReader = class {
  1932. constructor(buffer) {
  1933. this._buffer = buffer;
  1934. this._position = 0;
  1935. this._length = this._buffer.length;
  1936. this._dataView = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  1937. }
  1938. get position() {
  1939. return this._position;
  1940. }
  1941. get length() {
  1942. return this._length;
  1943. }
  1944. seek(position) {
  1945. this._position = position >= 0 ? position : this._length + position;
  1946. if (this._position > this._length) {
  1947. throw new tf.Error('Expected ' + (this._position - this._length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  1948. }
  1949. }
  1950. skip(offset) {
  1951. this._position += offset;
  1952. if (this._position > this._length) {
  1953. throw new tf.Error('Expected ' + (this._position - this._length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  1954. }
  1955. }
  1956. read(size) {
  1957. const position = this._position;
  1958. this.skip(size);
  1959. return this._buffer.subarray(position, this._position);
  1960. }
  1961. byte() {
  1962. const position = this._position;
  1963. this.skip(1);
  1964. return this._dataView.getUint8(position);
  1965. }
  1966. uint16() {
  1967. const position = this._position;
  1968. this.skip(2);
  1969. return this._dataView.getUint16(position, true);
  1970. }
  1971. int32() {
  1972. const position = this._position;
  1973. this.skip(4);
  1974. return this._dataView.getInt32(position, true);
  1975. }
  1976. uint32() {
  1977. const position = this._position;
  1978. this.skip(4);
  1979. return this._dataView.getUint32(position, true);
  1980. }
  1981. uint64() {
  1982. const position = this._position;
  1983. this.skip(4);
  1984. return this._dataView.getUint64(position, true);
  1985. }
  1986. varint32() {
  1987. return this.varint64();
  1988. }
  1989. varint64() {
  1990. let result = 0;
  1991. for (let shift = 0; shift <= 63; shift += 7) {
  1992. const byte = this.byte();
  1993. if (byte & 128) {
  1994. result |= (byte & 127) << shift;
  1995. }
  1996. else {
  1997. result |= byte << shift;
  1998. break;
  1999. }
  2000. }
  2001. return result;
  2002. }
  2003. unsnappy() {
  2004. const data = new Uint8Array(this.varint64());
  2005. const mask = [0, 0xff, 0xffff, 0xffffff, 0xffffffff];
  2006. let position = 0;
  2007. while (this._position < this._length) {
  2008. let length = 0;
  2009. const c = this.byte();
  2010. switch (c & 0x03) {
  2011. case 0: {
  2012. length = (c >>> 2) + 1;
  2013. if (length > 60) {
  2014. const short = length - 60;
  2015. length = (this.uint32() & mask[short]) + 1;
  2016. this._position += short - 4;
  2017. }
  2018. data.set(this.read(length), position);
  2019. break;
  2020. }
  2021. case 1: {
  2022. length = ((c >>> 2) & 0x07) + 4;
  2023. const offset = this.byte() + ((c >>> 5) << 8);
  2024. data.set(data.subarray(position - offset, position - offset + length), position);
  2025. break;
  2026. }
  2027. case 2: {
  2028. length = (c >>> 2) + 1;
  2029. const offset = this.uint16();
  2030. data.set(data.subarray(position - offset, position - offset + length), position);
  2031. break;
  2032. }
  2033. case 3: {
  2034. length = (c >>> 2) + 1;
  2035. const offset = this.uint32();
  2036. data.set(data.subarray(position - offset, position - offset + length), position);
  2037. break;
  2038. }
  2039. }
  2040. position += length;
  2041. }
  2042. return data;
  2043. }
  2044. };
  2045. tf.EventFileReader = class {
  2046. static open(stream) {
  2047. if (stream.length < 16) {
  2048. return null;
  2049. }
  2050. const masked_crc32c = (bytes) => {
  2051. const poly = 0x82f63b78;
  2052. let crc = 0xffffffff;
  2053. for (let n = 0; n < bytes.length; n++) {
  2054. crc ^= bytes[n];
  2055. crc = crc & 1 ? (crc >>> 1) ^ poly : crc >>> 1;
  2056. crc = crc & 1 ? (crc >>> 1) ^ poly : crc >>> 1;
  2057. crc = crc & 1 ? (crc >>> 1) ^ poly : crc >>> 1;
  2058. crc = crc & 1 ? (crc >>> 1) ^ poly : crc >>> 1;
  2059. crc = crc & 1 ? (crc >>> 1) ^ poly : crc >>> 1;
  2060. crc = crc & 1 ? (crc >>> 1) ^ poly : crc >>> 1;
  2061. crc = crc & 1 ? (crc >>> 1) ^ poly : crc >>> 1;
  2062. crc = crc & 1 ? (crc >>> 1) ^ poly : crc >>> 1;
  2063. crc = crc >>> 0;
  2064. }
  2065. crc = crc ^ 0xffffffff;
  2066. crc = crc >>> 0;
  2067. crc = ((crc >> 15) | (crc << 17)) + 0xa282ead8;
  2068. crc = crc >>> 0;
  2069. return crc;
  2070. };
  2071. const buffer = stream.peek(12);
  2072. const reader = new tf.BinaryReader(buffer);
  2073. const length_bytes = reader.read(8);
  2074. const length_crc = reader.uint32();
  2075. if (masked_crc32c(length_bytes) !== length_crc) {
  2076. return null;
  2077. }
  2078. return new tf.EventFileReader(stream);
  2079. }
  2080. constructor(stream) {
  2081. this._stream = stream;
  2082. }
  2083. read() {
  2084. if (this._stream.position < this._stream.length) {
  2085. const uint64 = (stream) => {
  2086. const buffer = stream.read(8);
  2087. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  2088. return view.getUint64(0, true).toNumber();
  2089. };
  2090. const length = uint64(this._stream);
  2091. this._stream.skip(4); // masked crc of length
  2092. const buffer = this._stream.read(length);
  2093. const reader = protobuf.BinaryReader.open(buffer);
  2094. const event = tf.proto.tensorflow.Event.decode(reader);
  2095. this._stream.skip(4); // masked crc of data
  2096. return event;
  2097. }
  2098. }
  2099. };
  2100. tf.GraphMetadata = class {
  2101. constructor(metadata, library) {
  2102. this._metadata = metadata;
  2103. this._functions = new Map();
  2104. this._attributes = new Map();
  2105. this._visibleCache = new Map();
  2106. if (library && Array.isArray(library.function)) {
  2107. for (const func of library.function) {
  2108. const name = func.signature.name;
  2109. if (this._functions.has(func.name)) {
  2110. throw new tf.Error("Duplicate function name '" + func.name + "'.");
  2111. }
  2112. this._functions.set(name, func);
  2113. }
  2114. }
  2115. }
  2116. type(name) {
  2117. if (this._functions.has(name)) {
  2118. const func = this._functions.get(name);
  2119. if (func instanceof tf.Function) {
  2120. return func;
  2121. }
  2122. this._functions.set(name, new tf.Function(this, func));
  2123. return this._functions.get(name);
  2124. }
  2125. return this._metadata.type(name);
  2126. }
  2127. attribute(type, name) {
  2128. const key = type + '::' + name;
  2129. if (!this._attributes.has(key)) {
  2130. const schema = this.type(type);
  2131. if (schema && schema.attributes) {
  2132. for (const attribute of schema.attributes) {
  2133. const key = type + '::' + attribute.name;
  2134. this._attributes.set(key, attribute);
  2135. }
  2136. }
  2137. }
  2138. return this._attributes.get(key);
  2139. }
  2140. visible(type, name) {
  2141. if (!this._visibleCache.has(type)) {
  2142. const set = new Set();
  2143. const schema = this.type(type);
  2144. if (schema && schema.inputs) {
  2145. for (const input of schema.inputs) {
  2146. if (input.typeAttr) {
  2147. set.add(input.typeAttr);
  2148. }
  2149. else if (input.typeListAttr) {
  2150. set.add(input.typeListAttr);
  2151. }
  2152. if (input.numberAttr) {
  2153. set.add(input.numberAttr);
  2154. }
  2155. }
  2156. }
  2157. if (schema && schema.outputs) {
  2158. for (const output of schema.outputs) {
  2159. if (output.typeAttr) {
  2160. set.add(output.typeAttr);
  2161. }
  2162. else if (output.typeListAttr) {
  2163. set.add(output.typeListAttr);
  2164. }
  2165. if (output.numberAttr) {
  2166. set.add(output.numberAttr);
  2167. }
  2168. }
  2169. }
  2170. this._visibleCache.set(type, set);
  2171. }
  2172. return !this._visibleCache.get(type).has(name);
  2173. }
  2174. };
  2175. tf.Metadata = class {
  2176. static open(context) {
  2177. if (tf.Metadata._metadata) {
  2178. return Promise.resolve(tf.Metadata._metadata);
  2179. }
  2180. return context.request('tf-metadata.json', 'utf-8', null).then((data) => {
  2181. tf.Metadata._metadata = new tf.Metadata(data);
  2182. return tf.Metadata._metadata;
  2183. }).catch(() => {
  2184. tf.Metadata._metadata = new tf.Metadata(null);
  2185. return tf.Metadata._metadata;
  2186. });
  2187. }
  2188. constructor(data) {
  2189. this._map = new Map();
  2190. if (data) {
  2191. const metadata = JSON.parse(data);
  2192. this._map = new Map(metadata.map((item) => [ item.name, item ]));
  2193. }
  2194. }
  2195. type(operator) {
  2196. return this._map.get(operator);
  2197. }
  2198. };
  2199. tf.Utility = class {
  2200. static decodeText(value) {
  2201. if (typeof value === 'string') {
  2202. return value;
  2203. }
  2204. if (value.length === 0) {
  2205. return '';
  2206. }
  2207. tf.Utility._utf8Decoder = tf.Utility._utf8Decoder || new TextDecoder('utf-8');
  2208. return tf.Utility._utf8Decoder.decode(value);
  2209. }
  2210. static dataType(type) {
  2211. if (!tf.Utility._dataTypes) {
  2212. const dataTypes = new Map();
  2213. const DataType = tf.proto.tensorflow.DataType;
  2214. for (let key of Object.keys(DataType)) {
  2215. const value = DataType[key];
  2216. key = key.startsWith('DT_') ? key.substring(3) : key;
  2217. dataTypes.set(value, key.toLowerCase());
  2218. }
  2219. dataTypes.set(DataType.DT_HALF, 'float16');
  2220. dataTypes.set(DataType.DT_FLOAT, 'float32');
  2221. dataTypes.set(DataType.DT_DOUBLE, 'float64');
  2222. tf.Utility._dataTypes = dataTypes;
  2223. }
  2224. return tf.Utility._dataTypes.has(type) ? tf.Utility._dataTypes.get(type) : '?';
  2225. }
  2226. static dataTypeKey(type) {
  2227. if (!tf.Utility._dataTypeKeys) {
  2228. const dataTypeKeys = new Map();
  2229. const DataType = tf.proto.tensorflow.DataType;
  2230. for (let key of Object.keys(DataType)) {
  2231. const value = DataType[key];
  2232. key = key.startsWith('DT_') ? key.substring(3) : key;
  2233. dataTypeKeys.set(key.toLowerCase(), value);
  2234. }
  2235. dataTypeKeys.set('float16', DataType.DT_HALF);
  2236. dataTypeKeys.set('float32', DataType.DT_FLOAT);
  2237. dataTypeKeys.set('float64', DataType.DT_DOUBLE);
  2238. tf.Utility._dataTypeKeys = dataTypeKeys;
  2239. }
  2240. return tf.Utility._dataTypeKeys.get(type);
  2241. }
  2242. };
  2243. tf.JsonReader = class {
  2244. static decodeGraphDef(json) {
  2245. const message = new tf.proto.tensorflow.GraphDef();
  2246. message.node = json.node.map((node) => tf.JsonReader.decodeNodeDef(node));
  2247. return message;
  2248. }
  2249. static decodeNodeDef(json) {
  2250. const message = new tf.proto.tensorflow.NodeDef();
  2251. message.name = json.name;
  2252. message.op = json.op;
  2253. message.input = json.input || [];
  2254. if (json.device) {
  2255. message.device = json.device;
  2256. }
  2257. message.attr = {};
  2258. if (json.attr) {
  2259. for (const key of Object.keys(json.attr)) {
  2260. message.attr[key] = tf.JsonReader.decodeAttrValue(json.attr[key]);
  2261. }
  2262. }
  2263. return message;
  2264. }
  2265. static decodeAttrValue(json) {
  2266. const message = new tf.proto.tensorflow.AttrValue();
  2267. const keys = Object.keys(json);
  2268. if (keys.length !== 1) {
  2269. throw new tf.Error("Unsupported JSON tensorflow.AttrValue '" + JSON.stringify(keys) + "'.");
  2270. }
  2271. const key = keys[0];
  2272. const value = json[key];
  2273. switch (key) {
  2274. case 'type':
  2275. message.type = tf.proto.tensorflow.DataType[value];
  2276. break;
  2277. case 'shape':
  2278. message.shape = tf.JsonReader.decodeTensorShapeProto(value);
  2279. break;
  2280. case 'tensor':
  2281. message.tensor = tf.JsonReader.decodeTensorProto(value);
  2282. break;
  2283. case 'b':
  2284. message[key] = value;
  2285. break;
  2286. case 'f':
  2287. message[key] = parseFloat(value);
  2288. break;
  2289. case 'i':
  2290. message[key] = parseInt(value, 10);
  2291. break;
  2292. case 's':
  2293. message[key] = typeof value === 'string' ? atob(value) : tf.Utility.decodeText(Uint8Array.from(value));
  2294. break;
  2295. case 'list':
  2296. message.list = tf.JsonReader.decodeAttrValueListValue(json.list);
  2297. break;
  2298. default:
  2299. throw new tf.Error("Unsupported JSON 'tensorflow.AttrValue." + key + "'.");
  2300. }
  2301. return message;
  2302. }
  2303. static decodeAttrValueListValue(json) {
  2304. const message = new tf.proto.tensorflow.AttrValue.ListValue();
  2305. const properties = Object.keys(json);
  2306. if (properties.length > 0) {
  2307. const keys = properties.filter((key) => Array.isArray(json[key]) && json[key].length > 0);
  2308. if (keys.length !== 1) {
  2309. throw new tf.Error("Unsupported JSON tensorflow.AttrValue.ListValue '" + JSON.stringify(keys) + "'.");
  2310. }
  2311. const key = keys[0];
  2312. const list = json[key];
  2313. switch (key) {
  2314. case 'i':
  2315. message[key] = list.map((value) => parseInt(value, 10));
  2316. break;
  2317. case 's':
  2318. message[key] = list.map((value) => typeof value === 'string' ? atob(value) : tf.Utility.decodeText(Uint8Array.from(value)));
  2319. break;
  2320. case 'type':
  2321. message[key] = list.map((value) => tf.proto.tensorflow.DataType[value]);
  2322. break;
  2323. default:
  2324. throw new tf.Error("Unsupported JSON 'tensorflow.AttrValue.ListValue." + key + "'.");
  2325. }
  2326. }
  2327. return message;
  2328. }
  2329. static decodeTensorProto(json) {
  2330. const message = new tf.proto.tensorflow.TensorProto();
  2331. message.dtype = tf.proto.tensorflow.DataType[json.dtype];
  2332. message.tensor_shape = tf.JsonReader.decodeTensorShapeProto(json.tensorShape);
  2333. return message;
  2334. }
  2335. static decodeTensorShapeProto(json) {
  2336. const message = new tf.proto.tensorflow.TensorShapeProto();
  2337. message.dim = (json.dim || []).map((json) => {
  2338. const message = new tf.proto.tensorflow.TensorShapeProto.Dim();
  2339. message.size = json.size;
  2340. message.name = json.name;
  2341. return message;
  2342. });
  2343. return message;
  2344. }
  2345. };
  2346. tf.Error = class extends Error {
  2347. constructor(message) {
  2348. super(message);
  2349. this.name = 'Error loading TensorFlow model.';
  2350. }
  2351. };
  2352. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  2353. module.exports.ModelFactory = tf.ModelFactory;
  2354. }