view.js 246 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789
  1. var view = {};
  2. var markdown = {};
  3. var base = require('./base');
  4. var zip = require('./zip');
  5. var tar = require('./tar');
  6. var json = require('./json');
  7. var xml = require('./xml');
  8. var protobuf = require('./protobuf');
  9. var flatbuffers = require('./flatbuffers');
  10. var hdf5 = require('./hdf5');
  11. var python = require('./python');
  12. var grapher = require('./grapher');
  13. view.View = class {
  14. constructor(host) {
  15. this._host = host;
  16. this._defaultOptions = {
  17. weights: true,
  18. attributes: false,
  19. names: false,
  20. direction: 'vertical',
  21. mousewheel: 'scroll'
  22. };
  23. this._options = Object.assign({}, this._defaultOptions);
  24. this._model = null;
  25. this._graphs = [];
  26. this._selection = [];
  27. this._sidebar = new view.Sidebar(this._host);
  28. this._searchText = '';
  29. this._modelFactoryService = new view.ModelFactoryService(this._host);
  30. }
  31. async start() {
  32. try {
  33. await this._host.view(this);
  34. const options = this._host.get('options') || {};
  35. for (const entry of Object.entries(options)) {
  36. const name = entry[0];
  37. this._options[name] = entry[1];
  38. }
  39. this._element('sidebar-button').addEventListener('click', () => {
  40. this.showModelProperties();
  41. });
  42. this._element('zoom-in-button').addEventListener('click', () => {
  43. this.zoomIn();
  44. });
  45. this._element('zoom-out-button').addEventListener('click', () => {
  46. this.zoomOut();
  47. });
  48. this._element('toolbar-path-back-button').addEventListener('click', () => {
  49. this.popGraph();
  50. });
  51. this._element('sidebar').addEventListener('mousewheel', (e) => {
  52. if (e.shiftKey || e.ctrlKey) {
  53. e.preventDefault();
  54. }
  55. }, { passive: true });
  56. this._host.document.addEventListener('keydown', () => {
  57. if (this._graph) {
  58. this._graph.select(null);
  59. }
  60. });
  61. const platform = this._host.environment('platform');
  62. this._menu = new view.Menu(this._host);
  63. this._menu.add({
  64. accelerator: platform === 'darwin' ? 'Ctrl+Cmd+F' : 'F11',
  65. execute: () => this._host.execute('fullscreen')
  66. });
  67. this._menu.add({
  68. accelerator: 'Backspace',
  69. execute: () => this.popGraph()
  70. });
  71. if (this._host.environment('menu')) {
  72. this._menu.attach(this._element('menu'), this._element('menu-button'));
  73. const file = this._menu.group('&File');
  74. file.add({
  75. label: '&Open...',
  76. accelerator: 'CmdOrCtrl+O',
  77. execute: () => this._host.execute('open')
  78. });
  79. if (this._host.type === 'Electron') {
  80. this._recents = file.group('Open &Recent');
  81. file.add({
  82. label: '&Export...',
  83. accelerator: 'CmdOrCtrl+Shift+E',
  84. execute: () => this._host.execute('export'),
  85. enabled: () => this.activeGraph
  86. });
  87. file.add({
  88. label: platform === 'darwin' ? '&Close Window' : '&Close',
  89. accelerator: 'CmdOrCtrl+W',
  90. execute: () => this._host.execute('close'),
  91. });
  92. file.add({
  93. label: platform === 'win32' ? 'E&xit' : '&Quit',
  94. accelerator: platform === 'win32' ? '' : 'CmdOrCtrl+Q',
  95. execute: () => this._host.execute('quit'),
  96. });
  97. } else {
  98. file.add({
  99. label: 'Export as &PNG',
  100. accelerator: 'CmdOrCtrl+Shift+E',
  101. execute: () => this.export(this._host.document.title + '.png'),
  102. enabled: () => this.activeGraph
  103. });
  104. file.add({
  105. label: 'Export as &SVG',
  106. accelerator: 'CmdOrCtrl+Alt+E',
  107. execute: () => this.export(this._host.document.title + '.svg'),
  108. enabled: () => this.activeGraph
  109. });
  110. }
  111. const edit = this._menu.group('&Edit');
  112. edit.add({
  113. label: '&Find...',
  114. accelerator: 'CmdOrCtrl+F',
  115. execute: () => this.find(),
  116. enabled: () => this.activeGraph
  117. });
  118. const view = this._menu.group('&View');
  119. view.add({
  120. label: () => this.options.attributes ? 'Hide &Attributes' : 'Show &Attributes',
  121. accelerator: 'CmdOrCtrl+D',
  122. execute: () => this.toggle('attributes'),
  123. enabled: () => this.activeGraph
  124. });
  125. view.add({
  126. label: () => this.options.weights ? 'Hide &Weights' : 'Show &Weights',
  127. accelerator: 'CmdOrCtrl+I',
  128. execute: () => this.toggle('weights'),
  129. enabled: () => this.activeGraph
  130. });
  131. view.add({
  132. label: () => this.options.names ? 'Hide &Names' : 'Show &Names',
  133. accelerator: 'CmdOrCtrl+U',
  134. execute: () => this.toggle('names'),
  135. enabled: () => this.activeGraph
  136. });
  137. view.add({
  138. label: () => this.options.direction === 'vertical' ? 'Show &Horizontal' : 'Show &Vertical',
  139. accelerator: 'CmdOrCtrl+K',
  140. execute: () => this.toggle('direction'),
  141. enabled: () => this.activeGraph
  142. });
  143. view.add({
  144. label: () => this.options.mousewheel === 'scroll' ? '&Mouse Wheel: Zoom' : '&Mouse Wheel: Scroll',
  145. accelerator: 'CmdOrCtrl+M',
  146. execute: () => this.toggle('mousewheel'),
  147. enabled: () => this.activeGraph
  148. });
  149. view.add({});
  150. if (this._host.type === 'Electron') {
  151. view.add({
  152. label: '&Reload',
  153. accelerator: platform === 'darwin' ? 'CmdOrCtrl+R' : 'F5',
  154. execute: () => this._host.execute('reload'),
  155. enabled: () => this.activeGraph
  156. });
  157. view.add({});
  158. }
  159. view.add({
  160. label: 'Zoom &In',
  161. accelerator: 'Shift+Up',
  162. execute: () => this.zoomIn(),
  163. enabled: () => this.activeGraph
  164. });
  165. view.add({
  166. label: 'Zoom &Out',
  167. accelerator: 'Shift+Down',
  168. execute: () => this.zoomOut(),
  169. enabled: () => this.activeGraph
  170. });
  171. view.add({
  172. label: 'Actual &Size',
  173. accelerator: 'Shift+Backspace',
  174. execute: () => this.resetZoom(),
  175. enabled: () => this.activeGraph
  176. });
  177. view.add({});
  178. view.add({
  179. label: '&Properties...',
  180. accelerator: 'CmdOrCtrl+Enter',
  181. execute: () => this.showModelProperties(),
  182. enabled: () => this.activeGraph
  183. });
  184. if (this._host.type === 'Electron' && !this._host.environment('packaged')) {
  185. view.add({});
  186. view.add({
  187. label: '&Developer Tools...',
  188. accelerator: 'CmdOrCtrl+Alt+I',
  189. execute: () => this._host.execute('toggle-developer-tools')
  190. });
  191. }
  192. const help = this._menu.group('&Help');
  193. help.add({
  194. label: 'Report &Issue',
  195. execute: () => this._host.execute('report-issue')
  196. });
  197. help.add({
  198. label: '&About ' + this._host.environment('name'),
  199. execute: () => this._host.execute('about')
  200. });
  201. }
  202. await this._host.start();
  203. } catch (err) {
  204. this.error(err, null, null);
  205. }
  206. }
  207. show(page) {
  208. if (!page) {
  209. page = (!this._model && !this.activeGraph) ? 'welcome' : 'default';
  210. }
  211. this._host.event('screen_view', {
  212. screen_name: page,
  213. });
  214. if (this._sidebar) {
  215. this._sidebar.close();
  216. }
  217. if (this._menu) {
  218. this._menu.close();
  219. }
  220. this._host.document.body.classList.remove(...Array.from(this._host.document.body.classList).filter((_) => _ !== 'active'));
  221. this._host.document.body.classList.add(...page.split(' '));
  222. if (page === 'default') {
  223. this._activate();
  224. } else {
  225. this._deactivate();
  226. }
  227. if (page === 'welcome') {
  228. const element = this._element('open-file-button');
  229. if (element) {
  230. element.focus();
  231. }
  232. }
  233. this._page = page;
  234. }
  235. progress(percent) {
  236. const bar = this._element('progress-bar');
  237. if (bar) {
  238. bar.style.width = percent.toString() + '%';
  239. }
  240. }
  241. cut() {
  242. this._host.document.execCommand('cut');
  243. }
  244. copy() {
  245. this._host.document.execCommand('copy');
  246. }
  247. paste() {
  248. this._host.document.execCommand('paste');
  249. }
  250. selectAll() {
  251. this._host.document.execCommand('selectall');
  252. }
  253. find() {
  254. if (this._graph) {
  255. this._graph.select(null);
  256. const content = new view.FindSidebar(this._host, this.activeGraph);
  257. content.on('search-text-changed', (sender, text) => {
  258. this._searchText = text;
  259. });
  260. content.on('select', (sender, selection) => {
  261. this.scrollTo(this._graph.select([ selection ]));
  262. });
  263. content.on('focus', (sender, selection) => {
  264. this._graph.focus([ selection ]);
  265. });
  266. content.on('blur', (sender, selection) => {
  267. this._graph.blur([ selection ]);
  268. });
  269. this._sidebar.open(content.render(), 'Find');
  270. content.focus(this._searchText);
  271. }
  272. }
  273. get model() {
  274. return this._model;
  275. }
  276. get options() {
  277. return this._options;
  278. }
  279. toggle(name) {
  280. switch (name) {
  281. case 'names':
  282. case 'attributes':
  283. case 'weights':
  284. this._options[name] = !this._options[name];
  285. this._reload();
  286. break;
  287. case 'direction':
  288. this._options.direction = this._options.direction === 'vertical' ? 'horizontal' : 'vertical';
  289. this._reload();
  290. break;
  291. case 'mousewheel':
  292. this._options.mousewheel = this._options.mousewheel === 'scroll' ? 'zoom' : 'scroll';
  293. break;
  294. default:
  295. throw new view.Error("Unsupported toogle '" + name + "'.");
  296. }
  297. const options = {};
  298. for (const entry of Object.entries(this._options)) {
  299. const name = entry[0];
  300. if (this._defaultOptions[name] !== entry[1]) {
  301. options[name] = entry[1];
  302. }
  303. }
  304. if (Object.entries(options).length == 0) {
  305. this._host.delete('options');
  306. } else {
  307. this._host.set('options', options);
  308. }
  309. }
  310. recents(recents) {
  311. if (this._recents) {
  312. this._recents.clear();
  313. for (let i = 0; i < recents.length; i++) {
  314. const recent = recents[i];
  315. this._recents.add({
  316. label: recent.label,
  317. accelerator: 'CmdOrCtrl+' + (i + 1).toString(),
  318. execute: () => this._host.execute('open', recent.path)
  319. });
  320. }
  321. }
  322. }
  323. _reload() {
  324. this.show('welcome spinner');
  325. if (this._model && this._graphs.length > 0) {
  326. this._updateGraph(this._model, this._graphs).catch((error) => {
  327. if (error) {
  328. this.error(error, 'Graph update failed.', 'welcome');
  329. }
  330. });
  331. }
  332. }
  333. _timeout(delay) {
  334. return new Promise((resolve) => {
  335. setTimeout(resolve, delay);
  336. });
  337. }
  338. _element(id) {
  339. return this._host.document.getElementById(id);
  340. }
  341. zoomIn() {
  342. this._updateZoom(this._zoom * 1.1);
  343. }
  344. zoomOut() {
  345. this._updateZoom(this._zoom * 0.9);
  346. }
  347. resetZoom() {
  348. this._updateZoom(1);
  349. }
  350. _activate() {
  351. if (!this._events) {
  352. this._events = {};
  353. this._events.scroll = (e) => this._scrollHandler(e);
  354. this._events.wheel = (e) => this._wheelHandler(e);
  355. this._events.gesturestart = (e) => this._gestureStartHandler(e);
  356. this._events.pointerdown = (e) => this._pointerDownHandler(e);
  357. this._events.touchstart = (e) => this._touchStartHandler(e);
  358. }
  359. const graph = this._element('graph');
  360. graph.focus();
  361. graph.addEventListener('scroll', this._events.scroll);
  362. graph.addEventListener('wheel', this._events.wheel, { passive: false });
  363. graph.addEventListener('pointerdown', this._events.pointerdown);
  364. if (this._host.environment('agent') === 'safari') {
  365. graph.addEventListener('gesturestart', this._events.gesturestart, false);
  366. } else {
  367. graph.addEventListener('touchstart', this._events.touchstart, { passive: true });
  368. }
  369. }
  370. _deactivate() {
  371. if (this._events) {
  372. const graph = this._element('graph');
  373. graph.removeEventListener('scroll', this._events.scroll);
  374. graph.removeEventListener('wheel', this._events.wheel);
  375. graph.removeEventListener('pointerdown', this._events.pointerdown);
  376. graph.removeEventListener('gesturestart', this._events.gesturestart);
  377. graph.removeEventListener('touchstart', this._events.touchstart);
  378. }
  379. }
  380. _updateZoom(zoom, e) {
  381. const container = this._element('graph');
  382. const canvas = this._element('canvas');
  383. const limit = this._options.direction === 'vertical' ?
  384. container.clientHeight / this._height :
  385. container.clientWidth / this._width;
  386. const min = Math.min(Math.max(limit, 0.15), 1);
  387. zoom = Math.max(min, Math.min(zoom, 1.4));
  388. const scrollLeft = this._scrollLeft || container.scrollLeft;
  389. const scrollTop = this._scrollTop || container.scrollTop;
  390. const x = (e ? e.pageX : (container.clientWidth / 2)) + scrollLeft;
  391. const y = (e ? e.pageY : (container.clientHeight / 2)) + scrollTop;
  392. const width = zoom * this._width;
  393. const height = zoom * this._height;
  394. canvas.style.width = width + 'px';
  395. canvas.style.height = height + 'px';
  396. this._scrollLeft = Math.max(0, ((x * zoom) / this._zoom) - (x - scrollLeft));
  397. this._scrollTop = Math.max(0, ((y * zoom) / this._zoom) - (y - scrollTop));
  398. container.scrollLeft = this._scrollLeft;
  399. container.scrollTop = this._scrollTop;
  400. this._zoom = zoom;
  401. }
  402. _pointerDownHandler(e) {
  403. if (e.pointerType !== 'touch' && e.buttons === 1) {
  404. e.target.setPointerCapture(e.pointerId);
  405. const document = this._host.document.documentElement;
  406. const container = this._element('graph');
  407. this._mousePosition = {
  408. left: container.scrollLeft,
  409. top: container.scrollTop,
  410. x: e.clientX,
  411. y: e.clientY
  412. };
  413. container.style.cursor = 'grabbing';
  414. e.stopImmediatePropagation();
  415. const pointerMoveHandler = (e) => {
  416. e.preventDefault();
  417. e.stopImmediatePropagation();
  418. if (this._mousePosition) {
  419. const dx = e.clientX - this._mousePosition.x;
  420. const dy = e.clientY - this._mousePosition.y;
  421. this._mousePosition.moved = dx * dx + dy * dy > 0;
  422. if (this._mousePosition.moved) {
  423. const container = this._element('graph');
  424. container.scrollTop = this._mousePosition.top - dy;
  425. container.scrollLeft = this._mousePosition.left - dx;
  426. }
  427. }
  428. };
  429. const clickHandler = (e) => {
  430. e.stopPropagation();
  431. document.removeEventListener('click', clickHandler, true);
  432. };
  433. const pointerUpHandler = (e) => {
  434. e.target.releasePointerCapture(e.pointerId);
  435. container.style.removeProperty('cursor');
  436. container.removeEventListener('pointerup', pointerUpHandler);
  437. container.removeEventListener('pointerleave', pointerUpHandler);
  438. container.removeEventListener('pointermove', pointerMoveHandler);
  439. if (this._mousePosition && this._mousePosition.moved) {
  440. e.preventDefault();
  441. e.stopImmediatePropagation();
  442. delete this._mousePosition;
  443. document.addEventListener('click', clickHandler, true);
  444. }
  445. };
  446. container.addEventListener('pointermove', pointerMoveHandler);
  447. container.addEventListener('pointerup', pointerUpHandler);
  448. container.addEventListener('pointerleave', pointerUpHandler);
  449. }
  450. }
  451. _touchStartHandler(e) {
  452. if (e.touches.length === 2) {
  453. this._touchPoints = Array.from(e.touches);
  454. this._touchZoom = this._zoom;
  455. }
  456. const touchMoveHandler = (e) => {
  457. if (Array.isArray(this._touchPoints) && this._touchPoints.length === 2 && e.touches.length === 2) {
  458. const distance = (points) => {
  459. const dx =(points[1].clientX - points[0].clientX);
  460. const dy =(points[1].clientY - points[0].clientY);
  461. return Math.sqrt(dx * dx + dy * dy);
  462. };
  463. const d1 = distance(Array.from(e.touches));
  464. const d2 = distance(this._touchPoints);
  465. if (d2 !== 0) {
  466. const points = this._touchPoints;
  467. const e = {
  468. pageX: (points[1].pageX + points[0].pageX) / 2,
  469. pageY: (points[1].pageY + points[0].pageY) / 2
  470. };
  471. const zoom = d2 === 0 ? d1 : d1 / d2;
  472. this._updateZoom(this._touchZoom * zoom, e);
  473. }
  474. }
  475. };
  476. const container = this._element('graph');
  477. const touchEndHandler = () => {
  478. container.removeEventListener('touchmove', touchMoveHandler, { passive: true });
  479. container.removeEventListener('touchcancel', touchEndHandler, { passive: true });
  480. container.removeEventListener('touchend', touchEndHandler, { passive: true });
  481. delete this._touchPoints;
  482. delete this._touchZoom;
  483. };
  484. container.addEventListener('touchmove', touchMoveHandler, { passive: true });
  485. container.addEventListener('touchcancel', touchEndHandler, { passive: true });
  486. container.addEventListener('touchend', touchEndHandler, { passive: true });
  487. }
  488. _gestureStartHandler(e) {
  489. e.preventDefault();
  490. this._gestureZoom = this._zoom;
  491. const container = this._element('graph');
  492. const gestureChangeHandler = (e) => {
  493. e.preventDefault();
  494. this._updateZoom(this._gestureZoom * e.scale, e);
  495. };
  496. const gestureEndHandler = (e) => {
  497. container.removeEventListener('gesturechange', gestureChangeHandler, false);
  498. container.removeEventListener('gestureend', gestureEndHandler, false);
  499. e.preventDefault();
  500. if (this._gestureZoom) {
  501. this._updateZoom(this._gestureZoom * e.scale, e);
  502. delete this._gestureZoom;
  503. }
  504. };
  505. container.addEventListener('gesturechange', gestureChangeHandler, false);
  506. container.addEventListener('gestureend', gestureEndHandler, false);
  507. }
  508. _scrollHandler(e) {
  509. if (this._scrollLeft && e.target.scrollLeft !== Math.floor(this._scrollLeft)) {
  510. delete this._scrollLeft;
  511. }
  512. if (this._scrollTop && e.target.scrollTop !== Math.floor(this._scrollTop)) {
  513. delete this._scrollTop;
  514. }
  515. }
  516. _wheelHandler(e) {
  517. if (e.shiftKey || e.ctrlKey || this._options.mousewheel === 'zoom') {
  518. const delta = -e.deltaY * (e.deltaMode === 1 ? 0.05 : e.deltaMode ? 1 : 0.002) * (e.ctrlKey ? 10 : 1);
  519. this._updateZoom(this._zoom * Math.pow(2, delta), e);
  520. e.preventDefault();
  521. }
  522. }
  523. scrollTo(selection) {
  524. if (selection && selection.length > 0) {
  525. const container = this._element('graph');
  526. let x = 0;
  527. let y = 0;
  528. for (const element of selection) {
  529. const rect = element.getBoundingClientRect();
  530. x += rect.left + (rect.width / 2);
  531. y += rect.top + (rect.height / 2);
  532. }
  533. x = x / selection.length;
  534. y = y / selection.length;
  535. const rect = container.getBoundingClientRect();
  536. const left = (container.scrollLeft + x - rect.left) - (rect.width / 2);
  537. const top = (container.scrollTop + y - rect.top) - (rect.height / 2);
  538. container.scrollTo({ left: left, top: top, behavior: 'smooth' });
  539. }
  540. }
  541. async error(err, name, screen) {
  542. if (this._sidebar) {
  543. this._sidebar.close();
  544. }
  545. this._host.exception(err, false);
  546. const knowns = [
  547. { name: '', message: /^Invalid value identifier/, url: 'https://github.com/lutzroeder/netron/issues/540' },
  548. { name: '', message: /^Cannot read property/, url: 'https://github.com/lutzroeder/netron/issues/647' },
  549. { name: '', message: /^Failed to render tensor/, url: 'https://github.com/lutzroeder/netron/issues/681' },
  550. { name: 'Error', message: /^EPERM: operation not permitted/, url: 'https://github.com/lutzroeder/netron/issues/551' },
  551. { name: 'Error', message: /^EACCES: permission denied/, url: 'https://github.com/lutzroeder/netron/issues/504' },
  552. { name: 'RangeError', message: /^Offset is outside the bounds of the DataView/, url: 'https://github.com/lutzroeder/netron/issues/563' },
  553. { name: 'RangeError', message: /^Maximum call stack size exceeded/, url: 'https://github.com/lutzroeder/netron/issues/589' },
  554. { name: 'RangeError', message: /^Invalid string length/, url: 'https://github.com/lutzroeder/netron/issues/648' },
  555. { name: 'Python Error', message: /^Unknown function/, url: 'https://github.com/lutzroeder/netron/issues/546' },
  556. { name: 'Error loading model.', message: /^Unsupported file content \(/, url: 'https://github.com/lutzroeder/netron/issues/550' },
  557. { name: 'Error loading model.', message: /^Unsupported Protocol Buffers content/, url: 'https://github.com/lutzroeder/netron/issues/593' },
  558. { name: 'Error loading model.', message: /^Unsupported Protocol Buffers text content/, url: 'https://github.com/lutzroeder/netron/issues/594' },
  559. { name: 'Error loading model.', message: /^Unsupported JSON content/, url: 'https://github.com/lutzroeder/netron/issues/595' },
  560. { name: 'Error loading Caffe model.', message: /^File format is not caffe\.NetParameter/, url: 'https://github.com/lutzroeder/netron/issues/563' },
  561. { name: 'Error loading DaVinci OM model.', message: /^Unsupported DaVinci OM partition type\./, url: 'https://github.com/lutzroeder/netron/issues/1154' },
  562. { name: 'Error loading MNN model.', message: /^File format is not mnn\.Net/, url: 'https://github.com/lutzroeder/netron/issues/746' },
  563. { name: 'Error loading NNEF model.', message: /^.*/, url: 'https://github.com/lutzroeder/netron/issues/992' },
  564. { name: 'Error loading PyTorch model.', message: /^File does not contain root module or state dictionary/, url: 'https://github.com/lutzroeder/netron/issues/543' },
  565. { name: 'Error loading PyTorch model.', message: /^Module does not contain modules/, url: 'https://github.com/lutzroeder/netron/issues/544' },
  566. { name: 'Error loading PyTorch model.', message: /^Unknown type name/, url: 'https://github.com/lutzroeder/netron/issues/969' },
  567. { name: 'Error loading ONNX model.', message: /^File format is not onnx\.ModelProto \(Unexpected end of file\)\./, url: 'https://github.com/lutzroeder/netron/issues/1155' },
  568. { name: 'Error loading ONNX model.', message: /^File format is not onnx\.ModelProto \(Cannot read properties of undefined \(reading 'ModelProto'\)\)\./, url: 'https://github.com/lutzroeder/netron/issues/1156' },
  569. { name: 'Error loading ONNX model.', message: /^File format is not onnx\.ModelProto/, url: 'https://github.com/lutzroeder/netron/issues/549' },
  570. { name: 'Error loading TensorFlow Lite model.', message: /^Offset is outside the bounds of the DataView/, url: 'https://github.com/lutzroeder/netron/issues/563' },
  571. { name: 'Error loading TensorRT model.', message: /^Invalid file content. File contains undocumented TensorRT engine data\./, url: 'https://github.com/lutzroeder/netron/issues/725' }
  572. ];
  573. const known = knowns.find((known) => (known.name.length === 0 || known.name === err.name) && err.message.match(known.message));
  574. const url = known && known.url ? known.url : null;
  575. const message = err.message;
  576. name = name || err.name;
  577. const button = await this._host.error(name, message, url === null);
  578. if (button === 0 && (url || this._host.type == 'Electron')) {
  579. this._host.openURL(url || this._host.environment('repository') + '/issues');
  580. }
  581. this.show(screen !== undefined ? screen : 'welcome');
  582. }
  583. accept(file, size) {
  584. return this._modelFactoryService.accept(file, size);
  585. }
  586. async open(context) {
  587. this._sidebar.close();
  588. await this._timeout(2);
  589. try {
  590. const model = await this._modelFactoryService.open(context);
  591. const format = [];
  592. if (model.format) {
  593. format.push(model.format);
  594. }
  595. if (model.producer) {
  596. format.push('(' + model.producer + ')');
  597. }
  598. if (format.length > 0) {
  599. this._host.event('model_open', {
  600. model_format: model.format || '',
  601. model_producer: model.producer || ''
  602. });
  603. }
  604. await this._timeout(20);
  605. const graphs = Array.isArray(model.graphs) && model.graphs.length > 0 ? [ model.graphs[0] ] : [];
  606. return await this._updateGraph(model, graphs);
  607. } catch (error) {
  608. if (error && context.identifier) {
  609. error.context = context.identifier;
  610. }
  611. throw error;
  612. }
  613. }
  614. async _updateActiveGraph(graph) {
  615. this._sidebar.close();
  616. if (this._model) {
  617. const model = this._model;
  618. this.show('welcome spinner');
  619. await this._timeout(200);
  620. try {
  621. await this._updateGraph(model, [ graph ]);
  622. } catch (error) {
  623. if (error) {
  624. this.error(error, 'Graph update failed.', 'welcome');
  625. }
  626. }
  627. }
  628. }
  629. get activeGraph() {
  630. return Array.isArray(this._graphs) && this._graphs.length > 0 ? this._graphs[0] : null;
  631. }
  632. async _updateGraph(model, graphs) {
  633. await this._timeout(100);
  634. const graph = Array.isArray(graphs) && graphs.length > 0 ? graphs[0] : null;
  635. if (graph && graph != this._graphs[0]) {
  636. const nodes = graph.nodes;
  637. if (nodes.length > 2048) {
  638. 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?')) {
  639. this._host.event('graph_view', {
  640. graph_node_count: nodes.length,
  641. graph_skip: 1 }
  642. );
  643. this.show(null);
  644. return null;
  645. }
  646. }
  647. }
  648. const update = async (model, graphs) => {
  649. this._model = model;
  650. this._graphs = graphs;
  651. await this.renderGraph(this._model, this.activeGraph, this._options);
  652. if (this._page !== 'default') {
  653. this.show('default');
  654. }
  655. const path = this._element('toolbar-path');
  656. const back = this._element('toolbar-path-back-button');
  657. while (path.children.length > 1) {
  658. path.removeChild(path.lastElementChild);
  659. }
  660. if (this._graphs.length <= 1) {
  661. back.style.opacity = 0;
  662. } else {
  663. back.style.opacity = 1;
  664. const last = this._graphs.length - 2;
  665. const count = Math.min(2, last);
  666. if (count < last) {
  667. const element = this._host.document.createElement('button');
  668. element.setAttribute('class', 'toolbar-path-name-button');
  669. element.innerHTML = '&hellip;';
  670. path.appendChild(element);
  671. }
  672. for (let i = count; i >= 0; i--) {
  673. const graph = this._graphs[i];
  674. const element = this._host.document.createElement('button');
  675. element.setAttribute('class', 'toolbar-path-name-button');
  676. element.addEventListener('click', () => {
  677. if (i > 0) {
  678. this._graphs = this._graphs.slice(i);
  679. this._updateGraph(this._model, this._graphs);
  680. }
  681. this.showDefinition(this._graphs[0]);
  682. });
  683. const name = graph && graph.name ? graph.name : '';
  684. if (name.length > 24) {
  685. element.setAttribute('title', name);
  686. element.innerHTML = '&hellip;' + name.substring(name.length - 24, name.length);
  687. } else {
  688. element.removeAttribute('title');
  689. element.innerHTML = name;
  690. }
  691. path.appendChild(element);
  692. }
  693. }
  694. };
  695. const lastModel = this._model;
  696. const lastGraphs = this._graphs;
  697. try {
  698. await update(model, graphs);
  699. return this._model;
  700. } catch (error) {
  701. await update(lastModel, lastGraphs);
  702. throw error;
  703. }
  704. }
  705. pushGraph(graph) {
  706. if (graph && graph !== this.activeGraph && Array.isArray(graph.nodes)) {
  707. this._sidebar.close();
  708. this._updateGraph(this._model, [ graph ].concat(this._graphs));
  709. }
  710. }
  711. popGraph() {
  712. if (this._graphs.length > 1) {
  713. this._sidebar.close();
  714. return this._updateGraph(this._model, this._graphs.slice(1));
  715. }
  716. return null;
  717. }
  718. async renderGraph(model, graph, options) {
  719. this._graph = null;
  720. const canvas = this._element('canvas');
  721. while (canvas.lastChild) {
  722. canvas.removeChild(canvas.lastChild);
  723. }
  724. if (!graph) {
  725. return;
  726. }
  727. this._zoom = 1;
  728. const groups = graph.groups;
  729. const nodes = graph.nodes;
  730. this._host.event('graph_view', {
  731. graph_node_count: nodes.length,
  732. graph_skip: 0
  733. });
  734. const layout = {};
  735. layout.nodesep = 20;
  736. layout.ranksep = 20;
  737. const rotate = graph.nodes.every((node) => node.inputs.filter((input) => input.value.every((argument) => !argument.initializer)).length === 0 && node.outputs.length === 0);
  738. const horizontal = rotate ? options.direction === 'vertical' : options.direction !== 'vertical';
  739. if (horizontal) {
  740. layout.rankdir = "LR";
  741. }
  742. if (nodes.length > 3000) {
  743. layout.ranker = 'longest-path';
  744. }
  745. const viewGraph = new view.Graph(this, model, options, groups, layout);
  746. viewGraph.add(graph);
  747. // Workaround for Safari background drag/zoom issue:
  748. // https://stackoverflow.com/questions/40887193/d3-js-zoom-is-not-working-with-mousewheel-in-safari
  749. const background = this._host.document.createElementNS('http://www.w3.org/2000/svg', 'rect');
  750. background.setAttribute('id', 'background');
  751. background.setAttribute('fill', 'none');
  752. background.setAttribute('pointer-events', 'all');
  753. canvas.appendChild(background);
  754. const origin = this._host.document.createElementNS('http://www.w3.org/2000/svg', 'g');
  755. origin.setAttribute('id', 'origin');
  756. canvas.appendChild(origin);
  757. viewGraph.build(this._host.document, origin);
  758. await this._timeout(20);
  759. viewGraph.layout();
  760. viewGraph.update();
  761. const elements = Array.from(canvas.getElementsByClassName('graph-input') || []);
  762. if (elements.length === 0) {
  763. const nodeElements = Array.from(canvas.getElementsByClassName('graph-node') || []);
  764. if (nodeElements.length > 0) {
  765. elements.push(nodeElements[0]);
  766. }
  767. }
  768. const size = canvas.getBBox();
  769. const margin = 100;
  770. const width = Math.ceil(margin + size.width + margin);
  771. const height = Math.ceil(margin + size.height + margin);
  772. origin.setAttribute('transform', 'translate(' + margin.toString() + ', ' + margin.toString() + ') scale(1)');
  773. background.setAttribute('width', width);
  774. background.setAttribute('height', height);
  775. this._width = width;
  776. this._height = height;
  777. delete this._scrollLeft;
  778. delete this._scrollRight;
  779. canvas.setAttribute('viewBox', '0 0 ' + width + ' ' + height);
  780. canvas.setAttribute('width', width);
  781. canvas.setAttribute('height', height);
  782. this._zoom = 1;
  783. this._updateZoom(this._zoom);
  784. const container = this._element('graph');
  785. if (elements && elements.length > 0) {
  786. // Center view based on input elements
  787. const xs = [];
  788. const ys = [];
  789. for (let i = 0; i < elements.length; i++) {
  790. const element = elements[i];
  791. const rect = element.getBoundingClientRect();
  792. xs.push(rect.left + (rect.width / 2));
  793. ys.push(rect.top + (rect.height / 2));
  794. }
  795. let x = xs[0];
  796. const y = ys[0];
  797. if (ys.every((y) => y === ys[0])) {
  798. x = xs.reduce((a, b) => a + b, 0) / xs.length;
  799. }
  800. const graphRect = container.getBoundingClientRect();
  801. const left = (container.scrollLeft + x - graphRect.left) - (graphRect.width / 2);
  802. const top = (container.scrollTop + y - graphRect.top) - (graphRect.height / 2);
  803. container.scrollTo({ left: left, top: top, behavior: 'auto' });
  804. } else {
  805. const canvasRect = canvas.getBoundingClientRect();
  806. const graphRect = container.getBoundingClientRect();
  807. const left = (container.scrollLeft + (canvasRect.width / 2) - graphRect.left) - (graphRect.width / 2);
  808. const top = (container.scrollTop + (canvasRect.height / 2) - graphRect.top) - (graphRect.height / 2);
  809. container.scrollTo({ left: left, top: top, behavior: 'auto' });
  810. }
  811. this._graph = viewGraph;
  812. }
  813. applyStyleSheet(element, name) {
  814. let rules = [];
  815. for (const styleSheet of this._host.document.styleSheets) {
  816. if (styleSheet && styleSheet.href && styleSheet.href.endsWith('/' + name)) {
  817. rules = styleSheet.cssRules;
  818. break;
  819. }
  820. }
  821. const nodes = element.getElementsByTagName('*');
  822. for (const node of nodes) {
  823. for (const rule of rules) {
  824. if (node.matches(rule.selectorText)) {
  825. for (const item of rule.style) {
  826. node.style[item] = rule.style[item];
  827. }
  828. }
  829. }
  830. }
  831. }
  832. export(file) {
  833. const lastIndex = file.lastIndexOf('.');
  834. const extension = (lastIndex != -1) ? file.substring(lastIndex + 1).toLowerCase() : 'png';
  835. if (this.activeGraph && (extension === 'png' || extension === 'svg')) {
  836. const canvas = this._element('canvas');
  837. const clone = canvas.cloneNode(true);
  838. this.applyStyleSheet(clone, 'grapher.css');
  839. clone.setAttribute('id', 'export');
  840. clone.removeAttribute('viewBox');
  841. clone.removeAttribute('width');
  842. clone.removeAttribute('height');
  843. clone.style.removeProperty('opacity');
  844. clone.style.removeProperty('display');
  845. clone.style.removeProperty('width');
  846. clone.style.removeProperty('height');
  847. const background = clone.querySelector('#background');
  848. const origin = clone.querySelector('#origin');
  849. origin.setAttribute('transform', 'translate(0,0) scale(1)');
  850. background.removeAttribute('width');
  851. background.removeAttribute('height');
  852. const parent = canvas.parentElement;
  853. parent.insertBefore(clone, canvas);
  854. const size = clone.getBBox();
  855. parent.removeChild(clone);
  856. parent.removeChild(canvas);
  857. parent.appendChild(canvas);
  858. const delta = (Math.min(size.width, size.height) / 2.0) * 0.1;
  859. const width = Math.ceil(delta + size.width + delta);
  860. const height = Math.ceil(delta + size.height + delta);
  861. origin.setAttribute('transform', 'translate(' + (delta - size.x).toString() + ', ' + (delta - size.y).toString() + ') scale(1)');
  862. clone.setAttribute('width', width);
  863. clone.setAttribute('height', height);
  864. background.setAttribute('width', width);
  865. background.setAttribute('height', height);
  866. background.setAttribute('fill', '#fff');
  867. const data = new XMLSerializer().serializeToString(clone);
  868. if (extension === 'svg') {
  869. const blob = new Blob([ data ], { type: 'image/svg' });
  870. this._host.export(file, blob);
  871. }
  872. if (extension === 'png') {
  873. const image = new Image();
  874. image.onload = () => {
  875. const max = Math.max(width, height);
  876. const scale = Math.min(24000.0 / max, 2.0);
  877. const canvas = this._host.document.createElement('canvas');
  878. canvas.width = Math.ceil(width * scale);
  879. canvas.height = Math.ceil(height * scale);
  880. const context = canvas.getContext('2d');
  881. context.scale(scale, scale);
  882. context.drawImage(image, 0, 0);
  883. canvas.toBlob((blob) => {
  884. if (blob) {
  885. this._host.export(file, blob);
  886. } else {
  887. const error = new Error('Image may be too large to render as PNG.');
  888. error.name = 'Error exporting image.';
  889. this._host.exception(error, false);
  890. this._host.error(error.name, error.message);
  891. }
  892. }, 'image/png');
  893. };
  894. image.src = 'data:image/svg+xml;base64,' + this._host.window.btoa(unescape(encodeURIComponent(data)));
  895. }
  896. }
  897. }
  898. showModelProperties() {
  899. if (this._model) {
  900. try {
  901. const modelSidebar = new view.ModelSidebar(this._host, this._model, this.activeGraph);
  902. modelSidebar.on('update-active-graph', (sender, graph) => {
  903. this._updateActiveGraph(graph);
  904. });
  905. const content = modelSidebar.render();
  906. this._sidebar.open(content, 'Model Properties');
  907. } catch (error) {
  908. if (error) {
  909. error.context = this._model.identifier;
  910. }
  911. this.error(error, 'Error showing model properties.', null);
  912. }
  913. }
  914. }
  915. showNodeProperties(node) {
  916. if (node) {
  917. try {
  918. if (this._menu) {
  919. this._menu.close();
  920. }
  921. const nodeSidebar = new view.NodeSidebar(this._host, node);
  922. nodeSidebar.on('show-documentation', (/* sender, e */) => {
  923. this.showDefinition(node.type);
  924. });
  925. nodeSidebar.on('show-graph', (sender, graph) => {
  926. this.pushGraph(graph);
  927. });
  928. nodeSidebar.on('export-tensor', (sender, tensor) => {
  929. const defaultPath = tensor.name ? tensor.name.split('/').join('_').split(':').join('_').split('.').join('_') : 'tensor';
  930. this._host.save('NumPy Array', 'npy', defaultPath, (file) => {
  931. try {
  932. let data_type = tensor.type.dataType;
  933. if (data_type === 'boolean') {
  934. data_type = 'bool';
  935. }
  936. const execution = new python.Execution();
  937. const bytes = execution.invoke('io.BytesIO', []);
  938. const dtype = execution.invoke('numpy.dtype', [ data_type ]);
  939. const array = execution.invoke('numpy.asarray', [ tensor.value, dtype ]);
  940. execution.invoke('numpy.save', [ bytes, array ]);
  941. bytes.seek(0);
  942. const blob = new Blob([ bytes.read() ], { type: 'application/octet-stream' });
  943. this._host.export(file, blob);
  944. } catch (error) {
  945. this.error(error, 'Error saving NumPy tensor.', null);
  946. }
  947. });
  948. });
  949. nodeSidebar.on('error', (sender, error) => {
  950. if (this._model) {
  951. error.context = this._model.identifier;
  952. }
  953. this.error(error, null, null);
  954. });
  955. nodeSidebar.on('activate', (sender, value) => {
  956. this._graph.select([ value ]);
  957. });
  958. nodeSidebar.on('deactivate', () => {
  959. this._graph.select(null);
  960. });
  961. nodeSidebar.on('select', (sender, value) => {
  962. this.scrollTo(this._graph.activate(value));
  963. });
  964. this._sidebar.open(nodeSidebar.render(), 'Node Properties');
  965. } catch (error) {
  966. if (error) {
  967. error.context = this._model.identifier;
  968. }
  969. this.error(error, 'Error showing node properties.', null);
  970. }
  971. }
  972. }
  973. showConnectionProperties(value, from, to) {
  974. try {
  975. if (this._menu) {
  976. this._menu.close();
  977. }
  978. const connectionSidebar = new view.ConnectionSidebar(this._host, value, from, to);
  979. connectionSidebar.on('activate', (sender, value) => {
  980. this._graph.select([ value ]);
  981. });
  982. connectionSidebar.on('deactivate', () => {
  983. this._graph.select(null);
  984. });
  985. connectionSidebar.on('select', (sender, value) => {
  986. this.scrollTo(this._graph.activate(value));
  987. });
  988. connectionSidebar.on('error', (sender, error) => {
  989. if (this._model) {
  990. error.context = this._model.identifier;
  991. }
  992. this.error(error, null, null);
  993. });
  994. this._sidebar.open(connectionSidebar.render(), 'Connection Properties');
  995. } catch (error) {
  996. if (error) {
  997. error.context = this._model.identifier;
  998. }
  999. this.error(error, 'Error showing connection properties.', null);
  1000. }
  1001. }
  1002. showDefinition(type) {
  1003. if (type && (type.description || type.inputs || type.outputs || type.attributes)) {
  1004. if (type.nodes && type.nodes.length > 0) {
  1005. this.pushGraph(type);
  1006. }
  1007. const documentationSidebar = new view.DocumentationSidebar(this._host, type);
  1008. documentationSidebar.on('navigate', (sender, e) => {
  1009. this._host.openURL(e.link);
  1010. });
  1011. const title = type.type === 'function' ? 'Function' : 'Documentation';
  1012. this._sidebar.push(documentationSidebar.render(), title);
  1013. }
  1014. }
  1015. about() {
  1016. this._host.document.getElementById('version').innerText = this._host.version;
  1017. const handler = () => {
  1018. this._host.window.removeEventListener('keydown', handler);
  1019. this._host.document.body.removeEventListener('click', handler);
  1020. this._host.document.body.classList.remove('about');
  1021. };
  1022. this._host.window.addEventListener('keydown', handler);
  1023. this._host.document.body.addEventListener('click', handler);
  1024. this._host.document.body.classList.add('about');
  1025. }
  1026. };
  1027. view.Menu = class {
  1028. constructor(host) {
  1029. this.items = [];
  1030. this._darwin = host.environment('platform') === 'darwin';
  1031. this._document = host.document;
  1032. this._stack = [];
  1033. this._root = [];
  1034. this._buttons = [];
  1035. this._accelerators = new Map();
  1036. this._keyCodes = new Map([
  1037. [ 'Backspace', 0x08 ], [ 'Enter', 0x0D ], [ 'Escape', 0x1B ],
  1038. [ 'Left', 0x25 ], [ 'Up', 0x26 ], [ 'Right', 0x27 ], [ 'Down', 0x28 ],
  1039. [ 'F5', 0x74 ], [ 'F11', 0x7a ]
  1040. ]);
  1041. this._symbols = new Map([
  1042. [ 'Backspace', '&#x232B;' ], [ 'Enter', '&#x23ce;' ],
  1043. [ 'Up', '&#x2191;' ], [ 'Down', '&#x2193;' ],
  1044. ]);
  1045. this._keydown = (e) => {
  1046. this._alt = false;
  1047. const code = e.keyCode | (e.altKey ? 0x0200 : 0) | (e.shiftKey ? 0x0100 : 0);
  1048. const modifier = (e.ctrlKey ? 0x0400 : 0) | (e.metaKey ? 0x0800 : 0);
  1049. if ((code | modifier) === 0x0212) { // Alt
  1050. this._alt = true;
  1051. } else {
  1052. const action =
  1053. this._accelerators.get(code | modifier) ||
  1054. this._accelerators.get(code | ((e.ctrlKey && !this._darwin) || (e.metaKey && this._darwin) ? 0x1000 : 0));
  1055. if (action && this._execute(action)) {
  1056. e.preventDefault();
  1057. } else {
  1058. const item = this._mnemonic(code | modifier);
  1059. if (item && this._activate(item)) {
  1060. e.preventDefault();
  1061. }
  1062. }
  1063. }
  1064. };
  1065. this._keyup = (e) => {
  1066. const code = e.keyCode;
  1067. if (code === 0x0012 && this._alt) { // Alt
  1068. switch (this._stack.length) {
  1069. case 0: {
  1070. if (this.open()) {
  1071. e.preventDefault();
  1072. }
  1073. break;
  1074. }
  1075. case 1: {
  1076. if (this.close()) {
  1077. e.preventDefault();
  1078. }
  1079. break;
  1080. }
  1081. default: {
  1082. this._stack = [ this ];
  1083. if (this._root.length > 1) {
  1084. this._root = [ this ];
  1085. this._rebuild();
  1086. }
  1087. this._update();
  1088. e.preventDefault();
  1089. break;
  1090. }
  1091. }
  1092. }
  1093. this._alt = false;
  1094. };
  1095. this._next = () => {
  1096. const button = this._element.ownerDocument.activeElement;
  1097. const index = this._buttons.indexOf(button);
  1098. if (index !== -1 && index < this._buttons.length - 1) {
  1099. const next = this._buttons[index + 1];
  1100. next.focus();
  1101. }
  1102. };
  1103. this._previous = () => {
  1104. const button = this._element.ownerDocument.activeElement;
  1105. const index = this._buttons.indexOf(button);
  1106. if (index > 0) {
  1107. const next = this._buttons[index - 1];
  1108. next.focus();
  1109. }
  1110. };
  1111. this._push = () => {
  1112. const button = this._element.ownerDocument.activeElement;
  1113. if (button && button.getAttribute('data-type') === 'group') {
  1114. button.click();
  1115. }
  1116. };
  1117. this._pop = () => {
  1118. if (this._stack.length > 1) {
  1119. this._deactivate();
  1120. }
  1121. };
  1122. this._exit = () => {
  1123. this._deactivate();
  1124. if (this._stack.length === 0) {
  1125. this.close();
  1126. }
  1127. };
  1128. host.window.addEventListener('keydown', this._keydown);
  1129. host.window.addEventListener('keyup', this._keyup);
  1130. }
  1131. attach(element, button) {
  1132. this._element = element;
  1133. button.addEventListener('click', (e) => {
  1134. this.toggle();
  1135. e.preventDefault();
  1136. });
  1137. }
  1138. add(value) {
  1139. const item = new view.Menu.Command(value);
  1140. this.register(item, item.accelerator);
  1141. }
  1142. group(label) {
  1143. const item = new view.Menu.Group(this, label);
  1144. item.identifier = 'menu-item-' + this.items.length.toString();
  1145. this.items.push(item);
  1146. item.shortcut = this.register(item.accelerator);
  1147. return item;
  1148. }
  1149. toggle() {
  1150. if (this._element.style.opacity >= 1) {
  1151. this.close();
  1152. } else {
  1153. this._root = [ this ];
  1154. this._stack = [ this ];
  1155. this.open();
  1156. }
  1157. }
  1158. open() {
  1159. if (this._element) {
  1160. if (this._stack.length === 0) {
  1161. this.toggle();
  1162. this._stack = [ this ];
  1163. }
  1164. this._rebuild();
  1165. this._update();
  1166. this.register(this._exit, 'Escape');
  1167. this.register(this._previous, 'Up');
  1168. this.register(this._next, 'Down');
  1169. this.register(this._pop, 'Left');
  1170. this.register(this._push, 'Right');
  1171. }
  1172. }
  1173. close() {
  1174. if (this._element) {
  1175. this.unregister(this._exit);
  1176. this.unregister(this._previous);
  1177. this.unregister(this._next);
  1178. this.unregister(this._pop);
  1179. this.unregister(this._push);
  1180. this._element.style.opacity = 0;
  1181. this._element.style.left = '-17em';
  1182. const button = this._element.ownerDocument.activeElement;
  1183. if (this._buttons.indexOf(button) > 0) {
  1184. button.blur();
  1185. }
  1186. while (this._root.length > 1) {
  1187. this._deactivate();
  1188. }
  1189. this._stack = [];
  1190. }
  1191. }
  1192. register(action, accelerator) {
  1193. let shortcut = '';
  1194. if (accelerator) {
  1195. let shift = false;
  1196. let alt = false;
  1197. let ctrl = false;
  1198. let cmd = false;
  1199. let cmdOrCtrl = false;
  1200. let key = '';
  1201. for (const part of accelerator.split('+')) {
  1202. switch (part) {
  1203. case 'CmdOrCtrl': cmdOrCtrl = true; break;
  1204. case 'Cmd': cmd = true; break;
  1205. case 'Ctrl': ctrl = true; break;
  1206. case 'Alt': alt = true; break;
  1207. case 'Shift': shift = true; break;
  1208. default: key = part; break;
  1209. }
  1210. }
  1211. if (key !== '') {
  1212. if (this._darwin) {
  1213. shortcut += ctrl ? '&#x2303' : '';
  1214. shortcut += alt ? '&#x2325;' : '';
  1215. shortcut += shift ? '&#x21e7;' : '';
  1216. shortcut += cmdOrCtrl || cmd ? '&#x2318;' : '';
  1217. shortcut += this._symbols.has(key) ? this._symbols.get(key) : key;
  1218. } else {
  1219. shortcut += cmdOrCtrl || ctrl ? 'Ctrl+' : '';
  1220. shortcut += alt ? 'Alt+' : '';
  1221. shortcut += shift ? 'Shift+' : '';
  1222. shortcut += key;
  1223. }
  1224. let code = (cmdOrCtrl ? 0x1000 : 0) | (cmd ? 0x0800 : 0) | (ctrl ? 0x0400 : 0) | (alt ? 0x0200 : 0 | shift ? 0x0100 : 0);
  1225. code |= this._keyCodes.has(key) ? this._keyCodes.get(key) : key.charCodeAt(0);
  1226. this._accelerators.set(code, action);
  1227. }
  1228. }
  1229. return shortcut;
  1230. }
  1231. unregister(action) {
  1232. this._accelerators = new Map(Array.from(this._accelerators.entries()).filter((entry) => entry[1] !== action));
  1233. }
  1234. _execute(action) {
  1235. if (typeof action === 'function') {
  1236. action();
  1237. return true;
  1238. }
  1239. switch (action ? action.type : null) {
  1240. case 'group': {
  1241. while (this._stack.length > this._root.length) {
  1242. this._stack.pop();
  1243. }
  1244. this._root.push({ items: [ action ] });
  1245. this._stack.push(action);
  1246. this._rebuild();
  1247. this._update();
  1248. return true;
  1249. }
  1250. case 'command': {
  1251. this.close();
  1252. setTimeout(() => action.execute(), 10);
  1253. return true;
  1254. }
  1255. default: {
  1256. return false;
  1257. }
  1258. }
  1259. }
  1260. _mnemonic(code) {
  1261. const key = /[a-zA-Z0-9]/.test(String.fromCharCode(code & 0x00FF));
  1262. const modifier = (code & 0xFF00) !== 0;
  1263. const alt = (code & 0xFF00) === 0x0200;
  1264. if (alt && key) {
  1265. this.open();
  1266. }
  1267. if (this._stack.length > 0 && key && (alt || !modifier)) {
  1268. const key = String.fromCharCode(code & 0x00FF);
  1269. const group = this._stack.length > 0 ? this._stack[this._stack.length - 1] : this;
  1270. const item = group.items.find((item) => key === item.mnemonic && (item.type === 'group' || item.type === 'command') && item.enabled);
  1271. if (item) {
  1272. return item;
  1273. }
  1274. }
  1275. return null;
  1276. }
  1277. _activate(item) {
  1278. switch (item ? item.type : null) {
  1279. case 'group': {
  1280. this._stack.push(item);
  1281. this._rebuild();
  1282. this._update();
  1283. return true;
  1284. }
  1285. case 'command': {
  1286. return this._execute(item);
  1287. }
  1288. default: {
  1289. return false;
  1290. }
  1291. }
  1292. }
  1293. _deactivate() {
  1294. if (this._root.length > 1) {
  1295. this._root.pop();
  1296. const group = this._stack.pop();
  1297. this._rebuild();
  1298. this._update();
  1299. if (group) {
  1300. const button = this._buttons.find((button) => button.getAttribute('id') === group.identifier);
  1301. if (button) {
  1302. button.focus();
  1303. }
  1304. }
  1305. } else if (this._stack.length > 0) {
  1306. this._stack.pop();
  1307. this._update();
  1308. }
  1309. }
  1310. _label(item, mnemonic) {
  1311. delete item.mnemonic;
  1312. const value = item.label;
  1313. if (value) {
  1314. const index = value.indexOf('&');
  1315. if (index !== -1) {
  1316. if (mnemonic) {
  1317. item.mnemonic = value[index + 1].toUpperCase();
  1318. return value.substring(0, index) + '<u>' + value[index + 1] + '</u>' + value.substring(index + 2);
  1319. }
  1320. return value.substring(0, index) + value.substring(index + 1);
  1321. }
  1322. }
  1323. return value || '';
  1324. }
  1325. _rebuild() {
  1326. this._element.innerHTML = '';
  1327. const root = this._root[this._root.length - 1];
  1328. for (const group of root.items) {
  1329. const container = this._document.createElement('div');
  1330. container.setAttribute('id', group.identifier);
  1331. container.setAttribute('class', 'menu-group');
  1332. container.innerHTML = "<div class='menu-group-header'></div>";
  1333. for (const item of group.items) {
  1334. switch (item.type) {
  1335. case 'group':
  1336. case 'command': {
  1337. const button = this._document.createElement('button');
  1338. button.setAttribute('class', 'menu-command');
  1339. button.setAttribute('id', item.identifier);
  1340. button.setAttribute('data-type', item.type);
  1341. button.addEventListener('mouseenter', () => button.focus());
  1342. button.addEventListener('click', () => this._execute(item));
  1343. const accelerator = this._document.createElement('span');
  1344. accelerator.setAttribute('class', 'menu-shortcut');
  1345. if (item.type === 'group') {
  1346. accelerator.innerHTML = '&#10095;';
  1347. } else if (item.shortcut) {
  1348. accelerator.innerHTML = item.shortcut;
  1349. }
  1350. button.appendChild(accelerator);
  1351. const content = this._document.createElement('span');
  1352. content.setAttribute('class', 'menu-label');
  1353. button.appendChild(content);
  1354. container.appendChild(button);
  1355. break;
  1356. }
  1357. case 'separator': {
  1358. const element = this._document.createElement('div');
  1359. element.setAttribute('class', 'menu-separator');
  1360. element.setAttribute('id', item.identifier);
  1361. container.appendChild(element);
  1362. break;
  1363. }
  1364. default: {
  1365. break;
  1366. }
  1367. }
  1368. }
  1369. this._element.appendChild(container);
  1370. }
  1371. this._element.style.opacity = 1.0;
  1372. this._element.style.left = '0px';
  1373. if (this._root.length > 1) {
  1374. this._element.style.width = 'auto';
  1375. this._element.style.maxWidth = '60%';
  1376. } else {
  1377. this._element.style.removeProperty('width');
  1378. this._element.style.maxWidth = 'auto';
  1379. }
  1380. }
  1381. _update() {
  1382. this._buttons = [];
  1383. const selected = this._stack.length > 0 ? this._stack[this._stack.length - 1] : null;
  1384. const root = this._root[this._root.length - 1];
  1385. for (const group of root.items) {
  1386. let visible = false;
  1387. let block = false;
  1388. const active = this._stack.length <= 1 || this._stack[1] === group;
  1389. const container = this._document.getElementById(group.identifier);
  1390. container.childNodes[0].innerHTML = this._label(group, this === selected);
  1391. for (const item of group.items) {
  1392. switch (item.type) {
  1393. case 'group':
  1394. case 'command': {
  1395. const label = this._label(item, group === selected);
  1396. const button = this._document.getElementById(item.identifier);
  1397. button.childNodes[1].innerHTML = label;
  1398. if (item.enabled) {
  1399. button.removeAttribute('disabled');
  1400. button.style.display = 'block';
  1401. visible = true;
  1402. block = true;
  1403. if (active) {
  1404. this._buttons.push(button);
  1405. }
  1406. } else {
  1407. button.setAttribute('disabled', '');
  1408. button.style.display = 'none';
  1409. }
  1410. break;
  1411. }
  1412. case 'separator': {
  1413. const element = this._document.getElementById(item.identifier);
  1414. element.style.display = block ? 'block' : 'none';
  1415. block = false;
  1416. break;
  1417. }
  1418. default: {
  1419. break;
  1420. }
  1421. }
  1422. }
  1423. for (let i = group.items.length - 1; i >= 0; i--) {
  1424. const item = group.items[i];
  1425. if ((item.type === 'group' || item.type === 'command') && item.enabled) {
  1426. break;
  1427. } else if (item.type === 'separator') {
  1428. const element = this._document.getElementById(item.identifier);
  1429. element.style.display = 'none';
  1430. }
  1431. }
  1432. if (!visible) {
  1433. container.style.display = 'none';
  1434. }
  1435. container.style.opacity = active ? 1 : 0;
  1436. }
  1437. const button = this._element.ownerDocument.activeElement;
  1438. const index = this._buttons.indexOf(button);
  1439. if (index === -1 && this._buttons.length > 0) {
  1440. this._buttons[0].focus();
  1441. }
  1442. }
  1443. };
  1444. view.Menu.Group = class {
  1445. constructor(parent, label) {
  1446. this.type = 'group';
  1447. this.parent = parent;
  1448. this.label = label;
  1449. this.items = [];
  1450. }
  1451. get enabled() {
  1452. return this.items.some((item) => item.enabled);
  1453. }
  1454. add(value) {
  1455. const item = Object.keys(value).length > 0 ? new view.Menu.Command(value) : new view.Menu.Separator();
  1456. item.identifier = this.identifier + '-' + this.items.length.toString();
  1457. this.items.push(item);
  1458. item.shortcut = this.parent.register(item, item.accelerator);
  1459. }
  1460. group(label) {
  1461. const item = new view.Menu.Group(this, label);
  1462. item.identifier = this.identifier + '-' + this.items.length.toString();
  1463. this.items.push(item);
  1464. item.shortcut = this.parent.register(item, item.accelerator);
  1465. return item;
  1466. }
  1467. clear() {
  1468. for (const item of this.items) {
  1469. if (item.clear) {
  1470. item.clear();
  1471. }
  1472. this.parent.unregister(item);
  1473. }
  1474. this.items = [];
  1475. }
  1476. register(item, accelerator) {
  1477. return this.parent.register(item, accelerator);
  1478. }
  1479. unregister(item) {
  1480. this.parent.unregister(item);
  1481. }
  1482. };
  1483. view.Menu.Command = class {
  1484. constructor(item) {
  1485. this.type = 'command';
  1486. this.accelerator = item.accelerator;
  1487. this._label = item.label;
  1488. this._enabled = item.enabled;
  1489. this._execute = item.execute;
  1490. }
  1491. get label() {
  1492. return typeof this._label === 'function' ? this._label() : this._label;
  1493. }
  1494. get enabled() {
  1495. return this._enabled ? this._enabled() : true;
  1496. }
  1497. execute() {
  1498. if (this._execute && this.enabled) {
  1499. this._execute();
  1500. }
  1501. }
  1502. };
  1503. view.Menu.Separator = class {
  1504. constructor() {
  1505. this.type = 'separator';
  1506. this.enabled = false;
  1507. }
  1508. };
  1509. view.Graph = class extends grapher.Graph {
  1510. constructor(view, model, options, compound, layout) {
  1511. super(compound, layout);
  1512. this.view = view;
  1513. this.model = model;
  1514. this.options = options;
  1515. this._nodeKey = 0;
  1516. this._values = new Map();
  1517. this._table = new Map();
  1518. this._selection = new Set();
  1519. }
  1520. createNode(node) {
  1521. const value = new view.Node(this, node);
  1522. value.name = (this._nodeKey++).toString();
  1523. this._table.set(node, value);
  1524. return value;
  1525. }
  1526. createInput(input) {
  1527. const value = new view.Input(this, input);
  1528. value.name = (this._nodeKey++).toString();
  1529. this._table.set(input, value);
  1530. return value;
  1531. }
  1532. createOutput(output) {
  1533. const value = new view.Output(this, output);
  1534. value.name = (this._nodeKey++).toString();
  1535. this._table.set(output, value);
  1536. return value;
  1537. }
  1538. createValue(argument) {
  1539. const name = argument.name;
  1540. if (!this._values.has(name)) {
  1541. const value = new view.Value(this, argument);
  1542. this._values.set(name, value);
  1543. this._table.set(argument, value);
  1544. } else {
  1545. // duplicate argument name
  1546. const value = this._values.get(name);
  1547. this._table.set(argument, value);
  1548. }
  1549. return this._values.get(name);
  1550. }
  1551. add(graph) {
  1552. const clusters = new Set();
  1553. const clusterParentMap = new Map();
  1554. const groups = graph.groups;
  1555. if (groups) {
  1556. for (const node of graph.nodes) {
  1557. if (node.group) {
  1558. const path = node.group.split('/');
  1559. while (path.length > 0) {
  1560. const name = path.join('/');
  1561. path.pop();
  1562. clusterParentMap.set(name, path.join('/'));
  1563. }
  1564. }
  1565. }
  1566. }
  1567. for (const input of graph.inputs) {
  1568. const viewInput = this.createInput(input);
  1569. this.setNode(viewInput);
  1570. for (const value of input.value) {
  1571. this.createValue(value).from = viewInput;
  1572. }
  1573. }
  1574. for (const node of graph.nodes) {
  1575. const viewNode = this.createNode(node);
  1576. this.setNode(viewNode);
  1577. const inputs = node.inputs;
  1578. for (const input of inputs) {
  1579. for (const value of input.value) {
  1580. if (value.name != '' && !value.initializer) {
  1581. this.createValue(value).to.push(viewNode);
  1582. }
  1583. }
  1584. }
  1585. let outputs = node.outputs;
  1586. if (node.chain && node.chain.length > 0) {
  1587. const chainOutputs = node.chain[node.chain.length - 1].outputs;
  1588. if (chainOutputs.length > 0) {
  1589. outputs = chainOutputs;
  1590. }
  1591. }
  1592. for (const output of outputs) {
  1593. for (const value of output.value) {
  1594. if (!value) {
  1595. const error = new view.Error('Invalid null argument.');
  1596. error.context = this.model.identifier;
  1597. throw error;
  1598. }
  1599. if (value.name != '') {
  1600. this.createValue(value).from = viewNode;
  1601. }
  1602. }
  1603. }
  1604. if (node.controlDependencies && node.controlDependencies.length > 0) {
  1605. for (const value of node.controlDependencies) {
  1606. this.createValue(value).controlDependency(viewNode);
  1607. }
  1608. }
  1609. const createCluster = (name) => {
  1610. if (!clusters.has(name)) {
  1611. this.setNode({ name: name, rx: 5, ry: 5 });
  1612. clusters.add(name);
  1613. const parent = clusterParentMap.get(name);
  1614. if (parent) {
  1615. createCluster(parent);
  1616. this.setParent(name, parent);
  1617. }
  1618. }
  1619. };
  1620. if (groups) {
  1621. let groupName = node.group;
  1622. if (groupName && groupName.length > 0) {
  1623. if (!clusterParentMap.has(groupName)) {
  1624. const lastIndex = groupName.lastIndexOf('/');
  1625. if (lastIndex != -1) {
  1626. groupName = groupName.substring(0, lastIndex);
  1627. if (!clusterParentMap.has(groupName)) {
  1628. groupName = null;
  1629. }
  1630. } else {
  1631. groupName = null;
  1632. }
  1633. }
  1634. if (groupName) {
  1635. createCluster(groupName + '\ngroup');
  1636. this.setParent(viewNode.name, groupName + '\ngroup');
  1637. }
  1638. }
  1639. }
  1640. }
  1641. for (const output of graph.outputs) {
  1642. const viewOutput = this.createOutput(output);
  1643. this.setNode(viewOutput);
  1644. for (const value of output.value) {
  1645. this.createValue(value).to.push(viewOutput);
  1646. }
  1647. }
  1648. }
  1649. build(document, origin) {
  1650. for (const value of this._values.values()) {
  1651. value.build();
  1652. }
  1653. super.build(document, origin);
  1654. }
  1655. select(selection) {
  1656. if (this._selection.size > 0) {
  1657. for (const element of this._selection) {
  1658. element.deselect();
  1659. }
  1660. this._selection.clear();
  1661. }
  1662. if (selection) {
  1663. let array = [];
  1664. for (const value of selection) {
  1665. if (this._table.has(value)) {
  1666. const element = this._table.get(value);
  1667. array = array.concat(element.select());
  1668. this._selection.add(element);
  1669. }
  1670. }
  1671. return array;
  1672. }
  1673. return null;
  1674. }
  1675. activate(value) {
  1676. if (this._table.has(value)) {
  1677. this.select(null);
  1678. const element = this._table.get(value);
  1679. element.activate();
  1680. return this.select([ value ]);
  1681. }
  1682. return [];
  1683. }
  1684. focus(selection) {
  1685. for (const value of selection) {
  1686. const element = this._table.get(value);
  1687. if (element && !this._selection.has(element)) {
  1688. element.select();
  1689. }
  1690. }
  1691. }
  1692. blur(selection) {
  1693. for (const value of selection) {
  1694. const element = this._table.get(value);
  1695. if (element && !this._selection.has(element)) {
  1696. element.deselect();
  1697. }
  1698. }
  1699. }
  1700. };
  1701. view.Node = class extends grapher.Node {
  1702. constructor(context, value) {
  1703. super();
  1704. this.context = context;
  1705. this.value = value;
  1706. view.Node.counter = view.Node.counter || 0;
  1707. this.id = 'node-' + (value.name ? 'name-' + value.name : 'id-' + (view.Node.counter++).toString());
  1708. this._add(this.value);
  1709. }
  1710. get class() {
  1711. return 'graph-node';
  1712. }
  1713. get inputs() {
  1714. return this.value.inputs;
  1715. }
  1716. get outputs() {
  1717. return this.value.outputs;
  1718. }
  1719. _add(node) {
  1720. const options = this.context.options;
  1721. const header = this.header();
  1722. const styles = [ 'node-item-type' ];
  1723. const type = node.type;
  1724. const category = type && type.category ? type.category : '';
  1725. if (category) {
  1726. styles.push('node-item-type-' + category.toLowerCase());
  1727. }
  1728. if (typeof type.name !== 'string' || !type.name.split) { // #416
  1729. const error = new view.Error("Unsupported node type '" + JSON.stringify(type.name) + "'.");
  1730. if (this.context.model && this.context.model.identifier) {
  1731. error.context = this.context.model.identifier;
  1732. }
  1733. throw error;
  1734. }
  1735. const content = options.names && (node.name || node.location) ? (node.name || node.location) : type.name.split('.').pop();
  1736. const tooltip = options.names && (node.name || node.location) ? type.name : (node.name || node.location);
  1737. const title = header.add(null, styles, content, tooltip);
  1738. title.on('click', () => this.context.activate(node));
  1739. if (node.type.nodes && node.type.nodes.length > 0) {
  1740. const definition = header.add(null, styles, '\u0192', 'Show Function Definition');
  1741. definition.on('click', () => this.context.view.pushGraph(node.type));
  1742. }
  1743. if (node.nodes) {
  1744. // this._expand = header.add(null, styles, '+', null);
  1745. // this._expand.on('click', () => this.toggle());
  1746. }
  1747. const initializers = [];
  1748. let hiddenInitializers = false;
  1749. if (options.weights) {
  1750. for (const input of node.inputs) {
  1751. if (input.visible !== false && input.value.length === 1 && input.value[0].initializer != null) {
  1752. initializers.push(input);
  1753. }
  1754. if ((input.visible === false || input.value.length > 1) &&
  1755. input.value.some((argument) => argument.initializer != null)) {
  1756. hiddenInitializers = true;
  1757. }
  1758. }
  1759. }
  1760. const objects = [];
  1761. const attributes = [];
  1762. if (Array.isArray(node.attributes) && node.attributes.length > 0) {
  1763. for (const attribute of node.attributes) {
  1764. switch (attribute.type) {
  1765. /* case 'object':
  1766. case 'function': {
  1767. objects.push(attribute);
  1768. break;
  1769. } */
  1770. default: {
  1771. if (options.attributes && attribute.visible !== false) {
  1772. attributes.push(attribute);
  1773. }
  1774. }
  1775. }
  1776. }
  1777. attributes.sort((a, b) => a.name.toUpperCase().localeCompare(b.name.toUpperCase()));
  1778. }
  1779. if (initializers.length > 0 || hiddenInitializers || attributes.length > 0 || objects.length > 0) {
  1780. const list = this.list();
  1781. list.on('click', () => this.context.activate(node));
  1782. for (const argument of initializers) {
  1783. const value = argument.value[0];
  1784. const type = value.type;
  1785. let shape = '';
  1786. let separator = '';
  1787. if (type && type.shape && type.shape.dimensions && Array.isArray(type.shape.dimensions)) {
  1788. shape = '\u3008' + type.shape.dimensions.map((d) => (d !== null && d !== undefined) ? d : '?').join('\u00D7') + '\u3009';
  1789. if (type.shape.dimensions.length === 0 && value.initializer) {
  1790. try {
  1791. const initializer = value.initializer;
  1792. const tensor = new view.Tensor(initializer);
  1793. const encoding = tensor.encoding;
  1794. if ((encoding === '<' || encoding === '>' || encoding === '|') && !tensor.empty && tensor.type.dataType !== '?') {
  1795. shape = tensor.toString();
  1796. if (shape && shape.length > 10) {
  1797. shape = shape.substring(0, 10) + '\u2026';
  1798. }
  1799. separator = ' = ';
  1800. }
  1801. } catch (err) {
  1802. let type = '?';
  1803. try {
  1804. type = value.initializer.type.toString();
  1805. } catch (error) {
  1806. // continue regardless of error
  1807. }
  1808. const error = new view.Error("Failed to render tensor of type '" + type + "' (" + err.message + ").");
  1809. if (this.context.view.model && this.context.view.model.identifier) {
  1810. error.context = this.context.view.model.identifier;
  1811. }
  1812. throw error;
  1813. }
  1814. }
  1815. }
  1816. list.add(argument.name, shape, type ? type.toString() : '', separator);
  1817. }
  1818. if (hiddenInitializers) {
  1819. list.add('\u3008\u2026\u3009', '', null, '');
  1820. }
  1821. for (const attribute of attributes) {
  1822. if (attribute.visible !== false) {
  1823. let value = new view.Formatter(attribute.value, attribute.type).toString();
  1824. if (value && value.length > 25) {
  1825. value = value.substring(0, 25) + '\u2026';
  1826. }
  1827. list.add(attribute.name, value, attribute.type, ' = ');
  1828. }
  1829. }
  1830. for (const attribute of objects) {
  1831. if (attribute.type === 'function' || attribute.type === 'object') {
  1832. const node = this.context.createNode(attribute.value);
  1833. const item = list.add(attribute.name, node, '', '');
  1834. item.height = 20;
  1835. }
  1836. }
  1837. }
  1838. if (Array.isArray(node.nodes) && node.nodes.length > 0) {
  1839. // this.canvas = this.canvas();
  1840. }
  1841. if (Array.isArray(node.chain) && node.chain.length > 0) {
  1842. for (const innerNode of node.chain) {
  1843. this.context.createNode(innerNode);
  1844. this._add(innerNode);
  1845. }
  1846. }
  1847. if (node.inner) {
  1848. this.context.createNode(node.inner);
  1849. this._add(node.inner);
  1850. }
  1851. }
  1852. toggle() {
  1853. this._expand.content = '-';
  1854. this._graph = new view.Graph(this.context.view, this.context.model, this.context.options, false, {});
  1855. this._graph.add(this.value);
  1856. // const document = this.element.ownerDocument;
  1857. // const parent = this.element.parentElement;
  1858. // this._graph.build(document, parent);
  1859. // this._graph.update();
  1860. this.canvas.width = 300;
  1861. this.canvas.height = 300;
  1862. this.layout();
  1863. this.context.update();
  1864. }
  1865. activate() {
  1866. this.context.view.showNodeProperties(this.value);
  1867. }
  1868. };
  1869. view.Input = class extends grapher.Node {
  1870. constructor(context, value) {
  1871. super();
  1872. this.context = context;
  1873. this.value = value;
  1874. view.Input.counter = view.Input.counter || 0;
  1875. const types = value.value.map((argument) => argument.type || '').join('\n');
  1876. let name = value.name || '';
  1877. if (name.length > 16) {
  1878. name = name.split('/').pop();
  1879. }
  1880. const header = this.header();
  1881. const title = header.add(null, [ 'graph-item-input' ], name, types);
  1882. title.on('click', () => this.context.view.showModelProperties());
  1883. this.id = 'input-' + (name ? 'name-' + name : 'id-' + (view.Input.counter++).toString());
  1884. }
  1885. get class() {
  1886. return 'graph-input';
  1887. }
  1888. get inputs() {
  1889. return [];
  1890. }
  1891. get outputs() {
  1892. return [ this.value ];
  1893. }
  1894. activate() {
  1895. this.context.view.showModelProperties();
  1896. }
  1897. };
  1898. view.Output = class extends grapher.Node {
  1899. constructor(context, value) {
  1900. super();
  1901. this.context = context;
  1902. this.value = value;
  1903. const types = value.value.map((argument) => argument.type || '').join('\n');
  1904. let name = value.name || '';
  1905. if (name.length > 16) {
  1906. name = name.split('/').pop();
  1907. }
  1908. const header = this.header();
  1909. const title = header.add(null, [ 'graph-item-output' ], name, types);
  1910. title.on('click', () => this.context.view.showModelProperties());
  1911. }
  1912. get inputs() {
  1913. return [ this.value ];
  1914. }
  1915. get outputs() {
  1916. return [];
  1917. }
  1918. activate() {
  1919. this.context.view.showModelProperties();
  1920. }
  1921. };
  1922. view.Value = class {
  1923. constructor(context, argument) {
  1924. this.context = context;
  1925. this.value = argument;
  1926. this.from = null;
  1927. this.to = [];
  1928. }
  1929. controlDependency(node) {
  1930. this._controlDependencies = this._controlDependencies || new Set();
  1931. this._controlDependencies.add(this.to.length);
  1932. this.to.push(node);
  1933. }
  1934. build() {
  1935. this._edges = this._edges || [];
  1936. if (this.from && Array.isArray(this.to)) {
  1937. for (let i = 0; i < this.to.length; i++) {
  1938. const to = this.to[i];
  1939. let content = '';
  1940. const type = this.value.type;
  1941. if (type &&
  1942. type.shape &&
  1943. type.shape.dimensions &&
  1944. type.shape.dimensions.length > 0 &&
  1945. type.shape.dimensions.every((dim) => !dim || Number.isInteger(dim) || dim instanceof base.Int64 || (typeof dim === 'string'))) {
  1946. content = type.shape.dimensions.map((dim) => (dim !== null && dim !== undefined) ? dim : '?').join('\u00D7');
  1947. content = content.length > 16 ? '' : content;
  1948. }
  1949. if (this.context.options.names) {
  1950. content = this.value.name.split('\n').shift(); // custom argument id
  1951. }
  1952. const edge = new view.Edge(this, this.from, to);
  1953. edge.v = this.from.name;
  1954. edge.w = to.name;
  1955. if (content) {
  1956. edge.label = content;
  1957. }
  1958. edge.id = 'edge-' + this.value.name;
  1959. if (this._controlDependencies && this._controlDependencies.has(i)) {
  1960. edge.class = 'edge-path-control-dependency';
  1961. }
  1962. this.context.setEdge(edge);
  1963. this._edges.push(edge);
  1964. }
  1965. }
  1966. }
  1967. select() {
  1968. let array = [];
  1969. for (const edge of this._edges) {
  1970. array = array.concat(edge.select());
  1971. }
  1972. return array;
  1973. }
  1974. deselect() {
  1975. for (const edge of this._edges) {
  1976. edge.deselect();
  1977. }
  1978. }
  1979. activate() {
  1980. if (this.value && this.from && Array.isArray(this.to)) {
  1981. const value = this.value;
  1982. const from = this.from.value;
  1983. const to = this.to.map((node) => node.value);
  1984. this.context.view.showConnectionProperties(value, from, to);
  1985. }
  1986. }
  1987. };
  1988. view.Edge = class extends grapher.Edge {
  1989. constructor(value, from, to) {
  1990. super(from, to);
  1991. this.value = value;
  1992. }
  1993. get minlen() {
  1994. if (this.from.inputs.every((argument) => argument.value.every((value) => value.initializer))) {
  1995. return 2;
  1996. }
  1997. return 1;
  1998. }
  1999. emit(event) {
  2000. switch (event) {
  2001. case 'pointerover': {
  2002. this.value.context.focus([ this.value.value ]);
  2003. break;
  2004. }
  2005. case 'pointerleave': {
  2006. this.value.context.blur([ this.value.value ]);
  2007. break;
  2008. }
  2009. case 'click': {
  2010. this.value.context.activate(this.value.value);
  2011. break;
  2012. }
  2013. default:
  2014. break;
  2015. }
  2016. }
  2017. };
  2018. view.Sidebar = class {
  2019. constructor(host) {
  2020. this._host = host;
  2021. this._stack = [];
  2022. const pop = () => this._update(this._stack.slice(0, -1));
  2023. this._closeSidebarHandler = () => pop();
  2024. this._closeSidebarKeyDownHandler = (e) => {
  2025. if (e.keyCode == 27) {
  2026. e.preventDefault();
  2027. pop();
  2028. }
  2029. };
  2030. const sidebar = this._element('sidebar');
  2031. sidebar.addEventListener('transitionend', (event) => {
  2032. if (event.propertyName === 'opacity' && sidebar.style.opacity === '0') {
  2033. const content = this._element('sidebar-content');
  2034. content.innerHTML = '';
  2035. }
  2036. });
  2037. }
  2038. _element(id) {
  2039. return this._host.document.getElementById(id);
  2040. }
  2041. open(content, title) {
  2042. this._update([ { title: title, content: content } ]);
  2043. }
  2044. close() {
  2045. this._update([]);
  2046. }
  2047. push(content, title) {
  2048. this._update(this._stack.concat({ title: title, content: content }));
  2049. }
  2050. _update(stack) {
  2051. const sidebar = this._element('sidebar');
  2052. const container = this._element('graph');
  2053. const closeButton = this._element('sidebar-closebutton');
  2054. closeButton.removeEventListener('click', this._closeSidebarHandler);
  2055. this._host.document.removeEventListener('keydown', this._closeSidebarKeyDownHandler);
  2056. if (stack) {
  2057. this._stack = stack;
  2058. } else if (this._stack.length > 0) {
  2059. this._stack.pop();
  2060. }
  2061. if (this._stack.length > 0) {
  2062. const item = this._stack[this._stack.length - 1];
  2063. this._element('sidebar-title').innerHTML = item.title || '';
  2064. closeButton.addEventListener('click', this._closeSidebarHandler);
  2065. const content = this._element('sidebar-content');
  2066. if (typeof item.content == 'string') {
  2067. content.innerHTML = item.content;
  2068. } else if (item.content instanceof Array) {
  2069. content.innerHTML = '';
  2070. for (const element of item.content) {
  2071. content.appendChild(element);
  2072. }
  2073. } else {
  2074. content.innerHTML = '';
  2075. content.appendChild(item.content);
  2076. }
  2077. sidebar.style.width = 'min(calc(100% * 0.6), 42em)';
  2078. sidebar.style.right = 0;
  2079. sidebar.style.opacity = 1;
  2080. this._host.document.addEventListener('keydown', this._closeSidebarKeyDownHandler);
  2081. container.style.width = 'max(40vw, calc(100vw - 42em))';
  2082. } else {
  2083. sidebar.style.right = 'calc(0px - min(calc(100% * 0.6), 42em))';
  2084. sidebar.style.opacity = 0;
  2085. container.style.width = '100%';
  2086. container.focus();
  2087. }
  2088. }
  2089. };
  2090. view.Control = class {
  2091. constructor(host) {
  2092. this._host = host;
  2093. }
  2094. createElement(tagName, className) {
  2095. const element = this._host.document.createElement(tagName);
  2096. if (className) {
  2097. element.setAttribute('class', className);
  2098. }
  2099. return element;
  2100. }
  2101. on(event, callback) {
  2102. this._events = this._events || {};
  2103. this._events[event] = this._events[event] || [];
  2104. this._events[event].push(callback);
  2105. }
  2106. emit(event, data) {
  2107. if (this._events && this._events[event]) {
  2108. for (const callback of this._events[event]) {
  2109. callback(this, data);
  2110. }
  2111. }
  2112. }
  2113. };
  2114. view.ObjectSidebar = class extends view.Control {
  2115. constructor(host) {
  2116. super(host);
  2117. this._container = this.createElement('div', 'sidebar-object');
  2118. }
  2119. add(name, item) {
  2120. const entry = new view.NameValueView(this._host, name, item);
  2121. const element = entry.render();
  2122. this._container.appendChild(element);
  2123. }
  2124. addProperty(name, value, style) {
  2125. const item = new view.ValueTextView(this._host, value, style);
  2126. this.add(name, item);
  2127. return item;
  2128. }
  2129. addHeader(title) {
  2130. const element = this.createElement('div', 'sidebar-header');
  2131. element.innerText = title;
  2132. this._container.appendChild(element);
  2133. }
  2134. render() {
  2135. return [ this._container ];
  2136. }
  2137. };
  2138. view.NodeSidebar = class extends view.ObjectSidebar {
  2139. constructor(host, node) {
  2140. super(host);
  2141. this._node = node;
  2142. this._attributes = [];
  2143. this._inputs = [];
  2144. this._outputs = [];
  2145. if (node.type) {
  2146. const type = node.type;
  2147. const item = this.addProperty('type', node.type.identifier || node.type.name);
  2148. if (type && (type.description || type.inputs || type.outputs || type.attributes)) {
  2149. item.action(type.nodes ? '\u0192': '?', () => {
  2150. this.emit('show-documentation', null);
  2151. });
  2152. }
  2153. if (node.type.module) {
  2154. this.addProperty('module', node.type.module);
  2155. }
  2156. }
  2157. if (node.name) {
  2158. this.addProperty('name', node.name);
  2159. }
  2160. if (node.location) {
  2161. this.addProperty('location', node.location);
  2162. }
  2163. if (node.description) {
  2164. this.addProperty('description', node.description);
  2165. }
  2166. if (node.device) {
  2167. this.addProperty('device', node.device);
  2168. }
  2169. const attributes = node.attributes;
  2170. if (Array.isArray(attributes) && attributes.length > 0) {
  2171. this.addHeader('Attributes');
  2172. attributes.sort((a, b) => {
  2173. const au = a.name.toUpperCase();
  2174. const bu = b.name.toUpperCase();
  2175. return (au < bu) ? -1 : (au > bu) ? 1 : 0;
  2176. });
  2177. for (const attribute of attributes) {
  2178. this._addAttribute(attribute.name, attribute);
  2179. }
  2180. }
  2181. const inputs = node.inputs;
  2182. if (Array.isArray(inputs) && inputs.length > 0) {
  2183. this.addHeader('Inputs');
  2184. for (const input of inputs) {
  2185. this._addInput(input.name, input);
  2186. }
  2187. }
  2188. const outputs = node.outputs;
  2189. if (Array.isArray(outputs) && outputs.length > 0) {
  2190. this.addHeader('Outputs');
  2191. for (const output of outputs) {
  2192. this._addOutput(output.name, output);
  2193. }
  2194. }
  2195. }
  2196. _addAttribute(name, attribute) {
  2197. let value = null;
  2198. switch (attribute.type) {
  2199. case 'tensor': {
  2200. value = new view.ValueView(this._host, { type: attribute.value.type, initializer: attribute.value }, '');
  2201. value.on('export-tensor', (sender, value) => this.emit('export-tensor', value));
  2202. value.on('error', (sender, value) => this.emit('error', value));
  2203. break;
  2204. }
  2205. case 'tensor[]': {
  2206. const values = attribute.value.map((value) => {
  2207. return { type: value.type, initializer: value };
  2208. });
  2209. value = new view.ArgumentView(this._host, { value: values }, '');
  2210. break;
  2211. }
  2212. default: {
  2213. value = new view.AttributeView(this._host, attribute);
  2214. value.on('show-graph', (sender, graph) => {
  2215. this.emit('show-graph', graph);
  2216. });
  2217. break;
  2218. }
  2219. }
  2220. const item = new view.NameValueView(this._host, name, value);
  2221. this._attributes.push(item);
  2222. this._container.appendChild(item.render());
  2223. }
  2224. _addInput(name, input) {
  2225. if (input.value.length > 0) {
  2226. const value = new view.ArgumentView(this._host, input);
  2227. value.on('export-tensor', (sender, value) => this.emit('export-tensor', value));
  2228. value.on('error', (sender, value) => this.emit('error', value));
  2229. value.on('activate', (sender, value) => this.emit('activate', value));
  2230. value.on('deactivate', (sender, value) => this.emit('deactivate', value));
  2231. value.on('select', (sender, value) => this.emit('select', value));
  2232. const item = new view.NameValueView(this._host, name, value);
  2233. this._inputs.push(item);
  2234. this._container.appendChild(item.render());
  2235. }
  2236. }
  2237. _addOutput(name, output) {
  2238. if (output.value.length > 0) {
  2239. const value = new view.ArgumentView(this._host, output);
  2240. value.on('activate', (sender, value) => this.emit('activate', value));
  2241. value.on('deactivate', (sender, value) => this.emit('deactivate', value));
  2242. value.on('select', (sender, value) => this.emit('select', value));
  2243. const item = new view.NameValueView(this._host, name, value);
  2244. this._outputs.push(item);
  2245. this._container.appendChild(item.render());
  2246. }
  2247. }
  2248. };
  2249. view.NameValueView = class extends view.Control {
  2250. constructor(host, name, value) {
  2251. super(host);
  2252. this._host = host;
  2253. this._name = name;
  2254. this._value = value;
  2255. const nameElement = this.createElement('div', 'sidebar-item-name');
  2256. const input = this.createElement('input');
  2257. input.setAttribute('type', 'text');
  2258. input.setAttribute('value', name);
  2259. input.setAttribute('title', name);
  2260. input.setAttribute('readonly', 'true');
  2261. nameElement.appendChild(input);
  2262. const valueElement = this.createElement('div', 'sidebar-item-value-list');
  2263. for (const element of value.render()) {
  2264. valueElement.appendChild(element);
  2265. }
  2266. this._element = this.createElement('div', 'sidebar-item');
  2267. this._element.appendChild(nameElement);
  2268. this._element.appendChild(valueElement);
  2269. }
  2270. get name() {
  2271. return this._name;
  2272. }
  2273. render() {
  2274. return this._element;
  2275. }
  2276. toggle() {
  2277. this._value.toggle();
  2278. }
  2279. };
  2280. view.SelectView = class extends view.Control {
  2281. constructor(host, values, selected) {
  2282. super();
  2283. this._host = host;
  2284. this._elements = [];
  2285. this._values = values;
  2286. const selectElement = this.createElement('select', 'sidebar-item-select');
  2287. selectElement.addEventListener('change', (e) => {
  2288. this.emit('change', this._values[e.target.selectedIndex]);
  2289. });
  2290. this._elements.push(selectElement);
  2291. for (const value of values) {
  2292. const optionElement = this.createElement('option');
  2293. optionElement.innerText = value.name || '';
  2294. if (value == selected) {
  2295. optionElement.setAttribute('selected', 'selected');
  2296. }
  2297. selectElement.appendChild(optionElement);
  2298. }
  2299. }
  2300. render() {
  2301. return this._elements;
  2302. }
  2303. };
  2304. view.ValueTextView = class extends view.Control {
  2305. constructor(host, value, style) {
  2306. super(host);
  2307. this._element = this.createElement('div', 'sidebar-item-value');
  2308. if (value) {
  2309. const list = Array.isArray(value) ? value : [ value ];
  2310. let className = 'sidebar-item-value-line';
  2311. for (const item of list) {
  2312. const line = this.createElement('div', className);
  2313. switch (style) {
  2314. case 'code':
  2315. line.innerHTML = '<code>' + item + '<code>';
  2316. break;
  2317. case 'bold':
  2318. line.innerHTML = '<b>' + item + '<b>';
  2319. break;
  2320. default:
  2321. line.innerText = item;
  2322. break;
  2323. }
  2324. this._element.appendChild(line);
  2325. className = 'sidebar-item-value-line-border';
  2326. }
  2327. }
  2328. }
  2329. action(text, callback) {
  2330. this._action = this.createElement('div', 'sidebar-item-value-expander');
  2331. this._action.innerHTML = text;
  2332. this._action.addEventListener('click', () => {
  2333. callback();
  2334. });
  2335. this._element.insertBefore(this._action, this._element.childNodes[0]);
  2336. }
  2337. render() {
  2338. return [ this._element ];
  2339. }
  2340. toggle() {
  2341. }
  2342. };
  2343. view.AttributeView = class extends view.Control {
  2344. constructor(host, attribute) {
  2345. super(host);
  2346. this._attribute = attribute;
  2347. this._element = this.createElement('div', 'sidebar-item-value');
  2348. const type = this._attribute.type;
  2349. if (type && type !== 'tensor') {
  2350. this._expander = this.createElement('div', 'sidebar-item-value-expander');
  2351. this._expander.innerText = '+';
  2352. this._expander.addEventListener('click', () => {
  2353. this.toggle();
  2354. });
  2355. this._element.appendChild(this._expander);
  2356. }
  2357. const value = this._attribute.value;
  2358. switch (type) {
  2359. case 'graph': {
  2360. const line = this.createElement('div', 'sidebar-item-value-line-link');
  2361. line.innerHTML = value.name;
  2362. line.addEventListener('click', () => {
  2363. this.emit('show-graph', value);
  2364. });
  2365. this._element.appendChild(line);
  2366. break;
  2367. }
  2368. case 'function': {
  2369. const line = this.createElement('div', 'sidebar-item-value-line-link');
  2370. line.innerHTML = value.type.name;
  2371. line.addEventListener('click', () => {
  2372. this.emit('show-graph', value.type);
  2373. });
  2374. this._element.appendChild(line);
  2375. break;
  2376. }
  2377. case 'tensor': {
  2378. throw new view.Error('Attribute view tensor not implemented.');
  2379. }
  2380. default: {
  2381. let content = new view.Formatter(value, type).toString();
  2382. if (content && content.length > 1000) {
  2383. content = content.substring(0, 1000) + '\u2026';
  2384. }
  2385. if (content && typeof content === 'string') {
  2386. content = content.split('<').join('&lt;').split('>').join('&gt;');
  2387. }
  2388. const line = this.createElement('div', 'sidebar-item-value-line');
  2389. line.innerHTML = content ? content : '&nbsp;';
  2390. this._element.appendChild(line);
  2391. }
  2392. }
  2393. }
  2394. render() {
  2395. return [ this._element ];
  2396. }
  2397. toggle() {
  2398. if (this._expander.innerText == '+') {
  2399. this._expander.innerText = '-';
  2400. const type = this._attribute.type;
  2401. const value = this._attribute.value;
  2402. const content = type == 'tensor' && value && value.type ? value.type.toString() : this._attribute.type;
  2403. const typeLine = this.createElement('div', 'sidebar-item-value-line-border');
  2404. typeLine.innerHTML = 'type: ' + '<code><b>' + content + '</b></code>';
  2405. this._element.appendChild(typeLine);
  2406. const description = this._attribute.description;
  2407. if (description) {
  2408. const descriptionLine = this.createElement('div', 'sidebar-item-value-line-border');
  2409. descriptionLine.innerHTML = description;
  2410. this._element.appendChild(descriptionLine);
  2411. }
  2412. } else {
  2413. this._expander.innerText = '+';
  2414. while (this._element.childElementCount > 2) {
  2415. this._element.removeChild(this._element.lastChild);
  2416. }
  2417. }
  2418. }
  2419. };
  2420. view.ArgumentView = class extends view.Control {
  2421. constructor(host, argument) {
  2422. super();
  2423. this._argument = argument;
  2424. this._elements = [];
  2425. this._items = [];
  2426. for (const value of argument.value) {
  2427. const item = new view.ValueView(host, value);
  2428. item.on('export-tensor', (sender, value) => this.emit('export-tensor', value));
  2429. item.on('error', (sender, value) => this.emit('error', value));
  2430. item.on('activate', (sender, value) => this.emit('activate', value));
  2431. item.on('deactivate', (sender, value) => this.emit('deactivate', value));
  2432. item.on('select', (sender, value) => this.emit('select', value));
  2433. this._items.push(item);
  2434. for (const element of item.render()) {
  2435. this._elements.push(element);
  2436. }
  2437. }
  2438. }
  2439. render() {
  2440. return this._elements;
  2441. }
  2442. toggle() {
  2443. for (const item of this._items) {
  2444. item.toggle();
  2445. }
  2446. }
  2447. };
  2448. view.ValueView = class extends view.Control {
  2449. constructor(host, value, name) {
  2450. super(host);
  2451. this._value = value;
  2452. this._element = this.createElement('div', 'sidebar-item-value');
  2453. const type = this._value.type;
  2454. const initializer = this._value.initializer;
  2455. const quantization = this._value.quantization;
  2456. const location = this._value.location !== undefined;
  2457. if (initializer) {
  2458. this._element.classList.add('sidebar-item-value-dark');
  2459. }
  2460. if (type || initializer || quantization || location || name === undefined) {
  2461. this._expander = this.createElement('div', 'sidebar-item-value-expander');
  2462. this._expander.innerText = '+';
  2463. this._expander.addEventListener('click', () => {
  2464. this.toggle();
  2465. });
  2466. this._element.appendChild(this._expander);
  2467. }
  2468. const tensor = name !== undefined;
  2469. name = this._value.name ? this._value.name.split('\n').shift() : ''; // custom argument id
  2470. this._hasId = name && !tensor ? true : false;
  2471. this._hasCategory = initializer && initializer.category ? true : false;
  2472. if (this._hasId || (!this._hasCategory && !type && !tensor)) {
  2473. this._hasId = true;
  2474. const nameLine = this.createElement('div', 'sidebar-item-value-line');
  2475. if (typeof name !== 'string') {
  2476. throw new Error("Invalid value identifier '" + JSON.stringify(name) + "'.");
  2477. }
  2478. nameLine.innerHTML = '<span class=\'sidebar-item-value-line-content\'>name: <b>' + (name || ' ') + '</b></span>';
  2479. nameLine.addEventListener('pointerenter', () => this.emit('activate', this._value));
  2480. nameLine.addEventListener('pointerleave', () => this.emit('deactivate', this._value));
  2481. if (!initializer) {
  2482. nameLine.style.cursor = 'pointer';
  2483. nameLine.addEventListener('click', () => this.emit('select', this._value));
  2484. }
  2485. this._element.appendChild(nameLine);
  2486. } else if (this._hasCategory) {
  2487. this._bold('category', initializer.category);
  2488. } else if (type) {
  2489. this._code('tensor', type.toString().split('<').join('&lt;').split('>').join('&gt;'));
  2490. }
  2491. }
  2492. render() {
  2493. return [ this._element ];
  2494. }
  2495. toggle() {
  2496. if (this._expander) {
  2497. if (this._expander.innerText == '+') {
  2498. this._expander.innerText = '-';
  2499. const initializer = this._value.initializer;
  2500. if (this._hasId && this._hasCategory) {
  2501. this._bold('category', initializer.category);
  2502. }
  2503. let type = null;
  2504. let denotation = null;
  2505. if (this._value.type) {
  2506. type = this._value.type.toString();
  2507. denotation = this._value.type.denotation || null;
  2508. }
  2509. if (type && (this._hasId || this._hasCategory)) {
  2510. this._code('tensor', type.split('<').join('&lt;').split('>').join('&gt;'));
  2511. }
  2512. if (denotation) {
  2513. this._code('denotation', denotation);
  2514. }
  2515. const description = this._value.description;
  2516. if (description) {
  2517. const descriptionLine = this.createElement('div', 'sidebar-item-value-line-border');
  2518. descriptionLine.innerHTML = description;
  2519. this._element.appendChild(descriptionLine);
  2520. }
  2521. const quantization = this._value.quantization;
  2522. if (quantization) {
  2523. const quantizationLine = this.createElement('div', 'sidebar-item-value-line-border');
  2524. const content = !Array.isArray(quantization) ? quantization : '<br><br>' + quantization.map((value) => ' ' + value).join('<br>');
  2525. quantizationLine.innerHTML = '<span class=\'sidebar-item-value-line-content\'>quantization: ' + '<b>' + content + '</b></span>';
  2526. this._element.appendChild(quantizationLine);
  2527. }
  2528. const location = this._value.location;
  2529. if (location !== undefined) {
  2530. this._bold('location', location);
  2531. }
  2532. const layout = this._value.type ? this._value.type.layout : null;
  2533. if (layout) {
  2534. const layouts = new Map([
  2535. [ 'sparse', 'sparse' ],
  2536. [ 'sparse.coo', 'sparse coo' ],
  2537. [ 'sparse.csr', 'sparse csr' ],
  2538. [ 'sparse.csc', 'sparse csc' ],
  2539. [ 'sparse.bsr', 'sparse bsr' ],
  2540. [ 'sparse.bsc', 'sparse bsc' ]
  2541. ]);
  2542. this._bold('layout', layouts.get(layout));
  2543. }
  2544. if (initializer) {
  2545. this._tensor(initializer);
  2546. }
  2547. } else {
  2548. this._expander.innerText = '+';
  2549. while (this._element.childElementCount > 2) {
  2550. this._element.removeChild(this._element.lastChild);
  2551. }
  2552. }
  2553. }
  2554. }
  2555. _bold(name, value) {
  2556. const line = this.createElement('div');
  2557. line.innerHTML = name + ': ' + '<b>' + value + '</b>';
  2558. this._add(line);
  2559. }
  2560. _code(name, value) {
  2561. const line = this.createElement('div');
  2562. line.innerHTML = name + ': ' + '<code><b>' + value + '</b></code>';
  2563. this._add(line);
  2564. }
  2565. _add(child) {
  2566. child.className = this._element.childNodes.length < 2 ? 'sidebar-item-value-line' : 'sidebar-item-value-line-border';
  2567. this._element.appendChild(child);
  2568. }
  2569. _tensor(value) {
  2570. const contentLine = this.createElement('pre');
  2571. try {
  2572. const tensor = new view.Tensor(value);
  2573. if (Array.isArray(tensor.stride) && tensor.stride.length > 0) {
  2574. this._code('stride', tensor.stride.join(','));
  2575. }
  2576. if (tensor.encoding !== '<' && tensor.encoding !== '>' && tensor.encoding !== '|') {
  2577. contentLine.innerHTML = "Tensor encoding '" + tensor.layout + "' is not implemented.";
  2578. } else if (tensor.layout && (tensor.layout !== 'sparse' && tensor.layout !== 'sparse.coo')) {
  2579. contentLine.innerHTML = "Tensor layout '" + tensor.layout + "' is not implemented.";
  2580. } else if (tensor.empty) {
  2581. contentLine.innerHTML = 'Tensor data is empty.';
  2582. } else if (tensor.type && tensor.type.dataType === '?') {
  2583. contentLine.innerHTML = 'Tensor data type is not defined.';
  2584. } else if (tensor.type && !tensor.type.shape) {
  2585. contentLine.innerHTML = 'Tensor shape is not defined.';
  2586. } else {
  2587. contentLine.innerHTML = tensor.toString();
  2588. if (this._host.save &&
  2589. value.type.shape && value.type.shape.dimensions &&
  2590. value.type.shape.dimensions.length > 0) {
  2591. this._saveButton = this.createElement('div', 'sidebar-item-value-expander');
  2592. this._saveButton.innerHTML = '&#x1F4BE;';
  2593. this._saveButton.addEventListener('click', () => {
  2594. this.emit('export-tensor', tensor);
  2595. });
  2596. this._element.appendChild(this._saveButton);
  2597. }
  2598. }
  2599. } catch (err) {
  2600. contentLine.innerHTML = err.toString();
  2601. this.emit('error', err);
  2602. }
  2603. const valueLine = this.createElement('div', 'sidebar-item-value-line-border');
  2604. valueLine.appendChild(contentLine);
  2605. this._element.appendChild(valueLine);
  2606. }
  2607. };
  2608. view.NodeView = class extends view.Control {
  2609. constructor(host, node) {
  2610. super(host);
  2611. this._node = node;
  2612. this._element = this.createElement('div', 'sidebar-item-value');
  2613. const name = node.name;
  2614. const type = node.type ? node.type.name : '';
  2615. if (name && type) {
  2616. this._expander = this.createElement('div', 'sidebar-item-value-expander');
  2617. this._expander.innerText = '+';
  2618. this._expander.addEventListener('click', () => {
  2619. this.toggle();
  2620. });
  2621. this._element.appendChild(this._expander);
  2622. }
  2623. if (type) {
  2624. const type = node.type.name;
  2625. const element = this.createElement('div', 'sidebar-item-value-line');
  2626. element.innerHTML = '<span class=\'sidebar-item-value-line-content\'>node: <b>' + (type || ' ') + '</b></span>';
  2627. element.addEventListener('pointerenter', () => this.emit('activate', this._node));
  2628. element.addEventListener('pointerleave', () => this.emit('deactivate', this._node));
  2629. element.addEventListener('click', () => this.emit('select', this._node));
  2630. element.style.cursor = 'pointer';
  2631. this._element.appendChild(element);
  2632. } else {
  2633. const element = this.createElement('div', 'sidebar-item-value-line');
  2634. element.innerHTML = '<span class=\'sidebar-item-value-line-content\'>name: <b>' + (name || ' ') + '</b></span>';
  2635. element.addEventListener('pointerenter', () => this.emit('activate', this._node));
  2636. element.addEventListener('pointerleave', () => this.emit('deactivate', this._node));
  2637. element.addEventListener('click', () => this.emit('select', this._node));
  2638. element.style.cursor = 'pointer';
  2639. this._element.appendChild(element);
  2640. }
  2641. }
  2642. render() {
  2643. return [ this._element ];
  2644. }
  2645. toggle() {
  2646. if (this._expander) {
  2647. if (this._expander.innerText == '+') {
  2648. this._expander.innerText = '-';
  2649. const name = this._node.name;
  2650. const element = this.createElement('div', 'sidebar-item-value-line-border');
  2651. element.innerHTML = '<span class=\'sidebar-item-value-line-content\'>name: <b>' + name + '</b></span>';
  2652. element.addEventListener('pointerenter', () => this.emit('activate', this._node));
  2653. element.addEventListener('pointerleave', () => this.emit('deactivate', this._node));
  2654. element.addEventListener('click', () => this.emit('select', this._node));
  2655. element.style.cursor = 'pointer';
  2656. this._element.appendChild(element);
  2657. } else {
  2658. this._expander.innerText = '+';
  2659. while (this._element.childElementCount > 2) {
  2660. this._element.removeChild(this._element.lastChild);
  2661. }
  2662. }
  2663. }
  2664. }
  2665. };
  2666. view.NodeListView = class extends view.Control {
  2667. constructor(host, list) {
  2668. super();
  2669. this._host = host;
  2670. this._elements = [];
  2671. for (const node of list) {
  2672. const item = new view.NodeView(host, node);
  2673. item.on('activate', (sender, value) => this.emit('activate', value));
  2674. item.on('deactivate', (sender, value) => this.emit('deactivate', value));
  2675. item.on('select', (sender, value) => this.emit('select', value));
  2676. item.toggle();
  2677. for (const element of item.render()) {
  2678. this._elements.push(element);
  2679. }
  2680. }
  2681. }
  2682. render() {
  2683. return this._elements;
  2684. }
  2685. };
  2686. view.ConnectionSidebar = class extends view.ObjectSidebar {
  2687. constructor(host, value, from, to) {
  2688. super(host);
  2689. this._host = host;
  2690. this._value = value;
  2691. this._from = from;
  2692. this._to = to;
  2693. const name = value.name.split('\n')[0];
  2694. this.addProperty('name', name);
  2695. if (value.type) {
  2696. const item = new view.ValueView(this._host, value, '');
  2697. this.add('type', item);
  2698. item.toggle();
  2699. }
  2700. if (from) {
  2701. this.addHeader('Inputs');
  2702. const list = new view.NodeListView(host, [ from ]);
  2703. list.on('activate', (sender, value) => this.emit('activate', value));
  2704. list.on('deactivate', (sender, value) => this.emit('deactivate', value));
  2705. list.on('select', (sender, value) => this.emit('select', value));
  2706. const item = new view.NameValueView(this._host, 'from', list);
  2707. this._container.appendChild(item.render());
  2708. }
  2709. if (Array.isArray(to) && to.length > 0) {
  2710. this.addHeader('Outputs');
  2711. const list = new view.NodeListView(this._host, to);
  2712. list.on('activate', (sender, value) => this.emit('activate', value));
  2713. list.on('deactivate', (sender, value) => this.emit('deactivate', value));
  2714. list.on('select', (sender, value) => this.emit('select', value));
  2715. const item = new view.NameValueView(this._host, 'to', list);
  2716. this._container.appendChild(item.render());
  2717. }
  2718. }
  2719. };
  2720. view.ModelSidebar = class extends view.ObjectSidebar {
  2721. constructor(host, model, graph) {
  2722. super(host);
  2723. this._model = model;
  2724. if (model.format) {
  2725. this.addProperty('format', model.format);
  2726. }
  2727. if (model.producer) {
  2728. this.addProperty('producer', model.producer);
  2729. }
  2730. if (model.name) {
  2731. this.addProperty('name', model.name);
  2732. }
  2733. if (model.version) {
  2734. this.addProperty('version', model.version);
  2735. }
  2736. if (model.description) {
  2737. this.addProperty('description', model.description);
  2738. }
  2739. if (model.domain) {
  2740. this.addProperty('domain', model.domain);
  2741. }
  2742. if (model.imports) {
  2743. this.addProperty('imports', model.imports);
  2744. }
  2745. if (model.runtime) {
  2746. this.addProperty('runtime', model.runtime);
  2747. }
  2748. if (model.metadata) {
  2749. for (const entry of model.metadata) {
  2750. this.addProperty(entry.name, entry.value);
  2751. }
  2752. }
  2753. const graphs = Array.isArray(model.graphs) ? model.graphs : [];
  2754. if (graphs.length === 1 && graphs[0].name) {
  2755. this.addProperty('graph', graphs[0].name);
  2756. } else if (graphs.length > 1) {
  2757. const selector = new view.SelectView(this._host, model.graphs, graph);
  2758. selector.on('change', (sender, data) => this.emit('update-active-graph', data));
  2759. this.add('graph', selector);
  2760. }
  2761. if (graph) {
  2762. if (graph.version) {
  2763. this.addProperty('version', graph.version);
  2764. }
  2765. if (graph.type) {
  2766. this.addProperty('type', graph.type);
  2767. }
  2768. if (graph.tags) {
  2769. this.addProperty('tags', graph.tags);
  2770. }
  2771. if (graph.description) {
  2772. this.addProperty('description', graph.description);
  2773. }
  2774. if (Array.isArray(graph.inputs) && graph.inputs.length > 0) {
  2775. this.addHeader('Inputs');
  2776. for (const input of graph.inputs) {
  2777. this.addArgument(input.name, input);
  2778. }
  2779. }
  2780. if (Array.isArray(graph.outputs) && graph.outputs.length > 0) {
  2781. this.addHeader('Outputs');
  2782. for (const output of graph.outputs) {
  2783. this.addArgument(output.name, output);
  2784. }
  2785. }
  2786. }
  2787. }
  2788. render() {
  2789. return [ this._container ];
  2790. }
  2791. addArgument(name, argument) {
  2792. const value = new view.ArgumentView(this._host, argument);
  2793. value.toggle();
  2794. const item = new view.NameValueView(this._host, name, value);
  2795. this._container.appendChild(item.render());
  2796. }
  2797. };
  2798. view.DocumentationSidebar = class extends view.Control {
  2799. constructor(host, type) {
  2800. super();
  2801. this._host = host;
  2802. this._type = type;
  2803. }
  2804. render() {
  2805. if (!this._elements) {
  2806. this._elements = [];
  2807. const type = view.Documentation.format(this._type);
  2808. const element = this.createElement('div', 'sidebar-documentation');
  2809. this._append(element, 'h1', type.name);
  2810. if (type.summary) {
  2811. this._append(element, 'p', type.summary);
  2812. }
  2813. if (type.description) {
  2814. this._append(element, 'p', type.description);
  2815. }
  2816. if (Array.isArray(type.attributes) && type.attributes.length > 0) {
  2817. this._append(element, 'h2', 'Attributes');
  2818. const attributes = this._append(element, 'dl');
  2819. for (const attribute of type.attributes) {
  2820. this._append(attributes, 'dt', attribute.name + (attribute.type ? ': <tt>' + attribute.type + '</tt>' : ''));
  2821. this._append(attributes, 'dd', attribute.description);
  2822. }
  2823. element.appendChild(attributes);
  2824. }
  2825. if (Array.isArray(type.inputs) && type.inputs.length > 0) {
  2826. this._append(element, 'h2', 'Inputs' + (type.inputs_range ? ' (' + type.inputs_range + ')' : ''));
  2827. const inputs = this._append(element, 'dl');
  2828. for (const input of type.inputs) {
  2829. this._append(inputs, 'dt', input.name + (input.type ? ': <tt>' + input.type + '</tt>' : '') + (input.option ? ' (' + input.option + ')' : ''));
  2830. this._append(inputs, 'dd', input.description);
  2831. }
  2832. }
  2833. if (Array.isArray(type.outputs) && type.outputs.length > 0) {
  2834. this._append(element, 'h2', 'Outputs' + (type.outputs_range ? ' (' + type.outputs_range + ')' : ''));
  2835. const outputs = this._append(element, 'dl');
  2836. for (const output of type.outputs) {
  2837. this._append(outputs, 'dt', output.name + (output.type ? ': <tt>' + output.type + '</tt>' : '') + (output.option ? ' (' + output.option + ')' : ''));
  2838. this._append(outputs, 'dd', output.description);
  2839. }
  2840. }
  2841. if (Array.isArray(type.type_constraints) && type.type_constraints.length > 0) {
  2842. this._append(element, 'h2', 'Type Constraints');
  2843. const type_constraints = this._append(element, 'dl');
  2844. for (const type_constraint of type.type_constraints) {
  2845. this._append(type_constraints, 'dt', type_constraint.type_param_str + ': ' + type_constraint.allowed_type_strs.map((item) => '<tt>' + item + '</tt>').join(', '));
  2846. this._append(type_constraints, 'dd', type_constraint.description);
  2847. }
  2848. }
  2849. if (Array.isArray(type.examples) && type.examples.length > 0) {
  2850. this._append(element, 'h2', 'Examples');
  2851. for (const example of type.examples) {
  2852. this._append(element, 'h3', example.summary);
  2853. this._append(element, 'pre', example.code);
  2854. }
  2855. }
  2856. if (Array.isArray(type.references) && type.references.length > 0) {
  2857. this._append(element, 'h2', 'References');
  2858. const references = this._append(element, 'ul');
  2859. for (const reference of type.references) {
  2860. this._append(references, 'li', reference.description);
  2861. }
  2862. }
  2863. if (type.domain && type.version && type.support_level) {
  2864. this._append(element, 'h2', 'Support');
  2865. this._append(element, 'dl', 'In domain <tt>' + type.domain + '</tt> since version <tt>' + type.version + '</tt> at support level <tt>' + type.support_level + '</tt>.');
  2866. }
  2867. if (this._host.type === 'Electron') {
  2868. element.addEventListener('click', (e) => {
  2869. if (e.target && e.target.href) {
  2870. const url = e.target.href;
  2871. if (url.startsWith('http://') || url.startsWith('https://')) {
  2872. e.preventDefault();
  2873. this.emit('navigate', { link: url });
  2874. }
  2875. }
  2876. });
  2877. }
  2878. this._elements = [ element ];
  2879. }
  2880. return this._elements;
  2881. }
  2882. _append(parent, type, content) {
  2883. const element = this.createElement(type);
  2884. if (content) {
  2885. element.innerHTML = content;
  2886. }
  2887. parent.appendChild(element);
  2888. return element;
  2889. }
  2890. };
  2891. view.FindSidebar = class extends view.Control {
  2892. constructor(host, graph) {
  2893. super(host);
  2894. this._graph = graph;
  2895. this._table = new Map();
  2896. this._searchElement = this.createElement('input', 'sidebar-find-search');
  2897. this._searchElement.setAttribute('id', 'search');
  2898. this._searchElement.setAttribute('type', 'text');
  2899. this._searchElement.setAttribute('spellcheck', 'false');
  2900. this._searchElement.setAttribute('placeholder', 'Search');
  2901. this._searchElement.addEventListener('input', (e) => {
  2902. this.update(e.target.value);
  2903. this.emit('search-text-changed', e.target.value);
  2904. });
  2905. this._contentElement = this.createElement('ol', 'sidebar-find-content');
  2906. this._contentElement.addEventListener('click', (e) => {
  2907. const identifier = e.target.getAttribute('data');
  2908. if (this._table.has(identifier)) {
  2909. this.emit('select', this._table.get(identifier));
  2910. }
  2911. });
  2912. }
  2913. on(event, callback) {
  2914. this._events = this._events || {};
  2915. this._events[event] = this._events[event] || [];
  2916. this._events[event].push(callback);
  2917. }
  2918. emit(event, data) {
  2919. if (this._events && this._events[event]) {
  2920. for (const callback of this._events[event]) {
  2921. callback(this, data);
  2922. }
  2923. }
  2924. }
  2925. focus(searchText) {
  2926. this._searchElement.focus();
  2927. this._searchElement.value = '';
  2928. this._searchElement.value = searchText;
  2929. this.update(searchText);
  2930. }
  2931. update(searchText) {
  2932. while (this._contentElement.lastChild) {
  2933. this._contentElement.removeChild(this._contentElement.lastChild);
  2934. }
  2935. this._table.clear();
  2936. let index = 0;
  2937. const add = (value, content) => {
  2938. const key = index.toString();
  2939. index++;
  2940. this._table.set(key, value);
  2941. const element = this.createElement('li');
  2942. element.innerText = content;
  2943. element.setAttribute('data', key);
  2944. element.addEventListener('pointerover', (e) => {
  2945. const identifier = e.target.getAttribute('data');
  2946. if (this._table.has(identifier)) {
  2947. this.emit('focus', this._table.get(identifier));
  2948. }
  2949. });
  2950. element.addEventListener('pointerleave', (e) => {
  2951. const identifier = e.target.getAttribute('data');
  2952. if (this._table.has(identifier)) {
  2953. this.emit('blur', this._table.get(identifier));
  2954. }
  2955. });
  2956. this._contentElement.appendChild(element);
  2957. };
  2958. let terms = null;
  2959. let match = null;
  2960. const unquote = searchText.match(new RegExp(/^'(.*)'|"(.*)"$/));
  2961. if (unquote) {
  2962. const term = unquote[1] || unquote[2];
  2963. terms = [ term ];
  2964. match = (name) => {
  2965. return term == name;
  2966. };
  2967. } else {
  2968. terms = searchText.trim().toLowerCase().split(' ').map((term) => term.trim()).filter((term) => term.length > 0);
  2969. match = (name) => {
  2970. return terms.every((term) => name.toLowerCase().indexOf(term) !== -1);
  2971. };
  2972. }
  2973. const edges = new Set();
  2974. const arg = (argument) => {
  2975. if (terms.length === 0) {
  2976. return true;
  2977. }
  2978. let match = false;
  2979. for (const term of terms) {
  2980. if (argument.name && argument.name.toLowerCase().indexOf(term) !== -1) {
  2981. match = true;
  2982. break;
  2983. }
  2984. if (argument.type) {
  2985. if (argument.type.dataType && term === argument.type.dataType.toLowerCase()) {
  2986. match = true;
  2987. break;
  2988. }
  2989. if (argument.type.shape) {
  2990. if (term === argument.type.shape.toString().toLowerCase()) {
  2991. match = true;
  2992. break;
  2993. }
  2994. if (argument.type.shape && Array.isArray(argument.type.shape.dimensions)) {
  2995. const dimensions = argument.type.shape.dimensions.map((dimension) => dimension ? dimension.toString().toLowerCase() : '');
  2996. if (term === dimensions.join(',')) {
  2997. match = true;
  2998. break;
  2999. }
  3000. if (dimensions.some((dimension) => term === dimension)) {
  3001. match = true;
  3002. break;
  3003. }
  3004. }
  3005. }
  3006. }
  3007. }
  3008. return match;
  3009. };
  3010. const edge = (argument) => {
  3011. if (argument.name && !edges.has(argument.name) && arg(argument)) {
  3012. add(argument, '\u2192 ' + argument.name.split('\n').shift()); // split custom argument id
  3013. edges.add(argument.name);
  3014. }
  3015. };
  3016. for (const input of this._graph.inputs) {
  3017. for (const value of input.value) {
  3018. edge(value);
  3019. }
  3020. }
  3021. for (const node of this._graph.nodes) {
  3022. const initializers = [];
  3023. for (const input of node.inputs) {
  3024. for (const value of input.value) {
  3025. if (value.initializer) {
  3026. initializers.push(value);
  3027. } else {
  3028. edge(value);
  3029. }
  3030. }
  3031. }
  3032. const name = node.name;
  3033. const type = node.type.name;
  3034. if ((name && match(name)) || (type && match(type))) {
  3035. add(node, '\u25A2 ' + (name || '[' + type + ']'));
  3036. }
  3037. for (const value of initializers) {
  3038. if (value.name && !edges.has(value.name) && arg(value)) {
  3039. add(node, '\u25A0 ' + value.name.split('\n').shift()); // split custom argument id
  3040. }
  3041. }
  3042. }
  3043. for (const output of this._graph.outputs) {
  3044. for (const value of output.value) {
  3045. edge(value);
  3046. }
  3047. }
  3048. this._contentElement.style.display = this._contentElement.childNodes.length != 0 ? 'block' : 'none';
  3049. }
  3050. render() {
  3051. return [ this._searchElement, this._contentElement ];
  3052. }
  3053. };
  3054. view.Tensor = class {
  3055. constructor(tensor) {
  3056. this._tensor = tensor;
  3057. this._type = tensor.type;
  3058. this._encoding = tensor.encoding;
  3059. this._layout = tensor.type.layout;
  3060. this._stride = tensor.stride;
  3061. switch (this._encoding) {
  3062. case undefined:
  3063. case '':
  3064. case '<': {
  3065. this._data = this._tensor.values;
  3066. this._encoding = '<';
  3067. this._littleEndian = true;
  3068. break;
  3069. }
  3070. case '>': {
  3071. this._data = this._tensor.values;
  3072. this._encoding = '>';
  3073. this._littleEndian = false;
  3074. break;
  3075. }
  3076. case '|': {
  3077. this._values = this._tensor.values;
  3078. this._encoding = '|';
  3079. break;
  3080. }
  3081. default: {
  3082. throw new view.Error("Unsupported tensor encoding '" + this._encoding + "'.");
  3083. }
  3084. }
  3085. switch (this._layout) {
  3086. case 'sparse':
  3087. case 'sparse.coo': {
  3088. this._indices = this._tensor.indices;
  3089. this._values = this._tensor.values;
  3090. break;
  3091. }
  3092. default: {
  3093. break;
  3094. }
  3095. }
  3096. view.Tensor.dataTypes = view.Tensor.dataTypeSizes || new Map([
  3097. [ 'boolean', 1 ],
  3098. [ 'qint8', 1 ], [ 'qint16', 2 ], [ 'qint32', 4 ],
  3099. [ 'quint8', 1 ], [ 'quint16', 2 ], [ 'quint32', 4 ],
  3100. [ 'xint8', 1 ],
  3101. [ 'int8', 1 ], [ 'int16', 2 ], [ 'int32', 4 ], [ 'int64', 8 ],
  3102. [ 'uint8', 1 ], [ 'uint16', 2 ], [ 'uint32', 4, ], [ 'uint64', 8 ],
  3103. [ 'float16', 2 ], [ 'float32', 4 ], [ 'float64', 8 ], [ 'bfloat16', 2 ],
  3104. [ 'complex64', 8 ], [ 'complex128', 16 ],
  3105. [ 'float8e4m3fn', 1 ], [ 'float8e4m3fnuz', 1 ], [ 'float8e5m2', 1 ], [ 'float8e5m2fnuz', 1 ]
  3106. ]);
  3107. }
  3108. get type() {
  3109. return this._type;
  3110. }
  3111. get encoding() {
  3112. return this._encoding;
  3113. }
  3114. get layout() {
  3115. return this._layout;
  3116. }
  3117. get stride() {
  3118. return this._stride;
  3119. }
  3120. get empty() {
  3121. switch (this._layout) {
  3122. case 'sparse':
  3123. case 'sparse.coo': {
  3124. return !this._values || this.indices || this._values.values === null || this._values.values.length === 0;
  3125. }
  3126. default: {
  3127. switch (this._encoding) {
  3128. case '<':
  3129. case '>':
  3130. return !(Array.isArray(this._data) || this._data instanceof Uint8Array || this._data instanceof Int8Array) || this._data.length === 0;
  3131. case '|':
  3132. return !(Array.isArray(this._values) || ArrayBuffer.isView(this._values)) || this._values.length === 0;
  3133. default:
  3134. throw new Error("Unsupported tensor encoding '" + this._encoding + "'.");
  3135. }
  3136. }
  3137. }
  3138. }
  3139. get value() {
  3140. const context = this._context();
  3141. context.limit = Number.MAX_SAFE_INTEGER;
  3142. switch (context.encoding) {
  3143. case '<':
  3144. case '>': {
  3145. return this._decodeData(context, 0, 0);
  3146. }
  3147. case '|': {
  3148. return this._decodeValues(context, 0, 0);
  3149. }
  3150. default: {
  3151. throw new Error("Unsupported tensor encoding '" + context.encoding + "'.");
  3152. }
  3153. }
  3154. }
  3155. toString() {
  3156. const context = this._context();
  3157. context.limit = 10000;
  3158. switch (context.encoding) {
  3159. case '<':
  3160. case '>': {
  3161. const value = this._decodeData(context, 0, 0);
  3162. return view.Tensor._stringify(value, '', ' ');
  3163. }
  3164. case '|': {
  3165. const value = this._decodeValues(context, 0, 0);
  3166. return view.Tensor._stringify(value, '', ' ');
  3167. }
  3168. default: {
  3169. throw new Error("Unsupported tensor encoding '" + context.encoding + "'.");
  3170. }
  3171. }
  3172. }
  3173. _context() {
  3174. if (this._encoding !== '<' && this._encoding !== '>' && this._encoding !== '|') {
  3175. throw new Error("Tensor encoding '" + this._encoding + "' is not supported.");
  3176. }
  3177. if (this._layout && (this._layout !== 'sparse' && this._layout !== 'sparse.coo')) {
  3178. throw new Error("Tensor layout '" + this._layout + "' is not supported.");
  3179. }
  3180. const dataType = this._type.dataType;
  3181. const context = {};
  3182. context.encoding = this._encoding;
  3183. context.dimensions = this._type.shape.dimensions.map((value) => !Number.isInteger(value) && value.toNumber ? value.toNumber() : value);
  3184. context.dataType = dataType;
  3185. const shape = context.dimensions;
  3186. context.stride = this._stride;
  3187. if (!Array.isArray(context.stride)) {
  3188. context.stride = new Array(shape.length);
  3189. let value = 1;
  3190. for (let i = shape.length - 1; i >= 0; i--) {
  3191. context.stride[i] = value;
  3192. value *= shape[i];
  3193. }
  3194. }
  3195. switch (this._layout) {
  3196. case 'sparse': {
  3197. const indices = new view.Tensor(this._indices).value;
  3198. const values = new view.Tensor(this._values).value;
  3199. context.data = this._decodeSparse(dataType, context.dimensions, indices, values);
  3200. context.encoding = '|';
  3201. break;
  3202. }
  3203. case 'sparse.coo': {
  3204. const values = new view.Tensor(this._values).value;
  3205. const data = new view.Tensor(this._indices).value;
  3206. const dimensions = context.dimensions.length;
  3207. let stride = 1;
  3208. const strides = context.dimensions.slice().reverse().map((dim) => {
  3209. const value = stride;
  3210. stride *= dim;
  3211. return value;
  3212. }).reverse();
  3213. const indices = new Uint32Array(values.length);
  3214. for (let i = 0; i < dimensions; i++) {
  3215. const stride = strides[i];
  3216. const dimension = data[i];
  3217. for (let i = 0; i < indices.length; i++) {
  3218. indices[i] += dimension[i] * stride;
  3219. }
  3220. }
  3221. context.data = this._decodeSparse(dataType, context.dimensions, indices, values);
  3222. context.encoding = '|';
  3223. break;
  3224. }
  3225. default: {
  3226. switch (this._encoding) {
  3227. case '<':
  3228. case '>': {
  3229. context.data = (this._data instanceof Uint8Array || this._data instanceof Int8Array) ? this._data : this._data.peek();
  3230. context.view = new DataView(context.data.buffer, context.data.byteOffset, context.data.byteLength);
  3231. if (view.Tensor.dataTypes.has(dataType)) {
  3232. const itemsize = view.Tensor.dataTypes.get(dataType);
  3233. const length = context.data.length;
  3234. const stride = context.stride;
  3235. if (length < (itemsize * shape.reduce((a, v) => a * v, 1))) {
  3236. const max = stride.reduce((a, v, i) => v > stride[i] ? i : a, 0);
  3237. if (length !== (itemsize * stride[max] * shape[max])) {
  3238. throw new Error('Invalid tensor data size.');
  3239. }
  3240. }
  3241. context.itemsize = itemsize;
  3242. context.stride = stride.map((v) => v * itemsize);
  3243. } else if (dataType.startsWith('uint') && !isNaN(parseInt(dataType.substring(4), 10))) {
  3244. context.dataType = 'uint';
  3245. context.bits = parseInt(dataType.substring(4), 10);
  3246. context.itemsize = 1;
  3247. } else if (dataType.startsWith('int') && !isNaN(parseInt(dataType.substring(3), 10))) {
  3248. context.dataType = 'int';
  3249. context.bits = parseInt(dataType.substring(3), 10);
  3250. context.itemsize = 1;
  3251. } else {
  3252. throw new Error("Tensor data type '" + dataType + "' is not implemented.");
  3253. }
  3254. break;
  3255. }
  3256. case '|': {
  3257. context.data = this._values;
  3258. if (!view.Tensor.dataTypes.has(dataType) && dataType !== 'string' && dataType !== 'object') {
  3259. throw new Error("Tensor data type '" + dataType + "' is not implemented.");
  3260. }
  3261. const size = context.dimensions.reduce((a, v) => a * v, 1);
  3262. if (size !== this._values.length) {
  3263. throw new Error('Invalid tensor data length.');
  3264. }
  3265. break;
  3266. }
  3267. default: {
  3268. throw new view.Tensor("Unsupported tensor encoding '" + this._encoding + "'.");
  3269. }
  3270. }
  3271. }
  3272. }
  3273. context.index = 0;
  3274. context.count = 0;
  3275. return context;
  3276. }
  3277. _decodeSparse(dataType, dimensions, indices, values) {
  3278. const size = dimensions.reduce((a, b) => a * b, 1);
  3279. const array = new Array(size);
  3280. switch (dataType) {
  3281. case 'boolean':
  3282. array.fill(false);
  3283. break;
  3284. default:
  3285. array.fill(0);
  3286. break;
  3287. }
  3288. if (indices.length > 0) {
  3289. if (Object.prototype.hasOwnProperty.call(indices[0], 'low')) {
  3290. for (let i = 0; i < indices.length; i++) {
  3291. const index = indices[i];
  3292. array[index.high === 0 ? index.low : index.toNumber()] = values[i];
  3293. }
  3294. } else {
  3295. for (let i = 0; i < indices.length; i++) {
  3296. array[indices[i]] = values[i];
  3297. }
  3298. }
  3299. }
  3300. return array;
  3301. }
  3302. _decodeData(context, dimension, offset) {
  3303. const results = [];
  3304. const shape = context.dimensions.length == 0 ? [ 1 ] : context.dimensions;
  3305. const size = shape[dimension];
  3306. const dataType = context.dataType;
  3307. const view = context.view;
  3308. const stride = context.stride[dimension];
  3309. if (dimension == shape.length - 1) {
  3310. const ellipsis = (context.count + size) > context.limit;
  3311. const length = ellipsis ? context.limit - context.count : size;
  3312. const max = offset + (length * context.itemsize);
  3313. switch (dataType) {
  3314. case 'boolean':
  3315. for (; offset < max; offset += stride) {
  3316. results.push(view.getUint8(offset) === 0 ? false : true);
  3317. }
  3318. break;
  3319. case 'qint8':
  3320. case 'xint8':
  3321. case 'int8':
  3322. for (; offset < max; offset += stride) {
  3323. results.push(view.getInt8(offset));
  3324. }
  3325. break;
  3326. case 'qint16':
  3327. case 'int16':
  3328. for (; offset < max; offset += stride) {
  3329. results.push(view.getInt16(offset, this._littleEndian));
  3330. }
  3331. break;
  3332. case 'qint32':
  3333. case 'int32':
  3334. for (; offset < max; offset += stride) {
  3335. results.push(view.getInt32(offset, this._littleEndian));
  3336. }
  3337. break;
  3338. case 'int64':
  3339. for (; offset < max; offset += stride) {
  3340. results.push(view.getInt64(offset, this._littleEndian));
  3341. }
  3342. break;
  3343. case 'int':
  3344. for (; offset < size; offset += stride) {
  3345. results.push(view.getIntBits(offset, context.bits));
  3346. }
  3347. break;
  3348. case 'quint8':
  3349. case 'uint8':
  3350. for (; offset < max; offset += stride) {
  3351. results.push(view.getUint8(offset));
  3352. }
  3353. break;
  3354. case 'quint16':
  3355. case 'uint16':
  3356. for (; offset < max; offset += stride) {
  3357. results.push(view.getUint16(offset, true));
  3358. }
  3359. break;
  3360. case 'quint32':
  3361. case 'uint32':
  3362. for (; offset < max; offset += stride) {
  3363. results.push(view.getUint32(offset, true));
  3364. }
  3365. break;
  3366. case 'uint64':
  3367. for (; offset < max; offset += stride) {
  3368. results.push(view.getUint64(offset, true));
  3369. }
  3370. break;
  3371. case 'uint':
  3372. for (; offset < max; offset += stride) {
  3373. results.push(view.getUintBits(offset, context.bits));
  3374. }
  3375. break;
  3376. case 'float16':
  3377. for (; offset < max; offset += stride) {
  3378. results.push(view.getFloat16(offset, this._littleEndian));
  3379. }
  3380. break;
  3381. case 'float32':
  3382. for (; offset < max; offset += stride) {
  3383. results.push(view.getFloat32(offset, this._littleEndian));
  3384. }
  3385. break;
  3386. case 'float64':
  3387. for (; offset < max; offset += stride) {
  3388. results.push(view.getFloat64(offset, this._littleEndian));
  3389. }
  3390. break;
  3391. case 'bfloat16':
  3392. for (; offset < max; offset += stride) {
  3393. results.push(view.getBfloat16(offset, this._littleEndian));
  3394. }
  3395. break;
  3396. case 'complex64':
  3397. for (; offset < max; offset += stride) {
  3398. results.push(view.getComplex64(offset, this._littleEndian));
  3399. }
  3400. break;
  3401. case 'complex128':
  3402. for (; offset < size; offset += stride) {
  3403. results.push(view.getComplex128(offset, this._littleEndian));
  3404. }
  3405. break;
  3406. case 'float8e4m3fn':
  3407. for (; offset < size; offset += stride) {
  3408. results.push(view.getFloat8e4m3(offset, true, false));
  3409. }
  3410. break;
  3411. case 'float8e4m3fnuz':
  3412. for (; offset < size; offset += stride) {
  3413. results.push(view.getFloat8e4m3(offset, true, true));
  3414. }
  3415. break;
  3416. case 'float8e5m2':
  3417. for (; offset < size; offset += stride) {
  3418. results.push(view.getFloat8e5m2(offset, false, false));
  3419. }
  3420. break;
  3421. case 'float8e5m2fnuz':
  3422. for (; offset < size; offset += stride) {
  3423. results.push(view.getFloat8e5m2(offset, true, true));
  3424. }
  3425. break;
  3426. default:
  3427. throw new Error("Unsupported tensor data type '" + dataType + "'.");
  3428. }
  3429. context.count += length;
  3430. if (ellipsis) {
  3431. results.push('...');
  3432. }
  3433. } else {
  3434. for (let j = 0; j < size; j++) {
  3435. if (context.count >= context.limit) {
  3436. results.push('...');
  3437. return results;
  3438. }
  3439. const nextOffset = offset + (j * stride);
  3440. results.push(this._decodeData(context, dimension + 1, nextOffset));
  3441. }
  3442. }
  3443. if (context.dimensions.length == 0) {
  3444. return results[0];
  3445. }
  3446. return results;
  3447. }
  3448. _decodeValues(context, dimension, position) {
  3449. const results = [];
  3450. const shape = (context.dimensions.length == 0) ? [ 1 ] : context.dimensions;
  3451. const size = shape[dimension];
  3452. const dataType = context.dataType;
  3453. const stride = context.stride[dimension];
  3454. if (dimension == shape.length - 1) {
  3455. const ellipsis = (context.count + size) > context.limit;
  3456. const length = ellipsis ? context.limit - context.count : size;
  3457. const data = context.data;
  3458. for (let i = 0; i < length; i++) {
  3459. if (context.count > context.limit) {
  3460. results.push('...');
  3461. return results;
  3462. }
  3463. switch (dataType) {
  3464. case 'boolean':
  3465. results.push(data[position] === 0 ? false : true);
  3466. break;
  3467. default:
  3468. results.push(data[position]);
  3469. break;
  3470. }
  3471. position += stride;
  3472. context.count++;
  3473. }
  3474. } else {
  3475. for (let i = 0; i < size; i++) {
  3476. if (context.count >= context.limit) {
  3477. results.push('...');
  3478. return results;
  3479. }
  3480. const nextPosition = position + (i * stride);
  3481. results.push(this._decodeValues(context, dimension + 1, nextPosition));
  3482. }
  3483. }
  3484. if (context.dimensions.length == 0) {
  3485. return results[0];
  3486. }
  3487. return results;
  3488. }
  3489. static _stringify(value, indentation, indent) {
  3490. if (Array.isArray(value)) {
  3491. const result = [];
  3492. result.push(indentation + '[');
  3493. const items = value.map((item) => view.Tensor._stringify(item, indentation + indent, indent));
  3494. if (items.length > 0) {
  3495. result.push(items.join(',\n'));
  3496. }
  3497. result.push(indentation + ']');
  3498. return result.join('\n');
  3499. }
  3500. if (value === null) {
  3501. return indentation + 'null';
  3502. }
  3503. switch (typeof value) {
  3504. case 'boolean':
  3505. return indentation + value.toString();
  3506. case 'string':
  3507. return indentation + '"' + value + '"';
  3508. case 'number':
  3509. if (value == Infinity) {
  3510. return indentation + 'Infinity';
  3511. }
  3512. if (value == -Infinity) {
  3513. return indentation + '-Infinity';
  3514. }
  3515. if (isNaN(value)) {
  3516. return indentation + 'NaN';
  3517. }
  3518. return indentation + value.toString();
  3519. default:
  3520. if (value && value.toString) {
  3521. return indentation + value.toString();
  3522. }
  3523. return indentation + '(undefined)';
  3524. }
  3525. }
  3526. };
  3527. view.Documentation = class {
  3528. static format(source) {
  3529. if (source) {
  3530. const generator = new markdown.Generator();
  3531. const target = {};
  3532. if (source.name !== undefined) {
  3533. target.name = source.name;
  3534. }
  3535. if (source.module !== undefined) {
  3536. target.module = source.module;
  3537. }
  3538. if (source.category !== undefined) {
  3539. target.category = source.category;
  3540. }
  3541. if (source.summary !== undefined) {
  3542. target.summary = generator.html(source.summary);
  3543. }
  3544. if (source.description !== undefined) {
  3545. target.description = generator.html(source.description);
  3546. }
  3547. if (Array.isArray(source.attributes)) {
  3548. target.attributes = source.attributes.map((source) => {
  3549. const target = {};
  3550. target.name = source.name;
  3551. if (source.type !== undefined) {
  3552. target.type = source.type;
  3553. }
  3554. if (source.option !== undefined) {
  3555. target.option = source.option;
  3556. }
  3557. if (source.optional !== undefined) {
  3558. target.optional = source.optional;
  3559. }
  3560. if (source.required !== undefined) {
  3561. target.required = source.required;
  3562. }
  3563. if (source.minimum !== undefined) {
  3564. target.minimum = source.minimum;
  3565. }
  3566. if (source.src !== undefined) {
  3567. target.src = source.src;
  3568. }
  3569. if (source.src_type !== undefined) {
  3570. target.src_type = source.src_type;
  3571. }
  3572. if (source.description !== undefined) {
  3573. target.description = generator.html(source.description);
  3574. }
  3575. if (source.default !== undefined) {
  3576. target.default = source.default;
  3577. }
  3578. if (source.visible !== undefined) {
  3579. target.visible = source.visible;
  3580. }
  3581. return target;
  3582. });
  3583. }
  3584. if (Array.isArray(source.inputs)) {
  3585. target.inputs = source.inputs.map((source) => {
  3586. const target = {};
  3587. target.name = source.name;
  3588. if (source.type !== undefined) {
  3589. target.type = source.type;
  3590. }
  3591. if (source.description !== undefined) {
  3592. target.description = generator.html(source.description);
  3593. }
  3594. if (source.default !== undefined) {
  3595. target.default = source.default;
  3596. }
  3597. if (source.src !== undefined) {
  3598. target.src = source.src;
  3599. }
  3600. if (source.list !== undefined) {
  3601. target.list = source.list;
  3602. }
  3603. if (source.isRef !== undefined) {
  3604. target.isRef = source.isRef;
  3605. }
  3606. if (source.typeAttr !== undefined) {
  3607. target.typeAttr = source.typeAttr;
  3608. }
  3609. if (source.numberAttr !== undefined) {
  3610. target.numberAttr = source.numberAttr;
  3611. }
  3612. if (source.typeListAttr !== undefined) {
  3613. target.typeListAttr = source.typeListAttr;
  3614. }
  3615. if (source.option !== undefined) {
  3616. target.option = source.option;
  3617. }
  3618. if (source.optional !== undefined) {
  3619. target.optional = source.optional;
  3620. }
  3621. if (source.visible !== undefined) {
  3622. target.visible = source.visible;
  3623. }
  3624. return target;
  3625. });
  3626. }
  3627. if (Array.isArray(source.outputs)) {
  3628. target.outputs = source.outputs.map((source) => {
  3629. const target = {};
  3630. target.name = source.name;
  3631. if (source.type) {
  3632. target.type = source.type;
  3633. }
  3634. if (source.description !== undefined) {
  3635. target.description = generator.html(source.description);
  3636. }
  3637. if (source.list !== undefined) {
  3638. target.list = source.list;
  3639. }
  3640. if (source.typeAttr !== undefined) {
  3641. target.typeAttr = source.typeAttr;
  3642. }
  3643. if (source.typeListAttr !== undefined) {
  3644. target.typeListAttr = source.typeAttr;
  3645. }
  3646. if (source.numberAttr !== undefined) {
  3647. target.numberAttr = source.numberAttr;
  3648. }
  3649. if (source.isRef !== undefined) {
  3650. target.isRef = source.isRef;
  3651. }
  3652. if (source.option !== undefined) {
  3653. target.option = source.option;
  3654. }
  3655. return target;
  3656. });
  3657. }
  3658. if (Array.isArray(source.references)) {
  3659. target.references = source.references.map((source) => {
  3660. if (source) {
  3661. target.description = generator.html(source.description);
  3662. }
  3663. return target;
  3664. });
  3665. }
  3666. if (source.version !== undefined) {
  3667. target.version = source.version;
  3668. }
  3669. if (source.operator !== undefined) {
  3670. target.operator = source.operator;
  3671. }
  3672. if (source.identifier !== undefined) {
  3673. target.identifier = source.identifier;
  3674. }
  3675. if (source.package !== undefined) {
  3676. target.package = source.package;
  3677. }
  3678. if (source.support_level !== undefined) {
  3679. target.support_level = source.support_level;
  3680. }
  3681. if (source.min_input !== undefined) {
  3682. target.min_input = source.min_input;
  3683. }
  3684. if (source.max_input !== undefined) {
  3685. target.max_input = source.max_input;
  3686. }
  3687. if (source.min_output !== undefined) {
  3688. target.min_output = source.min_output;
  3689. }
  3690. if (source.max_input !== undefined) {
  3691. target.max_output = source.max_output;
  3692. }
  3693. if (source.inputs_range !== undefined) {
  3694. target.inputs_range = source.inputs_range;
  3695. }
  3696. if (source.outputs_range !== undefined) {
  3697. target.outputs_range = source.outputs_range;
  3698. }
  3699. if (source.examples !== undefined) {
  3700. target.examples = source.examples;
  3701. }
  3702. if (source.constants !== undefined) {
  3703. target.constants = source.constants;
  3704. }
  3705. if (source.type_constraints !== undefined) {
  3706. target.type_constraints = source.type_constraints;
  3707. }
  3708. return target;
  3709. }
  3710. return '';
  3711. }
  3712. };
  3713. view.Formatter = class {
  3714. constructor(value, type, quote) {
  3715. this._value = value;
  3716. this._type = type;
  3717. this._quote = quote;
  3718. this._values = new Set();
  3719. }
  3720. toString() {
  3721. return this._format(this._value, this._type, this._quote);
  3722. }
  3723. _format(value, type, quote) {
  3724. if (value && value.__class__ && value.__class__.__module__ === 'builtins' && value.__class__.__name__ === 'type') {
  3725. return value.__module__ + '.' + value.__name__;
  3726. }
  3727. if (value && value.__class__ && value.__class__.__module__ === 'builtins' && value.__class__.__name__ === 'function') {
  3728. return value.__module__ + '.' + value.__name__;
  3729. }
  3730. if (typeof value === 'function') {
  3731. return value();
  3732. }
  3733. if (value && (value instanceof base.Int64 || value instanceof base.Uint64)) {
  3734. return value.toString();
  3735. }
  3736. if (Number.isNaN(value)) {
  3737. return 'NaN';
  3738. }
  3739. switch (type) {
  3740. case 'shape':
  3741. return value ? value.toString() : '(null)';
  3742. case 'shape[]':
  3743. if (value && !Array.isArray(value)) {
  3744. throw new Error("Invalid shape '" + JSON.stringify(value) + "'.");
  3745. }
  3746. return value ? value.map((item) => item.toString()).join(', ') : '(null)';
  3747. case 'graph':
  3748. return value ? value.name : '(null)';
  3749. case 'graph[]':
  3750. return value ? value.map((graph) => graph.name).join(', ') : '(null)';
  3751. case 'tensor':
  3752. if (value && value.type && value.type.shape && value.type.shape.dimensions && value.type.shape.dimensions.length == 0) {
  3753. return value.toString();
  3754. }
  3755. return '[...]';
  3756. case 'object':
  3757. case 'function':
  3758. return value.type.name;
  3759. case 'object[]':
  3760. case 'function[]':
  3761. return value ? value.map((item) => item.type.name).join(', ') : '(null)';
  3762. case 'type':
  3763. return value ? value.toString() : '(null)';
  3764. case 'type[]':
  3765. return value ? value.map((item) => item.toString()).join(', ') : '(null)';
  3766. default:
  3767. break;
  3768. }
  3769. if (typeof value === 'string' && (!type || type != 'string')) {
  3770. return quote ? '"' + value + '"' : value;
  3771. }
  3772. if (Array.isArray(value)) {
  3773. if (value.length == 0) {
  3774. return quote ? '[]' : '';
  3775. }
  3776. let ellipsis = false;
  3777. if (value.length > 1000) {
  3778. value = value.slice(0, 1000);
  3779. ellipsis = true;
  3780. }
  3781. const itemType = (type && type.endsWith('[]')) ? type.substring(0, type.length - 2) : null;
  3782. const array = value.map((item) => {
  3783. if (item && (item instanceof base.Int64 || item instanceof base.Uint64)) {
  3784. return item.toString();
  3785. }
  3786. if (Number.isNaN(item)) {
  3787. return 'NaN';
  3788. }
  3789. const quote = !itemType || itemType === 'string';
  3790. return this._format(item, itemType, quote);
  3791. });
  3792. if (ellipsis) {
  3793. array.push('\u2026');
  3794. }
  3795. return quote ? [ '[', array.join(', '), ']' ].join(' ') : array.join(', ');
  3796. }
  3797. if (value === null) {
  3798. return quote ? 'null' : '';
  3799. }
  3800. if (value === undefined) {
  3801. return 'undefined';
  3802. }
  3803. if (value !== Object(value)) {
  3804. return value.toString();
  3805. }
  3806. if (this._values.has(value)) {
  3807. return '\u2026';
  3808. }
  3809. this._values.add(value);
  3810. let list = null;
  3811. const entries = Object.entries(value).filter((entry) => !entry[0].startsWith('__') && !entry[0].endsWith('__'));
  3812. if (entries.length == 1) {
  3813. list = [ this._format(entries[0][1], null, true) ];
  3814. } else {
  3815. list = new Array(entries.length);
  3816. for (let i = 0; i < entries.length; i++) {
  3817. const entry = entries[i];
  3818. list[i] = entry[0] + ': ' + this._format(entry[1], null, true);
  3819. }
  3820. }
  3821. let objectType = value.__type__;
  3822. if (!objectType && value.constructor.name && value.constructor.name !== 'Object') {
  3823. objectType = value.constructor.name;
  3824. }
  3825. if (objectType) {
  3826. return objectType + (list.length == 0 ? '()' : [ '(', list.join(', '), ')' ].join(''));
  3827. }
  3828. switch (list.length) {
  3829. case 0:
  3830. return quote ? '()' : '';
  3831. case 1:
  3832. return list[0];
  3833. default:
  3834. return quote ? [ '(', list.join(', '), ')' ].join(' ') : list.join(', ');
  3835. }
  3836. }
  3837. };
  3838. markdown.Generator = class {
  3839. constructor() {
  3840. this._newlineRegExp = /^\n+/;
  3841. this._codeRegExp = /^( {4}[^\n]+\n*)+/;
  3842. this._fencesRegExp = /^ {0,3}(`{3,}(?=[^`\n]*\n)|~{3,})([^\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?:\n+|$)|$)/;
  3843. this._hrRegExp = /^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/;
  3844. this._headingRegExp = /^ {0,3}(#{1,6}) +([^\n]*?)(?: +#+)? *(?:\n+|$)/;
  3845. this._blockquoteRegExp = /^( {0,3}> ?(([^\n]+(?:\n(?! {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)| {0,3}#{1,6} | {0,3}>| {0,3}(?:`{3,}(?=[^`\n]*\n)|~{3,})[^\n]*\n| {0,3}(?:[*+-]|1[.)]) |<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?: +|\n|\/?>)|<(?:script|pre|style|!--))[^\n]+)*)|[^\n]*)(?:\n|$))+/;
  3846. this._listRegExp = /^( {0,3})((?:[*+-]|\d{1,9}[.)])) [\s\S]+?(?:\n+(?=\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$))|\n+(?= {0,3}\[((?!\s*\])(?:\\[[\]]|[^[\]])+)\]: *\n? *<?([^\s>]+)>?(?:(?: +\n? *| *\n *)((?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))))? *(?:\n+|$))|\n{2,}(?! )(?!\1(?:[*+-]|\d{1,9}[.)]) )\n*|\s*$)/;
  3847. this._htmlRegExp = /^ {0,3}(?:<(script|pre|style)[\s>][\s\S]*?(?:<\/\1>[^\n]*\n+|$)|<!--(?!-?>)[\s\S]*?(?:-->|$)[^\n]*(\n+|$)|<\?[\s\S]*?(?:\?>\n*|$)|<![A-Z][\s\S]*?(?:>\n*|$)|<!\[CDATA\[[\s\S]*?(?:\]\]>\n*|$)|<\/?(address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?: +|\n|\/?>)[\s\S]*?(?:\n{2,}|$)|<(?!script|pre|style)([a-z][\w-]*)(?: +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?)*? *\/?>(?=[ \t]*(?:\n|$))[\s\S]*?(?:\n{2,}|$)|<\/(?!script|pre|style)[a-z][\w-]*\s*>(?=[ \t]*(?:\n|$))[\s\S]*?(?:\n{2,}|$))/i;
  3848. this._defRegExp = /^ {0,3}\[((?!\s*\])(?:\\[[\]]|[^[\]])+)\]: *\n? *<?([^\s>]+)>?(?:(?: +\n? *| *\n *)((?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))))? *(?:\n+|$)/;
  3849. this._nptableRegExp = /^ *([^|\n ].*\|.*)\n {0,3}([-:]+ *\|[-| :]*)(?:\n((?:(?!\n| {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)| {0,3}#{1,6} | {0,3}>| {4}[^\n]| {0,3}(?:`{3,}(?=[^`\n]*\n)|~{3,})[^\n]*\n| {0,3}(?:[*+-]|1[.)]) |<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?: +|\n|\/?>)|<(?:script|pre|style|!--)).*(?:\n|$))*)\n*|$)/;
  3850. this._tableRegExp = /^ *\|(.+)\n {0,3}\|?( *[-:]+[-| :]*)(?:\n *((?:(?!\n| {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)| {0,3}#{1,6} | {0,3}>| {4}[^\n]| {0,3}(?:`{3,}(?=[^`\n]*\n)|~{3,})[^\n]*\n| {0,3}(?:[*+-]|1[.)]) |<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?: +|\n|\/?>)|<(?:script|pre|style|!--)).*(?:\n|$))*)\n*|$)/;
  3851. this._lheadingRegExp = /^([^\n]+)\n {0,3}(=+|-+) *(?:\n+|$)/;
  3852. this._textRegExp = /^[^\n]+/;
  3853. this._bulletRegExp = /(?:[*+-]|\d{1,9}[.)])/;
  3854. this._itemRegExp = /^( *)((?:[*+-]|\d{1,9}[.)])) ?[^\n]*(?:\n(?!\1(?:[*+-]|\d{1,9}[.)]) ?)[^\n]*)*/gm;
  3855. this._paragraphRegExp = /^([^\n]+(?:\n(?! {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)| {0,3}#{1,6} | {0,3}>| {0,3}(?:`{3,}(?=[^`\n]*\n)|~{3,})[^\n]*\n| {0,3}(?:[*+-]|1[.)]) |<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?: +|\n|\/?>)|<(?:script|pre|style|!--))[^\n]+)*)/;
  3856. this._backpedalRegExp = /(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/;
  3857. this._escapeRegExp = /^\\([!"#$%&'()*+,\-./:;<=>?@[\]\\^_`{|}~~|])/;
  3858. this._escapesRegExp = /\\([!"#$%&'()*+,\-./:;<=>?@[\]\\^_`{|}~])/g;
  3859. /* eslint-disable no-control-regex */
  3860. this._autolinkRegExp = /^<([a-zA-Z][a-zA-Z0-9+.-]{1,31}:[^\s\x00-\x1f<>]*|[a-zA-Z0-9.!#$%&'*+/=?_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_]))>/;
  3861. this._linkRegExp = /^!?\[((?:\[(?:\\.|[^[\]\\])*\]|\\.|`[^`]*`|[^[\]\\`])*?)\]\(\s*(<(?:\\[<>]?|[^\s<>\\])*>|[^\s\x00-\x1f]*)(?:\s+("(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)))?\s*\)/;
  3862. /* eslint-enable no-control-regex */
  3863. this._urlRegExp = /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9-]+\.?)+[^\s<]*|^[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/i;
  3864. this._tagRegExp = /^<!--(?!-?>)[\s\S]*?-->|^<\/[a-zA-Z][\w:-]*\s*>|^<[a-zA-Z][\w-]*(?:\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?)*?\s*\/?>|^<\?[\s\S]*?\?>|^<![a-zA-Z]+\s[\s\S]*?>|^<!\[CDATA\[[\s\S]*?\]\]>/;
  3865. this._reflinkRegExp = /^!?\[((?:\[(?:\\.|[^[\]\\])*\]|\\.|`[^`]*`|[^[\]\\`])*?)\]\[(?!\s*\])((?:\\[[\]]?|[^[\]\\])+)\]/;
  3866. this._nolinkRegExp = /^!?\[(?!\s*\])((?:\[[^[\]]*\]|\\[[\]]|[^[\]])*)\](?:\[\])?/;
  3867. this._reflinkSearchRegExp = /!?\[((?:\[(?:\\.|[^[\]\\])*\]|\\.|`[^`]*`|[^[\]\\`])*?)\]\[(?!\s*\])((?:\\[[\]]?|[^[\]\\])+)\]|!?\[(?!\s*\])((?:\[[^[\]]*\]|\\[[\]]|[^[\]])*)\](?:\[\])?(?!\()/g;
  3868. this._strongStartRegExp = /^(?:(\*\*(?=[*!"#$%&'()+\-.,/:;<=>?@[\]`{|}~]))|\*\*)(?![\s])|__/;
  3869. this._strongMiddleRegExp = /^\*\*(?:(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^*]|\\\*)|__[^_]*?__|\*\*\[^\*\]*?\*\*)|\*(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^*]|\\\*)|__[^_]*?__|\*\*\[^\*\]*?\*\*)*?\*)+?\*\*$|^__(?![\s])((?:(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^_]|\\_)|__[^_]*?__|\*\*\[^\*\]*?\*\*)|_(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^_]|\\_)|__[^_]*?__|\*\*\[^\*\]*?\*\*)*?_)+?)__$/;
  3870. this._strongEndAstRegExp = /[^!"#$%&'()+\-.,/:;<=>?@[\]`{|}~\s]\*\*(?!\*)|[!"#$%&'()+\-.,/:;<=>?@[\]`{|}~]\*\*(?!\*)(?:(?=[!"#$%&'()+\-.,/:;<=>?@[\]`{|}~_\s]|$))/g;
  3871. this._strongEndUndRegExp = /[^\s]__(?!_)(?:(?=[!"#$%&'()+\-.,/:;<=>?@[\]`{|}~*\s])|$)/g;
  3872. this._emStartRegExp = /^(?:(\*(?=[!"#$%&'()+\-.,/:;<=>?@[\]`{|}~]))|\*)(?![*\s])|_/;
  3873. this._emMiddleRegExp = /^\*(?:(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^*]|\\\*)|__[^_]*?__|\*\*\[^\*\]*?\*\*)|\*(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^*]|\\\*)|__[^_]*?__|\*\*\[^\*\]*?\*\*)*?\*)+?\*$|^_(?![_\s])(?:(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^_]|\\_)|__[^_]*?__|\*\*\[^\*\]*?\*\*)|_(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^_]|\\_)|__[^_]*?__|\*\*\[^\*\]*?\*\*)*?_)+?_$/;
  3874. this._emEndAstRegExp = /[^!"#$%&'()+\-.,/:;<=>?@[\]`{|}~\s]\*(?!\*)|[!"#$%&'()+\-.,/:;<=>?@[\]`{|}~]\*(?!\*)(?:(?=[!"#$%&'()+\-.,/:;<=>?@[\]`{|}~_\s]|$))/g;
  3875. this._emEndUndRegExp = /[^\s]_(?!_)(?:(?=[!"#$%&'()+\-.,/:;<=>?@[\]`{|}~*\s])|$)/g;
  3876. this._codespanRegExp = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;
  3877. this._brRegExp = /^( {2,}|\\)\n(?!\s*$)/;
  3878. this._delRegExp = /^~+(?=\S)([\s\S]*?\S)~+/;
  3879. this._textspanRegExp = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<![`*~]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+/=?_`{|}~-](?=[a-zA-Z0-9.!#$%&'*+/=?_`{|}~-]+@))|(?=[a-zA-Z0-9.!#$%&'*+/=?_`{|}~-]+@))/;
  3880. this._punctuationRegExp = /^([\s*!"#$%&'()+\-.,/:;<=>?@[\]`{|}~])/;
  3881. this._blockSkipRegExp = /\[[^\]]*?\]\([^)]*?\)|`[^`]*?`|<[^>]*?>/g;
  3882. this._escapeTestRegExp = /[&<>"']/;
  3883. this._escapeReplaceRegExp = /[&<>"']/g;
  3884. this._escapeTestNoEncodeRegExp = /[<>"']|&(?!#?\w+;)/;
  3885. this._escapeReplaceNoEncodeRegExp = /[<>"']|&(?!#?\w+;)/g;
  3886. this._escapeReplacementsMap = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
  3887. }
  3888. html(source) {
  3889. const tokens = [];
  3890. const links = new Map();
  3891. source = source.replace(/\r\n|\r/g, '\n').replace(/\t/g, ' ');
  3892. this._tokenize(source, tokens, links, true);
  3893. this._tokenizeBlock(tokens, links);
  3894. const result = this._render(tokens, true);
  3895. return result;
  3896. }
  3897. _tokenize(source, tokens, links, top) {
  3898. source = source.replace(/^ +$/gm, '');
  3899. while (source) {
  3900. let match = this._newlineRegExp.exec(source);
  3901. if (match) {
  3902. source = source.substring(match[0].length);
  3903. if (match[0].length > 1) {
  3904. tokens.push({ type: 'space' });
  3905. }
  3906. continue;
  3907. }
  3908. match = this._codeRegExp.exec(source);
  3909. if (match) {
  3910. source = source.substring(match[0].length);
  3911. const lastToken = tokens[tokens.length - 1];
  3912. if (lastToken && lastToken.type === 'paragraph') {
  3913. lastToken.text += '\n' + match[0].trimRight();
  3914. } else {
  3915. const text = match[0].replace(/^ {4}/gm, '').replace(/\n*$/, '');
  3916. tokens.push({ type: 'code', text: text });
  3917. }
  3918. continue;
  3919. }
  3920. match = this._fencesRegExp.exec(source);
  3921. if (match) {
  3922. source = source.substring(match[0].length);
  3923. const language = match[2] ? match[2].trim() : match[2];
  3924. let content = match[3] || '';
  3925. const matchIndent = match[0].match(/^(\s+)(?:```)/);
  3926. if (matchIndent !== null) {
  3927. const indent = matchIndent[1];
  3928. content = content.split('\n').map((node) => {
  3929. const match = node.match(/^\s+/);
  3930. return (match !== null && match[0].length >= indent.length) ? node.slice(indent.length) : node;
  3931. }).join('\n');
  3932. }
  3933. tokens.push({ type: 'code', language: language, text: content });
  3934. continue;
  3935. }
  3936. match = this._headingRegExp.exec(source);
  3937. if (match) {
  3938. source = source.substring(match[0].length);
  3939. tokens.push({ type: 'heading', depth: match[1].length, text: match[2] });
  3940. continue;
  3941. }
  3942. match = this._nptableRegExp.exec(source);
  3943. if (match) {
  3944. const header = this._splitCells(match[1].replace(/^ *| *\| *$/g, ''));
  3945. const align = match[2].replace(/^ *|\| *$/g, '').split(/ *\| */);
  3946. if (header.length === align.length) {
  3947. const cells = match[3] ? match[3].replace(/\n$/, '').split('\n') : [];
  3948. const token = { type: 'table', header: header, align: align, cells: cells, raw: match[0] };
  3949. for (let i = 0; i < token.align.length; i++) {
  3950. if (/^ *-+: *$/.test(token.align[i])) {
  3951. token.align[i] = 'right';
  3952. } else if (/^ *:-+: *$/.test(token.align[i])) {
  3953. token.align[i] = 'center';
  3954. } else if (/^ *:-+ *$/.test(token.align[i])) {
  3955. token.align[i] = 'left';
  3956. } else {
  3957. token.align[i] = null;
  3958. }
  3959. }
  3960. token.cells = token.cells.map((cell) => this._splitCells(cell, token.header.length));
  3961. source = source.substring(token.raw.length);
  3962. tokens.push(token);
  3963. continue;
  3964. }
  3965. }
  3966. match = this._hrRegExp.exec(source);
  3967. if (match) {
  3968. source = source.substring(match[0].length);
  3969. tokens.push({ type: 'hr' });
  3970. continue;
  3971. }
  3972. match = this._blockquoteRegExp.exec(source);
  3973. if (match) {
  3974. source = source.substring(match[0].length);
  3975. const text = match[0].replace(/^ *> ?/gm, '');
  3976. tokens.push({ type: 'blockquote', text: text, tokens: this._tokenize(text, [], links, top) });
  3977. continue;
  3978. }
  3979. match = this._listRegExp.exec(source);
  3980. if (match) {
  3981. let raw = match[0];
  3982. const bull = match[2];
  3983. const ordered = bull.length > 1;
  3984. const parent = bull[bull.length - 1] === ')';
  3985. const list = { type: 'list', raw: raw, ordered: ordered, start: ordered ? +bull.slice(0, -1) : '', loose: false, items: [] };
  3986. const itemMatch = match[0].match(this._itemRegExp);
  3987. let next = false;
  3988. const length = itemMatch.length;
  3989. for (let i = 0; i < length; i++) {
  3990. let item = itemMatch[i];
  3991. raw = item;
  3992. let space = item.length;
  3993. item = item.replace(/^ *([*+-]|\d+[.)]) ?/, '');
  3994. if (~item.indexOf('\n ')) {
  3995. space -= item.length;
  3996. item = item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '');
  3997. }
  3998. if (i !== length - 1) {
  3999. const bullet = this._bulletRegExp.exec(itemMatch[i + 1])[0];
  4000. if (ordered ? bullet.length === 1 || (!parent && bullet[bullet.length - 1] === ')') : (bullet.length > 1)) {
  4001. const addBack = itemMatch.slice(i + 1).join('\n');
  4002. list.raw = list.raw.substring(0, list.raw.length - addBack.length);
  4003. i = length - 1;
  4004. }
  4005. }
  4006. let loose = next || /\n\n(?!\s*$)/.test(item);
  4007. if (i !== length - 1) {
  4008. next = item.charAt(item.length - 1) === '\n';
  4009. if (!loose) {
  4010. loose = next;
  4011. }
  4012. }
  4013. if (loose) {
  4014. list.loose = true;
  4015. }
  4016. const task = /^\[[ xX]\] /.test(item);
  4017. let checked = undefined;
  4018. if (task) {
  4019. checked = item[1] !== ' ';
  4020. item = item.replace(/^\[[ xX]\] +/, '');
  4021. }
  4022. list.items.push({ type: 'list_item', raw, task: task, checked: checked, loose: loose, text: item });
  4023. }
  4024. source = source.substring(list.raw.length);
  4025. for (const item of list.items) {
  4026. item.tokens = this._tokenize(item.text, [], links, false);
  4027. }
  4028. tokens.push(list);
  4029. continue;
  4030. }
  4031. match = this._htmlRegExp.exec(source);
  4032. if (match) {
  4033. source = source.substring(match[0].length);
  4034. tokens.push({ type: 'html', pre: (match[1] === 'pre' || match[1] === 'script' || match[1] === 'style'), text: match[0] });
  4035. continue;
  4036. }
  4037. if (top) {
  4038. match = this._defRegExp.exec(source);
  4039. if (match) {
  4040. source = source.substring(match[0].length);
  4041. match[3] = match[3] ? match[3].substring(1, match[3].length - 1) : match[3];
  4042. const tag = match[1].toLowerCase().replace(/\s+/g, ' ');
  4043. if (!links.has(tag)) {
  4044. links.set(tag, { href: match[2], title: match[3] });
  4045. }
  4046. continue;
  4047. }
  4048. }
  4049. match = this._tableRegExp.exec(source);
  4050. if (match) {
  4051. const header = this._splitCells(match[1].replace(/^ *| *\| *$/g, ''));
  4052. const align = match[2].replace(/^ *|\| *$/g, '').split(/ *\| */);
  4053. if (header.length === align.length) {
  4054. const cells = match[3] ? match[3].replace(/\n$/, '').split('\n') : [];
  4055. const token = { type: 'table', header: header, align: align, cells: cells, raw: match[0] };
  4056. for (let i = 0; i < token.align.length; i++) {
  4057. if (/^ *-+: *$/.test(token.align[i])) {
  4058. token.align[i] = 'right';
  4059. } else if (/^ *:-+: *$/.test(token.align[i])) {
  4060. token.align[i] = 'center';
  4061. } else if (/^ *:-+ *$/.test(token.align[i])) {
  4062. token.align[i] = 'left';
  4063. } else {
  4064. token.align[i] = null;
  4065. }
  4066. }
  4067. token.cells = token.cells.map((cell) => this._splitCells(cell.replace(/^ *\| *| *\| *$/g, ''), token.header.length));
  4068. source = source.substring(token.raw.length);
  4069. tokens.push(token);
  4070. continue;
  4071. }
  4072. }
  4073. match = this._lheadingRegExp.exec(source);
  4074. if (match) {
  4075. source = source.substring(match[0].length);
  4076. tokens.push({ type: 'heading', depth: match[2].charAt(0) === '=' ? 1 : 2, text: match[1] });
  4077. continue;
  4078. }
  4079. if (top) {
  4080. match = this._paragraphRegExp.exec(source);
  4081. if (match) {
  4082. source = source.substring(match[0].length);
  4083. tokens.push({ type: 'paragraph', text: match[1].charAt(match[1].length - 1) === '\n' ? match[1].slice(0, -1) : match[1] });
  4084. continue;
  4085. }
  4086. }
  4087. match = this._textRegExp.exec(source);
  4088. if (match) {
  4089. source = source.substring(match[0].length);
  4090. const lastToken = tokens[tokens.length - 1];
  4091. if (lastToken && lastToken.type === 'text') {
  4092. lastToken.text += '\n' + match[0];
  4093. } else {
  4094. tokens.push({ type: 'text', text: match[0] });
  4095. }
  4096. continue;
  4097. }
  4098. throw new Error("Unexpected '" + source.charCodeAt(0) + "'.");
  4099. }
  4100. return tokens;
  4101. }
  4102. _tokenizeInline(source, links, inLink, inRawBlock, prevChar) {
  4103. const tokens = [];
  4104. let maskedSource = source;
  4105. if (links.size > 0) {
  4106. while (maskedSource) {
  4107. const match = this._reflinkSearchRegExp.exec(maskedSource);
  4108. if (match) {
  4109. if (links.has(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {
  4110. maskedSource = maskedSource.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSource.slice(this._reflinkSearchRegExp.lastIndex);
  4111. }
  4112. continue;
  4113. }
  4114. break;
  4115. }
  4116. }
  4117. while (maskedSource) {
  4118. const match = this._blockSkipRegExp.exec(maskedSource);
  4119. if (match) {
  4120. maskedSource = maskedSource.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSource.slice(this._blockSkipRegExp.lastIndex);
  4121. continue;
  4122. }
  4123. break;
  4124. }
  4125. while (source) {
  4126. let match = this._escapeRegExp.exec(source);
  4127. if (match) {
  4128. source = source.substring(match[0].length);
  4129. tokens.push({ type: 'escape', text: this._escape(match[1]) });
  4130. continue;
  4131. }
  4132. match = this._tagRegExp.exec(source);
  4133. if (match) {
  4134. source = source.substring(match[0].length);
  4135. if (!inLink && /^<a /i.test(match[0])) {
  4136. inLink = true;
  4137. } else if (inLink && /^<\/a>/i.test(match[0])) {
  4138. inLink = false;
  4139. }
  4140. if (!inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(match[0])) {
  4141. inRawBlock = true;
  4142. } else if (inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(match[0])) {
  4143. inRawBlock = false;
  4144. }
  4145. tokens.push({ type: 'html', raw: match[0], text: match[0] });
  4146. continue;
  4147. }
  4148. match = this._linkRegExp.exec(source);
  4149. if (match) {
  4150. let index = -1;
  4151. const ref = match[2];
  4152. if (ref.indexOf(')') !== -1) {
  4153. let level = 0;
  4154. for (let i = 0; i < ref.length; i++) {
  4155. switch (ref[i]) {
  4156. case '\\':
  4157. i++;
  4158. break;
  4159. case '(':
  4160. level++;
  4161. break;
  4162. case ')':
  4163. level--;
  4164. if (level < 0) {
  4165. index = i;
  4166. i = ref.length;
  4167. }
  4168. break;
  4169. default:
  4170. break;
  4171. }
  4172. }
  4173. }
  4174. if (index > -1) {
  4175. const length = (match[0].indexOf('!') === 0 ? 5 : 4) + match[1].length + index;
  4176. match[2] = match[2].substring(0, index);
  4177. match[0] = match[0].substring(0, length).trim();
  4178. match[3] = '';
  4179. }
  4180. const title = (match[3] ? match[3].slice(1, -1) : '').replace(this._escapesRegExp, '$1');
  4181. const href = match[2].trim().replace(/^<([\s\S]*)>$/, '$1').replace(this._escapesRegExp, '$1');
  4182. const token = this._outputLink(match, href, title);
  4183. source = source.substring(match[0].length);
  4184. if (token.type === 'link') {
  4185. token.tokens = this._tokenizeInline(token.text, links, true, inRawBlock, '');
  4186. }
  4187. tokens.push(token);
  4188. continue;
  4189. }
  4190. match = this._reflinkRegExp.exec(source) || this._nolinkRegExp.exec(source);
  4191. if (match) {
  4192. let link = (match[2] || match[1]).replace(/\s+/g, ' ');
  4193. link = links.get(link.toLowerCase());
  4194. if (!link || !link.href) {
  4195. const text = match[0].charAt(0);
  4196. source = source.substring(text.length);
  4197. tokens.push({ type: 'text', text: text });
  4198. } else {
  4199. source = source.substring(match[0].length);
  4200. const token = this._outputLink(match, link);
  4201. if (token.type === 'link') {
  4202. token.tokens = this._tokenizeInline(token.text, links, true, inRawBlock, '');
  4203. }
  4204. tokens.push(token);
  4205. }
  4206. continue;
  4207. }
  4208. match = this._strongStartRegExp.exec(source);
  4209. if (match && (!match[1] || (match[1] && (prevChar === '' || this._punctuationRegExp.exec(prevChar))))) {
  4210. const masked = maskedSource.slice(-1 * source.length);
  4211. const endReg = match[0] === '**' ? this._strongEndAstRegExp : this._strongEndUndRegExp;
  4212. endReg.lastIndex = 0;
  4213. let cap;
  4214. while ((match = endReg.exec(masked)) != null) {
  4215. cap = this._strongMiddleRegExp.exec(masked.slice(0, match.index + 3));
  4216. if (cap) {
  4217. break;
  4218. }
  4219. }
  4220. if (cap) {
  4221. const text = source.substring(2, cap[0].length - 2);
  4222. source = source.substring(cap[0].length);
  4223. tokens.push({ type: 'strong', text: text, tokens: this._tokenizeInline(text, links, inLink, inRawBlock, '') });
  4224. continue;
  4225. }
  4226. }
  4227. match = this._emStartRegExp.exec(source);
  4228. if (match && (!match[1] || (match[1] && (prevChar === '' || this._punctuationRegExp.exec(prevChar))))) {
  4229. const masked = maskedSource.slice(-1 * source.length);
  4230. const endReg = match[0] === '*' ? this._emEndAstRegExp : this._emEndUndRegExp;
  4231. endReg.lastIndex = 0;
  4232. let cap;
  4233. while ((match = endReg.exec(masked)) != null) {
  4234. cap = this._emMiddleRegExp.exec(masked.slice(0, match.index + 2));
  4235. if (cap) {
  4236. break;
  4237. }
  4238. }
  4239. if (cap) {
  4240. const text = source.slice(1, cap[0].length - 1);
  4241. source = source.substring(cap[0].length);
  4242. tokens.push({ type: 'em', text: text, tokens: this._tokenizeInline(text, links, inLink, inRawBlock, '') });
  4243. continue;
  4244. }
  4245. }
  4246. match = this._codespanRegExp.exec(source);
  4247. if (match) {
  4248. source = source.substring(match[0].length);
  4249. let content = match[2].replace(/\n/g, ' ');
  4250. if (/[^ ]/.test(content) && content.startsWith(' ') && content.endsWith(' ')) {
  4251. content = content.substring(1, content.length - 1);
  4252. }
  4253. tokens.push({ type: 'codespan', text: this._encode(content) });
  4254. continue;
  4255. }
  4256. match = this._brRegExp.exec(source);
  4257. if (match) {
  4258. source = source.substring(match[0].length);
  4259. tokens.push({ type: 'br' });
  4260. continue;
  4261. }
  4262. match = this._delRegExp.exec(source);
  4263. if (match) {
  4264. source = source.substring(match[0].length);
  4265. const text = match[1];
  4266. tokens.push({ type: 'del', text: text, tokens: this._tokenizeInline(text, links, inLink, inRawBlock, '') });
  4267. continue;
  4268. }
  4269. match = this._autolinkRegExp.exec(source);
  4270. if (match) {
  4271. source = source.substring(match[0].length);
  4272. const text = this._escape(match[1]);
  4273. const href = match[2] === '@' ? 'mailto:' + text : text;
  4274. tokens.push({ type: 'link', text: text, href: href, tokens: [ { type: 'text', raw: text, text } ] });
  4275. continue;
  4276. }
  4277. if (!inLink) {
  4278. match = this._urlRegExp.exec(source);
  4279. if (match) {
  4280. const email = match[2] === '@';
  4281. if (!email) {
  4282. let prevCapZero;
  4283. do {
  4284. prevCapZero = match[0];
  4285. match[0] = this._backpedalRegExp.exec(match[0])[0];
  4286. } while (prevCapZero !== match[0]);
  4287. }
  4288. const text = this._escape(match[0]);
  4289. const href = email ? ('mailto:' + text) : (match[1] === 'www.' ? 'http://' + text : text);
  4290. source = source.substring(match[0].length);
  4291. tokens.push({ type: 'link', text: text, href: href, tokens: [ { type: 'text', text: text } ] });
  4292. continue;
  4293. }
  4294. }
  4295. match = this._textspanRegExp.exec(source);
  4296. if (match) {
  4297. source = source.substring(match[0].length);
  4298. prevChar = match[0].slice(-1);
  4299. tokens.push({ type: 'text' , text: inRawBlock ? match[0] : this._escape(match[0]) });
  4300. continue;
  4301. }
  4302. throw new Error("Unexpected '" + source.charCodeAt(0) + "'.");
  4303. }
  4304. return tokens;
  4305. }
  4306. _tokenizeBlock(tokens, links) {
  4307. for (const token of tokens) {
  4308. switch (token.type) {
  4309. case 'paragraph':
  4310. case 'text':
  4311. case 'heading': {
  4312. token.tokens = this._tokenizeInline(token.text, links, false, false, '');
  4313. break;
  4314. }
  4315. case 'table': {
  4316. token.tokens = {};
  4317. token.tokens.header = token.header.map((header) => this._tokenizeInline(header, links, false, false, ''));
  4318. token.tokens.cells = token.cells.map((cell) => cell.map((row) => this._tokenizeInline(row, links, false, false, '')));
  4319. break;
  4320. }
  4321. case 'blockquote': {
  4322. this._tokenizeBlock(token.tokens, links);
  4323. break;
  4324. }
  4325. case 'list': {
  4326. for (const item of token.items) {
  4327. this._tokenizeBlock(item.tokens, links);
  4328. }
  4329. break;
  4330. }
  4331. default: {
  4332. break;
  4333. }
  4334. }
  4335. }
  4336. }
  4337. _render(tokens, top) {
  4338. let html = '';
  4339. while (tokens.length > 0) {
  4340. const token = tokens.shift();
  4341. switch (token.type) {
  4342. case 'space': {
  4343. continue;
  4344. }
  4345. case 'hr': {
  4346. html += '<hr>\n';
  4347. continue;
  4348. }
  4349. case 'heading': {
  4350. const level = token.depth;
  4351. html += '<h' + level + '">' + this._renderInline(token.tokens) + '</h' + level + '>\n';
  4352. continue;
  4353. }
  4354. case 'code': {
  4355. const code = token.text;
  4356. const language = (token.language || '').match(/\S*/)[0];
  4357. html += '<pre><code' + (language ? ' class="' + 'language-' + this._encode(language) + '"' : '') + '>' + (token.escaped ? code : this._encode(code)) + '</code></pre>\n';
  4358. continue;
  4359. }
  4360. case 'table': {
  4361. let header = '';
  4362. let cell = '';
  4363. for (let j = 0; j < token.header.length; j++) {
  4364. const content = this._renderInline(token.tokens.header[j]);
  4365. const align = token.align[j];
  4366. cell += '<th' + (align ? ' align="' + align + '"' : '') + '>' + content + '</th>\n';
  4367. }
  4368. header += '<tr>\n' + cell + '</tr>\n';
  4369. let body = '';
  4370. for (let j = 0; j < token.cells.length; j++) {
  4371. const row = token.tokens.cells[j];
  4372. cell = '';
  4373. for (let k = 0; k < row.length; k++) {
  4374. const content = this._renderInline(row[k]);
  4375. const align = token.align[k];
  4376. cell += '<td' + (align ? ' align="' + align + '"' : '') + '>' + content + '</td>\n';
  4377. }
  4378. body += '<tr>\n' + cell + '</tr>\n';
  4379. }
  4380. html += '<table>\n<thead>\n' + header + '</thead>\n' + (body ? '<tbody>' + body + '</tbody>' : body) + '</table>\n';
  4381. continue;
  4382. }
  4383. case 'blockquote': {
  4384. html += '<blockquote>\n' + this._render(token.tokens, true) + '</blockquote>\n';
  4385. continue;
  4386. }
  4387. case 'list': {
  4388. const ordered = token.ordered;
  4389. const start = token.start;
  4390. const loose = token.loose;
  4391. let body = '';
  4392. for (const item of token.items) {
  4393. let itemBody = '';
  4394. if (item.task) {
  4395. const checkbox = '<input ' + (item.checked ? 'checked="" ' : '') + 'disabled="" type="checkbox"' + '> ';
  4396. if (loose) {
  4397. if (item.tokens.length > 0 && item.tokens[0].type === 'text') {
  4398. item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;
  4399. if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {
  4400. item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text;
  4401. }
  4402. } else {
  4403. item.tokens.unshift({ type: 'text', text: checkbox });
  4404. }
  4405. } else {
  4406. itemBody += checkbox;
  4407. }
  4408. }
  4409. itemBody += this._render(item.tokens, loose);
  4410. body += '<li>' + itemBody + '</li>\n';
  4411. }
  4412. const type = (ordered ? 'ol' : 'ul');
  4413. html += '<' + type + (ordered && start !== 1 ? (' start="' + start + '"') : '') + '>\n' + body + '</' + type + '>\n';
  4414. continue;
  4415. }
  4416. case 'html': {
  4417. html += token.text;
  4418. continue;
  4419. }
  4420. case 'paragraph': {
  4421. html += '<p>' + this._renderInline(token.tokens) + '</p>\n';
  4422. continue;
  4423. }
  4424. case 'text': {
  4425. html += top ? '<p>' : '';
  4426. html += token.tokens ? this._renderInline(token.tokens) : token.text;
  4427. while (tokens.length > 0 && tokens[0].type === 'text') {
  4428. const token = tokens.shift();
  4429. html += '\n' + (token.tokens ? this._renderInline(token.tokens) : token.text);
  4430. }
  4431. html += top ? '</p>\n' : '';
  4432. continue;
  4433. }
  4434. default: {
  4435. throw new Error("Unexpected token type '" + token.type + "'.");
  4436. }
  4437. }
  4438. }
  4439. return html;
  4440. }
  4441. _renderInline(tokens) {
  4442. let html = '';
  4443. for (const token of tokens) {
  4444. switch (token.type) {
  4445. case 'escape':
  4446. case 'html':
  4447. case 'text': {
  4448. html += token.text;
  4449. break;
  4450. }
  4451. case 'link': {
  4452. const text = this._renderInline(token.tokens);
  4453. html += '<a href="' + token.href + '"' + (token.title ? ' title="' + token.title + '"' : '') + ' target="_blank">' + text + '</a>';
  4454. break;
  4455. }
  4456. case 'image': {
  4457. html += '<img src="' + token.href + '" alt="' + token.text + '"' + (token.title ? ' title="' + token.title + '"' : '') + '>';
  4458. break;
  4459. }
  4460. case 'strong': {
  4461. const text = this._renderInline(token.tokens);
  4462. html += '<strong>' + text + '</strong>';
  4463. break;
  4464. }
  4465. case 'em': {
  4466. const text = this._renderInline(token.tokens);
  4467. html += '<em>' + text + '</em>';
  4468. break;
  4469. }
  4470. case 'codespan': {
  4471. html += '<code>' + token.text + '</code>';
  4472. break;
  4473. }
  4474. case 'br': {
  4475. html += '<br>';
  4476. break;
  4477. }
  4478. case 'del': {
  4479. const text = this._renderInline(token.tokens);
  4480. html += '<del>' + text + '</del>';
  4481. break;
  4482. }
  4483. default: {
  4484. throw new Error("Unexpected token type '" + token.type + "'.");
  4485. }
  4486. }
  4487. }
  4488. return html;
  4489. }
  4490. _outputLink(match, href, title) {
  4491. title = title ? this._escape(title) : null;
  4492. const text = match[1].replace(/\\([[\]])/g, '$1');
  4493. return match[0].charAt(0) !== '!' ?
  4494. { type: 'link', href: href, title: title, text: text } :
  4495. { type: 'image', href: href, title: title, text: this._escape(text) };
  4496. }
  4497. _splitCells(tableRow, count) {
  4498. const row = tableRow.replace(/\|/g, (match, offset, str) => {
  4499. let escaped = false;
  4500. let position = offset;
  4501. while (--position >= 0 && str[position] === '\\') {
  4502. escaped = !escaped;
  4503. }
  4504. return escaped ? '|' : ' |';
  4505. });
  4506. const cells = row.split(/ \|/);
  4507. if (cells.length > count) {
  4508. cells.splice(count);
  4509. } else {
  4510. while (cells.length < count) {
  4511. cells.push('');
  4512. }
  4513. }
  4514. return cells.map((cell) => cell.trim().replace(/\\\|/g, '|'));
  4515. }
  4516. _encode(content) {
  4517. if (this._escapeTestRegExp.test(content)) {
  4518. return content.replace(this._escapeReplaceRegExp, (ch) => this._escapeReplacementsMap[ch]);
  4519. }
  4520. return content;
  4521. }
  4522. _escape(content) {
  4523. if (this._escapeTestNoEncodeRegExp.test(content)) {
  4524. return content.replace(this._escapeReplaceNoEncodeRegExp, (ch) => this._escapeReplacementsMap[ch]);
  4525. }
  4526. return content;
  4527. }
  4528. };
  4529. view.ModelContext = class {
  4530. constructor(context) {
  4531. this._context = context;
  4532. this._tags = new Map();
  4533. this._content = new Map();
  4534. let stream = context.stream;
  4535. const entries = context.entries;
  4536. if (!stream && entries && entries.size > 0) {
  4537. this._entries = entries;
  4538. this._format = '';
  4539. } else {
  4540. this._entries = new Map();
  4541. const entry = context instanceof view.EntryContext;
  4542. try {
  4543. const archive = zip.Archive.open(stream, 'gzip');
  4544. if (archive) {
  4545. this._entries = archive.entries;
  4546. this._format = 'gzip';
  4547. if (this._entries.size === 1) {
  4548. stream = this._entries.values().next().value;
  4549. }
  4550. }
  4551. } catch (error) {
  4552. if (!entry) {
  4553. throw error;
  4554. }
  4555. }
  4556. try {
  4557. const formats = new Map([ [ 'zip', zip ], [ 'tar', tar ] ]);
  4558. for (const pair of formats) {
  4559. const format = pair[0];
  4560. const module = pair[1];
  4561. const archive = module.Archive.open(stream);
  4562. if (archive) {
  4563. this._entries = archive.entries;
  4564. this._format = format;
  4565. break;
  4566. }
  4567. }
  4568. } catch (error) {
  4569. if (!entry) {
  4570. throw error;
  4571. }
  4572. }
  4573. }
  4574. }
  4575. get identifier() {
  4576. return this._context.identifier;
  4577. }
  4578. get stream() {
  4579. return this._context.stream;
  4580. }
  4581. request(file, encoding, base) {
  4582. return this._context.request(file, encoding, base);
  4583. }
  4584. require(id) {
  4585. return this._context.require(id);
  4586. }
  4587. exception(error, fatal) {
  4588. if (error && this.identifier) {
  4589. error.context = this.identifier;
  4590. }
  4591. this._context.exception(error, fatal);
  4592. }
  4593. entries(format) {
  4594. if (format !== undefined && format !== this._format) {
  4595. return new Map();
  4596. }
  4597. return this._entries;
  4598. }
  4599. open(type) {
  4600. if (!this._content.has(type)) {
  4601. this._content.set(type, undefined);
  4602. const stream = this.stream;
  4603. if (stream) {
  4604. const position = stream.position;
  4605. const match = (buffer, signature) => {
  4606. return signature.length <= buffer.length && buffer.every((value, index) => signature[index] === undefined || signature[index] === value);
  4607. };
  4608. const buffer = stream.peek(Math.min(stream.length, 16));
  4609. const skip =
  4610. match(buffer, [ 0x80, undefined, 0x8a, 0x0a, 0x6c, 0xfc, 0x9c, 0x46, 0xf9, 0x20, 0x6a, 0xa8, 0x50, 0x19 ]) || // PyTorch
  4611. match(buffer, [ 0x50, 0x4B, 0x03, 0x04 ]) || // Zip
  4612. type !== 'hdf5' && match(buffer, [ 0x89, 0x48, 0x44, 0x46, 0x0D, 0x0A, 0x1A, 0x0A ]) || // \x89HDF\r\n\x1A\n
  4613. Array.from(this._tags).some((entry) => entry[0] !== 'flatbuffers' && entry[1].size > 0) ||
  4614. Array.from(this._content.values()).some((obj) => obj !== undefined);
  4615. if (!skip) {
  4616. switch (type) {
  4617. case 'json': {
  4618. try {
  4619. const buffer = stream.peek(Math.min(this.stream.length, 0x1000));
  4620. if (stream.length < 0x7ffff000 &&
  4621. (buffer.length < 8 || String.fromCharCode.apply(null, buffer.slice(0, 8)) !== '\x89HDF\r\n\x1A\n') &&
  4622. (buffer.some((v) => v === 0x22 || v === 0x5b || v === 0x5d || v === 0x7b || v === 0x7d))) {
  4623. const reader = json.TextReader.open(stream);
  4624. if (reader) {
  4625. const obj = reader.read();
  4626. this._content.set(type, obj);
  4627. }
  4628. }
  4629. } catch (error) {
  4630. // continue regardless of error
  4631. }
  4632. break;
  4633. }
  4634. case 'json.gz': {
  4635. try {
  4636. const archive = zip.Archive.open(stream, 'gzip');
  4637. if (archive && archive.entries.size === 1) {
  4638. const stream = archive.entries.values().next().value;
  4639. const reader = json.TextReader.open(stream);
  4640. if (reader) {
  4641. const obj = reader.read();
  4642. this._content.set(type, obj);
  4643. }
  4644. }
  4645. } catch (error) {
  4646. // continue regardless of error
  4647. }
  4648. break;
  4649. }
  4650. case 'pkl': {
  4651. let unpickler = null;
  4652. const types = new Set();
  4653. try {
  4654. const archive = zip.Archive.open(stream, 'zlib');
  4655. const data = archive ? archive.entries.get('') : stream;
  4656. let condition = false;
  4657. if (data.length > 2) {
  4658. const head = data.peek(2);
  4659. condition = head[0] === 0x80 && head[1] < 7;
  4660. if (!condition) {
  4661. data.seek(-1);
  4662. const tail = data.peek(1);
  4663. data.seek(0);
  4664. condition = tail[0] === 0x2e;
  4665. }
  4666. }
  4667. if (condition) {
  4668. const execution = new python.Execution();
  4669. execution.on('resolve', (_, name) => types.add(name));
  4670. const pickle = execution.__import__('pickle');
  4671. unpickler = new pickle.Unpickler(data);
  4672. }
  4673. } catch (error) {
  4674. // continue regardless of error
  4675. }
  4676. if (unpickler) {
  4677. const storages = new Map();
  4678. unpickler.persistent_load = (saved_id) => {
  4679. if (Array.isArray(saved_id) && saved_id.length > 3) {
  4680. switch (saved_id[0]) {
  4681. case 'storage': {
  4682. const storage_type = saved_id[1];
  4683. const key = saved_id[2];
  4684. const size = saved_id[4];
  4685. if (!storages.has(key)) {
  4686. const storage = new storage_type(size);
  4687. storages.set(key, storage);
  4688. }
  4689. return storages.get(key);
  4690. }
  4691. default: {
  4692. throw new python.Error("Unsupported persistent load type '" + saved_id[0] + "'.");
  4693. }
  4694. }
  4695. }
  4696. throw new view.Error("Unsupported 'persistent_load'.");
  4697. };
  4698. try {
  4699. const obj = unpickler.load();
  4700. this._content.set(type, obj);
  4701. } catch (error) {
  4702. this._content.set(type, error);
  4703. }
  4704. if (Array.from(types).every((name) => !name.startsWith('__torch__.'))) {
  4705. for (const name of types) {
  4706. this.exception(new view.Error("Unknown type name '" + name + "'."));
  4707. }
  4708. } else {
  4709. this._content.set(type, new view.Error("PyTorch standalone 'data.pkl' format not supported."));
  4710. }
  4711. }
  4712. break;
  4713. }
  4714. case 'hdf5': {
  4715. const file = hdf5.File.open(stream);
  4716. if (file) {
  4717. try {
  4718. this._content.set(type, file.read());
  4719. } catch (error) {
  4720. this._content.set(type, error);
  4721. }
  4722. }
  4723. break;
  4724. }
  4725. default: {
  4726. throw new view.Error("Unsupported open format type '" + type + "'.");
  4727. }
  4728. }
  4729. }
  4730. if (stream.position !== position) {
  4731. stream.seek(0);
  4732. }
  4733. }
  4734. }
  4735. return this._content.get(type);
  4736. }
  4737. tags(type) {
  4738. if (!this._tags.has(type)) {
  4739. let tags = new Map();
  4740. const stream = this.stream;
  4741. if (stream) {
  4742. const position = stream.position;
  4743. const signatures = [
  4744. [ 0x89, 0x48, 0x44, 0x46, 0x0D, 0x0A, 0x1A, 0x0A ], // HDF5
  4745. [ 0x80, undefined, 0x8a, 0x0a, 0x6c, 0xfc, 0x9c, 0x46, 0xf9, 0x20, 0x6a, 0xa8, 0x50, 0x19 ], // PyTorch
  4746. [ 0x50, 0x4b ], // Zip
  4747. [ 0x1f, 0x8b ] // Gzip
  4748. ];
  4749. const skip =
  4750. signatures.some((signature) => signature.length <= stream.length && stream.peek(signature.length).every((value, index) => signature[index] === undefined || signature[index] === value)) ||
  4751. (Array.from(this._tags).some((pair) => pair[0] !== 'flatbuffers' && pair[1].size > 0) && type !== 'pb+') ||
  4752. Array.from(this._content.values()).some((obj) => obj !== undefined) ||
  4753. (stream.length < 0x7ffff000 && json.TextReader.open(stream));
  4754. if (!skip && stream.length < 0x7ffff000) {
  4755. try {
  4756. switch (type) {
  4757. case 'pbtxt': {
  4758. const reader = protobuf.TextReader.open(stream);
  4759. tags = reader ? reader.signature() : tags;
  4760. break;
  4761. }
  4762. case 'pb': {
  4763. const reader = protobuf.BinaryReader.open(stream);
  4764. tags = reader.signature();
  4765. break;
  4766. }
  4767. case 'pb+': {
  4768. const reader = protobuf.BinaryReader.open(stream);
  4769. tags = reader.decode();
  4770. break;
  4771. }
  4772. case 'flatbuffers': {
  4773. if (stream.length >= 8) {
  4774. const buffer = stream.peek(Math.min(32, stream.length));
  4775. const reader = flatbuffers.BinaryReader.open(buffer);
  4776. const identifier = reader.identifier;
  4777. if (identifier.length > 0) {
  4778. tags.set('file_identifier', identifier);
  4779. }
  4780. }
  4781. break;
  4782. }
  4783. case 'xml': {
  4784. const reader = xml.TextReader.open(stream);
  4785. if (reader) {
  4786. const document = reader.peek();
  4787. const element = document.documentElement;
  4788. const namespaceURI = element.namespaceURI;
  4789. const localName = element.localName;
  4790. const name = namespaceURI ? namespaceURI + ':' + localName : localName;
  4791. tags.set(name, element);
  4792. }
  4793. break;
  4794. }
  4795. default: {
  4796. throw new view.Error("Unsupported tags format type '" + type + "'.");
  4797. }
  4798. }
  4799. } catch (error) {
  4800. tags.clear();
  4801. }
  4802. }
  4803. if (stream.position !== position) {
  4804. stream.seek(position);
  4805. }
  4806. }
  4807. this._tags.set(type, tags);
  4808. }
  4809. return this._tags.get(type);
  4810. }
  4811. metadata(name) {
  4812. return view.Metadata.open(this, name);
  4813. }
  4814. };
  4815. view.EntryContext = class {
  4816. constructor(host, entries, rootFolder, identifier, stream) {
  4817. this._host = host;
  4818. this._entries = new Map();
  4819. if (entries) {
  4820. for (const entry of entries) {
  4821. if (entry[0].startsWith(rootFolder)) {
  4822. const name = entry[0].substring(rootFolder.length);
  4823. this._entries.set(name, entry[1]);
  4824. }
  4825. }
  4826. }
  4827. this._identifier = identifier.substring(rootFolder.length);
  4828. this._stream = stream;
  4829. }
  4830. get identifier() {
  4831. return this._identifier;
  4832. }
  4833. get stream() {
  4834. return this._stream;
  4835. }
  4836. async request(file, encoding, base) {
  4837. if (base === undefined) {
  4838. const stream = this._entries.get(file);
  4839. if (!stream) {
  4840. throw new view.Error('File not found.');
  4841. }
  4842. if (encoding) {
  4843. const decoder = new TextDecoder(encoding);
  4844. const buffer = stream.peek();
  4845. const value = decoder.decode(buffer);
  4846. return value;
  4847. }
  4848. return stream;
  4849. }
  4850. return this._host.request(file, encoding, base);
  4851. }
  4852. require(id) {
  4853. return this._host.require(id);
  4854. }
  4855. exception(error, fatal) {
  4856. this._host.exception(error, fatal);
  4857. }
  4858. };
  4859. view.ArchiveError = class extends Error {
  4860. constructor(message) {
  4861. super(message);
  4862. this.name = 'Error loading archive.';
  4863. }
  4864. };
  4865. view.ModelFactoryService = class {
  4866. constructor(host) {
  4867. this._host = host;
  4868. this._extensions = new Set([ '.zip', '.tar', '.tar.gz', '.tgz', '.gz' ]);
  4869. this._factories = [];
  4870. this.register('./server', [ '.netron']);
  4871. 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', '.ff', '.ptmf', '.jit', '.pte' ], [ '.model' ]);
  4872. this.register('./onnx', [ '.onnx', '.onn', '.pb', '.onnxtxt', '.pbtxt', '.prototxt', '.txt', '.model', '.pt', '.pth', '.pkl', '.ort', '.ort.onnx', 'onnxmodel', 'ngf', 'json' ]);
  4873. this.register('./mxnet', [ '.json', '.params' ], [ '.mar']);
  4874. this.register('./coreml', [ '.mlmodel', '.bin', 'manifest.json', 'metadata.json', 'featuredescriptions.json', '.pb' ], [ '.mlpackage' ]);
  4875. this.register('./caffe', [ '.caffemodel', '.pbtxt', '.prototxt', '.pt', '.txt' ]);
  4876. this.register('./caffe2', [ '.pb', '.pbtxt', '.prototxt' ]);
  4877. this.register('./torch', [ '.t7', '.net' ]);
  4878. this.register('./tflite', [ '.tflite', '.lite', '.tfl', '.bin', '.pb', '.tmfile', '.h5', '.model', '.json', '.txt', '.dat' ]);
  4879. this.register('./circle', [ '.circle' ]);
  4880. 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' ]);
  4881. this.register('./mediapipe', [ '.pbtxt' ]);
  4882. this.register('./uff', [ '.uff', '.pb', '.pbtxt', '.uff.txt', '.trt', '.engine' ]);
  4883. this.register('./tensorrt', [ '.trt', '.trtmodel', '.engine', '.model', '.txt', '.uff', '.pb', '.tmfile', '.onnx', '.pth', '.dnn', '.plan', '.pt', '.dat' ]);
  4884. this.register('./keras', [ '.h5', '.hd5', '.hdf5', '.keras', '.json', '.cfg', '.model', '.pb', '.pth', '.weights', '.pkl', '.lite', '.tflite', '.ckpt', '.pb', 'model.weights.npz' ], [ '.zip' ]);
  4885. this.register('./numpy', [ '.npz', '.npy', '.pkl', '.pickle', '.model', '.model2', '.mge', '.joblib' ]);
  4886. this.register('./lasagne', [ '.pkl', '.pickle', '.joblib', '.model', '.pkl.z', '.joblib.z' ]);
  4887. this.register('./lightgbm', [ '.txt', '.pkl', '.model' ]);
  4888. this.register('./sklearn', [ '.pkl', '.pickle', '.joblib', '.model', '.meta', '.pb', '.pt', '.h5', '.pkl.z', '.joblib.z', '.pickle.dat' ]);
  4889. this.register('./megengine', [ '.tm', '.mge' ]);
  4890. this.register('./pickle', [ '.pkl', '.pickle', '.joblib', '.model', '.meta', '.pb', '.pt', '.h5', '.pkl.z', '.joblib.z', '.pdstates', '.mge' ]);
  4891. this.register('./cntk', [ '.model', '.cntk', '.cmf', '.dnn' ]);
  4892. this.register('./paddle', [ '.pdmodel', '.pdiparams', '.pdparams', '.pdopt', '.paddle', '__model__', '.__model__', '.pbtxt', '.txt', '.tar', '.tar.gz', '.nb' ]);
  4893. this.register('./bigdl', [ '.model', '.bigdl' ]);
  4894. this.register('./darknet', [ '.cfg', '.model', '.txt', '.weights' ]);
  4895. this.register('./weka', [ '.model' ]);
  4896. this.register('./rknn', [ '.rknn', '.nb', '.onnx', '.json' ]);
  4897. this.register('./dlc', [ '.dlc', 'model', '.params' ]);
  4898. this.register('./armnn', [ '.armnn', '.json' ]);
  4899. this.register('./mnn', ['.mnn']);
  4900. this.register('./ncnn', [ '.param', '.bin', '.cfg.ncnn', '.weights.ncnn', '.ncnnmodel' ]);
  4901. this.register('./tnn', [ '.tnnproto', '.tnnmodel' ]);
  4902. this.register('./tengine', ['.tmfile']);
  4903. this.register('./mslite', [ '.ms']);
  4904. this.register('./barracuda', [ '.nn' ]);
  4905. this.register('./dnn', [ '.dnn' ]);
  4906. this.register('./xmodel', [ '.xmodel' ]);
  4907. this.register('./kmodel', [ '.kmodel' ]);
  4908. this.register('./flux', [ '.bson' ]);
  4909. this.register('./dl4j', [ '.json', '.bin' ]);
  4910. this.register('./openvino', [ '.xml', '.bin' ]);
  4911. this.register('./mlnet', [ '.zip', '.mlnet' ]);
  4912. this.register('./acuity', [ '.json' ]);
  4913. this.register('./imgdnn', [ '.dnn', 'params', '.json' ]);
  4914. this.register('./flax', [ '.msgpack' ]);
  4915. this.register('./om', [ '.om', '.onnx', '.pb', '.engine' ]);
  4916. this.register('./nnabla', [ '.nntxt' ], [ '.nnp' ]);
  4917. this.register('./hickle', [ '.h5', '.hkl' ]);
  4918. this.register('./nnef', [ '.nnef', '.dat' ]);
  4919. this.register('./cambricon', [ '.cambricon' ]);
  4920. this.register('./onednn', [ '.json']);
  4921. this.register('./mlir', [ '.mlir']);
  4922. this.register('./sentencepiece', [ '.model' ]);
  4923. this.register('./hailo', [ '.hn', '.har' ]);
  4924. this.register('./nnc', [ '.nnc' ]);
  4925. this.register('./safetensors', [ '.safetensors' ]);
  4926. this.register('./modular', [ '.maxviz' ]);
  4927. }
  4928. register(id, factories, containers) {
  4929. for (const extension of factories) {
  4930. this._factories.push({ extension: extension, id: id });
  4931. this._extensions.add(extension);
  4932. }
  4933. for (const extension of containers || []) {
  4934. this._extensions.add(extension);
  4935. }
  4936. }
  4937. async open(context) {
  4938. try {
  4939. await this._openSignature(context);
  4940. const modelContext = new view.ModelContext(context);
  4941. const model = await this._openContext(modelContext);
  4942. if (!model) {
  4943. const entries = modelContext.entries();
  4944. if (!entries || entries.size === 0) {
  4945. this._unsupported(modelContext);
  4946. }
  4947. const context = await this._openEntries(entries);
  4948. if (!context) {
  4949. this._unsupported(modelContext);
  4950. }
  4951. return this._openContext(context);
  4952. }
  4953. return model;
  4954. } catch (error) {
  4955. if (error && context.identifier) {
  4956. error.context = context.identifier;
  4957. }
  4958. throw error;
  4959. }
  4960. }
  4961. _unsupported(context) {
  4962. const identifier = context.identifier;
  4963. const extension = identifier.split('.').pop().toLowerCase();
  4964. const stream = context.stream;
  4965. const callbacks = [
  4966. (stream) => zip.Archive.open(stream, 'zip'),
  4967. (stream) => tar.Archive.open(stream),
  4968. (stream) => zip.Archive.open(stream, 'gzip')
  4969. ];
  4970. for (const callback of callbacks) {
  4971. let archive = null;
  4972. try {
  4973. archive = callback(stream);
  4974. } catch (error) {
  4975. // continue regardless of error
  4976. }
  4977. if (archive) {
  4978. throw new view.Error("Archive contains no model files.");
  4979. }
  4980. }
  4981. const json = () => {
  4982. const obj = context.open('json');
  4983. if (obj) {
  4984. const formats = [
  4985. { name: 'Netron metadata', tags: [ '[].name', '[].schema' ] },
  4986. { name: 'Netron metadata', tags: [ '[].name', '[].attributes' ] },
  4987. { name: 'Netron metadata', tags: [ '[].name', '[].category' ] },
  4988. { name: 'Netron test data', tags: [ '[].type', '[].target', '[].source', '[].format', '[].link' ] },
  4989. { name: 'Darkflow metadata', tags: [ 'net', 'type', 'model' ] },
  4990. { name: 'keras-yolo2 configuration', tags: [ 'model', 'train', 'valid' ] },
  4991. { name: 'Vulkan SwiftShader ICD manifest', tags: [ 'file_format_version', 'ICD' ] },
  4992. { name: 'DeepLearningExamples configuration', tags: [ 'attention_probs_dropout_prob', 'hidden_act', 'hidden_dropout_prob', 'hidden_size', ] },
  4993. { name: 'GitHub page data', tags: [ 'payload', 'title' ] },
  4994. { name: 'NuGet assets', tags: [ 'version', 'targets', 'packageFolders' ] },
  4995. { name: 'NuGet data', tags: [ 'format', 'restore', 'projects' ] },
  4996. { name: 'NPM package', tags: [ 'name', 'version', 'dependencies' ] },
  4997. { name: 'NetworkX adjacency_data', tags: [ 'directed', 'graph', 'nodes' ] },
  4998. { name: 'Waifu2x data', tags: [ 'name', 'arch_name', 'channels' ] },
  4999. { name: 'Waifu2x data', tags: [ '[].nInputPlane', '[].nOutputPlane', '[].weight', '[].bias' ] },
  5000. { name: 'Brain.js data', tags: [ 'type', 'sizes', 'layers' ] },
  5001. { name: 'Custom Vision metadata', tags: [ 'CustomVision.Metadata.Version' ] },
  5002. { name: 'W&B metadata', tags: [ 'program', 'host', 'executable' ] }
  5003. ];
  5004. const match = (obj, tag) => {
  5005. if (tag.startsWith('[].')) {
  5006. tag = tag.substring(3);
  5007. return (Array.isArray(obj) && obj.some((item) => Object.prototype.hasOwnProperty.call(item, tag)));
  5008. }
  5009. return Object.prototype.hasOwnProperty.call(obj, tag);
  5010. };
  5011. for (const format of formats) {
  5012. if (format.tags.every((tag) => match(obj, tag))) {
  5013. throw new view.Error('Invalid file content. File contains ' + format.name + '.');
  5014. }
  5015. }
  5016. const content = JSON.stringify(obj).substring(0, 100).replace(/\s/, '').substring(0, 48) + '...';
  5017. throw new view.Error("Unsupported JSON content '" + (content.length > 64 ? content.substring(0, 100) + '...' : content) + "' for extension '." + extension + "'.");
  5018. }
  5019. };
  5020. const pbtxt = () => {
  5021. const formats = [
  5022. { name: 'ImageNet LabelMap data', tags: [ 'entry', 'entry.target_class' ] },
  5023. { name: 'StringIntLabelMapProto data', tags: [ 'item', 'item.id', 'item.name' ] },
  5024. { name: 'caffe.LabelMap data', tags: [ 'item', 'item.name', 'item.label' ] },
  5025. { name: 'Triton Inference Server configuration', tags: [ 'name', 'platform', 'input', 'output' ] },
  5026. { name: 'TensorFlow OpList data', tags: [ 'op', 'op.name', 'op.input_arg' ] },
  5027. { name: 'vitis.ai.proto.DpuModelParamList data', tags: [ 'model', 'model.name', 'model.kernel' ] },
  5028. { name: 'object_detection.protos.DetectionModel data', tags: [ 'model', 'model.ssd' ] },
  5029. { name: 'object_detection.protos.DetectionModel data', tags: [ 'model', 'model.faster_rcnn' ] },
  5030. { name: 'tensorflow.CheckpointState data', tags: [ 'model_checkpoint_path', 'all_model_checkpoint_paths' ] },
  5031. { name: 'apollo.perception.camera.traffic_light.detection.DetectionParam data', tags: [ 'min_crop_size', 'crop_method' ] },
  5032. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: [ 'caffe_ssd' ] }, // https://github.com/TexasInstruments/edgeai-mmdetection/blob/master/mmdet/utils/proto/mmdet_meta_arch.proto
  5033. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: [ 'tf_od_api_ssd' ] },
  5034. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: [ 'tidl_ssd' ] },
  5035. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: [ 'tidl_faster_rcnn' ] },
  5036. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: [ 'tidl_yolo' ] },
  5037. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: [ 'tidl_retinanet' ] },
  5038. { name: 'domi.InsertNewOps data', tags: [ 'aipp_op' ] } // https://github.com/Ascend/parser/blob/development/parser/proto/insert_op.proto
  5039. ];
  5040. const tags = context.tags('pbtxt');
  5041. if (tags.size > 0) {
  5042. for (const format of formats) {
  5043. if (format.tags.every((tag) => tags.has(tag))) {
  5044. const error = new view.Error('Invalid file content. File contains ' + format.name + '.');
  5045. error.context = context.identifier;
  5046. throw error;
  5047. }
  5048. }
  5049. const entries = [];
  5050. entries.push(...Array.from(tags).filter((pair) => pair[0].toString().indexOf('.') === -1));
  5051. entries.push(...Array.from(tags).filter((pair) => pair[0].toString().indexOf('.') !== -1));
  5052. const content = entries.map((pair) => pair[1] === true ? pair[0] : pair[0] + ':' + JSON.stringify(pair[1])).join(',');
  5053. throw new view.Error("Unsupported Protocol Buffers text content '" + (content.length > 64 ? content.substring(0, 100) + '...' : content) + "' for extension '." + extension + "'.");
  5054. }
  5055. };
  5056. const pb = () => {
  5057. const tags = context.tags('pb+');
  5058. if (Object.keys(tags).length > 0) {
  5059. const formats = [
  5060. { 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,[]]] },
  5061. { 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]] },
  5062. { name: 'third_party.tensorflow.python.keras.protobuf.SavedMetadata data', tags: [[1,[[1,[[1,0],[2,0]]],[2,0],[3,2],[4,2],[5,2]]]] },
  5063. { 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
  5064. ];
  5065. const match = (tags, schema) => {
  5066. for (const pair of schema) {
  5067. const key = pair[0];
  5068. const inner = pair[1];
  5069. const value = tags[key];
  5070. if (value === undefined) {
  5071. continue;
  5072. }
  5073. if (inner === false) {
  5074. return false;
  5075. }
  5076. if (Array.isArray(inner)) {
  5077. if (typeof value !== 'object' || !match(value, inner)) {
  5078. return false;
  5079. }
  5080. } else if (inner !== value) {
  5081. if (inner === 2 && !Array.isArray(value) && Object(value) === (value) && Object.keys(value).length === 0) {
  5082. return true;
  5083. }
  5084. return false;
  5085. }
  5086. }
  5087. return true;
  5088. };
  5089. const tags = context.tags('pb+');
  5090. for (const format of formats) {
  5091. if (match(tags, format.tags)) {
  5092. const error = new view.Error('Invalid file content. File contains ' + format.name + '.');
  5093. error.context = context.identifier;
  5094. throw error;
  5095. }
  5096. }
  5097. const format = (tags) => {
  5098. const content = Object.entries(tags).map((pair) => {
  5099. const key = pair[0];
  5100. const value = pair[1];
  5101. return key.toString() + ':' + (Object(value) === value ? '{' + format(value) + '}' : value.toString());
  5102. });
  5103. return content.join(',');
  5104. };
  5105. const content = format(tags);
  5106. throw new view.Error("Unsupported Protocol Buffers content '" + (content.length > 64 ? content.substring(0, 100) + '...' : content) + "' for extension '." + extension + "'.");
  5107. }
  5108. };
  5109. const flatbuffers = () => {
  5110. const tags = context.tags('flatbuffers');
  5111. if (tags.has('file_identifier')) {
  5112. const file_identifier = tags.get('file_identifier');
  5113. const formats = [
  5114. { name: 'onnxruntime.experimental.fbs.InferenceSession data', identifier: 'ORTM' },
  5115. { name: 'tflite.Model data', identifier: 'TFL3' }
  5116. ];
  5117. for (const format of formats) {
  5118. if (file_identifier === format.identifier) {
  5119. throw new view.Error('Invalid file content. File contains ' + format.name + '.');
  5120. }
  5121. }
  5122. }
  5123. };
  5124. const xml = () => {
  5125. const tags = context.tags('xml');
  5126. if (tags.size > 0) {
  5127. const formats = [
  5128. { name: 'OpenCV storage data', tags: [ 'opencv_storage' ] },
  5129. { name: 'XHTML markup', tags: [ 'http://www.w3.org/1999/xhtml:html' ] }
  5130. ];
  5131. for (const format of formats) {
  5132. if (format.tags.some((tag) => tags.has(tag))) {
  5133. const error = new view.Error('Invalid file content. File contains ' + format.name + '.');
  5134. error.content = context.identifier;
  5135. throw error;
  5136. }
  5137. }
  5138. throw new view.Error("Unsupported XML content '" + tags.keys().next().value + "'.");
  5139. }
  5140. };
  5141. const hdf5 = () => {
  5142. const obj = context.open('hdf5');
  5143. if (obj instanceof Error) {
  5144. throw obj;
  5145. }
  5146. };
  5147. const unknown = () => {
  5148. if (stream) {
  5149. stream.seek(0);
  5150. const buffer = stream.peek(Math.min(16, stream.length));
  5151. const bytes = Array.from(buffer).map((c) => (c < 16 ? '0' : '') + c.toString(16)).join('');
  5152. const content = stream.length > 268435456 ? '(' + bytes + ') [' + stream.length.toString() + ']': '(' + bytes + ')';
  5153. throw new view.Error("Unsupported file content " + content + " for extension '." + extension + "'.");
  5154. }
  5155. throw new view.Error("Unsupported file directory.");
  5156. };
  5157. json();
  5158. pbtxt();
  5159. pb();
  5160. flatbuffers();
  5161. xml();
  5162. hdf5();
  5163. unknown();
  5164. }
  5165. async _openContext(context) {
  5166. const modules = this._filter(context).filter((module) => module && module.length > 0);
  5167. const errors = [];
  5168. let success = false;
  5169. const next = async () => {
  5170. if (modules.length > 0) {
  5171. try {
  5172. const id = modules.shift();
  5173. const module = await this._host.require(id);
  5174. if (!module.ModelFactory) {
  5175. throw new view.Error("Failed to load module '" + id + "'.");
  5176. }
  5177. const modelFactory = new module.ModelFactory();
  5178. const target = modelFactory.match(context);
  5179. if (target) {
  5180. success = true;
  5181. const model = await modelFactory.open(context, target);
  5182. if (!model.identifier) {
  5183. model.identifier = context.identifier;
  5184. }
  5185. return model;
  5186. }
  5187. } catch (error) {
  5188. if (context.stream && context.stream.position !== 0) {
  5189. context.stream.seek(0);
  5190. }
  5191. errors.push(error);
  5192. }
  5193. return await next();
  5194. }
  5195. if (success) {
  5196. if (errors.length === 1) {
  5197. throw errors[0];
  5198. }
  5199. throw new view.Error(errors.map((err) => err.message).join('\n'));
  5200. }
  5201. return null;
  5202. };
  5203. return await next();
  5204. }
  5205. async _openEntries(entries) {
  5206. try {
  5207. const rootFolder = (files) => {
  5208. const map = files.map((file) => file.split('/').slice(0, -1));
  5209. const at = (index) => (list) => list[index];
  5210. const rotate = (list) => list.length === 0 ? [] : list[0].map((item, index) => list.map(at(index)));
  5211. const equals = (list) => list.every((item) => item === list[0]);
  5212. const folder = rotate(map).filter(equals).map(at(0)).join('/');
  5213. return folder.length === 0 ? folder : folder + '/';
  5214. };
  5215. const list = Array.from(entries).map((entry) => {
  5216. return { name: entry[0], stream: entry[1] };
  5217. });
  5218. const files = list.filter((entry) => {
  5219. if (entry.name.endsWith('/')) {
  5220. return false;
  5221. }
  5222. if (entry.name.split('/').pop().startsWith('.')) {
  5223. return false;
  5224. }
  5225. if (!entry.name.startsWith('./') && entry.name.startsWith('.')) {
  5226. return false;
  5227. }
  5228. return true;
  5229. });
  5230. const folder = rootFolder(files.map((entry) => entry.name));
  5231. const filter = async (queue) => {
  5232. let matches = [];
  5233. const nextEntry = async () => {
  5234. if (queue.length > 0) {
  5235. const entry = queue.shift();
  5236. const context = new view.ModelContext(new view.EntryContext(this._host, entries, folder, entry.name, entry.stream));
  5237. const modules = this._filter(context);
  5238. const nextModule = async () => {
  5239. if (modules.length > 0) {
  5240. const id = modules.shift();
  5241. const module = await this._host.require(id);
  5242. if (!module.ModelFactory) {
  5243. throw new view.ArchiveError("Failed to load module '" + id + "'.", null);
  5244. }
  5245. const modelFactory = new module.ModelFactory();
  5246. if (modelFactory.match(context)) {
  5247. matches.push(context);
  5248. modules.splice(0, modules.length);
  5249. }
  5250. return await nextModule();
  5251. }
  5252. return await nextEntry();
  5253. };
  5254. return await nextModule();
  5255. }
  5256. if (matches.length === 0) {
  5257. return null;
  5258. }
  5259. // MXNet
  5260. if (matches.length === 2 &&
  5261. matches.some((context) => context.identifier.toLowerCase().endsWith('.params')) &&
  5262. matches.some((context) => context.identifier.toLowerCase().endsWith('-symbol.json'))) {
  5263. matches = matches.filter((context) => context.identifier.toLowerCase().endsWith('.params'));
  5264. }
  5265. // TensorFlow.js
  5266. if (matches.length > 0 &&
  5267. matches.some((context) => context.identifier.toLowerCase().endsWith('.bin')) &&
  5268. matches.some((context) => context.identifier.toLowerCase().endsWith('.json'))) {
  5269. matches = matches.filter((context) => context.identifier.toLowerCase().endsWith('.json'));
  5270. }
  5271. // ncnn
  5272. if (matches.length > 0 &&
  5273. matches.some((context) => context.identifier.toLowerCase().endsWith('.bin')) &&
  5274. matches.some((context) => context.identifier.toLowerCase().endsWith('.param'))) {
  5275. matches = matches.filter((context) => context.identifier.toLowerCase().endsWith('.param'));
  5276. }
  5277. // ncnn
  5278. if (matches.length > 0 &&
  5279. matches.some((context) => context.identifier.toLowerCase().endsWith('.bin')) &&
  5280. matches.some((context) => context.identifier.toLowerCase().endsWith('.param.bin'))) {
  5281. matches = matches.filter((context) => context.identifier.toLowerCase().endsWith('.param.bin'));
  5282. }
  5283. // NNEF
  5284. if (matches.length > 0 &&
  5285. matches.some((context) => context.identifier.toLowerCase().endsWith('.nnef')) &&
  5286. matches.some((context) => context.identifier.toLowerCase().endsWith('.dat'))) {
  5287. matches = matches.filter((context) => context.identifier.toLowerCase().endsWith('.nnef'));
  5288. }
  5289. // Paddle
  5290. if (matches.length > 0 &&
  5291. matches.some((context) => context.identifier.toLowerCase().endsWith('.pdmodel')) &&
  5292. (matches.some((context) => context.identifier.toLowerCase().endsWith('.pdparams')) ||
  5293. matches.some((context) => context.identifier.toLowerCase().endsWith('.pdopt')) ||
  5294. matches.some((context) => context.identifier.toLowerCase().endsWith('.pdiparams')))) {
  5295. matches = matches.filter((context) => context.identifier.toLowerCase().endsWith('.pdmodel'));
  5296. }
  5297. // Paddle Lite
  5298. if (matches.length > 0 &&
  5299. matches.some((context) => context.identifier.toLowerCase().split('/').pop() === '__model__.nb') &&
  5300. matches.some((context) => context.identifier.toLowerCase().split('/').pop() === 'param.nb')) {
  5301. matches = matches.filter((context) => context.identifier.toLowerCase().split('/').pop() == '__model__.nb');
  5302. }
  5303. // TensorFlow Bundle
  5304. if (matches.length > 1 &&
  5305. matches.some((context) => context.identifier.toLowerCase().endsWith('.data-00000-of-00001'))) {
  5306. matches = matches.filter((context) => !context.identifier.toLowerCase().endsWith('.data-00000-of-00001'));
  5307. }
  5308. // TensorFlow SavedModel
  5309. if (matches.length === 2 &&
  5310. matches.some((context) => context.identifier.toLowerCase().split('/').pop() === 'keras_metadata.pb')) {
  5311. matches = matches.filter((context) => context.identifier.toLowerCase().split('/').pop() !== 'keras_metadata.pb');
  5312. }
  5313. // Keras
  5314. if (matches.length === 3 &&
  5315. matches.some((context) => context.identifier.toLowerCase().split('/').pop() === 'model.weights.h5' || context.identifier.toLowerCase().split('/').pop() === 'model.weights.npz') &&
  5316. matches.some((context) => context.identifier.toLowerCase().split('/').pop() === 'config.json') &&
  5317. matches.some((context) => context.identifier.toLowerCase().split('/').pop() === 'metadata.json')) {
  5318. matches = matches.filter((context) => context.identifier.toLowerCase().split('/').pop() == 'model.weights.h5' || context.identifier.toLowerCase().split('/').pop() === 'model.weights.npz');
  5319. }
  5320. if (matches.length === 2 &&
  5321. matches.some((context) => context.identifier.toLowerCase().split('/').pop() === 'model.weights.h5' || context.identifier.toLowerCase().split('/').pop() === 'model.weights.npz') &&
  5322. matches.some((context) => context.identifier.toLowerCase().split('/').pop() === 'config.json')) {
  5323. matches = matches.filter((context) => context.identifier.toLowerCase().split('/').pop() == 'model.weights.h5' || context.identifier.toLowerCase().split('/').pop() === 'model.weights.npz');
  5324. }
  5325. if ((matches.length === 2) &&
  5326. matches.some((context) => context.identifier.toLowerCase().split('/').pop() === 'config.json') &&
  5327. matches.some((context) => context.identifier.toLowerCase().split('/').pop() === 'metadata.json')) {
  5328. matches = matches.filter((context) => context.identifier.toLowerCase().split('/').pop() == 'config.json');
  5329. }
  5330. if (matches.length > 1) {
  5331. throw new view.ArchiveError('Archive contains multiple model files.');
  5332. }
  5333. const match = matches.shift();
  5334. return match;
  5335. };
  5336. return await nextEntry();
  5337. };
  5338. const queue = files.slice(0).filter((entry) => entry.name.substring(folder.length).indexOf('/') < 0);
  5339. const context = await filter(queue);
  5340. if (!context) {
  5341. const queue = files.slice(0).filter((entry) => entry.name.substring(folder.length).indexOf('/') >= 0);
  5342. return await filter(queue);
  5343. }
  5344. return context;
  5345. } catch (error) {
  5346. throw new view.ArchiveError(error.message);
  5347. }
  5348. }
  5349. accept(identifier, size) {
  5350. const extension = identifier.indexOf('.') === -1 ? '' : identifier.split('.').pop().toLowerCase();
  5351. identifier = identifier.toLowerCase().split('/').pop();
  5352. let accept = false;
  5353. for (const extension of this._extensions) {
  5354. if ((typeof extension === 'string' && identifier.endsWith(extension)) || (extension instanceof RegExp && extension.exec(identifier))) {
  5355. accept = true;
  5356. break;
  5357. }
  5358. }
  5359. this._host.event('model_file', {
  5360. file_extension: extension,
  5361. file_size: size || 0,
  5362. file_accept: accept ? 1 : 0
  5363. });
  5364. return accept;
  5365. }
  5366. _filter(context) {
  5367. const identifier = context.identifier.toLowerCase().split('/').pop();
  5368. const list = this._factories.filter((entry) =>
  5369. (typeof entry.extension === 'string' && identifier.endsWith(entry.extension)) ||
  5370. (entry.extension instanceof RegExp && entry.extension.exec(identifier)));
  5371. return Array.from(new Set(list.map((entry) => entry.id)));
  5372. }
  5373. async _openSignature(context) {
  5374. const stream = context.stream;
  5375. if (stream) {
  5376. let empty = true;
  5377. let position = 0;
  5378. while (position < stream.length) {
  5379. const buffer = stream.read(Math.min(4096, stream.length - position));
  5380. position += buffer.length;
  5381. if (!buffer.every((value) => value === 0x00)) {
  5382. empty = false;
  5383. break;
  5384. }
  5385. }
  5386. stream.seek(0);
  5387. if (empty) {
  5388. throw new view.Error('File has no content.');
  5389. }
  5390. /* eslint-disable no-control-regex */
  5391. const entries = [
  5392. { name: 'ELF executable', value: /^\x7FELF/ },
  5393. { name: 'PNG image', value: /^\x89PNG/ },
  5394. { name: 'Git LFS header', value: /^version https:\/\/git-lfs.github.com/ },
  5395. { name: 'Git LFS header', value: /^\s*oid sha256:/ },
  5396. { name: 'GGML data', value: /^lmgg|fmgg|tjgg|algg|fugg/ },
  5397. { name: 'HTML markup', value: /^\s*<html>/ },
  5398. { name: 'HTML markup', value: /^\s*<!doctype\s*html>/ },
  5399. { name: 'HTML markup', value: /^\s*<!DOCTYPE\s*html>/ },
  5400. { name: 'HTML markup', value: /^\s*<!DOCTYPE\s*HTML>/ },
  5401. { name: 'HTML markup', value: /^\s*<!DOCTYPE\s*HTML\s+(PUBLIC|SYSTEM)?/ },
  5402. { name: 'Unity metadata', value: /^fileFormatVersion:/ },
  5403. { name: 'Python source code', value: /^((#.*(\n|\r\n))|('''.*'''(\n|\r\n))|("""[\s\S]*""")|(\n|\r\n))*(import[ ]+[a-zA-Z_]\w*(\.[a-zA-Z_]\w*)*([ ]+as[ ]+[a-zA-Z]\w*)?[ ]*(,|;|\n|\r\n))/ },
  5404. { name: 'Python source code', value: /^((#.*(\n|\r\n))|('''.*'''(\n|\r\n))|("""[\s\S]*""")|(\n|\r\n))*(from[ ]+([a-zA-Z_]\w*(\.[a-zA-Z_]\w*)*)[ ]+import[ ]+[a-zA-Z]\w*)/ },
  5405. { name: 'Python virtual environment configuration', value: /^home[ ]*=[ ]*/, identifier: 'pyvenv.cfg' },
  5406. { name: 'Bash script', value: /^#!\/usr\/bin\/env\s/ },
  5407. { name: 'Bash script', value: /^#!\/bin\/bash\s/ },
  5408. { name: 'TSD header', value: /^%TSD-Header-###%/ },
  5409. { name: 'AppleDouble data', value: /^\x00\x05\x16\x07/ },
  5410. { name: 'TensorFlow Hub module', value: /^\x08\x03$/, identifier: 'tfhub_module.pb' },
  5411. { name: 'V8 snapshot', value: /^.\x00\x00\x00.\x00\x00\x00/, identifier: 'snapshot_blob.bin' },
  5412. { name: 'V8 context snapshot', value: /^.\x00\x00\x00.\x00\x00\x00/, identifier: 'v8_context_snapshot.bin' },
  5413. { name: 'V8 natives blob', value: /^./, identifier: 'natives_blob.bin' },
  5414. { name: 'ViSQOL model', value: /^svm_type\s/ },
  5415. { name: 'SenseTime model', value: /^STEF/ },
  5416. { name: 'AES Crypt data', value: /^AES[\x01|\x02]\x00/ }
  5417. ];
  5418. /* eslint-enable no-control-regex */
  5419. const buffer = stream.peek(Math.min(4096, stream.length));
  5420. const content = String.fromCharCode.apply(null, buffer);
  5421. for (const entry of entries) {
  5422. if (content.match(entry.value) && (!entry.identifier || entry.identifier === context.identifier)) {
  5423. throw new view.Error('Invalid file content. File contains ' + entry.name + '.');
  5424. }
  5425. }
  5426. }
  5427. }
  5428. };
  5429. view.Metadata = class {
  5430. static async open(context, name) {
  5431. view.Metadata._metadata = view.Metadata._metadata || new Map();
  5432. if (view.Metadata._metadata.has(name)) {
  5433. return view.Metadata._metadata.get(name);
  5434. }
  5435. try {
  5436. const json = await context.request(name, 'utf-8', null);
  5437. const data = JSON.parse(json);
  5438. const library = new view.Metadata(data);
  5439. view.Metadata._metadata.set(name, library);
  5440. return library;
  5441. } catch (error) {
  5442. const library = new view.Metadata(null);
  5443. view.Metadata._metadata.set(name, library);
  5444. return library;
  5445. }
  5446. }
  5447. constructor(data) {
  5448. this._types = new Map();
  5449. this._attributes = new Map();
  5450. this._inputs = new Map();
  5451. for (const entry of data || []) {
  5452. this._types.set(entry.name, entry);
  5453. if (entry.identifier !== undefined) {
  5454. this._types.set(entry.identifier, entry);
  5455. }
  5456. }
  5457. }
  5458. type(name) {
  5459. if (!this._types.has(name)) {
  5460. this._types.set(name, { name: name.toString() });
  5461. }
  5462. return this._types.get(name);
  5463. }
  5464. attribute(type, name) {
  5465. const key = type + ':' + name;
  5466. if (!this._attributes.has(key)) {
  5467. this._attributes.set(key, null);
  5468. const metadata = this.type(type);
  5469. if (metadata && Array.isArray(metadata.attributes)) {
  5470. for (const attribute of metadata.attributes) {
  5471. this._attributes.set(type + ':' + attribute.name, attribute);
  5472. }
  5473. }
  5474. }
  5475. return this._attributes.get(key);
  5476. }
  5477. input(type, name) {
  5478. const key = type + ':' + name;
  5479. if (!this._inputs.has(key)) {
  5480. this._inputs.set(key, null);
  5481. const metadata = this.type(type);
  5482. if (metadata && Array.isArray(metadata.inputs)) {
  5483. for (const input of metadata.inputs) {
  5484. this._inputs.set(type + ':' + input.name, input);
  5485. }
  5486. }
  5487. }
  5488. return this._inputs.get(key);
  5489. }
  5490. };
  5491. view.Error = class extends Error {
  5492. constructor(message) {
  5493. super(message);
  5494. this.name = 'Error loading model.';
  5495. }
  5496. };
  5497. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  5498. module.exports.View = view.View;
  5499. module.exports.ModelFactoryService = view.ModelFactoryService;
  5500. module.exports.Documentation = view.Documentation;
  5501. module.exports.Formatter = view.Formatter;
  5502. module.exports.Tensor = view.Tensor;
  5503. }