view.js 94 KB

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