view.js 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105
  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. const lastModel = this._model;
  425. const lastGraphs = this._graphs;
  426. this._model = model;
  427. this._graphs = graphs;
  428. const graph = this.activeGraph;
  429. return this._timeout(100).then(() => {
  430. if (graph && graph != lastGraphs[0]) {
  431. const nodes = graph.nodes;
  432. if (nodes.length > 2048) {
  433. 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?')) {
  434. this._host.event('Graph', 'Render', 'Skip', nodes.length);
  435. this.show(null);
  436. return null;
  437. }
  438. }
  439. }
  440. const update = () => {
  441. const nameButton = this._getElementById('name-button');
  442. const backButton = this._getElementById('back-button');
  443. if (this._graphs.length > 1) {
  444. const graph = this.activeGraph;
  445. nameButton.innerHTML = graph ? graph.name : '';
  446. backButton.style.opacity = 1;
  447. nameButton.style.opacity = 1;
  448. }
  449. else {
  450. backButton.style.opacity = 0;
  451. nameButton.style.opacity = 0;
  452. }
  453. };
  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. else {
  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. }
  584. catch (error) {
  585. return Promise.reject(error);
  586. }
  587. }
  588. applyStyleSheet(element, name) {
  589. let rules = [];
  590. for (const styleSheet of this._host.document.styleSheets) {
  591. if (styleSheet && styleSheet.href && styleSheet.href.endsWith('/' + name)) {
  592. rules = styleSheet.cssRules;
  593. break;
  594. }
  595. }
  596. const nodes = element.getElementsByTagName('*');
  597. for (const node of nodes) {
  598. for (const rule of rules) {
  599. if (node.matches(rule.selectorText)) {
  600. for (const item of rule.style) {
  601. node.style[item] = rule.style[item];
  602. }
  603. }
  604. }
  605. }
  606. }
  607. export(file) {
  608. const lastIndex = file.lastIndexOf('.');
  609. const extension = (lastIndex != -1) ? file.substring(lastIndex + 1) : '';
  610. if (this.activeGraph && (extension === 'png' || extension === 'svg')) {
  611. const canvas = this._getElementById('canvas');
  612. const clone = canvas.cloneNode(true);
  613. this.applyStyleSheet(clone, 'view-grapher.css');
  614. clone.setAttribute('id', 'export');
  615. clone.removeAttribute('viewBox');
  616. clone.removeAttribute('width');
  617. clone.removeAttribute('height');
  618. clone.style.removeProperty('opacity');
  619. clone.style.removeProperty('display');
  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, formats) {
  1144. this._context = context;
  1145. this._tags = new Map();
  1146. this._content = new Map();
  1147. this._formats = formats || new Map();
  1148. }
  1149. get identifier() {
  1150. return this._context.identifier;
  1151. }
  1152. get stream() {
  1153. return this._context.stream;
  1154. }
  1155. request(file, encoding, base) {
  1156. return this._context.request(file, encoding, base);
  1157. }
  1158. require(id) {
  1159. return this._context.require(id);
  1160. }
  1161. exception(error, fatal) {
  1162. this._context.exception(error, fatal);
  1163. }
  1164. entries(format) {
  1165. return this._formats.get(format) || new Map();
  1166. }
  1167. open(type) {
  1168. if (!this._content.has(type)) {
  1169. this._content.set(type, undefined);
  1170. const stream = this.stream;
  1171. const position = stream.position;
  1172. const signatures = [
  1173. [ 0x89, 0x48, 0x44, 0x46, 0x0D, 0x0A, 0x1A, 0x0A ], // HDF5
  1174. [ 0x80, undefined, 0x8a, 0x0a, 0x6c, 0xfc, 0x9c, 0x46, 0xf9, 0x20, 0x6a, 0xa8, 0x50, 0x19 ] // PyTorch
  1175. ];
  1176. const skip =
  1177. signatures.some((signature) => signature.length <= stream.length && stream.peek(signature.length).every((value, index) => signature[index] === undefined || signature[index] === value)) ||
  1178. Array.from(this._tags).some((pair) => pair[0] !== 'flatbuffers' && pair[1].size > 0) ||
  1179. Array.from(this._content.values()).some((obj) => obj !== undefined);
  1180. if (!skip) {
  1181. switch (type) {
  1182. case 'json': {
  1183. try {
  1184. const reader = json.TextReader.open(this.stream);
  1185. if (reader) {
  1186. const obj = reader.read();
  1187. this._content.set(type, obj);
  1188. }
  1189. }
  1190. catch (err) {
  1191. // continue regardless of error
  1192. }
  1193. break;
  1194. }
  1195. case 'json.gz': {
  1196. try {
  1197. const archive = gzip.Archive.open(this.stream);
  1198. if (archive) {
  1199. const entries = archive.entries;
  1200. if (entries.size === 1) {
  1201. const stream = entries.values().next().value;
  1202. const reader = json.TextReader.open(stream);
  1203. if (reader) {
  1204. const obj = reader.read();
  1205. this._content.set(type, obj);
  1206. }
  1207. }
  1208. }
  1209. }
  1210. catch (err) {
  1211. // continue regardless of error
  1212. }
  1213. break;
  1214. }
  1215. case 'pkl': {
  1216. let unpickler = null;
  1217. try {
  1218. if (stream.length > 2) {
  1219. const zlib = (stream) => {
  1220. const buffer = stream.peek(2);
  1221. if (buffer[0] === 0x78) {
  1222. const check = (buffer[0] << 8) + buffer[1];
  1223. if (check % 31 === 0) {
  1224. const archive = zip.Archive.open(stream);
  1225. return archive.entries.get('');
  1226. }
  1227. }
  1228. return stream;
  1229. };
  1230. unpickler = python.Unpickler.open(zlib(stream));
  1231. }
  1232. }
  1233. catch (err) {
  1234. // continue regardless of error
  1235. }
  1236. if (unpickler) {
  1237. const execution = new python.Execution(null, (error, fatal) => {
  1238. const message = error && error.message ? error.message : error.toString();
  1239. this.exception(new view.Error(message.replace(/\.$/, '') + " in '" + this.identifier + "'."), fatal);
  1240. });
  1241. const persistent_load = (saved_id) => {
  1242. return saved_id;
  1243. };
  1244. const obj = unpickler.load((name, args) => execution.invoke(name, args), persistent_load);
  1245. this._content.set(type, obj);
  1246. }
  1247. break;
  1248. }
  1249. default: {
  1250. throw new view.Error("Unsupported open format type '" + type + "'.");
  1251. }
  1252. }
  1253. }
  1254. if (stream.position !== position) {
  1255. stream.seek(0);
  1256. }
  1257. }
  1258. return this._content.get(type);
  1259. }
  1260. tags(type) {
  1261. if (!this._tags.has(type)) {
  1262. let tags = new Map();
  1263. const stream = this.stream;
  1264. const position = stream.position;
  1265. if (stream) {
  1266. const signatures = [
  1267. [ 0x89, 0x48, 0x44, 0x46, 0x0D, 0x0A, 0x1A, 0x0A ], // HDF5
  1268. [ 0x80, undefined, 0x8a, 0x0a, 0x6c, 0xfc, 0x9c, 0x46, 0xf9, 0x20, 0x6a, 0xa8, 0x50, 0x19 ], // PyTorch
  1269. [ 0x50, 0x4b ], // Zip
  1270. [ 0x1f, 0x8b ] // Gzip
  1271. ];
  1272. const skip =
  1273. signatures.some((signature) => signature.length <= stream.length && stream.peek(signature.length).every((value, index) => signature[index] === undefined || signature[index] === value)) ||
  1274. (Array.from(this._tags).some((pair) => pair[0] !== 'flatbuffers' && pair[1].size > 0) && type !== 'pb+') ||
  1275. Array.from(this._content.values()).some((obj) => obj !== undefined);
  1276. if (!skip) {
  1277. try {
  1278. switch (type) {
  1279. case 'pbtxt': {
  1280. const reader = protobuf.TextReader.open(stream);
  1281. tags = reader ? reader.signature() : tags;
  1282. break;
  1283. }
  1284. case 'pb': {
  1285. const reader = protobuf.BinaryReader.open(stream);
  1286. tags = reader.signature();
  1287. break;
  1288. }
  1289. case 'pb+': {
  1290. const reader = protobuf.BinaryReader.open(stream);
  1291. tags = reader.decode();
  1292. break;
  1293. }
  1294. case 'flatbuffers': {
  1295. if (stream.length >= 8) {
  1296. const buffer = stream.peek(Math.min(32, stream.length));
  1297. const reader = flatbuffers.BinaryReader.open(buffer);
  1298. const identifier = reader.identifier;
  1299. if (identifier.length > 0) {
  1300. tags.set('file_identifier', identifier);
  1301. }
  1302. }
  1303. break;
  1304. }
  1305. case 'xml': {
  1306. const reader = xml.TextReader.open(stream);
  1307. if (reader) {
  1308. const document = reader.peek();
  1309. const element = document.documentElement;
  1310. const namespaceURI = element.namespaceURI;
  1311. const localName = element.localName;
  1312. const name = namespaceURI ? namespaceURI + ':' + localName : localName;
  1313. tags.set(name, element);
  1314. }
  1315. break;
  1316. }
  1317. default: {
  1318. throw new view.Error("Unsupported tags format type '" + type + "'.");
  1319. }
  1320. }
  1321. }
  1322. catch (error) {
  1323. tags.clear();
  1324. }
  1325. }
  1326. }
  1327. if (stream.position !== position) {
  1328. stream.seek(position);
  1329. }
  1330. this._tags.set(type, tags);
  1331. }
  1332. return this._tags.get(type);
  1333. }
  1334. };
  1335. view.ArchiveContext = class {
  1336. constructor(host, entries, rootFolder, identifier, stream) {
  1337. this._host = host;
  1338. this._entries = new Map();
  1339. if (entries) {
  1340. for (const entry of entries) {
  1341. if (entry[0].startsWith(rootFolder)) {
  1342. const name = entry[0].substring(rootFolder.length);
  1343. this._entries.set(name, entry[1]);
  1344. }
  1345. }
  1346. }
  1347. this._identifier = identifier.substring(rootFolder.length);
  1348. this._stream = stream;
  1349. }
  1350. get identifier() {
  1351. return this._identifier;
  1352. }
  1353. get stream() {
  1354. return this._stream;
  1355. }
  1356. request(file, encoding, base) {
  1357. if (base === undefined) {
  1358. const stream = this._entries.get(file);
  1359. if (!stream) {
  1360. return Promise.reject(new Error('File not found.'));
  1361. }
  1362. if (encoding) {
  1363. const decoder = new TextDecoder(encoding);
  1364. const buffer = stream.peek();
  1365. const value = decoder.decode(buffer);
  1366. return Promise.resolve(value);
  1367. }
  1368. return Promise.resolve(stream);
  1369. }
  1370. return this._host.request(file, encoding, base);
  1371. }
  1372. require(id) {
  1373. return this._host.require(id);
  1374. }
  1375. exception(error, fatal) {
  1376. this._host.exception(error, fatal);
  1377. }
  1378. };
  1379. view.ArchiveError = class extends Error {
  1380. constructor(message) {
  1381. super(message);
  1382. this.name = 'Error loading archive.';
  1383. }
  1384. };
  1385. view.ModelFactoryService = class {
  1386. constructor(host) {
  1387. this._host = host;
  1388. this._extensions = new Set([ '.zip', '.tar', '.tar.gz', '.tgz', '.gz' ]);
  1389. this._factories = [];
  1390. 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' ]);
  1391. this.register('./onnx', [ '.onnx', '.onn', '.pb', '.onnxtxt', '.pbtxt', '.prototxt', '.txt', '.model', '.pt', '.pth', '.pkl', '.ort', '.ort.onnx', 'onnxmodel' ]);
  1392. this.register('./mxnet', [ '.json', '.params' ], [ '.mar'] );
  1393. this.register('./coreml', [ '.mlmodel', '.bin', 'manifest.json', 'metadata.json', 'featuredescriptions.json', '.pb' ], [ '.mlpackage' ]);
  1394. this.register('./caffe', [ '.caffemodel', '.pbtxt', '.prototxt', '.pt', '.txt' ]);
  1395. this.register('./caffe2', [ '.pb', '.pbtxt', '.prototxt' ]);
  1396. this.register('./torch', [ '.t7', '.net' ]);
  1397. this.register('./tflite', [ '.tflite', '.lite', '.tfl', '.bin', '.pb', '.tmfile', '.h5', '.model', '.json', '.txt' ]);
  1398. this.register('./circle', [ '.circle' ]);
  1399. 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' ]);
  1400. this.register('./mediapipe', [ '.pbtxt' ]);
  1401. this.register('./uff', [ '.uff', '.pb', '.pbtxt', '.uff.txt', '.trt', '.engine' ]);
  1402. this.register('./tensorrt', [ '.trt', '.engine', '.model', '.txt', '.uff', '.pb', '.tmfile', '.onnx', '.pth', '.dnn', '.plan' ]);
  1403. this.register('./numpy', [ '.npz', '.npy', '.pkl', '.pickle' ]);
  1404. this.register('./lasagne', [ '.pkl', '.pickle', '.joblib', '.model', '.pkl.z', '.joblib.z' ]);
  1405. this.register('./lightgbm', [ '.txt', '.pkl', '.model' ]);
  1406. this.register('./keras', [ '.h5', '.hd5', '.hdf5', '.keras', '.json', '.cfg', '.model', '.pb', '.pth', '.weights', '.pkl', '.lite', '.tflite', '.ckpt' ], [ '.zip' ]);
  1407. this.register('./sklearn', [ '.pkl', '.pickle', '.joblib', '.model', '.meta', '.pb', '.pt', '.h5', '.pkl.z', '.joblib.z' ]);
  1408. this.register('./pickle', [ '.pkl', '.pickle', '.joblib', '.model', '.meta', '.pb', '.pt', '.h5', '.pkl.z', '.joblib.z', '.pdstates' ]);
  1409. this.register('./cntk', [ '.model', '.cntk', '.cmf', '.dnn' ]);
  1410. this.register('./paddle', [ '.pdmodel', '.pdiparams', '.pdparams', '.pdopt', '.paddle', '__model__', '.__model__', '.pbtxt', '.txt', '.tar', '.tar.gz', '.nb' ]);
  1411. this.register('./bigdl', [ '.model', '.bigdl' ]);
  1412. this.register('./darknet', [ '.cfg', '.model', '.txt', '.weights' ]);
  1413. this.register('./weka', [ '.model' ]);
  1414. this.register('./rknn', [ '.rknn', '.onnx' ]);
  1415. this.register('./dlc', [ '.dlc' ]);
  1416. this.register('./armnn', [ '.armnn', '.json' ]);
  1417. this.register('./mnn', ['.mnn']);
  1418. this.register('./ncnn', [ '.param', '.bin', '.cfg.ncnn', '.weights.ncnn', '.ncnnmodel' ]);
  1419. this.register('./tnn', [ '.tnnproto', '.tnnmodel' ]);
  1420. this.register('./tengine', ['.tmfile']);
  1421. this.register('./mslite', [ '.ms']);
  1422. this.register('./barracuda', [ '.nn' ]);
  1423. this.register('./dnn', [ '.dnn' ]);
  1424. this.register('./xmodel', [ '.xmodel' ]);
  1425. this.register('./kmodel', [ '.kmodel' ]);
  1426. this.register('./flux', [ '.bson' ]);
  1427. this.register('./dl4j', [ '.json', '.bin' ]);
  1428. this.register('./openvino', [ '.xml', '.bin' ]);
  1429. this.register('./mlnet', [ '.zip' ]);
  1430. this.register('./acuity', [ '.json' ]);
  1431. this.register('./imgdnn', [ '.dnn', 'params', '.json' ]);
  1432. this.register('./flax', [ '.msgpack' ]);
  1433. this.register('./om', [ '.om', '.onnx', '.pb', '.engine' ]);
  1434. this.register('./nnabla', [ '.nntxt' ], [ '.nnp' ]);
  1435. }
  1436. register(id, factories, containers) {
  1437. for (const extension of factories) {
  1438. this._factories.push({ extension: extension, id: id });
  1439. this._extensions.add(extension);
  1440. }
  1441. for (const extension of containers || []) {
  1442. this._extensions.add(extension);
  1443. }
  1444. }
  1445. open(context) {
  1446. return this._openSignature(context).then((context) => {
  1447. const containers = new Map();
  1448. let stream = context.stream;
  1449. const entries = context.entries;
  1450. if (!stream && entries && entries.size > 0) {
  1451. containers.set('', entries);
  1452. }
  1453. else {
  1454. const identifier = context.identifier;
  1455. try {
  1456. const archive = gzip.Archive.open(stream);
  1457. if (archive) {
  1458. const entries = archive.entries;
  1459. containers.set('gzip', entries);
  1460. if (entries.size === 1) {
  1461. stream = entries.values().next().value;
  1462. }
  1463. }
  1464. }
  1465. catch (error) {
  1466. const message = error && error.message ? error.message : error.toString();
  1467. throw new view.ArchiveError(message.replace(/\.$/, '') + " in '" + identifier + "'.");
  1468. }
  1469. try {
  1470. const formats = new Map([ [ 'zip', zip ], [ 'tar', tar ] ]);
  1471. for (const pair of formats) {
  1472. const format = pair[0];
  1473. const module = pair[1];
  1474. const archive = module.Archive.open(stream);
  1475. if (archive) {
  1476. containers.set(format, archive.entries);
  1477. containers.delete('gzip');
  1478. break;
  1479. }
  1480. }
  1481. }
  1482. catch (error) {
  1483. const message = error && error.message ? error.message : error.toString();
  1484. throw new view.ArchiveError(message.replace(/\.$/, '') + " in '" + identifier + "'.");
  1485. }
  1486. }
  1487. const modelContext = new view.ModelContext(context, containers);
  1488. /* eslint-disable consistent-return */
  1489. return this._openContext(modelContext).then((model) => {
  1490. if (model) {
  1491. return model;
  1492. }
  1493. if (containers.size > 0) {
  1494. return this._openEntries(containers.values().next().value).then((context) => {
  1495. if (context) {
  1496. return this._openContext(context);
  1497. }
  1498. this._unsupported(modelContext);
  1499. });
  1500. }
  1501. this._unsupported(modelContext);
  1502. });
  1503. /* eslint-enable consistent-return */
  1504. });
  1505. }
  1506. _unsupported(context) {
  1507. const identifier = context.identifier;
  1508. const extension = identifier.split('.').pop().toLowerCase();
  1509. const stream = context.stream;
  1510. for (const module of [ zip, tar, gzip ]) {
  1511. let archive = null;
  1512. try {
  1513. archive = module.Archive.open(stream);
  1514. }
  1515. catch (error) {
  1516. // continue regardless of error
  1517. }
  1518. if (archive) {
  1519. throw new view.Error("Archive contains no model files in '" + identifier + "'.", true);
  1520. }
  1521. }
  1522. const skip = () => {
  1523. const knownUnsupportedIdentifiers = new Set([
  1524. 'natives_blob.bin',
  1525. 'v8_context_snapshot.bin',
  1526. 'snapshot_blob.bin',
  1527. 'image_net_labels.json',
  1528. 'package.json',
  1529. 'models.json',
  1530. 'LICENSE.meta',
  1531. 'input_0.pb',
  1532. 'output_0.pb'
  1533. ]);
  1534. return knownUnsupportedIdentifiers.has(context.identifier);
  1535. };
  1536. const json = () => {
  1537. const obj = context.open('json');
  1538. if (obj) {
  1539. const formats = [
  1540. { name: 'Netron metadata', tags: [ '[].name', '[].schema' ] },
  1541. { name: 'Netron metadata', tags: [ '[].name', '[].attributes' ] },
  1542. { name: 'Netron metadata', tags: [ '[].name', '[].category' ] },
  1543. { name: 'Darkflow metadata', tags: [ 'net', 'type', 'model' ] },
  1544. { name: 'keras-yolo2 configuration', tags: [ 'model', 'train', 'valid' ] },
  1545. { name: 'Vulkan SwiftShader ICD manifest', tags: [ 'file_format_version', 'ICD' ] },
  1546. { name: 'DeepLearningExamples configuration', tags: [ 'attention_probs_dropout_prob', 'hidden_act', 'hidden_dropout_prob', 'hidden_size', ] },
  1547. { name: 'NuGet assets', tags: [ 'version', 'targets', 'packageFolders' ] },
  1548. { name: 'NuGet data', tags: [ 'format', 'restore', 'projects' ] },
  1549. { name: 'NPM package', tags: [ 'name', 'version', 'dependencies' ] },
  1550. { name: 'NetworkX adjacency_data', tags: [ 'directed', 'graph', 'nodes' ] },
  1551. { name: 'Waifu2x data', tags: [ 'name', 'arch_name', 'channels' ] },
  1552. { name: 'Waifu2x data', tags: [ '[].nInputPlane', '[].nOutputPlane', '[].weight', '[].bias' ] },
  1553. { name: 'Brain.js data', tags: [ 'type', 'sizes', 'layers' ] },
  1554. { name: 'Custom Vision metadata', tags: [ 'CustomVision.Metadata.Version' ] }
  1555. ];
  1556. const match = (obj, tag) => {
  1557. if (tag.startsWith('[].')) {
  1558. tag = tag.substring(3);
  1559. return (Array.isArray(obj) && obj.some((item) => Object.prototype.hasOwnProperty.call(item, tag)));
  1560. }
  1561. return Object.prototype.hasOwnProperty.call(obj, tag);
  1562. };
  1563. for (const format of formats) {
  1564. if (format.tags.every((tag) => match(obj, tag))) {
  1565. throw new view.Error('Invalid file content. File contains ' + format.name + '.', true);
  1566. }
  1567. }
  1568. const content = JSON.stringify(obj).substring(0, 100).replace(/\s/, '').substr(0, 48) + '...';
  1569. throw new view.Error("Unsupported JSON content '" + (content.length > 64 ? content.substring(0, 100) + '...' : content) + "' for extension '." + extension + "' in '" + identifier + "'.", !skip());
  1570. }
  1571. };
  1572. const pbtxt = () => {
  1573. const formats = [
  1574. { name: 'ImageNet LabelMap data', tags: [ 'entry', 'entry.target_class' ] },
  1575. { name: 'StringIntLabelMapProto data', tags: [ 'item', 'item.id', 'item.name' ] },
  1576. { name: 'caffe.LabelMap data', tags: [ 'item', 'item.name', 'item.label' ] },
  1577. { name: 'Triton Inference Server configuration', tags: [ 'name', 'platform', 'input', 'output' ] },
  1578. { name: 'TensorFlow OpList data', tags: [ 'op', 'op.name', 'op.input_arg' ] },
  1579. { name: 'vitis.ai.proto.DpuModelParamList data', tags: [ 'model', 'model.name', 'model.kernel' ] },
  1580. { name: 'object_detection.protos.DetectionModel data', tags: [ 'model', 'model.ssd' ] },
  1581. { name: 'object_detection.protos.DetectionModel data', tags: [ 'model', 'model.faster_rcnn' ] },
  1582. { name: 'tensorflow.CheckpointState data', tags: [ 'model_checkpoint_path', 'all_model_checkpoint_paths' ] },
  1583. { name: 'apollo.perception.camera.traffic_light.detection.DetectionParam data', tags: [ 'min_crop_size', 'crop_method' ] },
  1584. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: [ 'caffe_ssd' ] }, // https://github.com/TexasInstruments/edgeai-mmdetection/blob/master/mmdet/utils/proto/mmdet_meta_arch.proto
  1585. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: [ 'tf_od_api_ssd' ] },
  1586. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: [ 'tidl_ssd' ] },
  1587. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: [ 'tidl_faster_rcnn' ] },
  1588. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: [ 'tidl_yolo' ] },
  1589. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: [ 'tidl_retinanet' ] },
  1590. { name: 'domi.InsertNewOps data', tags: [ 'aipp_op' ] } // https://github.com/Ascend/parser/blob/development/parser/proto/insert_op.proto
  1591. ];
  1592. const tags = context.tags('pbtxt');
  1593. if (tags.size > 0) {
  1594. for (const format of formats) {
  1595. if (format.tags.every((tag) => tags.has(tag))) {
  1596. throw new view.Error('Invalid file content. File contains ' + format.name + '.', true);
  1597. }
  1598. }
  1599. const entries = [];
  1600. entries.push(...Array.from(tags).filter((pair) => pair[0].toString().indexOf('.') === -1));
  1601. entries.push(...Array.from(tags).filter((pair) => pair[0].toString().indexOf('.') !== -1));
  1602. const content = entries.map((pair) => pair[1] === true ? pair[0] : pair[0] + ':' + JSON.stringify(pair[1])).join(',');
  1603. throw new view.Error("Unsupported Protocol Buffers text content '" + (content.length > 64 ? content.substring(0, 100) + '...' : content) + "' for extension '." + extension + "' in '" + identifier + "'.", !skip());
  1604. }
  1605. };
  1606. const pb = () => {
  1607. const tags = context.tags('pb+');
  1608. if (Object.keys(tags).length > 0) {
  1609. const formats = [
  1610. { 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,[]]] },
  1611. { 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]] },
  1612. { name: 'third_party.tensorflow.python.keras.protobuf.SavedMetadata data', tags: [[1,[[1,[[1,0],[2,0]]],[2,0],[3,2],[4,2],[5,2]]]] },
  1613. { 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
  1614. ];
  1615. const match = (tags, schema) => {
  1616. for (const pair of schema) {
  1617. const key = pair[0];
  1618. const inner = pair[1];
  1619. const value = tags[key];
  1620. if (value === undefined) {
  1621. continue;
  1622. }
  1623. if (inner === false) {
  1624. return false;
  1625. }
  1626. if (Array.isArray(inner)) {
  1627. if (typeof value !== 'object' || !match(value, inner)) {
  1628. return false;
  1629. }
  1630. }
  1631. else if (inner !== value) {
  1632. if (inner === 2 && !Array.isArray(value) && Object(value) === (value) && Object.keys(value).length === 0) {
  1633. return true;
  1634. }
  1635. return false;
  1636. }
  1637. }
  1638. return true;
  1639. };
  1640. const tags = context.tags('pb+');
  1641. for (const format of formats) {
  1642. if (match(tags, format.tags)) {
  1643. throw new view.Error('Invalid file content. File contains ' + format.name + '.', true);
  1644. }
  1645. }
  1646. const format = (tags) => {
  1647. const content = Object.entries(tags).map((pair) => {
  1648. const key = pair[0];
  1649. const value = pair[1];
  1650. return key.toString() + ':' + (Object(value) === value ? '{' + format(value) + '}' : value.toString());
  1651. });
  1652. return content.join(',');
  1653. };
  1654. const content = format(tags);
  1655. throw new view.Error("Unsupported Protocol Buffers content '" + (content.length > 64 ? content.substring(0, 100) + '...' : content) + "' for extension '." + extension + "' in '" + identifier + "'.", !skip());
  1656. }
  1657. };
  1658. const flatbuffers = () => {
  1659. const tags = context.tags('flatbuffers');
  1660. if (tags.has('file_identifier')) {
  1661. const file_identifier = tags.get('file_identifier');
  1662. const formats = [
  1663. { name: 'onnxruntime.experimental.fbs.InferenceSession data', identifier: 'ORTM' },
  1664. { name: 'tflite.Model data', identifier: 'TFL3' },
  1665. { name: 'FlatBuffers ENNC data', identifier: 'ENNC' },
  1666. ];
  1667. for (const format of formats) {
  1668. if (file_identifier === format.identifier) {
  1669. throw new view.Error('Invalid file content. File contains ' + format.name + '.', true);
  1670. }
  1671. }
  1672. }
  1673. };
  1674. const xml = () => {
  1675. const tags = context.tags('xml');
  1676. if (tags.size > 0) {
  1677. const formats = [
  1678. { name: 'OpenCV storage data', tags: [ 'opencv_storage' ] },
  1679. { name: 'XHTML markup', tags: [ 'http://www.w3.org/1999/xhtml:html' ]}
  1680. ];
  1681. for (const format of formats) {
  1682. if (format.tags.some((tag) => tags.has(tag))) {
  1683. throw new view.Error('Invalid file content. File contains ' + format.name + '.', true);
  1684. }
  1685. }
  1686. throw new view.Error("Unsupported XML content '" + tags.keys().next().value + "' in '" + identifier + "'.", !skip());
  1687. }
  1688. };
  1689. const unknown = () => {
  1690. stream.seek(0);
  1691. const buffer = stream.peek(Math.min(16, stream.length));
  1692. const bytes = Array.from(buffer).map((c) => (c < 16 ? '0' : '') + c.toString(16)).join('');
  1693. const content = stream.length > 268435456 ? '(' + bytes + ') [' + stream.length.toString() + ']': '(' + bytes + ')';
  1694. throw new view.Error("Unsupported file content " + content + " for extension '." + extension + "' in '" + identifier + "'.", !skip());
  1695. };
  1696. json();
  1697. pbtxt();
  1698. pb();
  1699. flatbuffers();
  1700. xml();
  1701. unknown();
  1702. }
  1703. _openContext(context) {
  1704. const modules = this._filter(context).filter((module) => module && module.length > 0);
  1705. const errors = [];
  1706. let success = false;
  1707. const nextModule = () => {
  1708. if (modules.length > 0) {
  1709. const id = modules.shift();
  1710. return this._host.require(id).then((module) => {
  1711. const updateErrorContext = (error, context) => {
  1712. const content = " in '" + context.identifier + "'.";
  1713. if (error && typeof error.message === 'string' && !error.message.endsWith(content) && (error.context === undefined || error.context === true)) {
  1714. error.message = error.message.replace(/\.$/, '') + content;
  1715. }
  1716. };
  1717. if (!module.ModelFactory) {
  1718. throw new view.Error("Failed to load module '" + id + "'.");
  1719. }
  1720. const modelFactory = new module.ModelFactory();
  1721. let match = undefined;
  1722. try {
  1723. match = modelFactory.match(context);
  1724. if (!match) {
  1725. return nextModule();
  1726. }
  1727. }
  1728. catch (error) {
  1729. updateErrorContext(error, context);
  1730. return Promise.reject(error);
  1731. }
  1732. success = true;
  1733. return modelFactory.open(context, match).then((model) => {
  1734. if (!model.identifier) {
  1735. model.identifier = context.identifier;
  1736. }
  1737. return model;
  1738. }).catch((error) => {
  1739. updateErrorContext(error, context);
  1740. errors.push(error);
  1741. return nextModule();
  1742. });
  1743. });
  1744. }
  1745. else {
  1746. if (success) {
  1747. if (errors.length === 1) {
  1748. const error = errors[0];
  1749. return Promise.reject(error);
  1750. }
  1751. return Promise.reject(new view.Error(errors.map((err) => err.message).join('\n')));
  1752. }
  1753. return Promise.resolve(null);
  1754. }
  1755. };
  1756. return nextModule();
  1757. }
  1758. _openEntries(entries) {
  1759. try {
  1760. const rootFolder = (files) => {
  1761. const map = files.map((file) => file.split('/').slice(0, -1));
  1762. const at = index => list => list[index];
  1763. const rotate = list => list.length === 0 ? [] : list[0].map((item, index) => list.map(at(index)));
  1764. const equals = list => list.every((item) => item === list[0]);
  1765. const folder = rotate(map).filter(equals).map(at(0)).join('/');
  1766. return folder.length === 0 ? folder : folder + '/';
  1767. };
  1768. const filter = (queue) => {
  1769. let matches = [];
  1770. const nextEntry = () => {
  1771. if (queue.length > 0) {
  1772. const entry = queue.shift();
  1773. const context = new view.ModelContext(new view.ArchiveContext(this._host, null, folder, entry.name, entry.stream));
  1774. let modules = this._filter(context);
  1775. const nextModule = () => {
  1776. if (modules.length > 0) {
  1777. const id = modules.shift();
  1778. return this._host.require(id).then((module) => {
  1779. if (!module.ModelFactory) {
  1780. throw new view.ArchiveError("Failed to load module '" + id + "'.", null);
  1781. }
  1782. const factory = new module.ModelFactory();
  1783. if (factory.match(context)) {
  1784. matches.push(entry);
  1785. modules = [];
  1786. }
  1787. return nextModule();
  1788. });
  1789. }
  1790. else {
  1791. return nextEntry();
  1792. }
  1793. };
  1794. return nextModule();
  1795. }
  1796. else {
  1797. if (matches.length === 0) {
  1798. return Promise.resolve(null);
  1799. }
  1800. // MXNet
  1801. if (matches.length === 2 &&
  1802. matches.some((e) => e.name.toLowerCase().endsWith('.params')) &&
  1803. matches.some((e) => e.name.toLowerCase().endsWith('-symbol.json'))) {
  1804. matches = matches.filter((e) => e.name.toLowerCase().endsWith('.params'));
  1805. }
  1806. // TensorFlow.js
  1807. if (matches.length > 0 &&
  1808. matches.some((e) => e.name.toLowerCase().endsWith('.bin')) &&
  1809. matches.some((e) => e.name.toLowerCase().endsWith('.json'))) {
  1810. matches = matches.filter((e) => e.name.toLowerCase().endsWith('.json'));
  1811. }
  1812. // ncnn
  1813. if (matches.length > 0 &&
  1814. matches.some((e) => e.name.toLowerCase().endsWith('.bin')) &&
  1815. matches.some((e) => e.name.toLowerCase().endsWith('.param'))) {
  1816. matches = matches.filter((e) => e.name.toLowerCase().endsWith('.param'));
  1817. }
  1818. // ncnn
  1819. if (matches.length > 0 &&
  1820. matches.some((e) => e.name.toLowerCase().endsWith('.bin')) &&
  1821. matches.some((e) => e.name.toLowerCase().endsWith('.param.bin'))) {
  1822. matches = matches.filter((e) => e.name.toLowerCase().endsWith('.param.bin'));
  1823. }
  1824. // Paddle
  1825. if (matches.length > 0 &&
  1826. matches.some((e) => e.name.toLowerCase().endsWith('.pdmodel')) &&
  1827. (matches.some((e) => e.name.toLowerCase().endsWith('.pdparams')) ||
  1828. matches.some((e) => e.name.toLowerCase().endsWith('.pdopt')) ||
  1829. matches.some((e) => e.name.toLowerCase().endsWith('.pdiparams')))) {
  1830. matches = matches.filter((e) => e.name.toLowerCase().endsWith('.pdmodel'));
  1831. }
  1832. // Paddle Lite
  1833. if (matches.length > 0 &&
  1834. matches.some((e) => e.name.toLowerCase().split('/').pop() === '__model__.nb') &&
  1835. matches.some((e) => e.name.toLowerCase().split('/').pop() === 'param.nb')) {
  1836. matches = matches.filter((e) => e.name.toLowerCase().split('/').pop() == '__model__.nb');
  1837. }
  1838. // TensorFlow Bundle
  1839. if (matches.length > 1 &&
  1840. matches.some((e) => e.name.toLowerCase().endsWith('.data-00000-of-00001'))) {
  1841. matches = matches.filter((e) => !e.name.toLowerCase().endsWith('.data-00000-of-00001'));
  1842. }
  1843. // TensorFlow SavedModel
  1844. if (matches.length === 2 &&
  1845. matches.some((e) => e.name.toLowerCase().split('/').pop() === 'keras_metadata.pb')) {
  1846. matches = matches.filter((e) => e.name.toLowerCase().split('/').pop() !== 'keras_metadata.pb');
  1847. }
  1848. if (matches.length > 1) {
  1849. return Promise.reject(new view.ArchiveError('Archive contains multiple model files.'));
  1850. }
  1851. const match = matches.shift();
  1852. return Promise.resolve(new view.ModelContext(new view.ArchiveContext(this._host, entries, folder, match.name, match.stream)));
  1853. }
  1854. };
  1855. return nextEntry();
  1856. };
  1857. const list = Array.from(entries).map((entry) => {
  1858. return { name: entry[0], stream: entry[1] };
  1859. });
  1860. const files = list.filter((entry) => {
  1861. if (entry.name.endsWith('/')) {
  1862. return false;
  1863. }
  1864. if (entry.name.split('/').pop().startsWith('.')) {
  1865. return false;
  1866. }
  1867. if (!entry.name.startsWith('./') && entry.name.startsWith('.')) {
  1868. return false;
  1869. }
  1870. return true;
  1871. });
  1872. const folder = rootFolder(files.map((entry) => entry.name));
  1873. const queue = files.slice(0).filter((entry) => entry.name.substring(folder.length).indexOf('/') < 0);
  1874. return filter(queue).then((context) => {
  1875. if (context) {
  1876. return Promise.resolve(context);
  1877. }
  1878. const queue = files.slice(0).filter((entry) => entry.name.substring(folder.length).indexOf('/') >= 0);
  1879. return filter(queue);
  1880. });
  1881. }
  1882. catch (error) {
  1883. return Promise.reject(new view.ArchiveError(error.message));
  1884. }
  1885. }
  1886. accept(identifier) {
  1887. const extension = identifier.indexOf('.') === -1 ? '' : identifier.split('.').pop().toLowerCase();
  1888. identifier = identifier.toLowerCase().split('/').pop();
  1889. for (const extension of this._extensions) {
  1890. if ((typeof extension === 'string' && identifier.endsWith(extension)) || (extension instanceof RegExp && extension.exec(identifier))) {
  1891. this._host.event('File', 'Accept', extension, 1);
  1892. return true;
  1893. }
  1894. }
  1895. this._host.event('File', 'Reject', extension, 1);
  1896. return false;
  1897. }
  1898. _filter(context) {
  1899. const identifier = context.identifier.toLowerCase().split('/').pop();
  1900. const list = this._factories.filter((entry) =>
  1901. (typeof entry.extension === 'string' && identifier.endsWith(entry.extension)) ||
  1902. (entry.extension instanceof RegExp && entry.extension.exec(identifier)));
  1903. return Array.from(new Set(list.map((entry) => entry.id)));
  1904. }
  1905. _openSignature(context) {
  1906. const stream = context.stream;
  1907. if (stream) {
  1908. let empty = true;
  1909. let position = 0;
  1910. while (empty && position < stream.length) {
  1911. const buffer = stream.read(Math.min(4096, stream.length - position));
  1912. position += buffer.length;
  1913. if (!buffer.every((value) => value === 0x00)) {
  1914. empty = false;
  1915. break;
  1916. }
  1917. }
  1918. stream.seek(0);
  1919. if (empty) {
  1920. return Promise.reject(new view.Error('File has no content.', true));
  1921. }
  1922. /* eslint-disable no-control-regex */
  1923. const entries = [
  1924. { name: 'ELF executable', value: /^\x7FELF/ },
  1925. { name: 'PNG image', value: /^\x89PNG/ },
  1926. { name: 'Git LFS header', value: /^version https:\/\/git-lfs.github.com/ },
  1927. { name: 'Git LFS header', value: /^\s*oid sha256:/ },
  1928. { name: 'HTML markup', value: /^\s*<html>/ },
  1929. { name: 'HTML markup', value: /^\s*<!doctype\s*html>/ },
  1930. { name: 'HTML markup', value: /^\s*<!DOCTYPE\s*html>/ },
  1931. { name: 'HTML markup', value: /^\s*<!DOCTYPE\s*HTML>/ },
  1932. { name: 'HTML markup', value: /^\s*<!DOCTYPE\s*HTML\s+(PUBLIC|SYSTEM)?/ },
  1933. { name: 'Unity metadata', value: /^fileFormatVersion:/ },
  1934. { name: 'Python source code', value: /^\s*import[ ]+(os|sys|types|torch|argparse|onnx|numpy|tensorflow)(,|;|\s)/ },
  1935. { name: 'Python source code', value: /^\s*import[ ]+([a-z])+[ ]+as[ ]+/ },
  1936. { name: 'Python source code', value: /^\s*from[ ]+(torch)[ ]+import[ ]+/ },
  1937. { name: 'Python source code', value: /^\s*from[ ]+(keras)[ ]+import[ ]+/ },
  1938. { name: 'Bash script', value: /^#!\/usr\/bin\/env\s/ },
  1939. { name: 'Bash script', value: /^#!\/bin\/bash\s/ },
  1940. { name: 'TSD header', value: /^%TSD-Header-###%/ },
  1941. { name: 'AppleDouble data', value: /^\x00\x05\x16\x07/ },
  1942. { name: 'TensorFlow Hub module', value: /^\x08\x03$/, identifier: 'tfhub_module.pb' },
  1943. { name: 'OpenVX network binary graph data', value: /^VPMN/ } // network_binary.nb
  1944. ];
  1945. /* eslint-enable no-control-regex */
  1946. const buffer = stream.peek(Math.min(4096, stream.length));
  1947. const content = String.fromCharCode.apply(null, buffer);
  1948. for (const entry of entries) {
  1949. if (content.match(entry.value) && (!entry.identifier || entry.identifier === context.identifier)) {
  1950. return Promise.reject(new view.Error('Invalid file content. File contains ' + entry.name + '.', true));
  1951. }
  1952. }
  1953. }
  1954. return Promise.resolve(context);
  1955. }
  1956. };
  1957. view.Error = class extends Error {
  1958. constructor(message, telemetry) {
  1959. super(message);
  1960. this.name = 'Error loading model.';
  1961. this.telemetry = telemetry;
  1962. this.stack = undefined;
  1963. }
  1964. };
  1965. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  1966. module.exports.View = view.View;
  1967. module.exports.ModelFactoryService = view.ModelFactoryService;
  1968. }