view.js 95 KB

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