python.js 297 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447
  1. // Experimental Python Execution
  2. var python = python || {};
  3. python.Parser = class {
  4. constructor(text, file, debug) {
  5. this._tokenizer = new python.Tokenizer(text, file);
  6. this._debug = debug;
  7. python.Parser._precedence = python.Parser._precedence || {
  8. 'or': 2, 'and': 3, 'not' : 4,
  9. 'in': 5, 'instanceof': 5, 'is': 5, '<': 5, '>': 5, '<=': 5, '>=': 5, '<>': 5, '==': 5, '!=': 5,
  10. '|': 6, '^' : 7, '&' : 8,
  11. '<<': 9, '>>': 9, '+': 10, '-': 10, '*': 11, '@': 11, '/': 11, '//': 11, '%': 11,
  12. // '+': 12, '-': 12,
  13. '~': 13, '**': 14
  14. };
  15. }
  16. parse() {
  17. const node = this._node('program');
  18. node.body = [];
  19. while (!this._tokenizer.match('eof')) {
  20. const statement = this._statement();
  21. if (statement) {
  22. node.body.push(statement);
  23. continue;
  24. }
  25. if (this._tokenizer.eat('\n') || this._tokenizer.eat(';') || this._tokenizer.peek().type == 'eof') {
  26. continue;
  27. }
  28. if (this._tokenizer.eat('indent') && this._tokenizer.peek().type == 'eof') {
  29. continue;
  30. }
  31. throw new python.Error('Unsupported statement' + this._tokenizer.location());
  32. }
  33. return node;
  34. }
  35. _suite() {
  36. const node = this._node('block');
  37. node.statements = [];
  38. let statement = null;
  39. if (this._tokenizer.eat('\n')) {
  40. if (this._tokenizer.eat('indent')) {
  41. while (!this._tokenizer.eat('eof') && !this._tokenizer.eat('dedent')) {
  42. if (this._tokenizer.eat(';')) {
  43. continue;
  44. }
  45. statement = this._statement();
  46. if (statement) {
  47. node.statements.push(statement);
  48. continue;
  49. }
  50. if (this._tokenizer.eat('\n')) {
  51. continue;
  52. }
  53. if (this._tokenizer.match('dedent') || this._tokenizer.match('eof')) {
  54. continue;
  55. }
  56. throw new python.Error('Empty statement' + this._tokenizer.location());
  57. }
  58. }
  59. }
  60. else if (!this._tokenizer.eat('eof')) {
  61. while (!this._tokenizer.match('\n') && !this._tokenizer.match('eof') && !this._tokenizer.match('dedent')) {
  62. if (this._tokenizer.eat(';')) {
  63. continue;
  64. }
  65. statement = this._statement();
  66. if (statement) {
  67. node.statements.push(statement);
  68. continue;
  69. }
  70. throw new python.Error('Empty statement' + this._tokenizer.location());
  71. }
  72. this._tokenizer.eat('\n');
  73. }
  74. return node;
  75. }
  76. _statement() {
  77. let node = this._eat('id', 'break');
  78. if (node) {
  79. return node;
  80. }
  81. node = this._eat('id', 'continue');
  82. if (node) {
  83. return node;
  84. }
  85. node = this._eat('id', 'return');
  86. if (node) {
  87. node.expression = this._expression(-1, [], true);
  88. return node;
  89. }
  90. node = this._eat('id', 'raise');
  91. if (node) {
  92. node.exception = this._expression(-1, [ 'from' ]);
  93. if (this._tokenizer.eat('id', 'from')) {
  94. node.from = this._expression();
  95. }
  96. else if (this._tokenizer.eat(',')) {
  97. node.exception = [ node.exception ];
  98. node.exception.push(this._expression());
  99. if (this._tokenizer.eat(',')) {
  100. node.exception.push(this._expression());
  101. }
  102. }
  103. return node;
  104. }
  105. node = this._eat('id', 'assert');
  106. if (node) {
  107. node.condition = this._expression(-1, [ ',' ]);
  108. if (this._tokenizer.eat(',')) {
  109. node.message = this._expression();
  110. }
  111. return node;
  112. }
  113. node = this._eat('id', 'exec');
  114. if (node) {
  115. node.variable = this._expression(-1, [ 'in' ]);
  116. if (this._tokenizer.eat('in')) {
  117. do {
  118. node.target = node.target || [];
  119. node.target.push(this._expression(-1, [ 'in' ], false));
  120. }
  121. while (this._tokenizer.eat(','));
  122. }
  123. return node;
  124. }
  125. node = this._eat('id', 'global');
  126. if (node) {
  127. node.names = [];
  128. do {
  129. node.names.push(this._name(true).value);
  130. }
  131. while (this._tokenizer.eat(','));
  132. return node;
  133. }
  134. node = this._eat('id', 'nonlocal');
  135. if (node) {
  136. node.names = [];
  137. do {
  138. node.names.push(this._name(true).value);
  139. }
  140. while (this._tokenizer.eat(','));
  141. return node;
  142. }
  143. node = this._eat('id', 'import');
  144. if (node) {
  145. node.names = [];
  146. do {
  147. const alias = this._node('alias');
  148. alias.name = this._dottedName();
  149. if (this._tokenizer.eat('id', 'as')) {
  150. alias.asname = this._name(true).value;
  151. }
  152. node.names.push(alias);
  153. }
  154. while (this._tokenizer.eat(','));
  155. return node;
  156. }
  157. node = this._eat('id', 'from');
  158. if (node) {
  159. node.type = 'import_from';
  160. node.level = 0;
  161. const dots = this._tokenizer.peek();
  162. if (dots && Array.from(dots.type).every((c) => c == '.')) {
  163. this._eat(dots.type);
  164. node.level = Array.from(dots.type).length;
  165. }
  166. node.module = this._dottedName();
  167. this._tokenizer.expect('id', 'import');
  168. node.names = [];
  169. const close = this._tokenizer.eat('(');
  170. do {
  171. const alias = this._node('alias');
  172. alias.name = this._name(true).value;
  173. if (this._tokenizer.eat('id', 'as')) {
  174. alias.asname = this._name(true).value;
  175. }
  176. node.names.push(alias);
  177. }
  178. while (this._tokenizer.eat(','));
  179. if (close) {
  180. this._tokenizer.expect(')');
  181. }
  182. return node;
  183. }
  184. let decorator_list = this._decorator();
  185. node = this._eat('id', 'class');
  186. if (node) {
  187. node.name = this._name(true).value;
  188. if (decorator_list) {
  189. node.decorator_list = Array.from(decorator_list);
  190. decorator_list = null;
  191. }
  192. node.bases = this._tokenizer.peek().type === '(' ? this._arguments() : [];
  193. this._tokenizer.expect(':');
  194. node.body = this._suite();
  195. return node;
  196. }
  197. const async = this._eat('id', 'async');
  198. if (async &&
  199. !this._tokenizer.match('id', 'def') &&
  200. !this._tokenizer.match('id', 'with') &&
  201. !this._tokenizer.match('id', 'for')) {
  202. throw new python.Error("Expected 'def', 'with' or 'for'" + this._tokenizer.location());
  203. }
  204. node = this._eat('id', 'def');
  205. if (node) {
  206. if (async) {
  207. node.async = async;
  208. }
  209. node.name = this._name(true).value;
  210. if (decorator_list) {
  211. node.decorator_list = Array.from(decorator_list);
  212. decorator_list = null;
  213. }
  214. this._tokenizer.expect('(');
  215. node.parameters = this._parameters(')');
  216. if (this._tokenizer.eat('->')) {
  217. node.returnType = this._type();
  218. }
  219. this._tokenizer.expect(':');
  220. node.body = this._suite();
  221. return node;
  222. }
  223. if (decorator_list && decorator_list.length > 0) {
  224. throw new python.Error('Unexpected decorator.');
  225. }
  226. node = this._eat('id', 'del');
  227. if (node) {
  228. node.expression = this._expression(-1, [], true);
  229. return node;
  230. }
  231. node = this._eat('id', 'print');
  232. if (node) {
  233. node.expression = this._expression(-1, [], true);
  234. return node;
  235. }
  236. node = this._eat('id', 'if');
  237. if (node) {
  238. node.condition = this._expression();
  239. this._tokenizer.expect(':');
  240. node.then = this._suite();
  241. let current = node;
  242. this._tokenizer.eat('\n');
  243. while (this._tokenizer.eat('id', 'elif')) {
  244. current.else = this._node('if');
  245. current = current.else;
  246. current.condition = this._expression();
  247. this._tokenizer.expect(':');
  248. current.then = this._suite();
  249. this._tokenizer.eat('\n');
  250. }
  251. if (this._tokenizer.eat('id', 'else')) {
  252. this._tokenizer.expect(':');
  253. current.else = this._suite();
  254. }
  255. return node;
  256. }
  257. node = this._eat('id', 'while');
  258. if (node) {
  259. node.condition = this._expression();
  260. this._tokenizer.expect(':');
  261. node.body = this._suite();
  262. if (this._tokenizer.eat('id', 'else')) {
  263. this._tokenizer.expect(':');
  264. node.else = this._suite();
  265. }
  266. return node;
  267. }
  268. node = this._eat('id', 'pass');
  269. if (node) {
  270. return node;
  271. }
  272. node = this._eat('id', 'for');
  273. if (node) {
  274. node.variable = [];
  275. node.variable.push(this._expression(-1, [ 'in' ]));
  276. while (this._tokenizer.eat(',')) {
  277. if (this._tokenizer.match('id', 'in')) {
  278. node.variable.push({});
  279. break;
  280. }
  281. node.variable.push(this._expression(-1, [ 'in' ]));
  282. }
  283. this._tokenizer.expect('id', 'in');
  284. node.target = [];
  285. node.target.push(this._expression());
  286. while (this._tokenizer.eat(',')) {
  287. if (this._tokenizer.match(':')) {
  288. node.target.push({});
  289. break;
  290. }
  291. node.target.push(this._expression(-1, [ 'in' ]));
  292. }
  293. this._tokenizer.expect(':');
  294. node.body = this._suite();
  295. if (this._tokenizer.eat('id', 'else')) {
  296. this._tokenizer.expect(':');
  297. node.else = this._suite();
  298. }
  299. return node;
  300. }
  301. node = this._eat('id', 'with');
  302. if (node) {
  303. if (async) {
  304. node.async = async;
  305. }
  306. node.item = [];
  307. do {
  308. const item = this._node();
  309. item.type = 'with_item';
  310. item.expression = this._expression();
  311. if (this._tokenizer.eat('id', 'as')) {
  312. item.variable = this._expression();
  313. }
  314. node.item.push(item);
  315. }
  316. while (this._tokenizer.eat(','));
  317. this._tokenizer.expect(':');
  318. node.body = this._suite();
  319. return node;
  320. }
  321. node = this._eat('id', 'try');
  322. if (node) {
  323. this._tokenizer.expect(':');
  324. node.body = this._suite();
  325. node.except = [];
  326. while (this._tokenizer.match('id', 'except')) {
  327. const except = this._node('except');
  328. this._tokenizer.expect('id', 'except');
  329. except.clause = [];
  330. except.clause.push(this._expression());
  331. while (this._tokenizer.eat(',')) {
  332. if (this._tokenizer.match(':') || this._tokenizer.match('as')) {
  333. except.clause.push({});
  334. break;
  335. }
  336. except.clause.push(this._expression());
  337. }
  338. if (this._tokenizer.eat('id', 'as')) {
  339. except.variable = this._expression();
  340. }
  341. this._tokenizer.expect(':');
  342. except.body = this._suite();
  343. node.except.push(except);
  344. }
  345. if (this._tokenizer.match('id', 'else')) {
  346. node.else = this._node('else');
  347. this._tokenizer.expect('id', 'else');
  348. this._tokenizer.expect(':');
  349. node.else.body = this._suite();
  350. }
  351. if (this._tokenizer.match('id', 'finally')) {
  352. node.finally = this._node('finally');
  353. this._tokenizer.expect('id', 'finally');
  354. this._tokenizer.expect(':');
  355. node.finally.body = this._suite();
  356. }
  357. return node;
  358. }
  359. const expression = this._expression(-1, [], true);
  360. if (expression) {
  361. if (expression.type == 'id' && this._tokenizer.eat(':')) {
  362. node = this._node('var');
  363. node.name = expression.value;
  364. node.location = expression.location;
  365. node.variableType = this._expression(-1, [ '=' ]);
  366. if (this._tokenizer.eat('=')) {
  367. node.initializer = this._expression();
  368. }
  369. return node;
  370. }
  371. switch (expression.type) {
  372. case '=':
  373. case ':=':
  374. case '==':
  375. case '!=':
  376. case '+=':
  377. case '-=':
  378. case '*=':
  379. case '@=':
  380. case '/=':
  381. case '//=':
  382. case '**=':
  383. case '&=':
  384. case '|=':
  385. case '%=':
  386. case '>>=':
  387. case '<<=':
  388. case '>>':
  389. case '<<':
  390. case '>=':
  391. case '<=':
  392. case '<':
  393. case '>':
  394. case '%':
  395. case '^=':
  396. case '...':
  397. case 'call':
  398. case 'assert':
  399. case 'raise':
  400. case 'string':
  401. case 'list':
  402. case 'var':
  403. case '.':
  404. case '[]':
  405. case 'yield':
  406. case '+':
  407. case '-':
  408. case '*':
  409. case '**':
  410. case '@':
  411. case '/':
  412. case '//':
  413. case '~':
  414. case '&':
  415. case '^':
  416. case '|':
  417. case 'not':
  418. case 'id':
  419. case 'number':
  420. case 'in':
  421. case 'and':
  422. case 'or':
  423. case 'if':
  424. case 'for':
  425. case 'tuple':
  426. case 'lambda':
  427. case 'await':
  428. return expression;
  429. default:
  430. throw new python.Error("Unhandled expression" + this._tokenizer.location());
  431. }
  432. }
  433. return null;
  434. }
  435. _expression(minPrecedence, terminal, tuple) {
  436. minPrecedence = minPrecedence || -1;
  437. const terminalSet = new Set(terminal);
  438. const stack = [];
  439. for (;;) {
  440. let node = this._node();
  441. const token = this._tokenizer.peek();
  442. if (stack.length == 1 && terminalSet.has(token.value)) {
  443. break;
  444. }
  445. const precedence = python.Parser._precedence[token.value];
  446. if (precedence) {
  447. if (precedence >= minPrecedence) {
  448. this._tokenizer.read();
  449. node.type = token.value;
  450. if (token.type == 'id' && (token.value === 'in' || token.value === 'not')) {
  451. if (token.value === 'in') {
  452. node.type = 'in';
  453. }
  454. else if (this._tokenizer.eat('id', 'in')) {
  455. node.type = 'not in';
  456. }
  457. else {
  458. node.type = 'not';
  459. node.expression = this._expression(precedence, terminal, tuple === false ? false : true);
  460. stack.push(node);
  461. continue;
  462. }
  463. }
  464. else if (token.value == '~') {
  465. node.type = '~';
  466. node.expression = this._expression(precedence, terminal, tuple === false ? false : true);
  467. stack.push(node);
  468. continue;
  469. }
  470. else if (token.type == 'id' && token.value == 'is') {
  471. if (this._tokenizer.eat('id', 'not')) {
  472. node.type = 'is not';
  473. }
  474. }
  475. if (stack.length > 0) {
  476. node.op = node.type;
  477. node.type = 'binary';
  478. node.left = stack.pop();
  479. node.right = this._expression(precedence, terminal, tuple === true ? true : false);
  480. }
  481. else {
  482. node.op = node.type;
  483. node.type = 'unary';
  484. node.operand = this._expression(precedence, terminal, tuple === true ? true : false);
  485. }
  486. stack.push(node);
  487. continue;
  488. }
  489. }
  490. if (this._tokenizer.eat(':=')) {
  491. node.type = ':=';
  492. node.target = stack.pop();
  493. node.expression = this._expression(-1, terminal, tuple === false ? false : true);
  494. stack.push(node);
  495. continue;
  496. }
  497. if (this._tokenizer.eat('=')) {
  498. node.type = '=';
  499. node.target = stack.pop();
  500. node.expression = this._expression(-1, terminal, tuple === false ? false : true);
  501. stack.push(node);
  502. continue;
  503. }
  504. switch (token.type) {
  505. case '-=':
  506. case '**=':
  507. case '*=':
  508. case '//=':
  509. case '/=':
  510. case '&=':
  511. case '%=':
  512. case '^=':
  513. case '+=':
  514. case '<<=':
  515. case '>>=':
  516. case '|=':
  517. case '@=':
  518. node = this._node(token.type);
  519. this._tokenizer.expect(token.type);
  520. node.target = stack.pop();
  521. node.expression = this._expression(-1, terminal, true);
  522. stack.push(node);
  523. continue;
  524. default:
  525. break;
  526. }
  527. node = this._eat('id', 'if');
  528. if (node) {
  529. node.then = stack.pop();
  530. node.condition = this._expression();
  531. this._tokenizer.expect('id', 'else');
  532. node.else = this._expression();
  533. stack.push(node);
  534. continue;
  535. }
  536. while (this._tokenizer.match('id', 'for') || this._tokenizer.match('id', 'async')) {
  537. const async = this._eat('id', 'async');
  538. if (async && !this._tokenizer.match('id', 'for')) {
  539. throw new python.Error("Expected 'for'" + this._tokenizer.location());
  540. }
  541. node = this._eat('id', 'for');
  542. if (node) {
  543. if (async) {
  544. node.async = async;
  545. }
  546. node.expression = stack.pop();
  547. node.variable = this._expression(-1, [ 'in' ], true);
  548. this._tokenizer.expect('id', 'in');
  549. node.target = this._expression(-1, [ 'for', 'if' ], true);
  550. while (this._tokenizer.eat('id', 'if')) {
  551. node.condition = node.condition || [];
  552. node.condition.push(this._expression(-1, [ 'for', 'if' ]));
  553. }
  554. stack.push(node);
  555. }
  556. }
  557. node = this._eat('id', 'lambda');
  558. if (node) {
  559. node.parameters = this._parameters(':');
  560. node.body = this._expression(-1, terminal, false);
  561. stack.push(node);
  562. continue;
  563. }
  564. node = this._eat('id', 'yield');
  565. if (node) {
  566. if (this._tokenizer.eat('id', 'from')) {
  567. node.from = this._expression(-1, [], true);
  568. }
  569. else {
  570. node.expression = [];
  571. do {
  572. node.expression.push(this._expression(-1, [], false));
  573. }
  574. while (this._tokenizer.eat(','));
  575. }
  576. stack.push(node);
  577. continue;
  578. }
  579. node = this._eat('id', 'await');
  580. if (node) {
  581. node.expression = this._expression(minPrecedence, terminal, tuple);
  582. stack.push(node);
  583. continue;
  584. }
  585. node = this._eat('.');
  586. if (node) {
  587. this._tokenizer.eat('\n');
  588. node.target = stack.pop();
  589. node.member = this._name();
  590. stack.push(node);
  591. continue;
  592. }
  593. if (this._tokenizer.peek().type === '(') {
  594. if (stack.length == 0) {
  595. node = this._node('tuple');
  596. const args = this._arguments();
  597. if (args.length == 1) {
  598. stack.push(args[0]);
  599. }
  600. else {
  601. node.value = args;
  602. stack.push(node);
  603. }
  604. }
  605. else {
  606. node = this._node('call');
  607. node.target = stack.pop();
  608. node.arguments = this._arguments();
  609. stack.push(node);
  610. }
  611. continue;
  612. }
  613. if (this._tokenizer.peek().type === '[') {
  614. if (stack.length == 0) {
  615. stack.push(this._expressions());
  616. }
  617. else {
  618. node = this._node('[]');
  619. node.target = stack.pop();
  620. node.arguments = this._slice();
  621. stack.push(node);
  622. }
  623. continue;
  624. }
  625. if (this._tokenizer.peek().type == '{') {
  626. stack.push(this._dictOrSetMaker());
  627. continue;
  628. }
  629. node = this._node();
  630. const literal = this._literal();
  631. if (literal) {
  632. if (stack.length > 0 && literal.type == 'number' &&
  633. (literal.value.startsWith('-') || literal.value.startsWith('+'))) {
  634. node.type = literal.value.substring(0, 1);
  635. literal.value = literal.value.substring(1);
  636. node.left = stack.pop();
  637. node.right = literal;
  638. stack.push(node);
  639. }
  640. else if (stack.length == 1 && literal.type == 'string' && stack[0].type == 'string') {
  641. stack[0].value += literal.value;
  642. }
  643. else {
  644. if (literal.type === 'number') {
  645. switch (literal.value) {
  646. case 'inf': literal.value = Infinity; break;
  647. case '-inf': literal.value = -Infinity; break;
  648. default: break;
  649. }
  650. }
  651. stack.push(literal);
  652. }
  653. continue;
  654. }
  655. if (this._tokenizer.peek().keyword) {
  656. break;
  657. }
  658. node = this._eat('...');
  659. if (node) {
  660. stack.push(node);
  661. continue;
  662. }
  663. const identifier = this._name();
  664. if (identifier) {
  665. stack.push(identifier);
  666. continue;
  667. }
  668. if (tuple === true && stack.length == 1 && this._tokenizer.eat(',')) {
  669. if (stack[0].type === 'tuple') {
  670. node = stack[0];
  671. }
  672. else {
  673. node = this._node('tuple');
  674. node.value = [ stack.pop() ];
  675. stack.push(node);
  676. }
  677. // for, bar, = <expr>
  678. if (this._tokenizer.peek().type === '=') {
  679. continue;
  680. }
  681. if (!this._tokenizer.match('=') && !terminalSet.has(this._tokenizer.peek().value)) {
  682. const nextTerminal = terminal.slice(0).concat([ ',', '=' ]);
  683. const expression = this._expression(minPrecedence, nextTerminal, tuple);
  684. if (expression) {
  685. node.value.push(expression);
  686. continue;
  687. }
  688. }
  689. break;
  690. }
  691. break;
  692. }
  693. if (stack.length == 1) {
  694. return stack.pop();
  695. }
  696. if (stack.length != 0) {
  697. throw new python.Error('Unexpected expression' + this._tokenizer.location());
  698. }
  699. return null;
  700. }
  701. _decorator() {
  702. let list = null;
  703. while (this._tokenizer.eat('@')) {
  704. const node = this._node('decorator');
  705. node.value = this._expression();
  706. if (!node.value || (node.value.type !== 'call' && node.value.type !== 'id' && node.value.type !== '.')) {
  707. throw new python.Error('Invalid decorator' + this._tokenizer.location());
  708. }
  709. this._tokenizer.eat('\n');
  710. list = list !== null ? list : [];
  711. list.push(node);
  712. }
  713. return list;
  714. }
  715. _dictOrSetMaker() {
  716. const list = [];
  717. this._tokenizer.expect('{');
  718. let dict = true;
  719. while (!this._tokenizer.eat('}')) {
  720. const item = this._expression(-1, [], false);
  721. if (item == null) {
  722. throw new python.Error('Expected expression' + this._tokenizer.location());
  723. }
  724. if (!this._tokenizer.eat(':')) {
  725. dict = false;
  726. }
  727. if (dict) {
  728. const value = this._expression(-1, [], false);
  729. if (value == null) {
  730. throw new python.Error('Expected expression' + this._tokenizer.location());
  731. }
  732. list.push({ type: 'pair', key: item, value: value });
  733. }
  734. else {
  735. list.push(item);
  736. }
  737. this._tokenizer.eat(',');
  738. this._tokenizer.eat('\n');
  739. if (this._tokenizer.eat('}')) {
  740. break;
  741. }
  742. }
  743. if (dict) {
  744. return { type: 'dict', value: list };
  745. }
  746. return { type: 'set', value: list };
  747. }
  748. _expressions() {
  749. const list = [];
  750. this._tokenizer.expect('[');
  751. while (!this._tokenizer.eat(']')) {
  752. const expression = this._expression();
  753. if (expression == null) {
  754. throw new python.Error('Expected expression' + this._tokenizer.location());
  755. }
  756. list.push(expression);
  757. this._tokenizer.eat(',');
  758. while (this._tokenizer.eat('\n')) {
  759. // continue
  760. }
  761. if (this._tokenizer.eat(']')) {
  762. break;
  763. }
  764. }
  765. return { type: 'list', value: list };
  766. }
  767. _slice() {
  768. let node = { type: '::' };
  769. let list = [];
  770. const group = [ 'start', 'stop', 'step' ];
  771. this._tokenizer.expect('[');
  772. while (!this._tokenizer.eat(']')) {
  773. if (this._tokenizer.eat(':')) {
  774. node[group.shift()] = { type: 'list', value: list };
  775. list = [];
  776. continue;
  777. }
  778. if (this._tokenizer.eat(',')) {
  779. // list.push({});
  780. continue;
  781. }
  782. if (this._tokenizer.peek().type != ']') {
  783. const expression = this._expression();
  784. if (expression == null) {
  785. throw new python.Error('Expected expression' + this._tokenizer.location());
  786. }
  787. list.push(expression);
  788. }
  789. }
  790. if (list.length > 0) {
  791. node[group.shift()] = { type: 'list', value: list };
  792. }
  793. if (node.start && !node.stop && !node.step) {
  794. node = node.start;
  795. }
  796. return node;
  797. }
  798. _name(required) {
  799. const token = this._tokenizer.peek();
  800. if (token.type == 'id' && !token.keyword) {
  801. this._tokenizer.read();
  802. return token;
  803. }
  804. if (required) {
  805. throw new python.Error("Invalid syntax" + this._tokenizer.location());
  806. }
  807. return null;
  808. }
  809. _dottedName() {
  810. const list = [];
  811. do {
  812. list.push(this._name(true).value);
  813. }
  814. while (this._tokenizer.eat('.'));
  815. return list.join('.');
  816. }
  817. _literal() {
  818. const token = this._tokenizer.peek();
  819. if (token.type == 'string' || token.type == 'number' || token.type == 'boolean') {
  820. this._tokenizer.read();
  821. return token;
  822. }
  823. return null;
  824. }
  825. _typeArguments() {
  826. const list = [];
  827. this._tokenizer.expect('[');
  828. while (!this._tokenizer.eat(']')) {
  829. const type = this._type();
  830. if (type == null) {
  831. throw new python.Error('Expected type ' + this._tokenizer.location());
  832. }
  833. list.push(type);
  834. if (!this._tokenizer.eat(',')) {
  835. this._tokenizer.expect(']');
  836. break;
  837. }
  838. }
  839. return list;
  840. }
  841. _type() {
  842. const type = this._node();
  843. type.type = 'type';
  844. type.name = this._expression(-1, [ '[', '=' ]);
  845. if (type.name) {
  846. if (this._tokenizer.peek().value === '[') {
  847. type.arguments = this._typeArguments();
  848. }
  849. return type;
  850. }
  851. return null;
  852. }
  853. _parameter(terminal) {
  854. const node = this._node('parameter');
  855. if (this._tokenizer.eat('/')) {
  856. node.name = '/';
  857. return node;
  858. }
  859. if (this._tokenizer.eat('**')) {
  860. node.parameterType = '**';
  861. }
  862. if (this._tokenizer.eat('*')) {
  863. node.parameterType = '*';
  864. }
  865. const identifier = this._name();
  866. if (identifier !== null) {
  867. node.name = identifier.value;
  868. if (terminal !== ':' && this._tokenizer.eat(':')) {
  869. node.parameterType = this._type();
  870. }
  871. if (this._tokenizer.eat('=')) {
  872. node.initializer = this._expression();
  873. }
  874. return node;
  875. }
  876. return null;
  877. }
  878. _parameters(terminal) {
  879. const list = [];
  880. while (!this._tokenizer.eat(terminal)) {
  881. this._tokenizer.eat('\n');
  882. if (this._tokenizer.eat('(')) {
  883. list.push(this._parameters(')'));
  884. }
  885. else {
  886. list.push(this._parameter(terminal));
  887. }
  888. this._tokenizer.eat('\n');
  889. if (!this._tokenizer.eat(',')) {
  890. this._tokenizer.expect(terminal);
  891. break;
  892. }
  893. }
  894. return list;
  895. }
  896. _arguments() {
  897. const list = [];
  898. this._tokenizer.expect('(');
  899. while (!this._tokenizer.eat(')')) {
  900. if (this._tokenizer.eat('\n')) {
  901. continue;
  902. }
  903. const expression = this._expression(-1, [], false);
  904. if (expression == null) {
  905. throw new python.Error('Expected expression ' + this._tokenizer.location());
  906. }
  907. list.push(expression);
  908. if (!this._tokenizer.eat(',')) {
  909. this._tokenizer.eat('\n');
  910. this._tokenizer.expect(')');
  911. break;
  912. }
  913. }
  914. return list;
  915. }
  916. _node(type) {
  917. const node = {};
  918. node.location = this._tokenizer.location();
  919. if (type) {
  920. node.type = type;
  921. }
  922. return node;
  923. }
  924. _eat(type, value) {
  925. if (this._tokenizer.match(type, value)) {
  926. const node = this._node(type === 'id' ? value : type);
  927. this._tokenizer.expect(type, value);
  928. return node;
  929. }
  930. return null;
  931. }
  932. };
  933. python.Tokenizer = class {
  934. constructor(text, file) {
  935. this._text = text;
  936. this._file = file;
  937. this._position = 0;
  938. this._lineStart = 0;
  939. this._line = 0;
  940. this._token = { type: '', value: '' };
  941. this._brackets = 0;
  942. this._indentation = [];
  943. this._outdent = 0;
  944. if (!python.Tokenizer._whitespace) {
  945. python.Tokenizer._whitespace = new RegExp('[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]');
  946. const identifierStartChars = '\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc';
  947. const identifierChars = '\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u0620-\u0649\u0672-\u06d3\u06e7-\u06e8\u06fb-\u06fc\u0730-\u074a\u0800-\u0814\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0840-\u0857\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962-\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09d7\u09df-\u09e0\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5f-\u0b60\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2-\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d46-\u0d48\u0d57\u0d62-\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e34-\u0e3a\u0e40-\u0e45\u0e50-\u0e59\u0eb4-\u0eb9\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f41-\u0f47\u0f71-\u0f84\u0f86-\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1029\u1040-\u1049\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u170e-\u1710\u1720-\u1730\u1740-\u1750\u1772\u1773\u1780-\u17b2\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1920-\u192b\u1930-\u193b\u1951-\u196d\u19b0-\u19c0\u19c8-\u19c9\u19d0-\u19d9\u1a00-\u1a15\u1a20-\u1a53\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b46-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1bb0-\u1bb9\u1be6-\u1bf3\u1c00-\u1c22\u1c40-\u1c49\u1c5b-\u1c7d\u1cd0-\u1cd2\u1d00-\u1dbe\u1e01-\u1f15\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2d81-\u2d96\u2de0-\u2dff\u3021-\u3028\u3099\u309a\ua640-\ua66d\ua674-\ua67d\ua69f\ua6f0-\ua6f1\ua7f8-\ua800\ua806\ua80b\ua823-\ua827\ua880-\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8f3-\ua8f7\ua900-\ua909\ua926-\ua92d\ua930-\ua945\ua980-\ua983\ua9b3-\ua9c0\uaa00-\uaa27\uaa40-\uaa41\uaa4c-\uaa4d\uaa50-\uaa59\uaa7b\uaae0-\uaae9\uaaf2-\uaaf3\uabc0-\uabe1\uabec\uabed\uabf0-\uabf9\ufb20-\ufb28\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f';
  948. python.Tokenizer._identifierStart = new RegExp('[' + identifierStartChars + ']');
  949. /* eslint-disable */
  950. python.Tokenizer._identifierChar = new RegExp('[' + identifierStartChars + identifierChars + ']');
  951. /* eslint-enable */
  952. }
  953. }
  954. peek() {
  955. if (!this._cache) {
  956. this._tokenize();
  957. this._cache = true;
  958. }
  959. return this._token;
  960. }
  961. read() {
  962. if (!this._cache) {
  963. this._tokenize();
  964. }
  965. const next = this._position + this._token.value.length;
  966. while (this._position < next) {
  967. if (python.Tokenizer._isNewline(this._get(this._position))) {
  968. this._position = this._newLine(this._position);
  969. this._lineStart = this._position;
  970. this._line++;
  971. }
  972. else {
  973. this._position++;
  974. }
  975. }
  976. this._cache = false;
  977. return this._token;
  978. }
  979. match(type, value) {
  980. const token = this.peek();
  981. if (token.type === type && (!value || token.value === value)) {
  982. return true;
  983. }
  984. return false;
  985. }
  986. eat(type, value) {
  987. const token = this.peek();
  988. if (token.type === type && (!value || token.value === value)) {
  989. this.read();
  990. return true;
  991. }
  992. return false;
  993. }
  994. expect(type, value) {
  995. const token = this.peek();
  996. if (token.type !== type) {
  997. throw new python.Error("Unexpected '" + token.value + "' instead of '" + type + "'" + this.location());
  998. }
  999. if (value && token.value !== value) {
  1000. throw new python.Error("Unexpected '" + token.value + "' instead of '" + value + "'" + this.location());
  1001. }
  1002. this.read();
  1003. }
  1004. location() {
  1005. return ' at ' + this._file + ':' + (this._line + 1).toString() + ':' + (this._position - this._lineStart + 1).toString();
  1006. }
  1007. static _isSpace(c) {
  1008. switch (c) {
  1009. case ' ':
  1010. case '\t':
  1011. case '\v': // 11
  1012. case '\f': // 12
  1013. case '\xA0': // 160
  1014. return true;
  1015. default:
  1016. if (c.charCodeAt(0) >= 0x1680) {
  1017. return python.Tokenizer._whitespace.test(c);
  1018. }
  1019. return false;
  1020. }
  1021. }
  1022. static _isNewline(c) {
  1023. switch (c) {
  1024. case '\n':
  1025. case '\r':
  1026. case '\u2028': // 8232
  1027. case '\u2029': // 8233
  1028. return true;
  1029. default:
  1030. return false;
  1031. }
  1032. }
  1033. static _isIdentifierStartChar(c) {
  1034. if (c < 'A') {
  1035. return c === '$';
  1036. }
  1037. if (c <= 'Z') {
  1038. return true;
  1039. }
  1040. if (c < 'a') {
  1041. return c === '_';
  1042. }
  1043. if (c <= 'z') {
  1044. return true;
  1045. }
  1046. const code = c.charCodeAt(0);
  1047. if (code >= 0xAA) {
  1048. return python.Tokenizer._identifierStart.test(c);
  1049. }
  1050. return false;
  1051. }
  1052. static _isIdentifierChar(c) {
  1053. if (c < '0') {
  1054. return c === '$';
  1055. }
  1056. if (c <= '9') {
  1057. return true;
  1058. }
  1059. if (c < 'A') {
  1060. return false;
  1061. }
  1062. if (c <= 'Z') {
  1063. return true;
  1064. }
  1065. if (c < 'a') {
  1066. return c === '_';
  1067. }
  1068. if (c <= 'z') {
  1069. return true;
  1070. }
  1071. const code = c.charCodeAt(0);
  1072. if (code >= 0xAA) {
  1073. return python.Tokenizer._identifierChar.test(c);
  1074. }
  1075. return false;
  1076. }
  1077. _get(position) {
  1078. return position >= this._text.length ? '\0' : this._text[position];
  1079. }
  1080. _skipLine() {
  1081. while (this._position < this._text.length) {
  1082. if (python.Tokenizer._isNewline(this._get(this._position))) {
  1083. break;
  1084. }
  1085. this._position++;
  1086. }
  1087. }
  1088. _skipWhitespace() {
  1089. while (this._position < this._text.length) {
  1090. const c = this._text[this._position];
  1091. if (c == '#') {
  1092. this._skipLine();
  1093. }
  1094. else if (python.Tokenizer._isSpace(c)) {
  1095. this._position++;
  1096. }
  1097. else if (c == '\\') {
  1098. // Explicit Line Continuation
  1099. this._position++;
  1100. if (python.Tokenizer._isNewline(this._get(this._position))) {
  1101. this._position = this._newLine(this._position);
  1102. this._lineStart = this._position;
  1103. this._line++;
  1104. }
  1105. else {
  1106. throw new python.Error("Unexpected '" + this._text[this._position] + "' after line continuation" + this.location());
  1107. }
  1108. }
  1109. else if (this._brackets > 0 && python.Tokenizer._isNewline(c)) {
  1110. // Implicit Line Continuation
  1111. this._position = this._newLine(this._position);
  1112. this._lineStart = this._position;
  1113. this._line++;
  1114. }
  1115. else {
  1116. break;
  1117. }
  1118. }
  1119. }
  1120. _newLine(position) {
  1121. if ((this._get(position) === '\n' && this._get(position + 1) === '\r') ||
  1122. (this._get(position) === '\r' && this._get(position + 1) === '\n')) {
  1123. return position + 2;
  1124. }
  1125. return position + 1;
  1126. }
  1127. _tokenize() {
  1128. if (this._token.type !== '\n') {
  1129. this._skipWhitespace();
  1130. }
  1131. if (this._token.type === 'dedent') {
  1132. this._indentation.pop();
  1133. this._outdent--;
  1134. if (this._outdent > 0) {
  1135. this._token = { type: 'dedent', value: '' };
  1136. return;
  1137. }
  1138. }
  1139. if (this._token.type == '\n') {
  1140. let indent = '';
  1141. let i = this._position;
  1142. while (i < this._text.length) {
  1143. const c = this._text[i];
  1144. if (python.Tokenizer._isSpace(c)) {
  1145. indent += c;
  1146. i++;
  1147. }
  1148. else if (python.Tokenizer._isNewline(c)) {
  1149. indent = '';
  1150. i = this._newLine(i);
  1151. this._position = i;
  1152. this._lineStart = i;
  1153. this._line++;
  1154. }
  1155. else if (c == '#') {
  1156. indent = '';
  1157. while (i < this._text.length && !python.Tokenizer._isNewline(this._text[i])) {
  1158. i++;
  1159. }
  1160. continue;
  1161. }
  1162. else {
  1163. break;
  1164. }
  1165. }
  1166. let type = null;
  1167. if (indent.length > 0) {
  1168. const current = this._indentation.length > 0 ? this._indentation[this._indentation.length - 1] : '';
  1169. if (indent.length > current.length) {
  1170. type = 'indent';
  1171. this._indentation.push(indent);
  1172. }
  1173. else if (indent.length > 0 && indent.length < current.length) {
  1174. type = 'dedent';
  1175. this._outdent = 0;
  1176. for (let j = this._indentation.length - 1; j >= 0 && indent.length < this._indentation[j].length; j--) {
  1177. this._outdent++;
  1178. }
  1179. }
  1180. else {
  1181. this._position += indent.length;
  1182. }
  1183. }
  1184. else if (i >= this._text.length) {
  1185. this._token = { type: 'eof', value: '' };
  1186. return;
  1187. }
  1188. else if (this._indentation.length > 0) {
  1189. type = 'dedent';
  1190. this._outdent = this._indentation.length;
  1191. }
  1192. if (type === 'indent' || type === 'dedent') {
  1193. this._token = { type: type, value: indent };
  1194. return;
  1195. }
  1196. }
  1197. if (this._position >= this._text.length) {
  1198. this._token = { type: 'eof', value: '' };
  1199. return;
  1200. }
  1201. const c = this._get(this._position);
  1202. const string = this._string();
  1203. if (string) {
  1204. this._token = string;
  1205. return;
  1206. }
  1207. switch (c) {
  1208. case '(':
  1209. case '[':
  1210. case '{':
  1211. this._brackets++;
  1212. this._token = { type: c, value: c };
  1213. return;
  1214. case ')':
  1215. case ']':
  1216. case '}':
  1217. if (this._brackets === 0) {
  1218. throw new python.Error("Unexpected '" + c + "'" + this.location);
  1219. }
  1220. this._brackets--;
  1221. this._token = { type: c, value: c };
  1222. return;
  1223. case ',':
  1224. case ';':
  1225. case '?':
  1226. this._token = { type: c, value: c };
  1227. return;
  1228. default: {
  1229. const number = this._number();
  1230. if (number) {
  1231. this._token = number;
  1232. return;
  1233. }
  1234. if (c === '.') {
  1235. let end = this._position + 1;
  1236. while (this._get(end) === '.') {
  1237. end++;
  1238. }
  1239. const text = this._text.substring(this._position, end);
  1240. this._token = { type: text, value: text };
  1241. return;
  1242. }
  1243. const identifier = this._identifier();
  1244. if (identifier) {
  1245. this._token = identifier;
  1246. return;
  1247. }
  1248. const operator = this._operator();
  1249. if (operator) {
  1250. this._token = operator;
  1251. return;
  1252. }
  1253. break;
  1254. }
  1255. }
  1256. if (c === '.') {
  1257. this._token = { type: c, value: c };
  1258. return;
  1259. }
  1260. if (c === '\\') {
  1261. this._token = { type: '\\', value: c };
  1262. return;
  1263. }
  1264. if (python.Tokenizer._isNewline(c)) {
  1265. this._token = { type: '\n', value: this._text.substring(this._position, this._newLine(this._position)) };
  1266. return;
  1267. }
  1268. throw new python.Error("Unexpected token '" + c + "'" + this.location());
  1269. }
  1270. _number() {
  1271. const octal = (c) => c >= '0' && c <= '7' || c === '_';
  1272. const binary = (c) => c === '0' || c === '1' || c === '_';
  1273. const decimal = (c) => c >= '0' && c <= '9' || c === '_';
  1274. const hex = (c) => decimal(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || c === '_';
  1275. let c = this._get(this._position);
  1276. const sign = (c === '-' || c === '+') ? 1 : 0;
  1277. let i = this._position + sign;
  1278. c = this._get(i);
  1279. if (c === '0') {
  1280. let radix = 0;
  1281. const n = this._get(i + 1);
  1282. if ((n === 'x' || n === 'X') && hex(this._get(i + 2))) {
  1283. i += 2;
  1284. while (hex(this._get(i))) {
  1285. i += 1;
  1286. }
  1287. if (this._get(i) === 'l' || this._get(i) === 'L') {
  1288. i += 1;
  1289. }
  1290. radix = 16;
  1291. }
  1292. else if ((n === 'b' || n === 'B') && binary(this._get(i + 2))) {
  1293. i += 2;
  1294. while (binary(this._get(i))) {
  1295. i++;
  1296. }
  1297. radix = 2;
  1298. }
  1299. else if ((n === 'o' || n === 'O') && octal(this._get(i + 2))) {
  1300. i += 2;
  1301. while (octal(this._get(i))) {
  1302. i++;
  1303. }
  1304. radix = 8;
  1305. }
  1306. else if (n >= '0' && n <= '7') {
  1307. i++;
  1308. while (octal(this._get(i))) {
  1309. i += 1;
  1310. }
  1311. if (this._get(i) === 'l' || this._get(i) === 'L') {
  1312. i += 1;
  1313. }
  1314. radix = 8;
  1315. }
  1316. if (radix > 0 && this._get(i) !== '.') {
  1317. const radixText = this._text.substring(this._position, i);
  1318. const radixParseText = radixText.indexOf('_') !== -1 ? radixText.split('_').join('') : radixText;
  1319. if (!isNaN(parseInt(radixParseText, radix))) {
  1320. return { type: 'number', value: radixText };
  1321. }
  1322. }
  1323. }
  1324. i = this._position + sign;
  1325. let isDecimal = false;
  1326. if (this._get(i) >= '1' && this._get(i) <= '9') {
  1327. while (decimal(this._get(i))) {
  1328. i++;
  1329. }
  1330. c = this._get(i).toLowerCase();
  1331. isDecimal = c !== '.' && c !== 'e';
  1332. }
  1333. if (this._get(i) === '0') {
  1334. i++;
  1335. c = this._get(i).toLowerCase();
  1336. isDecimal = !decimal(c) && c !== '.' && c !== 'e' && c !== 'j';
  1337. }
  1338. if (isDecimal) {
  1339. if (this._get(i) === 'j' || this._get(i) === 'J' || this._get(i) === 'l' || this._get(i) === 'L') {
  1340. return { 'type': 'number', value: this._text.substring(this._position, i + 1) };
  1341. }
  1342. const intText = this._text.substring(this._position, i);
  1343. if (!isNaN(parseInt(intText, 10))) {
  1344. return { type: 'number', value: intText };
  1345. }
  1346. }
  1347. i = this._position + sign;
  1348. if ((this._get(i) >= '0' && this._get(i) <= '9') ||
  1349. (this._get(i) === '.' && this._get(i + 1) >= '0' && this._get(i + 1) <= '9')) {
  1350. while (decimal(this._get(i))) {
  1351. i++;
  1352. }
  1353. if (this._get(i) === '.') {
  1354. i++;
  1355. }
  1356. while (decimal(this._get(i))) {
  1357. i++;
  1358. }
  1359. if (i > (this._position + sign)) {
  1360. if (this._get(i) === 'e' || this._get(i) === 'E') {
  1361. i++;
  1362. if (this._get(i) == '-' || this._get(i) == '+') {
  1363. i++;
  1364. }
  1365. if (!decimal(this._get(i))) {
  1366. i = this._position;
  1367. }
  1368. else {
  1369. while (decimal(this._get(i))) {
  1370. i++;
  1371. }
  1372. }
  1373. }
  1374. else {
  1375. while (decimal(this._get(i))) {
  1376. i++;
  1377. }
  1378. }
  1379. }
  1380. if (i > (this._position + sign)) {
  1381. if (this._get(i) === 'j' || this._get(i) === 'J') {
  1382. return { type: 'number', value: this._text.substring(this._position, i + 1) };
  1383. }
  1384. const floatText = this._text.substring(this._position, i);
  1385. const floatParseText = floatText.indexOf('_') != -1 ? floatText.split('_').join('') : floatText;
  1386. if (!isNaN(parseFloat(floatParseText))) {
  1387. return { type: 'number', value: floatText };
  1388. }
  1389. }
  1390. }
  1391. return null;
  1392. }
  1393. _identifier() {
  1394. let i = this._position;
  1395. if (python.Tokenizer._isIdentifierStartChar(this._get(i))) {
  1396. i++;
  1397. while (python.Tokenizer._isIdentifierChar(this._get(i))) {
  1398. i++;
  1399. }
  1400. }
  1401. if (i > this._position) {
  1402. const text = this._text.substring(this._position, i);
  1403. let keyword = false;
  1404. switch (text) {
  1405. case 'and':
  1406. case 'as':
  1407. case 'else':
  1408. case 'for':
  1409. case 'if':
  1410. case 'import':
  1411. case 'in':
  1412. case 'is':
  1413. case 'not':
  1414. case 'or':
  1415. keyword = true;
  1416. break;
  1417. default:
  1418. keyword = false;
  1419. break;
  1420. }
  1421. return { type: 'id', value: text, keyword: keyword };
  1422. }
  1423. return null;
  1424. }
  1425. _operator() {
  1426. let length = 0;
  1427. const c0 = this._get(this._position);
  1428. const c1 = this._get(this._position + 1);
  1429. const c2 = this._get(this._position + 2);
  1430. switch (c0) {
  1431. case '+':
  1432. case '&':
  1433. case '|':
  1434. case '^':
  1435. case '=':
  1436. case '!':
  1437. case '%':
  1438. case '~':
  1439. length = c1 === '=' ? 2 : 1;
  1440. break;
  1441. case '-':
  1442. length = c1 === '=' || c1 === '>' ? 2 : 1;
  1443. break;
  1444. case '*':
  1445. length = c1 === '*' ? (c2 === '=' ? 3 : 2) : (c1 === '=' ? 2 : 1);
  1446. break;
  1447. case '/':
  1448. length = c1 === '/' ? (c2 === '=' ? 3 : 2) : (c1 === '=' ? 2 : 1);
  1449. break;
  1450. case '<':
  1451. length = c1 === '>' ? 2 : (c1 === '<' ? (c2 === '=' ? 3 : 2) : (c1 === '=' ? 2 : 1));
  1452. break;
  1453. case '>':
  1454. length = c1 === '>' ? (c2 === '=' ? 3 : 2) : (c1 === '=' ? 2 : 1);
  1455. break;
  1456. case '@':
  1457. length = c1 === '=' ? 2 : 1;
  1458. break;
  1459. case ':':
  1460. length = c1 === '=' ? 2 : 1;
  1461. break;
  1462. default:
  1463. return null;
  1464. }
  1465. const text = this._text.substring(this._position, this._position + length);
  1466. return { type: text, value: text };
  1467. }
  1468. _string() {
  1469. let i = this._position;
  1470. let prefix = -1;
  1471. if (this._get(i) === "'" || this._get(i) === '"') {
  1472. prefix = '';
  1473. }
  1474. else if (this._get(i + 1) === "'" || this._get(i + 1) === '"') {
  1475. const c = this._get(i);
  1476. switch (c.toLowerCase()) {
  1477. case 'b':
  1478. case 'f':
  1479. case 'r':
  1480. case 'u':
  1481. prefix = c;
  1482. break;
  1483. default:
  1484. break;
  1485. }
  1486. }
  1487. else if (this._get(i + 2) === "'" || this._get(i + 2) === '"') {
  1488. const cc = this._text.substr(this._position, 2);
  1489. switch (cc.toLowerCase()) {
  1490. case 'br':
  1491. case 'fr':
  1492. case 'rb':
  1493. case 'rf':
  1494. case 'ur':
  1495. prefix = cc;
  1496. break;
  1497. default:
  1498. break;
  1499. }
  1500. }
  1501. if (prefix.length >= 0) {
  1502. i += prefix.length;
  1503. let quote = '';
  1504. let count = 0;
  1505. const q0 = this._get(i);
  1506. const q1 = this._get(i + 1);
  1507. const q2 = this._get(i + 2);
  1508. switch (q0) {
  1509. case "'":
  1510. quote = q0;
  1511. count = (q1 === "'" && q2 === "'") ? 3 : 1;
  1512. break;
  1513. case '"':
  1514. quote = q0;
  1515. count = (q1 === '"' && q2 === '"') ? 3 : 1;
  1516. break;
  1517. default:
  1518. throw new python.Error("Unsupported string quote '" + q0 + "'.");
  1519. }
  1520. i += count;
  1521. if (count == 1) {
  1522. while (i < this._text.length) {
  1523. if (this._text[i] === quote) {
  1524. return { type: 'string', value: this._text.substring(this._position, i + 1) };
  1525. }
  1526. else if (this._text[i] === '\\' &&
  1527. (this._get(i + 1) == quote || this._get(i + 1) == '\n' || this._get(i + 1) == '\\')) {
  1528. i += 2;
  1529. }
  1530. else if (this._text[i] === '\r' || this._text[i] === '\n') {
  1531. break;
  1532. }
  1533. else {
  1534. i++;
  1535. }
  1536. }
  1537. }
  1538. else if (count == 3) {
  1539. while (i < this._text.length) {
  1540. if (this._get(i) === quote && this._get(i + 1) === quote && this._get(i + 2) === quote) {
  1541. return { type: 'string', value: this._text.substring(this._position, i + 3) };
  1542. }
  1543. else if (this._get(i) === '\\' && this._get(i + 1) === quote) {
  1544. i += 2;
  1545. continue;
  1546. }
  1547. i++;
  1548. }
  1549. }
  1550. }
  1551. i = this._position;
  1552. if (this._get(i) === '`') {
  1553. i++;
  1554. while (i < this._text.length) {
  1555. if (this._text[i] === '`') {
  1556. return { type: 'string', value: this._text.substring(this._position, i + 1) };
  1557. }
  1558. i++;
  1559. }
  1560. }
  1561. return null;
  1562. }
  1563. };
  1564. python.Execution = class {
  1565. constructor(sources) {
  1566. const self = this;
  1567. const execution = self;
  1568. this._sources = sources || new Map();
  1569. this._events = new Map();
  1570. this._utf8Decoder = new TextDecoder('utf-8');
  1571. this._unresolved = new Map();
  1572. const dict = class extends Map {
  1573. constructor(items) {
  1574. super();
  1575. if (items) {
  1576. for (const pair of items) {
  1577. this.__setitem__(pair[0], pair[1]);
  1578. }
  1579. }
  1580. }
  1581. __contains__(key) {
  1582. return this.has(key);
  1583. }
  1584. __setitem__(key, value) {
  1585. this.set(key, value);
  1586. }
  1587. __getitem__(key) {
  1588. return this.get(key);
  1589. }
  1590. };
  1591. this._modules = new dict();
  1592. this._registry = new Map();
  1593. const module = class {
  1594. constructor(name) {
  1595. this.__name__ = name;
  1596. }
  1597. };
  1598. this._builtins = this.register('builtins', new module('builtins'));
  1599. this._registry.set('__builtin__', this._builtins);
  1600. this.registerType('builtins.type', class {}).__class__ = this._builtins.type;
  1601. this.registerType('builtins.module', module);
  1602. this.registerType('builtins.method', class {});
  1603. this.registerType('builtins.function', class {});
  1604. this.import('builtins');
  1605. this.registerType('builtins.builtin_function_or_method', class {});
  1606. this._typing = this.register('typing');
  1607. this.register('_codecs');
  1608. this.register('argparse');
  1609. this.register('collections');
  1610. this.register('copy_reg');
  1611. this.register('cuml');
  1612. this.register('gensim');
  1613. this.register('io');
  1614. this.register('joblib');
  1615. this.register('keras');
  1616. this.register('lightgbm');
  1617. this.register('nolearn');
  1618. const math = this.register('math');
  1619. math.inf = Infinity;
  1620. const numpy = this.register('numpy');
  1621. const pickle = this.register('pickle');
  1622. this.register('sklearn');
  1623. const torch = this.register('torch');
  1624. this.register('torch.storage');
  1625. this.register('torch.nn.parameter');
  1626. this.register('torch.ops');
  1627. this.register('torch.ops.torchvision');
  1628. this.register('torch.ops.torchaudio');
  1629. this.register('torch.ops._caffe2');
  1630. this.register('torchvision');
  1631. this.register('__torch__');
  1632. this.register('sys').modules = this._modules;
  1633. this.register('xgboost');
  1634. this.registerType('builtins.dict', dict);
  1635. this.registerType('builtins.list', class {});
  1636. this.registerType('builtins.number', class {});
  1637. this.registerFunction('builtins.__import__', function(name, globals, locals, fromlist, level) {
  1638. return execution.__import__(name, globals, locals, fromlist, level);
  1639. });
  1640. this.registerFunction('builtins.bool', function(value) {
  1641. if (value) {
  1642. if (value.__bool__) {
  1643. return value.__bool__();
  1644. }
  1645. if (value.__len__) {
  1646. return value.__len__() > 0;
  1647. }
  1648. }
  1649. return false;
  1650. });
  1651. this.registerFunction('builtins.int', function(value) {
  1652. if (value) {
  1653. if (value.__int__) {
  1654. return value.__int__();
  1655. }
  1656. if (Number.isInteger(value)) {
  1657. return value;
  1658. }
  1659. }
  1660. return NaN;
  1661. });
  1662. this.registerFunction('builtins.float', function(value) {
  1663. if (value) {
  1664. if (value.__float__) {
  1665. return value.__float__();
  1666. }
  1667. if (Number(value) === value) {
  1668. return value;
  1669. }
  1670. }
  1671. return NaN;
  1672. });
  1673. this.registerFunction('builtins.str', function(value) {
  1674. if (value) {
  1675. if (value.__str__) {
  1676. return value.__str__();
  1677. }
  1678. }
  1679. return JSON.stringify(value);
  1680. });
  1681. this.registerType('builtins.object', class {});
  1682. this.registerType('builtins.tuple', class extends Array {
  1683. constructor(items) {
  1684. super(items ? items.length : 0);
  1685. if (items) {
  1686. for (let i = 0; i < items.length; i++) {
  1687. this[i] = items[i];
  1688. }
  1689. }
  1690. }
  1691. });
  1692. this.registerFunction('builtins.long', this.builtins.int);
  1693. this.registerFunction('builtins.print', function() {});
  1694. this.registerFunction('builtins.unicode', function(/* value */) {
  1695. throw new python.Error('Not implemented.');
  1696. });
  1697. this.registerType('builtins.Warning', class {});
  1698. this.registerType('builtins.FutureWarning', class extends this._builtins.Warning {});
  1699. this.registerType('typing._Final', class {});
  1700. this.registerType('typing._SpecialForm', class extends this._typing._Final {});
  1701. this.registerType('typing._BaseGenericAlias', class extends this._typing._Final {});
  1702. this.registerType('typing._GenericAlias', class extends this._typing._BaseGenericAlias {});
  1703. this.registerType('typing._SpecialGenericAlias', class extends this._typing._BaseGenericAlias {});
  1704. this.registerType('typing._TupleType', class extends this._typing._SpecialGenericAlias {});
  1705. this._typing.Optional = Reflect.construct(this._typing._SpecialForm, []);
  1706. this._typing.List = Reflect.construct(this._typing._SpecialGenericAlias, []);
  1707. this._typing.Dict = Reflect.construct(this._typing._SpecialGenericAlias, []);
  1708. this._typing.Tuple = Reflect.construct(this._typing._TupleType, []);
  1709. this._typing.Any = Reflect.construct(this._typing._SpecialForm, []);
  1710. this.registerType('argparse.Namespace', class {
  1711. constructor(args) {
  1712. this.args = args;
  1713. }
  1714. });
  1715. this.registerType('collections.deque', class extends Array {
  1716. constructor(iterable) {
  1717. super();
  1718. if (Array.isArray(iterable)) {
  1719. for (const value of iterable) {
  1720. this.push(value);
  1721. }
  1722. }
  1723. }
  1724. });
  1725. this.registerType('collections.OrderedDict', class extends dict {});
  1726. this.registerType('cuml.common.array_descriptor.CumlArrayDescriptorMeta', class {});
  1727. this.registerType('cuml.ensemble.randomforestclassifier.RandomForestClassifier', class {});
  1728. this.registerType('cuml.raft.common.handle.Handle', class {
  1729. __setstate__(state) {
  1730. this._handle = state;
  1731. }
  1732. });
  1733. this.registerType('dnnlib.tflib.network.Network', class {});
  1734. this.registerType('dnnlib.util.EasyDict', class extends dict {});
  1735. this.registerType('haiku._src.data_structures.FlatMapping', class {
  1736. constructor(dict) {
  1737. Object.assign(this, dict);
  1738. }
  1739. });
  1740. this.registerType('haiku._src.data_structures.frozendict', class {
  1741. constructor(obj) {
  1742. Object.assign(this, obj);
  1743. }
  1744. });
  1745. this.registerType('hmmlearn.hmm.MultinomialHMM', class {
  1746. __setstate__(state) {
  1747. Object.assign(this, state);
  1748. }
  1749. });
  1750. this.registerType('hmmlearn.base.ConvergenceMonitor', class {
  1751. __setstate__(state) {
  1752. Object.assign(this, state);
  1753. }
  1754. });
  1755. this.registerType('io.BytesIO', class {
  1756. constructor(buf, mode) {
  1757. this.mode = mode || 'r';
  1758. this._buf = this.mode === 'w' ? null : buf;
  1759. this._point = 0;
  1760. }
  1761. seek(offset) {
  1762. this._point = offset;
  1763. }
  1764. read(size) {
  1765. const start = this._point;
  1766. this._point = size !== undefined ? start + size : this._buf.length;
  1767. return this._buf.subarray(start, this._point);
  1768. }
  1769. write(data) {
  1770. const src = this._buf || new Uint8Array();
  1771. this._point = src.length + data.length;
  1772. this._buf = new Uint8Array(this._point);
  1773. this._buf.set(src, 0);
  1774. this._buf.set(data, src.length);
  1775. }
  1776. });
  1777. this.registerType('numpy.dtype', class {
  1778. constructor(obj, align, copy) {
  1779. if (typeof obj === 'string' && (obj.startsWith('<') || obj.startsWith('>'))) {
  1780. this.byteorder = obj[0];
  1781. obj = obj.substring(1);
  1782. }
  1783. else {
  1784. this.byteorder = '=';
  1785. }
  1786. switch (obj) {
  1787. case 'b1': case 'bool': this.itemsize = 1; this.kind = 'b'; break;
  1788. case 'i1': case 'int8': this.itemsize = 1; this.kind = 'i'; break;
  1789. case 'i2': case 'int16': this.itemsize = 2; this.kind = 'i'; break;
  1790. case 'i4': case 'int32': this.itemsize = 4; this.kind = 'i'; break;
  1791. case 'i8': case 'int64': case 'int': this.itemsize = 8; this.kind = 'i'; break;
  1792. case 'u1': case 'uint8': this.itemsize = 1; this.kind = 'u'; break;
  1793. case 'u2': case 'uint16': this.itemsize = 2; this.kind = 'u'; break;
  1794. case 'u4': case 'uint32': this.itemsize = 4; this.kind = 'u'; break;
  1795. case 'u8': case 'uint64': case 'uint': this.itemsize = 8; this.kind = 'u'; break;
  1796. case 'f2': case 'float16': this.itemsize = 2; this.kind = 'f'; break;
  1797. case 'f4': case 'float32': this.itemsize = 4; this.kind = 'f'; break;
  1798. case 'f8': case 'float64': case 'float': this.itemsize = 8; this.kind = 'f'; break;
  1799. case 'c8': case 'complex64': this.itemsize = 8; this.kind = 'c'; break;
  1800. case 'c16': case 'complex128': case 'complex': this.itemsize = 16; this.kind = 'c'; break;
  1801. case 'M8': case 'M': this.itemsize = 8; this.kind = 'M'; break;
  1802. default:
  1803. if (obj.startsWith('V')) {
  1804. this.itemsize = parseInt(obj.substring(1), 10);
  1805. this.kind = 'V';
  1806. }
  1807. else if (obj.startsWith('O')) {
  1808. this.itemsize = obj === 'O' ? 8 : parseInt(obj.substring(1), 10);
  1809. this.kind = 'O';
  1810. }
  1811. else if (obj.startsWith('S')) {
  1812. this.itemsize = parseInt(obj.substring(1), 10);
  1813. this.kind = 'S';
  1814. }
  1815. else if (obj.startsWith('U')) { // Unicode string
  1816. this.kind = 'U';
  1817. this.itemsize = 4 * parseInt(obj.substring(1), 10);
  1818. }
  1819. else {
  1820. throw new python.Error("Unsupported dtype '" + obj.toString() + "'.");
  1821. }
  1822. break;
  1823. }
  1824. if (align) {
  1825. this.align = align;
  1826. }
  1827. if (copy) {
  1828. this.copy = copy;
  1829. }
  1830. }
  1831. get str() {
  1832. return (this.byteorder === '=' ? '<' : this.byteorder) + this.kind + this.itemsize.toString();
  1833. }
  1834. get name() {
  1835. switch (this.kind) {
  1836. case 'V': return 'void' + (this.itemsize === 0 ? '' : (this.itemsize * 8).toString());
  1837. case 'S': return 'bytes' + (this.itemsize === 0 ? '' : (this.itemsize * 8).toString());
  1838. case 'U': return 'str' + (this.itemsize === 0 ? '' : (this.itemsize * 8).toString());
  1839. case 'M': return 'datetime64';
  1840. case 'b': return 'bool';
  1841. default: return this.__name__;
  1842. }
  1843. }
  1844. __setstate__(state) {
  1845. switch (state.length) {
  1846. case 8:
  1847. this.version = state[0];
  1848. this.byteorder = state[1];
  1849. this.subarray = state[2];
  1850. this.names = state[3];
  1851. this.fields = state[4];
  1852. this.elsize = state[5];
  1853. this.alignment = state[6];
  1854. this.int_dtypeflags = state[7];
  1855. break;
  1856. case 9:
  1857. this.version = state[0];
  1858. this.byteorder = state[1];
  1859. this.subarray = state[2];
  1860. this.names = state[3];
  1861. this.fields = state[4];
  1862. this.elsize = state[5];
  1863. this.alignment = state[6];
  1864. this.int_dtypeflags = state[7];
  1865. this.metadata = state[8];
  1866. break;
  1867. default:
  1868. throw new python.Error("Unsupported numpy.dtype setstate length '" + state.length.toString() + "'.");
  1869. }
  1870. }
  1871. get __name__() {
  1872. switch (this.kind) {
  1873. case 'b':
  1874. switch (this.itemsize) {
  1875. case 1: return 'boolean';
  1876. default: throw new python.Error("Unsupported boolean itemsize '" + this.itemsize + "'.");
  1877. }
  1878. case 'i':
  1879. switch (this.itemsize) {
  1880. case 1: return 'int8';
  1881. case 2: return 'int16';
  1882. case 4: return 'int32';
  1883. case 8: return 'int64';
  1884. default: throw new python.Error("Unsupported int itemsize '" + this.itemsize + "'.");
  1885. }
  1886. case 'u':
  1887. switch (this.itemsize) {
  1888. case 1: return 'uint8';
  1889. case 2: return 'uint16';
  1890. case 4: return 'uint32';
  1891. case 8: return 'uint64';
  1892. default: throw new python.Error("Unsupported uint itemsize '" + this.itemsize + "'.");
  1893. }
  1894. case 'f':
  1895. switch (this.itemsize) {
  1896. case 2: return 'float16';
  1897. case 4: return 'float32';
  1898. case 8: return 'float64';
  1899. default: throw new python.Error("Unsupported float itemsize '" + this.itemsize + "'.");
  1900. }
  1901. case 'c':
  1902. switch (this.itemsize) {
  1903. case 8: return 'complex64';
  1904. case 16: return 'complex128';
  1905. default: throw new python.Error("Unsupported complex itemsize '" + this.itemsize + "'.");
  1906. }
  1907. case 'S':
  1908. case 'U':
  1909. return 'string';
  1910. case 'M':
  1911. return 'datetime';
  1912. case 'O':
  1913. return 'object';
  1914. case 'V':
  1915. return 'void';
  1916. default:
  1917. throw new python.Error("Unsupported dtype kind '" + this.kind + "'.");
  1918. }
  1919. }
  1920. });
  1921. this.registerType('numpy.generic', class {});
  1922. this.registerType('numpy.inexact', class {});
  1923. this.registerType('numpy.number', class extends numpy.generic {});
  1924. this.registerType('numpy.integer', class extends numpy.number {});
  1925. this.registerType('numpy.floating', class extends numpy.inexact {});
  1926. this.registerType('numpy.float32', class extends numpy.floating {});
  1927. this.registerType('numpy.float64', class extends numpy.floating {});
  1928. this.registerType('numpy.signedinteger', class extends numpy.integer {});
  1929. this.registerType('numpy.int8', class extends numpy.signedinteger {});
  1930. this.registerType('numpy.int16', class extends numpy.signedinteger {});
  1931. this.registerType('numpy.int32', class extends numpy.signedinteger {});
  1932. this.registerType('numpy.int64', class extends numpy.signedinteger {});
  1933. this.registerType('numpy.unsignedinteger', class extends numpy.integer {});
  1934. this.registerType('numpy.uint8', class extends numpy.unsignedinteger {});
  1935. this.registerType('numpy.uint16', class extends numpy.unsignedinteger {});
  1936. this.registerType('numpy.uint32', class extends numpy.unsignedinteger {});
  1937. this.registerType('numpy.uint64', class extends numpy.unsignedinteger {});
  1938. this.registerType('fastai.callback.core.TrainEvalCallback', class {});
  1939. this.registerType('fastai.callback.hook._hook_inner', class {});
  1940. this.registerType('fastai.callback.hook.Hook', class {});
  1941. this.registerType('fastai.callback.hook.Hooks', class {});
  1942. this.registerType('fastai.callback.progress.ProgressCallback', class {});
  1943. this.registerType('fastai.data.core.DataLoaders', class {});
  1944. this.registerType('fastai.data.core.Datasets', class {});
  1945. this.registerType('fastai.data.core.TfmdDL', class {});
  1946. this.registerType('fastai.data.core.TfmdLists', class {});
  1947. this.registerType('fastai.data.load._FakeLoader', class {});
  1948. this.registerType('fastai.data.load._wif', class {});
  1949. this.registerType('fastai.data.transforms.Categorize', class {});
  1950. this.registerType('fastai.data.transforms.CategoryMap', class {});
  1951. this.registerType('fastai.data.transforms.IntToFloatTensor', class {});
  1952. this.registerType('fastai.data.transforms.Normalize', class {});
  1953. this.registerType('fastai.data.transforms.parent_label', class {});
  1954. this.registerType('fastai.data.transforms.ToTensor', class {});
  1955. this.registerType('fastai.imports.noop', class {});
  1956. this.registerType('fastai.layers.AdaptiveConcatPool2d', class {});
  1957. this.registerType('fastai.layers.ConvLayer', class {});
  1958. this.registerType('fastai.layers.Flatten', class {});
  1959. this.registerType('fastai.layers.MergeLayer', class {});
  1960. this.registerType('fastai.layers.PixelShuffle_ICNR', class {});
  1961. this.registerType('fastai.layers.ResBlock', class {});
  1962. this.registerType('fastai.layers.SelfAttention', class {});
  1963. this.registerType('fastai.learner.AvgLoss', class {});
  1964. this.registerType('fastai.learner.AvgMetric', class {});
  1965. this.registerType('fastai.learner.AvgSmoothLoss', class {});
  1966. this.registerType('fastai.learner.Learner', class {});
  1967. this.registerType('fastai.learner.Recorder', class {});
  1968. this.registerType('fastai.losses.CrossEntropyLossFlat', class {});
  1969. this.registerType('fastai.metrics.error_rate', class {});
  1970. this.registerType('fastai.optimizer.Adam', class {});
  1971. this.registerType('fastai.torch_core._fa_rebuild_tensor', class {});
  1972. this.registerType('fastai.torch_core.TensorBase', class {});
  1973. this.registerType('fastai.torch_core.TensorCategory', class {});
  1974. this.registerType('fastai.torch_core.TensorImage', class {});
  1975. this.registerType('fastai.vision.augment._BrightnessLogit', class {});
  1976. this.registerType('fastai.vision.augment._ContrastLogit', class {});
  1977. this.registerType('fastai.vision.augment._WarpCoord', class {});
  1978. this.registerType('fastai.vision.augment.Brightness', class {});
  1979. this.registerType('fastai.vision.augment.flip_mat', class {});
  1980. this.registerType('fastai.vision.augment.Flip', class {});
  1981. this.registerType('fastai.vision.augment.RandomResizedCropGPU', class {});
  1982. this.registerType('fastai.vision.augment.Resize', class {});
  1983. this.registerType('fastai.vision.augment.rotate_mat', class {});
  1984. this.registerType('fastai.vision.augment.zoom_mat', class {});
  1985. this.registerType('fastai.vision.core.PILImage', class {});
  1986. this.registerType('fastai.vision.learner._resnet_split', class {});
  1987. this.registerType('fastai.vision.models.unet.DynamicUnet', class {});
  1988. this.registerType('fastai.vision.models.unet.ResizeToOrig', class {});
  1989. this.registerType('fastai.vision.models.unet.UnetBlock', class {});
  1990. this.registerType('fastcore.basics.fastuple', class {});
  1991. this.registerType('fastcore.basics.GetAttr', class {});
  1992. this.registerType('fastcore.dispatch._TypeDict', class {});
  1993. this.registerType('fastcore.dispatch.TypeDispatch', class {});
  1994. this.registerType('fastcore.foundation.L', class {});
  1995. this.registerType('fastcore.transform.Pipeline', class {});
  1996. this.registerType('fastcore.transform.Transform', class {});
  1997. this.registerType('functools.partial', class {});
  1998. this.registerType('gensim.models.doc2vec.Doctag', class {});
  1999. this.registerType('gensim.models.doc2vec.Doc2Vec', class {});
  2000. this.registerType('gensim.models.doc2vec.Doc2VecTrainables', class {});
  2001. this.registerType('gensim.models.doc2vec.Doc2VecVocab', class {});
  2002. this.registerType('gensim.models.fasttext.FastText', class {});
  2003. this.registerType('gensim.models.fasttext.FastTextTrainables', class {});
  2004. this.registerType('gensim.models.fasttext.FastTextVocab', class {});
  2005. this.registerType('gensim.models.fasttext.FastTextKeyedVectors', class {});
  2006. this.registerType('gensim.models.keyedvectors.Doc2VecKeyedVectors', class {});
  2007. this.registerType('gensim.models.keyedvectors.FastTextKeyedVectors', class {});
  2008. this.registerType('gensim.models.keyedvectors.KeyedVectors', class {});
  2009. this.registerType('gensim.models.keyedvectors.Vocab', class {});
  2010. this.registerType('gensim.models.keyedvectors.Word2VecKeyedVectors', class {});
  2011. this.registerType('gensim.models.phrases.Phrases', class {});
  2012. this.registerType('gensim.models.tfidfmodel.TfidfModel', class {});
  2013. this.registerType('gensim.models.word2vec.Vocab', class {});
  2014. this.registerType('gensim.models.word2vec.Word2Vec', class {});
  2015. this.registerType('gensim.models.word2vec.Word2VecTrainables', class {});
  2016. this.registerType('gensim.models.word2vec.Word2VecVocab', class {});
  2017. this.registerType('google3.learning.deepmind.research.nbr.pbl_jax.clean_jaxline.utils.optimizers.ScaleByLarsState', class {
  2018. constructor(obj) {
  2019. Object.assign(this, obj);
  2020. }
  2021. });
  2022. this.registerType('joblib.numpy_pickle.NumpyArrayWrapper', class {
  2023. constructor(/* subtype, shape, dtype */) {
  2024. }
  2025. __setstate__(state) {
  2026. this.subclass = state.subclass;
  2027. this.dtype = state.dtype;
  2028. this.shape = state.shape;
  2029. this.order = state.order;
  2030. this.allow_mmap = state.allow_mmap;
  2031. }
  2032. __read__(unpickler) {
  2033. if (this.dtype.__name__ == 'object') {
  2034. return unpickler.load();
  2035. }
  2036. const size = this.dtype.itemsize * this.shape.reduce((a, b) => a * b, 1);
  2037. this.data = unpickler.read(size);
  2038. return execution.invoke(this.subclass, [ this.shape, this.dtype, this.data ]);
  2039. }
  2040. });
  2041. this.registerType('keras.engine.sequential.Sequential', class {});
  2042. this.registerType('lasagne.layers.conv.Conv2DLayer', class {});
  2043. this.registerType('lasagne.layers.dense.DenseLayer', class {});
  2044. this.registerType('lasagne.layers.input.InputLayer', class {});
  2045. this.registerType('lasagne.layers.pool.MaxPool2DLayer', class {});
  2046. this.registerType('lightgbm.sklearn.LGBMRegressor', class {});
  2047. this.registerType('lightgbm.sklearn.LGBMClassifier', class {});
  2048. this.registerType('lightgbm.basic.Booster', class {
  2049. constructor() {
  2050. this.average_output = false;
  2051. this.models = [];
  2052. this.loaded_parameter = '';
  2053. }
  2054. __setstate__(state) {
  2055. if (typeof state.handle === 'string') {
  2056. this.LoadModelFromString(state.handle);
  2057. return;
  2058. }
  2059. Object.assign(this, state);
  2060. }
  2061. LoadModelFromString(model_str) {
  2062. const lines = model_str.split('\n');
  2063. const signature = lines.shift() || '?';
  2064. if (signature.trim() !== 'tree') {
  2065. throw new python.Error("Invalid signature '" + signature.trim() + "'.");
  2066. }
  2067. // GBDT::LoadModelFromString() in https://github.com/microsoft/LightGBM/blob/master/src/boosting/gbdt_model_text.cpp
  2068. const key_vals = new Map();
  2069. while (lines.length > 0 && !lines[0].startsWith('Tree=')) {
  2070. const cur_line = lines.shift().trim();
  2071. if (cur_line.length > 0) {
  2072. const strs = cur_line.split('=');
  2073. if (strs.length === 1) {
  2074. key_vals.set(strs[0], '');
  2075. }
  2076. else if (strs.length === 2) {
  2077. key_vals.set(strs[0], strs[1]);
  2078. }
  2079. else if (strs.length > 2) {
  2080. if (strs[0] === "feature_names") {
  2081. key_vals.set(strs[0], cur_line.substring("feature_names=".length));
  2082. }
  2083. else if (strs[0] == 'monotone_constraints') {
  2084. key_vals.set(strs[0], cur_line.substring('monotone_constraints='.length));
  2085. }
  2086. else {
  2087. throw new python.Error('Wrong line: ' + cur_line.substring(0, Math.min(128, cur_line.length)));
  2088. }
  2089. }
  2090. }
  2091. }
  2092. const atoi = (key, value) => {
  2093. if (key_vals.has(key)) {
  2094. return parseInt(key_vals.get(key), 10);
  2095. }
  2096. if (value !== undefined) {
  2097. return value;
  2098. }
  2099. throw new python.Error('Model file does not specify ' + key + '.');
  2100. };
  2101. const list = (key, size) => {
  2102. if (key_vals.has(key)) {
  2103. const value = key_vals.get(key).split(' ');
  2104. if (value.length !== size) {
  2105. throw new python.Error('Wrong size of ' + key + '.');
  2106. }
  2107. return value;
  2108. }
  2109. throw new python.Error('Model file does not contain ' + key + '.');
  2110. };
  2111. this.version = key_vals.get('version') || '';
  2112. this.num_class = atoi('num_class');
  2113. this.num_tree_per_iteration = atoi('num_tree_per_iteration', this.num_class);
  2114. this.label_index = atoi('label_index');
  2115. this.max_feature_idx = atoi('max_feature_idx');
  2116. if (key_vals.has('average_output')) {
  2117. this.average_output = true;
  2118. }
  2119. this.feature_names = list('feature_names', this.max_feature_idx + 1);
  2120. this.feature_infos = list('feature_infos', this.max_feature_idx + 1);
  2121. if (key_vals.has('monotone_constraints')) {
  2122. this.monotone_constraints = list('monotone_constraints', this.max_feature_idx + 1);
  2123. }
  2124. if (key_vals.has('objective')) {
  2125. this.objective = key_vals.get('objective');
  2126. }
  2127. let tree = null;
  2128. while (lines.length > 0) {
  2129. const text = lines.shift();
  2130. const line = text.trim();
  2131. if (line.length === 0) {
  2132. continue;
  2133. }
  2134. if (line.startsWith('Tree=')) {
  2135. tree = { index: parseInt(line.split('=').pop(), 10) };
  2136. this.models.push(tree);
  2137. continue;
  2138. }
  2139. if (line === 'end of trees') {
  2140. break;
  2141. }
  2142. const param = line.split('=');
  2143. if (param.length !== 2) {
  2144. throw new python.Error("Invalid property '" + line + "'.");
  2145. }
  2146. const name = param[0].trim();
  2147. const value = param[1].trim();
  2148. tree[name] = value;
  2149. }
  2150. const ss = [];
  2151. let is_inparameter = false;
  2152. while (lines.length > 0) {
  2153. const text = lines.shift();
  2154. const line = text.trim();
  2155. if (line === 'parameters:') {
  2156. is_inparameter = true;
  2157. continue;
  2158. }
  2159. else if (line === 'end of parameters') {
  2160. break;
  2161. }
  2162. else if (is_inparameter) {
  2163. ss.push(line);
  2164. }
  2165. }
  2166. if (ss.length > 0) {
  2167. this.loaded_parameter = ss.join('\n');
  2168. }
  2169. }
  2170. });
  2171. this.registerFunction('megengine.functional.nn.conv2d', function() {});
  2172. this.registerFunction('megengine.functional.nn.relu', function() {});
  2173. this.registerFunction('megengine.module.qat.module.QATModule._apply_fakequant_with_observer', function() {});
  2174. this.registerFunction('megengine.functional.tensor.concat', function() {});
  2175. this.registerFunction('megengine.functional.tensor.flatten', function() {});
  2176. this.registerType('megengine.core._imperative_rt.common.CompNode', class {});
  2177. this.registerType('megengine.core._imperative_rt.ops.FakeQuant', class {});
  2178. this.registerType('megengine.core._imperative_rt.ops.GetVarShape', class {});
  2179. this.registerType('megengine.core.ops._internal.param_defs.ConvolutionV0.Mode', class {});
  2180. this.registerType('megengine.core.ops._internal.param_defs.Convolution.ComputeMode', class {});
  2181. this.registerType('megengine.module.activation.ReLU', class {});
  2182. this.registerType('megengine.module.batchnorm.BatchNorm1d', class {});
  2183. this.registerType('megengine.module.batchnorm.BatchNorm2d', class {});
  2184. this.registerType('megengine.module.conv.Conv2d', class {});
  2185. this.registerType('megengine.module.conv.ConvTranspose2d', class {});
  2186. this.registerType('megengine.module.identity.Identity', class {});
  2187. this.registerType('megengine.module.linear.Linear', class {});
  2188. this.registerType('megengine.module.module.Module', class {});
  2189. this.registerType('megengine.module.pooling.AvgPool2d', class {});
  2190. this.registerType('megengine.module.pooling.MaxPool2d', class {});
  2191. this.registerType('megengine.module.qat.concat.Concat', class {});
  2192. this.registerType('megengine.module.qat.elemwise.Elemwise', class {});
  2193. this.registerType('megengine.module.sequential.Sequential', class {});
  2194. this.registerType('megengine.quantization.fake_quant.FakeQuantize', class {});
  2195. this.registerType('megengine.quantization.utils.QParams', class {});
  2196. this.registerType('megengine.quantization.utils.QuantMode', class {});
  2197. this.registerType('megengine.quantization.observer.PassiveObserver', class {});
  2198. this.registerType('megengine.quantization.observer.MinMaxObserver', class {});
  2199. this.registerType('megengine.quantization.observer.ExponentialMovingAverageObserver', class {});
  2200. this.registerType('megengine.traced_module.expr.Apply', class {});
  2201. this.registerType('megengine.traced_module.expr.CallFunction', class {});
  2202. this.registerType('megengine.traced_module.expr.CallMethod', class {});
  2203. this.registerType('megengine.traced_module.expr.Constant', class {});
  2204. this.registerType('megengine.traced_module.expr.GetAttr', class {});
  2205. this.registerType('megengine.traced_module.expr.Input', class {});
  2206. this.registerType('megengine.traced_module.fake_quant.FakeQuantize', class {});
  2207. this.registerType('megengine.traced_module.node.ModuleNode', class {});
  2208. this.registerType('megengine.traced_module.node.NodeMixin', class {});
  2209. this.registerType('megengine.traced_module.node.TensorNode', class {});
  2210. this.registerType('megengine.traced_module.pytree.ArgsIndex', class {});
  2211. this.registerType('megengine.traced_module.serialization._ModuleState', class {});
  2212. this.registerType('megengine.traced_module.traced_module.InternalGraph', class {});
  2213. this.registerType('megengine.traced_module.traced_module.NameSpace', class {});
  2214. this.registerType('megengine.traced_module.traced_module.TracedModule', class {});
  2215. this.registerType('megengine.tensor.Parameter', class {
  2216. constructor(data, dtype, device) {
  2217. this.data = data;
  2218. this.dtype = dtype;
  2219. this.device = device;
  2220. }
  2221. });
  2222. this.registerType('megengine.traced_module.pytree.TreeDef', class {
  2223. toString() {
  2224. let content = '';
  2225. for (const child of this.children_defs) {
  2226. content += child.toString() + ",";
  2227. }
  2228. if (typeof this.type === "string") {
  2229. return this.type.split(".").slice(-1) + '(' + content + ')';
  2230. }
  2231. return this.type.__name__ + '(' + content + ')';
  2232. }
  2233. });
  2234. this.registerType('megengine.traced_module.pytree.LeafDef', class {
  2235. toString() {
  2236. let content = '';
  2237. if (this.const_val !== null) {
  2238. content += this.const_val;
  2239. }
  2240. else {
  2241. content += '[';
  2242. }
  2243. for (var t of Object.values(this.type)) {
  2244. content += t.__name__;
  2245. }
  2246. content += ']';
  2247. return content;
  2248. }
  2249. });
  2250. this.registerType('megengine.tensor.Tensor', class {
  2251. constructor(data, dtype, device) {
  2252. this.data = data;
  2253. this.dtype = dtype;
  2254. this.device = device;
  2255. }
  2256. });
  2257. this.registerType('megengine.core.tensor.dtype.QuantDtypeMeta', class {
  2258. constructor(name, cname, np_dtype, qmin, qmax, is_signed) {
  2259. this.name = name;
  2260. this.cname = cname;
  2261. this.np_dtype = np_dtype;
  2262. this.qmin = qmin;
  2263. this.qmax = qmax;
  2264. this.is_signed = is_signed;
  2265. }
  2266. });
  2267. this.registerType('nolearn.lasagne.base.BatchIterator', class {});
  2268. this.registerType('nolearn.lasagne.base.Layers', class {});
  2269. this.registerType('nolearn.lasagne.base.NeuralNet', class {});
  2270. this.registerType('nolearn.lasagne.base.TrainSplit', class {});
  2271. this.registerType('nolearn.lasagne.handlers.PrintLayerInfo', class {});
  2272. this.registerType('nolearn.lasagne.handlers.PrintLog', class {});
  2273. this.registerType('numpy.ndarray', class {
  2274. constructor(shape, dtype, buffer, offset, strides, order) {
  2275. this.shape = shape;
  2276. this.dtype = dtype;
  2277. this.data = buffer !== undefined ? buffer : null;
  2278. this.offset = offset !== undefined ? offset : 0;
  2279. this.strides = strides !== undefined ? strides : null;
  2280. this.order = offset !== undefined ? order : null;
  2281. this.flags = {};
  2282. this._read();
  2283. }
  2284. __setstate__(state) {
  2285. this.version = state[0];
  2286. this.shape = state[1];
  2287. this.dtype = state[2];
  2288. this.flags.fnc = state[3];
  2289. this.data = state[4];
  2290. this._read();
  2291. }
  2292. tobytes() {
  2293. return this.data;
  2294. }
  2295. tolist() {
  2296. if (this.shape.length < 0 || this.shape.length > 1) {
  2297. throw new Error(JSON.stringify(this.shape));
  2298. }
  2299. const size = this.shape.reduce((a, b) => a * b, 1);
  2300. const list = new Array(size);
  2301. switch (this.dtype.kind) {
  2302. case 'U': {
  2303. const data = new Uint32Array(new Uint8Array(this.data).buffer);
  2304. const itemsize = this.dtype.itemsize >> 2;
  2305. let offset = 0;
  2306. for (let i = 0; i < size; i++) {
  2307. const buffer = data.subarray(offset, offset + itemsize);
  2308. const index = buffer.indexOf(0);
  2309. list[i] = Array.from(index >= 0 ? buffer.subarray(0, index) : buffer).map((c) => String.fromCodePoint(c)).join('');
  2310. offset += itemsize;
  2311. }
  2312. return list;
  2313. }
  2314. case 'S': {
  2315. const data = this.data;
  2316. const itemsize = this.dtype.itemsize;
  2317. const decoder = new TextDecoder('utf-8');
  2318. let offset = 0;
  2319. for (let i = 0; i < size; i++) {
  2320. const buffer = data.subarray(offset, offset + itemsize);
  2321. const index = buffer.indexOf(0);
  2322. list[i] = decoder.decode(index >= 0 ? buffer.subarray(0, index) : buffer);
  2323. offset += itemsize;
  2324. }
  2325. return list;
  2326. }
  2327. case 'O': {
  2328. return this.data;
  2329. }
  2330. default: {
  2331. throw new python.Error("Type kind '" + this.dtype.kind + "' not implemented.");
  2332. }
  2333. }
  2334. }
  2335. get size() {
  2336. return (this.shape || []).reduce((a, b) => a * b, 1);
  2337. }
  2338. _read() {
  2339. if (this.data) {
  2340. const length = this.dtype.itemsize * this.size;
  2341. if (typeof this.data == 'string') {
  2342. this.data = this._unescape(this.data, length);
  2343. if (this.data.length != length) {
  2344. throw new python.Error('Invalid string array data size.');
  2345. }
  2346. }
  2347. else if (this.data.length != length) {
  2348. // throw new python.Error('Invalid array data size.');
  2349. }
  2350. }
  2351. }
  2352. _unescape(token, size) {
  2353. const length = token.length;
  2354. const a = new Uint8Array(length);
  2355. if (size && size == length) {
  2356. for (let p = 0; p < size; p++) {
  2357. a[p] = token.charCodeAt(p);
  2358. }
  2359. return a;
  2360. }
  2361. let i = 0;
  2362. let o = 0;
  2363. while (i < length) {
  2364. let c = token.charCodeAt(i++);
  2365. if (c !== 0x5C || i >= length) {
  2366. a[o++] = c;
  2367. }
  2368. else {
  2369. c = token.charCodeAt(i++);
  2370. switch (c) {
  2371. case 0x27: a[o++] = 0x27; break; // '
  2372. case 0x5C: a[o++] = 0x5C; break; // \\
  2373. case 0x22: a[o++] = 0x22; break; // "
  2374. case 0x72: a[o++] = 0x0D; break; // \r
  2375. case 0x6E: a[o++] = 0x0A; break; // \n
  2376. case 0x74: a[o++] = 0x09; break; // \t
  2377. case 0x62: a[o++] = 0x08; break; // \b
  2378. case 0x58: // x
  2379. case 0x78: { // X
  2380. const xsi = i - 1;
  2381. const xso = o;
  2382. for (let xi = 0; xi < 2; xi++) {
  2383. if (i >= length) {
  2384. i = xsi;
  2385. o = xso;
  2386. a[o] = 0x5c;
  2387. break;
  2388. }
  2389. let xd = token.charCodeAt(i++);
  2390. xd = xd >= 65 && xd <= 70 ? xd - 55 : xd >= 97 && xd <= 102 ? xd - 87 : xd >= 48 && xd <= 57 ? xd - 48 : -1;
  2391. if (xd === -1) {
  2392. i = xsi;
  2393. o = xso;
  2394. a[o] = 0x5c;
  2395. break;
  2396. }
  2397. a[o] = a[o] << 4 | xd;
  2398. }
  2399. o++;
  2400. break;
  2401. }
  2402. default:
  2403. if (c < 48 || c > 57) { // 0-9
  2404. a[o++] = 0x5c;
  2405. a[o++] = c;
  2406. }
  2407. else {
  2408. i--;
  2409. const osi = i;
  2410. const oso = o;
  2411. for (let oi = 0; oi < 3; oi++) {
  2412. if (i >= length) {
  2413. i = osi;
  2414. o = oso;
  2415. a[o] = 0x5c;
  2416. break;
  2417. }
  2418. const od = token.charCodeAt(i++);
  2419. if (od < 48 || od > 57) {
  2420. i = osi;
  2421. o = oso;
  2422. a[o] = 0x5c;
  2423. break;
  2424. }
  2425. a[o] = a[o] << 3 | od - 48;
  2426. }
  2427. o++;
  2428. }
  2429. break;
  2430. }
  2431. }
  2432. }
  2433. return a.slice(0, o);
  2434. }
  2435. });
  2436. this.registerType('numpy.ma.core.MaskedArray', class extends numpy.ndarray {
  2437. constructor(data /*, mask, dtype, copy, subok, ndmin, fill_value, keep_mask, hard_mask, shrink, order */) {
  2438. super(data.shape, data.dtype, data.data);
  2439. }
  2440. });
  2441. this.registerType('numpy.core.memmap.memmap', class extends numpy.ndarray {
  2442. constructor(shape, dtype) {
  2443. super(shape, dtype);
  2444. }
  2445. });
  2446. this.registerType('pathlib.Path', class {});
  2447. this.registerType('pathlib.PosixPath', class {});
  2448. this.registerType('pathlib.WindowsPath', class {});
  2449. this.registerType('sklearn.calibration._CalibratedClassifier', class {});
  2450. this.registerType('sklearn.calibration._SigmoidCalibration', class {});
  2451. this.registerType('sklearn.calibration.CalibratedClassifierCV', class {});
  2452. this.registerType('sklearn.compose._column_transformer.ColumnTransformer', class {});
  2453. this.registerType('sklearn.compose._target.TransformedTargetRegressor', class {});
  2454. this.registerType('sklearn.cluster._agglomerative.FeatureAgglomeration', class {});
  2455. this.registerType('sklearn.cluster._dbscan.DBSCAN', class {});
  2456. this.registerType('sklearn.cluster._kmeans.KMeans', class {});
  2457. this.registerType('sklearn.decomposition._fastica.FastICA', class {});
  2458. this.registerType('sklearn.decomposition._pca.PCA', class {});
  2459. this.registerType('sklearn.decomposition._truncated_svd.TruncatedSVD', class {});
  2460. this.registerType('sklearn.decomposition.PCA', class {});
  2461. this.registerType('sklearn.decomposition.pca.PCA', class {});
  2462. this.registerType('sklearn.decomposition.truncated_svd.TruncatedSVD', class {});
  2463. this.registerType('sklearn.discriminant_analysis.LinearDiscriminantAnalysis', class {});
  2464. this.registerType('sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis', class {});
  2465. this.registerType('sklearn.dummy.DummyClassifier', class {});
  2466. this.registerType('sklearn.dummy.DummyRegressor', class {});
  2467. this.registerType('sklearn.externals.joblib.numpy_pickle.NumpyArrayWrapper', class {
  2468. constructor(/* subtype, shape, dtype */) {
  2469. }
  2470. __setstate__(state) {
  2471. this.subclass = state.subclass;
  2472. this.dtype = state.dtype;
  2473. this.shape = state.shape;
  2474. this.order = state.order;
  2475. this.allow_mmap = state.allow_mmap;
  2476. }
  2477. __read__(unpickler) {
  2478. if (this.dtype.__name__ == 'object') {
  2479. return unpickler.load();
  2480. }
  2481. const size = this.dtype.itemsize * this.shape.reduce((a, b) => a * b, 1);
  2482. this.data = unpickler.read(size);
  2483. return execution.invoke(this.subclass, [ this.shape, this.dtype, this.data ]);
  2484. }
  2485. });
  2486. this.registerType('sklearn.externals.joblib.numpy_pickle.NDArrayWrapper', class {
  2487. constructor(/* subtype, shape, dtype */) {
  2488. }
  2489. __setstate__(state) {
  2490. this.subclass = state.subclass;
  2491. this.filename = state.state;
  2492. this.allow_mmap = state.allow_mmap;
  2493. }
  2494. __read__(/* unpickler */) {
  2495. return this; // return execution.invoke(this.subclass, [ this.shape, this.dtype, this.data ]);
  2496. }
  2497. });
  2498. this.registerType('sklearn.ensemble._bagging.BaggingClassifier', class {});
  2499. this.registerType('sklearn.ensemble._forest.RandomForestRegressor', class {});
  2500. this.registerType('sklearn.ensemble._forest.RandomForestClassifier', class {});
  2501. this.registerType('sklearn.ensemble._forest.ExtraTreesClassifier', class {});
  2502. this.registerType('sklearn.ensemble._gb_losses.BinomialDeviance', class {});
  2503. this.registerType('sklearn.ensemble._gb_losses.LeastSquaresError', class {});
  2504. this.registerType('sklearn.ensemble._gb_losses.MultinomialDeviance', class {});
  2505. this.registerType('sklearn.ensemble._gb.GradientBoostingClassifier', class {});
  2506. this.registerType('sklearn.ensemble._gb.GradientBoostingRegressor', class {});
  2507. this.registerType('sklearn.ensemble._hist_gradient_boosting.binning._BinMapper', class {});
  2508. this.registerType('sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingRegressor', class {});
  2509. this.registerType('sklearn.ensemble._hist_gradient_boosting.loss.LeastSquares', class {});
  2510. this.registerType('sklearn.ensemble._hist_gradient_boosting.predictor.TreePredictor', class {});
  2511. this.registerType('sklearn.ensemble._iforest.IsolationForest', class {});
  2512. this.registerType('sklearn.ensemble._stacking.StackingClassifier', class {});
  2513. this.registerType('sklearn.ensemble._voting.VotingClassifier', class {});
  2514. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostClassifier', class {});
  2515. this.registerType('sklearn.ensemble.forest.RandomForestClassifier', class {});
  2516. this.registerType('sklearn.ensemble.forest.RandomForestRegressor', class {});
  2517. this.registerType('sklearn.ensemble.forest.ExtraTreesClassifier', class {});
  2518. this.registerType('sklearn.ensemble.gradient_boosting.BinomialDeviance', class {});
  2519. this.registerType('sklearn.ensemble.gradient_boosting.GradientBoostingClassifier', class {});
  2520. this.registerType('sklearn.ensemble.gradient_boosting.LogOddsEstimator', class {});
  2521. this.registerType('sklearn.ensemble.gradient_boosting.MultinomialDeviance', class {});
  2522. this.registerType('sklearn.ensemble.gradient_boosting.PriorProbabilityEstimator', class {});
  2523. this.registerType('sklearn.ensemble.weight_boosting.AdaBoostClassifier', class {});
  2524. this.registerType('sklearn.feature_extraction._hashing.FeatureHasher', class {});
  2525. this.registerType('sklearn.feature_extraction.text.CountVectorizer', class {});
  2526. this.registerType('sklearn.feature_extraction.text.HashingVectorizer', class {});
  2527. this.registerType('sklearn.feature_extraction.text.TfidfTransformer', class {});
  2528. this.registerType('sklearn.feature_extraction.text.TfidfVectorizer', class {});
  2529. this.registerType('sklearn.feature_selection._from_model.SelectFromModel', class {});
  2530. this.registerType('sklearn.feature_selection._univariate_selection.GenericUnivariateSelect', class {});
  2531. this.registerType('sklearn.feature_selection._univariate_selection.SelectKBest', class {});
  2532. this.registerType('sklearn.feature_selection._univariate_selection.SelectPercentile', class {});
  2533. this.registerType('sklearn.feature_selection._variance_threshold.VarianceThreshold', class {});
  2534. this.registerType('sklearn.feature_selection.univariate_selection.SelectKBest', class {});
  2535. this.registerType('sklearn.feature_selection.variance_threshold.VarianceThreshold', class {});
  2536. this.registerType('sklearn.gaussian_process._gpr.GaussianProcessRegressor', class {});
  2537. this.registerType('sklearn.gaussian_process.gpc.GaussianProcessClassifier', class {});
  2538. this.registerType('sklearn.gaussian_process.kernels.ConstantKernel', class {});
  2539. this.registerType('sklearn.gaussian_process.kernels.DotProduct', class {});
  2540. this.registerType('sklearn.gaussian_process.kernels.Product', class {});
  2541. this.registerType('sklearn.gaussian_process.kernels.RBF', class {});
  2542. this.registerType('sklearn.gaussian_process.kernels.Sum', class {});
  2543. this.registerType('sklearn.gaussian_process.kernels.WhiteKernel', class {});
  2544. this.registerType('sklearn.grid_search._CVScoreTuple', class {});
  2545. this.registerType('sklearn.grid_search.GridSearchCV', class {});
  2546. this.registerType('sklearn.impute._base.SimpleImputer', class {});
  2547. this.registerType('sklearn.impute.SimpleImputer', class {});
  2548. this.registerType('sklearn.isotonic.IsotonicRegression', class {});
  2549. this.registerType('sklearn.linear_model._base.LinearRegression', class {});
  2550. this.registerType('sklearn.linear_model._bayes.BayesianRidge', class {});
  2551. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNetCV', class {});
  2552. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNet', class {});
  2553. this.registerType('sklearn.linear_model._logistic.LogisticRegression', class {});
  2554. this.registerType('sklearn.linear_model._ridge.Ridge', class {});
  2555. this.registerType('sklearn.linear_model._ridge.RidgeClassifier', class {});
  2556. this.registerType('sklearn.linear_model._sgd_fast.Hinge', class {});
  2557. this.registerType('sklearn.linear_model._sgd_fast.Log', class {});
  2558. this.registerType('sklearn.linear_model._sgd_fast.ModifiedHuber', class {});
  2559. this.registerType('sklearn.linear_model._sgd_fast.SquaredHinge', class {});
  2560. this.registerType('sklearn.linear_model._stochastic_gradient.SGDClassifier', class {});
  2561. this.registerType('sklearn.linear_model.base.LinearRegression', class {});
  2562. this.registerType('sklearn.linear_model.sgd_fast.Hinge', class {});
  2563. this.registerType('sklearn.linear_model.LogisticRegression', class {});
  2564. this.registerType('sklearn.linear_model.logistic.LogisticRegression', class {});
  2565. this.registerType('sklearn.linear_model.logistic.LogisticRegressionCV', class {});
  2566. this.registerType('sklearn.linear_model.LassoLars​', class {});
  2567. this.registerType('sklearn.linear_model.ridge.Ridge', class {});
  2568. this.registerType('sklearn.linear_model.sgd_fast.Log', class {});
  2569. this.registerType('sklearn.linear_model.stochastic_gradient.SGDClassifier', class {});
  2570. this.registerType('sklearn.metrics._classification.accuracy_score', class {});
  2571. this.registerType('sklearn.metrics._regression.mean_squared_error', class {});
  2572. this.registerType('sklearn.metrics._scorer._PredictScorer', class {});
  2573. this.registerType('sklearn.metrics.scorer._PredictScorer', class {});
  2574. this.registerType('sklearn.metrics._scorer._ThresholdScorer', class {});
  2575. this.registerType('sklearn.mixture._bayesian_mixture.BayesianGaussianMixture', class {});
  2576. this.registerType('sklearn.model_selection._search.GridSearchCV', class {});
  2577. this.registerType('sklearn.model_selection._search.RandomizedSearchCV', class {});
  2578. this.registerType('sklearn.model_selection._split.KFold', class {});
  2579. this.registerType('sklearn.model_selection._split.StratifiedKFold', class {});
  2580. this.registerType('sklearn.multiclass.OneVsRestClassifier', class {});
  2581. this.registerType('sklearn.multioutput.MultiOutputClassifier', class {});
  2582. this.registerType('sklearn.multioutput.MultiOutputRegressor', class {});
  2583. this.registerType('sklearn.naive_bayes.BernoulliNB', class {});
  2584. this.registerType('sklearn.naive_bayes.ComplementNB', class {});
  2585. this.registerType('sklearn.naive_bayes.GaussianNB', class {});
  2586. this.registerType('sklearn.naive_bayes.MultinomialNB', class {});
  2587. this.registerType('sklearn.neighbors._classification.KNeighborsClassifier', class {});
  2588. this.registerType('sklearn.neighbors._dist_metrics.newObj', class {});
  2589. this.registerType('sklearn.neighbors._dist_metrics.EuclideanDistance', class {});
  2590. this.registerType('sklearn.neighbors._kd_tree.KDTree', class {});
  2591. this.registerType('sklearn.neighbors._kd_tree.newObj', class {});
  2592. this.registerType('sklearn.neighbors._regression.KNeighborsRegressor', class {});
  2593. this.registerType('sklearn.neighbors.classification.KNeighborsClassifier', class {});
  2594. this.registerType('sklearn.neighbors.dist_metrics.newObj', class {});
  2595. this.registerType('sklearn.neighbors.dist_metrics.EuclideanDistance', class {});
  2596. this.registerType('sklearn.neighbors.kd_tree.newObj', class {});
  2597. this.registerType('sklearn.neighbors.kd_tree.KDTree', class {});
  2598. this.registerType('sklearn.neighbors.KNeighborsClassifier', class {});
  2599. this.registerType('sklearn.neighbors.KNeighborsRegressor', class {});
  2600. this.registerType('sklearn.neighbors.regression.KNeighborsRegressor', class {});
  2601. this.registerType('sklearn.neighbors.unsupervised.NearestNeighbors', class {});
  2602. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPClassifier', class {});
  2603. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPRegressor', class {});
  2604. this.registerType('sklearn.neural_network._stochastic_optimizers.AdamOptimizer', class {});
  2605. this.registerType('sklearn.neural_network._stochastic_optimizers.SGDOptimizer', class {});
  2606. this.registerType('sklearn.neural_network.rbm.BernoulliRBM', class {});
  2607. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPClassifier', class {});
  2608. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPRegressor', class {});
  2609. this.registerType('sklearn.neural_network.stochastic_gradient.SGDClassifier', class {});
  2610. this.registerType('sklearn.pipeline.Pipeline', class {});
  2611. this.registerType('sklearn.pipeline.FeatureUnion', class {});
  2612. this.registerType('sklearn.preprocessing._data.MinMaxScaler', class {});
  2613. this.registerType('sklearn.preprocessing._data.MaxAbsScaler', class {});
  2614. this.registerType('sklearn.preprocessing._data.Normalizer', class {});
  2615. this.registerType('sklearn.preprocessing._data.PolynomialFeatures', class {});
  2616. this.registerType('sklearn.preprocessing._data.PowerTransformer', class {});
  2617. this.registerType('sklearn.preprocessing._data.QuantileTransformer', class {});
  2618. this.registerType('sklearn.preprocessing._data.RobustScaler', class {});
  2619. this.registerType('sklearn.preprocessing._data.StandardScaler', class {});
  2620. this.registerType('sklearn.preprocessing._discretization.KBinsDiscretizer', class {});
  2621. this.registerType('sklearn.preprocessing._encoders.OneHotEncoder', class {});
  2622. this.registerType('sklearn.preprocessing._function_transformer.FunctionTransformer', class {});
  2623. this.registerType('sklearn.preprocessing._label.LabelBinarizer', class {});
  2624. this.registerType('sklearn.preprocessing._label.LabelEncoder', class {});
  2625. this.registerType('sklearn.preprocessing._label.MultiLabelBinarizer', class {});
  2626. this.registerType('sklearn.preprocessing._polynomial.PolynomialFeatures', class {});
  2627. this.registerType('sklearn.preprocessing.data.Binarizer', class {});
  2628. this.registerType('sklearn.preprocessing.data.MaxAbsScaler', class {});
  2629. this.registerType('sklearn.preprocessing.data.MinMaxScaler', class {});
  2630. this.registerType('sklearn.preprocessing.data.Normalizer', class {});
  2631. this.registerType('sklearn.preprocessing.data.OneHotEncoder', class {});
  2632. this.registerType('sklearn.preprocessing.data.PolynomialFeatures', class {});
  2633. this.registerType('sklearn.preprocessing.data.PowerTransformer', class {});
  2634. this.registerType('sklearn.preprocessing.data.RobustScaler', class {});
  2635. this.registerType('sklearn.preprocessing.data.QuantileTransformer', class {});
  2636. this.registerType('sklearn.preprocessing.data.StandardScaler', class {});
  2637. this.registerType('sklearn.preprocessing.imputation.Imputer', class {});
  2638. this.registerType('sklearn.preprocessing.label.LabelBinarizer', class {});
  2639. this.registerType('sklearn.preprocessing.label.LabelEncoder', class {});
  2640. this.registerType('sklearn.preprocessing.label.MultiLabelBinarizer', class {});
  2641. this.registerType('sklearn.svm._classes.LinearSVC', class {});
  2642. this.registerType('sklearn.svm._classes.NuSVC', class {});
  2643. this.registerType('sklearn.svm._classes.OneClassSVM', class {});
  2644. this.registerType('sklearn.svm._classes.SVC', class {});
  2645. this.registerType('sklearn.svm._classes.SVR', class {});
  2646. this.registerType('sklearn.svm.classes.LinearSVC', class {});
  2647. this.registerType('sklearn.svm.classes.OneClassSVM', class {});
  2648. this.registerType('sklearn.svm.classes.SVC', class {});
  2649. this.registerType('sklearn.svm.classes.SVR', class {});
  2650. this.registerType('sklearn.tree._classes.DecisionTreeClassifier', class {});
  2651. this.registerType('sklearn.tree._classes.DecisionTreeRegressor', class {});
  2652. this.registerType('sklearn.tree._classes.ExtraTreeClassifier', class {});
  2653. this.registerType('sklearn.tree._classes.ExtraTreeRegressor', class {});
  2654. this.registerType('sklearn.tree._tree.Tree', class {
  2655. constructor(n_features, n_classes, n_outputs) {
  2656. this.n_features = n_features;
  2657. this.n_classes = n_classes;
  2658. this.n_outputs = n_outputs;
  2659. }
  2660. __setstate__(state) {
  2661. this.max_depth = state.max_depth;
  2662. this.node_count = state.node_count;
  2663. this.nodes = state.nodes;
  2664. this.values = state.values;
  2665. }
  2666. });
  2667. this.registerType('sklearn.tree.tree.DecisionTreeClassifier', class {});
  2668. this.registerType('sklearn.tree.tree.DecisionTreeRegressor', class {});
  2669. this.registerType('sklearn.tree.tree.ExtraTreeClassifier', class {});
  2670. this.registerType('sklearn.utils._bunch.Bunch', class {});
  2671. this.registerType('sklearn.utils.deprecation.DeprecationDict', class {});
  2672. this.registerType('pickle.Unpickler', class {
  2673. constructor(data) {
  2674. this._reader = data instanceof Uint8Array ? new python.BinaryReader(data) : new python.StreamReader(data);
  2675. this.persistent_load = () => {
  2676. throw new python.Error('Unsupported persistent id.');
  2677. };
  2678. }
  2679. load() {
  2680. const reader = this._reader;
  2681. const marker = [];
  2682. let stack = [];
  2683. const memo = new Map();
  2684. while (reader.position < reader.length) {
  2685. const opcode = reader.byte();
  2686. // console.log((reader.position - 1).toString() + ' ' + Object.entries(OpCode).find((entry) => entry[1] === opcode)[0]);
  2687. // https://svn.python.org/projects/python/trunk/Lib/pickletools.py
  2688. // https://github.com/python/cpython/blob/master/Lib/pickle.py
  2689. switch (opcode) {
  2690. case 128: { // PROTO
  2691. const version = reader.byte();
  2692. if (version > 5) {
  2693. throw new python.Error("Unsupported protocol version '" + version + "'.");
  2694. }
  2695. break;
  2696. }
  2697. case 99: { // GLOBAL 'c'
  2698. const module = reader.line();
  2699. const name = reader.line();
  2700. stack.push(this.find_class(module, name));
  2701. break;
  2702. }
  2703. case 147: { // STACK_GLOBAL '\x93' (Protocol 4)
  2704. const name = stack.pop();
  2705. const module = stack.pop();
  2706. stack.push(this.find_class(module, name));
  2707. break;
  2708. }
  2709. case 111: { // OBJ 'o'
  2710. const args = stack;
  2711. const cls = args.pop();
  2712. stack = marker.pop();
  2713. const obj = this._instantiate(cls, args);
  2714. stack.push(obj);
  2715. break;
  2716. }
  2717. case 112 : { // PUT 'p'
  2718. const index = parseInt(reader.line(), 10);
  2719. memo.set(index, stack[stack.length - 1]);
  2720. break;
  2721. }
  2722. case 103: { // GET 'g'
  2723. const index = parseInt(reader.line(), 10);
  2724. stack.push(memo.get(index));
  2725. break;
  2726. }
  2727. case 48: // POP '0'
  2728. stack.pop();
  2729. break;
  2730. case 49: // POP_MARK '1'
  2731. stack = marker.pop();
  2732. break;
  2733. case 50: // DUP '2'
  2734. stack.push(stack[stack.length-1]);
  2735. break;
  2736. case 80: // PERSID 'P'
  2737. stack.push(this.persistent_load(reader.line()));
  2738. break;
  2739. case 81: // BINPERSID 'Q'
  2740. stack.push(this.persistent_load(stack.pop()));
  2741. break;
  2742. case 82: { // REDUCE 'R'
  2743. const args = stack.pop();
  2744. const func = stack.pop();
  2745. stack.push(this._reduce(func, args));
  2746. break;
  2747. }
  2748. case 129: { // NEWOBJ
  2749. const args = stack.pop();
  2750. const cls = stack.pop();
  2751. const obj = this._newobj(cls, args);
  2752. stack.push(obj);
  2753. break;
  2754. }
  2755. case 146: { // NEWOBJ_EX '\x92' (Protocol 4)
  2756. const kwargs = stack.pop();
  2757. const args = stack.pop();
  2758. const cls = stack.pop();
  2759. if (Object.entries(kwargs).length > 0) {
  2760. throw new python.Error("Unpickle 'NEWOBJ_EX' not implemented.");
  2761. }
  2762. const obj = this._newobj(cls, args);
  2763. stack.push(obj);
  2764. break;
  2765. }
  2766. case 104: // BINGET 'h'
  2767. stack.push(memo.get(reader.byte()));
  2768. break;
  2769. case 105: { // INST 'i'
  2770. const module = reader.line();
  2771. const name = reader.line();
  2772. const args = stack;
  2773. const cls = module + '.' + name;
  2774. stack = marker.pop();
  2775. // TODO
  2776. // cls = this.find_class(module, name)
  2777. const obj = this._instantiate(cls, args);
  2778. stack.push(obj);
  2779. break;
  2780. }
  2781. case 106: // LONG_BINGET 'j'
  2782. stack.push(memo.get(reader.uint32()));
  2783. break;
  2784. case 113: // BINPUT 'q'
  2785. memo.set(reader.byte(), stack[stack.length - 1]);
  2786. break;
  2787. case 114: // LONG_BINPUT 'r'
  2788. memo.set(reader.uint32(), stack[stack.length - 1]);
  2789. break;
  2790. case 74: // BININT 'J'
  2791. stack.push(reader.int32());
  2792. break;
  2793. case 75: // BININT1 'K'
  2794. stack.push(reader.byte());
  2795. break;
  2796. case 76: // LONG 'L'
  2797. stack.push(parseInt(reader.line(), 10));
  2798. break;
  2799. case 77: // BININT2 'M'
  2800. stack.push(reader.uint16());
  2801. break;
  2802. case 66: // BINBYTES 'B' (Protocol 3)
  2803. stack.push(reader.read(reader.int32()));
  2804. break;
  2805. case 67: // SHORT_BINBYTES 'C' (Protocol 3)
  2806. stack.push(reader.read(reader.byte()));
  2807. break;
  2808. case 142: // BINBYTES8 '\x8e' (Protocol 4)
  2809. stack.push(reader.read(reader.int64()));
  2810. break;
  2811. case 70: // FLOAT 'F'
  2812. stack.push(parseFloat(reader.line()));
  2813. break;
  2814. case 71: // BINFLOAT 'G'
  2815. stack.push(reader.float64());
  2816. break;
  2817. case 73: { // INT 'I'
  2818. const value = reader.line();
  2819. if (value == '01') {
  2820. stack.push(true);
  2821. }
  2822. else if (value == '00') {
  2823. stack.push(false);
  2824. }
  2825. else {
  2826. stack.push(parseInt(value, 10));
  2827. }
  2828. break;
  2829. }
  2830. case 93: // EMPTY_LIST ']'
  2831. stack.push([]);
  2832. break;
  2833. case 41: // EMPTY_TUPLE ')'
  2834. stack.push([]);
  2835. break;
  2836. case 143: // EMPTY_SET '\x8f' (Protocol 4)
  2837. stack.push([]);
  2838. break;
  2839. case 144: { // ADDITEMS '\x90' (Protocol 4)
  2840. const items = stack;
  2841. stack = marker.pop();
  2842. const obj = stack[stack.length - 1];
  2843. for (let i = 0; i < items.length; i++) {
  2844. obj.push(items[i]);
  2845. }
  2846. break;
  2847. }
  2848. case 145: { // FROZENSET '\x91' (Protocol 4)
  2849. const items = stack;
  2850. stack = marker.pop();
  2851. stack.push(items);
  2852. break;
  2853. }
  2854. case 100: { // DICT 'd'
  2855. const items = stack;
  2856. stack = marker.pop();
  2857. const dict = {};
  2858. for (let i = 0; i < items.length; i += 2) {
  2859. dict[items[i]] = items[i + 1];
  2860. }
  2861. stack.push(dict);
  2862. break;
  2863. }
  2864. case 108: { // LIST 'l'
  2865. const items = stack;
  2866. stack = marker.pop();
  2867. stack.push(items);
  2868. break;
  2869. }
  2870. case 116: { // TUPLE 't'
  2871. const items = stack;
  2872. stack = marker.pop();
  2873. stack.push(items);
  2874. break;
  2875. }
  2876. case 133: { // TUPLE1 // '\x85'
  2877. stack.push([ stack.pop() ]);
  2878. break;
  2879. }
  2880. case 134: { // TUPLE2 '\x86'
  2881. const b = stack.pop();
  2882. const a = stack.pop();
  2883. stack.push([ a, b ]);
  2884. break;
  2885. }
  2886. case 135: { // TUPLE3 '\x87'
  2887. const c = stack.pop();
  2888. const b = stack.pop();
  2889. const a = stack.pop();
  2890. stack.push([ a, b, c ]);
  2891. break;
  2892. }
  2893. case 115: { // SETITEM 's'
  2894. const value = stack.pop();
  2895. const key = stack.pop();
  2896. const obj = stack[stack.length - 1];
  2897. if (obj.__setitem__) {
  2898. obj.__setitem__(key, value);
  2899. }
  2900. else {
  2901. obj[key] = value;
  2902. }
  2903. break;
  2904. }
  2905. case 117: { // SETITEMS 'u'
  2906. const items = stack;
  2907. stack = marker.pop();
  2908. const obj = stack[stack.length - 1];
  2909. for (let i = 0; i < items.length; i += 2) {
  2910. if (obj.__setitem__) {
  2911. obj.__setitem__(items[i], items[i + 1]);
  2912. }
  2913. else {
  2914. obj[items[i]] = items[i + 1];
  2915. }
  2916. }
  2917. break;
  2918. }
  2919. case 125: // EMPTY_DICT '}'
  2920. stack.push({});
  2921. break;
  2922. case 97: { // APPEND 'a'
  2923. const append = stack.pop();
  2924. stack[stack.length-1].push(append);
  2925. break;
  2926. }
  2927. case 101: { // APPENDS 'e'
  2928. const appends = stack;
  2929. stack = marker.pop();
  2930. const list = stack[stack.length - 1];
  2931. list.push.apply(list, appends);
  2932. break;
  2933. }
  2934. case 83: { // STRING 'S'
  2935. const str = reader.line();
  2936. stack.push(str.substr(1, str.length - 2));
  2937. break;
  2938. }
  2939. case 84: // BINSTRING 'T'
  2940. stack.push(reader.string(reader.uint32()));
  2941. break;
  2942. case 85 : // SHORT_BINSTRING 'U'
  2943. stack.push(reader.string(reader.byte()));
  2944. break;
  2945. case 86: // UNICODE 'V'
  2946. stack.push(reader.line());
  2947. break;
  2948. case 88: // BINUNICODE 'X
  2949. stack.push(reader.string(reader.uint32(), 'utf-8'));
  2950. break;
  2951. case 140: // SHORT_BINUNICODE '\x8c' (Protocol 4)
  2952. stack.push(reader.string(reader.byte(), 'utf-8'));
  2953. break;
  2954. case 98: { // BUILD 'b'
  2955. const state = stack.pop();
  2956. let obj = stack.pop();
  2957. if (obj.__setstate__) {
  2958. if (obj.__setstate__.__call__) {
  2959. obj.__setstate__.__call__([ obj, state ]);
  2960. }
  2961. else {
  2962. obj.__setstate__(state);
  2963. }
  2964. }
  2965. else if (ArrayBuffer.isView(state) || Object(state) !== state) {
  2966. obj.__state__ = state;
  2967. }
  2968. else if (obj instanceof Map) {
  2969. for (const key in state) {
  2970. obj.set(key, state[key]);
  2971. }
  2972. }
  2973. else {
  2974. Object.assign(obj, state);
  2975. }
  2976. if (obj.__read__) {
  2977. obj = obj.__read__(this);
  2978. }
  2979. stack.push(obj);
  2980. break;
  2981. }
  2982. case 40: // MARK '('
  2983. marker.push(stack);
  2984. stack = [];
  2985. break;
  2986. case 136: // NEWTRUE '\x88'
  2987. stack.push(true);
  2988. break;
  2989. case 137: // NEWFALSE '\x89'
  2990. stack.push(false);
  2991. break;
  2992. case 138: { // LONG1 '\x8a'
  2993. const data = reader.read(reader.byte());
  2994. let number = 0;
  2995. switch (data.length) {
  2996. case 0: number = 0; break;
  2997. case 1: number = data[0]; break;
  2998. case 2: number = data[1] << 8 | data[0]; break;
  2999. case 3: number = data[2] << 16 | data[1] << 8 | data[0]; break;
  3000. case 4: number = data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]; break;
  3001. case 5: number = data[4] * 0x100000000 + ((data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]) >>> 0); break;
  3002. default: number = Array.prototype.slice.call(data, 0); break;
  3003. }
  3004. stack.push(number);
  3005. break;
  3006. }
  3007. case 139: // LONG4 '\x8b'
  3008. // TODO decode LONG4
  3009. stack.push(reader.read(reader.uint32()));
  3010. break;
  3011. case 148: // MEMOIZE '\x94' (Protocol 4)
  3012. memo.set(memo.size, stack[stack.length - 1]);
  3013. break;
  3014. case 149: // FRAME '\x95' (Protocol 4)
  3015. reader.read(8);
  3016. break;
  3017. case 150: { // BYTEARRAY8 '\x96' (Protocol 5)
  3018. stack.push(reader.read(reader.int64()));
  3019. break;
  3020. }
  3021. case 78: // NONE 'N'
  3022. stack.push(null);
  3023. break;
  3024. case 46: // STOP '.'
  3025. return stack.pop();
  3026. case 141: // BINUNICODE8 '\x8d' (Protocol 4)
  3027. case 151: // NEXT_BUFFER '\x97' (Protocol 5)
  3028. case 152: // READONLY_BUFFER '\x98' (Protocol 5)
  3029. default:
  3030. throw new python.Error('Unknown opcode ' + opcode + ' at position ' + (reader.position - 1).toString() + '.');
  3031. }
  3032. }
  3033. throw new python.Error('Unexpected end of file.');
  3034. }
  3035. find_class(module, name) {
  3036. execution.__import__(module);
  3037. return execution.resolve(module + '.' + name);
  3038. }
  3039. _instantiate(cls, args) {
  3040. return execution.invoke(cls, args);
  3041. }
  3042. _newobj(cls, args) {
  3043. // cls.__new__(cls, args)
  3044. return execution.invoke(cls, args);
  3045. }
  3046. _reduce(func, args) {
  3047. return execution.invoke(func, args);
  3048. }
  3049. read(size) {
  3050. return this._reader.read(size);
  3051. }
  3052. stream(size) {
  3053. return this._reader.stream(size);
  3054. }
  3055. });
  3056. this.registerType('random.Random', class {});
  3057. this.registerType('re.Pattern', class {
  3058. constructor(pattern, flags) {
  3059. this.pattern = pattern;
  3060. this.flags = flags;
  3061. }
  3062. });
  3063. this.registerType('spacy._ml.PrecomputableAffine', class {
  3064. __setstate__(state) {
  3065. Object.assign(this, new pickle.Unpickler(state).load());
  3066. }
  3067. });
  3068. this.registerType('spacy.syntax._parser_model.ParserModel', class {
  3069. __setstate__(state) {
  3070. Object.assign(this, new pickle.Unpickler(state).load());
  3071. }
  3072. });
  3073. this.registerType('theano.compile.function_module._constructor_Function', class {});
  3074. this.registerType('theano.compile.function_module._constructor_FunctionMaker', class {});
  3075. this.registerType('theano.compile.function_module.Function', class {});
  3076. this.registerType('theano.compile.function_module.Supervisor', class {});
  3077. this.registerType('theano.compile.io.In', class {});
  3078. this.registerType('theano.compile.io.SymbolicOutput', class {});
  3079. this.registerType('theano.compile.mode.Mode', class {});
  3080. this.registerType('theano.compile.ops.OutputGuard', class {});
  3081. this.registerType('theano.compile.ops.Shape', class {});
  3082. this.registerType('theano.compile.ops.Shape_i', class {});
  3083. this.registerType('theano.gof.destroyhandler.DestroyHandler', class {});
  3084. this.registerType('theano.gof.fg.FunctionGraph', class {});
  3085. this.registerType('theano.gof.graph.Apply', class {});
  3086. this.registerType('theano.gof.link.Container', class {});
  3087. this.registerType('theano.gof.opt._metadict', class {});
  3088. this.registerType('theano.gof.opt.ChangeTracker', class {});
  3089. this.registerType('theano.gof.opt.MergeFeature', class {});
  3090. this.registerType('theano.gof.optdb.Query', class {});
  3091. this.registerType('theano.gof.toolbox.PreserveVariableAttributes', class {});
  3092. this.registerType('theano.gof.toolbox.ReplaceValidate', class {});
  3093. this.registerType('theano.gof.utils.scratchpad', class {});
  3094. this.registerType('theano.misc.ordered_set.Link', class {});
  3095. this.registerType('theano.misc.ordered_set.OrderedSet', class {});
  3096. this.registerType('theano.sandbox.cuda.basic_ops.HostFromGpu', class {});
  3097. this.registerType('theano.sandbox.cuda.type.CudaNdarray_unpickler', class {});
  3098. this.registerType('theano.sandbox.cuda.type.CudaNdarrayType', class {});
  3099. this.registerType('theano.sandbox.cuda.var.CudaNdarraySharedVariable', class {});
  3100. this.registerType('theano.scalar.basic.Abs', class {});
  3101. this.registerType('theano.scalar.basic.Add', class {});
  3102. this.registerType('theano.scalar.basic.Cast', class {});
  3103. this.registerType('theano.scalar.basic.Composite', class {});
  3104. this.registerType('theano.scalar.basic.EQ', class {});
  3105. this.registerType('theano.scalar.basic.GE', class {});
  3106. this.registerType('theano.scalar.basic.Identity', class {});
  3107. this.registerType('theano.scalar.basic.IntDiv', class {});
  3108. this.registerType('theano.scalar.basic.Inv', class {});
  3109. this.registerType('theano.scalar.basic.LE', class {});
  3110. this.registerType('theano.scalar.basic.LT', class {});
  3111. this.registerType('theano.scalar.basic.Mul', class {});
  3112. this.registerType('theano.scalar.basic.Neg', class {});
  3113. this.registerType('theano.scalar.basic.Scalar', class {});
  3114. this.registerType('theano.scalar.basic.ScalarConstant', class {});
  3115. this.registerType('theano.scalar.basic.ScalarVariable', class {});
  3116. this.registerType('theano.scalar.basic.Second', class {});
  3117. this.registerType('theano.scalar.basic.Sgn', class {});
  3118. this.registerType('theano.scalar.basic.specific_out', class {});
  3119. this.registerType('theano.scalar.basic.Sub', class {});
  3120. this.registerType('theano.scalar.basic.Switch', class {});
  3121. this.registerType('theano.scalar.basic.Tanh', class {});
  3122. this.registerType('theano.scalar.basic.transfer_type', class {});
  3123. this.registerType('theano.scalar.basic.TrueDiv', class {});
  3124. this.registerType('theano.tensor.basic.Alloc', class {});
  3125. this.registerType('theano.tensor.basic.Dot', class {});
  3126. this.registerType('theano.tensor.basic.MaxAndArgmax', class {});
  3127. this.registerType('theano.tensor.basic.Reshape', class {});
  3128. this.registerType('theano.tensor.basic.ScalarFromTensor', class {});
  3129. this.registerType('theano.tensor.blas.Dot22', class {});
  3130. this.registerType('theano.tensor.blas.Dot22Scalar', class {});
  3131. this.registerType('theano.tensor.blas.Gemm', class {});
  3132. this.registerType('theano.tensor.elemwise.DimShuffle', class {});
  3133. this.registerType('theano.tensor.elemwise.Elemwise', class {});
  3134. this.registerType('theano.tensor.elemwise.Sum', class {});
  3135. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d', class {});
  3136. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradInputs', class {});
  3137. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradWeights', class {});
  3138. this.registerType('theano.tensor.nnet.corr.CorrMM', class {});
  3139. this.registerType('theano.tensor.nnet.corr.CorrMM_gradInputs', class {});
  3140. this.registerType('theano.tensor.nnet.corr.CorrMM_gradWeights', class {});
  3141. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1Hot', class {});
  3142. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1HotGrad', class {});
  3143. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmax1HotWithBiasDx', class {});
  3144. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmaxArgmax1HotWithBias', class {});
  3145. this.registerType('theano.tensor.nnet.nnet.Softmax', class {});
  3146. this.registerType('theano.tensor.nnet.nnet.SoftmaxGrad', class {});
  3147. this.registerType('theano.tensor.nnet.nnet.SoftmaxWithBias', class {});
  3148. this.registerType('theano.tensor.opt.MakeVector', class {});
  3149. this.registerType('theano.tensor.opt.ShapeFeature', class {});
  3150. this.registerType('theano.tensor.sharedvar.TensorSharedVariable', class {});
  3151. this.registerType('theano.tensor.signal.pool.MaxPoolGrad', class {});
  3152. this.registerType('theano.tensor.signal.pool.Pool', class {});
  3153. this.registerType('theano.tensor.subtensor.Subtensor', class {});
  3154. this.registerType('theano.tensor.type.TensorType', class {});
  3155. this.registerType('theano.tensor.var.TensorConstant', class {});
  3156. this.registerType('theano.tensor.var.TensorConstantSignature', class {});
  3157. this.registerType('theano.tensor.var.TensorVariable', class {});
  3158. this.registerType('thinc.describe.Biases', class {
  3159. __setstate__(state) {
  3160. Object.assign(this, state);
  3161. }
  3162. });
  3163. this.registerType('thinc.describe.Dimension', class {
  3164. __setstate__(state) {
  3165. Object.assign(this, state);
  3166. }
  3167. });
  3168. this.registerType('thinc.describe.Gradient', class {
  3169. __setstate__(state) {
  3170. Object.assign(this, state);
  3171. }
  3172. });
  3173. this.registerType('thinc.describe.Weights', class {
  3174. __setstate__(state) {
  3175. Object.assign(this, state);
  3176. }
  3177. });
  3178. this.registerType('thinc.describe.Synapses', class {
  3179. __setstate__(state) {
  3180. Object.assign(this, state);
  3181. }
  3182. });
  3183. this.registerType('thinc.neural._classes.affine.Affine', class {
  3184. __setstate__(state) {
  3185. Object.assign(this, new pickle.Unpickler(state).load());
  3186. }
  3187. });
  3188. this.registerType('thinc.neural._classes.convolution.ExtractWindow', class {
  3189. __setstate__(state) {
  3190. Object.assign(this, new pickle.Unpickler(state).load());
  3191. }
  3192. });
  3193. this.registerType('thinc.neural._classes.feature_extracter.FeatureExtracter', class {
  3194. __setstate__(state) {
  3195. Object.assign(this, new pickle.Unpickler(state).load());
  3196. }
  3197. });
  3198. this.registerType('thinc.neural._classes.feed_forward.FeedForward', class {
  3199. __setstate__(state) {
  3200. Object.assign(this, new pickle.Unpickler(state).load());
  3201. }
  3202. });
  3203. this.registerType('thinc.neural._classes.function_layer.FunctionLayer', class {
  3204. __setstate__(state) {
  3205. Object.assign(this, new pickle.Unpickler(state).load());
  3206. }
  3207. });
  3208. this.registerType('thinc.neural._classes.hash_embed.HashEmbed', class {
  3209. __setstate__(state) {
  3210. Object.assign(this, new pickle.Unpickler(state).load());
  3211. }
  3212. });
  3213. this.registerType('thinc.neural._classes.layernorm.LayerNorm', class {
  3214. __setstate__(state) {
  3215. Object.assign(this, new pickle.Unpickler(state).load());
  3216. }
  3217. });
  3218. this.registerType('thinc.neural._classes.maxout.Maxout', class {
  3219. __setstate__(state) {
  3220. Object.assign(this, new pickle.Unpickler(state).load());
  3221. }
  3222. });
  3223. this.registerType('thinc.neural._classes.resnet.Residual', class {
  3224. __setstate__(state) {
  3225. Object.assign(this, new pickle.Unpickler(state).load());
  3226. }
  3227. });
  3228. this.registerType('thinc.neural._classes.softmax.Softmax', class {
  3229. __setstate__(state) {
  3230. Object.assign(this, new pickle.Unpickler(state).load());
  3231. }
  3232. });
  3233. this.registerType('thinc.neural.mem.Memory', class {
  3234. });
  3235. this.registerType('thinc.neural.ops.NumpyOps', class {
  3236. });
  3237. this.registerType('__main__.BYOLState', class {
  3238. constructor(dict) {
  3239. Object.assign(this, dict);
  3240. }
  3241. });
  3242. this.registerType('types.CodeType', class {});
  3243. this.register('types').ObjectType = this._builtins.object;
  3244. this.register('types').ModuleType = this._builtins.module;
  3245. this.register('types').MethodType = this._builtins.method;
  3246. this.register('types').FunctionType = this._builtins.function;
  3247. this.registerType('xgboost.compat.XGBoostLabelEncoder', class {});
  3248. this.registerType('xgboost.core.Booster', class {});
  3249. this.registerType('xgboost.sklearn.XGBClassifier', class {});
  3250. this.registerType('xgboost.sklearn.XGBRegressor', class {});
  3251. this.registerFunction('_codecs.encode', function(obj, encoding) {
  3252. return execution.invoke('builtins.bytearray', [ obj, encoding ]);
  3253. });
  3254. this.registerFunction('builtins.bytearray', function(source, encoding /*, errors */) {
  3255. if (source) {
  3256. if (Array.isArray(source) || source instanceof Uint8Array) {
  3257. const target = new Uint8Array(source.length);
  3258. for (let i = 0; i < source.length; i++) {
  3259. target[i] = source[i];
  3260. }
  3261. return target;
  3262. }
  3263. if (encoding === 'latin-1' || encoding === 'latin1') {
  3264. const target = new Uint8Array(source.length);
  3265. const length = source.length;
  3266. for (let i = 0; i < length; i++) {
  3267. target[i] = source.charCodeAt(i);
  3268. }
  3269. return target;
  3270. }
  3271. throw new python.Error("Unsupported bytearray encoding '" + JSON.stringify(encoding) + "'.");
  3272. }
  3273. return [];
  3274. });
  3275. this.registerFunction('builtins.bytes', function(source, encoding /*, errors */) {
  3276. if (source) {
  3277. if (Array.isArray(source) || source instanceof Uint8Array) {
  3278. const target = new Uint8Array(source.length);
  3279. for (let i = 0; i < source.length; i++) {
  3280. target[i] = source[i];
  3281. }
  3282. return target;
  3283. }
  3284. if (encoding === 'latin-1') {
  3285. const array = new Uint8Array(source.length);
  3286. for (let i = 0; i < source.length; i++) {
  3287. array[i] = source.charCodeAt(i);
  3288. }
  3289. return array;
  3290. }
  3291. throw new python.Error("Unsupported bytes encoding '" + JSON.stringify(encoding) + "'.");
  3292. }
  3293. return [];
  3294. });
  3295. this.registerFunction('builtins.frozenset', function(iterable) {
  3296. return iterable ? iterable : [];
  3297. });
  3298. this.registerFunction('builtins.getattr', function(obj, name, defaultValue) {
  3299. if (Object.prototype.hasOwnProperty.call(obj, name)) {
  3300. return obj[name];
  3301. }
  3302. return defaultValue;
  3303. });
  3304. this.registerFunction('builtins.set', function(iterable) {
  3305. return iterable ? iterable : [];
  3306. });
  3307. this.registerFunction('builtins.slice', function(start, stop, step) {
  3308. return [ start, stop, step ];
  3309. });
  3310. this.registerFunction('cloudpickle.cloudpickle._builtin_type', function(name) {
  3311. return name;
  3312. });
  3313. this.registerFunction('collections.Counter', function(/* iterable */) {
  3314. return { __module__: 'collections', __name__: 'Counter' };
  3315. });
  3316. this.registerFunction('collections.defaultdict', function(/* default_factory */) {
  3317. return {};
  3318. });
  3319. this.registerFunction('copy_reg._reconstructor', function(cls, base, state) {
  3320. // copyreg._reconstructor in Python 3
  3321. if (base === '__builtin__.object' || base === self._builtins.object) {
  3322. return self.invoke(cls, []);
  3323. }
  3324. else if (base === '__builtin__.tuple' || base === self._builtins.tuple) {
  3325. const obj = self.invoke(cls, []);
  3326. for (let i = 0; i < state.length; i++) {
  3327. obj[i] = state[i];
  3328. }
  3329. return obj;
  3330. }
  3331. throw new python.Error("Unsupported copy_reg._reconstructor base type '" + base + "'.");
  3332. });
  3333. this.registerFunction('copy.deepcopy', function(/* x */) {
  3334. throw new python.Error('Unsupported copy.deepcopy().');
  3335. });
  3336. this.registerFunction('dill._dill._create_cell', function(/* args */) {
  3337. return function() {
  3338. // TODO
  3339. };
  3340. });
  3341. this.registerFunction('dill._dill._create_code', function(args) {
  3342. return self.invoke('types.CodeType', [ args ]);
  3343. });
  3344. this.registerFunction('dill._dill._create_function', function(/* fcode, fglobals, fname, fdefaults, fclosure, fdict, fkwdefaults */) {
  3345. return function() {
  3346. // TODO
  3347. };
  3348. });
  3349. this.registerFunction('dill._dill._create_namedtuple', function(name, fieldnames, modulename /*, defaults */) {
  3350. const obj = execution.invoke('dill._dill._import_module', [ modulename + '.' + name ]);
  3351. if (obj) {
  3352. return obj;
  3353. }
  3354. return undefined;
  3355. });
  3356. this.registerFunction('dill._dill._get_attr', function(self, name) {
  3357. if (Object.prototype.hasOwnProperty.call(self, name)) {
  3358. return self[name];
  3359. }
  3360. return undefined;
  3361. });
  3362. this.registerFunction('dill._dill._import_module', function(import_name, safe) {
  3363. try {
  3364. if (import_name.startsWith('__runtime__.')) {
  3365. return execution.module(import_name);
  3366. }
  3367. else if (import_name.indexOf('.') === -1) {
  3368. return execution.__import__(import_name);
  3369. }
  3370. return execution.resolve(import_name);
  3371. }
  3372. catch (err) {
  3373. if (safe) {
  3374. return null;
  3375. }
  3376. throw err;
  3377. }
  3378. });
  3379. this.registerFunction('dill._dill._load_type', function(name) {
  3380. return self.resolve('types.' + name);
  3381. });
  3382. this.registerFunction('lasagne.nonlinearities.rectify', function() {
  3383. throw new python.Error('Function not implemented.');
  3384. });
  3385. this.registerFunction('lasagne.nonlinearities.softmax', function() {
  3386. throw new python.Error('Function not implemented.');
  3387. });
  3388. this.registerFunction('lasagne.objectives.categorical_crossentropy', function() {
  3389. throw new python.Error('Function not implemented.');
  3390. });
  3391. this.registerFunction('lasagne.updates.nesterov_momentum', function() {
  3392. throw new python.Error('Function not implemented.');
  3393. });
  3394. this.registerFunction('msgpack.unpackb', function(packed, ext_hook) {
  3395. const BinaryReader = class {
  3396. constructor(buffer, ext_hook) {
  3397. // https://github.com/msgpack/msgpack-javascript/blob/master/src/Decoder.ts
  3398. // https://github.com/msgpack/msgpack-python/blob/main/msgpack/_unpacker.pyx
  3399. this._buffer = buffer;
  3400. this._position = 0;
  3401. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  3402. this._ext_hook = ext_hook;
  3403. }
  3404. value() {
  3405. const c = this._view.getUint8(this.skip(1));
  3406. if (c >= 0xe0) {
  3407. return c - 0x100;
  3408. }
  3409. if (c < 0xC0) {
  3410. if (c < 0x80) {
  3411. return c;
  3412. }
  3413. if (c < 0x90) {
  3414. return this.map(c - 0x80);
  3415. }
  3416. if (c < 0xa0) {
  3417. return this.array(c - 0x90);
  3418. }
  3419. return this.string(c - 0xa0);
  3420. }
  3421. switch (c) {
  3422. case 0xC0: return null;
  3423. case 0xC2: return false;
  3424. case 0xC3: return true;
  3425. case 0xC4: return this.read(this._view.getUint8(this.skip(1)));
  3426. case 0xC5: return this.read(this._view.getUint16(this.skip(2)));
  3427. case 0xC6: return this.read(this._view.getUint32(this.skip(4)));
  3428. case 0xC7: return this.extension(this._view.getUint8(this.skip(1)));
  3429. case 0xC8: return this.extension(this._view.getUint16(this.skip(2)));
  3430. case 0xC9: return this.extension(this._view.getUint32(this.skip(4)));
  3431. case 0xCA: return this._view.getFloat32(this.skip(4));
  3432. case 0xCB: return this._view.getFloat64(this.skip(8));
  3433. case 0xCC: return this._view.getUint8(this.skip(1));
  3434. case 0xCD: return this._view.getUint16(this.skip(2));
  3435. case 0xCE: return this._view.getUint32(this.skip(4));
  3436. case 0xCF: return this._view.getUint64(this.skip(8));
  3437. case 0xD0: return this._view.getInt8(this.skip(1));
  3438. case 0xD1: return this._view.getInt16(this.skip(2));
  3439. case 0xD2: return this._view.getInt32(this.skip(4));
  3440. case 0xD3: return this._view.getInt64(this.skip(8));
  3441. case 0xD4: return this.extension(1);
  3442. case 0xD5: return this.extension(2);
  3443. case 0xD6: return this.extension(4);
  3444. case 0xD7: return this.extension(8);
  3445. case 0xD8: return this.extension(16);
  3446. case 0xD9: return this.string(this._view.getUint8(this.skip(1)));
  3447. case 0xDA: return this.string(this._view.getUint16(this.skip(2)));
  3448. case 0xDB: return this.string(this._view.getUint32(this.skip(4)));
  3449. case 0xDC: return this.array(this._view.getUint16(this.skip(2)));
  3450. case 0xDD: return this.array(this._view.getUint32(this.skip(4)));
  3451. case 0xDE: return this.map(this._view.getUint16(this.skip(2)));
  3452. case 0xDF: return this.map(this._view.getUint32(this.skip(4)));
  3453. default: throw new python.Error("Invalid code '" + c + "'.");
  3454. }
  3455. }
  3456. map(size) {
  3457. const map = {};
  3458. for (let i = 0; i < size; i++) {
  3459. const key = this.value();
  3460. const value = this.value();
  3461. map[key] = value;
  3462. }
  3463. return map;
  3464. }
  3465. array(size) {
  3466. const array = new Array(size);
  3467. for (let i = 0; i < size; i++) {
  3468. array[i] = this.value();
  3469. }
  3470. return array;
  3471. }
  3472. extension(size) {
  3473. const code = this._view.getUint8(this.skip(1));
  3474. const data = this.read(size);
  3475. return this._ext_hook(code, data);
  3476. }
  3477. skip(offset) {
  3478. const position = this._position;
  3479. this._position += offset;
  3480. if (this._position > this._buffer.length) {
  3481. throw new python.Error('Expected ' + (this._position - this._buffer.length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  3482. }
  3483. return position;
  3484. }
  3485. read(size) {
  3486. const data = this._buffer.subarray(this._position, this._position + size);
  3487. this._position += size;
  3488. return data;
  3489. }
  3490. string(size) {
  3491. const buffer = this.read(size);
  3492. this._decoder = this._decoder || new TextDecoder('utf8');
  3493. return this._decoder.decode(buffer);
  3494. }
  3495. };
  3496. return new BinaryReader(packed, ext_hook).value();
  3497. });
  3498. this.registerFunction('nolearn.lasagne.base.objective', function() {
  3499. throw new python.Error('Function not implemented.');
  3500. });
  3501. this.registerFunction('numpy._reconstruct', function(subtype, shape, dtype) {
  3502. return self.invoke(subtype, [ shape, dtype ]);
  3503. });
  3504. this.registerFunction('numpy.core._multiarray_umath._reconstruct', function(subtype, shape, dtype) {
  3505. return self.invoke(subtype, [ shape, dtype ]);
  3506. });
  3507. this.registerFunction('numpy.core.multiarray._reconstruct', function(subtype, shape, dtype) {
  3508. return self.invoke(subtype, [ shape, dtype ]);
  3509. });
  3510. this.registerFunction('numpy.core.multiarray.scalar', function(dtype, rawData) {
  3511. let data = rawData;
  3512. if (typeof rawData === 'string' || rawData instanceof String) {
  3513. data = new Uint8Array(rawData.length);
  3514. for (let i = 0; i < rawData.length; i++) {
  3515. data[i] = rawData.charCodeAt(i);
  3516. }
  3517. }
  3518. switch (dtype.kind) {
  3519. case 'b': {
  3520. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3521. switch (dtype.itemsize) {
  3522. case 1: return view.getInt8(0) ? true : false;
  3523. default: throw new python.Error("Unsupported scalar dtype boolean itemsize '" + dtype.itemsize + "'.");
  3524. }
  3525. }
  3526. case 'f': {
  3527. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3528. switch (dtype.itemsize) {
  3529. case 4: return view.getFloat32(0, dtype.byteorder === '<');
  3530. case 8: return view.getFloat64(0, dtype.byteorder === '<');
  3531. default: throw new python.Error("Unsupported scalar dtype float itemsize '" + dtype.itemsize + "'.");
  3532. }
  3533. }
  3534. case 'i': {
  3535. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3536. switch (dtype.itemsize) {
  3537. case 1: return view.getInt8(0);
  3538. case 2: return view.getInt16(0, dtype.byteorder === '<');
  3539. case 4: return view.getInt32(0, dtype.byteorder === '<');
  3540. case 8: return view.getInt64(0, dtype.byteorder === '<');
  3541. default: throw new python.Error("Unsupported scalar dtype int itemsize '" + dtype.itemsize + "'.");
  3542. }
  3543. }
  3544. case 'u': {
  3545. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3546. switch (dtype.itemsize) {
  3547. case 1: return view.getUint8(0);
  3548. case 2: return view.getUint16(0, dtype.byteorder === '<');
  3549. case 4: return view.getUint32(0, dtype.byteorder === '<');
  3550. case 8: return view.getUint64(0, dtype.byteorder === '<');
  3551. default: throw new python.Error("Unsupported scalar dtype uint itemsize '" + dtype.itemsize + "'.");
  3552. }
  3553. }
  3554. case 'U': {
  3555. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3556. const list = [];
  3557. for (let i = 0; i < dtype.itemsize; i += 4) {
  3558. list.push(String.fromCodePoint(view.getUint32(i, true)));
  3559. }
  3560. return list.join('');
  3561. }
  3562. default: {
  3563. throw new python.Error("Unsupported scalar dtype kind '" + dtype.kind + "'.");
  3564. }
  3565. }
  3566. });
  3567. this.registerFunction('numpy.core._multiarray_umath.scalar', function(dtype, rawData) {
  3568. let data = rawData;
  3569. if (typeof rawData === 'string') {
  3570. data = new Uint8Array(rawData.length);
  3571. for (let i = 0; i < rawData.length; i++) {
  3572. data[i] = rawData.charCodeAt(i);
  3573. }
  3574. }
  3575. const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3576. switch (dtype.__name__) {
  3577. case 'uint8':
  3578. return dataView.getUint8(0);
  3579. case 'float32':
  3580. return dataView.getFloat32(0, true);
  3581. case 'float64':
  3582. return dataView.getFloat64(0, true);
  3583. case 'int8':
  3584. return dataView.getInt8(0, true);
  3585. case 'int16':
  3586. return dataView.getInt16(0, true);
  3587. case 'int32':
  3588. return dataView.getInt32(0, true);
  3589. case 'int64':
  3590. return dataView.getInt64(0, true);
  3591. default:
  3592. throw new python.Error("Unsupported scalar type '" + dtype.__name__ + "'.");
  3593. }
  3594. });
  3595. this.registerFunction('numpy.load', function(file) {
  3596. // https://github.com/numpy/numpy/blob/main/numpy/lib/format.py
  3597. const signature = [ 0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59 ];
  3598. if (!file.read(6).every((v, i) => v == signature[i])) {
  3599. throw new python.Error('Invalid signature.');
  3600. }
  3601. const major = file.read(1)[0];
  3602. const minor = file.read(1)[0];
  3603. if (major > 3) {
  3604. throw new python.Error("Invalid version '" + [ major, minor ].join('.') + "'.");
  3605. }
  3606. const buffer = new Uint8Array([ 0, 0, 0, 0 ]);
  3607. buffer.set(file.read(major >= 2 ? 4 : 2), 0);
  3608. const header_length = buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0];
  3609. let header = file.read(header_length);
  3610. const decoder = new TextDecoder(major >= 3 ? 'utf-8' : 'ascii');
  3611. header = decoder.decode(header);
  3612. header = JSON.parse(header.replace(/\(/,'[').replace(/\)/,']').replace('[,','[1,]').replace(',]',',1]').replace(/'/g, '"').replace(/:\s*False\s*,/,':false,').replace(/:\s*True\s*,/,':true,').replace(/,\s*\}/, ' }'));
  3613. if (!header.descr || header.descr.length < 2) {
  3614. throw new python.Error("Missing property 'descr'.");
  3615. }
  3616. if (!header.shape) {
  3617. throw new python.Error("Missing property 'shape'.");
  3618. }
  3619. const shape = header.shape;
  3620. const dtype = self.invoke('numpy.dtype', [ header.descr.substring(1) ]);
  3621. dtype.byteorder = header.descr[0];
  3622. let data = null;
  3623. switch (dtype.byteorder) {
  3624. case '|': {
  3625. data = file.read();
  3626. if (dtype.kind === 'O') {
  3627. const unpickler = execution.invoke('pickle.Unpickler', [ data ]);
  3628. return unpickler.load();
  3629. }
  3630. break;
  3631. }
  3632. case '>':
  3633. case '<': {
  3634. if (header.descr.length !== 3) {
  3635. throw new python.Error("Unsupported data type '" + header.descr + "'.");
  3636. }
  3637. const count = shape.length === 0 ? 1 : shape.reduce((a, b) => a * b, 1);
  3638. data = file.read(dtype.itemsize * count);
  3639. break;
  3640. }
  3641. default: {
  3642. throw new python.Error("Unsupported data type '" + header.descr + "'.");
  3643. }
  3644. }
  3645. if (header.fortran_order) {
  3646. data = null;
  3647. }
  3648. return self.invoke('numpy.ndarray', [ shape, dtype, data ]);
  3649. });
  3650. this.registerFunction('numpy.save', function(file, arr) {
  3651. const descr = arr.dtype.str;
  3652. if (descr[0] !== '<' && descr[0] !== '>') {
  3653. throw new python.Error("Unsupported byte order '" + descr + "'.");
  3654. }
  3655. if (descr.length !== 3 || (descr[1] !== 'f' && descr[1] !== 'i' && descr[1] !== 'u' && descr[1] !== 'c' && descr.substring(1) !== 'b1')) {
  3656. throw new python.Error("Unsupported data type '" + descr + "'.");
  3657. }
  3658. let shape = '';
  3659. switch (arr.shape.length) {
  3660. case 0: shape = '()'; break;
  3661. case 1: shape = '(' + arr.shape[0].toString() + ',)'; break;
  3662. default: shape = '(' + arr.shape.map((dimension) => dimension.toString()).join(', ') + ')'; break;
  3663. }
  3664. const properties = [
  3665. "'descr': '" + descr + "'",
  3666. "'fortran_order': False",
  3667. "'shape': " + shape
  3668. ];
  3669. let header = '{ ' + properties.join(', ') + ' }';
  3670. header += ' '.repeat(64 - ((header.length + 2 + 8 + 1) & 0x3f)) + '\n';
  3671. const encoder = new TextEncoder('ascii');
  3672. file.write([ 0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59, 0x01, 0x00 ]); // '\\x93NUMPY' + version
  3673. file.write([ header.length & 0xff, (header.length >> 8) & 0xff ]);
  3674. file.write(encoder.encode(header));
  3675. file.write(arr.tobytes());
  3676. });
  3677. this.registerFunction('numpy.asarray', function(a, dtype) {
  3678. const encode = (context, data, dim) => {
  3679. const size = context.shape[dim];
  3680. const littleendian = context.littleendian;
  3681. if (dim == context.shape.length - 1) {
  3682. for (let i = 0; i < size; i++) {
  3683. switch (context.dtype) {
  3684. case 'f2':
  3685. context.view.setFloat16(context.position, data[i], littleendian);
  3686. break;
  3687. case 'f4':
  3688. context.view.setFloat32(context.position, data[i], littleendian);
  3689. break;
  3690. case 'f8':
  3691. context.view.setFloat64(context.position, data[i], littleendian);
  3692. break;
  3693. case 'i1':
  3694. context.view.setInt8(context.position, data[i], littleendian);
  3695. break;
  3696. case 'i2':
  3697. context.view.setInt16(context.position, data[i], littleendian);
  3698. break;
  3699. case 'i4':
  3700. context.view.setInt32(context.position, data[i], littleendian);
  3701. break;
  3702. case 'i8':
  3703. context.view.setInt64(context.position, data[i], littleendian);
  3704. break;
  3705. case 'u1':
  3706. context.view.setUint8(context.position, data[i], littleendian);
  3707. break;
  3708. case 'u2':
  3709. context.view.setUint16(context.position, data[i], littleendian);
  3710. break;
  3711. case 'u4':
  3712. context.view.setUint32(context.position, data[i], littleendian);
  3713. break;
  3714. case 'u8':
  3715. context.view.setUint64(context.position, data[i], littleendian);
  3716. break;
  3717. case 'c8':
  3718. context.view.setComplex64(context.position, data[i], littleendian);
  3719. break;
  3720. case 'c16':
  3721. context.view.setComplex128(context.position, data[i], littleendian);
  3722. break;
  3723. default:
  3724. throw new python.Error("Unsupported tensor data type '" + context.dtype + "'.");
  3725. }
  3726. context.position += context.itemsize;
  3727. }
  3728. }
  3729. else {
  3730. for (let j = 0; j < size; j++) {
  3731. encode(context, data[j], dim + 1);
  3732. }
  3733. }
  3734. };
  3735. const array_size = (value) => {
  3736. if (value.every((item) => Array.isArray(item))) {
  3737. const dims = value.map((item) => array_size(item));
  3738. const dim = dims[0];
  3739. for (let i = 1; i < dims.length; i++) {
  3740. if (dim.length === dims[i].length) {
  3741. if (!dims[i].every((value, i) => value ===dim[i])) {
  3742. throw new python.Error('Invalid array shape.');
  3743. }
  3744. }
  3745. }
  3746. return [ value.length ].concat(dim);
  3747. }
  3748. return [ value.length ];
  3749. };
  3750. const shape = Array.isArray(a) ? array_size(a) : [];
  3751. const size = dtype.itemsize * shape.reduce((a, b) => a * b, 1);
  3752. const context = {
  3753. position: 0,
  3754. itemsize: dtype.itemsize,
  3755. dtype: dtype.str.substring(1),
  3756. littleendian: dtype.str[0],
  3757. shape: shape,
  3758. data: new Uint8Array(size)
  3759. };
  3760. context.view = new DataView(context.data.buffer, context.data.byteOffset, size);
  3761. encode(context, a, 0);
  3762. return self.invoke('numpy.ndarray', [ shape, dtype, context.data ]);
  3763. });
  3764. this.registerFunction('numpy.ma.core._mareconstruct', function(subtype, baseclass, baseshape, basetype) {
  3765. const data = self.invoke(baseclass, [ baseshape, basetype ]);
  3766. // = ndarray.__new__(ndarray, baseshape, make_mask_descr(basetype))
  3767. const mask = self.invoke('numpy.ndarray', [ baseshape, '' ]);
  3768. return self.invoke(subtype, [ data, mask, basetype ]);
  3769. });
  3770. this.registerFunction('numpy.random.__RandomState_ctor', function() {
  3771. return {};
  3772. });
  3773. this.registerFunction('numpy.random._pickle.__randomstate_ctor', function() {
  3774. return {};
  3775. });
  3776. this.registerFunction('numpy.core.numeric._frombuffer', function(/* buf, dtype, shape, order */) {
  3777. return {};
  3778. });
  3779. this.registerFunction('sklearn.metrics.scorer._passthrough_scorer', function() {
  3780. throw new python.Error("Function not implemented.");
  3781. });
  3782. this.registerFunction('sklearn.feature_selection._univariate_selection.f_classif', function() {
  3783. throw new python.Error("Function not implemented.");
  3784. });
  3785. this.registerFunction('re._compile', function(pattern, flags) {
  3786. return self.invoke('re.Pattern', [ pattern, flags ]);
  3787. });
  3788. this.registerFunction('srsly.cloudpickle.cloudpickle._builtin_type', function(name) {
  3789. return function() {
  3790. return self.invoke('types.' + name, arguments);
  3791. };
  3792. });
  3793. this.registerFunction('theano.scalar.basic.same_out', function() {
  3794. throw new python.Error('Function not implemented.');
  3795. });
  3796. this.registerFunction('theano.scalar.basic.same_out_nocomplex', function() {
  3797. throw new python.Error('Function not implemented.');
  3798. });
  3799. this.registerFunction('theano.scalar.basic.upcast_out', function() {
  3800. throw new python.Error('Function not implemented.');
  3801. });
  3802. this.registerFunction('theano.scalar.basic.upgrade_to_float', function() {
  3803. throw new python.Error('Function not implemented.');
  3804. });
  3805. this.registerFunction('theano.tensor.nnet.conv2d', function() {
  3806. throw new python.Error('Function not implemented.');
  3807. });
  3808. this.registerFunction('theano.tensor.type.values_eq_approx_remove_inf_nan', function() {
  3809. throw new python.Error('Function not implemented.');
  3810. });
  3811. this.registerFunction('theano.tensor.type.values_eq_approx_remove_nan', function() {
  3812. throw new python.Error('Function not implemented.');
  3813. });
  3814. this.registerType('torch.nn.modules.module.Module', class {
  3815. constructor() {
  3816. this._modules = execution.invoke('collections.OrderedDict', []);
  3817. this._parameters = execution.invoke('collections.OrderedDict', []);
  3818. this._buffers = execution.invoke('collections.OrderedDict', []);
  3819. }
  3820. __setattr__(name, value) {
  3821. if (value instanceof torch.nn.modules.module.Module) {
  3822. this._modules.set(name, value);
  3823. }
  3824. else {
  3825. this[name] = value;
  3826. }
  3827. }
  3828. __getattr__(name) {
  3829. if (this._modules.has(name)) {
  3830. return this._modules.get(name);
  3831. }
  3832. return this[name];
  3833. }
  3834. });
  3835. torch.nn.Module = torch.nn.modules.module.Module;
  3836. torch.nn.modules.Module = torch.nn.modules.module.Module;
  3837. this.registerType('torch.ao.quantization.observer._PartialWrapper', class {});
  3838. this.registerType('torch.ao.quantization.observer.HistogramObserver', class {});
  3839. this.registerType('torch.ao.quantization.observer.MovingAverageMinMaxObserver', class {});
  3840. this.registerType('torch.ao.quantization.observer.PerChannelMinMaxObserver', class {});
  3841. this.registerType('torch.ao.quantization.qconfig.QConfig', class {});
  3842. this.registerType('torch.ao.quantization.stubs.DeQuantStub', class {});
  3843. this.registerType('torch.ao.quantization.stubs.QuantStub', class {});
  3844. this.registerType('torch.autograd.variable.Variable', class {});
  3845. this.registerType('torch.backends.cudnn.rnn.Unserializable', class {});
  3846. this.registerType('torch.distributions.bernoulli.Bernoulli', class {});
  3847. this.registerType('torch.distributions.constraints._LowerCholesky', class {});
  3848. this.registerType('torch.distributions.constraints._Real', class {});
  3849. this.registerType('torch.distributions.multivariate_normal.MultivariateNormal', class {});
  3850. this.registerType('torch.distributions.normal.Normal', class {});
  3851. this.registerType('torch.distributions.transforms.LowerCholeskyTransform', class {});
  3852. this.registerType('torch.distributions.uniform.Uniform', class {});
  3853. this.registerType('torch.nn.backends.thnn._get_thnn_function_backend', class {});
  3854. this.registerType('torch.nn.intrinsic.modules.fused.ConvBnReLU2d', class {});
  3855. this.registerType('torch.nn.intrinsic.modules.fused.ConvReLU2d', class {});
  3856. this.registerType('torch.nn.intrinsic.modules.fused.BNReLU2d', class {});
  3857. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBn2d', class {});
  3858. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  3859. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvReLU2d', class {});
  3860. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class {});
  3861. this.registerType('torch.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class {});
  3862. this.registerType('torch.nn.modules.activation.CELU', class extends torch.nn.Module {});
  3863. this.registerType('torch.nn.modules.activation.ELU', class extends torch.nn.Module {});
  3864. this.registerType('torch.nn.modules.activation.GELU', class extends torch.nn.Module {});
  3865. this.registerType('torch.nn.modules.activation.GLU', class extends torch.nn.Module {});
  3866. this.registerType('torch.nn.modules.activation.Hardtanh', class extends torch.nn.Module {});
  3867. this.registerType('torch.nn.modules.activation.Hardswish', class extends torch.nn.Module {});
  3868. this.registerType('torch.nn.modules.activation.Hardsigmoid', class extends torch.nn.Module {});
  3869. this.registerType('torch.nn.modules.activation.LeakyReLU', class extends torch.nn.Module {});
  3870. this.registerType('torch.nn.modules.activation.LogSigmoid', class extends torch.nn.Module {});
  3871. this.registerType('torch.nn.modules.activation.LogSoftmax', class extends torch.nn.Module {});
  3872. this.registerType('torch.nn.modules.activation.Mish', class extends torch.nn.Module {});
  3873. this.registerType('torch.nn.modules.activation.MultiheadAttention', class extends torch.nn.Module {});
  3874. this.registerType('torch.nn.modules.activation.ReLU', class extends torch.nn.Module {});
  3875. this.registerType('torch.nn.modules.activation.ReLU6', class extends torch.nn.Module {});
  3876. this.registerType('torch.nn.modules.activation.PReLU', class extends torch.nn.Module {});
  3877. this.registerType('torch.nn.modules.activation.RReLU', class extends torch.nn.Module {});
  3878. this.registerType('torch.nn.modules.activation.SELU', class extends torch.nn.Module {});
  3879. this.registerType('torch.nn.modules.activation.Sigmoid', class extends torch.nn.Module {});
  3880. this.registerType('torch.nn.modules.activation.SiLU', class extends torch.nn.Module {});
  3881. this.registerType('torch.nn.modules.activation.Softmax', class extends torch.nn.Module {});
  3882. this.registerType('torch.nn.modules.activation.Softmax2d', class extends torch.nn.Module {});
  3883. this.registerType('torch.nn.modules.activation.Softplus', class extends torch.nn.Module {});
  3884. this.registerType('torch.nn.modules.activation.Tanh', class extends torch.nn.Module {});
  3885. this.registerType('torch.nn.modules.activation.Tanhshrink', class extends torch.nn.Module {});
  3886. this.registerType('torch.nn.modules.activation.Threshold', class extends torch.nn.Module {});
  3887. this.registerType('torch.nn.modules.batchnorm._NormBase', class extends torch.nn.Module {});
  3888. this.registerType('torch.nn.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._NormBase {});
  3889. this.registerType('torch.nn.modules.batchnorm.BatchNorm1d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  3890. this.registerType('torch.nn.modules.batchnorm.BatchNorm2d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  3891. this.registerType('torch.nn.modules.batchnorm.BatchNorm3d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  3892. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm1d', class {});
  3893. this.registerType('torch.nn.modules.batchnorm.SyncBatchNorm', class {});
  3894. this.registerType('torch.nn.modules.container.ModuleDict', class extends torch.nn.Module {});
  3895. this.registerType('torch.nn.modules.container.ModuleList', class extends torch.nn.Module {});
  3896. this.registerType('torch.nn.modules.container.ParameterDict', class extends torch.nn.Module {});
  3897. this.registerType('torch.nn.modules.container.ParameterList', class extends torch.nn.Module {});
  3898. this.registerType('torch.nn.modules.container.Sequential', class extends torch.nn.Module {});
  3899. this.registerType('torch.nn.modules.conv._ConvNd', class extends torch.nn.Module {});
  3900. this.registerType('torch.nn.modules.conv.Conv1d', class extends torch.nn.modules.conv._ConvNd {});
  3901. this.registerType('torch.nn.modules.conv.Conv2d', class extends torch.nn.modules.conv._ConvNd {});
  3902. this.registerType('torch.nn.modules.conv.Conv3d', class extends torch.nn.modules.conv._ConvNd {});
  3903. this.registerType('torch.nn.modules.conv._ConvTransposeNd', class extends torch.nn.Module {});
  3904. this.registerType('torch.nn.modules.conv.ConvTranspose1d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  3905. this.registerType('torch.nn.modules.conv.ConvTranspose2d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  3906. this.registerType('torch.nn.modules.conv.ConvTranspose3d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  3907. this.registerType('torch.nn.modules.distance.CosineSimilarity', class {});
  3908. this.registerType('torch.nn.modules.dropout._DropoutNd', class extends torch.nn.Module {});
  3909. this.registerType('torch.nn.modules.dropout.AlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  3910. this.registerType('torch.nn.modules.dropout.Dropout', class extends torch.nn.modules.dropout._DropoutNd {});
  3911. this.registerType('torch.nn.modules.dropout.Dropout2d', class extends torch.nn.modules.dropout._DropoutNd {});
  3912. this.registerType('torch.nn.modules.dropout.Dropout3d', class extends torch.nn.modules.dropout._DropoutNd {});
  3913. this.registerType('torch.nn.modules.fold.Fold', class {});
  3914. this.registerType('torch.nn.modules.fold.Unfold', class {});
  3915. this.registerType('torch.nn.modules.flatten.Flatten', class extends torch.nn.Module {});
  3916. this.registerType('torch.nn.modules.flatten.Unflatten', class extends torch.nn.Module {});
  3917. this.registerType('torch.nn.modules.instancenorm.InstanceNorm1d', class {});
  3918. this.registerType('torch.nn.modules.instancenorm.InstanceNorm2d', class {});
  3919. this.registerType('torch.nn.modules.instancenorm.InstanceNorm3d', class {});
  3920. this.registerType('torch.nn.modules.linear._LinearWithBias', class {});
  3921. this.registerType('torch.nn.modules.linear.Bilinear', class extends torch.nn.Module {});
  3922. this.registerType('torch.nn.modules.linear.Identity', class extends torch.nn.Module {});
  3923. this.registerType('torch.nn.modules.linear.LazyLinear', class extends torch.nn.Module {});
  3924. this.registerType('torch.nn.modules.linear.Linear', class extends torch.nn.Module {});
  3925. this.registerType('torch.nn.modules.linear.NonDynamicallyQuantizableLinear', class extends torch.nn.modules.linear.Linear {});
  3926. this.registerType('torch.nn.modules.loss._Loss', class extends torch.nn.Module {});
  3927. this.registerType('torch.nn.modules.loss._WeightedLoss', class extends torch.nn.modules.loss._Loss {});
  3928. this.registerType('torch.nn.modules.loss.BCELoss', class extends torch.nn.modules.loss._Loss {});
  3929. this.registerType('torch.nn.modules.loss.BCEWithLogitsLoss', class extends torch.nn.modules.loss._Loss {});
  3930. this.registerType('torch.nn.modules.loss.CrossEntropyLoss', class extends torch.nn.modules.loss._Loss {});
  3931. this.registerType('torch.nn.modules.loss.CTCLoss', class extends torch.nn.modules.loss._Loss {});
  3932. this.registerType('torch.nn.modules.loss.KLDivLoss', class extends torch.nn.modules.loss._Loss {});
  3933. this.registerType('torch.nn.modules.loss.L1Loss', class extends torch.nn.modules.loss._Loss {});
  3934. this.registerType('torch.nn.modules.loss.MarginRankingLoss', class extends torch.nn.modules.loss._Loss {});
  3935. this.registerType('torch.nn.modules.loss.MSELoss', class extends torch.nn.modules.loss._Loss {});
  3936. this.registerType('torch.nn.modules.loss.NLLLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  3937. this.registerType('torch.nn.modules.loss.NLLLoss2d', class extends torch.nn.modules.loss.NLLLoss {});
  3938. this.registerType('torch.nn.modules.loss.SmoothL1Loss', class {});
  3939. this.registerType('torch.nn.modules.module._IncompatibleKeys', class {});
  3940. this.registerType('torch.nn.modules.module.PatchForward', class {});
  3941. this.registerType('torch.nn.modules.normalization.CrossMapLRN2d', class {});
  3942. this.registerType('torch.nn.modules.normalization.GroupNorm', class extends torch.nn.Module {});
  3943. this.registerType('torch.nn.modules.normalization.LayerNorm', class extends torch.nn.Module {});
  3944. this.registerType('torch.nn.modules.normalization.LocalResponseNorm', class {});
  3945. this.registerType('torch.nn.modules.padding._ReflectionPadNd', class extends torch.nn.Module {});
  3946. this.registerType('torch.nn.modules.padding.ReflectionPad1d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  3947. this.registerType('torch.nn.modules.padding.ReflectionPad2d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  3948. this.registerType('torch.nn.modules.padding.ReflectionPad3d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  3949. this.registerType('torch.nn.modules.padding._ReplicationPadNd', class extends torch.nn.Module {});
  3950. this.registerType('torch.nn.modules.padding.ReplicationPad1d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  3951. this.registerType('torch.nn.modules.padding.ReplicationPad2d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  3952. this.registerType('torch.nn.modules.padding.ReplicationPad3d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  3953. this.registerType('torch.nn.modules.padding.ZeroPad2d', class {});
  3954. this.registerType('torch.nn.modules.padding.ConstantPad1d', class {});
  3955. this.registerType('torch.nn.modules.padding.ConstantPad2d', class {});
  3956. this.registerType('torch.nn.modules.padding.ConstantPad3d', class {});
  3957. this.registerType('torch.nn.modules.pixelshuffle.PixelShuffle', class {});
  3958. this.registerType('torch.nn.modules.pixelshuffle.PixelUnshuffle', class {});
  3959. this.registerType('torch.nn.modules.pooling._AdaptiveAvgPoolNd', class extends torch.nn.Module {});
  3960. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool1d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  3961. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool2d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  3962. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool3d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  3963. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool1d', class {});
  3964. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool2d', class {});
  3965. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool3d', class {});
  3966. this.registerType('torch.nn.modules.pooling.AvgPool1d', class {});
  3967. this.registerType('torch.nn.modules.pooling.AvgPool2d', class {});
  3968. this.registerType('torch.nn.modules.pooling.AvgPool3d', class {});
  3969. this.registerType('torch.nn.modules.pooling.FractionalMaxPool2d', class {});
  3970. this.registerType('torch.nn.modules.pooling.LPPool2d', class {});
  3971. this.registerType('torch.nn.modules.pooling.MaxPool1d', class {});
  3972. this.registerType('torch.nn.modules.pooling.MaxPool2d', class {});
  3973. this.registerType('torch.nn.modules.pooling.MaxPool3d', class {});
  3974. this.registerType('torch.nn.modules.pooling.MaxUnpool1d', class {});
  3975. this.registerType('torch.nn.modules.pooling.MaxUnpool2d', class {});
  3976. this.registerType('torch.nn.modules.pooling.MaxUnpool3d', class {});
  3977. this.registerType('torch.nn.modules.rnn.GRU', class {});
  3978. this.registerType('torch.nn.modules.rnn.GRUCell', class {});
  3979. this.registerType('torch.nn.modules.rnn.LSTM', class {});
  3980. this.registerType('torch.nn.modules.rnn.LSTMCell', class {});
  3981. this.registerType('torch.nn.modules.rnn.RNN', class {});
  3982. this.registerType('torch.nn.modules.rnn.RNNCell', class {});
  3983. this.registerType('torch.nn.modules.sparse.Embedding', class {});
  3984. this.registerType('torch.nn.modules.sparse.EmbeddingBag', class {});
  3985. this.registerType('torch.nn.modules.transformer.Transformer', class {});
  3986. this.registerType('torch.nn.modules.transformer.TransformerDecoder', class {});
  3987. this.registerType('torch.nn.modules.transformer.TransformerDecoderLayer', class {});
  3988. this.registerType('torch.nn.modules.transformer.TransformerEncoder', class {});
  3989. this.registerType('torch.nn.modules.transformer.TransformerEncoderLayer', class {});
  3990. this.registerType('torch.nn.modules.upsampling.Upsample', class {});
  3991. this.registerType('torch.nn.modules.upsampling.UpsamplingBilinear2d', class {});
  3992. this.registerType('torch.nn.modules.upsampling.UpsamplingNearest2d', class {});
  3993. this.registerType('torch.nn.parallel.data_parallel.DataParallel', class {});
  3994. this.registerType('torch.nn.parallel.distributed._DDPUnevenInputsConfig', class {});
  3995. this.registerType('torch.nn.parallel.distributed.DistributedDataParallel', class {});
  3996. this.registerType('torch.nn.qat.modules.conv.Conv2d', class {});
  3997. this.registerType('torch.nn.qat.modules.linear.Linear', class {});
  3998. this.registerType('torch.nn.quantized.modules.activation.ReLU', class {});
  3999. this.registerType('torch.nn.quantized.modules.activation.LeakyReLU', class {});
  4000. this.registerType('torch.nn.quantized.dynamic.modules.linear.Linear', class {});
  4001. this.registerType('torch.nn.quantized.dynamic.modules.rnn.GRU', class {});
  4002. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTM', class {});
  4003. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTMCell', class {});
  4004. this.registerType('torch.nn.quantized.dynamic.modules.rnn.PackedParameter', class {});
  4005. this.registerType('torch.nn.quantized.modules.activation.ReLU6', class {});
  4006. this.registerType('torch.nn.quantized.modules.batchnorm.BatchNorm2d', class {});
  4007. this.registerType('torch.nn.quantized.modules.conv.Conv1d', class {});
  4008. this.registerType('torch.nn.quantized.modules.conv.Conv2d', class {});
  4009. this.registerType('torch.nn.quantized.modules.conv.ConvTranspose2d', class {});
  4010. this.registerType('torch.nn.quantized.modules.DeQuantize', class {});
  4011. this.registerType('torch.nn.quantized.modules.dropout.Dropout', class {});
  4012. this.registerType('torch.nn.quantized.modules.embedding_ops.Embedding', class {});
  4013. this.registerType('torch.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class {});
  4014. this.registerType('torch.nn.quantized.modules.functional_modules.FloatFunctional', class {});
  4015. this.registerType('torch.nn.quantized.modules.functional_modules.QFunctional', class {});
  4016. this.registerType('torch.nn.quantized.modules.linear.Linear', class {});
  4017. this.registerType('torch.nn.quantized.modules.linear.LinearPackedParams', class {});
  4018. this.registerType('torch.nn.quantized.modules.normalization.InstanceNorm2d', class {});
  4019. this.registerType('torch.nn.quantized.modules.normalization.LayerNorm', class {});
  4020. this.registerType('torch.nn.quantized.modules.Quantize', class {});
  4021. this.registerType('torch.nn.utils.prune.L1Unstructured', class {});
  4022. this.registerType('torch.nn.utils.spectral_norm.SpectralNorm', class {});
  4023. this.registerType('torch.nn.utils.spectral_norm.SpectralNormStateDictHook', class {});
  4024. this.registerType('torch.nn.utils.spectral_norm.SpectralNormLoadStateDictPreHook', class {});
  4025. this.registerType('torch.nn.utils.weight_norm.WeightNorm', class {});
  4026. this.registerType('torch.torch_version.TorchVersion', class extends String {});
  4027. this.registerType('torch.optim.adam.Adam', class {});
  4028. this.registerType('torch.optim.adamw.AdamW', class {});
  4029. this.registerType('torch.optim.adagrad.Adagrad', class {});
  4030. this.registerType('torch.optim.adadelta.Adadelta', class {});
  4031. this.registerType('torch.optim.lr_scheduler.CosineAnnealingLR', class {});
  4032. this.registerType('torch.optim.lr_scheduler.CyclicLR', class {});
  4033. this.registerType('torch.optim.lr_scheduler.ExponentialLR', class {});
  4034. this.registerType('torch.optim.lr_scheduler.LambdaLR', class {});
  4035. this.registerType('torch.optim.lr_scheduler.MultiStepLR', class {});
  4036. this.registerType('torch.optim.lr_scheduler.OneCycleLR', class {});
  4037. this.registerType('torch.optim.lr_scheduler.ReduceLROnPlateau', class {});
  4038. this.registerType('torch.optim.lr_scheduler.StepLR', class {});
  4039. this.registerType('torch.optim.optimizer._RequiredParameter', class {});
  4040. this.registerType('torch.optim.rmsprop.RMSprop', class {});
  4041. this.registerType('torch.optim.sgd.SGD', class {});
  4042. this.registerType('torch.optim.sparse_adam.SparseAdam', class {});
  4043. this.registerType('torch.quantization.fake_quantize.FakeQuantize', class {});
  4044. this.registerType('torch.quantization.observer._PartialWrapper', class {});
  4045. this.registerType('torch.quantization.observer.MinMaxObserver', class {});
  4046. this.registerType('torch.quantization.observer.MovingAverageMinMaxObserver', class {});
  4047. this.registerType('torch.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  4048. this.registerType('torch.quantization.qconfig.QConfig', class {});
  4049. this.registerType('torch.quantization.stubs.DeQuantStub', class {});
  4050. this.registerType('torch.quantization.stubs.QuantStub', class {});
  4051. this.registerType('torch.utils.data.dataloader._MultiProcessingDataLoaderIter', class {});
  4052. this.registerType('torch.utils.data.dataloader.DataLoader', class {});
  4053. this.registerType('torch.utils.data.dataset.Subset', class {});
  4054. this.registerType('torch.utils.data.dataset.ConcatDataset', class {});
  4055. this.registerType('torch.utils.data.dataset.TensorDataset', class {});
  4056. this.registerType('torch.utils.data.sampler.BatchSampler', class {});
  4057. this.registerType('torch.utils.data.sampler.RandomSampler', class {});
  4058. this.registerType('torch.utils.data.sampler.SequentialSampler', class {});
  4059. this.registerType('torchvision.datasets.folder.ImageFolder', class {});
  4060. this.registerType('torchvision.datasets.mnist.MNIST', class {});
  4061. this.registerType('torchvision.datasets.vision.StandardTransform', class {});
  4062. this.registerType('torchvision.models.alexnet.AlexNet', class {});
  4063. this.registerType('torchvision.models.densenet.DenseNet', class {});
  4064. this.registerType('torchvision.models.densenet._DenseBlock', class {});
  4065. this.registerType('torchvision.models.densenet._DenseLayer', class {});
  4066. this.registerType('torchvision.models.densenet._Transition', class {});
  4067. this.registerType('torchvision.models.detection._utils.BalancedPositiveNegativeSampler', class {});
  4068. this.registerType('torchvision.models.detection._utils.BoxCoder', class {});
  4069. this.registerType('torchvision.models.detection._utils.Matcher', class {});
  4070. this.registerType('torchvision.models.detection._utils.SSDMatcher', class {});
  4071. this.registerType('torchvision.models.detection.anchor_utils.AnchorGenerator', class {});
  4072. this.registerType('torchvision.models.detection.anchor_utils.DefaultBoxGenerator', class {});
  4073. this.registerType('torchvision.models.detection.backbone_utils.BackboneWithFPN', class {});
  4074. this.registerType('torchvision.models.detection.faster_rcnn.FasterRCNN', class {});
  4075. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNPredictor', class {});
  4076. this.registerType('torchvision.models.detection.faster_rcnn.TwoMLPHead', class {});
  4077. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNN', class {});
  4078. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNHeads', class {});
  4079. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNPredictor', class {});
  4080. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNN', class {});
  4081. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNHeads', class {});
  4082. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNPredictor', class {});
  4083. this.registerType('torchvision.models.detection.retinanet.RetinaNet', class {});
  4084. this.registerType('torchvision.models.detection.retinanet.RetinaNetClassificationHead', class {});
  4085. this.registerType('torchvision.models.detection.retinanet.RetinaNetHead', class {});
  4086. this.registerType('torchvision.models.detection.retinanet.RetinaNetRegressionHead', class {});
  4087. this.registerType('torchvision.models.detection.roi_heads.RoIHeads', class {});
  4088. this.registerType('torchvision.models.detection.rpn.AnchorGenerator', class {});
  4089. this.registerType('torchvision.models.detection.rpn.RegionProposalNetwork', class {});
  4090. this.registerType('torchvision.models.detection.rpn.RPNHead', class {});
  4091. this.registerType('torchvision.models.detection.ssd.SSD', class {});
  4092. this.registerType('torchvision.models.detection.ssdlite.SSDLiteClassificationHead', class {});
  4093. this.registerType('torchvision.models.detection.ssdlite.SSDLiteFeatureExtractorMobileNet', class {});
  4094. this.registerType('torchvision.models.detection.ssdlite.SSDLiteHead', class {});
  4095. this.registerType('torchvision.models.detection.ssdlite.SSDLiteRegressionHead', class {});
  4096. this.registerType('torchvision.models.detection.transform.GeneralizedRCNNTransform', class {});
  4097. this.registerType('torchvision.models.efficientnet.EfficientNet', class {});
  4098. this.registerType('torchvision.models.efficientnet.MBConv', class {});
  4099. this.registerType('torchvision.models.googlenet.BasicConv2d', class {});
  4100. this.registerType('torchvision.models.googlenet.GoogLeNet', class {});
  4101. this.registerType('torchvision.models.googlenet.Inception', class {});
  4102. this.registerType('torchvision.models.googlenet.InceptionAux', class {});
  4103. this.registerType('torchvision.models.inception.BasicConv2d', class {});
  4104. this.registerType('torchvision.models.inception.Inception3', class {});
  4105. this.registerType('torchvision.models.inception.InceptionAux', class {});
  4106. this.registerType('torchvision.models.inception.InceptionA', class {});
  4107. this.registerType('torchvision.models.inception.InceptionB', class {});
  4108. this.registerType('torchvision.models.inception.InceptionC', class {});
  4109. this.registerType('torchvision.models.inception.InceptionD', class {});
  4110. this.registerType('torchvision.models.inception.InceptionE', class {});
  4111. this.registerType('torchvision.models.mnasnet._InvertedResidual', class {});
  4112. this.registerType('torchvision.models.mnasnet.MNASNet', class {});
  4113. this.registerType('torchvision.models.mobilenet.ConvBNReLU', class {});
  4114. this.registerType('torchvision.models.mobilenet.MobileNetV2', class {});
  4115. this.registerType('torchvision.models.mobilenet.InvertedResidual', class {});
  4116. this.registerType('torchvision.models.mobilenetv2.ConvBNActivation', class {});
  4117. this.registerType('torchvision.models.mobilenetv2.InvertedResidual', class {});
  4118. this.registerType('torchvision.models.mobilenetv2.MobileNetV2', class {});
  4119. this.registerType('torchvision.models.mobilenetv3.InvertedResidual', class {});
  4120. this.registerType('torchvision.models.mobilenetv3.MobileNetV3', class {});
  4121. this.registerType('torchvision.models.mobilenetv3.SqueezeExcitation', class {});
  4122. this.registerType('torchvision.models.resnet.Bottleneck', class {});
  4123. this.registerType('torchvision.models.resnet.BasicBlock', class {});
  4124. this.registerType('torchvision.models.quantization.mobilenet.QuantizableInvertedResidual', class {});
  4125. this.registerType('torchvision.models.quantization.mobilenet.QuantizableMobileNetV2', class {});
  4126. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableInvertedResidual', class {});
  4127. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableMobileNetV2', class {});
  4128. this.registerType('torchvision.models.quantization.resnet.QuantizableBasicBlock', class {});
  4129. this.registerType('torchvision.models.quantization.resnet.QuantizableBottleneck', class {});
  4130. this.registerType('torchvision.models.quantization.resnet.QuantizableResNet', class {});
  4131. this.registerType('torchvision.models.segmentation.deeplabv3.ASPP', class {});
  4132. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPConv', class {});
  4133. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPPooling', class {});
  4134. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabHead', class {});
  4135. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabV3', class {});
  4136. this.registerType('torchvision.models.segmentation.fcn.FCN', class {});
  4137. this.registerType('torchvision.models.segmentation.fcn.FCNHead', class {});
  4138. this.registerType('torchvision.models.shufflenetv2.ShuffleNetV2', class {});
  4139. this.registerType('torchvision.models.shufflenetv2.InvertedResidual', class {});
  4140. this.registerType('torchvision.models.squeezenet.Fire', class {});
  4141. this.registerType('torchvision.models.squeezenet.SqueezeNet', class {});
  4142. this.registerType('torchvision.models.resnet.ResNet', class {});
  4143. this.registerType('torchvision.models.vgg.VGG', class {});
  4144. this.registerType('torchvision.models.video.resnet.BasicBlock', class {});
  4145. this.registerType('torchvision.models.video.resnet.BasicStem', class {});
  4146. this.registerType('torchvision.models.video.resnet.Conv2Plus1D', class {});
  4147. this.registerType('torchvision.models.video.resnet.Conv3DNoTemporal', class {});
  4148. this.registerType('torchvision.models.video.resnet.Conv3DSimple', class {});
  4149. this.registerType('torchvision.models.video.resnet.R2Plus1dStem', class {});
  4150. this.registerType('torchvision.models.video.resnet.VideoResNet', class {});
  4151. this.registerType('torchvision.models._utils.IntermediateLayerGetter', class {});
  4152. this.registerType('torchvision.ops.deform_conv.DeformConv2d', class {});
  4153. this.registerType('torchvision.ops.feature_pyramid_network.FeaturePyramidNetwork', class {});
  4154. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelMaxPool', class {});
  4155. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelP6P7', class {});
  4156. this.registerType('torchvision.ops.misc.Conv2dNormActivation', class {});
  4157. this.registerType('torchvision.ops.misc.ConvNormActivation', class {});
  4158. this.registerType('torchvision.ops.misc.ConvTranspose2d', class {});
  4159. this.registerType('torchvision.ops.misc.FrozenBatchNorm2d', class {});
  4160. this.registerType('torchvision.ops.misc.SqueezeExcitation', class {});
  4161. this.registerType('torchvision.ops.poolers.LevelMapper', class {});
  4162. this.registerType('torchvision.ops.poolers.MultiScaleRoIAlign', class {});
  4163. this.registerType('torchvision.ops.stochastic_depth.StochasticDepth', class {});
  4164. this.registerType('torchvision.transforms.functional.InterpolationMode', class {});
  4165. this.registerType('torchvision.transforms.transforms.Compose', class {});
  4166. this.registerType('torchvision.transforms.transforms.CenterCrop', class {});
  4167. this.registerType('torchvision.transforms.transforms.Grayscale', class {});
  4168. this.registerType('torchvision.transforms.transforms.Normalize', class {});
  4169. this.registerType('torchvision.transforms.transforms.RandomAffine', class {});
  4170. this.registerType('torchvision.transforms.transforms.RandomCrop', class {});
  4171. this.registerType('torchvision.transforms.transforms.RandomHorizontalFlip', class {});
  4172. this.registerType('torchvision.transforms.transforms.RandomRotation', class {});
  4173. this.registerType('torchvision.transforms.transforms.Resize', class {});
  4174. this.registerType('torchvision.transforms.transforms.Scale', class {});
  4175. this.registerType('torchvision.transforms.transforms.ToPILImage', class {});
  4176. this.registerType('torchvision.transforms.transforms.ToTensor', class {});
  4177. this.registerFunction('torchvision.models.resnet.resnet34', function() {});
  4178. this.registerFunction('builtins.annotate', function(type, value) {
  4179. if (type === self._builtins.int) {
  4180. return Number.isInteger(value) ? value : NaN;
  4181. }
  4182. if (type === self._builtins.float) {
  4183. return typeof value === 'number' ? value : NaN;
  4184. }
  4185. if (type === self._builtins.number) {
  4186. // if (pytorch.Utility.isTensor(value)) {
  4187. // value.resize_([]);
  4188. // }
  4189. }
  4190. return value;
  4191. });
  4192. this.registerFunction('builtins.unchecked_cast', function(type, value) {
  4193. return value;
  4194. });
  4195. this.registerFunction('builtins.uninitialized', function(/* type */) {
  4196. return undefined;
  4197. });
  4198. this.registerFunction('ops.prim.data', function(tensor) {
  4199. return tensor;
  4200. });
  4201. this.registerFunction('ops.prim.device', function(tensor) {
  4202. return tensor.device;
  4203. });
  4204. this.registerFunction('ops.prim.dtype', function(tensor) {
  4205. return tensor.dtype.scalar_type();
  4206. });
  4207. this.registerFunction('ops.prim.is_quantized', function(tensor) {
  4208. return tensor.is_quantized;
  4209. });
  4210. this.registerFunction('ops.prim.is_cuda', function(/* tensor */) {
  4211. return false;
  4212. });
  4213. this.registerFunction('ops.prim.is_nested', function(tensor) {
  4214. return tensor.is_nested;
  4215. });
  4216. this.registerFunction('ops.prim.is_sparse', function(tensor) {
  4217. return tensor.is_sparse;
  4218. });
  4219. this.registerFunction('ops.prim.unchecked_unwrap_optional', function(value) {
  4220. return value;
  4221. });
  4222. this.registerFunction('ops.prim.NumToTensor', function(value) {
  4223. const tensor = self.invoke('torch.Tensor', []);
  4224. tensor.value = value; // TODO
  4225. return tensor;
  4226. });
  4227. this.registerFunction('ops.prim.min', function(value) {
  4228. if (Array.isArray(value)) {
  4229. return Math.min.apply(null, value);
  4230. }
  4231. return Math.min.apply(null, arguments);
  4232. });
  4233. this.registerFunction('ops.prim.max', function(value) {
  4234. if (Array.isArray(value)) {
  4235. return Math.max.apply(null, value);
  4236. }
  4237. return Math.max.apply(null, arguments);
  4238. });
  4239. this.registerFunction('ops.prim.shape', function(tensor) {
  4240. return tensor && tensor.size ? tensor.size() : undefined;
  4241. });
  4242. this.registerFunction('ops.quantized.conv_prepack', function(weight, bias, stride, padding, dilation, groups) {
  4243. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  4244. params.weight = weight;
  4245. params.bias = bias;
  4246. params.stride = stride;
  4247. params.padding =padding;
  4248. params.dilation = dilation;
  4249. params.groups = groups;
  4250. return params;
  4251. });
  4252. this.registerFunction('ops.quantized.conv1d_prepack', function(weight, bias, stride, padding, dilation, groups) {
  4253. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  4254. params.weight = weight;
  4255. params.bias = bias;
  4256. params.stride = stride;
  4257. params.padding =padding;
  4258. params.dilation = dilation;
  4259. params.groups = groups;
  4260. return params;
  4261. });
  4262. this.registerFunction('ops.quantized.conv2d_prepack', function(weight, bias, stride, padding, dilation, groups) {
  4263. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  4264. params.weight = weight;
  4265. params.bias = bias;
  4266. params.stride = stride;
  4267. params.padding =padding;
  4268. params.dilation = dilation;
  4269. params.groups = groups;
  4270. return params;
  4271. });
  4272. this.registerFunction('ops.quantized.conv3d_prepack', function(weight, bias, stride, padding, dilation, groups) {
  4273. const params = self.invoke('__torch__.torch.classes.quantized.Conv3dPackedParamsBase', []);
  4274. params.weight = weight;
  4275. params.bias = bias;
  4276. params.stride = stride;
  4277. params.padding =padding;
  4278. params.dilation = dilation;
  4279. params.groups = groups;
  4280. return params;
  4281. });
  4282. this.registerFunction('ops.quantized.conv_transpose1d_prepack', function(weight, bias, stride, padding, output_padding, dilation, groups) {
  4283. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  4284. params.weight = weight;
  4285. params.bias = bias;
  4286. params.stride = stride;
  4287. params.padding =padding;
  4288. params.output_padding = output_padding;
  4289. params.dilation = dilation;
  4290. params.groups = groups;
  4291. return params;
  4292. });
  4293. this.registerFunction('ops.quantized.conv_transpose2d_prepack', function(weight, bias, stride, padding, output_padding, dilation, groups) {
  4294. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  4295. params.weight = weight;
  4296. params.bias = bias;
  4297. params.stride = stride;
  4298. params.padding =padding;
  4299. params.output_padding = output_padding;
  4300. params.dilation = dilation;
  4301. params.groups = groups;
  4302. return params;
  4303. });
  4304. this.registerFunction('ops.quantized.linear_prepack', function(weight, bias) {
  4305. const params = self.invoke('__torch__.torch.classes.quantized.LinearPackedParamsBase', []);
  4306. params.weight = weight;
  4307. params.bias = bias;
  4308. return params;
  4309. });
  4310. this.registerFunction('ops.prim.RaiseException', function(message) {
  4311. throw new python.Error(message);
  4312. });
  4313. this.registerFunction('builtins.range', function(start, stop, step) {
  4314. if (stop === undefined && step === undefined) {
  4315. if (Number.isInteger(start)) {
  4316. return Array(start).keys();
  4317. }
  4318. if (isNaN(start)) {
  4319. return [];
  4320. }
  4321. }
  4322. throw new python.Error('Unsupported range(' + JSON.stringify(start) + ', ' + JSON.stringify(stop) + ', ' + JSON.stringify(step) + ')');
  4323. });
  4324. this.registerFunction('torch._utils._rebuild_sparse_tensor', function(layout, data) {
  4325. if (layout === torch.sparse_coo) {
  4326. return self.invoke('torch._sparse_coo_tensor_unsafe', data);
  4327. }
  4328. throw new python.Error("Unsupported sparse tensor layout '" + (layout ? layout.__str__() : '') + "'.");
  4329. });
  4330. this.registerFunction('torch.from_numpy', function(obj) {
  4331. const dtypes = new Map([
  4332. [ '<f2', torch.float16 ],
  4333. [ '<f4', torch.float32 ],
  4334. [ '<f8', torch.float64 ],
  4335. [ '<i2', torch.int16 ],
  4336. [ '<i4', torch.int32 ],
  4337. [ '<i8', torch.int64 ],
  4338. ]);
  4339. if (!dtypes.has(obj.dtype.str)) {
  4340. throw new python.Error("Unsupported numpy.ndarray type '" + obj.dtype.str + "'.");
  4341. }
  4342. const dtype = dtypes.get(obj.dtype.str);
  4343. const storage = execution.invoke('torch.storage._TypedStorage', [ obj.size, dtype ]);
  4344. storage._set_cdata(obj.data);
  4345. const tensor = execution.invoke('torch.Tensor', []);
  4346. tensor.__setstate__([ storage, 0, obj.shape, null ]);
  4347. return tensor;
  4348. });
  4349. this.registerFunction('torch._utils._rebuild_device_tensor_from_numpy', function(data, dtype, device, requires_grad) {
  4350. const tensor = execution.invoke('torch.from_numpy', [ data ]);
  4351. // tensor = tensor.to(dtype, device)
  4352. tensor.requires_grad = requires_grad;
  4353. return tensor;
  4354. });
  4355. this.registerFunction('torch._sparse_coo_tensor_unsafe', function(indices, values, size) {
  4356. const tensor = self.invoke('torch.Tensor', []);
  4357. tensor._layout = torch.sparse_coo;
  4358. tensor._indices = indices;
  4359. tensor._values = values;
  4360. tensor._shape = size;
  4361. return tensor;
  4362. });
  4363. this.registerFunction('torch._utils._rebuild_tensor', function (storage, storage_offset, size, stride) {
  4364. if (Array.isArray(storage) && storage.length === 5 && storage[0] === 'storage') {
  4365. const storage_type = storage[1];
  4366. const size = storage[4];
  4367. storage = new storage_type(size);
  4368. }
  4369. const name = storage.__class__.__module__ + '.' + storage.__class__.__name__.replace('Storage', 'Tensor');
  4370. const tensor = self.invoke(name, []);
  4371. tensor.__setstate__([ storage, storage_offset, size, stride ]);
  4372. return tensor;
  4373. });
  4374. this.registerFunction('torch._utils._rebuild_tensor_v2', function (storage, storage_offset, size, stride, requires_grad, backward_hooks) {
  4375. const tensor = execution.invoke('torch._utils._rebuild_tensor', [ storage, storage_offset, size, stride ]);
  4376. tensor.requires_grad = requires_grad;
  4377. tensor.backward_hooks = backward_hooks;
  4378. return tensor;
  4379. });
  4380. this.registerFunction('torch._utils._rebuild_parameter', function(data, requires_grad, backward_hooks) {
  4381. const obj = self.invoke('torch.nn.parameter.Parameter', [ data, requires_grad ]);
  4382. obj.backward_hooks = backward_hooks;
  4383. return obj;
  4384. });
  4385. this.registerFunction('torch._utils._rebuild_qtensor', function(storage, storage_offset, size, stride, quantizer_params, requires_grad, backward_hooks) {
  4386. const tensor = execution.invoke('torch._utils._rebuild_tensor_v2', [ storage, storage_offset, size, stride, requires_grad, backward_hooks ]);
  4387. tensor.quantizer_params = quantizer_params;
  4388. return tensor;
  4389. });
  4390. this.registerFunction('torch._set_item', function(dict, key, value) {
  4391. dict[key] = value;
  4392. });
  4393. this.registerFunction('torch.__and__', function(left, right) {
  4394. return left && right;
  4395. });
  4396. this.registerFunction('torch.__contains__', function(dict, key) {
  4397. return dict[key] !== undefined;
  4398. });
  4399. this.registerFunction('torch.__derive_index', function(index, start, step) {
  4400. return start + index * step;
  4401. });
  4402. this.registerFunction('torch.__is__', function(left, right) {
  4403. if (left === null && right === null) {
  4404. return true;
  4405. }
  4406. if ((left !== null && right === null) || (left === null && right !== null)) {
  4407. return false;
  4408. }
  4409. throw new python.Error("Unsupported 'torch.__is__' expression type.");
  4410. });
  4411. this.registerFunction('torch.__isnot__', function(left, right) {
  4412. if (left === null && right === null) {
  4413. return false;
  4414. }
  4415. if ((left !== null && right === null) || (left === null && right !== null)) {
  4416. return true;
  4417. }
  4418. throw new python.Error("Unsupported 'torch.__isnot__' expression type.");
  4419. });
  4420. this.registerFunction('torch.__not__', function(value) {
  4421. if (typeof value === 'boolean') {
  4422. return !value;
  4423. }
  4424. throw new python.Error("Unsupported 'torch.__not__' expression type.");
  4425. });
  4426. this.registerFunction('torch.__range_length', function(lo, hi, step) {
  4427. if (step === 0) {
  4428. throw new python.Error('range() arg 3 must not be zero');
  4429. }
  4430. if (step > 0 && lo < hi) {
  4431. return 1 + (hi - 1 - lo) / step;
  4432. }
  4433. else if (step < 0 && lo > hi) {
  4434. return 1 + (lo - 1 - hi) / (0 - step);
  4435. }
  4436. return 0;
  4437. });
  4438. this.registerFunction('torch._unwrap_optional', function(value) {
  4439. return value; // TODO
  4440. });
  4441. this.registerFunction('torch.add', function(left, right) {
  4442. if (typeof left === 'number' && typeof right === 'number') {
  4443. return left * right;
  4444. }
  4445. if (Array.isArray(left) && Array.isArray(right)) {
  4446. return left.concat(right);
  4447. }
  4448. if (typeof left === 'string' && typeof right === 'string') {
  4449. return left + right;
  4450. }
  4451. throw new python.Error('Unsupported torch.add expression type.');
  4452. });
  4453. this.registerFunction('torch.append', function(list, value) {
  4454. list.push(value);
  4455. return value;
  4456. });
  4457. this.registerFunction('torch.extend', function(list, value) {
  4458. list.push(...value);
  4459. });
  4460. this.registerFunction('torch.insert', function(list, index, value) {
  4461. list.splice(index, 0, value);
  4462. return value;
  4463. });
  4464. this.registerFunction('torch.clear', function(value) {
  4465. if (Object(value) === value) {
  4466. for (const key of Object.keys(value)) {
  4467. delete value[key];
  4468. }
  4469. }
  4470. });
  4471. this.registerFunction('torch.replace', function(value) {
  4472. return value;
  4473. });
  4474. this.registerFunction('torch.dict', function(args) {
  4475. const obj = {};
  4476. if (args) {
  4477. if (Array.isArray(args)) {
  4478. for (const pair of args) {
  4479. const key = pair[0];
  4480. const value = pair[1];
  4481. obj[key] = value;
  4482. }
  4483. }
  4484. else {
  4485. throw new python.Error("'torch.dict' arguments not supported.");
  4486. }
  4487. }
  4488. return obj;
  4489. });
  4490. this.registerFunction('torch.dim', function(tensor) {
  4491. if (tensor && tensor.size) {
  4492. const size = tensor.size();
  4493. if (size) {
  4494. return size.length;
  4495. }
  4496. }
  4497. return NaN; // TODO
  4498. });
  4499. this.registerFunction('torch.numel', function(tensor) {
  4500. if (tensor && tensor.size) {
  4501. const size = tensor.size();
  4502. if (size) {
  4503. return size.reduce((a, b) => a * b, 1);
  4504. }
  4505. }
  4506. return NaN;
  4507. });
  4508. this.registerFunction('torch.eq', function(left, right) {
  4509. if (typeof left === 'string' && typeof right === 'string') {
  4510. return left === right;
  4511. }
  4512. if (typeof left === 'number' && typeof right === 'number') {
  4513. if (isNaN(left) && isNaN(right)) {
  4514. return true;
  4515. }
  4516. return left === right;
  4517. }
  4518. if (left === undefined || right === undefined) {
  4519. return true;
  4520. }
  4521. if (Array.isArray(left) && Array.isArray(right)) {
  4522. return left.length === right.length && left.every((item, index) => item === right[index]);
  4523. }
  4524. throw new python.Error("Unsupported 'torch.eq' expression type.");
  4525. });
  4526. this.registerFunction('torch.floor', function(value) {
  4527. return Math.floor(value);
  4528. });
  4529. this.registerFunction('torch.ceil', function(value) {
  4530. return Math.ceil(value);
  4531. });
  4532. this.registerFunction('torch.floordiv', function(left, right) {
  4533. return Math.floor(left / right);
  4534. });
  4535. this.registerFunction('torch.format', function() {
  4536. const args = Array.from(arguments);
  4537. const list = args.shift().split(/({}D?)/);
  4538. return list.map((text) => {
  4539. if (text === '{}' || text === '{}D') {
  4540. const arg = args.shift();
  4541. return Array.isArray(arg) ? '[' + arg.map((item) => item.toString()).join(', ') + ']' : arg ? arg.toString() : '?';
  4542. }
  4543. return text;
  4544. }).join('');
  4545. });
  4546. this.registerFunction('torch.gt', function(left, right) {
  4547. if (typeof left === 'number' && typeof right === 'number') {
  4548. if (!isNaN(left) && !isNaN(right)) {
  4549. return left > right;
  4550. }
  4551. }
  4552. if (isNaN(left) && !isNaN(right)) {
  4553. return true;
  4554. }
  4555. throw new python.Error("Unsupported 'torch.gt' expression type.");
  4556. });
  4557. this.registerFunction('torch.ge', function(left, right) {
  4558. if (typeof left === 'number' && typeof right === 'number') {
  4559. if (!isNaN(left) && !isNaN(right)) {
  4560. return left > right;
  4561. }
  4562. }
  4563. if (isNaN(left) && !isNaN(right)) {
  4564. return true;
  4565. }
  4566. throw new python.Error("Unsupported 'torch.ge' expression type.");
  4567. });
  4568. this.registerFunction('torch.is_floating_point', function(tensor) {
  4569. const type = tensor.dtype.scalar_type();
  4570. return (type === 5 || type === 6 || type === 7);
  4571. });
  4572. this.registerFunction('torch.is_grad_enabled', function() {
  4573. return false;
  4574. });
  4575. this.registerFunction('torch.set_grad_enabled', function(/* value */) {
  4576. });
  4577. this.registerFunction('torch.serialization._get_layout', function(name) {
  4578. const value = name.startsWith('torch.') ? torch[name.split('.')[1]] : null;
  4579. return value instanceof torch.layout ? value : null;
  4580. });
  4581. this.registerFunction('torch.storage._load_from_bytes', function(b) {
  4582. return torch.load(b);
  4583. });
  4584. this.registerFunction('torch.jit._pickle.build_boollist', function(data) {
  4585. return data;
  4586. });
  4587. this.registerFunction('torch.jit._pickle.build_doublelist', function(data) {
  4588. return data;
  4589. });
  4590. this.registerFunction('torch.jit._pickle.build_intlist', function(data) {
  4591. return data;
  4592. });
  4593. this.registerFunction('torch.jit._pickle.build_tensorlist', function(data) {
  4594. return data;
  4595. });
  4596. this.registerFunction('torch.jit._pickle.build_tensor_from_id', function(data) {
  4597. return self.builtins.CONSTANTS['c' + data.toString()];
  4598. });
  4599. this.registerFunction('torch.jit._pickle.restore_type_tag', function(value /*, type_str */) {
  4600. return value;
  4601. });
  4602. this.registerFunction('torch.keys', function(dict) {
  4603. return Object.keys(dict);
  4604. });
  4605. this.registerFunction('torch.len', function(value) {
  4606. if (Array.isArray(value)) {
  4607. return value.length;
  4608. }
  4609. if (value && value.shape && value.__len__) {
  4610. return value.__len__();
  4611. }
  4612. return NaN;
  4613. });
  4614. this.registerFunction('torch.le', function(left, right) {
  4615. if (typeof left === 'number' && typeof right === 'number') {
  4616. if (isNaN(left) || isNaN(right)) {
  4617. return false;
  4618. }
  4619. return left <= right;
  4620. }
  4621. if (left === undefined || right === undefined) {
  4622. return true;
  4623. }
  4624. throw new python.Error("Unsupported 'torch.le' expression type.");
  4625. });
  4626. this.registerFunction('torch.list', function(args) {
  4627. return args;
  4628. });
  4629. this.registerFunction('torch.list_with_default', function(size /*, defaults */) {
  4630. return size;
  4631. });
  4632. this.registerFunction('torch.load', function(f) {
  4633. const legacy_load = (entries) => {
  4634. const deserialized_objects = {};
  4635. if (entries.has('storages')) {
  4636. const data = entries.get('storages');
  4637. const unpickler = execution.invoke('pickle.Unpickler', [ data ]);
  4638. const num_storages = unpickler.load();
  4639. for (let i = 0; i < num_storages; i++) {
  4640. const args = unpickler.load();
  4641. const key = args[0];
  4642. const storage_type = args[2];
  4643. const obj = storage_type._new_with_file(unpickler);
  4644. deserialized_objects[key] = obj;
  4645. }
  4646. /*
  4647. let storage_views = unpickler.load();
  4648. for target_cdata, root_cdata, offset, size in storage_views:
  4649. root = deserialized_objects[root_cdata]
  4650. deserialized_objects[target_cdata] = root[offset:offset + size]
  4651. */
  4652. }
  4653. if (entries.has('tensors')) {
  4654. const data = entries.get('tensors');
  4655. const unpickler = execution.invoke('pickle.Unpickler', [ data ]);
  4656. const num_tensors = unpickler.load();
  4657. const int32 = (unpickler) => {
  4658. const buffer = unpickler.read(4);
  4659. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24);
  4660. };
  4661. const int64 = (unpickler) => {
  4662. const buffer = unpickler.read(8);
  4663. if (buffer[6] !== 0 && buffer[7] !== 0) {
  4664. throw new python.Error('Unsigned 64-bit value exceeds 32-bit range.');
  4665. }
  4666. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24) + (buffer[4] * 4294967296) + (buffer[5] * 1099511627776);
  4667. };
  4668. for (let i = 0; i < num_tensors; i++) {
  4669. const args = unpickler.load();
  4670. const key = args[0];
  4671. const storage_id = args[1];
  4672. const storage = deserialized_objects[storage_id];
  4673. const ndim = int32(unpickler);
  4674. unpickler.read(4);
  4675. const shape = Array.from(new Array(ndim)).map(() => int64(unpickler));
  4676. const stride = Array.from(new Array(ndim)).map(() => int64(unpickler));
  4677. const storage_offset = int64(unpickler);
  4678. const tensor = execution.invoke('torch._utils._rebuild_tensor', [ storage, storage_offset, shape, stride ]);
  4679. deserialized_objects[key] = tensor;
  4680. }
  4681. }
  4682. const data = entries.get('pickle');
  4683. const unpickler = execution.invoke('pickle.Unpickler', [ data ]);
  4684. unpickler.persistent_load = (saved_id) => deserialized_objects[saved_id];
  4685. return unpickler.load();
  4686. };
  4687. const _legacy_load = () => {
  4688. const unpickler = execution.invoke('pickle.Unpickler', [ f ]);
  4689. unpickler.load(); // magic_number
  4690. const protocol_version = unpickler.load();
  4691. if (protocol_version != 1001) {
  4692. throw new python.Error("Unsupported protocol version '" + protocol_version + "'.");
  4693. }
  4694. const sys_info = unpickler.load();
  4695. if (sys_info.protocol_version != 1001) {
  4696. throw new python.Error("Unsupported protocol version '" + sys_info.protocol_version + "'.");
  4697. }
  4698. if (sys_info.little_endian === false) {
  4699. throw new python.Error("Unsupported big-endian storage data.");
  4700. }
  4701. const module_source_map = new Map();
  4702. const deserialized_objects = new Map();
  4703. unpickler.persistent_load = (saved_id) => {
  4704. const typename = saved_id[0];
  4705. switch (typename) {
  4706. case 'module': {
  4707. const module = saved_id[1];
  4708. const source = saved_id[3];
  4709. module_source_map.set(module, source);
  4710. return saved_id[1];
  4711. }
  4712. case 'storage': {
  4713. const storage_type = saved_id[1];
  4714. const root_key = saved_id[2];
  4715. /// const location = saved_id[3];
  4716. const size = saved_id[4];
  4717. const view_metadata = saved_id[5];
  4718. if (!deserialized_objects.has(root_key)) {
  4719. const obj = new storage_type(size);
  4720. deserialized_objects.set(root_key, obj);
  4721. }
  4722. if (view_metadata) {
  4723. const view_key = view_metadata.shift();
  4724. view_metadata.shift(); // view_offset
  4725. view_metadata.shift(); // view_size
  4726. if (!deserialized_objects.has(view_key)) {
  4727. const view = null; // storage.slice(view_offset, view_offset + view_size);
  4728. deserialized_objects.set(view_key, view);
  4729. }
  4730. return deserialized_objects.get(view_key);
  4731. }
  4732. return deserialized_objects.get(root_key);
  4733. }
  4734. default: {
  4735. throw new python.Error("Unsupported persistent load type '" + typename + "'.");
  4736. }
  4737. }
  4738. };
  4739. const obj = unpickler.load();
  4740. const deserialized_storage_keys = unpickler.load();
  4741. for (const deserialized_storage_key of deserialized_storage_keys) {
  4742. const storage = deserialized_objects.get(deserialized_storage_key);
  4743. storage._set_from_file(unpickler);
  4744. }
  4745. if (!obj) {
  4746. throw new python.Error('File format is not PyTorch.');
  4747. }
  4748. if (obj === 'None') {
  4749. throw new python.Error("File contains 'None' root object.");
  4750. }
  4751. return obj;
  4752. };
  4753. const _load = (entries) => {
  4754. if (f.has('constant.pkl')) {
  4755. throw python.Error("TorchScript 'torch.load' not supported.");
  4756. }
  4757. const loaded_storages = new Map();
  4758. const persistent_load = (saved_id) => {
  4759. const typename = saved_id[0];
  4760. if (typename !== 'storage') {
  4761. throw new python.Error("Unsupported persistent load type '" + typename + "'.");
  4762. }
  4763. const storage_type = saved_id[1];
  4764. const key = saved_id[2];
  4765. const numel = saved_id[4];
  4766. if (!loaded_storages.has(key)) {
  4767. const storage = new storage_type(numel);
  4768. const name = 'data/' + key;
  4769. const stream = entries.get(name);
  4770. storage._set_cdata(stream);
  4771. loaded_storages.set(key, storage);
  4772. }
  4773. return loaded_storages.get(key);
  4774. };
  4775. const data_file = entries.get('data.pkl');
  4776. const unpickler = execution.invoke('pickle.Unpickler', [ data_file ]);
  4777. unpickler.persistent_load = persistent_load;
  4778. const result = unpickler.load();
  4779. return result;
  4780. };
  4781. if (f instanceof Map) {
  4782. if (f.has('pickle')) {
  4783. return legacy_load(f);
  4784. }
  4785. if (f.has('data.pkl')) {
  4786. return _load(f);
  4787. }
  4788. throw new python.Error("Unsupported 'torch.load' input '" + JSON.stringify(Array.from(f.keys())) + "'.");
  4789. }
  4790. return _legacy_load(f);
  4791. });
  4792. this.registerFunction('torch.lt', function(left, right) {
  4793. if (typeof left === 'number' && typeof right === 'number') {
  4794. return left < right;
  4795. }
  4796. throw new python.Error("Unsupported 'torch.lt' expression type.");
  4797. });
  4798. this.registerFunction('torch.mul', function(left, right) {
  4799. if (typeof left === 'number' && typeof right === 'number') {
  4800. return left * right;
  4801. }
  4802. if (isNaN(left) || isNaN(right)) {
  4803. return NaN;
  4804. }
  4805. if (Array.isArray(left) && left.every((value) => typeof value === 'number') && typeof right === 'number') {
  4806. return left.map((value) => value * right);
  4807. }
  4808. throw new python.Error("Unsupported 'torch.mul' expression type.");
  4809. });
  4810. this.registerFunction('torch.div', function(left, right) {
  4811. if (typeof left === 'number' && typeof right === 'number') {
  4812. return left / right;
  4813. }
  4814. if (isNaN(left) || isNaN(right)) {
  4815. return NaN;
  4816. }
  4817. throw new python.Error("Unsupported 'torch.div' expression type.");
  4818. });
  4819. this.registerFunction('torch.round', function(value) {
  4820. if (typeof value === 'number') {
  4821. return Math.round(value);
  4822. }
  4823. if (isNaN(value)) {
  4824. return value;
  4825. }
  4826. throw new python.Error("Unsupported 'torch.round' expression type.");
  4827. });
  4828. this.registerFunction('torch.remainder', function(left, right) {
  4829. if (typeof left === 'number' && typeof right === 'number') {
  4830. return left % right;
  4831. }
  4832. if (isNaN(left) || isNaN(right)) {
  4833. return NaN;
  4834. }
  4835. throw new python.Error("Unsupported 'torch.remainder' expression type.");
  4836. });
  4837. this.registerFunction('torch.ne', function(left, right) {
  4838. if (typeof left === 'boolean' && typeof right === 'boolean') {
  4839. return left !== right;
  4840. }
  4841. if (typeof left === 'number' && typeof right === 'number') {
  4842. if (isNaN(left) || isNaN(right)) {
  4843. return false;
  4844. }
  4845. return left !== right;
  4846. }
  4847. if (Array.isArray(left) && Array.isArray(right) && left.length === right.length) {
  4848. return false;
  4849. }
  4850. if (typeof left === 'string' && typeof right === 'string') {
  4851. return left !== right;
  4852. }
  4853. if (left === undefined || right === undefined) {
  4854. return true;
  4855. }
  4856. throw new python.Error("Unsupported 'torch.ne' expression type.");
  4857. });
  4858. this.registerFunction('torch.neg', function(value) {
  4859. if (typeof value === 'number') {
  4860. return -value;
  4861. }
  4862. throw new python.Error("Unsupported 'torch.neg' expression type.");
  4863. });
  4864. this.registerFunction('torch.q_scale', function(/* tensor */) {
  4865. return -1; // TODO
  4866. });
  4867. this.registerFunction('torch.t', function(tensor) {
  4868. return tensor;
  4869. });
  4870. this.registerFunction('torch.size', function(tensor, dim) {
  4871. if (tensor && tensor.size) {
  4872. const size = tensor.size();
  4873. if (Array.isArray(size)) {
  4874. if (dim === undefined) {
  4875. return size;
  4876. }
  4877. if (Number.isInteger(dim)) {
  4878. if (dim >= 0 && dim < size.length) {
  4879. return size[dim];
  4880. }
  4881. if (dim < 0 && -dim < size.length) {
  4882. return size[size.length + dim];
  4883. }
  4884. }
  4885. throw new python.Error('Dimension out of range (expected to be in range of ' + JSON.stringify(size) + ', but got ' + JSON.stringify(dim) + ').');
  4886. }
  4887. }
  4888. if (Number.isInteger(dim)) {
  4889. return NaN;
  4890. }
  4891. return [];
  4892. });
  4893. this.registerFunction('torch.slice', function(l, start, end, step) {
  4894. if (!Array.isArray(l)) {
  4895. throw new python.Error('Slicing expected array');
  4896. }
  4897. step = step || 1;
  4898. if (step !== 1) {
  4899. throw new python.Error('Slicing only supports step=1');
  4900. }
  4901. start = Math.max(0, start >= 0 ? start : l.length + start);
  4902. end = Math.min(l.length, end || Number.MAX_SAFE_INTEGER);
  4903. return l.slice(start, end);
  4904. });
  4905. this.registerFunction('torch.sub', function(left, right) {
  4906. if (typeof left === 'number' && typeof right === 'number') {
  4907. return left - right;
  4908. }
  4909. throw new python.Error("Unsupported 'torch.sub' expression type.");
  4910. });
  4911. this.registerFunction('torch.nn.functional.gelu', function(/* input */) {
  4912. throw new python.Error("Function not implemented.");
  4913. });
  4914. this.registerFunction('torch.nn.functional.interpolate', function(/* input */) {
  4915. throw new python.Error("Function not implemented.");
  4916. });
  4917. this.registerFunction('torch.nn.functional.leaky_relu', function(/* input */) {
  4918. throw new python.Error("Function not implemented.");
  4919. });
  4920. this.registerFunction('torch.nn.functional.linear', function(/* input */) {
  4921. throw new python.Error("Function not implemented.");
  4922. });
  4923. this.registerFunction('torch.nn.functional.relu', function(/* input */) {
  4924. throw new python.Error("Function not implemented.");
  4925. });
  4926. this.registerFunction('torch.nn.functional.tanh', function(/* input */) {
  4927. throw new python.Error("Function not implemented.");
  4928. });
  4929. this.registerFunction('torch.values', function(dict) {
  4930. return Object.keys(dict).map((key) => dict[key]);
  4931. });
  4932. this.registerFunction('torch.warn', function() {
  4933. });
  4934. this.registerFunction('torch.fx.graph_module.reduce_graph_module', function(body /*, import_block */) {
  4935. // https://github.com/pytorch/pytorch/blob/master/torch/fx/graph_module.py
  4936. return body;
  4937. });
  4938. this.registerFunction('torch_utils.persistence._reconstruct_persistent_obj', function(meta) {
  4939. const name = '_imported_module_' + Math.floor(Math.random() * 10000).toString();
  4940. const module = execution.invoke('types.ModuleType', [ name ]);
  4941. execution.register('sys').modules.set(name, module);
  4942. const context = new python.Execution.Context(module, null);
  4943. execution.exec(meta.module_src, context);
  4944. const obj = execution.invoke(name + '.' + meta.class_name, []);
  4945. if (meta.state) {
  4946. if (obj.__setstate__) {
  4947. obj.__setstate__(meta.state);
  4948. }
  4949. else {
  4950. Object.assign(obj, meta.state);
  4951. }
  4952. }
  4953. return obj;
  4954. });
  4955. this.registerFunction('torch_utils.misc.assert_shape', function(/* tensor, ref_shape */) {});
  4956. this.registerFunction('torch_utils.ops.conv2d_resample.conv2d_resample', function(/* x, w, f, up, down, padding, groups, flip_weight, flip_filter */) {});
  4957. this.registerFunction('torch_utils.ops.upfirdn2d.setup_filter', function(/* x, f, up, down, padding, flip_filter, gain, impl */) {});
  4958. this.registerFunction('torch_utils.ops.bias_act', function(/* x, b, dim, act, alpha, gain, clamp, impl */) {});
  4959. this.registerFunction('torch_utils.ops.fma.fma', function(/* a, b, c */) {});
  4960. this.registerType('torch.device', class {
  4961. constructor(type, index) {
  4962. this.type = type;
  4963. if (index) {
  4964. this.index = index;
  4965. }
  4966. }
  4967. });
  4968. this.registerType('torch.dtype', class {
  4969. constructor(scalar_type, name, itemsize) {
  4970. this._scalar_type = scalar_type;
  4971. this._name = name;
  4972. this._itemsize = itemsize;
  4973. }
  4974. scalar_type() {
  4975. return this._scalar_type;
  4976. }
  4977. itemsize() {
  4978. return this._itemsize;
  4979. }
  4980. __reduce__() {
  4981. return this._name;
  4982. }
  4983. __str__() {
  4984. return 'torch.' + this._name;
  4985. }
  4986. toString() {
  4987. return this.__str__();
  4988. }
  4989. });
  4990. this.registerType('torch.layout', class {
  4991. constructor(name) {
  4992. this._name = name;
  4993. }
  4994. __str__() {
  4995. return this._name;
  4996. }
  4997. toString() {
  4998. return this.__str__();
  4999. }
  5000. });
  5001. this.registerType('torch.qscheme', class {
  5002. constructor(name) {
  5003. this._name = name;
  5004. }
  5005. __str__() {
  5006. return this._name;
  5007. }
  5008. toString() {
  5009. return this.__str__();
  5010. }
  5011. });
  5012. this.registerType('torch.utils.hooks.RemovableHandle', class {
  5013. __setstate__(state) {
  5014. this.hooks_dict_ref = state[0] || new Map();
  5015. this.id = state[1];
  5016. }
  5017. });
  5018. this.registerType('torch.storage._StorageBase', class {
  5019. constructor(size, dtype) {
  5020. this._size = size;
  5021. this._dtype = dtype;
  5022. this._device = null;
  5023. }
  5024. get device() {
  5025. return this._device;
  5026. }
  5027. get dtype() {
  5028. return this._dtype;
  5029. }
  5030. element_size() {
  5031. return this._dtype.element_size;
  5032. }
  5033. size() {
  5034. return this._size;
  5035. }
  5036. get data() {
  5037. return this._cdata;
  5038. }
  5039. _set_cdata(data) {
  5040. const length = this.size() * this.dtype.itemsize();
  5041. if (length !== data.length) {
  5042. throw new python.Error('Storage data size mismatch.');
  5043. }
  5044. this._cdata = data;
  5045. }
  5046. _set_from_file(unpickler) {
  5047. const buffer = unpickler.read(8);
  5048. const size = buffer.reverse().reduce((a, b) => (a*256)+b, 0);
  5049. if (size !== this.size()) {
  5050. throw new python.Error('Storage size mismatch.');
  5051. }
  5052. const itemsize = this.dtype.itemsize();
  5053. const data = unpickler.stream(itemsize * size);
  5054. this._set_cdata(data);
  5055. }
  5056. static _new_with_file(unpickler) {
  5057. const buffer = unpickler.read(8);
  5058. const size = buffer.reverse().reduce((a, b) => (a*256)+b, 0);
  5059. const storage = new this(size);
  5060. const itemsize = storage.dtype.itemsize();
  5061. const data = unpickler.stream(itemsize * size);
  5062. storage._set_cdata(data);
  5063. return storage;
  5064. }
  5065. });
  5066. this.registerType('torch.storage._UntypedStorage', class extends torch.storage._StorageBase {
  5067. constructor() {
  5068. super();
  5069. throw new python.Error('_UntypedStorage not implemented.');
  5070. }
  5071. });
  5072. this.registerType('torch.storage._TypedStorage', class {
  5073. constructor() {
  5074. if (arguments.length >= 2 && Number.isInteger(arguments[0]) && arguments[1] instanceof torch.dtype) {
  5075. this._size = arguments[0];
  5076. this._dtype = arguments[1];
  5077. if (arguments[3] instanceof torch.device) {
  5078. this._device = arguments[3];
  5079. }
  5080. }
  5081. else {
  5082. throw new python.Error("Unsupported _TypedStorage arguments '" + JSON.stringify(arguments) + "'.");
  5083. }
  5084. }
  5085. get device() {
  5086. return this._device;
  5087. }
  5088. get dtype() {
  5089. return this._dtype;
  5090. }
  5091. element_size() {
  5092. return this._dtype.element_size;
  5093. }
  5094. size() {
  5095. return this._size;
  5096. }
  5097. get data() {
  5098. return this._cdata;
  5099. }
  5100. _set_cdata(data) {
  5101. const length = this.size() * this.dtype.itemsize();
  5102. if (length !== data.length) {
  5103. throw new python.Error('Storage data size mismatch.');
  5104. }
  5105. this._cdata = data;
  5106. }
  5107. _set_from_file(unpickler) {
  5108. const buffer = unpickler.read(8);
  5109. const size = buffer.reverse().reduce((a, b) => (a*256)+b, 0);
  5110. if (size !== this.size()) {
  5111. throw new python.Error('Storage size mismatch.');
  5112. }
  5113. const itemsize = this.dtype.itemsize();
  5114. const data = unpickler.stream(itemsize * size);
  5115. this._set_cdata(data);
  5116. }
  5117. static _new_with_file(unpickler) {
  5118. const buffer = unpickler.read(8);
  5119. const size = buffer.reverse().reduce((a, b) => (a*256)+b, 0);
  5120. const storage = new this(size);
  5121. const itemsize = storage.dtype.itemsize();
  5122. const data = unpickler.stream(itemsize * size);
  5123. storage._set_cdata(data);
  5124. return storage;
  5125. }
  5126. });
  5127. this.registerType('torch.storage._LegacyStorage', class extends torch.storage._TypedStorage {
  5128. constructor() {
  5129. super();
  5130. throw new python.Error('_LegacyStorage not implemented.');
  5131. }
  5132. });
  5133. this.registerType('torch.BoolStorage', class extends torch.storage._StorageBase {
  5134. constructor(size) {
  5135. super(size, torch.bool);
  5136. }
  5137. });
  5138. this.registerType('torch.ByteStorage', class extends torch.storage._StorageBase {
  5139. constructor(size) {
  5140. super(size, torch.uint8);
  5141. }
  5142. });
  5143. this.registerType('torch.CharStorage', class extends torch.storage._StorageBase {
  5144. constructor(size) {
  5145. super(size, torch.int8);
  5146. }
  5147. });
  5148. this.registerType('torch.ShortStorage', class extends torch.storage._StorageBase {
  5149. constructor(size) {
  5150. super(size, torch.int16);
  5151. }
  5152. });
  5153. this.registerType('torch.IntStorage', class extends torch.storage._StorageBase {
  5154. constructor(size) {
  5155. super(size, torch.int32);
  5156. }
  5157. });
  5158. this.registerType('torch.LongStorage', class extends torch.storage._StorageBase {
  5159. constructor(size) {
  5160. super(size, torch.int64);
  5161. }
  5162. });
  5163. this.registerType('torch.HalfStorage', class extends torch.storage._StorageBase {
  5164. constructor(size) {
  5165. super(size, torch.float16);
  5166. }
  5167. });
  5168. this.registerType('torch.FloatStorage', class extends torch.storage._StorageBase {
  5169. constructor(size) {
  5170. super(size, torch.float32);
  5171. }
  5172. });
  5173. this.registerType('torch.DoubleStorage', class extends torch.storage._StorageBase {
  5174. constructor(size) {
  5175. super(size, torch.float64);
  5176. }
  5177. });
  5178. this.registerType('torch.ComplexHalfStorage', class extends torch.storage._StorageBase {
  5179. constructor(size) {
  5180. super(size, torch.complex32);
  5181. }
  5182. });
  5183. this.registerType('torch.ComplexFloatStorage', class extends torch.storage._StorageBase {
  5184. constructor(size) {
  5185. super(size, torch.complex64);
  5186. }
  5187. });
  5188. this.registerType('torch.ComplexDoubleStorage', class extends torch.storage._StorageBase {
  5189. constructor(size) {
  5190. super(size, torch.complex128);
  5191. }
  5192. });
  5193. this.registerType('torch.QInt8Storage', class extends torch.storage._StorageBase {
  5194. constructor(size) {
  5195. super(size, torch.qint8);
  5196. }
  5197. });
  5198. this.registerType('torch.QUInt8Storage', class extends torch.storage._StorageBase {
  5199. constructor(size) {
  5200. super(size, torch.quint8);
  5201. }
  5202. });
  5203. this.registerType('torch.QInt32Storage', class extends torch.storage._StorageBase {
  5204. constructor(size) {
  5205. super(size, torch.qint32);
  5206. }
  5207. });
  5208. this.registerType('torch.BFloat16Storage', class extends torch.storage._StorageBase {
  5209. constructor(size) {
  5210. super(size, torch.bfloat16);
  5211. }
  5212. });
  5213. this.registerType('torch.Size', class extends Array {
  5214. constructor(size) {
  5215. super(size.length);
  5216. for (let i = 0; i < size.length; i++) {
  5217. this[i] = size[i];
  5218. }
  5219. }
  5220. __len__() {
  5221. return this.length;
  5222. }
  5223. });
  5224. this.registerType('torch.Tensor', class {
  5225. constructor() {
  5226. this._layout = torch.strided;
  5227. }
  5228. get device() {
  5229. return this.storage().device;
  5230. }
  5231. get dtype() {
  5232. if (this._layout === torch.sparse_coo) {
  5233. return this._values.dtype();
  5234. }
  5235. return this.storage().dtype;
  5236. }
  5237. get shape() {
  5238. return this._shape;
  5239. }
  5240. get layout() {
  5241. return this._layout;
  5242. }
  5243. get values() {
  5244. if (this._layout === torch.sparse_coo) {
  5245. return this._values;
  5246. }
  5247. throw new python.Error("Unsupported values in layout'" + this._layout.__str__() + "'.");
  5248. }
  5249. get indices() {
  5250. if (this._layout === torch.sparse_coo) {
  5251. return this._indices;
  5252. }
  5253. throw new python.Error("Unsupported indices in layout'" + this._indices.__str__() + "'.");
  5254. }
  5255. get is_quantized() {
  5256. return this.__quantized__ === true;
  5257. }
  5258. get is_nested() {
  5259. return this.__nested__ === true;
  5260. }
  5261. get is_sparse() {
  5262. return this.layout !== torch.strided;
  5263. }
  5264. size() {
  5265. return this._shape;
  5266. }
  5267. storage() {
  5268. if (!this._storage) {
  5269. const name = this.__class__.__name__ == 'Tensor' ? 'FloatStorage' : this.__storage__.__name__.replace('Tensor', 'Storage');
  5270. this._storage = self.invoke(this.__class__.__module__ + '.' + name, []);
  5271. }
  5272. return this._storage;
  5273. }
  5274. storage_offset() {
  5275. return this._storage_offset;
  5276. }
  5277. stride() {
  5278. return this._stride;
  5279. }
  5280. resize_(shape) {
  5281. this._shape = shape;
  5282. }
  5283. __len__() {
  5284. return this._shape[0];
  5285. }
  5286. __setstate__(state) {
  5287. this._storage = state[0];
  5288. this._storage_offset = state[1];
  5289. this._shape = state[2];
  5290. this._stride = state[3];
  5291. }
  5292. __bool__() {
  5293. return true;
  5294. }
  5295. __int__() {
  5296. const storage = this.storage();
  5297. if (storage && storage.dtype.__reduce__() === 'int64' && storage.data.length === 8) {
  5298. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  5299. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  5300. return view.getInt64(0, true);
  5301. }
  5302. return NaN;
  5303. }
  5304. __float__() {
  5305. const storage = this.storage();
  5306. if (storage && storage.dtype.__reduce__() === 'float32') {
  5307. if (storage.size() !== undefined && storage.data.length === 4) {
  5308. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  5309. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  5310. return view.getFloat32(0, true);
  5311. }
  5312. }
  5313. return NaN;
  5314. }
  5315. __str__() {
  5316. return 'tensor(...)';
  5317. }
  5318. });
  5319. this.registerType('torch.nn.parameter.Parameter', class extends torch.Tensor {
  5320. constructor(data, requires_grad) {
  5321. super();
  5322. if (!data) {
  5323. data = self.invoke('torch.Tensor', [[]]);
  5324. }
  5325. this.data = data;
  5326. this.requires_grad = requires_grad !== undefined ? requires_grad : true;
  5327. }
  5328. __setstate__(state) {
  5329. switch (state.length) {
  5330. case 3:
  5331. this.data = null;
  5332. break;
  5333. case 4:
  5334. this.data = state[0];
  5335. break;
  5336. case 5:
  5337. this.data = state[0];
  5338. break;
  5339. default:
  5340. throw new python.Error("Unsupported parameter state length '" + state.length + "'.");
  5341. }
  5342. }
  5343. });
  5344. this.registerType('torch.nn.parameter.UninitializedParameter', class extends torch.nn.parameter.Parameter {
  5345. constructor(requires_grad /*, device, dtype */) {
  5346. super(undefined, requires_grad);
  5347. }
  5348. });
  5349. this.registerType('torch.BoolTensor', class extends torch.Tensor {});
  5350. this.registerType('torch.ByteTensor', class extends torch.Tensor {});
  5351. this.registerType('torch.CharTensor', class extends torch.Tensor {});
  5352. this.registerType('torch.ShortTensor', class extends torch.Tensor {});
  5353. this.registerType('torch.IntTensor', class extends torch.Tensor {});
  5354. this.registerType('torch.LongTensor', class extends torch.Tensor {});
  5355. this.registerType('torch.HalfTensor', class extends torch.Tensor {});
  5356. this.registerType('torch.FloatTensor', class extends torch.Tensor {});
  5357. this.registerType('torch.DoubleTensor', class extends torch.Tensor {});
  5358. this.registerType('torch.ComplexFloatTensor', class extends torch.Tensor {});
  5359. this.registerType('torch.ComplexDoubleTensor', class extends torch.Tensor {});
  5360. this.registerType('torch.QInt8Tensor', class extends torch.Tensor {});
  5361. this.registerType('torch.QUInt8Tensor', class extends torch.Tensor {});
  5362. this.registerType('torch.QInt32Tensor', class extends torch.Tensor {});
  5363. this.registerType('torch.BFloat16Tensor', class extends torch.Tensor {});
  5364. this.registerType('torch.cuda.FloatTensor', class extends torch.Tensor {});
  5365. this.registerType('torch.cuda.DoubleTensor', class extends torch.Tensor {});
  5366. this.register('torch.nn').Module = this.register('torch.nn.modules.module').Module;
  5367. this.register('torch.optim').Adam = this.register('torch.optim.adam').Adam;
  5368. this.register('torch.nn').ReLU = this.register('torch.nn.modules.activation').ReLU;
  5369. this.register('sklearn.utils').Bunch = this.register('sklearn.utils._bunch').Bunch;
  5370. torch.uint8 = torch.ByteStorage.dtype = new torch.dtype(0, 'uint8', 1);
  5371. torch.int8 = torch.CharStorage.dtype = new torch.dtype(1, 'int8', 1);
  5372. torch.int16 = torch.ShortStorage.dtype = new torch.dtype(2, 'int16', 2);
  5373. torch.int32 = torch.IntStorage.dtype = new torch.dtype(3, 'int32', 4);
  5374. torch.int64 = torch.LongStorage.dtype = new torch.dtype(4, 'int64', 8);
  5375. torch.float16 = torch.HalfStorage.dtype = new torch.dtype(5, 'float16', 2);
  5376. torch.float32 = torch.FloatStorage.dtype = new torch.dtype(6, 'float32', 4);
  5377. torch.float64 = torch.DoubleStorage.dtype = new torch.dtype(7, 'float64', 8);
  5378. torch.complex32 = torch.ComplexHalfStorage.dtype = new torch.dtype(8, 'complex32', 4);
  5379. torch.complex64 = torch.ComplexFloatStorage.dtype = new torch.dtype(9, 'complex64', 8);
  5380. torch.complex128 = torch.ComplexDoubleStorage.dtype = new torch.dtype(10, 'complex128', 16);
  5381. torch.bool = torch.BoolStorage.dtype = new torch.dtype(11, 'boolean', 1);
  5382. torch.qint8 = torch.QInt8Storage.dtype = new torch.dtype(12, 'qint8', 1);
  5383. torch.quint8 = torch.QUInt8Storage.dtype = new torch.dtype(13, 'quint8', 1);
  5384. torch.qint32 = torch.QInt32Storage.dtype = new torch.dtype(14, 'qint32', 4);
  5385. torch.bfloat16 = torch.BFloat16Storage.dtype = new torch.dtype(15, 'bfloat16', 2);
  5386. torch.quint4x2 = new torch.dtype(16, 'quint4x2');
  5387. torch.strided = new torch.layout('torch.strided');
  5388. torch.sparse_coo = new torch.layout('torch.sparse_coo');
  5389. torch.sparse_csr = new torch.layout('torch.sparse_csr');
  5390. torch.sparse_csc = new torch.layout('torch.sparse_csc');
  5391. torch.sparse_bsr = new torch.layout('torch.sparse_bsr');
  5392. torch.sparse_bsc = new torch.layout('torch.sparse_bsc');
  5393. torch._mkldnn = new torch.layout('torch._mkldnn');
  5394. torch.per_tensor_affine = new torch.qscheme('torch.per_tensor_affine');
  5395. torch.per_channel_affine = new torch.qscheme('torch.per_channel_affine');
  5396. torch.per_tensor_symmetric = new torch.qscheme('torch.per_tensor_symmetric');
  5397. torch.per_channel_symmetric = new torch.qscheme('torch.per_channel_symmetric');
  5398. torch.per_channel_affine_float_qparams = new torch.qscheme('torch.per_channel_affine_float_qparams');
  5399. torch.inf = this.register('math').inf;
  5400. }
  5401. get builtins() {
  5402. return this._builtins;
  5403. }
  5404. source(file) {
  5405. return this._sources.has(file) ? this._sources.get(file) : null;
  5406. }
  5407. debug(/* file */) {
  5408. }
  5409. exec(code , context) {
  5410. const reader = new python.Parser(code, '', null);
  5411. const program = reader.parse();
  5412. if (!program) {
  5413. throw new python.Error("Module '" + '?' + "' parse error.");
  5414. }
  5415. this.block(program.body, context);
  5416. }
  5417. parse(file) {
  5418. const buffer = this.source(file);
  5419. if (buffer) {
  5420. const debug = this.debug(file);
  5421. const code = this._utf8Decoder.decode(buffer);
  5422. const parser = new python.Parser(code, file, debug);
  5423. const program = parser.parse();
  5424. if (!program) {
  5425. throw new python.Error("Module '" + file + "' parse error.");
  5426. }
  5427. return program;
  5428. }
  5429. return null;
  5430. }
  5431. import(name, current, level) {
  5432. if (level) {
  5433. let bits = current.split('.');
  5434. if (bits.length < level) {
  5435. throw new python.Error('Invalid relative import beyond top-level package.');
  5436. }
  5437. bits = bits.slice(0, bits.length - level);
  5438. const base = bits.join('.');
  5439. name = name ? [ base, name ].join('.') : base;
  5440. }
  5441. const index = name.lastIndexOf('.');
  5442. let parent = null;
  5443. let child = null;
  5444. if (index > 0) {
  5445. parent = name.substring(0, index);
  5446. child = name.substring(index + 1);
  5447. this.import(parent);
  5448. }
  5449. if (!this._modules.has(name)) {
  5450. const module = this._registry.get(name) || new this._builtins.module(name);
  5451. module.__package__ = name;
  5452. this._modules.set(name, module);
  5453. const path = name.split('.').join('/');
  5454. module.__path__ = [ path ];
  5455. const file = path + '.py';
  5456. const program = this.parse(file);
  5457. if (program) {
  5458. module.__file__ = file;
  5459. for (const entry of Object.entries(this.builtins)) {
  5460. switch (entry[0]) {
  5461. case '__class__':
  5462. case '__package__':
  5463. case '__module__':
  5464. case '__name__':
  5465. case '__path__':
  5466. case '__file__':
  5467. break;
  5468. default:
  5469. module[entry[0]] = entry[1];
  5470. break;
  5471. }
  5472. }
  5473. const context = new python.Execution.Context(module, null);
  5474. if (name !== 'builtins') {
  5475. context.set('__builtins__', this._modules.get('builtins'));
  5476. }
  5477. this.block(program.body, context);
  5478. }
  5479. if (parent) {
  5480. const parent_module = this._modules.get(parent);
  5481. parent_module[child] = module;
  5482. }
  5483. }
  5484. return this._modules.get(name);
  5485. }
  5486. __import__(name, globals, locals, fromlist, level) {
  5487. let module = null;
  5488. level = level || 0;
  5489. if (level === 0) {
  5490. module = this.import(name);
  5491. }
  5492. else {
  5493. globals = globals || {};
  5494. let current = globals.__package__;
  5495. if (!current) {
  5496. const spec = globals.__spec__;
  5497. if (spec) {
  5498. current = spec.parent;
  5499. }
  5500. else {
  5501. const name = globals.__name__;
  5502. const bits = name.split('.');
  5503. bits.pop();
  5504. current = bits.join('.');
  5505. }
  5506. }
  5507. module = this.import(name, current, level);
  5508. }
  5509. if (!fromlist) {
  5510. if (level === 0) {
  5511. return this.import(name.split('.')[0]);
  5512. }
  5513. else if (name) {
  5514. throw new python.Error("Unsupported relative import '" + name + "'.");
  5515. // cut_off = len(name) - len(name.partition('.')[0])
  5516. // return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
  5517. }
  5518. }
  5519. else if (module.__path__) {
  5520. const handle_fromlist = (module, fromlist, recursive) => {
  5521. for (const name of fromlist) {
  5522. if (name == '*') {
  5523. if (!recursive && module.__all__) {
  5524. handle_fromlist(module, module.__all__, true);
  5525. }
  5526. }
  5527. else if (!module[name]) {
  5528. this.import(module.__name__ + '.' + name);
  5529. }
  5530. }
  5531. return module;
  5532. };
  5533. handle_fromlist(module, fromlist);
  5534. }
  5535. return module;
  5536. }
  5537. module(name) {
  5538. return this._modules.get(name);
  5539. }
  5540. resolve(name) {
  5541. const index = name.lastIndexOf('.');
  5542. const memberName = index === -1 ? name : name.substring(index + 1, name.length);
  5543. const moduleName = index === -1 ? '' : name.substring(0, index);
  5544. const module = this.import(moduleName);
  5545. let type = module ? module[memberName] : null;
  5546. if (!type) {
  5547. if (!this._unresolved.has(name)) {
  5548. const moduleName = name.split('.').shift();
  5549. if (this._registry.has(moduleName) && moduleName !== '__main__') {
  5550. this.emit('resolve', name);
  5551. }
  5552. const type = this._createType(name, class {});
  5553. this._unresolved.set(name, type);
  5554. }
  5555. type = this._unresolved.get(name);
  5556. }
  5557. return type;
  5558. }
  5559. invoke(target, args) {
  5560. if (typeof target === 'string') {
  5561. target = this.resolve(target);
  5562. }
  5563. if (target) {
  5564. if (target.__class__ === this._builtins.type) {
  5565. if (target.prototype && target.prototype.__class__ === target) {
  5566. return Reflect.construct(target, args);
  5567. }
  5568. const obj = Object.create(target);
  5569. if (obj.__init__ && typeof obj.__init__ === 'function') {
  5570. obj.__init__.apply(obj, args);
  5571. }
  5572. return obj;
  5573. }
  5574. else if (target.__class__ === this._builtins.function) {
  5575. if (target.__call__) {
  5576. return target.__call__(args);
  5577. }
  5578. return target.apply(null, args);
  5579. }
  5580. }
  5581. throw new python.Error('Unsupported invoke target.');
  5582. }
  5583. call(target, name, args, context) {
  5584. const callTarget = this.target(target, context);
  5585. const callArguments = args.map((argument) => this.expression(argument, context));
  5586. if (!callTarget || (name !== null && !callTarget[name])) {
  5587. if (name === '__new__' && callArguments.length === 1 && callArguments[0] == callTarget) {
  5588. name = null;
  5589. callArguments.shift();
  5590. }
  5591. else {
  5592. const format = (expression) => {
  5593. if (expression.type == 'id') {
  5594. return expression.value;
  5595. }
  5596. if (expression.type == '.') {
  5597. return format(expression.target) + '.' + format(expression.member);
  5598. }
  5599. return null;
  5600. };
  5601. const targetName = format(target) + '.' + name;
  5602. throw new python.Error("Unknown function '" + targetName + "'.");
  5603. }
  5604. }
  5605. const func = name ? callTarget[name] : callTarget;
  5606. if (func.__class__ === this._builtins.type) {
  5607. if (func.prototype && func.prototype.__class__ === func) {
  5608. return Reflect.construct(func, args);
  5609. }
  5610. const obj = Object.create(func);
  5611. obj.__class__ = func;
  5612. if (obj.__init__ && typeof obj.__init__ === 'function') {
  5613. obj.__init__.apply(obj, args);
  5614. }
  5615. return obj;
  5616. }
  5617. if (func.__class__ === this._builtins.function) {
  5618. if (func.__call__) {
  5619. return func.__call__(callArguments);
  5620. }
  5621. }
  5622. if (func.__class__ === this._builtins.method) {
  5623. if (func.__call__) {
  5624. return func.__call__([ callTarget ].concat(callArguments));
  5625. }
  5626. }
  5627. if (typeof func === 'function') {
  5628. return func.apply(callTarget, callArguments);
  5629. }
  5630. throw new python.Error("Unsupported call expression.");
  5631. }
  5632. apply(method, args, context) {
  5633. const locals = Array.prototype.slice.call(args);
  5634. context = new python.Execution.Context(context.globals, {});
  5635. for (const parameter of method.parameters) {
  5636. let value = locals.shift();
  5637. if (value === undefined && parameter.initializer) {
  5638. value = this.expression(parameter.initializer, context);
  5639. }
  5640. context.set(parameter.name, value);
  5641. }
  5642. return this.block(method.body.statements, context);
  5643. }
  5644. block(statements, context) {
  5645. statements = Array.prototype.slice.call(statements);
  5646. while (statements.length > 0) {
  5647. const statement = statements.shift();
  5648. const value = this.statement(statement, context);
  5649. if (value !== undefined) {
  5650. return value;
  5651. }
  5652. }
  5653. return undefined;
  5654. }
  5655. statement(statement, context) {
  5656. switch (statement.type) {
  5657. case 'pass': {
  5658. break;
  5659. }
  5660. case 'return': {
  5661. return this.expression(statement.expression, context);
  5662. }
  5663. case 'def': {
  5664. const module = context.get('__name__');
  5665. const self = this;
  5666. const parent = context.get('__class__');
  5667. const type = (parent === this._builtins.module) ? this._builtins.function : this._builtins.method;
  5668. const func = {
  5669. __class__: type,
  5670. __globals__: context,
  5671. __module__: module,
  5672. __name__: statement.name,
  5673. __code__: statement,
  5674. __call__: function(args) {
  5675. return self.apply(this.__code__, args, this.__globals__);
  5676. }
  5677. };
  5678. context.set(statement.name, func);
  5679. break;
  5680. }
  5681. case 'class': {
  5682. const bases = statement.bases.map((arg) => this.expression(arg, context));
  5683. if (bases.length > 1) {
  5684. throw new python.Error("Unsupported multiple bases for class '" + statement.name + "'.");
  5685. }
  5686. const base = bases.length === 1 ? bases[0] : null;
  5687. const name = context.get('__name__') + '.' + statement.name;
  5688. const value = this._createType(name, base ? class extends base {} : class {});
  5689. value.__bases__ = bases;
  5690. context.set(statement.name, value);
  5691. this.block(statement.body.statements, new python.Execution.Context(context.globals, value.prototype));
  5692. break;
  5693. }
  5694. case 'var': {
  5695. context.set(statement.name, statement.initializer ? this.expression(statement.initializer, context) : undefined);
  5696. break;
  5697. }
  5698. case '=': {
  5699. this.expression(statement, context);
  5700. break;
  5701. }
  5702. case 'if': {
  5703. const condition = this.expression(statement.condition, context);
  5704. if (condition === true || condition) {
  5705. const value = this.block(statement.then.statements, context);
  5706. if (value !== undefined) {
  5707. return value;
  5708. }
  5709. break;
  5710. }
  5711. else if (condition === false) {
  5712. const value = this.block(statement.else.statements, context);
  5713. if (value !== undefined) {
  5714. return value;
  5715. }
  5716. break;
  5717. }
  5718. throw new python.Error("Unsupported condition.");
  5719. }
  5720. case 'for': {
  5721. if (statement.target.length == 1 &&
  5722. statement.variable.length === 1 && statement.variable[0].type === 'id') {
  5723. const range = this.expression(statement.target[0], context);
  5724. const variable = statement.variable[0];
  5725. for (const current of range) {
  5726. this.statement({ type: '=', target: variable, expression: { type: 'number', value: current } }, context);
  5727. const value = this.block(statement.body.statements, context);
  5728. if (value !== undefined) {
  5729. return value;
  5730. }
  5731. }
  5732. break;
  5733. }
  5734. throw new python.Error("Unsupported 'for' statement.");
  5735. }
  5736. case 'while': {
  5737. const condition = this.expression(statement.condition, context);
  5738. if (condition) {
  5739. const value = this.block(statement.body.statements, context);
  5740. if (value !== undefined) {
  5741. return value;
  5742. }
  5743. }
  5744. break;
  5745. }
  5746. case 'with': {
  5747. const items = [];
  5748. for (const item of statement.item) {
  5749. items.push(this.expression(item.expression, context));
  5750. }
  5751. for (const item of items) {
  5752. if (item.__enter__ && item.__enter__.__call__) {
  5753. item.__enter__.__call__([ item ]);
  5754. }
  5755. }
  5756. const value = this.block(statement.body.statements, context);
  5757. for (const item of items) {
  5758. if (item.__exit__ && item.__exit__.__call__) {
  5759. item.__exit__.__call__([ item ]);
  5760. }
  5761. }
  5762. if (value !== undefined) {
  5763. return value;
  5764. }
  5765. break;
  5766. }
  5767. case 'call': {
  5768. this.expression(statement, context);
  5769. break;
  5770. }
  5771. case 'import': {
  5772. for (const alias of statement.names) {
  5773. let module = this.__import__(alias.name, context);
  5774. if (alias.asname) {
  5775. const bits = alias.name.split('.').reverse();
  5776. bits.pop();
  5777. while (bits.length > 0) {
  5778. module = module[bits.pop()];
  5779. }
  5780. context.set(alias.asname, module);
  5781. }
  5782. else {
  5783. context.set(alias.name.split('.')[0], module);
  5784. }
  5785. }
  5786. break;
  5787. }
  5788. case 'import_from': {
  5789. const fromlist = statement.names.map((name) => name.name);
  5790. const module = this.__import__(statement.module, context.globals, context.locals, fromlist, statement.level);
  5791. for (const entry of statement.names) {
  5792. const name = entry.name;
  5793. const asname = entry.asname ? entry.asname : null;
  5794. if (!module[name]) {
  5795. throw new python.Error("Cannot import '" + name + "' from '" + statement.module + "'.");
  5796. }
  5797. context.set(asname ? asname : name, module[name]);
  5798. }
  5799. break;
  5800. }
  5801. case 'string': {
  5802. break;
  5803. }
  5804. default: {
  5805. throw new python.Error("Unsupported statement '" + statement.type + "'.");
  5806. }
  5807. }
  5808. return undefined;
  5809. }
  5810. expression(expression, context) {
  5811. const self = context.get('self');
  5812. switch (expression.type) {
  5813. case '=': {
  5814. const target = expression.target;
  5815. if (target.type === 'id') {
  5816. context.set(target.value, this.expression(expression.expression, context));
  5817. return undefined;
  5818. }
  5819. else if (target.type === '[]') {
  5820. if (target.target.type === 'id' &&
  5821. target.arguments.type === 'list' &&
  5822. target.arguments.value.length === 1) {
  5823. const index = this.expression(target.arguments.value[0], context);
  5824. if (target.target.value === '__annotations__') {
  5825. context.set(target.target.value, context.get(target.target.value) || {});
  5826. }
  5827. const obj = context.get(target.target.value);
  5828. const value = this.expression(expression.expression, context);
  5829. if (obj instanceof Map) {
  5830. obj.set(index, value);
  5831. }
  5832. else {
  5833. obj[index] = value;
  5834. }
  5835. return undefined;
  5836. }
  5837. }
  5838. else if (target.type === '.' &&
  5839. target.member.type === 'id') {
  5840. this.expression(target.target, context)[target.member.value] = this.expression(expression.expression, context);
  5841. return undefined;
  5842. }
  5843. else if (target.type === 'tuple') {
  5844. context.target.push(target.value);
  5845. const value = this.expression(expression.expression, context);
  5846. context.target.pop();
  5847. if (target.value.every((item) => item.type === 'id')) {
  5848. if (target.value.length < value.length) {
  5849. throw new python.Error('ValueError: too many values to unpack (expected ' + target.value.length + ', actual ' + value.length + ').');
  5850. }
  5851. if (target.value.length > value.length) {
  5852. throw new python.Error('ValueError: not enough values to unpack (expected ' + target.value.length + ', actual ' + value.length + ').');
  5853. }
  5854. for (let i = 0; i < value.length; i++) {
  5855. context.set(target.value[i].value, value[i]);
  5856. }
  5857. return undefined;
  5858. }
  5859. }
  5860. break;
  5861. }
  5862. case 'list': {
  5863. return expression.value.map((item) => this.expression(item, context));
  5864. }
  5865. case 'string': {
  5866. return expression.value.substring(1, expression.value.length - 1);
  5867. }
  5868. case 'number': {
  5869. return Number(expression.value);
  5870. }
  5871. case '[]': {
  5872. if (expression.target.type === 'id' &&
  5873. expression.arguments.type === 'list' &&
  5874. expression.arguments.value.length === 1) {
  5875. if (context.get(expression.target.value)) {
  5876. const index = this.expression(expression.arguments.value[0], context);
  5877. const target = context.get(expression.target.value);
  5878. if (target instanceof Map) {
  5879. return target.get(index);
  5880. }
  5881. return target[index < 0 ? target.length + index : index];
  5882. }
  5883. }
  5884. const target = this.expression(expression.target, context);
  5885. if (target && expression.arguments.type === 'list' &&
  5886. (target.__class__ === this._typing._TupleType ||
  5887. target.__class__ === this._typing._SpecialGenericAlias ||
  5888. target.__class__ === this._typing._SpecialForm)) {
  5889. const type = Object.assign({}, target);
  5890. type.__args__ = expression.arguments.value.map((arg) => this.expression(arg, context));
  5891. return type;
  5892. }
  5893. if (expression.arguments.type === 'list' && expression.arguments.value.length === 1) {
  5894. const index = this.expression(expression.arguments.value[0], context);
  5895. if (target instanceof Map) {
  5896. return target.get(index);
  5897. }
  5898. return target[index < 0 ? target.length + index : index];
  5899. }
  5900. break;
  5901. }
  5902. case '.': {
  5903. if (expression.member.type == 'id') {
  5904. const target = this.target(expression.target, context);
  5905. return target[expression.member.value];
  5906. }
  5907. throw new python.Error("Unsupported field expression.");
  5908. }
  5909. case 'call': {
  5910. if (expression.target.type === 'id' && expression.target.value === 'unchecked_cast' && expression.arguments.length === 2) {
  5911. return this.expression(expression.arguments[1], context);
  5912. }
  5913. if (expression.target.type === '.') {
  5914. return this.call(expression.target.target, expression.target.member.value, expression.arguments, context);
  5915. }
  5916. return this.call(expression.target, null, expression.arguments, context);
  5917. }
  5918. case 'id': {
  5919. switch (expression.value) {
  5920. case 'self': return self;
  5921. case 'None': return null;
  5922. case 'True': return true;
  5923. case 'False': return false;
  5924. default: {
  5925. const type = (value) => {
  5926. return value &&
  5927. (value.__class__ === this._builtins.type ||
  5928. value.__class__ === this._typing._TupleType ||
  5929. value.__class__ === this._typing._SpecialGenericAlias ||
  5930. value.__class__ === this._typing._SpecialForm);
  5931. };
  5932. const builtin = this._builtins[expression.value];
  5933. if (type(builtin)) {
  5934. return builtin;
  5935. }
  5936. const value = context.get(expression.value);
  5937. if (value === undefined) {
  5938. const typing = this._typing[expression.value];
  5939. if (type(typing)) {
  5940. return typing;
  5941. }
  5942. }
  5943. return value;
  5944. }
  5945. }
  5946. }
  5947. case 'tuple': {
  5948. return expression.value.map((expression) => this.expression(expression, context));
  5949. }
  5950. case 'dict': {
  5951. const dict = {};
  5952. for (const pair of expression.value) {
  5953. if (pair.type !== 'pair') {
  5954. throw new python.Error("Unsupported dict item type '" + pair.type + "'.");
  5955. }
  5956. const key = this.expression(pair.key, context);
  5957. const value = this.expression(pair.value, context);
  5958. dict[key] = value;
  5959. }
  5960. return dict;
  5961. }
  5962. case 'unary': {
  5963. switch (expression.op) {
  5964. case '-': {
  5965. return -this.expression(expression.operand, context);
  5966. }
  5967. default: {
  5968. throw new python.Error("Unsupported unary expression '" + expression.op + "'.");
  5969. }
  5970. }
  5971. }
  5972. default: {
  5973. throw new python.Error("Unsupported expression '" + expression.type + "'.");
  5974. }
  5975. }
  5976. return undefined;
  5977. }
  5978. target(expression, context) {
  5979. let current = expression;
  5980. let path = [];
  5981. for (;;) {
  5982. if (current.type === '.' && current.member && current.member.type === 'id') {
  5983. path.push(current.member.value);
  5984. current = current.target;
  5985. }
  5986. else if (current.type === 'id' && current.value !== 'self' && current.value !== 'CONSTANTS') {
  5987. path.push(current.value);
  5988. break;
  5989. }
  5990. else {
  5991. path = null;
  5992. break;
  5993. }
  5994. }
  5995. if (path) {
  5996. let target = null;
  5997. for (let i = path.length - 1; i >= 0; i--) {
  5998. target = target ? target[path[i]] : context.get(path[i]);
  5999. if (!target) {
  6000. break;
  6001. }
  6002. }
  6003. if (!target) {
  6004. path.reverse();
  6005. const name = path.join('.');
  6006. const file = path.join('/') + '.py';
  6007. if (this._sources.has(file)) {
  6008. target = this.import(name);
  6009. }
  6010. else {
  6011. target = this.resolve(name);
  6012. }
  6013. }
  6014. return target;
  6015. }
  6016. return this.expression(expression, context);
  6017. }
  6018. add(name, source) {
  6019. this._sources.set(name, source);
  6020. }
  6021. on(event, listener) {
  6022. const value = this._events.get(event) || [];
  6023. value.push(listener);
  6024. this._events.set(event, value);
  6025. }
  6026. emit(event, ...args) {
  6027. if (this._events.has(event)) {
  6028. for (const callback of this._events.get(event)) {
  6029. callback(this, ...args);
  6030. }
  6031. }
  6032. }
  6033. register(name, value) {
  6034. if (!this._registry.has(name)) {
  6035. value = value || new (this._registry.get('builtins').module)(name);
  6036. this._registry.set(name, value);
  6037. let current = name;
  6038. for (;;) {
  6039. const index = current.lastIndexOf('.');
  6040. if (index === -1) {
  6041. break;
  6042. }
  6043. const child = current.substring(index + 1);
  6044. current = current.substring(0, index);
  6045. const parent = this.register(current);
  6046. parent[child] = value;
  6047. value = parent;
  6048. }
  6049. }
  6050. return this._registry.get(name);
  6051. }
  6052. registerFunction(name, value) {
  6053. const parts = name.split('.');
  6054. value.__class__ = this._builtins.function;
  6055. value.__name__ = parts.pop();
  6056. value.__module__ = parts.join('.');
  6057. const module = this.register(value.__module__);
  6058. if (module[name]) {
  6059. throw new python.Error("Function '" + name + "' is already registered.");
  6060. }
  6061. module[value.__name__] = value;
  6062. return value;
  6063. }
  6064. _createType(name, value) {
  6065. const parts = name.split('.');
  6066. value.__class__ = this._builtins.type;
  6067. value.__name__ = parts.pop();
  6068. value.__module__ = parts.join('.');
  6069. value.prototype.__class__ = value;
  6070. return value;
  6071. }
  6072. registerType(name, value) {
  6073. value = this._createType(name, value);
  6074. const parts = name.split('.');
  6075. const memberName = parts.pop();
  6076. const moduleName = parts.join('.');
  6077. const module = this.register(moduleName);
  6078. if (module[memberName]) {
  6079. throw new python.Error("Class '" + memberName + "' is already registered.");
  6080. }
  6081. module[memberName] = value;
  6082. return value;
  6083. }
  6084. };
  6085. python.Execution.Context = class {
  6086. constructor(globals, locals) {
  6087. this.globals = globals;
  6088. this.locals = locals;
  6089. }
  6090. set(name, value) {
  6091. if (this.locals) {
  6092. this.locals[name] = value;
  6093. }
  6094. else {
  6095. this.globals[name] = value;
  6096. }
  6097. }
  6098. get(name) {
  6099. if (this.locals && name in this.locals) {
  6100. return this.locals[name];
  6101. }
  6102. if (name in this.globals) {
  6103. return this.globals[name];
  6104. }
  6105. return undefined;
  6106. }
  6107. get target() {
  6108. this._target = this._target || [];
  6109. return this._target;
  6110. }
  6111. };
  6112. python.BinaryReader = class {
  6113. constructor(buffer) {
  6114. this._buffer = buffer;
  6115. this._length = buffer.length;
  6116. this._position = 0;
  6117. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  6118. this._utf8Decoder = new TextDecoder('utf-8');
  6119. this._asciiDecoder = new TextDecoder('ascii');
  6120. }
  6121. get position() {
  6122. return this._position;
  6123. }
  6124. get length() {
  6125. return this._length;
  6126. }
  6127. seek(position) {
  6128. this._position = position >= 0 ? position : this._length + position;
  6129. if (this._position > this._buffer.length) {
  6130. throw new Error('Expected ' + (this._position - this._buffer.length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  6131. }
  6132. }
  6133. skip(offset) {
  6134. this._position += offset;
  6135. if (this._position > this._buffer.length) {
  6136. throw new python.Error('Expected ' + (this._position - this._buffer.length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  6137. }
  6138. }
  6139. stream(length) {
  6140. const buffer = this.read(length);
  6141. return new python.BinaryReader(buffer);
  6142. }
  6143. peek(length) {
  6144. const position = this._position;
  6145. length = length !== undefined ? length : this._length - this._position;
  6146. this.skip(length);
  6147. const end = this._position;
  6148. this.skip(-length);
  6149. if (position === 0 && length === this._length) {
  6150. return this._buffer;
  6151. }
  6152. return this._buffer.subarray(position, end);
  6153. }
  6154. read(length) {
  6155. const position = this._position;
  6156. length = length !== undefined ? length : this._length - this._position;
  6157. this.skip(length);
  6158. if (position === 0 && length === this._length) {
  6159. return this._buffer;
  6160. }
  6161. return this._buffer.subarray(position, this._position);
  6162. }
  6163. byte() {
  6164. const position = this._position;
  6165. this.skip(1);
  6166. return this._view.getUint8(position);
  6167. }
  6168. uint16() {
  6169. const position = this._position;
  6170. this.skip(2);
  6171. return this._view.getUint16(position, true);
  6172. }
  6173. int32() {
  6174. const position = this._position;
  6175. this.skip(4);
  6176. return this._view.getInt32(position, true);
  6177. }
  6178. uint32() {
  6179. const position = this._position;
  6180. this.skip(4);
  6181. return this._view.getUint32(position, true);
  6182. }
  6183. int64() {
  6184. const position = this._position;
  6185. this.skip(8);
  6186. return this._view.getInt64(position, true).toNumber();
  6187. }
  6188. float64() {
  6189. const position = this._position;
  6190. this.skip(8);
  6191. return this._view.getFloat64(position, false);
  6192. }
  6193. string(size, encoding) {
  6194. const data = this.read(size);
  6195. return (encoding == 'utf-8') ?
  6196. this._utf8Decoder.decode(data) :
  6197. this._asciiDecoder.decode(data);
  6198. }
  6199. line() {
  6200. const index = this._buffer.indexOf(0x0A, this._position);
  6201. if (index == -1) {
  6202. throw new python.Error("Could not find end of line.");
  6203. }
  6204. const size = index - this._position;
  6205. const text = this.string(size, 'ascii');
  6206. this.skip(1);
  6207. return text;
  6208. }
  6209. };
  6210. python.StreamReader = class {
  6211. constructor(stream) {
  6212. this._stream = stream;
  6213. this._length = stream.length;
  6214. this._position = 0;
  6215. this._utf8Decoder = new TextDecoder('utf-8');
  6216. this._asciiDecoder = new TextDecoder('ascii');
  6217. }
  6218. get position() {
  6219. return this._position;
  6220. }
  6221. get length() {
  6222. return this._length;
  6223. }
  6224. seek(position) {
  6225. this._stream.seek(position);
  6226. this._position = this._stream.position;
  6227. }
  6228. skip(offset) {
  6229. this._position += offset;
  6230. if (this._position > this._length) {
  6231. throw new python.Error('Expected ' + (this._position - this._length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  6232. }
  6233. }
  6234. stream(length) {
  6235. this._stream.seek(this._position);
  6236. this.skip(length);
  6237. return this._stream.stream(length);
  6238. }
  6239. peek(length) {
  6240. this._stream.seek(this._position);
  6241. return this._stream.peek(length);
  6242. }
  6243. read(length) {
  6244. this._stream.seek(this._position);
  6245. this.skip(length);
  6246. return this._stream.read(length);
  6247. }
  6248. byte() {
  6249. const position = this._fill(1);
  6250. return this._view.getUint8(position);
  6251. }
  6252. uint16() {
  6253. const position = this._fill(2);
  6254. return this._view.getUint16(position, true);
  6255. }
  6256. int32() {
  6257. const position = this._fill(4);
  6258. return this._view.getInt32(position, true);
  6259. }
  6260. uint32() {
  6261. const position = this._fill(4);
  6262. return this._view.getUint32(position, true);
  6263. }
  6264. int64() {
  6265. const position = this._fill(8);
  6266. return this._view.getInt64(position, true).toNumber();
  6267. }
  6268. float64() {
  6269. const position = this._fill(8);
  6270. return this._view.getFloat64(position, true);
  6271. }
  6272. string(size, encoding) {
  6273. const data = this.read(size);
  6274. return (encoding == 'utf-8') ?
  6275. this._utf8Decoder.decode(data) :
  6276. this._asciiDecoder.decode(data);
  6277. }
  6278. line() {
  6279. let position = this._fill(0);
  6280. let index = this._buffer.indexOf(0x0A, position);
  6281. if (index == -1) {
  6282. const size = Math.min(0x1000000, this._stream.length - this._position);
  6283. this._fill(size);
  6284. this.skip(-size);
  6285. position = this._fill(0);
  6286. index = this._buffer.indexOf(0x0A, position);
  6287. if (index == -1) {
  6288. throw new python.Error("Could not find end of line.");
  6289. }
  6290. }
  6291. const size = index - position;
  6292. const text = this.string(size, 'ascii');
  6293. this.skip(1);
  6294. return text;
  6295. }
  6296. _fill(length) {
  6297. if (this._position + length > this._length) {
  6298. throw new Error('Expected ' + (this._position + length - this._length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  6299. }
  6300. if (!this._buffer || this._position < this._offset || this._position + length > this._offset + this._buffer.length) {
  6301. this._offset = this._position;
  6302. this._stream.seek(this._offset);
  6303. this._buffer = this._stream.read(Math.min(0x10000000, this._length - this._offset));
  6304. this._view = new DataView(this._buffer.buffer, this._buffer.byteOffset, this._buffer.byteLength);
  6305. }
  6306. const position = this._position;
  6307. this._position += length;
  6308. return position - this._offset;
  6309. }
  6310. };
  6311. python.Error = class extends Error {
  6312. constructor(message) {
  6313. super(message);
  6314. this.name = 'Python Error';
  6315. }
  6316. };
  6317. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  6318. module.exports.Execution = python.Execution;
  6319. }