view.js 94 KB

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