view.js 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115
  1. var view = view || {};
  2. var base = base || require('./base');
  3. var zip = zip || require('./zip');
  4. var gzip = gzip || require('./gzip');
  5. var tar = tar || require('./tar');
  6. var json = json || require('./json');
  7. var xml = xml || require('./xml');
  8. var protobuf = protobuf || require('./protobuf');
  9. var flatbuffers = flatbuffers || require('./flatbuffers');
  10. var python = python || require('./python');
  11. var sidebar = sidebar || require('./view-sidebar');
  12. var grapher = grapher || require('./view-grapher');
  13. view.View = class {
  14. constructor(host, id) {
  15. this._host = host;
  16. this._id = id ? ('-' + id) : '';
  17. this._options = {
  18. initializers: true,
  19. attributes: false,
  20. names: false,
  21. direction: 'vertical',
  22. mousewheel: 'scroll'
  23. };
  24. this._host.initialize(this).then(() => {
  25. this._model = null;
  26. this._graphs = [];
  27. this._selection = [];
  28. this._sidebar = new sidebar.Sidebar(this._host, id);
  29. this._searchText = '';
  30. this._modelFactoryService = new view.ModelFactoryService(this._host);
  31. this._getElementById('zoom-in-button').addEventListener('click', () => {
  32. this.zoomIn();
  33. });
  34. this._getElementById('zoom-out-button').addEventListener('click', () => {
  35. this.zoomOut();
  36. });
  37. this._getElementById('back-button').addEventListener('click', () => {
  38. this.popGraph();
  39. });
  40. this._getElementById('name-button').addEventListener('click', () => {
  41. this.showDocumentation(this.activeGraph);
  42. });
  43. this._getElementById('sidebar').addEventListener('mousewheel', (e) => {
  44. this._preventDefault(e);
  45. }, { passive: true });
  46. this._host.document.addEventListener('keydown', () => {
  47. this.clearSelection();
  48. });
  49. this._host.start();
  50. const container = this._getElementById('graph');
  51. container.addEventListener('scroll', (e) => this._scrollHandler(e));
  52. container.addEventListener('wheel', (e) => this._wheelHandler(e), { passive: false });
  53. container.addEventListener('mousedown', (e) => this._mouseDownHandler(e));
  54. switch (this._host.agent) {
  55. case 'safari':
  56. container.addEventListener('gesturestart', (e) => this._gestureStartHandler(e), false);
  57. break;
  58. default:
  59. container.addEventListener('touchstart', (e) => this._touchStartHandler(e), { passive: true });
  60. break;
  61. }
  62. }).catch((err) => {
  63. this.error(err, null, null);
  64. });
  65. }
  66. show(page) {
  67. if (!page) {
  68. page = (!this._model && !this.activeGraph) ? 'welcome' : 'default';
  69. }
  70. this._host.screen(page);
  71. if (this._sidebar) {
  72. this._sidebar.close();
  73. }
  74. this._host.document.body.setAttribute('class', page);
  75. if (page === 'default') {
  76. const container = this._getElementById('graph');
  77. if (container) {
  78. container.focus();
  79. }
  80. }
  81. if (page === 'welcome') {
  82. const element = this._getElementById('open-file-button');
  83. if (element) {
  84. element.focus();
  85. }
  86. }
  87. this._page = page;
  88. }
  89. cut() {
  90. this._host.document.execCommand('cut');
  91. }
  92. copy() {
  93. this._host.document.execCommand('copy');
  94. }
  95. paste() {
  96. this._host.document.execCommand('paste');
  97. }
  98. selectAll() {
  99. this._host.document.execCommand('selectall');
  100. }
  101. find() {
  102. if (this._graph) {
  103. this.clearSelection();
  104. const graphElement = this._getElementById('canvas');
  105. const view = new sidebar.FindSidebar(this._host, graphElement, this._graph);
  106. view.on('search-text-changed', (sender, text) => {
  107. this._searchText = text;
  108. });
  109. view.on('select', (sender, selection) => {
  110. this.select(selection);
  111. });
  112. this._sidebar.open(view.content, 'Find');
  113. view.focus(this._searchText);
  114. }
  115. }
  116. get model() {
  117. return this._model;
  118. }
  119. get options() {
  120. return this._options;
  121. }
  122. toggle(name) {
  123. switch (name) {
  124. case 'names':
  125. case 'attributes':
  126. case 'initializers':
  127. this._options[name] = !this._options[name];
  128. this._reload();
  129. break;
  130. case 'direction':
  131. this._options.direction = this._options.direction === 'vertical' ? 'horizontal' : 'vertical';
  132. this._reload();
  133. break;
  134. case 'mousewheel':
  135. this._options.mousewheel = this._options.mousewheel === 'scroll' ? 'zoom' : 'scroll';
  136. break;
  137. default:
  138. throw new view.Error("Unsupported toogle '" + name + "'.");
  139. }
  140. }
  141. _reload() {
  142. this.show('welcome spinner');
  143. if (this._model && this._graphs.length > 0) {
  144. this._updateGraph(this._model, this._graphs).catch((error) => {
  145. if (error) {
  146. this.error(error, 'Graph update failed.', 'welcome');
  147. }
  148. });
  149. }
  150. }
  151. _timeout(time) {
  152. return new Promise((resolve) => {
  153. setTimeout(() => { resolve(); }, time);
  154. });
  155. }
  156. _getElementById(id) {
  157. return this._host.document.getElementById(id + this._id);
  158. }
  159. zoomIn() {
  160. this._updateZoom(this._zoom * 1.1);
  161. }
  162. zoomOut() {
  163. this._updateZoom(this._zoom * 0.9);
  164. }
  165. resetZoom() {
  166. this._updateZoom(1);
  167. }
  168. _preventDefault(e) {
  169. if (e.shiftKey || e.ctrlKey) {
  170. e.preventDefault();
  171. }
  172. }
  173. _updateZoom(zoom, e) {
  174. const container = this._getElementById('graph');
  175. const canvas = this._getElementById('canvas');
  176. const limit = this._options.direction === 'vertical' ?
  177. container.clientHeight / this._height :
  178. container.clientWidth / this._width;
  179. const min = Math.min(Math.max(limit, 0.15), 1);
  180. zoom = Math.max(min, Math.min(zoom, 1.4));
  181. const scrollLeft = this._scrollLeft || container.scrollLeft;
  182. const scrollTop = this._scrollTop || container.scrollTop;
  183. const x = (e ? e.pageX : (container.clientWidth / 2)) + scrollLeft;
  184. const y = (e ? e.pageY : (container.clientHeight / 2)) + scrollTop;
  185. const width = zoom * this._width;
  186. const height = zoom * this._height;
  187. canvas.style.width = width + 'px';
  188. canvas.style.height = height + 'px';
  189. this._scrollLeft = Math.max(0, ((x * zoom) / this._zoom) - (x - scrollLeft));
  190. this._scrollTop = Math.max(0, ((y * zoom) / this._zoom) - (y - scrollTop));
  191. container.scrollLeft = this._scrollLeft;
  192. container.scrollTop = this._scrollTop;
  193. this._zoom = zoom;
  194. }
  195. _mouseDownHandler(e) {
  196. if (e.buttons === 1) {
  197. const document = this._host.document.documentElement;
  198. document.style.cursor = 'grabbing';
  199. const container = this._getElementById('graph');
  200. this._mousePosition = {
  201. left: container.scrollLeft,
  202. top: container.scrollTop,
  203. x: e.clientX,
  204. y: e.clientY
  205. };
  206. e.stopImmediatePropagation();
  207. const mouseMoveHandler = (e) => {
  208. e.preventDefault();
  209. e.stopImmediatePropagation();
  210. const dx = e.clientX - this._mousePosition.x;
  211. const dy = e.clientY - this._mousePosition.y;
  212. this._mousePosition.moved = dx * dx + dy * dy > 0;
  213. if (this._mousePosition.moved) {
  214. const container = this._getElementById('graph');
  215. container.scrollTop = this._mousePosition.top - dy;
  216. container.scrollLeft = this._mousePosition.left - dx;
  217. }
  218. };
  219. const mouseUpHandler = () => {
  220. document.style.cursor = null;
  221. container.removeEventListener('mouseup', mouseUpHandler);
  222. container.removeEventListener('mouseleave', mouseUpHandler);
  223. container.removeEventListener('mousemove', mouseMoveHandler);
  224. if (this._mousePosition && this._mousePosition.moved) {
  225. e.preventDefault();
  226. e.stopImmediatePropagation();
  227. delete this._mousePosition;
  228. document.addEventListener('click', clickHandler, true);
  229. }
  230. };
  231. const clickHandler = (e) => {
  232. e.stopPropagation();
  233. document.removeEventListener('click', clickHandler, true);
  234. };
  235. container.addEventListener('mousemove', mouseMoveHandler);
  236. container.addEventListener('mouseup', mouseUpHandler);
  237. container.addEventListener('mouseleave', mouseUpHandler);
  238. }
  239. }
  240. _touchStartHandler(e) {
  241. if (e.touches.length === 2) {
  242. this._touchPoints = Array.from(e.touches);
  243. this._touchZoom = this._zoom;
  244. }
  245. const touchMoveHandler = (e) => {
  246. if (Array.isArray(this._touchPoints) && this._touchPoints.length === 2 && e.touches.length === 2) {
  247. const distance = (points) => {
  248. const dx =(points[1].clientX - points[0].clientX);
  249. const dy =(points[1].clientY - points[0].clientY);
  250. return Math.sqrt(dx * dx + dy * dy);
  251. };
  252. const d1 = distance(Array.from(e.touches));
  253. const d2 = distance(this._touchPoints);
  254. if (d2 !== 0) {
  255. const points = this._touchPoints;
  256. const e = {
  257. pageX: (points[1].pageX + points[0].pageX) / 2,
  258. pageY: (points[1].pageY + points[0].pageY) / 2
  259. };
  260. const zoom = d2 === 0 ? d1 : d1 / d2;
  261. this._updateZoom(this._touchZoom * zoom, e);
  262. }
  263. }
  264. };
  265. const touchEndHandler = () => {
  266. container.removeEventListener('touchmove', touchMoveHandler, { passive: true });
  267. container.removeEventListener('touchcancel', touchEndHandler, { passive: true });
  268. container.removeEventListener('touchend', touchEndHandler, { passive: true });
  269. delete this._touchPoints;
  270. delete this._touchZoom;
  271. };
  272. const container = this._getElementById('graph');
  273. container.addEventListener('touchmove', touchMoveHandler, { passive: true });
  274. container.addEventListener('touchcancel', touchEndHandler, { passive: true });
  275. container.addEventListener('touchend', touchEndHandler, { passive: true });
  276. }
  277. _gestureStartHandler(e) {
  278. e.preventDefault();
  279. this._gestureZoom = this._zoom;
  280. const container = this._getElementById('graph');
  281. const gestureChangeHandler = (e) => {
  282. e.preventDefault();
  283. this._updateZoom(this._gestureZoom * e.scale, e);
  284. };
  285. const gestureEndHandler = (e) => {
  286. container.removeEventListener('gesturechange', gestureChangeHandler, false);
  287. container.removeEventListener('gestureend', gestureEndHandler, false);
  288. e.preventDefault();
  289. if (this._gestureZoom) {
  290. this._updateZoom(this._gestureZoom * e.scale, e);
  291. delete this._gestureZoom;
  292. }
  293. };
  294. container.addEventListener('gesturechange', gestureChangeHandler, false);
  295. container.addEventListener('gestureend', gestureEndHandler, false);
  296. }
  297. _scrollHandler(e) {
  298. if (this._scrollLeft && e.target.scrollLeft !== Math.floor(this._scrollLeft)) {
  299. delete this._scrollLeft;
  300. }
  301. if (this._scrollTop && e.target.scrollTop !== Math.floor(this._scrollTop)) {
  302. delete this._scrollTop;
  303. }
  304. }
  305. _wheelHandler(e) {
  306. if (e.shiftKey || e.ctrlKey || this._options.mousewheel === 'zoom') {
  307. const delta = -e.deltaY * (e.deltaMode === 1 ? 0.05 : e.deltaMode ? 1 : 0.002) * (e.ctrlKey ? 10 : 1);
  308. this._updateZoom(this._zoom * Math.pow(2, delta), e);
  309. e.preventDefault();
  310. }
  311. }
  312. select(selection) {
  313. this.clearSelection();
  314. if (selection && selection.length > 0) {
  315. const container = this._getElementById('graph');
  316. let x = 0;
  317. let y = 0;
  318. for (const element of selection) {
  319. element.classList.add('select');
  320. this._selection.push(element);
  321. const rect = element.getBoundingClientRect();
  322. x += rect.left + (rect.width / 2);
  323. y += rect.top + (rect.height / 2);
  324. }
  325. x = x / selection.length;
  326. y = y / selection.length;
  327. const rect = container.getBoundingClientRect();
  328. const left = (container.scrollLeft + x - rect.left) - (rect.width / 2);
  329. const top = (container.scrollTop + y - rect.top) - (rect.height / 2);
  330. container.scrollTo({ left: left, top: top, behavior: 'smooth' });
  331. }
  332. }
  333. clearSelection() {
  334. while (this._selection.length > 0) {
  335. const element = this._selection.pop();
  336. element.classList.remove('select');
  337. }
  338. }
  339. error(err, name, screen) {
  340. if (this._sidebar) {
  341. this._sidebar.close();
  342. }
  343. this._host.exception(err, false);
  344. const knowns = [
  345. { name: '', message: /^Invalid argument identifier/, url: 'https://github.com/lutzroeder/netron/issues/540' },
  346. { name: '', message: /^Cannot read property/, url: 'https://github.com/lutzroeder/netron/issues/647' },
  347. { name: '', message: /^Failed to render tensor/, url: 'https://github.com/lutzroeder/netron/issues/681' },
  348. { name: 'Error', message: /^EPERM: operation not permitted/, url: 'https://github.com/lutzroeder/netron/issues/551' },
  349. { name: 'Error', message: /^EACCES: permission denied/, url: 'https://github.com/lutzroeder/netron/issues/504' },
  350. { name: 'RangeError', message: /^Offset is outside the bounds of the DataView/, url: 'https://github.com/lutzroeder/netron/issues/563' },
  351. { name: 'RangeError', message: /^start offset of Int32Array/, url: 'https://github.com/lutzroeder/netron/issues/565' },
  352. { name: 'RangeError', message: /^Maximum call stack size exceeded/, url: 'https://github.com/lutzroeder/netron/issues/589' },
  353. { name: 'RangeError', message: /^Invalid string length/, url: 'https://github.com/lutzroeder/netron/issues/648' },
  354. { name: 'Error loading model.', message: /^Unsupported file content \(/, url: 'https://github.com/lutzroeder/netron/issues/550' },
  355. { name: 'Error loading model.', message: /^Unsupported Protocol Buffers content/, url: 'https://github.com/lutzroeder/netron/issues/593' },
  356. { name: 'Error loading model.', message: /^Unsupported Protocol Buffers text content/, url: 'https://github.com/lutzroeder/netron/issues/594' },
  357. { name: 'Error loading model.', message: /^Unsupported JSON content/, url: 'https://github.com/lutzroeder/netron/issues/595' },
  358. { name: 'Error loading Caffe model.', message: /^File format is not caffe\.NetParameter/, url: 'https://github.com/lutzroeder/netron/issues/563' },
  359. { name: 'Error loading Darknet model.', message: /^Invalid tensor shape/, url: 'https://github.com/lutzroeder/netron/issues/541' },
  360. { name: 'Error loading Keras model.', message: /^Unsupported data object header version/, url: 'https://github.com/lutzroeder/netron/issues/548' },
  361. { name: 'Error loading MNN model.', message: /^File format is not mnn\.Net/, url: 'https://github.com/lutzroeder/netron/issues/746' },
  362. { name: 'Error loading PyTorch model.', message: /^File does not contain root module or state dictionary/, url: 'https://github.com/lutzroeder/netron/issues/543' },
  363. { name: 'Error loading PyTorch model.', message: /^Module does not contain modules/, url: 'https://github.com/lutzroeder/netron/issues/544' },
  364. { name: 'Error loading PyTorch model.', message: /^Failed to resolve module/, url: 'https://github.com/lutzroeder/netron/issues/545' },
  365. { name: 'Error loading PyTorch model.', message: /^Unsupported function/, url: 'https://github.com/lutzroeder/netron/issues/546' },
  366. { name: 'Error loading PyTorch model.', message: /^Unsupported uninitialized argument/, url: 'https://github.com/lutzroeder/netron/issues/547' },
  367. { name: 'Error loading ONNX model.', message: /^File format is not onnx\.ModelProto/, url: 'https://github.com/lutzroeder/netron/issues/549' },
  368. { name: 'Error loading TensorFlow model.', message: /^File text format is not TensorFlow\.js graph-model/, url: 'https://github.com/lutzroeder/netron/issues/764' },
  369. { name: 'Error loading TensorFlow Lite model.', message: /^Offset is outside the bounds of the DataView/, url: 'https://github.com/lutzroeder/netron/issues/563' },
  370. { name: 'Error loading UFF model.', message: /^Unknown attribute/, url: 'https://github.com/lutzroeder/netron/issues/649' }
  371. ];
  372. const known = knowns.find((known) => (known.name.length === 0 || known.name === err.name) && err.message.match(known.message));
  373. const message = err.message + (known ? '\n\nPlease provide information about this issue at ' + known.url + '.' : '');
  374. name = name || err.name;
  375. this._host.error(name, message);
  376. this.show(screen !== undefined ? screen : 'welcome');
  377. if (known) {
  378. this._host.openURL(known.url);
  379. }
  380. }
  381. accept(file) {
  382. return this._modelFactoryService.accept(file);
  383. }
  384. open(context) {
  385. this._host.event('Model', 'Open', 'Size', context.stream ? context.stream.length : 0);
  386. this._sidebar.close();
  387. return this._timeout(2).then(() => {
  388. return this._modelFactoryService.open(context).then((model) => {
  389. const format = [];
  390. if (model.format) {
  391. format.push(model.format);
  392. }
  393. if (model.producer) {
  394. format.push('(' + model.producer + ')');
  395. }
  396. if (format.length > 0) {
  397. this._host.event('Model', 'Format', format.join(' '));
  398. }
  399. return this._timeout(20).then(() => {
  400. const graphs = Array.isArray(model.graphs) && model.graphs.length > 0 ? [ model.graphs[0] ] : [];
  401. return this._updateGraph(model, graphs);
  402. });
  403. });
  404. });
  405. }
  406. _updateActiveGraph(graph) {
  407. this._sidebar.close();
  408. if (this._model) {
  409. const model = this._model;
  410. this.show('welcome spinner');
  411. this._timeout(200).then(() => {
  412. return this._updateGraph(model, [ graph ]).catch((error) => {
  413. if (error) {
  414. this.error(error, 'Graph update failed.', 'welcome');
  415. }
  416. });
  417. });
  418. }
  419. }
  420. get activeGraph() {
  421. return Array.isArray(this._graphs) && this._graphs.length > 0 ? this._graphs[0] : null;
  422. }
  423. _updateGraph(model, graphs) {
  424. return this._timeout(100).then(() => {
  425. const graph = Array.isArray(graphs) && graphs.length > 0 ? graphs[0] : null;
  426. if (graph && graph != this._graphs[0]) {
  427. const nodes = graph.nodes;
  428. if (nodes.length > 2048) {
  429. if (!this._host.confirm('Large model detected.', 'This graph contains a large number of nodes and might take a long time to render. Do you want to continue?')) {
  430. this._host.event('Graph', 'Render', 'Skip', nodes.length);
  431. this.show(null);
  432. return null;
  433. }
  434. }
  435. }
  436. const update = () => {
  437. const nameButton = this._getElementById('name-button');
  438. const backButton = this._getElementById('back-button');
  439. if (this._graphs.length > 1) {
  440. const graph = this.activeGraph;
  441. nameButton.innerHTML = graph ? graph.name : '';
  442. backButton.style.opacity = 1;
  443. nameButton.style.opacity = 1;
  444. }
  445. else {
  446. backButton.style.opacity = 0;
  447. nameButton.style.opacity = 0;
  448. }
  449. };
  450. const lastModel = this._model;
  451. const lastGraphs = this._graphs;
  452. this._model = model;
  453. this._graphs = graphs;
  454. return this.renderGraph(this._model, this.activeGraph).then(() => {
  455. if (this._page !== 'default') {
  456. this.show('default');
  457. }
  458. update();
  459. return this._model;
  460. }).catch((error) => {
  461. this._model = lastModel;
  462. this._graphs = lastGraphs;
  463. return this.renderGraph(this._model, this.activeGraph).then(() => {
  464. if (this._page !== 'default') {
  465. this.show('default');
  466. }
  467. update();
  468. throw error;
  469. });
  470. });
  471. });
  472. }
  473. pushGraph(graph) {
  474. if (graph !== this.activeGraph) {
  475. this._sidebar.close();
  476. this._updateGraph(this._model, [ graph ].concat(this._graphs));
  477. }
  478. }
  479. popGraph() {
  480. if (this._graphs.length > 1) {
  481. this._sidebar.close();
  482. return this._updateGraph(this._model, this._graphs.slice(1));
  483. }
  484. return null;
  485. }
  486. renderGraph(model, graph) {
  487. try {
  488. this._graph = null;
  489. const canvas = this._getElementById('canvas');
  490. while (canvas.lastChild) {
  491. canvas.removeChild(canvas.lastChild);
  492. }
  493. if (!graph) {
  494. return Promise.resolve();
  495. }
  496. this._zoom = 1;
  497. const groups = graph.groups;
  498. const nodes = graph.nodes;
  499. this._host.event('Graph', 'Render', 'Size', nodes.length);
  500. const options = {};
  501. options.nodesep = 20;
  502. options.ranksep = 20;
  503. const rotate = graph.nodes.every((node) => node.inputs.filter((input) => input.arguments.every((argument) => !argument.initializer)).length === 0 && node.outputs.length === 0);
  504. const horizontal = rotate ? this._options.direction === 'vertical' : this._options.direction !== 'vertical';
  505. if (horizontal) {
  506. options.rankdir = "LR";
  507. }
  508. if (nodes.length > 3000) {
  509. options.ranker = 'longest-path';
  510. }
  511. const viewGraph = new view.Graph(this, model, groups, options);
  512. viewGraph.add(graph);
  513. // Workaround for Safari background drag/zoom issue:
  514. // https://stackoverflow.com/questions/40887193/d3-js-zoom-is-not-working-with-mousewheel-in-safari
  515. const background = this._host.document.createElementNS('http://www.w3.org/2000/svg', 'rect');
  516. background.setAttribute('id', 'background');
  517. background.setAttribute('fill', 'none');
  518. background.setAttribute('pointer-events', 'all');
  519. canvas.appendChild(background);
  520. const origin = this._host.document.createElementNS('http://www.w3.org/2000/svg', 'g');
  521. origin.setAttribute('id', 'origin');
  522. canvas.appendChild(origin);
  523. viewGraph.build(this._host.document, origin);
  524. this._zoom = 1;
  525. return this._timeout(20).then(() => {
  526. viewGraph.update();
  527. const elements = Array.from(canvas.getElementsByClassName('graph-input') || []);
  528. if (elements.length === 0) {
  529. const nodeElements = Array.from(canvas.getElementsByClassName('graph-node') || []);
  530. if (nodeElements.length > 0) {
  531. elements.push(nodeElements[0]);
  532. }
  533. }
  534. const size = canvas.getBBox();
  535. const margin = 100;
  536. const width = Math.ceil(margin + size.width + margin);
  537. const height = Math.ceil(margin + size.height + margin);
  538. origin.setAttribute('transform', 'translate(' + margin.toString() + ', ' + margin.toString() + ') scale(1)');
  539. background.setAttribute('width', width);
  540. background.setAttribute('height', height);
  541. this._width = width;
  542. this._height = height;
  543. delete this._scrollLeft;
  544. delete this._scrollRight;
  545. canvas.setAttribute('viewBox', '0 0 ' + width + ' ' + height);
  546. canvas.setAttribute('width', width);
  547. canvas.setAttribute('height', height);
  548. this._zoom = 1;
  549. this._updateZoom(this._zoom);
  550. const container = this._getElementById('graph');
  551. if (elements && elements.length > 0) {
  552. // Center view based on input elements
  553. const xs = [];
  554. const ys = [];
  555. for (let i = 0; i < elements.length; i++) {
  556. const element = elements[i];
  557. const rect = element.getBoundingClientRect();
  558. xs.push(rect.left + (rect.width / 2));
  559. ys.push(rect.top + (rect.height / 2));
  560. }
  561. let x = xs[0];
  562. const y = ys[0];
  563. if (ys.every(y => y === ys[0])) {
  564. x = xs.reduce((a, b) => a + b, 0) / xs.length;
  565. }
  566. const graphRect = container.getBoundingClientRect();
  567. const left = (container.scrollLeft + x - graphRect.left) - (graphRect.width / 2);
  568. const top = (container.scrollTop + y - graphRect.top) - (graphRect.height / 2);
  569. container.scrollTo({ left: left, top: top, behavior: 'auto' });
  570. }
  571. else {
  572. const canvasRect = canvas.getBoundingClientRect();
  573. const graphRect = container.getBoundingClientRect();
  574. const left = (container.scrollLeft + (canvasRect.width / 2) - graphRect.left) - (graphRect.width / 2);
  575. const top = (container.scrollTop + (canvasRect.height / 2) - graphRect.top) - (graphRect.height / 2);
  576. container.scrollTo({ left: left, top: top, behavior: 'auto' });
  577. }
  578. this._graph = viewGraph;
  579. return;
  580. });
  581. }
  582. catch (error) {
  583. return Promise.reject(error);
  584. }
  585. }
  586. applyStyleSheet(element, name) {
  587. let rules = [];
  588. for (const styleSheet of this._host.document.styleSheets) {
  589. if (styleSheet && styleSheet.href && styleSheet.href.endsWith('/' + name)) {
  590. rules = styleSheet.cssRules;
  591. break;
  592. }
  593. }
  594. const nodes = element.getElementsByTagName('*');
  595. for (const node of nodes) {
  596. for (const rule of rules) {
  597. if (node.matches(rule.selectorText)) {
  598. for (const item of rule.style) {
  599. node.style[item] = rule.style[item];
  600. }
  601. }
  602. }
  603. }
  604. }
  605. export(file) {
  606. const lastIndex = file.lastIndexOf('.');
  607. const extension = (lastIndex != -1) ? file.substring(lastIndex + 1) : '';
  608. if (this.activeGraph && (extension === 'png' || extension === 'svg')) {
  609. const canvas = this._getElementById('canvas');
  610. const clone = canvas.cloneNode(true);
  611. this.applyStyleSheet(clone, 'view-grapher.css');
  612. clone.setAttribute('id', 'export');
  613. clone.removeAttribute('viewBox');
  614. clone.removeAttribute('width');
  615. clone.removeAttribute('height');
  616. clone.style.removeProperty('opacity');
  617. clone.style.removeProperty('display');
  618. clone.style.removeProperty('width');
  619. clone.style.removeProperty('height');
  620. const background = clone.querySelector('#background');
  621. const origin = clone.querySelector('#origin');
  622. origin.setAttribute('transform', 'translate(0,0) scale(1)');
  623. background.removeAttribute('width');
  624. background.removeAttribute('height');
  625. const parent = canvas.parentElement;
  626. parent.insertBefore(clone, canvas);
  627. const size = clone.getBBox();
  628. parent.removeChild(clone);
  629. parent.removeChild(canvas);
  630. parent.appendChild(canvas);
  631. const delta = (Math.min(size.width, size.height) / 2.0) * 0.1;
  632. const width = Math.ceil(delta + size.width + delta);
  633. const height = Math.ceil(delta + size.height + delta);
  634. origin.setAttribute('transform', 'translate(' + (delta - size.x).toString() + ', ' + (delta - size.y).toString() + ') scale(1)');
  635. clone.setAttribute('width', width);
  636. clone.setAttribute('height', height);
  637. background.setAttribute('width', width);
  638. background.setAttribute('height', height);
  639. background.setAttribute('fill', '#fff');
  640. const data = new XMLSerializer().serializeToString(clone);
  641. if (extension === 'svg') {
  642. const blob = new Blob([ data ], { type: 'image/svg' });
  643. this._host.export(file, blob);
  644. }
  645. if (extension === 'png') {
  646. const image = new Image();
  647. image.onload = () => {
  648. const max = Math.max(width, height);
  649. const scale = Math.min(24000.0 / max, 2.0);
  650. const canvas = this._host.document.createElement('canvas');
  651. canvas.width = Math.ceil(width * scale);
  652. canvas.height = Math.ceil(height * scale);
  653. const context = canvas.getContext('2d');
  654. context.scale(scale, scale);
  655. context.drawImage(image, 0, 0);
  656. canvas.toBlob((blob) => {
  657. if (blob) {
  658. this._host.export(file, blob);
  659. }
  660. else {
  661. const err = new Error();
  662. err.name = 'Error exporting image.';
  663. err.message = 'Image may be too large to render as PNG.';
  664. this._host.exception(err, false);
  665. this._host.error(err.name, err.message);
  666. }
  667. }, 'image/png');
  668. };
  669. image.src = 'data:image/svg+xml;base64,' + this._host.window.btoa(unescape(encodeURIComponent(data)));
  670. }
  671. }
  672. }
  673. showModelProperties() {
  674. if (this._model) {
  675. try {
  676. const modelSidebar = new sidebar.ModelSidebar(this._host, this._model, this.activeGraph);
  677. modelSidebar.on('update-active-graph', (sender, graph) => {
  678. this._updateActiveGraph(graph);
  679. });
  680. const content = modelSidebar.render();
  681. this._sidebar.open(content, 'Model Properties');
  682. }
  683. catch (error) {
  684. const content = " in '" + this._model.identifier + "'.";
  685. if (error && !error.message.endsWith(content) && (error.context === undefined || error.context === true)) {
  686. error.message = error.message.replace(/\.$/, '') + content;
  687. }
  688. this.error(error, 'Error showing model properties.', null);
  689. }
  690. }
  691. }
  692. showNodeProperties(node, input) {
  693. if (node) {
  694. try {
  695. const nodeSidebar = new sidebar.NodeSidebar(this._host, node);
  696. nodeSidebar.on('show-documentation', (/* sender, e */) => {
  697. this.showDocumentation(node.type);
  698. });
  699. nodeSidebar.on('show-graph', (sender, graph) => {
  700. this.pushGraph(graph);
  701. });
  702. nodeSidebar.on('export-tensor', (sender, tensor) => {
  703. const defaultPath = tensor.name ? tensor.name.split('/').join('_').split(':').join('_').split('.').join('_') : 'tensor';
  704. this._host.save('NumPy Array', 'npy', defaultPath, (file) => {
  705. try {
  706. let data_type = tensor.type.dataType;
  707. if (data_type === 'boolean') {
  708. data_type = 'bool';
  709. }
  710. const execution = new python.Execution(null);
  711. const bytes = execution.invoke('io.BytesIO', []);
  712. const dtype = execution.invoke('numpy.dtype', [ data_type ]);
  713. const array = execution.invoke('numpy.asarray', [ tensor.value, dtype ]);
  714. execution.invoke('numpy.save', [ bytes, array ]);
  715. bytes.seek(0);
  716. const blob = new Blob([ bytes.read() ], { type: 'application/octet-stream' });
  717. this._host.export(file, blob);
  718. }
  719. catch (error) {
  720. this.error(error, 'Error saving NumPy tensor.', null);
  721. }
  722. });
  723. });
  724. nodeSidebar.on('error', (sender, error) => {
  725. if (this._model) {
  726. error.message = error.message.replace(/\.$/, '') + " in '" + this._model.identifier + "'.";
  727. }
  728. this.error(error, null, null);
  729. });
  730. if (input) {
  731. nodeSidebar.toggleInput(input.name);
  732. }
  733. this._sidebar.open(nodeSidebar.render(), 'Node Properties');
  734. }
  735. catch (error) {
  736. const content = " in '" + this._model.identifier + "'.";
  737. if (error && !error.message.endsWith(content) && (error.context === undefined || error.context === true)) {
  738. error.message = error.message.replace(/\.$/, '') + content;
  739. }
  740. this.error(error, 'Error showing node properties.', null);
  741. }
  742. }
  743. }
  744. showDocumentation(type) {
  745. if (type && (type.description || type.inputs || type.outputs || type.attributes)) {
  746. if (type.nodes && type.nodes.length > 0) {
  747. this.pushGraph(type);
  748. }
  749. const documentationSidebar = new sidebar.DocumentationSidebar(this._host, type);
  750. documentationSidebar.on('navigate', (sender, e) => {
  751. this._host.openURL(e.link);
  752. });
  753. const title = type.type === 'function' ? 'Function' : 'Documentation';
  754. this._sidebar.push(documentationSidebar.render(), title);
  755. }
  756. }
  757. };
  758. view.Graph = class extends grapher.Graph {
  759. constructor(view, model, compound, options) {
  760. super(compound, options);
  761. this.view = view;
  762. this.model = model;
  763. this._arguments = new Map();
  764. this._nodeKey = 0;
  765. }
  766. createNode(node) {
  767. const value = new view.Node(this, node);
  768. value.name = (this._nodeKey++).toString();
  769. // value.name = node.name;
  770. this.setNode(value);
  771. return value;
  772. }
  773. createInput(input) {
  774. const value = new view.Input(this, input);
  775. value.name = (this._nodeKey++).toString();
  776. this.setNode(value);
  777. return value;
  778. }
  779. createOutput(output) {
  780. const value = new view.Output(this, output);
  781. value.name = (this._nodeKey++).toString();
  782. this.setNode(value);
  783. return value;
  784. }
  785. createArgument(argument) {
  786. const name = argument.name;
  787. if (!this._arguments.has(name)) {
  788. this._arguments.set(name, new view.Argument(this, argument));
  789. }
  790. return this._arguments.get(name);
  791. }
  792. createEdge(from, to) {
  793. const value = new view.Edge(from, to);
  794. return value;
  795. }
  796. add(graph) {
  797. const clusters = new Set();
  798. const clusterParentMap = new Map();
  799. const groups = graph.groups;
  800. if (groups) {
  801. for (const node of graph.nodes) {
  802. if (node.group) {
  803. const path = node.group.split('/');
  804. while (path.length > 0) {
  805. const name = path.join('/');
  806. path.pop();
  807. clusterParentMap.set(name, path.join('/'));
  808. }
  809. }
  810. }
  811. }
  812. for (const input of graph.inputs) {
  813. const viewInput = this.createInput(input);
  814. for (const argument of input.arguments) {
  815. this.createArgument(argument).from(viewInput);
  816. }
  817. }
  818. for (const node of graph.nodes) {
  819. const viewNode = this.createNode(node);
  820. const inputs = node.inputs;
  821. for (const input of inputs) {
  822. for (const argument of input.arguments) {
  823. if (argument.name != '' && !argument.initializer) {
  824. this.createArgument(argument).to(viewNode);
  825. }
  826. }
  827. }
  828. let outputs = node.outputs;
  829. if (node.chain && node.chain.length > 0) {
  830. const chainOutputs = node.chain[node.chain.length - 1].outputs;
  831. if (chainOutputs.length > 0) {
  832. outputs = chainOutputs;
  833. }
  834. }
  835. for (const output of outputs) {
  836. for (const argument of output.arguments) {
  837. if (!argument) {
  838. throw new view.Error("Invalid null argument in '" + this.model.identifier + "'.");
  839. }
  840. if (argument.name != '') {
  841. this.createArgument(argument).from(viewNode);
  842. }
  843. }
  844. }
  845. if (node.controlDependencies && node.controlDependencies.length > 0) {
  846. for (const argument of node.controlDependencies) {
  847. this.createArgument(argument).to(viewNode, true);
  848. }
  849. }
  850. const createCluster = (name) => {
  851. if (!clusters.has(name)) {
  852. this.setNode({ name: name, rx: 5, ry: 5});
  853. clusters.add(name);
  854. const parent = clusterParentMap.get(name);
  855. if (parent) {
  856. createCluster(parent);
  857. this.setParent(name, parent);
  858. }
  859. }
  860. };
  861. if (groups) {
  862. let groupName = node.group;
  863. if (groupName && groupName.length > 0) {
  864. if (!clusterParentMap.has(groupName)) {
  865. const lastIndex = groupName.lastIndexOf('/');
  866. if (lastIndex != -1) {
  867. groupName = groupName.substring(0, lastIndex);
  868. if (!clusterParentMap.has(groupName)) {
  869. groupName = null;
  870. }
  871. }
  872. else {
  873. groupName = null;
  874. }
  875. }
  876. if (groupName) {
  877. createCluster(groupName);
  878. this.setParent(viewNode.name, groupName);
  879. }
  880. }
  881. }
  882. }
  883. for (const output of graph.outputs) {
  884. const viewOutput = this.createOutput(output);
  885. for (const argument of output.arguments) {
  886. this.createArgument(argument).to(viewOutput);
  887. }
  888. }
  889. }
  890. build(document, origin) {
  891. for (const argument of this._arguments.values()) {
  892. argument.build();
  893. }
  894. super.build(document, origin);
  895. }
  896. };
  897. view.Node = class extends grapher.Node {
  898. constructor(context, value) {
  899. super();
  900. this.context = context;
  901. this.value = value;
  902. view.Node.counter = view.Node.counter || 0;
  903. this.id = 'node-' + (value.name ? 'name-' + value.name : 'id-' + (view.Node.counter++).toString());
  904. this._add(this.value);
  905. }
  906. get class() {
  907. return 'graph-node';
  908. }
  909. get inputs() {
  910. return this.value.inputs;
  911. }
  912. get outputs() {
  913. return this.value.outputs;
  914. }
  915. _add(node) {
  916. const header = this.header();
  917. const styles = [ 'node-item-type' ];
  918. const type = node.type;
  919. const category = type && type.category ? type.category : '';
  920. if (category) {
  921. styles.push('node-item-type-' + category.toLowerCase());
  922. }
  923. if (typeof type.name !== 'string' || !type.name.split) { // #416
  924. const identifier = this.context.model && this.context.model.identifier ? this.context.model.identifier : '?';
  925. throw new view.Error("Unsupported node type '" + JSON.stringify(type.name) + "' in '" + identifier + "'.");
  926. }
  927. const content = this.context.view.options.names && (node.name || node.location) ? (node.name || node.location) : type.name.split('.').pop();
  928. const tooltip = this.context.view.options.names && (node.name || node.location) ? type.name : (node.name || node.location);
  929. const title = header.add(null, styles, content, tooltip);
  930. title.on('click', () => this.context.view.showNodeProperties(node, null));
  931. if (node.type.nodes && node.type.nodes.length > 0) {
  932. const definition = header.add(null, styles, '\u0192', 'Show Function Definition');
  933. definition.on('click', () => this.context.view.pushGraph(node.type));
  934. }
  935. if (node.nodes) {
  936. // this._expand = header.add(null, styles, '+', null);
  937. // this._expand.on('click', () => this.toggle());
  938. }
  939. const initializers = [];
  940. let hiddenInitializers = false;
  941. if (this.context.view.options.initializers) {
  942. for (const input of node.inputs) {
  943. if (input.visible && input.arguments.length === 1 && input.arguments[0].initializer != null) {
  944. initializers.push(input);
  945. }
  946. if ((!input.visible || input.arguments.length > 1) &&
  947. input.arguments.some((argument) => argument.initializer != null)) {
  948. hiddenInitializers = true;
  949. }
  950. }
  951. }
  952. let sortedAttributes = [];
  953. const attributes = node.attributes || [];
  954. if (this.context.view.options.attributes) {
  955. sortedAttributes = attributes.filter((attribute) => attribute.visible).slice();
  956. }
  957. sortedAttributes.sort((a, b) => {
  958. const au = a.name.toUpperCase();
  959. const bu = b.name.toUpperCase();
  960. return (au < bu) ? -1 : (au > bu) ? 1 : 0;
  961. });
  962. if (initializers.length > 0 || hiddenInitializers || sortedAttributes.length > 0) {
  963. const list = this.list();
  964. list.on('click', () => this.context.view.showNodeProperties(node));
  965. for (const initializer of initializers) {
  966. const argument = initializer.arguments[0];
  967. const type = argument.type;
  968. let shape = '';
  969. let separator = '';
  970. if (type && type.shape && type.shape.dimensions && Array.isArray(type.shape.dimensions)) {
  971. shape = '\u3008' + type.shape.dimensions.map((d) => d ? d : '?').join('\u00D7') + '\u3009';
  972. if (type.shape.dimensions.length === 0 && argument.initializer && !argument.initializer.state) {
  973. try {
  974. shape = argument.initializer.toString();
  975. if (shape && shape.length > 10) {
  976. shape = shape.substring(0, 10) + '\u2026';
  977. }
  978. separator = ' = ';
  979. }
  980. catch (err) {
  981. let type = '?';
  982. try {
  983. type = argument.initializer.type.toString();
  984. }
  985. catch (error) {
  986. // continue regardless of error
  987. }
  988. const identifier = this.context.view.model && this.context.view.model.identifier ? this.context.view.model.identifier : '?';
  989. throw new view.Error("Failed to render tensor of type '" + type + "' in '" + identifier + "' (" + err.message + ").");
  990. }
  991. }
  992. }
  993. list.add(argument.name ? 'initializer-' + argument.name : '', initializer.name, shape, type ? type.toString() : '', separator);
  994. }
  995. if (hiddenInitializers) {
  996. list.add(null, '\u3008' + '\u2026' + '\u3009', '', null, '');
  997. }
  998. for (const attribute of sortedAttributes) {
  999. if (attribute.visible) {
  1000. let value = new sidebar.Formatter(attribute.value, attribute.type).toString();
  1001. if (value && value.length > 25) {
  1002. value = value.substring(0, 25) + '\u2026';
  1003. }
  1004. list.add(null, attribute.name, value, attribute.type, ' = ');
  1005. }
  1006. }
  1007. }
  1008. if (Array.isArray(node.chain) && node.chain.length > 0) {
  1009. for (const innerNode of node.chain) {
  1010. this._add(innerNode);
  1011. }
  1012. }
  1013. if (node.inner) {
  1014. this._add(node.inner);
  1015. }
  1016. if (node.nodes) {
  1017. this.canvas = this.canvas();
  1018. }
  1019. }
  1020. toggle() {
  1021. this._expand.content = '-';
  1022. this._graph = new view.Graph(this.context.view, this.context.model, false, {});
  1023. this._graph.add(this.value);
  1024. // const document = this.element.ownerDocument;
  1025. // const parent = this.element.parentElement;
  1026. // this._graph.build(document, parent);
  1027. // this._graph.update();
  1028. this.canvas.width = 300;
  1029. this.canvas.height = 300;
  1030. this.layout();
  1031. this.context.update();
  1032. }
  1033. };
  1034. view.Input = class extends grapher.Node {
  1035. constructor(context, value) {
  1036. super();
  1037. this.context = context;
  1038. this.value = value;
  1039. view.Input.counter = view.Input.counter || 0;
  1040. const types = value.arguments.map((argument) => argument.type || '').join('\n');
  1041. let name = value.name || '';
  1042. if (name.length > 16) {
  1043. name = name.split('/').pop();
  1044. }
  1045. const header = this.header();
  1046. const title = header.add(null, [ 'graph-item-input' ], name, types);
  1047. title.on('click', () => this.context.view.showModelProperties());
  1048. this.id = 'input-' + (name ? 'name-' + name : 'id-' + (view.Input.counter++).toString());
  1049. }
  1050. get class() {
  1051. return 'graph-input';
  1052. }
  1053. get inputs() {
  1054. return [];
  1055. }
  1056. get outputs() {
  1057. return [ this.value ];
  1058. }
  1059. };
  1060. view.Output = class extends grapher.Node {
  1061. constructor(context, value) {
  1062. super();
  1063. this.context = context;
  1064. this.value = value;
  1065. const types = value.arguments.map((argument) => argument.type || '').join('\n');
  1066. let name = value.name || '';
  1067. if (name.length > 16) {
  1068. name = name.split('/').pop();
  1069. }
  1070. const header = this.header();
  1071. const title = header.add(null, [ 'graph-item-output' ], name, types);
  1072. title.on('click', () => this.context.view.showModelProperties());
  1073. }
  1074. get inputs() {
  1075. return [ this.value ];
  1076. }
  1077. get outputs() {
  1078. return [];
  1079. }
  1080. };
  1081. view.Argument = class {
  1082. constructor(context, argument) {
  1083. this.context = context;
  1084. this._argument = argument;
  1085. }
  1086. from(node) {
  1087. this._from = node;
  1088. }
  1089. to(node, controlDependency) {
  1090. this._to = this._to || [];
  1091. if (controlDependency) {
  1092. this._controlDependencies = this._controlDependencies || new Set();
  1093. this._controlDependencies.add(this._to.length);
  1094. }
  1095. this._to.push(node);
  1096. }
  1097. build() {
  1098. this._edges = this._edges || [];
  1099. if (this._from && this._to) {
  1100. for (let i = 0; i < this._to.length; i++) {
  1101. const to = this._to[i];
  1102. let content = '';
  1103. const type = this._argument.type;
  1104. if (type &&
  1105. type.shape &&
  1106. type.shape.dimensions &&
  1107. type.shape.dimensions.length > 0 &&
  1108. type.shape.dimensions.every((dim) => !dim || Number.isInteger(dim) || dim instanceof base.Int64 || (typeof dim === 'string'))) {
  1109. content = type.shape.dimensions.map((dim) => dim || '?').join('\u00D7');
  1110. content = content.length > 16 ? '' : content;
  1111. }
  1112. if (this.context.view.options.names) {
  1113. content = this._argument.name.split('\n').shift(); // custom argument id
  1114. }
  1115. const edge = this.context.createEdge(this._from, to);
  1116. edge.v = this._from.name;
  1117. edge.w = to.name;
  1118. if (content) {
  1119. edge.label = content;
  1120. }
  1121. edge.id = 'edge-' + this._argument.name;
  1122. if (this._controlDependencies && this._controlDependencies.has(i)) {
  1123. edge.class = 'edge-path-control-dependency';
  1124. }
  1125. this.context.setEdge(edge);
  1126. this._edges.push(edge);
  1127. }
  1128. }
  1129. }
  1130. };
  1131. view.Edge = class extends grapher.Edge {
  1132. constructor(from, to) {
  1133. super(from, to);
  1134. }
  1135. get minlen() {
  1136. if (this.from.inputs.every((parameter) => parameter.arguments.every((argument) => argument.initializer))) {
  1137. return 2;
  1138. }
  1139. return 1;
  1140. }
  1141. };
  1142. view.ModelContext = class {
  1143. constructor(context) {
  1144. this._context = context;
  1145. this._tags = new Map();
  1146. this._content = new Map();
  1147. let stream = context.stream;
  1148. const entries = context.entries;
  1149. if (!stream && entries && entries.size > 0) {
  1150. this._entries = entries;
  1151. this._format = '';
  1152. }
  1153. else {
  1154. this._entries = new Map();
  1155. const entry = context instanceof view.EntryContext;
  1156. const identifier = context.identifier;
  1157. try {
  1158. const archive = gzip.Archive.open(stream);
  1159. if (archive) {
  1160. this._entries = archive.entries;
  1161. this._format = 'gzip';
  1162. if (this._entries.size === 1) {
  1163. stream = this._entries.values().next().value;
  1164. }
  1165. }
  1166. }
  1167. catch (error) {
  1168. if (!entry) {
  1169. const message = error && error.message ? error.message : error.toString();
  1170. throw new view.ArchiveError(message.replace(/\.$/, '') + " in '" + identifier + "'.");
  1171. }
  1172. }
  1173. try {
  1174. const formats = new Map([ [ 'zip', zip ], [ 'tar', tar ] ]);
  1175. for (const pair of formats) {
  1176. const format = pair[0];
  1177. const module = pair[1];
  1178. const archive = module.Archive.open(stream);
  1179. if (archive) {
  1180. this._entries = archive.entries;
  1181. this._format = format;
  1182. break;
  1183. }
  1184. }
  1185. }
  1186. catch (error) {
  1187. if (!entry) {
  1188. const message = error && error.message ? error.message : error.toString();
  1189. throw new view.ArchiveError(message.replace(/\.$/, '') + " in '" + identifier + "'.");
  1190. }
  1191. }
  1192. }
  1193. }
  1194. get identifier() {
  1195. return this._context.identifier;
  1196. }
  1197. get stream() {
  1198. return this._context.stream;
  1199. }
  1200. request(file, encoding, base) {
  1201. return this._context.request(file, encoding, base);
  1202. }
  1203. require(id) {
  1204. return this._context.require(id);
  1205. }
  1206. exception(error, fatal) {
  1207. this._context.exception(error, fatal);
  1208. }
  1209. entries(format) {
  1210. if (format !== undefined && format !== this._format) {
  1211. return new Map();
  1212. }
  1213. return this._entries;
  1214. }
  1215. open(type) {
  1216. if (!this._content.has(type)) {
  1217. this._content.set(type, undefined);
  1218. const stream = this.stream;
  1219. const position = stream.position;
  1220. const signatures = [
  1221. [ 0x89, 0x48, 0x44, 0x46, 0x0D, 0x0A, 0x1A, 0x0A ], // HDF5
  1222. [ 0x80, undefined, 0x8a, 0x0a, 0x6c, 0xfc, 0x9c, 0x46, 0xf9, 0x20, 0x6a, 0xa8, 0x50, 0x19 ] // PyTorch
  1223. ];
  1224. const skip =
  1225. signatures.some((signature) => signature.length <= stream.length && stream.peek(signature.length).every((value, index) => signature[index] === undefined || signature[index] === value)) ||
  1226. Array.from(this._tags).some((pair) => pair[0] !== 'flatbuffers' && pair[1].size > 0) ||
  1227. Array.from(this._content.values()).some((obj) => obj !== undefined);
  1228. if (!skip) {
  1229. switch (type) {
  1230. case 'json': {
  1231. try {
  1232. const reader = json.TextReader.open(this.stream);
  1233. if (reader) {
  1234. const obj = reader.read();
  1235. this._content.set(type, obj);
  1236. }
  1237. }
  1238. catch (err) {
  1239. // continue regardless of error
  1240. }
  1241. break;
  1242. }
  1243. case 'json.gz': {
  1244. try {
  1245. const archive = gzip.Archive.open(this.stream);
  1246. if (archive) {
  1247. const entries = archive.entries;
  1248. if (entries.size === 1) {
  1249. const stream = entries.values().next().value;
  1250. const reader = json.TextReader.open(stream);
  1251. if (reader) {
  1252. const obj = reader.read();
  1253. this._content.set(type, obj);
  1254. }
  1255. }
  1256. }
  1257. }
  1258. catch (err) {
  1259. // continue regardless of error
  1260. }
  1261. break;
  1262. }
  1263. case 'pkl': {
  1264. let unpickler = null;
  1265. try {
  1266. if (stream.length > 2) {
  1267. const zlib = (stream) => {
  1268. const buffer = stream.peek(2);
  1269. if (buffer[0] === 0x78) {
  1270. const check = (buffer[0] << 8) + buffer[1];
  1271. if (check % 31 === 0) {
  1272. const archive = zip.Archive.open(stream);
  1273. return archive.entries.get('');
  1274. }
  1275. }
  1276. return stream;
  1277. };
  1278. unpickler = python.Unpickler.open(zlib(stream));
  1279. }
  1280. }
  1281. catch (err) {
  1282. // continue regardless of error
  1283. }
  1284. if (unpickler) {
  1285. const execution = new python.Execution(null, (error, fatal) => {
  1286. const message = error && error.message ? error.message : error.toString();
  1287. this.exception(new view.Error(message.replace(/\.$/, '') + " in '" + this.identifier + "'."), fatal);
  1288. });
  1289. const persistent_load = (saved_id) => {
  1290. return saved_id;
  1291. };
  1292. const obj = unpickler.load((name, args) => execution.invoke(name, args), persistent_load);
  1293. this._content.set(type, obj);
  1294. }
  1295. break;
  1296. }
  1297. default: {
  1298. throw new view.Error("Unsupported open format type '" + type + "'.");
  1299. }
  1300. }
  1301. }
  1302. if (stream.position !== position) {
  1303. stream.seek(0);
  1304. }
  1305. }
  1306. return this._content.get(type);
  1307. }
  1308. tags(type) {
  1309. if (!this._tags.has(type)) {
  1310. let tags = new Map();
  1311. const stream = this.stream;
  1312. const position = stream.position;
  1313. if (stream) {
  1314. const signatures = [
  1315. [ 0x89, 0x48, 0x44, 0x46, 0x0D, 0x0A, 0x1A, 0x0A ], // HDF5
  1316. [ 0x80, undefined, 0x8a, 0x0a, 0x6c, 0xfc, 0x9c, 0x46, 0xf9, 0x20, 0x6a, 0xa8, 0x50, 0x19 ], // PyTorch
  1317. [ 0x50, 0x4b ], // Zip
  1318. [ 0x1f, 0x8b ] // Gzip
  1319. ];
  1320. const skip =
  1321. signatures.some((signature) => signature.length <= stream.length && stream.peek(signature.length).every((value, index) => signature[index] === undefined || signature[index] === value)) ||
  1322. (Array.from(this._tags).some((pair) => pair[0] !== 'flatbuffers' && pair[1].size > 0) && type !== 'pb+') ||
  1323. Array.from(this._content.values()).some((obj) => obj !== undefined);
  1324. if (!skip) {
  1325. try {
  1326. switch (type) {
  1327. case 'pbtxt': {
  1328. const reader = protobuf.TextReader.open(stream);
  1329. tags = reader ? reader.signature() : tags;
  1330. break;
  1331. }
  1332. case 'pb': {
  1333. const reader = protobuf.BinaryReader.open(stream);
  1334. tags = reader.signature();
  1335. break;
  1336. }
  1337. case 'pb+': {
  1338. const reader = protobuf.BinaryReader.open(stream);
  1339. tags = reader.decode();
  1340. break;
  1341. }
  1342. case 'flatbuffers': {
  1343. if (stream.length >= 8) {
  1344. const buffer = stream.peek(Math.min(32, stream.length));
  1345. const reader = flatbuffers.BinaryReader.open(buffer);
  1346. const identifier = reader.identifier;
  1347. if (identifier.length > 0) {
  1348. tags.set('file_identifier', identifier);
  1349. }
  1350. }
  1351. break;
  1352. }
  1353. case 'xml': {
  1354. const reader = xml.TextReader.open(stream);
  1355. if (reader) {
  1356. const document = reader.peek();
  1357. const element = document.documentElement;
  1358. const namespaceURI = element.namespaceURI;
  1359. const localName = element.localName;
  1360. const name = namespaceURI ? namespaceURI + ':' + localName : localName;
  1361. tags.set(name, element);
  1362. }
  1363. break;
  1364. }
  1365. default: {
  1366. throw new view.Error("Unsupported tags format type '" + type + "'.");
  1367. }
  1368. }
  1369. }
  1370. catch (error) {
  1371. tags.clear();
  1372. }
  1373. }
  1374. }
  1375. if (stream.position !== position) {
  1376. stream.seek(position);
  1377. }
  1378. this._tags.set(type, tags);
  1379. }
  1380. return this._tags.get(type);
  1381. }
  1382. metadata(name) {
  1383. return base.Metadata.open(this, name);
  1384. }
  1385. };
  1386. view.EntryContext = class {
  1387. constructor(host, entries, rootFolder, identifier, stream) {
  1388. this._host = host;
  1389. this._entries = new Map();
  1390. if (entries) {
  1391. for (const entry of entries) {
  1392. if (entry[0].startsWith(rootFolder)) {
  1393. const name = entry[0].substring(rootFolder.length);
  1394. this._entries.set(name, entry[1]);
  1395. }
  1396. }
  1397. }
  1398. this._identifier = identifier.substring(rootFolder.length);
  1399. this._stream = stream;
  1400. }
  1401. get identifier() {
  1402. return this._identifier;
  1403. }
  1404. get stream() {
  1405. return this._stream;
  1406. }
  1407. request(file, encoding, base) {
  1408. if (base === undefined) {
  1409. const stream = this._entries.get(file);
  1410. if (!stream) {
  1411. return Promise.reject(new Error('File not found.'));
  1412. }
  1413. if (encoding) {
  1414. const decoder = new TextDecoder(encoding);
  1415. const buffer = stream.peek();
  1416. const value = decoder.decode(buffer);
  1417. return Promise.resolve(value);
  1418. }
  1419. return Promise.resolve(stream);
  1420. }
  1421. return this._host.request(file, encoding, base);
  1422. }
  1423. require(id) {
  1424. return this._host.require(id);
  1425. }
  1426. exception(error, fatal) {
  1427. this._host.exception(error, fatal);
  1428. }
  1429. };
  1430. view.ArchiveError = class extends Error {
  1431. constructor(message) {
  1432. super(message);
  1433. this.name = 'Error loading archive.';
  1434. }
  1435. };
  1436. view.ModelFactoryService = class {
  1437. constructor(host) {
  1438. this._host = host;
  1439. this._extensions = new Set([ '.zip', '.tar', '.tar.gz', '.tgz', '.gz' ]);
  1440. this._factories = [];
  1441. this.register('./pytorch', [ '.pt', '.pth', '.ptl', '.pt1', '.pyt', '.pyth', '.pkl', '.pickle', '.h5', '.t7', '.model', '.dms', '.tar', '.ckpt', '.chkpt', '.tckpt', '.bin', '.pb', '.zip', '.nn', '.torchmodel', '.torchscript', '.pytorch', '.ot', '.params', '.trt' ], [ '.model' ]);
  1442. this.register('./onnx', [ '.onnx', '.onn', '.pb', '.onnxtxt', '.pbtxt', '.prototxt', '.txt', '.model', '.pt', '.pth', '.pkl', '.ort', '.ort.onnx', 'onnxmodel' ]);
  1443. this.register('./mxnet', [ '.json', '.params' ], [ '.mar'] );
  1444. this.register('./coreml', [ '.mlmodel', '.bin', 'manifest.json', 'metadata.json', 'featuredescriptions.json', '.pb' ], [ '.mlpackage' ]);
  1445. this.register('./caffe', [ '.caffemodel', '.pbtxt', '.prototxt', '.pt', '.txt' ]);
  1446. this.register('./caffe2', [ '.pb', '.pbtxt', '.prototxt' ]);
  1447. this.register('./torch', [ '.t7', '.net' ]);
  1448. this.register('./tflite', [ '.tflite', '.lite', '.tfl', '.bin', '.pb', '.tmfile', '.h5', '.model', '.json', '.txt' ]);
  1449. this.register('./circle', [ '.circle' ]);
  1450. this.register('./tf', [ '.pb', '.meta', '.pbtxt', '.prototxt', '.txt', '.pt', '.json', '.index', '.ckpt', '.graphdef', '.pbmm', /.data-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9]$/, /^events.out.tfevents./ ], [ '.zip' ]);
  1451. this.register('./mediapipe', [ '.pbtxt' ]);
  1452. this.register('./uff', [ '.uff', '.pb', '.pbtxt', '.uff.txt', '.trt', '.engine' ]);
  1453. this.register('./tensorrt', [ '.trt', '.engine', '.model', '.txt', '.uff', '.pb', '.tmfile', '.onnx', '.pth', '.dnn', '.plan' ]);
  1454. this.register('./numpy', [ '.npz', '.npy', '.pkl', '.pickle' ]);
  1455. this.register('./lasagne', [ '.pkl', '.pickle', '.joblib', '.model', '.pkl.z', '.joblib.z' ]);
  1456. this.register('./lightgbm', [ '.txt', '.pkl', '.model' ]);
  1457. this.register('./keras', [ '.h5', '.hd5', '.hdf5', '.keras', '.json', '.cfg', '.model', '.pb', '.pth', '.weights', '.pkl', '.lite', '.tflite', '.ckpt' ], [ '.zip' ]);
  1458. this.register('./sklearn', [ '.pkl', '.pickle', '.joblib', '.model', '.meta', '.pb', '.pt', '.h5', '.pkl.z', '.joblib.z' ]);
  1459. this.register('./pickle', [ '.pkl', '.pickle', '.joblib', '.model', '.meta', '.pb', '.pt', '.h5', '.pkl.z', '.joblib.z', '.pdstates' ]);
  1460. this.register('./cntk', [ '.model', '.cntk', '.cmf', '.dnn' ]);
  1461. this.register('./paddle', [ '.pdmodel', '.pdiparams', '.pdparams', '.pdopt', '.paddle', '__model__', '.__model__', '.pbtxt', '.txt', '.tar', '.tar.gz', '.nb' ]);
  1462. this.register('./bigdl', [ '.model', '.bigdl' ]);
  1463. this.register('./darknet', [ '.cfg', '.model', '.txt', '.weights' ]);
  1464. this.register('./weka', [ '.model' ]);
  1465. this.register('./rknn', [ '.rknn', '.nb', '.onnx' ]);
  1466. this.register('./dlc', [ '.dlc', 'model', '.params' ]);
  1467. this.register('./armnn', [ '.armnn', '.json' ]);
  1468. this.register('./mnn', ['.mnn']);
  1469. this.register('./ncnn', [ '.param', '.bin', '.cfg.ncnn', '.weights.ncnn', '.ncnnmodel' ]);
  1470. this.register('./tnn', [ '.tnnproto', '.tnnmodel' ]);
  1471. this.register('./tengine', ['.tmfile']);
  1472. this.register('./mslite', [ '.ms']);
  1473. this.register('./barracuda', [ '.nn' ]);
  1474. this.register('./dnn', [ '.dnn' ]);
  1475. this.register('./xmodel', [ '.xmodel' ]);
  1476. this.register('./kmodel', [ '.kmodel' ]);
  1477. this.register('./flux', [ '.bson' ]);
  1478. this.register('./dl4j', [ '.json', '.bin' ]);
  1479. this.register('./openvino', [ '.xml', '.bin' ]);
  1480. this.register('./mlnet', [ '.zip' ]);
  1481. this.register('./acuity', [ '.json' ]);
  1482. this.register('./imgdnn', [ '.dnn', 'params', '.json' ]);
  1483. this.register('./flax', [ '.msgpack' ]);
  1484. this.register('./om', [ '.om', '.onnx', '.pb', '.engine' ]);
  1485. this.register('./nnabla', [ '.nntxt' ], [ '.nnp' ]);
  1486. this.register('./cambricon', [ '.cambricon' ]);
  1487. this.register('./message', [ '.json']);
  1488. }
  1489. register(id, factories, containers) {
  1490. for (const extension of factories) {
  1491. this._factories.push({ extension: extension, id: id });
  1492. this._extensions.add(extension);
  1493. }
  1494. for (const extension of containers || []) {
  1495. this._extensions.add(extension);
  1496. }
  1497. }
  1498. open(context) {
  1499. return this._openSignature(context).then((context) => {
  1500. const modelContext = new view.ModelContext(context);
  1501. /* eslint-disable consistent-return */
  1502. return this._openContext(modelContext).then((model) => {
  1503. if (model) {
  1504. return model;
  1505. }
  1506. const entries = modelContext.entries();
  1507. if (entries && entries.size > 0) {
  1508. return this._openEntries(entries).then((context) => {
  1509. if (context) {
  1510. return this._openContext(context);
  1511. }
  1512. this._unsupported(modelContext);
  1513. });
  1514. }
  1515. this._unsupported(modelContext);
  1516. });
  1517. /* eslint-enable consistent-return */
  1518. });
  1519. }
  1520. _unsupported(context) {
  1521. const identifier = context.identifier;
  1522. const extension = identifier.split('.').pop().toLowerCase();
  1523. const stream = context.stream;
  1524. for (const module of [ zip, tar, gzip ]) {
  1525. let archive = null;
  1526. try {
  1527. archive = module.Archive.open(stream);
  1528. }
  1529. catch (error) {
  1530. // continue regardless of error
  1531. }
  1532. if (archive) {
  1533. throw new view.Error("Archive contains no model files in '" + identifier + "'.", true);
  1534. }
  1535. }
  1536. const skip = () => {
  1537. const knownUnsupportedIdentifiers = new Set([
  1538. 'natives_blob.bin',
  1539. 'v8_context_snapshot.bin',
  1540. 'snapshot_blob.bin',
  1541. 'image_net_labels.json',
  1542. 'package.json',
  1543. 'models.json',
  1544. 'LICENSE.meta',
  1545. 'input_0.pb',
  1546. 'output_0.pb'
  1547. ]);
  1548. return knownUnsupportedIdentifiers.has(context.identifier);
  1549. };
  1550. const json = () => {
  1551. const obj = context.open('json');
  1552. if (obj) {
  1553. const formats = [
  1554. { name: 'Netron metadata', tags: [ '[].name', '[].schema' ] },
  1555. { name: 'Netron metadata', tags: [ '[].name', '[].attributes' ] },
  1556. { name: 'Netron metadata', tags: [ '[].name', '[].category' ] },
  1557. { name: 'Darkflow metadata', tags: [ 'net', 'type', 'model' ] },
  1558. { name: 'keras-yolo2 configuration', tags: [ 'model', 'train', 'valid' ] },
  1559. { name: 'Vulkan SwiftShader ICD manifest', tags: [ 'file_format_version', 'ICD' ] },
  1560. { name: 'DeepLearningExamples configuration', tags: [ 'attention_probs_dropout_prob', 'hidden_act', 'hidden_dropout_prob', 'hidden_size', ] },
  1561. { name: 'NuGet assets', tags: [ 'version', 'targets', 'packageFolders' ] },
  1562. { name: 'NuGet data', tags: [ 'format', 'restore', 'projects' ] },
  1563. { name: 'NPM package', tags: [ 'name', 'version', 'dependencies' ] },
  1564. { name: 'NetworkX adjacency_data', tags: [ 'directed', 'graph', 'nodes' ] },
  1565. { name: 'Waifu2x data', tags: [ 'name', 'arch_name', 'channels' ] },
  1566. { name: 'Waifu2x data', tags: [ '[].nInputPlane', '[].nOutputPlane', '[].weight', '[].bias' ] },
  1567. { name: 'Brain.js data', tags: [ 'type', 'sizes', 'layers' ] },
  1568. { name: 'Custom Vision metadata', tags: [ 'CustomVision.Metadata.Version' ] },
  1569. { name: 'W&B metadata', tags: [ 'program', 'host', 'executable' ] }
  1570. ];
  1571. const match = (obj, tag) => {
  1572. if (tag.startsWith('[].')) {
  1573. tag = tag.substring(3);
  1574. return (Array.isArray(obj) && obj.some((item) => Object.prototype.hasOwnProperty.call(item, tag)));
  1575. }
  1576. return Object.prototype.hasOwnProperty.call(obj, tag);
  1577. };
  1578. for (const format of formats) {
  1579. if (format.tags.every((tag) => match(obj, tag))) {
  1580. throw new view.Error('Invalid file content. File contains ' + format.name + '.', true);
  1581. }
  1582. }
  1583. const content = JSON.stringify(obj).substring(0, 100).replace(/\s/, '').substr(0, 48) + '...';
  1584. throw new view.Error("Unsupported JSON content '" + (content.length > 64 ? content.substring(0, 100) + '...' : content) + "' for extension '." + extension + "' in '" + identifier + "'.", !skip());
  1585. }
  1586. };
  1587. const pbtxt = () => {
  1588. const formats = [
  1589. { name: 'ImageNet LabelMap data', tags: [ 'entry', 'entry.target_class' ] },
  1590. { name: 'StringIntLabelMapProto data', tags: [ 'item', 'item.id', 'item.name' ] },
  1591. { name: 'caffe.LabelMap data', tags: [ 'item', 'item.name', 'item.label' ] },
  1592. { name: 'Triton Inference Server configuration', tags: [ 'name', 'platform', 'input', 'output' ] },
  1593. { name: 'TensorFlow OpList data', tags: [ 'op', 'op.name', 'op.input_arg' ] },
  1594. { name: 'vitis.ai.proto.DpuModelParamList data', tags: [ 'model', 'model.name', 'model.kernel' ] },
  1595. { name: 'object_detection.protos.DetectionModel data', tags: [ 'model', 'model.ssd' ] },
  1596. { name: 'object_detection.protos.DetectionModel data', tags: [ 'model', 'model.faster_rcnn' ] },
  1597. { name: 'tensorflow.CheckpointState data', tags: [ 'model_checkpoint_path', 'all_model_checkpoint_paths' ] },
  1598. { name: 'apollo.perception.camera.traffic_light.detection.DetectionParam data', tags: [ 'min_crop_size', 'crop_method' ] },
  1599. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: [ 'caffe_ssd' ] }, // https://github.com/TexasInstruments/edgeai-mmdetection/blob/master/mmdet/utils/proto/mmdet_meta_arch.proto
  1600. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: [ 'tf_od_api_ssd' ] },
  1601. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: [ 'tidl_ssd' ] },
  1602. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: [ 'tidl_faster_rcnn' ] },
  1603. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: [ 'tidl_yolo' ] },
  1604. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: [ 'tidl_retinanet' ] },
  1605. { name: 'domi.InsertNewOps data', tags: [ 'aipp_op' ] } // https://github.com/Ascend/parser/blob/development/parser/proto/insert_op.proto
  1606. ];
  1607. const tags = context.tags('pbtxt');
  1608. if (tags.size > 0) {
  1609. for (const format of formats) {
  1610. if (format.tags.every((tag) => tags.has(tag))) {
  1611. throw new view.Error('Invalid file content. File contains ' + format.name + '.', true);
  1612. }
  1613. }
  1614. const entries = [];
  1615. entries.push(...Array.from(tags).filter((pair) => pair[0].toString().indexOf('.') === -1));
  1616. entries.push(...Array.from(tags).filter((pair) => pair[0].toString().indexOf('.') !== -1));
  1617. const content = entries.map((pair) => pair[1] === true ? pair[0] : pair[0] + ':' + JSON.stringify(pair[1])).join(',');
  1618. throw new view.Error("Unsupported Protocol Buffers text content '" + (content.length > 64 ? content.substring(0, 100) + '...' : content) + "' for extension '." + extension + "' in '" + identifier + "'.", !skip());
  1619. }
  1620. };
  1621. const pb = () => {
  1622. const tags = context.tags('pb+');
  1623. if (Object.keys(tags).length > 0) {
  1624. const formats = [
  1625. { name: 'sentencepiece.ModelProto data', tags: [[1,[[1,2],[2,5],[3,0]]],[2,[[1,2],[2,2],[3,0],[4,0],[5,2],[6,0],[7,2],[10,5],[16,0],[40,0],[41,0],[42,0],[43,0]]],[3,[]],[4,[]],[5,[]]] },
  1626. { name: 'mediapipe.BoxDetectorIndex data', 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]] },
  1627. { name: 'third_party.tensorflow.python.keras.protobuf.SavedMetadata data', tags: [[1,[[1,[[1,0],[2,0]]],[2,0],[3,2],[4,2],[5,2]]]] },
  1628. { name: 'pblczero.Net data', tags: [[1,5],[2,2],[3,[[1,0],[2,0],[3,0]],[10,[[1,[]],[2,[]],[3,[]],[4,[]],[5,[]],[6,[]]]],[11,[]]]] } // https://github.com/LeelaChessZero/lczero-common/blob/master/proto/net.proto
  1629. ];
  1630. const match = (tags, schema) => {
  1631. for (const pair of schema) {
  1632. const key = pair[0];
  1633. const inner = pair[1];
  1634. const value = tags[key];
  1635. if (value === undefined) {
  1636. continue;
  1637. }
  1638. if (inner === false) {
  1639. return false;
  1640. }
  1641. if (Array.isArray(inner)) {
  1642. if (typeof value !== 'object' || !match(value, inner)) {
  1643. return false;
  1644. }
  1645. }
  1646. else if (inner !== value) {
  1647. if (inner === 2 && !Array.isArray(value) && Object(value) === (value) && Object.keys(value).length === 0) {
  1648. return true;
  1649. }
  1650. return false;
  1651. }
  1652. }
  1653. return true;
  1654. };
  1655. const tags = context.tags('pb+');
  1656. for (const format of formats) {
  1657. if (match(tags, format.tags)) {
  1658. throw new view.Error('Invalid file content. File contains ' + format.name + '.', true);
  1659. }
  1660. }
  1661. const format = (tags) => {
  1662. const content = Object.entries(tags).map((pair) => {
  1663. const key = pair[0];
  1664. const value = pair[1];
  1665. return key.toString() + ':' + (Object(value) === value ? '{' + format(value) + '}' : value.toString());
  1666. });
  1667. return content.join(',');
  1668. };
  1669. const content = format(tags);
  1670. throw new view.Error("Unsupported Protocol Buffers content '" + (content.length > 64 ? content.substring(0, 100) + '...' : content) + "' for extension '." + extension + "' in '" + identifier + "'.", !skip());
  1671. }
  1672. };
  1673. const flatbuffers = () => {
  1674. const tags = context.tags('flatbuffers');
  1675. if (tags.has('file_identifier')) {
  1676. const file_identifier = tags.get('file_identifier');
  1677. const formats = [
  1678. { name: 'onnxruntime.experimental.fbs.InferenceSession data', identifier: 'ORTM' },
  1679. { name: 'tflite.Model data', identifier: 'TFL3' },
  1680. { name: 'FlatBuffers ENNC data', identifier: 'ENNC' },
  1681. ];
  1682. for (const format of formats) {
  1683. if (file_identifier === format.identifier) {
  1684. throw new view.Error('Invalid file content. File contains ' + format.name + '.', true);
  1685. }
  1686. }
  1687. }
  1688. };
  1689. const xml = () => {
  1690. const tags = context.tags('xml');
  1691. if (tags.size > 0) {
  1692. const formats = [
  1693. { name: 'OpenCV storage data', tags: [ 'opencv_storage' ] },
  1694. { name: 'XHTML markup', tags: [ 'http://www.w3.org/1999/xhtml:html' ]}
  1695. ];
  1696. for (const format of formats) {
  1697. if (format.tags.some((tag) => tags.has(tag))) {
  1698. throw new view.Error('Invalid file content. File contains ' + format.name + '.', true);
  1699. }
  1700. }
  1701. throw new view.Error("Unsupported XML content '" + tags.keys().next().value + "' in '" + identifier + "'.", !skip());
  1702. }
  1703. };
  1704. const unknown = () => {
  1705. stream.seek(0);
  1706. const buffer = stream.peek(Math.min(16, stream.length));
  1707. const bytes = Array.from(buffer).map((c) => (c < 16 ? '0' : '') + c.toString(16)).join('');
  1708. const content = stream.length > 268435456 ? '(' + bytes + ') [' + stream.length.toString() + ']': '(' + bytes + ')';
  1709. throw new view.Error("Unsupported file content " + content + " for extension '." + extension + "' in '" + identifier + "'.", !skip());
  1710. };
  1711. json();
  1712. pbtxt();
  1713. pb();
  1714. flatbuffers();
  1715. xml();
  1716. unknown();
  1717. }
  1718. _openContext(context) {
  1719. const modules = this._filter(context).filter((module) => module && module.length > 0);
  1720. const errors = [];
  1721. let success = false;
  1722. const nextModule = () => {
  1723. if (modules.length > 0) {
  1724. const id = modules.shift();
  1725. return this._host.require(id).then((module) => {
  1726. const updateErrorContext = (error, context) => {
  1727. const content = " in '" + context.identifier + "'.";
  1728. if (error && typeof error.message === 'string' && !error.message.endsWith(content) && (error.context === undefined || error.context === true)) {
  1729. error.message = error.message.replace(/\.$/, '') + content;
  1730. }
  1731. };
  1732. if (!module.ModelFactory) {
  1733. throw new view.Error("Failed to load module '" + id + "'.");
  1734. }
  1735. const modelFactory = new module.ModelFactory();
  1736. let match = undefined;
  1737. try {
  1738. match = modelFactory.match(context);
  1739. if (!match) {
  1740. return nextModule();
  1741. }
  1742. }
  1743. catch (error) {
  1744. updateErrorContext(error, context);
  1745. return Promise.reject(error);
  1746. }
  1747. success = true;
  1748. return modelFactory.open(context, match).then((model) => {
  1749. if (!model.identifier) {
  1750. model.identifier = context.identifier;
  1751. }
  1752. return model;
  1753. }).catch((error) => {
  1754. updateErrorContext(error, context);
  1755. errors.push(error);
  1756. return nextModule();
  1757. });
  1758. });
  1759. }
  1760. if (success) {
  1761. if (errors.length === 1) {
  1762. const error = errors[0];
  1763. return Promise.reject(error);
  1764. }
  1765. return Promise.reject(new view.Error(errors.map((err) => err.message).join('\n')));
  1766. }
  1767. return Promise.resolve(null);
  1768. };
  1769. return nextModule();
  1770. }
  1771. _openEntries(entries) {
  1772. try {
  1773. const rootFolder = (files) => {
  1774. const map = files.map((file) => file.split('/').slice(0, -1));
  1775. const at = index => list => list[index];
  1776. const rotate = list => list.length === 0 ? [] : list[0].map((item, index) => list.map(at(index)));
  1777. const equals = list => list.every((item) => item === list[0]);
  1778. const folder = rotate(map).filter(equals).map(at(0)).join('/');
  1779. return folder.length === 0 ? folder : folder + '/';
  1780. };
  1781. const filter = (queue) => {
  1782. let matches = [];
  1783. const nextEntry = () => {
  1784. if (queue.length > 0) {
  1785. const entry = queue.shift();
  1786. const context = new view.ModelContext(new view.EntryContext(this._host, null, folder, entry.name, entry.stream));
  1787. let modules = this._filter(context);
  1788. const nextModule = () => {
  1789. if (modules.length > 0) {
  1790. const id = modules.shift();
  1791. return this._host.require(id).then((module) => {
  1792. if (!module.ModelFactory) {
  1793. throw new view.ArchiveError("Failed to load module '" + id + "'.", null);
  1794. }
  1795. const factory = new module.ModelFactory();
  1796. if (factory.match(context)) {
  1797. matches.push(entry);
  1798. modules = [];
  1799. }
  1800. return nextModule();
  1801. });
  1802. }
  1803. return nextEntry();
  1804. };
  1805. return nextModule();
  1806. }
  1807. if (matches.length === 0) {
  1808. return Promise.resolve(null);
  1809. }
  1810. // MXNet
  1811. if (matches.length === 2 &&
  1812. matches.some((e) => e.name.toLowerCase().endsWith('.params')) &&
  1813. matches.some((e) => e.name.toLowerCase().endsWith('-symbol.json'))) {
  1814. matches = matches.filter((e) => e.name.toLowerCase().endsWith('.params'));
  1815. }
  1816. // TensorFlow.js
  1817. if (matches.length > 0 &&
  1818. matches.some((e) => e.name.toLowerCase().endsWith('.bin')) &&
  1819. matches.some((e) => e.name.toLowerCase().endsWith('.json'))) {
  1820. matches = matches.filter((e) => e.name.toLowerCase().endsWith('.json'));
  1821. }
  1822. // ncnn
  1823. if (matches.length > 0 &&
  1824. matches.some((e) => e.name.toLowerCase().endsWith('.bin')) &&
  1825. matches.some((e) => e.name.toLowerCase().endsWith('.param'))) {
  1826. matches = matches.filter((e) => e.name.toLowerCase().endsWith('.param'));
  1827. }
  1828. // ncnn
  1829. if (matches.length > 0 &&
  1830. matches.some((e) => e.name.toLowerCase().endsWith('.bin')) &&
  1831. matches.some((e) => e.name.toLowerCase().endsWith('.param.bin'))) {
  1832. matches = matches.filter((e) => e.name.toLowerCase().endsWith('.param.bin'));
  1833. }
  1834. // Paddle
  1835. if (matches.length > 0 &&
  1836. matches.some((e) => e.name.toLowerCase().endsWith('.pdmodel')) &&
  1837. (matches.some((e) => e.name.toLowerCase().endsWith('.pdparams')) ||
  1838. matches.some((e) => e.name.toLowerCase().endsWith('.pdopt')) ||
  1839. matches.some((e) => e.name.toLowerCase().endsWith('.pdiparams')))) {
  1840. matches = matches.filter((e) => e.name.toLowerCase().endsWith('.pdmodel'));
  1841. }
  1842. // Paddle Lite
  1843. if (matches.length > 0 &&
  1844. matches.some((e) => e.name.toLowerCase().split('/').pop() === '__model__.nb') &&
  1845. matches.some((e) => e.name.toLowerCase().split('/').pop() === 'param.nb')) {
  1846. matches = matches.filter((e) => e.name.toLowerCase().split('/').pop() == '__model__.nb');
  1847. }
  1848. // TensorFlow Bundle
  1849. if (matches.length > 1 &&
  1850. matches.some((e) => e.name.toLowerCase().endsWith('.data-00000-of-00001'))) {
  1851. matches = matches.filter((e) => !e.name.toLowerCase().endsWith('.data-00000-of-00001'));
  1852. }
  1853. // TensorFlow SavedModel
  1854. if (matches.length === 2 &&
  1855. matches.some((e) => e.name.toLowerCase().split('/').pop() === 'keras_metadata.pb')) {
  1856. matches = matches.filter((e) => e.name.toLowerCase().split('/').pop() !== 'keras_metadata.pb');
  1857. }
  1858. if (matches.length > 1) {
  1859. return Promise.reject(new view.ArchiveError('Archive contains multiple model files.'));
  1860. }
  1861. const match = matches.shift();
  1862. return Promise.resolve(new view.ModelContext(new view.EntryContext(this._host, entries, folder, match.name, match.stream)));
  1863. };
  1864. return nextEntry();
  1865. };
  1866. const list = Array.from(entries).map((entry) => {
  1867. return { name: entry[0], stream: entry[1] };
  1868. });
  1869. const files = list.filter((entry) => {
  1870. if (entry.name.endsWith('/')) {
  1871. return false;
  1872. }
  1873. if (entry.name.split('/').pop().startsWith('.')) {
  1874. return false;
  1875. }
  1876. if (!entry.name.startsWith('./') && entry.name.startsWith('.')) {
  1877. return false;
  1878. }
  1879. return true;
  1880. });
  1881. const folder = rootFolder(files.map((entry) => entry.name));
  1882. const queue = files.slice(0).filter((entry) => entry.name.substring(folder.length).indexOf('/') < 0);
  1883. return filter(queue).then((context) => {
  1884. if (context) {
  1885. return Promise.resolve(context);
  1886. }
  1887. const queue = files.slice(0).filter((entry) => entry.name.substring(folder.length).indexOf('/') >= 0);
  1888. return filter(queue);
  1889. });
  1890. }
  1891. catch (error) {
  1892. return Promise.reject(new view.ArchiveError(error.message));
  1893. }
  1894. }
  1895. accept(identifier) {
  1896. const extension = identifier.indexOf('.') === -1 ? '' : identifier.split('.').pop().toLowerCase();
  1897. identifier = identifier.toLowerCase().split('/').pop();
  1898. for (const extension of this._extensions) {
  1899. if ((typeof extension === 'string' && identifier.endsWith(extension)) || (extension instanceof RegExp && extension.exec(identifier))) {
  1900. this._host.event('File', 'Accept', extension, 1);
  1901. return true;
  1902. }
  1903. }
  1904. this._host.event('File', 'Reject', extension, 1);
  1905. return false;
  1906. }
  1907. _filter(context) {
  1908. const identifier = context.identifier.toLowerCase().split('/').pop();
  1909. const list = this._factories.filter((entry) =>
  1910. (typeof entry.extension === 'string' && identifier.endsWith(entry.extension)) ||
  1911. (entry.extension instanceof RegExp && entry.extension.exec(identifier)));
  1912. return Array.from(new Set(list.map((entry) => entry.id)));
  1913. }
  1914. _openSignature(context) {
  1915. const stream = context.stream;
  1916. if (stream) {
  1917. let empty = true;
  1918. let position = 0;
  1919. while (empty && position < stream.length) {
  1920. const buffer = stream.read(Math.min(4096, stream.length - position));
  1921. position += buffer.length;
  1922. if (!buffer.every((value) => value === 0x00)) {
  1923. empty = false;
  1924. break;
  1925. }
  1926. }
  1927. stream.seek(0);
  1928. if (empty) {
  1929. return Promise.reject(new view.Error('File has no content.', true));
  1930. }
  1931. /* eslint-disable no-control-regex */
  1932. const entries = [
  1933. { name: 'ELF executable', value: /^\x7FELF/ },
  1934. { name: 'PNG image', value: /^\x89PNG/ },
  1935. { name: 'Git LFS header', value: /^version https:\/\/git-lfs.github.com/ },
  1936. { name: 'Git LFS header', value: /^\s*oid sha256:/ },
  1937. { name: 'HTML markup', value: /^\s*<html>/ },
  1938. { name: 'HTML markup', value: /^\s*<!doctype\s*html>/ },
  1939. { name: 'HTML markup', value: /^\s*<!DOCTYPE\s*html>/ },
  1940. { name: 'HTML markup', value: /^\s*<!DOCTYPE\s*HTML>/ },
  1941. { name: 'HTML markup', value: /^\s*<!DOCTYPE\s*HTML\s+(PUBLIC|SYSTEM)?/ },
  1942. { name: 'Unity metadata', value: /^fileFormatVersion:/ },
  1943. { name: 'Python source code', value: /^\s*import[ ]+(os|sys|types|torch|argparse|onnx|numpy|tensorflow)(,|;|\s)/ },
  1944. { name: 'Python source code', value: /^\s*import[ ]+([a-z])+[ ]+as[ ]+/ },
  1945. { name: 'Python source code', value: /^\s*from[ ]+(torch)[ ]+import[ ]+/ },
  1946. { name: 'Python source code', value: /^\s*from[ ]+(keras)[ ]+import[ ]+/ },
  1947. { name: 'Bash script', value: /^#!\/usr\/bin\/env\s/ },
  1948. { name: 'Bash script', value: /^#!\/bin\/bash\s/ },
  1949. { name: 'TSD header', value: /^%TSD-Header-###%/ },
  1950. { name: 'AppleDouble data', value: /^\x00\x05\x16\x07/ },
  1951. { name: 'TensorFlow Hub module', value: /^\x08\x03$/, identifier: 'tfhub_module.pb' },
  1952. { name: 'ViSQOL model', value: /^svm_type\snu_svr/ }
  1953. ];
  1954. /* eslint-enable no-control-regex */
  1955. const buffer = stream.peek(Math.min(4096, stream.length));
  1956. const content = String.fromCharCode.apply(null, buffer);
  1957. for (const entry of entries) {
  1958. if (content.match(entry.value) && (!entry.identifier || entry.identifier === context.identifier)) {
  1959. return Promise.reject(new view.Error('Invalid file content. File contains ' + entry.name + '.', true));
  1960. }
  1961. }
  1962. }
  1963. return Promise.resolve(context);
  1964. }
  1965. };
  1966. view.Error = class extends Error {
  1967. constructor(message, telemetry) {
  1968. super(message);
  1969. this.name = 'Error loading model.';
  1970. this.telemetry = telemetry;
  1971. this.stack = undefined;
  1972. }
  1973. };
  1974. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  1975. module.exports.View = view.View;
  1976. module.exports.ModelFactoryService = view.ModelFactoryService;
  1977. }