view.js 93 KB

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