python.js 293 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435
  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. this._modules = new dict();
  1574. this._registry = new Map();
  1575. const module = class {
  1576. constructor(name) {
  1577. this.__name__ = name;
  1578. }
  1579. };
  1580. this._builtins = this.register('builtins', new module('builtins'));
  1581. this._registry.set('__builtin__', this._builtins);
  1582. this.registerType('builtins.type', class {}).__class__ = this._builtins.type;
  1583. this.registerType('builtins.module', module);
  1584. this.registerType('builtins.method', class {});
  1585. this.registerType('builtins.function', class {});
  1586. this.import('builtins');
  1587. this.registerType('builtins.builtin_function_or_method', class {});
  1588. this._typing = this.register('typing');
  1589. this.register('_codecs');
  1590. this.register('argparse');
  1591. this.register('collections');
  1592. this.register('copy_reg');
  1593. this.register('cuml');
  1594. this.register('gensim');
  1595. this.register('io');
  1596. this.register('joblib');
  1597. this.register('keras');
  1598. this.register('lightgbm');
  1599. this.register('nolearn');
  1600. const math = this.register('math');
  1601. math.inf = Infinity;
  1602. const numpy = this.register('numpy');
  1603. this.register('pickle');
  1604. this.register('sklearn');
  1605. const torch = this.register('torch');
  1606. const torch_storage = this.register('torch.storage');
  1607. const torch_nn_parameter = this.register('torch.nn.parameter');
  1608. this.register('torch.ops');
  1609. this.register('torch.ops.torchvision');
  1610. this.register('torch.ops.torchaudio');
  1611. this.register('torch.ops._caffe2');
  1612. this.register('torchvision');
  1613. this.register('__torch__');
  1614. this.register('sys').modules = this._modules;
  1615. this.register('xgboost');
  1616. this.registerType('builtins.dict', dict);
  1617. this.registerType('builtins.list', class {});
  1618. this.registerType('builtins.number', class {});
  1619. this.registerFunction('builtins.__import__', function(name, globals, locals, fromlist, level) {
  1620. return execution.__import__(name, globals, locals, fromlist, level);
  1621. });
  1622. this.registerFunction('builtins.bool', function(value) {
  1623. if (value) {
  1624. if (value.__bool__) {
  1625. return value.__bool__();
  1626. }
  1627. if (value.__len__) {
  1628. return value.__len__() > 0;
  1629. }
  1630. }
  1631. return false;
  1632. });
  1633. this.registerFunction('builtins.int', function(value) {
  1634. if (value) {
  1635. if (value.__int__) {
  1636. return value.__int__();
  1637. }
  1638. if (Number.isInteger(value)) {
  1639. return value;
  1640. }
  1641. }
  1642. return NaN;
  1643. });
  1644. this.registerFunction('builtins.float', function(value) {
  1645. if (value) {
  1646. if (value.__float__) {
  1647. return value.__float__();
  1648. }
  1649. if (Number(value) === value) {
  1650. return value;
  1651. }
  1652. }
  1653. return NaN;
  1654. });
  1655. this.registerFunction('builtins.str', function(value) {
  1656. if (value) {
  1657. if (value.__str__) {
  1658. return value.__str__();
  1659. }
  1660. }
  1661. return JSON.stringify(value);
  1662. });
  1663. this.registerType('builtins.object', class {});
  1664. this.registerType('builtins.tuple', class extends Array {
  1665. constructor(items) {
  1666. super(items ? items.length : 0);
  1667. if (items) {
  1668. for (let i = 0; i < items.length; i++) {
  1669. this[i] = items[i];
  1670. }
  1671. }
  1672. }
  1673. });
  1674. this.registerFunction('builtins.long', this.builtins.int);
  1675. this.registerFunction('builtins.print', function() {});
  1676. this.registerFunction('builtins.unicode', function(/* value */) {
  1677. throw new python.Error('Not implemented.');
  1678. });
  1679. this.registerType('builtins.Warning', class {});
  1680. this.registerType('builtins.FutureWarning', class extends this._builtins.Warning {});
  1681. this.registerType('typing._Final', class {});
  1682. this.registerType('typing._SpecialForm', class extends this._typing._Final {});
  1683. this.registerType('typing._BaseGenericAlias', class extends this._typing._Final {});
  1684. this.registerType('typing._GenericAlias', class extends this._typing._BaseGenericAlias {});
  1685. this.registerType('typing._SpecialGenericAlias', class extends this._typing._BaseGenericAlias {});
  1686. this.registerType('typing._TupleType', class extends this._typing._SpecialGenericAlias {});
  1687. this._typing.Optional = Reflect.construct(this._typing._SpecialForm, []);
  1688. this._typing.List = Reflect.construct(this._typing._SpecialGenericAlias, []);
  1689. this._typing.Dict = Reflect.construct(this._typing._SpecialGenericAlias, []);
  1690. this._typing.Tuple = Reflect.construct(this._typing._TupleType, []);
  1691. this._typing.Any = Reflect.construct(this._typing._SpecialForm, []);
  1692. this.registerType('argparse.Namespace', class {
  1693. constructor(args) {
  1694. this.args = args;
  1695. }
  1696. });
  1697. this.registerType('collections.deque', class extends Array {
  1698. constructor(iterable) {
  1699. super();
  1700. if (Array.isArray(iterable)) {
  1701. for (const value of iterable) {
  1702. this.push(value);
  1703. }
  1704. }
  1705. }
  1706. });
  1707. this.registerType('collections.OrderedDict', class extends Map {
  1708. constructor(items) {
  1709. super();
  1710. if (items) {
  1711. for (const pair of items) {
  1712. this.__setitem__(pair[0], pair[1]);
  1713. }
  1714. }
  1715. }
  1716. __setitem__(key, value) {
  1717. this.set(key, value);
  1718. }
  1719. });
  1720. this.registerType('cuml.common.array_descriptor.CumlArrayDescriptorMeta', class {});
  1721. this.registerType('cuml.ensemble.randomforestclassifier.RandomForestClassifier', class {});
  1722. this.registerType('cuml.raft.common.handle.Handle', class {
  1723. __setstate__(state) {
  1724. this._handle = state;
  1725. }
  1726. });
  1727. this.registerType('dnnlib.tflib.network.Network', class {});
  1728. this.registerType('dnnlib.util.EasyDict', class extends dict {});
  1729. this.registerType('haiku._src.data_structures.FlatMapping', class {
  1730. constructor(dict) {
  1731. Object.assign(this, dict);
  1732. }
  1733. });
  1734. this.registerType('haiku._src.data_structures.frozendict', class {
  1735. constructor(obj) {
  1736. Object.assign(this, obj);
  1737. }
  1738. });
  1739. this.registerType('hmmlearn.hmm.MultinomialHMM', class {
  1740. __setstate__(state) {
  1741. Object.assign(this, state);
  1742. }
  1743. });
  1744. this.registerType('hmmlearn.base.ConvergenceMonitor', class {
  1745. __setstate__(state) {
  1746. Object.assign(this, state);
  1747. }
  1748. });
  1749. this.registerType('io.BytesIO', class {
  1750. constructor(buf, mode) {
  1751. this.mode = mode || 'r';
  1752. this._buf = this.mode === 'w' ? null : buf;
  1753. this._point = 0;
  1754. }
  1755. seek(offset) {
  1756. this._point = offset;
  1757. }
  1758. read(size) {
  1759. const start = this._point;
  1760. this._point = size !== undefined ? start + size : this._buf.length;
  1761. return this._buf.subarray(start, this._point);
  1762. }
  1763. write(data) {
  1764. const src = this._buf || new Uint8Array();
  1765. this._point = src.length + data.length;
  1766. this._buf = new Uint8Array(this._point);
  1767. this._buf.set(src, 0);
  1768. this._buf.set(data, src.length);
  1769. }
  1770. });
  1771. this.registerType('numpy.dtype', class {
  1772. constructor(obj, align, copy) {
  1773. if (typeof obj === 'string' && (obj.startsWith('<') || obj.startsWith('>'))) {
  1774. this.byteorder = obj[0];
  1775. obj = obj.substring(1);
  1776. }
  1777. else {
  1778. this.byteorder = '=';
  1779. }
  1780. switch (obj) {
  1781. case 'b1': case 'bool': this.itemsize = 1; this.kind = 'b'; break;
  1782. case 'i1': case 'int8': this.itemsize = 1; this.kind = 'i'; break;
  1783. case 'i2': case 'int16': this.itemsize = 2; this.kind = 'i'; break;
  1784. case 'i4': case 'int32': this.itemsize = 4; this.kind = 'i'; break;
  1785. case 'i8': case 'int64': case 'int': this.itemsize = 8; this.kind = 'i'; break;
  1786. case 'u1': case 'uint8': this.itemsize = 1; this.kind = 'u'; break;
  1787. case 'u2': case 'uint16': this.itemsize = 2; this.kind = 'u'; break;
  1788. case 'u4': case 'uint32': this.itemsize = 4; this.kind = 'u'; break;
  1789. case 'u8': case 'uint64': case 'uint': this.itemsize = 8; this.kind = 'u'; break;
  1790. case 'f2': case 'float16': this.itemsize = 2; this.kind = 'f'; break;
  1791. case 'f4': case 'float32': this.itemsize = 4; this.kind = 'f'; break;
  1792. case 'f8': case 'float64': case 'float': this.itemsize = 8; this.kind = 'f'; break;
  1793. case 'c8': case 'complex64': this.itemsize = 8; this.kind = 'c'; break;
  1794. case 'c16': case 'complex128': case 'complex': this.itemsize = 16; this.kind = 'c'; break;
  1795. case 'M8': case 'M': this.itemsize = 8; this.kind = 'M'; break;
  1796. default:
  1797. if (obj.startsWith('V')) {
  1798. this.itemsize = parseInt(obj.substring(1), 10);
  1799. this.kind = 'V';
  1800. }
  1801. else if (obj.startsWith('O')) {
  1802. this.itemsize = obj === 'O' ? 8 : parseInt(obj.substring(1), 10);
  1803. this.kind = 'O';
  1804. }
  1805. else if (obj.startsWith('S')) {
  1806. this.itemsize = parseInt(obj.substring(1), 10);
  1807. this.kind = 'S';
  1808. }
  1809. else if (obj.startsWith('U')) { // Unicode string
  1810. this.kind = 'U';
  1811. this.itemsize = 4 * parseInt(obj.substring(1), 10);
  1812. }
  1813. else {
  1814. throw new python.Error("Unsupported dtype '" + obj.toString() + "'.");
  1815. }
  1816. break;
  1817. }
  1818. if (align) {
  1819. this.align = align;
  1820. }
  1821. if (copy) {
  1822. this.copy = copy;
  1823. }
  1824. }
  1825. get str() {
  1826. return (this.byteorder === '=' ? '<' : this.byteorder) + this.kind + this.itemsize.toString();
  1827. }
  1828. get name() {
  1829. switch (this.kind) {
  1830. case 'V': return 'void' + (this.itemsize === 0 ? '' : (this.itemsize * 8).toString());
  1831. case 'S': return 'bytes' + (this.itemsize === 0 ? '' : (this.itemsize * 8).toString());
  1832. case 'U': return 'str' + (this.itemsize === 0 ? '' : (this.itemsize * 8).toString());
  1833. case 'M': return 'datetime64';
  1834. case 'b': return 'bool';
  1835. default: return this.__name__;
  1836. }
  1837. }
  1838. __setstate__(state) {
  1839. switch (state.length) {
  1840. case 8:
  1841. this.version = state[0];
  1842. this.byteorder = state[1];
  1843. this.subarray = state[2];
  1844. this.names = state[3];
  1845. this.fields = state[4];
  1846. this.elsize = state[5];
  1847. this.alignment = state[6];
  1848. this.int_dtypeflags = state[7];
  1849. break;
  1850. case 9:
  1851. this.version = state[0];
  1852. this.byteorder = state[1];
  1853. this.subarray = state[2];
  1854. this.names = state[3];
  1855. this.fields = state[4];
  1856. this.elsize = state[5];
  1857. this.alignment = state[6];
  1858. this.int_dtypeflags = state[7];
  1859. this.metadata = state[8];
  1860. break;
  1861. default:
  1862. throw new python.Error("Unsupported numpy.dtype setstate length '" + state.length.toString() + "'.");
  1863. }
  1864. }
  1865. get __name__() {
  1866. switch (this.kind) {
  1867. case 'b':
  1868. switch (this.itemsize) {
  1869. case 1: return 'boolean';
  1870. default: throw new python.Error("Unsupported boolean itemsize '" + this.itemsize + "'.");
  1871. }
  1872. case 'i':
  1873. switch (this.itemsize) {
  1874. case 1: return 'int8';
  1875. case 2: return 'int16';
  1876. case 4: return 'int32';
  1877. case 8: return 'int64';
  1878. default: throw new python.Error("Unsupported int itemsize '" + this.itemsize + "'.");
  1879. }
  1880. case 'u':
  1881. switch (this.itemsize) {
  1882. case 1: return 'uint8';
  1883. case 2: return 'uint16';
  1884. case 4: return 'uint32';
  1885. case 8: return 'uint64';
  1886. default: throw new python.Error("Unsupported uint itemsize '" + this.itemsize + "'.");
  1887. }
  1888. case 'f':
  1889. switch (this.itemsize) {
  1890. case 2: return 'float16';
  1891. case 4: return 'float32';
  1892. case 8: return 'float64';
  1893. default: throw new python.Error("Unsupported float itemsize '" + this.itemsize + "'.");
  1894. }
  1895. case 'c':
  1896. switch (this.itemsize) {
  1897. case 8: return 'complex64';
  1898. case 16: return 'complex128';
  1899. default: throw new python.Error("Unsupported complex itemsize '" + this.itemsize + "'.");
  1900. }
  1901. case 'S':
  1902. case 'U':
  1903. return 'string';
  1904. case 'M':
  1905. return 'datetime';
  1906. case 'O':
  1907. return 'object';
  1908. case 'V':
  1909. return 'void';
  1910. default:
  1911. throw new python.Error("Unsupported dtype kind '" + this.kind + "'.");
  1912. }
  1913. }
  1914. });
  1915. this.registerType('numpy.generic', class {});
  1916. this.registerType('numpy.inexact', class {});
  1917. this.registerType('numpy.number', class extends numpy.generic {});
  1918. this.registerType('numpy.integer', class extends numpy.number {});
  1919. this.registerType('numpy.floating', class extends numpy.inexact {});
  1920. this.registerType('numpy.float32', class extends numpy.floating {});
  1921. this.registerType('numpy.float64', class extends numpy.floating {});
  1922. this.registerType('numpy.signedinteger', class extends numpy.integer {});
  1923. this.registerType('numpy.int8', class extends numpy.signedinteger {});
  1924. this.registerType('numpy.int16', class extends numpy.signedinteger {});
  1925. this.registerType('numpy.int32', class extends numpy.signedinteger {});
  1926. this.registerType('numpy.int64', class extends numpy.signedinteger {});
  1927. this.registerType('numpy.unsignedinteger', class extends numpy.integer {});
  1928. this.registerType('numpy.uint8', class extends numpy.unsignedinteger {});
  1929. this.registerType('numpy.uint16', class extends numpy.unsignedinteger {});
  1930. this.registerType('numpy.uint32', class extends numpy.unsignedinteger {});
  1931. this.registerType('numpy.uint64', class extends numpy.unsignedinteger {});
  1932. this.registerType('fastai.callback.core.TrainEvalCallback', class {});
  1933. this.registerType('fastai.callback.hook._hook_inner', class {});
  1934. this.registerType('fastai.callback.hook.Hook', class {});
  1935. this.registerType('fastai.callback.hook.Hooks', class {});
  1936. this.registerType('fastai.callback.progress.ProgressCallback', class {});
  1937. this.registerType('fastai.data.core.DataLoaders', class {});
  1938. this.registerType('fastai.data.core.Datasets', class {});
  1939. this.registerType('fastai.data.core.TfmdDL', class {});
  1940. this.registerType('fastai.data.core.TfmdLists', class {});
  1941. this.registerType('fastai.data.load._FakeLoader', class {});
  1942. this.registerType('fastai.data.load._wif', class {});
  1943. this.registerType('fastai.data.transforms.Categorize', class {});
  1944. this.registerType('fastai.data.transforms.CategoryMap', class {});
  1945. this.registerType('fastai.data.transforms.IntToFloatTensor', class {});
  1946. this.registerType('fastai.data.transforms.Normalize', class {});
  1947. this.registerType('fastai.data.transforms.parent_label', class {});
  1948. this.registerType('fastai.data.transforms.ToTensor', class {});
  1949. this.registerType('fastai.imports.noop', class {});
  1950. this.registerType('fastai.layers.AdaptiveConcatPool2d', class {});
  1951. this.registerType('fastai.layers.ConvLayer', class {});
  1952. this.registerType('fastai.layers.Flatten', class {});
  1953. this.registerType('fastai.layers.MergeLayer', class {});
  1954. this.registerType('fastai.layers.PixelShuffle_ICNR', class {});
  1955. this.registerType('fastai.layers.ResBlock', class {});
  1956. this.registerType('fastai.layers.SelfAttention', class {});
  1957. this.registerType('fastai.learner.AvgLoss', class {});
  1958. this.registerType('fastai.learner.AvgMetric', class {});
  1959. this.registerType('fastai.learner.AvgSmoothLoss', class {});
  1960. this.registerType('fastai.learner.Learner', class {});
  1961. this.registerType('fastai.learner.Recorder', class {});
  1962. this.registerType('fastai.losses.CrossEntropyLossFlat', class {});
  1963. this.registerType('fastai.metrics.error_rate', class {});
  1964. this.registerType('fastai.optimizer.Adam', class {});
  1965. this.registerType('fastai.torch_core._fa_rebuild_tensor', class {});
  1966. this.registerType('fastai.torch_core.TensorBase', class {});
  1967. this.registerType('fastai.torch_core.TensorCategory', class {});
  1968. this.registerType('fastai.torch_core.TensorImage', class {});
  1969. this.registerType('fastai.vision.augment._BrightnessLogit', class {});
  1970. this.registerType('fastai.vision.augment._ContrastLogit', class {});
  1971. this.registerType('fastai.vision.augment._WarpCoord', class {});
  1972. this.registerType('fastai.vision.augment.Brightness', class {});
  1973. this.registerType('fastai.vision.augment.flip_mat', class {});
  1974. this.registerType('fastai.vision.augment.Flip', class {});
  1975. this.registerType('fastai.vision.augment.RandomResizedCropGPU', class {});
  1976. this.registerType('fastai.vision.augment.Resize', class {});
  1977. this.registerType('fastai.vision.augment.rotate_mat', class {});
  1978. this.registerType('fastai.vision.augment.zoom_mat', class {});
  1979. this.registerType('fastai.vision.core.PILImage', class {});
  1980. this.registerType('fastai.vision.learner._resnet_split', class {});
  1981. this.registerType('fastai.vision.models.unet.DynamicUnet', class {});
  1982. this.registerType('fastai.vision.models.unet.ResizeToOrig', class {});
  1983. this.registerType('fastai.vision.models.unet.UnetBlock', class {});
  1984. this.registerType('fastcore.basics.fastuple', class {});
  1985. this.registerType('fastcore.dispatch._TypeDict', class {});
  1986. this.registerType('fastcore.dispatch.TypeDispatch', class {});
  1987. this.registerType('fastcore.foundation.L', class {});
  1988. this.registerType('fastcore.transform.Pipeline', class {});
  1989. this.registerType('fastcore.transform.Transform', class {});
  1990. this.registerType('functools.partial', class {});
  1991. this.registerType('gensim.models.doc2vec.Doctag', class {});
  1992. this.registerType('gensim.models.doc2vec.Doc2Vec', class {});
  1993. this.registerType('gensim.models.doc2vec.Doc2VecTrainables', class {});
  1994. this.registerType('gensim.models.doc2vec.Doc2VecVocab', class {});
  1995. this.registerType('gensim.models.fasttext.FastText', class {});
  1996. this.registerType('gensim.models.fasttext.FastTextTrainables', class {});
  1997. this.registerType('gensim.models.fasttext.FastTextVocab', class {});
  1998. this.registerType('gensim.models.fasttext.FastTextKeyedVectors', class {});
  1999. this.registerType('gensim.models.keyedvectors.Doc2VecKeyedVectors', class {});
  2000. this.registerType('gensim.models.keyedvectors.FastTextKeyedVectors', class {});
  2001. this.registerType('gensim.models.keyedvectors.KeyedVectors', class {});
  2002. this.registerType('gensim.models.keyedvectors.Vocab', class {});
  2003. this.registerType('gensim.models.keyedvectors.Word2VecKeyedVectors', class {});
  2004. this.registerType('gensim.models.phrases.Phrases', class {});
  2005. this.registerType('gensim.models.tfidfmodel.TfidfModel', class {});
  2006. this.registerType('gensim.models.word2vec.Vocab', class {});
  2007. this.registerType('gensim.models.word2vec.Word2Vec', class {});
  2008. this.registerType('gensim.models.word2vec.Word2VecTrainables', class {});
  2009. this.registerType('gensim.models.word2vec.Word2VecVocab', class {});
  2010. this.registerType('google3.learning.deepmind.research.nbr.pbl_jax.clean_jaxline.utils.optimizers.ScaleByLarsState', class {
  2011. constructor(obj) {
  2012. Object.assign(this, obj);
  2013. }
  2014. });
  2015. this.registerType('joblib.numpy_pickle.NumpyArrayWrapper', class {
  2016. constructor(/* subtype, shape, dtype */) {
  2017. }
  2018. __setstate__(state) {
  2019. this.subclass = state.subclass;
  2020. this.dtype = state.dtype;
  2021. this.shape = state.shape;
  2022. this.order = state.order;
  2023. this.allow_mmap = state.allow_mmap;
  2024. }
  2025. __read__(unpickler) {
  2026. if (this.dtype.__name__ == 'object') {
  2027. return unpickler.load();
  2028. }
  2029. const size = this.dtype.itemsize * this.shape.reduce((a, b) => a * b, 1);
  2030. this.data = unpickler.read(size);
  2031. return execution.invoke(this.subclass, [ this.shape, this.dtype, this.data ]);
  2032. }
  2033. });
  2034. this.registerType('keras.engine.sequential.Sequential', class {});
  2035. this.registerType('lasagne.layers.conv.Conv2DLayer', class {});
  2036. this.registerType('lasagne.layers.dense.DenseLayer', class {});
  2037. this.registerType('lasagne.layers.input.InputLayer', class {});
  2038. this.registerType('lasagne.layers.pool.MaxPool2DLayer', class {});
  2039. this.registerType('lightgbm.sklearn.LGBMRegressor', class {});
  2040. this.registerType('lightgbm.sklearn.LGBMClassifier', class {});
  2041. this.registerType('lightgbm.basic.Booster', class {
  2042. constructor() {
  2043. this.average_output = false;
  2044. this.models = [];
  2045. this.loaded_parameter = '';
  2046. }
  2047. __setstate__(state) {
  2048. if (typeof state.handle === 'string') {
  2049. this.LoadModelFromString(state.handle);
  2050. return;
  2051. }
  2052. Object.assign(this, state);
  2053. }
  2054. LoadModelFromString(model_str) {
  2055. const lines = model_str.split('\n');
  2056. const signature = lines.shift() || '?';
  2057. if (signature.trim() !== 'tree') {
  2058. throw new python.Error("Invalid signature '" + signature.trim() + "'.");
  2059. }
  2060. // GBDT::LoadModelFromString() in https://github.com/microsoft/LightGBM/blob/master/src/boosting/gbdt_model_text.cpp
  2061. const key_vals = new Map();
  2062. while (lines.length > 0 && !lines[0].startsWith('Tree=')) {
  2063. const cur_line = lines.shift().trim();
  2064. if (cur_line.length > 0) {
  2065. const strs = cur_line.split('=');
  2066. if (strs.length === 1) {
  2067. key_vals.set(strs[0], '');
  2068. }
  2069. else if (strs.length === 2) {
  2070. key_vals.set(strs[0], strs[1]);
  2071. }
  2072. else if (strs.length > 2) {
  2073. if (strs[0] === "feature_names") {
  2074. key_vals.set(strs[0], cur_line.substring("feature_names=".length));
  2075. }
  2076. else if (strs[0] == 'monotone_constraints') {
  2077. key_vals.set(strs[0], cur_line.substring('monotone_constraints='.length));
  2078. }
  2079. else {
  2080. throw new python.Error('Wrong line: ' + cur_line.substring(0, Math.min(128, cur_line.length)));
  2081. }
  2082. }
  2083. }
  2084. }
  2085. const atoi = (key, value) => {
  2086. if (key_vals.has(key)) {
  2087. return parseInt(key_vals.get(key), 10);
  2088. }
  2089. if (value !== undefined) {
  2090. return value;
  2091. }
  2092. throw new python.Error('Model file does not specify ' + key + '.');
  2093. };
  2094. const list = (key, size) => {
  2095. if (key_vals.has(key)) {
  2096. const value = key_vals.get(key).split(' ');
  2097. if (value.length !== size) {
  2098. throw new python.Error('Wrong size of ' + key + '.');
  2099. }
  2100. return value;
  2101. }
  2102. throw new python.Error('Model file does not contain ' + key + '.');
  2103. };
  2104. this.version = key_vals.get('version') || '';
  2105. this.num_class = atoi('num_class');
  2106. this.num_tree_per_iteration = atoi('num_tree_per_iteration', this.num_class);
  2107. this.label_index = atoi('label_index');
  2108. this.max_feature_idx = atoi('max_feature_idx');
  2109. if (key_vals.has('average_output')) {
  2110. this.average_output = true;
  2111. }
  2112. this.feature_names = list('feature_names', this.max_feature_idx + 1);
  2113. this.feature_infos = list('feature_infos', this.max_feature_idx + 1);
  2114. if (key_vals.has('monotone_constraints')) {
  2115. this.monotone_constraints = list('monotone_constraints', this.max_feature_idx + 1);
  2116. }
  2117. if (key_vals.has('objective')) {
  2118. this.objective = key_vals.get('objective');
  2119. }
  2120. let tree = null;
  2121. while (lines.length > 0) {
  2122. const text = lines.shift();
  2123. const line = text.trim();
  2124. if (line.length === 0) {
  2125. continue;
  2126. }
  2127. if (line.startsWith('Tree=')) {
  2128. tree = { index: parseInt(line.split('=').pop(), 10) };
  2129. this.models.push(tree);
  2130. continue;
  2131. }
  2132. if (line === 'end of trees') {
  2133. break;
  2134. }
  2135. const param = line.split('=');
  2136. if (param.length !== 2) {
  2137. throw new python.Error("Invalid property '" + line + "'.");
  2138. }
  2139. const name = param[0].trim();
  2140. const value = param[1].trim();
  2141. tree[name] = value;
  2142. }
  2143. const ss = [];
  2144. let is_inparameter = false;
  2145. while (lines.length > 0) {
  2146. const text = lines.shift();
  2147. const line = text.trim();
  2148. if (line === 'parameters:') {
  2149. is_inparameter = true;
  2150. continue;
  2151. }
  2152. else if (line === 'end of parameters') {
  2153. break;
  2154. }
  2155. else if (is_inparameter) {
  2156. ss.push(line);
  2157. }
  2158. }
  2159. if (ss.length > 0) {
  2160. this.loaded_parameter = ss.join('\n');
  2161. }
  2162. }
  2163. });
  2164. this.registerFunction('megengine.functional.nn.conv2d', function() {});
  2165. this.registerFunction('megengine.functional.nn.relu', function() {});
  2166. this.registerFunction('megengine.module.qat.module.QATModule._apply_fakequant_with_observer', function() {});
  2167. this.registerFunction('megengine.functional.tensor.concat', function() {});
  2168. this.registerFunction('megengine.functional.tensor.flatten', function() {});
  2169. this.registerType('megengine.core._imperative_rt.common.CompNode', class {});
  2170. this.registerType('megengine.core._imperative_rt.ops.FakeQuant', class {});
  2171. this.registerType('megengine.core._imperative_rt.ops.GetVarShape', class {});
  2172. this.registerType('megengine.core.ops._internal.param_defs.ConvolutionV0.Mode', class {});
  2173. this.registerType('megengine.core.ops._internal.param_defs.Convolution.ComputeMode', class {});
  2174. this.registerType('megengine.module.activation.ReLU', class {});
  2175. this.registerType('megengine.module.batchnorm.BatchNorm1d', class {});
  2176. this.registerType('megengine.module.batchnorm.BatchNorm2d', class {});
  2177. this.registerType('megengine.module.conv.Conv2d', class {});
  2178. this.registerType('megengine.module.conv.ConvTranspose2d', class {});
  2179. this.registerType('megengine.module.identity.Identity', class {});
  2180. this.registerType('megengine.module.linear.Linear', class {});
  2181. this.registerType('megengine.module.module.Module', class {});
  2182. this.registerType('megengine.module.pooling.AvgPool2d', class {});
  2183. this.registerType('megengine.module.pooling.MaxPool2d', class {});
  2184. this.registerType('megengine.module.qat.concat.Concat', class {});
  2185. this.registerType('megengine.module.qat.elemwise.Elemwise', class {});
  2186. this.registerType('megengine.module.sequential.Sequential', class {});
  2187. this.registerType('megengine.quantization.fake_quant.FakeQuantize', class {});
  2188. this.registerType('megengine.quantization.utils.QParams', class {});
  2189. this.registerType('megengine.quantization.utils.QuantMode', class {});
  2190. this.registerType('megengine.quantization.observer.PassiveObserver', class {});
  2191. this.registerType('megengine.quantization.observer.MinMaxObserver', class {});
  2192. this.registerType('megengine.quantization.observer.ExponentialMovingAverageObserver', class {});
  2193. this.registerType('megengine.traced_module.expr.Apply', class {});
  2194. this.registerType('megengine.traced_module.expr.CallFunction', class {});
  2195. this.registerType('megengine.traced_module.expr.CallMethod', class {});
  2196. this.registerType('megengine.traced_module.expr.Constant', class {});
  2197. this.registerType('megengine.traced_module.expr.GetAttr', class {});
  2198. this.registerType('megengine.traced_module.expr.Input', class {});
  2199. this.registerType('megengine.traced_module.fake_quant.FakeQuantize', class {});
  2200. this.registerType('megengine.traced_module.node.ModuleNode', class {});
  2201. this.registerType('megengine.traced_module.node.NodeMixin', class {});
  2202. this.registerType('megengine.traced_module.node.TensorNode', class {});
  2203. this.registerType('megengine.traced_module.pytree.ArgsIndex', class {});
  2204. this.registerType('megengine.traced_module.serialization._ModuleState', class {});
  2205. this.registerType('megengine.traced_module.traced_module.InternalGraph', class {});
  2206. this.registerType('megengine.traced_module.traced_module.NameSpace', class {});
  2207. this.registerType('megengine.traced_module.traced_module.TracedModule', class {});
  2208. this.registerType('megengine.tensor.Parameter', class {
  2209. constructor(data, dtype, device) {
  2210. this.data = data;
  2211. this.dtype = dtype;
  2212. this.device = device;
  2213. }
  2214. });
  2215. this.registerType('megengine.traced_module.pytree.TreeDef', class {
  2216. toString() {
  2217. let content = '';
  2218. for (const child of this.children_defs) {
  2219. content += child.toString() + ",";
  2220. }
  2221. if (typeof this.type === "string") {
  2222. return this.type.split(".").slice(-1) + '(' + content + ')';
  2223. }
  2224. return this.type.__name__ + '(' + content + ')';
  2225. }
  2226. });
  2227. this.registerType('megengine.traced_module.pytree.LeafDef', class {
  2228. toString() {
  2229. let content = '';
  2230. if (this.const_val !== null) {
  2231. content += this.const_val;
  2232. }
  2233. else {
  2234. content += '[';
  2235. }
  2236. for (var t of Object.values(this.type)) {
  2237. content += t.__name__;
  2238. }
  2239. content += ']';
  2240. return content;
  2241. }
  2242. });
  2243. this.registerType('megengine.tensor.Tensor', class {
  2244. constructor(data, dtype, device) {
  2245. this.data = data;
  2246. this.dtype = dtype;
  2247. this.device = device;
  2248. }
  2249. });
  2250. this.registerType('megengine.core.tensor.dtype.QuantDtypeMeta', class {
  2251. constructor(name, cname, np_dtype, qmin, qmax, is_signed) {
  2252. this.name = name;
  2253. this.cname = cname;
  2254. this.np_dtype = np_dtype;
  2255. this.qmin = qmin;
  2256. this.qmax = qmax;
  2257. this.is_signed = is_signed;
  2258. }
  2259. });
  2260. this.registerType('nolearn.lasagne.base.BatchIterator', class {});
  2261. this.registerType('nolearn.lasagne.base.Layers', class {});
  2262. this.registerType('nolearn.lasagne.base.NeuralNet', class {});
  2263. this.registerType('nolearn.lasagne.base.TrainSplit', class {});
  2264. this.registerType('nolearn.lasagne.handlers.PrintLayerInfo', class {});
  2265. this.registerType('nolearn.lasagne.handlers.PrintLog', class {});
  2266. this.registerType('numpy.ndarray', class {
  2267. constructor(shape, dtype, buffer, offset, strides, order) {
  2268. this.shape = shape;
  2269. this.dtype = dtype;
  2270. this.data = buffer !== undefined ? buffer : null;
  2271. this.offset = offset !== undefined ? offset : 0;
  2272. this.strides = strides !== undefined ? strides : null;
  2273. this.order = offset !== undefined ? order : null;
  2274. this.flags = {};
  2275. this._read();
  2276. }
  2277. __setstate__(state) {
  2278. this.version = state[0];
  2279. this.shape = state[1];
  2280. this.dtype = state[2];
  2281. this.flags.fnc = state[3];
  2282. this.data = state[4];
  2283. this._read();
  2284. }
  2285. tobytes() {
  2286. return this.data;
  2287. }
  2288. tolist() {
  2289. if (this.shape.length < 0 || this.shape.length > 1) {
  2290. throw new Error(JSON.stringify(this.shape));
  2291. }
  2292. const size = this.shape.reduce((a, b) => a * b, 1);
  2293. const list = new Array(size);
  2294. switch (this.dtype.kind) {
  2295. case 'U': {
  2296. const data = new Uint32Array(new Uint8Array(this.data).buffer);
  2297. const itemsize = this.dtype.itemsize >> 2;
  2298. let offset = 0;
  2299. for (let i = 0; i < size; i++) {
  2300. const buffer = data.subarray(offset, offset + itemsize);
  2301. const index = buffer.indexOf(0);
  2302. list[i] = Array.from(index >= 0 ? buffer.subarray(0, index) : buffer).map((c) => String.fromCodePoint(c)).join('');
  2303. offset += itemsize;
  2304. }
  2305. return list;
  2306. }
  2307. case 'S': {
  2308. const data = this.data;
  2309. const itemsize = this.dtype.itemsize;
  2310. const decoder = new TextDecoder('utf-8');
  2311. let offset = 0;
  2312. for (let i = 0; i < size; i++) {
  2313. const buffer = data.subarray(offset, offset + itemsize);
  2314. const index = buffer.indexOf(0);
  2315. list[i] = decoder.decode(index >= 0 ? buffer.subarray(0, index) : buffer);
  2316. offset += itemsize;
  2317. }
  2318. return list;
  2319. }
  2320. case 'O': {
  2321. return this.data;
  2322. }
  2323. default: {
  2324. throw new python.Error("Type kind '" + this.dtype.kind + "' not implemented.");
  2325. }
  2326. }
  2327. }
  2328. get size() {
  2329. return (this.shape || []).reduce((a, b) => a * b, 1);
  2330. }
  2331. _read() {
  2332. if (this.data) {
  2333. const length = this.dtype.itemsize * this.size;
  2334. if (typeof this.data == 'string') {
  2335. this.data = this._unescape(this.data, length);
  2336. if (this.data.length != length) {
  2337. throw new python.Error('Invalid string array data size.');
  2338. }
  2339. }
  2340. else if (this.data.length != length) {
  2341. // throw new python.Error('Invalid array data size.');
  2342. }
  2343. }
  2344. }
  2345. _unescape(token, size) {
  2346. const length = token.length;
  2347. const a = new Uint8Array(length);
  2348. if (size && size == length) {
  2349. for (let p = 0; p < size; p++) {
  2350. a[p] = token.charCodeAt(p);
  2351. }
  2352. return a;
  2353. }
  2354. let i = 0;
  2355. let o = 0;
  2356. while (i < length) {
  2357. let c = token.charCodeAt(i++);
  2358. if (c !== 0x5C || i >= length) {
  2359. a[o++] = c;
  2360. }
  2361. else {
  2362. c = token.charCodeAt(i++);
  2363. switch (c) {
  2364. case 0x27: a[o++] = 0x27; break; // '
  2365. case 0x5C: a[o++] = 0x5C; break; // \\
  2366. case 0x22: a[o++] = 0x22; break; // "
  2367. case 0x72: a[o++] = 0x0D; break; // \r
  2368. case 0x6E: a[o++] = 0x0A; break; // \n
  2369. case 0x74: a[o++] = 0x09; break; // \t
  2370. case 0x62: a[o++] = 0x08; break; // \b
  2371. case 0x58: // x
  2372. case 0x78: { // X
  2373. const xsi = i - 1;
  2374. const xso = o;
  2375. for (let xi = 0; xi < 2; xi++) {
  2376. if (i >= length) {
  2377. i = xsi;
  2378. o = xso;
  2379. a[o] = 0x5c;
  2380. break;
  2381. }
  2382. let xd = token.charCodeAt(i++);
  2383. xd = xd >= 65 && xd <= 70 ? xd - 55 : xd >= 97 && xd <= 102 ? xd - 87 : xd >= 48 && xd <= 57 ? xd - 48 : -1;
  2384. if (xd === -1) {
  2385. i = xsi;
  2386. o = xso;
  2387. a[o] = 0x5c;
  2388. break;
  2389. }
  2390. a[o] = a[o] << 4 | xd;
  2391. }
  2392. o++;
  2393. break;
  2394. }
  2395. default:
  2396. if (c < 48 || c > 57) { // 0-9
  2397. a[o++] = 0x5c;
  2398. a[o++] = c;
  2399. }
  2400. else {
  2401. i--;
  2402. const osi = i;
  2403. const oso = o;
  2404. for (let oi = 0; oi < 3; oi++) {
  2405. if (i >= length) {
  2406. i = osi;
  2407. o = oso;
  2408. a[o] = 0x5c;
  2409. break;
  2410. }
  2411. const od = token.charCodeAt(i++);
  2412. if (od < 48 || od > 57) {
  2413. i = osi;
  2414. o = oso;
  2415. a[o] = 0x5c;
  2416. break;
  2417. }
  2418. a[o] = a[o] << 3 | od - 48;
  2419. }
  2420. o++;
  2421. }
  2422. break;
  2423. }
  2424. }
  2425. }
  2426. return a.slice(0, o);
  2427. }
  2428. });
  2429. this.registerType('numpy.ma.core.MaskedArray', class extends numpy.ndarray {
  2430. constructor(data /*, mask, dtype, copy, subok, ndmin, fill_value, keep_mask, hard_mask, shrink, order */) {
  2431. super(data.shape, data.dtype, data.data);
  2432. }
  2433. });
  2434. this.registerType('numpy.core.memmap.memmap', class extends numpy.ndarray {
  2435. constructor(shape, dtype) {
  2436. super(shape, dtype);
  2437. }
  2438. });
  2439. this.registerType('pathlib.Path', class {});
  2440. this.registerType('pathlib.PosixPath', class {});
  2441. this.registerType('pathlib.WindowsPath', class {});
  2442. this.registerType('sklearn.calibration._CalibratedClassifier', class {});
  2443. this.registerType('sklearn.calibration._SigmoidCalibration', class {});
  2444. this.registerType('sklearn.calibration.CalibratedClassifierCV', class {});
  2445. this.registerType('sklearn.compose._column_transformer.ColumnTransformer', class {});
  2446. this.registerType('sklearn.compose._target.TransformedTargetRegressor', class {});
  2447. this.registerType('sklearn.cluster._agglomerative.FeatureAgglomeration', class {});
  2448. this.registerType('sklearn.cluster._dbscan.DBSCAN', class {});
  2449. this.registerType('sklearn.cluster._kmeans.KMeans', class {});
  2450. this.registerType('sklearn.decomposition._fastica.FastICA', class {});
  2451. this.registerType('sklearn.decomposition._pca.PCA', class {});
  2452. this.registerType('sklearn.decomposition._truncated_svd.TruncatedSVD', class {});
  2453. this.registerType('sklearn.decomposition.PCA', class {});
  2454. this.registerType('sklearn.decomposition.pca.PCA', class {});
  2455. this.registerType('sklearn.decomposition.truncated_svd.TruncatedSVD', class {});
  2456. this.registerType('sklearn.discriminant_analysis.LinearDiscriminantAnalysis', class {});
  2457. this.registerType('sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis', class {});
  2458. this.registerType('sklearn.dummy.DummyClassifier', class {});
  2459. this.registerType('sklearn.dummy.DummyRegressor', class {});
  2460. this.registerType('sklearn.externals.joblib.numpy_pickle.NumpyArrayWrapper', class {
  2461. constructor(/* subtype, shape, dtype */) {
  2462. }
  2463. __setstate__(state) {
  2464. this.subclass = state.subclass;
  2465. this.dtype = state.dtype;
  2466. this.shape = state.shape;
  2467. this.order = state.order;
  2468. this.allow_mmap = state.allow_mmap;
  2469. }
  2470. __read__(unpickler) {
  2471. if (this.dtype.__name__ == 'object') {
  2472. return unpickler.load();
  2473. }
  2474. const size = this.dtype.itemsize * this.shape.reduce((a, b) => a * b, 1);
  2475. this.data = unpickler.read(size);
  2476. return execution.invoke(this.subclass, [ this.shape, this.dtype, this.data ]);
  2477. }
  2478. });
  2479. this.registerType('sklearn.externals.joblib.numpy_pickle.NDArrayWrapper', class {
  2480. constructor(/* subtype, shape, dtype */) {
  2481. }
  2482. __setstate__(state) {
  2483. this.subclass = state.subclass;
  2484. this.filename = state.state;
  2485. this.allow_mmap = state.allow_mmap;
  2486. }
  2487. __read__(/* unpickler */) {
  2488. return this; // return execution.invoke(this.subclass, [ this.shape, this.dtype, this.data ]);
  2489. }
  2490. });
  2491. this.registerType('sklearn.ensemble._bagging.BaggingClassifier', class {});
  2492. this.registerType('sklearn.ensemble._forest.RandomForestRegressor', class {});
  2493. this.registerType('sklearn.ensemble._forest.RandomForestClassifier', class {});
  2494. this.registerType('sklearn.ensemble._forest.ExtraTreesClassifier', class {});
  2495. this.registerType('sklearn.ensemble._gb_losses.BinomialDeviance', class {});
  2496. this.registerType('sklearn.ensemble._gb_losses.LeastSquaresError', class {});
  2497. this.registerType('sklearn.ensemble._gb_losses.MultinomialDeviance', class {});
  2498. this.registerType('sklearn.ensemble._gb.GradientBoostingClassifier', class {});
  2499. this.registerType('sklearn.ensemble._gb.GradientBoostingRegressor', class {});
  2500. this.registerType('sklearn.ensemble._hist_gradient_boosting.binning._BinMapper', class {});
  2501. this.registerType('sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingRegressor', class {});
  2502. this.registerType('sklearn.ensemble._hist_gradient_boosting.loss.LeastSquares', class {});
  2503. this.registerType('sklearn.ensemble._hist_gradient_boosting.predictor.TreePredictor', class {});
  2504. this.registerType('sklearn.ensemble._iforest.IsolationForest', class {});
  2505. this.registerType('sklearn.ensemble._stacking.StackingClassifier', class {});
  2506. this.registerType('sklearn.ensemble._voting.VotingClassifier', class {});
  2507. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostClassifier', class {});
  2508. this.registerType('sklearn.ensemble.forest.RandomForestClassifier', class {});
  2509. this.registerType('sklearn.ensemble.forest.RandomForestRegressor', class {});
  2510. this.registerType('sklearn.ensemble.forest.ExtraTreesClassifier', class {});
  2511. this.registerType('sklearn.ensemble.gradient_boosting.BinomialDeviance', class {});
  2512. this.registerType('sklearn.ensemble.gradient_boosting.GradientBoostingClassifier', class {});
  2513. this.registerType('sklearn.ensemble.gradient_boosting.LogOddsEstimator', class {});
  2514. this.registerType('sklearn.ensemble.gradient_boosting.MultinomialDeviance', class {});
  2515. this.registerType('sklearn.ensemble.gradient_boosting.PriorProbabilityEstimator', class {});
  2516. this.registerType('sklearn.ensemble.weight_boosting.AdaBoostClassifier', class {});
  2517. this.registerType('sklearn.feature_extraction._hashing.FeatureHasher', class {});
  2518. this.registerType('sklearn.feature_extraction.text.CountVectorizer', class {});
  2519. this.registerType('sklearn.feature_extraction.text.HashingVectorizer', class {});
  2520. this.registerType('sklearn.feature_extraction.text.TfidfTransformer', class {});
  2521. this.registerType('sklearn.feature_extraction.text.TfidfVectorizer', class {});
  2522. this.registerType('sklearn.feature_selection._from_model.SelectFromModel', class {});
  2523. this.registerType('sklearn.feature_selection._univariate_selection.GenericUnivariateSelect', class {});
  2524. this.registerType('sklearn.feature_selection._univariate_selection.SelectKBest', class {});
  2525. this.registerType('sklearn.feature_selection._univariate_selection.SelectPercentile', class {});
  2526. this.registerType('sklearn.feature_selection._variance_threshold.VarianceThreshold', class {});
  2527. this.registerType('sklearn.feature_selection.univariate_selection.SelectKBest', class {});
  2528. this.registerType('sklearn.feature_selection.variance_threshold.VarianceThreshold', class {});
  2529. this.registerType('sklearn.gaussian_process._gpr.GaussianProcessRegressor', class {});
  2530. this.registerType('sklearn.gaussian_process.gpc.GaussianProcessClassifier', class {});
  2531. this.registerType('sklearn.gaussian_process.kernels.ConstantKernel', class {});
  2532. this.registerType('sklearn.gaussian_process.kernels.DotProduct', class {});
  2533. this.registerType('sklearn.gaussian_process.kernels.Product', class {});
  2534. this.registerType('sklearn.gaussian_process.kernels.RBF', class {});
  2535. this.registerType('sklearn.gaussian_process.kernels.Sum', class {});
  2536. this.registerType('sklearn.gaussian_process.kernels.WhiteKernel', class {});
  2537. this.registerType('sklearn.grid_search._CVScoreTuple', class {});
  2538. this.registerType('sklearn.grid_search.GridSearchCV', class {});
  2539. this.registerType('sklearn.impute._base.SimpleImputer', class {});
  2540. this.registerType('sklearn.impute.SimpleImputer', class {});
  2541. this.registerType('sklearn.isotonic.IsotonicRegression', class {});
  2542. this.registerType('sklearn.linear_model._base.LinearRegression', class {});
  2543. this.registerType('sklearn.linear_model._bayes.BayesianRidge', class {});
  2544. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNetCV', class {});
  2545. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNet', class {});
  2546. this.registerType('sklearn.linear_model._logistic.LogisticRegression', class {});
  2547. this.registerType('sklearn.linear_model._ridge.Ridge', class {});
  2548. this.registerType('sklearn.linear_model._ridge.RidgeClassifier', class {});
  2549. this.registerType('sklearn.linear_model._sgd_fast.Hinge', class {});
  2550. this.registerType('sklearn.linear_model._sgd_fast.Log', class {});
  2551. this.registerType('sklearn.linear_model._sgd_fast.ModifiedHuber', class {});
  2552. this.registerType('sklearn.linear_model._sgd_fast.SquaredHinge', class {});
  2553. this.registerType('sklearn.linear_model._stochastic_gradient.SGDClassifier', class {});
  2554. this.registerType('sklearn.linear_model.base.LinearRegression', class {});
  2555. this.registerType('sklearn.linear_model.sgd_fast.Hinge', class {});
  2556. this.registerType('sklearn.linear_model.LogisticRegression', class {});
  2557. this.registerType('sklearn.linear_model.logistic.LogisticRegression', class {});
  2558. this.registerType('sklearn.linear_model.logistic.LogisticRegressionCV', class {});
  2559. this.registerType('sklearn.linear_model.LassoLars​', class {});
  2560. this.registerType('sklearn.linear_model.ridge.Ridge', class {});
  2561. this.registerType('sklearn.linear_model.sgd_fast.Log', class {});
  2562. this.registerType('sklearn.linear_model.stochastic_gradient.SGDClassifier', class {});
  2563. this.registerType('sklearn.metrics._classification.accuracy_score', class {});
  2564. this.registerType('sklearn.metrics._regression.mean_squared_error', class {});
  2565. this.registerType('sklearn.metrics._scorer._PredictScorer', class {});
  2566. this.registerType('sklearn.metrics.scorer._PredictScorer', class {});
  2567. this.registerType('sklearn.metrics._scorer._ThresholdScorer', class {});
  2568. this.registerType('sklearn.mixture._bayesian_mixture.BayesianGaussianMixture', class {});
  2569. this.registerType('sklearn.model_selection._search.GridSearchCV', class {});
  2570. this.registerType('sklearn.model_selection._search.RandomizedSearchCV', class {});
  2571. this.registerType('sklearn.model_selection._split.KFold', class {});
  2572. this.registerType('sklearn.model_selection._split.StratifiedKFold', class {});
  2573. this.registerType('sklearn.multiclass.OneVsRestClassifier', class {});
  2574. this.registerType('sklearn.multioutput.MultiOutputClassifier', class {});
  2575. this.registerType('sklearn.multioutput.MultiOutputRegressor', class {});
  2576. this.registerType('sklearn.naive_bayes.BernoulliNB', class {});
  2577. this.registerType('sklearn.naive_bayes.ComplementNB', class {});
  2578. this.registerType('sklearn.naive_bayes.GaussianNB', class {});
  2579. this.registerType('sklearn.naive_bayes.MultinomialNB', class {});
  2580. this.registerType('sklearn.neighbors._classification.KNeighborsClassifier', class {});
  2581. this.registerType('sklearn.neighbors._dist_metrics.newObj', class {});
  2582. this.registerType('sklearn.neighbors._dist_metrics.EuclideanDistance', class {});
  2583. this.registerType('sklearn.neighbors._kd_tree.KDTree', class {});
  2584. this.registerType('sklearn.neighbors._kd_tree.newObj', class {});
  2585. this.registerType('sklearn.neighbors._regression.KNeighborsRegressor', class {});
  2586. this.registerType('sklearn.neighbors.classification.KNeighborsClassifier', class {});
  2587. this.registerType('sklearn.neighbors.dist_metrics.newObj', class {});
  2588. this.registerType('sklearn.neighbors.dist_metrics.EuclideanDistance', class {});
  2589. this.registerType('sklearn.neighbors.kd_tree.newObj', class {});
  2590. this.registerType('sklearn.neighbors.kd_tree.KDTree', class {});
  2591. this.registerType('sklearn.neighbors.KNeighborsClassifier', class {});
  2592. this.registerType('sklearn.neighbors.KNeighborsRegressor', class {});
  2593. this.registerType('sklearn.neighbors.regression.KNeighborsRegressor', class {});
  2594. this.registerType('sklearn.neighbors.unsupervised.NearestNeighbors', class {});
  2595. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPClassifier', class {});
  2596. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPRegressor', class {});
  2597. this.registerType('sklearn.neural_network._stochastic_optimizers.AdamOptimizer', class {});
  2598. this.registerType('sklearn.neural_network._stochastic_optimizers.SGDOptimizer', class {});
  2599. this.registerType('sklearn.neural_network.rbm.BernoulliRBM', class {});
  2600. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPClassifier', class {});
  2601. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPRegressor', class {});
  2602. this.registerType('sklearn.neural_network.stochastic_gradient.SGDClassifier', class {});
  2603. this.registerType('sklearn.pipeline.Pipeline', class {});
  2604. this.registerType('sklearn.pipeline.FeatureUnion', class {});
  2605. this.registerType('sklearn.preprocessing._data.MinMaxScaler', class {});
  2606. this.registerType('sklearn.preprocessing._data.MaxAbsScaler', class {});
  2607. this.registerType('sklearn.preprocessing._data.Normalizer', class {});
  2608. this.registerType('sklearn.preprocessing._data.PolynomialFeatures', class {});
  2609. this.registerType('sklearn.preprocessing._data.PowerTransformer', class {});
  2610. this.registerType('sklearn.preprocessing._data.QuantileTransformer', class {});
  2611. this.registerType('sklearn.preprocessing._data.RobustScaler', class {});
  2612. this.registerType('sklearn.preprocessing._data.StandardScaler', class {});
  2613. this.registerType('sklearn.preprocessing._discretization.KBinsDiscretizer', class {});
  2614. this.registerType('sklearn.preprocessing._encoders.OneHotEncoder', class {});
  2615. this.registerType('sklearn.preprocessing._function_transformer.FunctionTransformer', class {});
  2616. this.registerType('sklearn.preprocessing._label.LabelBinarizer', class {});
  2617. this.registerType('sklearn.preprocessing._label.LabelEncoder', class {});
  2618. this.registerType('sklearn.preprocessing._label.MultiLabelBinarizer', class {});
  2619. this.registerType('sklearn.preprocessing._polynomial.PolynomialFeatures', class {});
  2620. this.registerType('sklearn.preprocessing.data.Binarizer', class {});
  2621. this.registerType('sklearn.preprocessing.data.MaxAbsScaler', class {});
  2622. this.registerType('sklearn.preprocessing.data.MinMaxScaler', class {});
  2623. this.registerType('sklearn.preprocessing.data.Normalizer', class {});
  2624. this.registerType('sklearn.preprocessing.data.OneHotEncoder', class {});
  2625. this.registerType('sklearn.preprocessing.data.PolynomialFeatures', class {});
  2626. this.registerType('sklearn.preprocessing.data.PowerTransformer', class {});
  2627. this.registerType('sklearn.preprocessing.data.RobustScaler', class {});
  2628. this.registerType('sklearn.preprocessing.data.QuantileTransformer', class {});
  2629. this.registerType('sklearn.preprocessing.data.StandardScaler', class {});
  2630. this.registerType('sklearn.preprocessing.imputation.Imputer', class {});
  2631. this.registerType('sklearn.preprocessing.label.LabelBinarizer', class {});
  2632. this.registerType('sklearn.preprocessing.label.LabelEncoder', class {});
  2633. this.registerType('sklearn.preprocessing.label.MultiLabelBinarizer', class {});
  2634. this.registerType('sklearn.svm._classes.LinearSVC', class {});
  2635. this.registerType('sklearn.svm._classes.NuSVC', class {});
  2636. this.registerType('sklearn.svm._classes.OneClassSVM', class {});
  2637. this.registerType('sklearn.svm._classes.SVC', class {});
  2638. this.registerType('sklearn.svm._classes.SVR', class {});
  2639. this.registerType('sklearn.svm.classes.LinearSVC', class {});
  2640. this.registerType('sklearn.svm.classes.OneClassSVM', class {});
  2641. this.registerType('sklearn.svm.classes.SVC', class {});
  2642. this.registerType('sklearn.svm.classes.SVR', class {});
  2643. this.registerType('sklearn.tree._classes.DecisionTreeClassifier', class {});
  2644. this.registerType('sklearn.tree._classes.DecisionTreeRegressor', class {});
  2645. this.registerType('sklearn.tree._classes.ExtraTreeClassifier', class {});
  2646. this.registerType('sklearn.tree._classes.ExtraTreeRegressor', class {});
  2647. this.registerType('sklearn.tree._tree.Tree', class {
  2648. constructor(n_features, n_classes, n_outputs) {
  2649. this.n_features = n_features;
  2650. this.n_classes = n_classes;
  2651. this.n_outputs = n_outputs;
  2652. }
  2653. __setstate__(state) {
  2654. this.max_depth = state.max_depth;
  2655. this.node_count = state.node_count;
  2656. this.nodes = state.nodes;
  2657. this.values = state.values;
  2658. }
  2659. });
  2660. this.registerType('sklearn.tree.tree.DecisionTreeClassifier', class {});
  2661. this.registerType('sklearn.tree.tree.DecisionTreeRegressor', class {});
  2662. this.registerType('sklearn.tree.tree.ExtraTreeClassifier', class {});
  2663. this.registerType('sklearn.utils._bunch.Bunch', class {});
  2664. this.registerType('sklearn.utils.deprecation.DeprecationDict', class {});
  2665. this.registerType('pickle.Unpickler', class {
  2666. constructor(data) {
  2667. this._reader = data instanceof Uint8Array ? new python.Unpickler.BinaryReader(data) : new python.Unpickler.StreamReader(data);
  2668. this.persistent_load = () => {
  2669. throw new python.Error('Unsupported persistent id.');
  2670. };
  2671. }
  2672. load() {
  2673. const reader = this._reader;
  2674. const marker = [];
  2675. let stack = [];
  2676. const memo = new Map();
  2677. const OpCode = python.Unpickler.OpCode;
  2678. while (reader.position < reader.length) {
  2679. const opcode = reader.byte();
  2680. // console.log((reader.position - 1).toString() + ' ' + Object.entries(OpCode).find((entry) => entry[1] === opcode)[0]);
  2681. switch (opcode) {
  2682. case OpCode.PROTO: {
  2683. const version = reader.byte();
  2684. if (version > 5) {
  2685. throw new python.Error("Unsupported protocol version '" + version + "'.");
  2686. }
  2687. break;
  2688. }
  2689. case OpCode.GLOBAL: {
  2690. const module = reader.line();
  2691. const name = reader.line();
  2692. stack.push(this.find_class(module, name));
  2693. break;
  2694. }
  2695. case OpCode.STACK_GLOBAL: {
  2696. const name = stack.pop();
  2697. const module = stack.pop();
  2698. stack.push(this.find_class(module, name));
  2699. break;
  2700. }
  2701. case OpCode.PUT: {
  2702. const index = parseInt(reader.line(), 10);
  2703. memo.set(index, stack[stack.length - 1]);
  2704. break;
  2705. }
  2706. case OpCode.OBJ: {
  2707. const args = stack;
  2708. const cls = args.pop();
  2709. stack = marker.pop();
  2710. const obj = this._instantiate(cls, args);
  2711. stack.push(obj);
  2712. break;
  2713. }
  2714. case OpCode.GET: {
  2715. const index = parseInt(reader.line(), 10);
  2716. stack.push(memo.get(index));
  2717. break;
  2718. }
  2719. case OpCode.POP:
  2720. stack.pop();
  2721. break;
  2722. case OpCode.POP_MARK:
  2723. stack = marker.pop();
  2724. break;
  2725. case OpCode.DUP:
  2726. stack.push(stack[stack.length-1]);
  2727. break;
  2728. case OpCode.PERSID:
  2729. stack.push(this.persistent_load(reader.line()));
  2730. break;
  2731. case OpCode.BINPERSID:
  2732. stack.push(this.persistent_load(stack.pop()));
  2733. break;
  2734. case OpCode.REDUCE: {
  2735. const args = stack.pop();
  2736. const func = stack.pop();
  2737. stack.push(execution.invoke(func, args));
  2738. break;
  2739. }
  2740. case OpCode.NEWOBJ: {
  2741. const args = stack.pop();
  2742. const cls = stack.pop();
  2743. // TODO resolved
  2744. // cls.__new__(cls, args)
  2745. stack.push(execution.invoke(cls, args));
  2746. break;
  2747. }
  2748. case OpCode.BINGET:
  2749. stack.push(memo.get(reader.byte()));
  2750. break;
  2751. case OpCode.INST: {
  2752. const module = reader.line();
  2753. const name = reader.line();
  2754. const args = stack;
  2755. const cls = module + '.' + name;
  2756. stack = marker.pop();
  2757. // TODO
  2758. // cls = this.find_class(module, name)
  2759. const obj = this._instantiate(cls, args);
  2760. stack.push(obj);
  2761. break;
  2762. }
  2763. case OpCode.LONG_BINGET:
  2764. stack.push(memo.get(reader.uint32()));
  2765. break;
  2766. case OpCode.BINPUT:
  2767. memo.set(reader.byte(), stack[stack.length - 1]);
  2768. break;
  2769. case OpCode.LONG_BINPUT:
  2770. memo.set(reader.uint32(), stack[stack.length - 1]);
  2771. break;
  2772. case OpCode.BININT:
  2773. stack.push(reader.int32());
  2774. break;
  2775. case OpCode.BININT1:
  2776. stack.push(reader.byte());
  2777. break;
  2778. case OpCode.LONG:
  2779. stack.push(parseInt(reader.line(), 10));
  2780. break;
  2781. case OpCode.BININT2:
  2782. stack.push(reader.uint16());
  2783. break;
  2784. case OpCode.BINBYTES:
  2785. stack.push(reader.read(reader.int32()));
  2786. break;
  2787. case OpCode.BINBYTES8:
  2788. stack.push(reader.read(reader.int64()));
  2789. break;
  2790. case OpCode.SHORT_BINBYTES:
  2791. stack.push(reader.read(reader.byte()));
  2792. break;
  2793. case OpCode.FLOAT:
  2794. stack.push(parseFloat(reader.line()));
  2795. break;
  2796. case OpCode.BINFLOAT:
  2797. stack.push(reader.float64());
  2798. break;
  2799. case OpCode.INT: {
  2800. const value = reader.line();
  2801. if (value == '01') {
  2802. stack.push(true);
  2803. }
  2804. else if (value == '00') {
  2805. stack.push(false);
  2806. }
  2807. else {
  2808. stack.push(parseInt(value, 10));
  2809. }
  2810. break;
  2811. }
  2812. case OpCode.EMPTY_LIST:
  2813. stack.push([]);
  2814. break;
  2815. case OpCode.EMPTY_TUPLE:
  2816. stack.push([]);
  2817. break;
  2818. case OpCode.EMPTY_SET:
  2819. stack.push([]);
  2820. break;
  2821. case OpCode.ADDITEMS: {
  2822. const items = stack;
  2823. stack = marker.pop();
  2824. const obj = stack[stack.length - 1];
  2825. for (let i = 0; i < items.length; i++) {
  2826. obj.push(items[i]);
  2827. }
  2828. break;
  2829. }
  2830. case OpCode.FROZENSET: {
  2831. const items = stack;
  2832. stack = marker.pop();
  2833. stack.push(items);
  2834. break;
  2835. }
  2836. case OpCode.DICT: {
  2837. const items = stack;
  2838. stack = marker.pop();
  2839. const dict = {};
  2840. for (let i = 0; i < items.length; i += 2) {
  2841. dict[items[i]] = items[i + 1];
  2842. }
  2843. stack.push(dict);
  2844. break;
  2845. }
  2846. case OpCode.LIST: {
  2847. const items = stack;
  2848. stack = marker.pop();
  2849. stack.push(items);
  2850. break;
  2851. }
  2852. case OpCode.TUPLE: {
  2853. const items = stack;
  2854. stack = marker.pop();
  2855. stack.push(items);
  2856. break;
  2857. }
  2858. case OpCode.SETITEM: {
  2859. const value = stack.pop();
  2860. const key = stack.pop();
  2861. const obj = stack[stack.length - 1];
  2862. if (obj.__setitem__) {
  2863. obj.__setitem__(key, value);
  2864. }
  2865. else {
  2866. obj[key] = value;
  2867. }
  2868. break;
  2869. }
  2870. case OpCode.SETITEMS: {
  2871. const items = stack;
  2872. stack = marker.pop();
  2873. const obj = stack[stack.length - 1];
  2874. for (let i = 0; i < items.length; i += 2) {
  2875. if (obj.__setitem__) {
  2876. obj.__setitem__(items[i], items[i + 1]);
  2877. }
  2878. else {
  2879. obj[items[i]] = items[i + 1];
  2880. }
  2881. }
  2882. break;
  2883. }
  2884. case OpCode.EMPTY_DICT:
  2885. stack.push({});
  2886. break;
  2887. case OpCode.APPEND: {
  2888. const append = stack.pop();
  2889. stack[stack.length-1].push(append);
  2890. break;
  2891. }
  2892. case OpCode.APPENDS: {
  2893. const appends = stack;
  2894. stack = marker.pop();
  2895. const list = stack[stack.length - 1];
  2896. list.push.apply(list, appends);
  2897. break;
  2898. }
  2899. case OpCode.STRING: {
  2900. const str = reader.line();
  2901. stack.push(str.substr(1, str.length - 2));
  2902. break;
  2903. }
  2904. case OpCode.BINSTRING:
  2905. stack.push(reader.string(reader.uint32()));
  2906. break;
  2907. case OpCode.SHORT_BINSTRING:
  2908. stack.push(reader.string(reader.byte()));
  2909. break;
  2910. case OpCode.UNICODE:
  2911. stack.push(reader.line());
  2912. break;
  2913. case OpCode.BINUNICODE:
  2914. stack.push(reader.string(reader.uint32(), 'utf-8'));
  2915. break;
  2916. case OpCode.SHORT_BINUNICODE:
  2917. stack.push(reader.string(reader.byte(), 'utf-8'));
  2918. break;
  2919. case OpCode.BUILD: {
  2920. const state = stack.pop();
  2921. let obj = stack.pop();
  2922. if (obj.__setstate__) {
  2923. if (obj.__setstate__.__call__) {
  2924. obj.__setstate__.__call__([ obj, state ]);
  2925. }
  2926. else {
  2927. obj.__setstate__(state);
  2928. }
  2929. }
  2930. else if (ArrayBuffer.isView(state) || Object(state) !== state) {
  2931. obj.__state__ = state;
  2932. }
  2933. else if (obj instanceof Map) {
  2934. for (const key in state) {
  2935. obj.set(key, state[key]);
  2936. }
  2937. }
  2938. else {
  2939. Object.assign(obj, state);
  2940. }
  2941. if (obj.__read__) {
  2942. obj = obj.__read__(this);
  2943. }
  2944. stack.push(obj);
  2945. break;
  2946. }
  2947. case OpCode.MARK:
  2948. marker.push(stack);
  2949. stack = [];
  2950. break;
  2951. case OpCode.NEWTRUE:
  2952. stack.push(true);
  2953. break;
  2954. case OpCode.NEWFALSE:
  2955. stack.push(false);
  2956. break;
  2957. case OpCode.LONG1: {
  2958. const data = reader.read(reader.byte());
  2959. let number = 0;
  2960. switch (data.length) {
  2961. case 0: number = 0; break;
  2962. case 1: number = data[0]; break;
  2963. case 2: number = data[1] << 8 | data[0]; break;
  2964. case 3: number = data[2] << 16 | data[1] << 8 | data[0]; break;
  2965. case 4: number = data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]; break;
  2966. case 5: number = data[4] * 0x100000000 + ((data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]) >>> 0); break;
  2967. default: number = Array.prototype.slice.call(data, 0); break;
  2968. }
  2969. stack.push(number);
  2970. break;
  2971. }
  2972. case OpCode.LONG4:
  2973. // TODO decode LONG4
  2974. stack.push(reader.read(reader.uint32()));
  2975. break;
  2976. case OpCode.TUPLE1:
  2977. stack.push([ stack.pop() ]);
  2978. break;
  2979. case OpCode.TUPLE2: {
  2980. const b = stack.pop();
  2981. const a = stack.pop();
  2982. stack.push([ a, b ]);
  2983. break;
  2984. }
  2985. case OpCode.TUPLE3: {
  2986. const c = stack.pop();
  2987. const b = stack.pop();
  2988. const a = stack.pop();
  2989. stack.push([ a, b, c ]);
  2990. break;
  2991. }
  2992. case OpCode.MEMOIZE:
  2993. memo.set(memo.size, stack[stack.length - 1]);
  2994. break;
  2995. case OpCode.FRAME:
  2996. reader.read(8);
  2997. break;
  2998. case OpCode.BYTEARRAY8: {
  2999. stack.push(reader.read(reader.int64()));
  3000. break;
  3001. }
  3002. case OpCode.NONE:
  3003. stack.push(null);
  3004. break;
  3005. case OpCode.STOP:
  3006. return stack.pop();
  3007. default:
  3008. throw new python.Error('Unknown opcode ' + opcode + ' at position ' + (reader.position - 1).toString() + '.');
  3009. }
  3010. }
  3011. throw new python.Error('Unexpected end of file.');
  3012. }
  3013. find_class(module, name) {
  3014. execution.__import__(module);
  3015. return execution.resolve(module + '.' + name);
  3016. }
  3017. _instantiate(cls, args) {
  3018. return execution.invoke(cls, args);
  3019. }
  3020. read(size) {
  3021. return this._reader.read(size);
  3022. }
  3023. stream(size) {
  3024. return this._reader.stream(size);
  3025. }
  3026. });
  3027. this.registerType('random.Random', class {});
  3028. this.registerType('re.Pattern', class {
  3029. constructor(pattern, flags) {
  3030. this.pattern = pattern;
  3031. this.flags = flags;
  3032. }
  3033. });
  3034. this.registerType('spacy._ml.PrecomputableAffine', class {
  3035. __setstate__(state) {
  3036. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  3037. }
  3038. });
  3039. this.registerType('spacy.syntax._parser_model.ParserModel', class {
  3040. __setstate__(state) {
  3041. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  3042. }
  3043. });
  3044. this.registerType('theano.compile.function_module._constructor_Function', class {});
  3045. this.registerType('theano.compile.function_module._constructor_FunctionMaker', class {});
  3046. this.registerType('theano.compile.function_module.Function', class {});
  3047. this.registerType('theano.compile.function_module.Supervisor', class {});
  3048. this.registerType('theano.compile.io.In', class {});
  3049. this.registerType('theano.compile.io.SymbolicOutput', class {});
  3050. this.registerType('theano.compile.mode.Mode', class {});
  3051. this.registerType('theano.compile.ops.OutputGuard', class {});
  3052. this.registerType('theano.compile.ops.Shape', class {});
  3053. this.registerType('theano.compile.ops.Shape_i', class {});
  3054. this.registerType('theano.gof.destroyhandler.DestroyHandler', class {});
  3055. this.registerType('theano.gof.fg.FunctionGraph', class {});
  3056. this.registerType('theano.gof.graph.Apply', class {});
  3057. this.registerType('theano.gof.link.Container', class {});
  3058. this.registerType('theano.gof.opt._metadict', class {});
  3059. this.registerType('theano.gof.opt.ChangeTracker', class {});
  3060. this.registerType('theano.gof.opt.MergeFeature', class {});
  3061. this.registerType('theano.gof.optdb.Query', class {});
  3062. this.registerType('theano.gof.toolbox.PreserveVariableAttributes', class {});
  3063. this.registerType('theano.gof.toolbox.ReplaceValidate', class {});
  3064. this.registerType('theano.gof.utils.scratchpad', class {});
  3065. this.registerType('theano.misc.ordered_set.Link', class {});
  3066. this.registerType('theano.misc.ordered_set.OrderedSet', class {});
  3067. this.registerType('theano.sandbox.cuda.basic_ops.HostFromGpu', class {});
  3068. this.registerType('theano.sandbox.cuda.type.CudaNdarray_unpickler', class {});
  3069. this.registerType('theano.sandbox.cuda.type.CudaNdarrayType', class {});
  3070. this.registerType('theano.sandbox.cuda.var.CudaNdarraySharedVariable', class {});
  3071. this.registerType('theano.scalar.basic.Abs', class {});
  3072. this.registerType('theano.scalar.basic.Add', class {});
  3073. this.registerType('theano.scalar.basic.Cast', class {});
  3074. this.registerType('theano.scalar.basic.Composite', class {});
  3075. this.registerType('theano.scalar.basic.EQ', class {});
  3076. this.registerType('theano.scalar.basic.GE', class {});
  3077. this.registerType('theano.scalar.basic.Identity', class {});
  3078. this.registerType('theano.scalar.basic.IntDiv', class {});
  3079. this.registerType('theano.scalar.basic.Inv', class {});
  3080. this.registerType('theano.scalar.basic.LE', class {});
  3081. this.registerType('theano.scalar.basic.LT', class {});
  3082. this.registerType('theano.scalar.basic.Mul', class {});
  3083. this.registerType('theano.scalar.basic.Neg', class {});
  3084. this.registerType('theano.scalar.basic.Scalar', class {});
  3085. this.registerType('theano.scalar.basic.ScalarConstant', class {});
  3086. this.registerType('theano.scalar.basic.ScalarVariable', class {});
  3087. this.registerType('theano.scalar.basic.Second', class {});
  3088. this.registerType('theano.scalar.basic.Sgn', class {});
  3089. this.registerType('theano.scalar.basic.specific_out', class {});
  3090. this.registerType('theano.scalar.basic.Sub', class {});
  3091. this.registerType('theano.scalar.basic.Switch', class {});
  3092. this.registerType('theano.scalar.basic.Tanh', class {});
  3093. this.registerType('theano.scalar.basic.transfer_type', class {});
  3094. this.registerType('theano.scalar.basic.TrueDiv', class {});
  3095. this.registerType('theano.tensor.basic.Alloc', class {});
  3096. this.registerType('theano.tensor.basic.Dot', class {});
  3097. this.registerType('theano.tensor.basic.MaxAndArgmax', class {});
  3098. this.registerType('theano.tensor.basic.Reshape', class {});
  3099. this.registerType('theano.tensor.basic.ScalarFromTensor', class {});
  3100. this.registerType('theano.tensor.blas.Dot22', class {});
  3101. this.registerType('theano.tensor.blas.Dot22Scalar', class {});
  3102. this.registerType('theano.tensor.blas.Gemm', class {});
  3103. this.registerType('theano.tensor.elemwise.DimShuffle', class {});
  3104. this.registerType('theano.tensor.elemwise.Elemwise', class {});
  3105. this.registerType('theano.tensor.elemwise.Sum', class {});
  3106. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d', class {});
  3107. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradInputs', class {});
  3108. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradWeights', class {});
  3109. this.registerType('theano.tensor.nnet.corr.CorrMM', class {});
  3110. this.registerType('theano.tensor.nnet.corr.CorrMM_gradInputs', class {});
  3111. this.registerType('theano.tensor.nnet.corr.CorrMM_gradWeights', class {});
  3112. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1Hot', class {});
  3113. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1HotGrad', class {});
  3114. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmax1HotWithBiasDx', class {});
  3115. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmaxArgmax1HotWithBias', class {});
  3116. this.registerType('theano.tensor.nnet.nnet.Softmax', class {});
  3117. this.registerType('theano.tensor.nnet.nnet.SoftmaxGrad', class {});
  3118. this.registerType('theano.tensor.nnet.nnet.SoftmaxWithBias', class {});
  3119. this.registerType('theano.tensor.opt.MakeVector', class {});
  3120. this.registerType('theano.tensor.opt.ShapeFeature', class {});
  3121. this.registerType('theano.tensor.sharedvar.TensorSharedVariable', class {});
  3122. this.registerType('theano.tensor.signal.pool.MaxPoolGrad', class {});
  3123. this.registerType('theano.tensor.signal.pool.Pool', class {});
  3124. this.registerType('theano.tensor.subtensor.Subtensor', class {});
  3125. this.registerType('theano.tensor.type.TensorType', class {});
  3126. this.registerType('theano.tensor.var.TensorConstant', class {});
  3127. this.registerType('theano.tensor.var.TensorConstantSignature', class {});
  3128. this.registerType('theano.tensor.var.TensorVariable', class {});
  3129. this.registerType('thinc.describe.Biases', class {
  3130. __setstate__(state) {
  3131. Object.assign(this, state);
  3132. }
  3133. });
  3134. this.registerType('thinc.describe.Dimension', class {
  3135. __setstate__(state) {
  3136. Object.assign(this, state);
  3137. }
  3138. });
  3139. this.registerType('thinc.describe.Gradient', class {
  3140. __setstate__(state) {
  3141. Object.assign(this, state);
  3142. }
  3143. });
  3144. this.registerType('thinc.describe.Weights', class {
  3145. __setstate__(state) {
  3146. Object.assign(this, state);
  3147. }
  3148. });
  3149. this.registerType('thinc.describe.Synapses', class {
  3150. __setstate__(state) {
  3151. Object.assign(this, state);
  3152. }
  3153. });
  3154. this.registerType('thinc.neural._classes.affine.Affine', class {
  3155. __setstate__(state) {
  3156. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  3157. }
  3158. });
  3159. this.registerType('thinc.neural._classes.convolution.ExtractWindow', class {
  3160. __setstate__(state) {
  3161. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  3162. }
  3163. });
  3164. this.registerType('thinc.neural._classes.feature_extracter.FeatureExtracter', class {
  3165. __setstate__(state) {
  3166. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  3167. }
  3168. });
  3169. this.registerType('thinc.neural._classes.feed_forward.FeedForward', class {
  3170. __setstate__(state) {
  3171. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  3172. }
  3173. });
  3174. this.registerType('thinc.neural._classes.function_layer.FunctionLayer', class {
  3175. __setstate__(state) {
  3176. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  3177. }
  3178. });
  3179. this.registerType('thinc.neural._classes.hash_embed.HashEmbed', class {
  3180. __setstate__(state) {
  3181. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  3182. }
  3183. });
  3184. this.registerType('thinc.neural._classes.layernorm.LayerNorm', class {
  3185. __setstate__(state) {
  3186. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  3187. }
  3188. });
  3189. this.registerType('thinc.neural._classes.maxout.Maxout', class {
  3190. __setstate__(state) {
  3191. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  3192. }
  3193. });
  3194. this.registerType('thinc.neural._classes.resnet.Residual', class {
  3195. __setstate__(state) {
  3196. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  3197. }
  3198. });
  3199. this.registerType('thinc.neural._classes.softmax.Softmax', class {
  3200. __setstate__(state) {
  3201. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  3202. }
  3203. });
  3204. this.registerType('thinc.neural.mem.Memory', class {
  3205. });
  3206. this.registerType('thinc.neural.ops.NumpyOps', class {
  3207. });
  3208. this.registerType('__main__.BYOLState', class {
  3209. constructor(dict) {
  3210. Object.assign(this, dict);
  3211. }
  3212. });
  3213. this.registerType('types.CodeType', class {});
  3214. this.register('types').ObjectType = this._builtins.object;
  3215. this.register('types').ModuleType = this._builtins.module;
  3216. this.register('types').MethodType = this._builtins.method;
  3217. this.register('types').FunctionType = this._builtins.function;
  3218. this.registerType('xgboost.compat.XGBoostLabelEncoder', class {});
  3219. this.registerType('xgboost.core.Booster', class {});
  3220. this.registerType('xgboost.sklearn.XGBClassifier', class {});
  3221. this.registerType('xgboost.sklearn.XGBRegressor', class {});
  3222. this.registerFunction('_codecs.encode', function(obj, encoding) {
  3223. return execution.invoke('builtins.bytearray', [ obj, encoding ]);
  3224. });
  3225. this.registerFunction('builtins.bytearray', function(source, encoding /*, errors */) {
  3226. if (source) {
  3227. if (Array.isArray(source) || source instanceof Uint8Array) {
  3228. const target = new Uint8Array(source.length);
  3229. for (let i = 0; i < source.length; i++) {
  3230. target[i] = source[i];
  3231. }
  3232. return target;
  3233. }
  3234. if (encoding === 'latin-1' || encoding === 'latin1') {
  3235. const target = new Uint8Array(source.length);
  3236. const length = source.length;
  3237. for (let i = 0; i < length; i++) {
  3238. target[i] = source.charCodeAt(i);
  3239. }
  3240. return target;
  3241. }
  3242. throw new python.Error("Unsupported bytearray encoding '" + JSON.stringify(encoding) + "'.");
  3243. }
  3244. return [];
  3245. });
  3246. this.registerFunction('builtins.bytes', function(source, encoding /*, errors */) {
  3247. if (source) {
  3248. if (Array.isArray(source) || source instanceof Uint8Array) {
  3249. const target = new Uint8Array(source.length);
  3250. for (let i = 0; i < source.length; i++) {
  3251. target[i] = source[i];
  3252. }
  3253. return target;
  3254. }
  3255. if (encoding === 'latin-1') {
  3256. const array = new Uint8Array(source.length);
  3257. for (let i = 0; i < source.length; i++) {
  3258. array[i] = source.charCodeAt(i);
  3259. }
  3260. return array;
  3261. }
  3262. throw new python.Error("Unsupported bytes encoding '" + JSON.stringify(encoding) + "'.");
  3263. }
  3264. return [];
  3265. });
  3266. this.registerFunction('builtins.frozenset', function(iterable) {
  3267. return iterable ? iterable : [];
  3268. });
  3269. this.registerFunction('builtins.getattr', function(obj, name, defaultValue) {
  3270. if (Object.prototype.hasOwnProperty.call(obj, name)) {
  3271. return obj[name];
  3272. }
  3273. return defaultValue;
  3274. });
  3275. this.registerFunction('builtins.set', function(iterable) {
  3276. return iterable ? iterable : [];
  3277. });
  3278. this.registerFunction('builtins.slice', function(start, stop, step) {
  3279. return [ start, stop, step ];
  3280. });
  3281. this.registerFunction('cloudpickle.cloudpickle._builtin_type', function(name) {
  3282. return name;
  3283. });
  3284. this.registerFunction('collections.Counter', function(/* iterable */) {
  3285. return { __module__: 'collections', __name__: 'Counter' };
  3286. });
  3287. this.registerFunction('collections.defaultdict', function(/* default_factory */) {
  3288. return {};
  3289. });
  3290. this.registerFunction('copy_reg._reconstructor', function(cls, base, state) {
  3291. // copyreg._reconstructor in Python 3
  3292. if (base === '__builtin__.object' || base === self._builtins.object) {
  3293. return self.invoke(cls, []);
  3294. }
  3295. else if (base === '__builtin__.tuple' || base === self._builtins.tuple) {
  3296. const obj = self.invoke(cls, []);
  3297. for (let i = 0; i < state.length; i++) {
  3298. obj[i] = state[i];
  3299. }
  3300. return obj;
  3301. }
  3302. throw new python.Error("Unsupported copy_reg._reconstructor base type '" + base + "'.");
  3303. });
  3304. this.registerFunction('copy.deepcopy', function(/* x */) {
  3305. throw new python.Error('Unsupported copy.deepcopy().');
  3306. });
  3307. this.registerFunction('dill._dill._create_cell', function(/* args */) {
  3308. return function() {
  3309. // TODO
  3310. };
  3311. });
  3312. this.registerFunction('dill._dill._create_code', function(args) {
  3313. return self.invoke('types.CodeType', [ args ]);
  3314. });
  3315. this.registerFunction('dill._dill._create_function', function(/* fcode, fglobals, fname, fdefaults, fclosure, fdict, fkwdefaults */) {
  3316. return function() {
  3317. // TODO
  3318. };
  3319. });
  3320. this.registerFunction('dill._dill._create_namedtuple', function(name, fieldnames, modulename /*, defaults */) {
  3321. const obj = execution.invoke('dill._dill._import_module', [ modulename + '.' + name ]);
  3322. if (obj) {
  3323. return obj;
  3324. }
  3325. return undefined;
  3326. });
  3327. this.registerFunction('dill._dill._get_attr', function(self, name) {
  3328. if (Object.prototype.hasOwnProperty.call(self, name)) {
  3329. return self[name];
  3330. }
  3331. return undefined;
  3332. });
  3333. this.registerFunction('dill._dill._import_module', function(import_name, safe) {
  3334. try {
  3335. if (import_name.startsWith('__runtime__.')) {
  3336. return execution.module(import_name);
  3337. }
  3338. else if (import_name.indexOf('.') === -1) {
  3339. return execution.__import__(import_name);
  3340. }
  3341. return execution.resolve(import_name);
  3342. }
  3343. catch (err) {
  3344. if (safe) {
  3345. return null;
  3346. }
  3347. throw err;
  3348. }
  3349. });
  3350. this.registerFunction('dill._dill._load_type', function(name) {
  3351. return self.resolve('types.' + name);
  3352. });
  3353. this.registerFunction('lasagne.nonlinearities.rectify', function() {
  3354. throw new python.Error('Function not implemented.');
  3355. });
  3356. this.registerFunction('lasagne.nonlinearities.softmax', function() {
  3357. throw new python.Error('Function not implemented.');
  3358. });
  3359. this.registerFunction('lasagne.objectives.categorical_crossentropy', function() {
  3360. throw new python.Error('Function not implemented.');
  3361. });
  3362. this.registerFunction('lasagne.updates.nesterov_momentum', function() {
  3363. throw new python.Error('Function not implemented.');
  3364. });
  3365. this.registerFunction('msgpack.unpackb', function(packed, ext_hook) {
  3366. const BinaryReader = class {
  3367. constructor(buffer, ext_hook) {
  3368. // https://github.com/msgpack/msgpack-javascript/blob/master/src/Decoder.ts
  3369. // https://github.com/msgpack/msgpack-python/blob/main/msgpack/_unpacker.pyx
  3370. this._buffer = buffer;
  3371. this._position = 0;
  3372. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  3373. this._ext_hook = ext_hook;
  3374. }
  3375. value() {
  3376. const c = this._view.getUint8(this.skip(1));
  3377. if (c >= 0xe0) {
  3378. return c - 0x100;
  3379. }
  3380. if (c < 0xC0) {
  3381. if (c < 0x80) {
  3382. return c;
  3383. }
  3384. if (c < 0x90) {
  3385. return this.map(c - 0x80);
  3386. }
  3387. if (c < 0xa0) {
  3388. return this.array(c - 0x90);
  3389. }
  3390. return this.string(c - 0xa0);
  3391. }
  3392. switch (c) {
  3393. case 0xC0: return null;
  3394. case 0xC2: return false;
  3395. case 0xC3: return true;
  3396. case 0xC4: return this.read(this._view.getUint8(this.skip(1)));
  3397. case 0xC5: return this.read(this._view.getUint16(this.skip(2)));
  3398. case 0xC6: return this.read(this._view.getUint32(this.skip(4)));
  3399. case 0xC7: return this.extension(this._view.getUint8(this.skip(1)));
  3400. case 0xC8: return this.extension(this._view.getUint16(this.skip(2)));
  3401. case 0xC9: return this.extension(this._view.getUint32(this.skip(4)));
  3402. case 0xCA: return this._view.getFloat32(this.skip(4));
  3403. case 0xCB: return this._view.getFloat64(this.skip(8));
  3404. case 0xCC: return this._view.getUint8(this.skip(1));
  3405. case 0xCD: return this._view.getUint16(this.skip(2));
  3406. case 0xCE: return this._view.getUint32(this.skip(4));
  3407. case 0xCF: return this._view.getUint64(this.skip(8));
  3408. case 0xD0: return this._view.getInt8(this.skip(1));
  3409. case 0xD1: return this._view.getInt16(this.skip(2));
  3410. case 0xD2: return this._view.getInt32(this.skip(4));
  3411. case 0xD3: return this._view.getInt64(this.skip(8));
  3412. case 0xD4: return this.extension(1);
  3413. case 0xD5: return this.extension(2);
  3414. case 0xD6: return this.extension(4);
  3415. case 0xD7: return this.extension(8);
  3416. case 0xD8: return this.extension(16);
  3417. case 0xD9: return this.string(this._view.getUint8(this.skip(1)));
  3418. case 0xDA: return this.string(this._view.getUint16(this.skip(2)));
  3419. case 0xDB: return this.string(this._view.getUint32(this.skip(4)));
  3420. case 0xDC: return this.array(this._view.getUint16(this.skip(2)));
  3421. case 0xDD: return this.array(this._view.getUint32(this.skip(4)));
  3422. case 0xDE: return this.map(this._view.getUint16(this.skip(2)));
  3423. case 0xDF: return this.map(this._view.getUint32(this.skip(4)));
  3424. default: throw new python.Error("Invalid code '" + c + "'.");
  3425. }
  3426. }
  3427. map(size) {
  3428. const map = {};
  3429. for (let i = 0; i < size; i++) {
  3430. const key = this.value();
  3431. const value = this.value();
  3432. map[key] = value;
  3433. }
  3434. return map;
  3435. }
  3436. array(size) {
  3437. const array = new Array(size);
  3438. for (let i = 0; i < size; i++) {
  3439. array[i] = this.value();
  3440. }
  3441. return array;
  3442. }
  3443. extension(size) {
  3444. const code = this._view.getUint8(this.skip(1));
  3445. const data = this.read(size);
  3446. return this._ext_hook(code, data);
  3447. }
  3448. skip(offset) {
  3449. const position = this._position;
  3450. this._position += offset;
  3451. if (this._position > this._buffer.length) {
  3452. throw new python.Error('Expected ' + (this._position - this._buffer.length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  3453. }
  3454. return position;
  3455. }
  3456. read(size) {
  3457. const data = this._buffer.subarray(this._position, this._position + size);
  3458. this._position += size;
  3459. return data;
  3460. }
  3461. string(size) {
  3462. const buffer = this.read(size);
  3463. this._decoder = this._decoder || new TextDecoder('utf8');
  3464. return this._decoder.decode(buffer);
  3465. }
  3466. };
  3467. return new BinaryReader(packed, ext_hook).value();
  3468. });
  3469. this.registerFunction('nolearn.lasagne.base.objective', function() {
  3470. throw new python.Error('Function not implemented.');
  3471. });
  3472. this.registerFunction('numpy._reconstruct', function(subtype, shape, dtype) {
  3473. return self.invoke(subtype, [ shape, dtype ]);
  3474. });
  3475. this.registerFunction('numpy.core._multiarray_umath._reconstruct', function(subtype, shape, dtype) {
  3476. return self.invoke(subtype, [ shape, dtype ]);
  3477. });
  3478. this.registerFunction('numpy.core.multiarray._reconstruct', function(subtype, shape, dtype) {
  3479. return self.invoke(subtype, [ shape, dtype ]);
  3480. });
  3481. this.registerFunction('numpy.core.multiarray.scalar', function(dtype, rawData) {
  3482. let data = rawData;
  3483. if (typeof rawData === 'string' || rawData instanceof String) {
  3484. data = new Uint8Array(rawData.length);
  3485. for (let i = 0; i < rawData.length; i++) {
  3486. data[i] = rawData.charCodeAt(i);
  3487. }
  3488. }
  3489. switch (dtype.kind) {
  3490. case 'b': {
  3491. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3492. switch (dtype.itemsize) {
  3493. case 1: return view.getInt8(0) ? true : false;
  3494. default: throw new python.Error("Unsupported scalar dtype boolean itemsize '" + dtype.itemsize + "'.");
  3495. }
  3496. }
  3497. case 'f': {
  3498. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3499. switch (dtype.itemsize) {
  3500. case 4: return view.getFloat32(0, dtype.byteorder === '<');
  3501. case 8: return view.getFloat64(0, dtype.byteorder === '<');
  3502. default: throw new python.Error("Unsupported scalar dtype float itemsize '" + dtype.itemsize + "'.");
  3503. }
  3504. }
  3505. case 'i': {
  3506. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3507. switch (dtype.itemsize) {
  3508. case 1: return view.getInt8(0);
  3509. case 2: return view.getInt16(0, dtype.byteorder === '<');
  3510. case 4: return view.getInt32(0, dtype.byteorder === '<');
  3511. case 8: return view.getInt64(0, dtype.byteorder === '<');
  3512. default: throw new python.Error("Unsupported scalar dtype int itemsize '" + dtype.itemsize + "'.");
  3513. }
  3514. }
  3515. case 'u': {
  3516. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3517. switch (dtype.itemsize) {
  3518. case 1: return view.getUint8(0);
  3519. case 2: return view.getUint16(0, dtype.byteorder === '<');
  3520. case 4: return view.getUint32(0, dtype.byteorder === '<');
  3521. case 8: return view.getUint64(0, dtype.byteorder === '<');
  3522. default: throw new python.Error("Unsupported scalar dtype uint itemsize '" + dtype.itemsize + "'.");
  3523. }
  3524. }
  3525. case 'U': {
  3526. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3527. const list = [];
  3528. for (let i = 0; i < dtype.itemsize; i += 4) {
  3529. list.push(String.fromCodePoint(view.getUint32(i, true)));
  3530. }
  3531. return list.join('');
  3532. }
  3533. default: {
  3534. throw new python.Error("Unsupported scalar dtype kind '" + dtype.kind + "'.");
  3535. }
  3536. }
  3537. });
  3538. this.registerFunction('numpy.core._multiarray_umath.scalar', function(dtype, rawData) {
  3539. let data = rawData;
  3540. if (typeof rawData === 'string') {
  3541. data = new Uint8Array(rawData.length);
  3542. for (let i = 0; i < rawData.length; i++) {
  3543. data[i] = rawData.charCodeAt(i);
  3544. }
  3545. }
  3546. const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3547. switch (dtype.__name__) {
  3548. case 'uint8':
  3549. return dataView.getUint8(0);
  3550. case 'float32':
  3551. return dataView.getFloat32(0, true);
  3552. case 'float64':
  3553. return dataView.getFloat64(0, true);
  3554. case 'int8':
  3555. return dataView.getInt8(0, true);
  3556. case 'int16':
  3557. return dataView.getInt16(0, true);
  3558. case 'int32':
  3559. return dataView.getInt32(0, true);
  3560. case 'int64':
  3561. return dataView.getInt64(0, true);
  3562. default:
  3563. throw new python.Error("Unsupported scalar type '" + dtype.__name__ + "'.");
  3564. }
  3565. });
  3566. this.registerFunction('numpy.load', function(file) {
  3567. // https://github.com/numpy/numpy/blob/main/numpy/lib/format.py
  3568. const signature = [ 0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59 ];
  3569. if (!file.read(6).every((v, i) => v == signature[i])) {
  3570. throw new python.Error('Invalid signature.');
  3571. }
  3572. const major = file.read(1)[0];
  3573. const minor = file.read(1)[0];
  3574. if (major > 3) {
  3575. throw new python.Error("Invalid version '" + [ major, minor ].join('.') + "'.");
  3576. }
  3577. const buffer = new Uint8Array([ 0, 0, 0, 0 ]);
  3578. buffer.set(file.read(major >= 2 ? 4 : 2), 0);
  3579. const header_length = buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0];
  3580. let header = file.read(header_length);
  3581. const decoder = new TextDecoder(major >= 3 ? 'utf-8' : 'ascii');
  3582. header = decoder.decode(header);
  3583. header = JSON.parse(header.replace(/\(/,'[').replace(/\)/,']').replace('[,','[1,]').replace(',]',',1]').replace(/'/g, '"').replace(/:\s*False\s*,/,':false,').replace(/:\s*True\s*,/,':true,').replace(/,\s*\}/, ' }'));
  3584. if (!header.descr || header.descr.length < 2) {
  3585. throw new python.Error("Missing property 'descr'.");
  3586. }
  3587. if (!header.shape) {
  3588. throw new python.Error("Missing property 'shape'.");
  3589. }
  3590. const shape = header.shape;
  3591. const dtype = self.invoke('numpy.dtype', [ header.descr.substring(1) ]);
  3592. dtype.byteorder = header.descr[0];
  3593. let data = null;
  3594. switch (dtype.byteorder) {
  3595. case '|': {
  3596. data = file.read();
  3597. if (dtype.kind === 'O') {
  3598. const unpickler = execution.invoke('pickle.Unpickler', [ data ]);
  3599. return unpickler.load();
  3600. }
  3601. break;
  3602. }
  3603. case '>':
  3604. case '<': {
  3605. if (header.descr.length !== 3) {
  3606. throw new python.Error("Unsupported data type '" + header.descr + "'.");
  3607. }
  3608. const count = shape.length === 0 ? 1 : shape.reduce((a, b) => a * b, 1);
  3609. data = file.read(dtype.itemsize * count);
  3610. break;
  3611. }
  3612. default: {
  3613. throw new python.Error("Unsupported data type '" + header.descr + "'.");
  3614. }
  3615. }
  3616. if (header.fortran_order) {
  3617. data = null;
  3618. }
  3619. return self.invoke('numpy.ndarray', [ shape, dtype, data ]);
  3620. });
  3621. this.registerFunction('numpy.save', function(file, arr) {
  3622. const descr = arr.dtype.str;
  3623. if (descr[0] !== '<' && descr[0] !== '>') {
  3624. throw new python.Error("Unsupported byte order '" + descr + "'.");
  3625. }
  3626. if (descr.length !== 3 || (descr[1] !== 'f' && descr[1] !== 'i' && descr[1] !== 'u' && descr[1] !== 'c' && descr.substring(1) !== 'b1')) {
  3627. throw new python.Error("Unsupported data type '" + descr + "'.");
  3628. }
  3629. let shape = '';
  3630. switch (arr.shape.length) {
  3631. case 0: shape = '()'; break;
  3632. case 1: shape = '(' + arr.shape[0].toString() + ',)'; break;
  3633. default: shape = '(' + arr.shape.map((dimension) => dimension.toString()).join(', ') + ')'; break;
  3634. }
  3635. const properties = [
  3636. "'descr': '" + descr + "'",
  3637. "'fortran_order': False",
  3638. "'shape': " + shape
  3639. ];
  3640. let header = '{ ' + properties.join(', ') + ' }';
  3641. header += ' '.repeat(64 - ((header.length + 2 + 8 + 1) & 0x3f)) + '\n';
  3642. const encoder = new TextEncoder('ascii');
  3643. file.write([ 0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59, 0x01, 0x00 ]); // '\\x93NUMPY' + version
  3644. file.write([ header.length & 0xff, (header.length >> 8) & 0xff ]);
  3645. file.write(encoder.encode(header));
  3646. file.write(arr.tobytes());
  3647. });
  3648. this.registerFunction('numpy.asarray', function(a, dtype) {
  3649. const encode = (context, data, dim) => {
  3650. const size = context.shape[dim];
  3651. const littleendian = context.littleendian;
  3652. if (dim == context.shape.length - 1) {
  3653. for (let i = 0; i < size; i++) {
  3654. switch (context.dtype) {
  3655. case 'f2':
  3656. context.view.setFloat16(context.position, data[i], littleendian);
  3657. break;
  3658. case 'f4':
  3659. context.view.setFloat32(context.position, data[i], littleendian);
  3660. break;
  3661. case 'f8':
  3662. context.view.setFloat64(context.position, data[i], littleendian);
  3663. break;
  3664. case 'i1':
  3665. context.view.setInt8(context.position, data[i], littleendian);
  3666. break;
  3667. case 'i2':
  3668. context.view.setInt16(context.position, data[i], littleendian);
  3669. break;
  3670. case 'i4':
  3671. context.view.setInt32(context.position, data[i], littleendian);
  3672. break;
  3673. case 'i8':
  3674. context.view.setInt64(context.position, data[i], littleendian);
  3675. break;
  3676. case 'u1':
  3677. context.view.setUint8(context.position, data[i], littleendian);
  3678. break;
  3679. case 'u2':
  3680. context.view.setUint16(context.position, data[i], littleendian);
  3681. break;
  3682. case 'u4':
  3683. context.view.setUint32(context.position, data[i], littleendian);
  3684. break;
  3685. case 'u8':
  3686. context.view.setUint64(context.position, data[i], littleendian);
  3687. break;
  3688. case 'c8':
  3689. context.view.setComplex64(context.position, data[i], littleendian);
  3690. break;
  3691. case 'c16':
  3692. context.view.setComplex128(context.position, data[i], littleendian);
  3693. break;
  3694. default:
  3695. throw new python.Error("Unsupported tensor data type '" + context.dtype + "'.");
  3696. }
  3697. context.position += context.itemsize;
  3698. }
  3699. }
  3700. else {
  3701. for (let j = 0; j < size; j++) {
  3702. encode(context, data[j], dim + 1);
  3703. }
  3704. }
  3705. };
  3706. const array_size = (value) => {
  3707. if (value.every((item) => Array.isArray(item))) {
  3708. const dims = value.map((item) => array_size(item));
  3709. const dim = dims[0];
  3710. for (let i = 1; i < dims.length; i++) {
  3711. if (dim.length === dims[i].length) {
  3712. if (!dims[i].every((value, i) => value ===dim[i])) {
  3713. throw new python.Error('Invalid array shape.');
  3714. }
  3715. }
  3716. }
  3717. return [ value.length ].concat(dim);
  3718. }
  3719. return [ value.length ];
  3720. };
  3721. const shape = Array.isArray(a) ? array_size(a) : [];
  3722. const size = dtype.itemsize * shape.reduce((a, b) => a * b, 1);
  3723. const context = {
  3724. position: 0,
  3725. itemsize: dtype.itemsize,
  3726. dtype: dtype.str.substring(1),
  3727. littleendian: dtype.str[0],
  3728. shape: shape,
  3729. data: new Uint8Array(size)
  3730. };
  3731. context.view = new DataView(context.data.buffer, context.data.byteOffset, size);
  3732. encode(context, a, 0);
  3733. return self.invoke('numpy.ndarray', [ shape, dtype, context.data ]);
  3734. });
  3735. this.registerFunction('numpy.ma.core._mareconstruct', function(subtype, baseclass, baseshape, basetype) {
  3736. const data = self.invoke(baseclass, [ baseshape, basetype ]);
  3737. // = ndarray.__new__(ndarray, baseshape, make_mask_descr(basetype))
  3738. const mask = self.invoke('numpy.ndarray', [ baseshape, '' ]);
  3739. return self.invoke(subtype, [ data, mask, basetype ]);
  3740. });
  3741. this.registerFunction('numpy.random.__RandomState_ctor', function() {
  3742. return {};
  3743. });
  3744. this.registerFunction('numpy.random._pickle.__randomstate_ctor', function() {
  3745. return {};
  3746. });
  3747. this.registerFunction('numpy.core.numeric._frombuffer', function(/* buf, dtype, shape, order */) {
  3748. return {};
  3749. });
  3750. this.registerFunction('sklearn.metrics.scorer._passthrough_scorer', function() {
  3751. throw new python.Error("Function not implemented.");
  3752. });
  3753. this.registerFunction('sklearn.feature_selection._univariate_selection.f_classif', function() {
  3754. throw new python.Error("Function not implemented.");
  3755. });
  3756. this.registerFunction('re._compile', function(pattern, flags) {
  3757. return self.invoke('re.Pattern', [ pattern, flags ]);
  3758. });
  3759. this.registerFunction('srsly.cloudpickle.cloudpickle._builtin_type', function(name) {
  3760. return function() {
  3761. return self.invoke('types.' + name, arguments);
  3762. };
  3763. });
  3764. this.registerFunction('theano.scalar.basic.same_out', function() {
  3765. throw new python.Error('Function not implemented.');
  3766. });
  3767. this.registerFunction('theano.scalar.basic.same_out_nocomplex', function() {
  3768. throw new python.Error('Function not implemented.');
  3769. });
  3770. this.registerFunction('theano.scalar.basic.upcast_out', function() {
  3771. throw new python.Error('Function not implemented.');
  3772. });
  3773. this.registerFunction('theano.scalar.basic.upgrade_to_float', function() {
  3774. throw new python.Error('Function not implemented.');
  3775. });
  3776. this.registerFunction('theano.tensor.nnet.conv2d', function() {
  3777. throw new python.Error('Function not implemented.');
  3778. });
  3779. this.registerFunction('theano.tensor.type.values_eq_approx_remove_inf_nan', function() {
  3780. throw new python.Error('Function not implemented.');
  3781. });
  3782. this.registerFunction('theano.tensor.type.values_eq_approx_remove_nan', function() {
  3783. throw new python.Error('Function not implemented.');
  3784. });
  3785. this.registerType('torch.ao.quantization.observer._PartialWrapper', class {});
  3786. this.registerType('torch.ao.quantization.observer.HistogramObserver', class {});
  3787. this.registerType('torch.ao.quantization.observer.MovingAverageMinMaxObserver', class {});
  3788. this.registerType('torch.ao.quantization.observer.PerChannelMinMaxObserver', class {});
  3789. this.registerType('torch.ao.quantization.qconfig.QConfig', class {});
  3790. this.registerType('torch.ao.quantization.stubs.DeQuantStub', class {});
  3791. this.registerType('torch.ao.quantization.stubs.QuantStub', class {});
  3792. this.registerType('torch.autograd.variable.Variable', class {});
  3793. this.registerType('torch.backends.cudnn.rnn.Unserializable', class {});
  3794. this.registerType('torch.distributions.bernoulli.Bernoulli', class {});
  3795. this.registerType('torch.distributions.constraints._LowerCholesky', class {});
  3796. this.registerType('torch.distributions.constraints._Real', class {});
  3797. this.registerType('torch.distributions.multivariate_normal.MultivariateNormal', class {});
  3798. this.registerType('torch.distributions.normal.Normal', class {});
  3799. this.registerType('torch.distributions.transforms.LowerCholeskyTransform', class {});
  3800. this.registerType('torch.distributions.uniform.Uniform', class {});
  3801. this.registerType('torch.nn.backends.thnn._get_thnn_function_backend', class {});
  3802. this.registerType('torch.nn.intrinsic.modules.fused.ConvBnReLU2d', class {});
  3803. this.registerType('torch.nn.intrinsic.modules.fused.ConvReLU2d', class {});
  3804. this.registerType('torch.nn.intrinsic.modules.fused.BNReLU2d', class {});
  3805. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBn2d', class {});
  3806. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  3807. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvReLU2d', class {});
  3808. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class {});
  3809. this.registerType('torch.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class {});
  3810. this.registerType('torch.nn.modules.activation.CELU', class {});
  3811. this.registerType('torch.nn.modules.activation.ELU', class {});
  3812. this.registerType('torch.nn.modules.activation.GELU', class {});
  3813. this.registerType('torch.nn.modules.activation.GLU', class {});
  3814. this.registerType('torch.nn.modules.activation.Hardtanh', class {});
  3815. this.registerType('torch.nn.modules.activation.Hardswish', class {});
  3816. this.registerType('torch.nn.modules.activation.Hardsigmoid', class {});
  3817. this.registerType('torch.nn.modules.activation.LeakyReLU', class {});
  3818. this.registerType('torch.nn.modules.activation.LogSigmoid', class {});
  3819. this.registerType('torch.nn.modules.activation.LogSoftmax', class {});
  3820. this.registerType('torch.nn.modules.activation.Mish', class {});
  3821. this.registerType('torch.nn.modules.activation.MultiheadAttention', class {});
  3822. this.registerType('torch.nn.modules.activation.ReLU', class {});
  3823. this.registerType('torch.nn.modules.activation.ReLU6', class {});
  3824. this.registerType('torch.nn.modules.activation.PReLU', class {});
  3825. this.registerType('torch.nn.modules.activation.RReLU', class {});
  3826. this.registerType('torch.nn.modules.activation.SELU', class {});
  3827. this.registerType('torch.nn.modules.activation.Sigmoid', class {});
  3828. this.registerType('torch.nn.modules.activation.SiLU', class {});
  3829. this.registerType('torch.nn.modules.activation.Softmax', class {});
  3830. this.registerType('torch.nn.modules.activation.Softmax2d', class {});
  3831. this.registerType('torch.nn.modules.activation.Softplus', class {});
  3832. this.registerType('torch.nn.modules.activation.Tanh', class {});
  3833. this.registerType('torch.nn.modules.activation.Tanhshrink', class {});
  3834. this.registerType('torch.nn.modules.activation.Threshold', class {});
  3835. this.registerType('torch.nn.modules.batchnorm.BatchNorm1d', class {});
  3836. this.registerType('torch.nn.modules.batchnorm.BatchNorm2d', class {});
  3837. this.registerType('torch.nn.modules.batchnorm.BatchNorm3d', class {});
  3838. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm1d', class {});
  3839. this.registerType('torch.nn.modules.batchnorm.SyncBatchNorm', class {});
  3840. this.registerType('torch.nn.modules.container.ModuleDict', class {});
  3841. this.registerType('torch.nn.modules.container.ModuleList', class {});
  3842. this.registerType('torch.nn.modules.container.ParameterDict', class {});
  3843. this.registerType('torch.nn.modules.container.ParameterList', class {});
  3844. this.registerType('torch.nn.modules.container.Sequential', class {});
  3845. this.registerType('torch.nn.modules.conv.Conv1d', class {});
  3846. this.registerType('torch.nn.modules.conv.Conv2d', class {});
  3847. this.registerType('torch.nn.modules.conv.Conv3d', class {});
  3848. this.registerType('torch.nn.modules.conv.ConvTranspose1d', class {});
  3849. this.registerType('torch.nn.modules.conv.ConvTranspose2d', class {});
  3850. this.registerType('torch.nn.modules.conv.ConvTranspose3d', class {});
  3851. this.registerType('torch.nn.modules.distance.CosineSimilarity', class {});
  3852. this.registerType('torch.nn.modules.dropout.AlphaDropout', class {});
  3853. this.registerType('torch.nn.modules.dropout.Dropout', class {});
  3854. this.registerType('torch.nn.modules.dropout.Dropout2d', class {});
  3855. this.registerType('torch.nn.modules.dropout.Dropout3d', class {});
  3856. this.registerType('torch.nn.modules.fold.Fold', class {});
  3857. this.registerType('torch.nn.modules.fold.Unfold', class {});
  3858. this.registerType('torch.nn.modules.flatten.Flatten', class {});
  3859. this.registerType('torch.nn.modules.flatten.Unflatten', class {});
  3860. this.registerType('torch.nn.modules.instancenorm.InstanceNorm1d', class {});
  3861. this.registerType('torch.nn.modules.instancenorm.InstanceNorm2d', class {});
  3862. this.registerType('torch.nn.modules.instancenorm.InstanceNorm3d', class {});
  3863. this.registerType('torch.nn.modules.linear._LinearWithBias', class {});
  3864. this.registerType('torch.nn.modules.linear.Bilinear', class {});
  3865. this.registerType('torch.nn.modules.linear.Identity', class {});
  3866. this.registerType('torch.nn.modules.linear.LazyLinear', class {});
  3867. this.registerType('torch.nn.modules.linear.Linear', class {});
  3868. this.registerType('torch.nn.modules.linear.NonDynamicallyQuantizableLinear', class {});
  3869. this.registerType('torch.nn.modules.loss.BCELoss', class {});
  3870. this.registerType('torch.nn.modules.loss.BCEWithLogitsLoss', class {});
  3871. this.registerType('torch.nn.modules.loss.CrossEntropyLoss', class {});
  3872. this.registerType('torch.nn.modules.loss.CTCLoss', class {});
  3873. this.registerType('torch.nn.modules.loss.KLDivLoss', class {});
  3874. this.registerType('torch.nn.modules.loss.L1Loss', class {});
  3875. this.registerType('torch.nn.modules.loss.MarginRankingLoss', class {});
  3876. this.registerType('torch.nn.modules.loss.MSELoss', class {});
  3877. this.registerType('torch.nn.modules.loss.NLLLoss', class {});
  3878. this.registerType('torch.nn.modules.loss.NLLLoss2d', class {});
  3879. this.registerType('torch.nn.modules.loss.SmoothL1Loss', class {});
  3880. this.registerType('torch.nn.modules.module._IncompatibleKeys', class {});
  3881. this.registerType('torch.nn.modules.module.Module', class {});
  3882. this.registerType('torch.nn.modules.module.PatchForward', class {});
  3883. this.registerType('torch.nn.modules.normalization.CrossMapLRN2d', class {});
  3884. this.registerType('torch.nn.modules.normalization.GroupNorm', class {});
  3885. this.registerType('torch.nn.modules.normalization.LayerNorm', class {});
  3886. this.registerType('torch.nn.modules.normalization.LocalResponseNorm', class {});
  3887. this.registerType('torch.nn.modules.padding.ReflectionPad1d', class {});
  3888. this.registerType('torch.nn.modules.padding.ReflectionPad2d', class {});
  3889. this.registerType('torch.nn.modules.padding.ReplicationPad1d', class {});
  3890. this.registerType('torch.nn.modules.padding.ReplicationPad2d', class {});
  3891. this.registerType('torch.nn.modules.padding.ReplicationPad3d', class {});
  3892. this.registerType('torch.nn.modules.padding.ZeroPad2d', class {});
  3893. this.registerType('torch.nn.modules.padding.ConstantPad1d', class {});
  3894. this.registerType('torch.nn.modules.padding.ConstantPad2d', class {});
  3895. this.registerType('torch.nn.modules.padding.ConstantPad3d', class {});
  3896. this.registerType('torch.nn.modules.pixelshuffle.PixelShuffle', class {});
  3897. this.registerType('torch.nn.modules.pixelshuffle.PixelUnshuffle', class {});
  3898. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool1d', class {});
  3899. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool2d', class {});
  3900. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool3d', class {});
  3901. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool1d', class {});
  3902. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool2d', class {});
  3903. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool3d', class {});
  3904. this.registerType('torch.nn.modules.pooling.AvgPool1d', class {});
  3905. this.registerType('torch.nn.modules.pooling.AvgPool2d', class {});
  3906. this.registerType('torch.nn.modules.pooling.AvgPool3d', class {});
  3907. this.registerType('torch.nn.modules.pooling.FractionalMaxPool2d', class {});
  3908. this.registerType('torch.nn.modules.pooling.LPPool2d', class {});
  3909. this.registerType('torch.nn.modules.pooling.MaxPool1d', class {});
  3910. this.registerType('torch.nn.modules.pooling.MaxPool2d', class {});
  3911. this.registerType('torch.nn.modules.pooling.MaxPool3d', class {});
  3912. this.registerType('torch.nn.modules.pooling.MaxUnpool1d', class {});
  3913. this.registerType('torch.nn.modules.pooling.MaxUnpool2d', class {});
  3914. this.registerType('torch.nn.modules.pooling.MaxUnpool3d', class {});
  3915. this.registerType('torch.nn.modules.rnn.GRU', class {});
  3916. this.registerType('torch.nn.modules.rnn.GRUCell', class {});
  3917. this.registerType('torch.nn.modules.rnn.LSTM', class {});
  3918. this.registerType('torch.nn.modules.rnn.LSTMCell', class {});
  3919. this.registerType('torch.nn.modules.rnn.RNN', class {});
  3920. this.registerType('torch.nn.modules.rnn.RNNCell', class {});
  3921. this.registerType('torch.nn.modules.sparse.Embedding', class {});
  3922. this.registerType('torch.nn.modules.sparse.EmbeddingBag', class {});
  3923. this.registerType('torch.nn.modules.transformer.Transformer', class {});
  3924. this.registerType('torch.nn.modules.transformer.TransformerDecoder', class {});
  3925. this.registerType('torch.nn.modules.transformer.TransformerDecoderLayer', class {});
  3926. this.registerType('torch.nn.modules.transformer.TransformerEncoder', class {});
  3927. this.registerType('torch.nn.modules.transformer.TransformerEncoderLayer', class {});
  3928. this.registerType('torch.nn.modules.upsampling.Upsample', class {});
  3929. this.registerType('torch.nn.modules.upsampling.UpsamplingBilinear2d', class {});
  3930. this.registerType('torch.nn.modules.upsampling.UpsamplingNearest2d', class {});
  3931. this.registerType('torch.nn.parallel.data_parallel.DataParallel', class {});
  3932. this.registerType('torch.nn.parallel.distributed._DDPUnevenInputsConfig', class {});
  3933. this.registerType('torch.nn.parallel.distributed.DistributedDataParallel', class {});
  3934. this.registerType('torch.nn.qat.modules.conv.Conv2d', class {});
  3935. this.registerType('torch.nn.qat.modules.linear.Linear', class {});
  3936. this.registerType('torch.nn.quantized.modules.activation.ReLU', class {});
  3937. this.registerType('torch.nn.quantized.modules.activation.LeakyReLU', class {});
  3938. this.registerType('torch.nn.quantized.dynamic.modules.linear.Linear', class {});
  3939. this.registerType('torch.nn.quantized.dynamic.modules.rnn.GRU', class {});
  3940. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTM', class {});
  3941. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTMCell', class {});
  3942. this.registerType('torch.nn.quantized.dynamic.modules.rnn.PackedParameter', class {});
  3943. this.registerType('torch.nn.quantized.modules.activation.ReLU6', class {});
  3944. this.registerType('torch.nn.quantized.modules.batchnorm.BatchNorm2d', class {});
  3945. this.registerType('torch.nn.quantized.modules.conv.Conv1d', class {});
  3946. this.registerType('torch.nn.quantized.modules.conv.Conv2d', class {});
  3947. this.registerType('torch.nn.quantized.modules.conv.ConvTranspose2d', class {});
  3948. this.registerType('torch.nn.quantized.modules.DeQuantize', class {});
  3949. this.registerType('torch.nn.quantized.modules.dropout.Dropout', class {});
  3950. this.registerType('torch.nn.quantized.modules.embedding_ops.Embedding', class {});
  3951. this.registerType('torch.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class {});
  3952. this.registerType('torch.nn.quantized.modules.functional_modules.FloatFunctional', class {});
  3953. this.registerType('torch.nn.quantized.modules.functional_modules.QFunctional', class {});
  3954. this.registerType('torch.nn.quantized.modules.linear.Linear', class {});
  3955. this.registerType('torch.nn.quantized.modules.linear.LinearPackedParams', class {});
  3956. this.registerType('torch.nn.quantized.modules.normalization.InstanceNorm2d', class {});
  3957. this.registerType('torch.nn.quantized.modules.normalization.LayerNorm', class {});
  3958. this.registerType('torch.nn.quantized.modules.Quantize', class {});
  3959. this.registerType('torch.nn.utils.prune.L1Unstructured', class {});
  3960. this.registerType('torch.nn.utils.spectral_norm.SpectralNorm', class {});
  3961. this.registerType('torch.nn.utils.spectral_norm.SpectralNormStateDictHook', class {});
  3962. this.registerType('torch.nn.utils.spectral_norm.SpectralNormLoadStateDictPreHook', class {});
  3963. this.registerType('torch.nn.utils.weight_norm.WeightNorm', class {});
  3964. this.registerType('torch.torch_version.TorchVersion', class extends String {});
  3965. this.registerType('torch.optim.adam.Adam', class {});
  3966. this.registerType('torch.optim.adamw.AdamW', class {});
  3967. this.registerType('torch.optim.adagrad.Adagrad', class {});
  3968. this.registerType('torch.optim.adadelta.Adadelta', class {});
  3969. this.registerType('torch.optim.lr_scheduler.CosineAnnealingLR', class {});
  3970. this.registerType('torch.optim.lr_scheduler.CyclicLR', class {});
  3971. this.registerType('torch.optim.lr_scheduler.ExponentialLR', class {});
  3972. this.registerType('torch.optim.lr_scheduler.LambdaLR', class {});
  3973. this.registerType('torch.optim.lr_scheduler.MultiStepLR', class {});
  3974. this.registerType('torch.optim.lr_scheduler.OneCycleLR', class {});
  3975. this.registerType('torch.optim.lr_scheduler.ReduceLROnPlateau', class {});
  3976. this.registerType('torch.optim.lr_scheduler.StepLR', class {});
  3977. this.registerType('torch.optim.optimizer._RequiredParameter', class {});
  3978. this.registerType('torch.optim.rmsprop.RMSprop', class {});
  3979. this.registerType('torch.optim.sgd.SGD', class {});
  3980. this.registerType('torch.optim.sparse_adam.SparseAdam', class {});
  3981. this.registerType('torch.quantization.fake_quantize.FakeQuantize', class {});
  3982. this.registerType('torch.quantization.observer._PartialWrapper', class {});
  3983. this.registerType('torch.quantization.observer.MinMaxObserver', class {});
  3984. this.registerType('torch.quantization.observer.MovingAverageMinMaxObserver', class {});
  3985. this.registerType('torch.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  3986. this.registerType('torch.quantization.qconfig.QConfig', class {});
  3987. this.registerType('torch.quantization.stubs.DeQuantStub', class {});
  3988. this.registerType('torch.quantization.stubs.QuantStub', class {});
  3989. this.registerType('torch.utils.data.dataloader._MultiProcessingDataLoaderIter', class {});
  3990. this.registerType('torch.utils.data.dataloader.DataLoader', class {});
  3991. this.registerType('torch.utils.data.dataset.Subset', class {});
  3992. this.registerType('torch.utils.data.dataset.ConcatDataset', class {});
  3993. this.registerType('torch.utils.data.dataset.TensorDataset', class {});
  3994. this.registerType('torch.utils.data.sampler.BatchSampler', class {});
  3995. this.registerType('torch.utils.data.sampler.RandomSampler', class {});
  3996. this.registerType('torch.utils.data.sampler.SequentialSampler', class {});
  3997. this.registerType('torchvision.datasets.folder.ImageFolder', class {});
  3998. this.registerType('torchvision.datasets.mnist.MNIST', class {});
  3999. this.registerType('torchvision.datasets.vision.StandardTransform', class {});
  4000. this.registerType('torchvision.models.alexnet.AlexNet', class {});
  4001. this.registerType('torchvision.models.densenet.DenseNet', class {});
  4002. this.registerType('torchvision.models.densenet._DenseBlock', class {});
  4003. this.registerType('torchvision.models.densenet._DenseLayer', class {});
  4004. this.registerType('torchvision.models.densenet._Transition', class {});
  4005. this.registerType('torchvision.models.detection._utils.BalancedPositiveNegativeSampler', class {});
  4006. this.registerType('torchvision.models.detection._utils.BoxCoder', class {});
  4007. this.registerType('torchvision.models.detection._utils.Matcher', class {});
  4008. this.registerType('torchvision.models.detection._utils.SSDMatcher', class {});
  4009. this.registerType('torchvision.models.detection.anchor_utils.AnchorGenerator', class {});
  4010. this.registerType('torchvision.models.detection.anchor_utils.DefaultBoxGenerator', class {});
  4011. this.registerType('torchvision.models.detection.backbone_utils.BackboneWithFPN', class {});
  4012. this.registerType('torchvision.models.detection.faster_rcnn.FasterRCNN', class {});
  4013. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNPredictor', class {});
  4014. this.registerType('torchvision.models.detection.faster_rcnn.TwoMLPHead', class {});
  4015. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNN', class {});
  4016. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNHeads', class {});
  4017. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNPredictor', class {});
  4018. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNN', class {});
  4019. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNHeads', class {});
  4020. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNPredictor', class {});
  4021. this.registerType('torchvision.models.detection.retinanet.RetinaNet', class {});
  4022. this.registerType('torchvision.models.detection.retinanet.RetinaNetClassificationHead', class {});
  4023. this.registerType('torchvision.models.detection.retinanet.RetinaNetHead', class {});
  4024. this.registerType('torchvision.models.detection.retinanet.RetinaNetRegressionHead', class {});
  4025. this.registerType('torchvision.models.detection.roi_heads.RoIHeads', class {});
  4026. this.registerType('torchvision.models.detection.rpn.AnchorGenerator', class {});
  4027. this.registerType('torchvision.models.detection.rpn.RegionProposalNetwork', class {});
  4028. this.registerType('torchvision.models.detection.rpn.RPNHead', class {});
  4029. this.registerType('torchvision.models.detection.ssd.SSD', class {});
  4030. this.registerType('torchvision.models.detection.ssdlite.SSDLiteClassificationHead', class {});
  4031. this.registerType('torchvision.models.detection.ssdlite.SSDLiteFeatureExtractorMobileNet', class {});
  4032. this.registerType('torchvision.models.detection.ssdlite.SSDLiteHead', class {});
  4033. this.registerType('torchvision.models.detection.ssdlite.SSDLiteRegressionHead', class {});
  4034. this.registerType('torchvision.models.detection.transform.GeneralizedRCNNTransform', class {});
  4035. this.registerType('torchvision.models.efficientnet.EfficientNet', class {});
  4036. this.registerType('torchvision.models.efficientnet.MBConv', class {});
  4037. this.registerType('torchvision.models.googlenet.BasicConv2d', class {});
  4038. this.registerType('torchvision.models.googlenet.GoogLeNet', class {});
  4039. this.registerType('torchvision.models.googlenet.Inception', class {});
  4040. this.registerType('torchvision.models.googlenet.InceptionAux', class {});
  4041. this.registerType('torchvision.models.inception.BasicConv2d', class {});
  4042. this.registerType('torchvision.models.inception.Inception3', class {});
  4043. this.registerType('torchvision.models.inception.InceptionAux', class {});
  4044. this.registerType('torchvision.models.inception.InceptionA', class {});
  4045. this.registerType('torchvision.models.inception.InceptionB', class {});
  4046. this.registerType('torchvision.models.inception.InceptionC', class {});
  4047. this.registerType('torchvision.models.inception.InceptionD', class {});
  4048. this.registerType('torchvision.models.inception.InceptionE', class {});
  4049. this.registerType('torchvision.models.mnasnet._InvertedResidual', class {});
  4050. this.registerType('torchvision.models.mnasnet.MNASNet', class {});
  4051. this.registerType('torchvision.models.mobilenet.ConvBNReLU', class {});
  4052. this.registerType('torchvision.models.mobilenet.MobileNetV2', class {});
  4053. this.registerType('torchvision.models.mobilenet.InvertedResidual', class {});
  4054. this.registerType('torchvision.models.mobilenetv2.ConvBNActivation', class {});
  4055. this.registerType('torchvision.models.mobilenetv2.InvertedResidual', class {});
  4056. this.registerType('torchvision.models.mobilenetv2.MobileNetV2', class {});
  4057. this.registerType('torchvision.models.mobilenetv3.InvertedResidual', class {});
  4058. this.registerType('torchvision.models.mobilenetv3.MobileNetV3', class {});
  4059. this.registerType('torchvision.models.mobilenetv3.SqueezeExcitation', class {});
  4060. this.registerType('torchvision.models.resnet.Bottleneck', class {});
  4061. this.registerType('torchvision.models.resnet.BasicBlock', class {});
  4062. this.registerType('torchvision.models.quantization.mobilenet.QuantizableInvertedResidual', class {});
  4063. this.registerType('torchvision.models.quantization.mobilenet.QuantizableMobileNetV2', class {});
  4064. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableInvertedResidual', class {});
  4065. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableMobileNetV2', class {});
  4066. this.registerType('torchvision.models.quantization.resnet.QuantizableBasicBlock', class {});
  4067. this.registerType('torchvision.models.quantization.resnet.QuantizableBottleneck', class {});
  4068. this.registerType('torchvision.models.quantization.resnet.QuantizableResNet', class {});
  4069. this.registerType('torchvision.models.segmentation.deeplabv3.ASPP', class {});
  4070. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPConv', class {});
  4071. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPPooling', class {});
  4072. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabHead', class {});
  4073. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabV3', class {});
  4074. this.registerType('torchvision.models.segmentation.fcn.FCN', class {});
  4075. this.registerType('torchvision.models.segmentation.fcn.FCNHead', class {});
  4076. this.registerType('torchvision.models.shufflenetv2.ShuffleNetV2', class {});
  4077. this.registerType('torchvision.models.shufflenetv2.InvertedResidual', class {});
  4078. this.registerType('torchvision.models.squeezenet.Fire', class {});
  4079. this.registerType('torchvision.models.squeezenet.SqueezeNet', class {});
  4080. this.registerType('torchvision.models.resnet.ResNet', class {});
  4081. this.registerType('torchvision.models.vgg.VGG', class {});
  4082. this.registerType('torchvision.models.video.resnet.BasicBlock', class {});
  4083. this.registerType('torchvision.models.video.resnet.BasicStem', class {});
  4084. this.registerType('torchvision.models.video.resnet.Conv2Plus1D', class {});
  4085. this.registerType('torchvision.models.video.resnet.Conv3DNoTemporal', class {});
  4086. this.registerType('torchvision.models.video.resnet.Conv3DSimple', class {});
  4087. this.registerType('torchvision.models.video.resnet.R2Plus1dStem', class {});
  4088. this.registerType('torchvision.models.video.resnet.VideoResNet', class {});
  4089. this.registerType('torchvision.models._utils.IntermediateLayerGetter', class {});
  4090. this.registerType('torchvision.ops.deform_conv.DeformConv2d', class {});
  4091. this.registerType('torchvision.ops.feature_pyramid_network.FeaturePyramidNetwork', class {});
  4092. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelMaxPool', class {});
  4093. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelP6P7', class {});
  4094. this.registerType('torchvision.ops.misc.Conv2dNormActivation', class {});
  4095. this.registerType('torchvision.ops.misc.ConvNormActivation', class {});
  4096. this.registerType('torchvision.ops.misc.ConvTranspose2d', class {});
  4097. this.registerType('torchvision.ops.misc.FrozenBatchNorm2d', class {});
  4098. this.registerType('torchvision.ops.misc.SqueezeExcitation', class {});
  4099. this.registerType('torchvision.ops.poolers.LevelMapper', class {});
  4100. this.registerType('torchvision.ops.poolers.MultiScaleRoIAlign', class {});
  4101. this.registerType('torchvision.ops.stochastic_depth.StochasticDepth', class {});
  4102. this.registerType('torchvision.transforms.functional.InterpolationMode', class {});
  4103. this.registerType('torchvision.transforms.transforms.Compose', class {});
  4104. this.registerType('torchvision.transforms.transforms.CenterCrop', class {});
  4105. this.registerType('torchvision.transforms.transforms.Grayscale', class {});
  4106. this.registerType('torchvision.transforms.transforms.Normalize', class {});
  4107. this.registerType('torchvision.transforms.transforms.RandomAffine', class {});
  4108. this.registerType('torchvision.transforms.transforms.RandomCrop', class {});
  4109. this.registerType('torchvision.transforms.transforms.RandomHorizontalFlip', class {});
  4110. this.registerType('torchvision.transforms.transforms.RandomRotation', class {});
  4111. this.registerType('torchvision.transforms.transforms.Resize', class {});
  4112. this.registerType('torchvision.transforms.transforms.Scale', class {});
  4113. this.registerType('torchvision.transforms.transforms.ToPILImage', class {});
  4114. this.registerType('torchvision.transforms.transforms.ToTensor', class {});
  4115. this.registerFunction('torchvision.models.resnet.resnet34', function() {});
  4116. this.registerFunction('builtins.annotate', function(type, value) {
  4117. if (type === self._builtins.int) {
  4118. return Number.isInteger(value) ? value : NaN;
  4119. }
  4120. if (type === self._builtins.float) {
  4121. return typeof value === 'number' ? value : NaN;
  4122. }
  4123. if (type === self._builtins.number) {
  4124. // if (pytorch.Utility.isTensor(value)) {
  4125. // value.resize_([]);
  4126. // }
  4127. }
  4128. return value;
  4129. });
  4130. this.registerFunction('builtins.unchecked_cast', function(type, value) {
  4131. return value;
  4132. });
  4133. this.registerFunction('builtins.uninitialized', function(/* type */) {
  4134. return undefined;
  4135. });
  4136. this.registerFunction('ops.prim.data', function(tensor) {
  4137. return tensor;
  4138. });
  4139. this.registerFunction('ops.prim.device', function(tensor) {
  4140. return tensor.device;
  4141. });
  4142. this.registerFunction('ops.prim.dtype', function(tensor) {
  4143. return tensor.dtype.scalar_type();
  4144. });
  4145. this.registerFunction('ops.prim.is_quantized', function(tensor) {
  4146. return tensor && tensor.__quantized__ === true;
  4147. });
  4148. this.registerFunction('ops.prim.is_cuda', function(/* tensor */) {
  4149. return false;
  4150. });
  4151. this.registerFunction('ops.prim.unchecked_unwrap_optional', function(value) {
  4152. return value;
  4153. });
  4154. this.registerFunction('ops.prim.NumToTensor', function(value) {
  4155. const tensor = self.invoke('torch.Tensor', []);
  4156. tensor.value = value; // TODO
  4157. return tensor;
  4158. });
  4159. this.registerFunction('ops.prim.min', function(value) {
  4160. if (Array.isArray(value)) {
  4161. return Math.min.apply(null, value);
  4162. }
  4163. return Math.min.apply(null, arguments);
  4164. });
  4165. this.registerFunction('ops.prim.max', function(value) {
  4166. if (Array.isArray(value)) {
  4167. return Math.max.apply(null, value);
  4168. }
  4169. return Math.max.apply(null, arguments);
  4170. });
  4171. this.registerFunction('ops.prim.shape', function(tensor) {
  4172. return tensor && tensor.size ? tensor.size() : undefined;
  4173. });
  4174. this.registerFunction('ops.quantized.conv_prepack', function(weight, bias, stride, padding, dilation, groups) {
  4175. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  4176. params.weight = weight;
  4177. params.bias = bias;
  4178. params.stride = stride;
  4179. params.padding =padding;
  4180. params.dilation = dilation;
  4181. params.groups = groups;
  4182. return params;
  4183. });
  4184. this.registerFunction('ops.quantized.conv1d_prepack', function(weight, bias, stride, padding, dilation, groups) {
  4185. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  4186. params.weight = weight;
  4187. params.bias = bias;
  4188. params.stride = stride;
  4189. params.padding =padding;
  4190. params.dilation = dilation;
  4191. params.groups = groups;
  4192. return params;
  4193. });
  4194. this.registerFunction('ops.quantized.conv2d_prepack', function(weight, bias, stride, padding, dilation, groups) {
  4195. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  4196. params.weight = weight;
  4197. params.bias = bias;
  4198. params.stride = stride;
  4199. params.padding =padding;
  4200. params.dilation = dilation;
  4201. params.groups = groups;
  4202. return params;
  4203. });
  4204. this.registerFunction('ops.quantized.conv3d_prepack', function(weight, bias, stride, padding, dilation, groups) {
  4205. const params = self.invoke('__torch__.torch.classes.quantized.Conv3dPackedParamsBase', []);
  4206. params.weight = weight;
  4207. params.bias = bias;
  4208. params.stride = stride;
  4209. params.padding =padding;
  4210. params.dilation = dilation;
  4211. params.groups = groups;
  4212. return params;
  4213. });
  4214. this.registerFunction('ops.quantized.conv_transpose1d_prepack', function(weight, bias, stride, padding, output_padding, dilation, groups) {
  4215. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  4216. params.weight = weight;
  4217. params.bias = bias;
  4218. params.stride = stride;
  4219. params.padding =padding;
  4220. params.output_padding = output_padding;
  4221. params.dilation = dilation;
  4222. params.groups = groups;
  4223. return params;
  4224. });
  4225. this.registerFunction('ops.quantized.conv_transpose2d_prepack', function(weight, bias, stride, padding, output_padding, dilation, groups) {
  4226. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  4227. params.weight = weight;
  4228. params.bias = bias;
  4229. params.stride = stride;
  4230. params.padding =padding;
  4231. params.output_padding = output_padding;
  4232. params.dilation = dilation;
  4233. params.groups = groups;
  4234. return params;
  4235. });
  4236. this.registerFunction('ops.quantized.linear_prepack', function(weight, bias) {
  4237. const params = self.invoke('__torch__.torch.classes.quantized.LinearPackedParamsBase', []);
  4238. params.weight = weight;
  4239. params.bias = bias;
  4240. return params;
  4241. });
  4242. this.registerFunction('ops.prim.RaiseException', function(message) {
  4243. throw new python.Error(message);
  4244. });
  4245. this.registerFunction('builtins.range', function(start, stop, step) {
  4246. if (stop === undefined && step === undefined) {
  4247. if (Number.isInteger(start)) {
  4248. return Array(start).keys();
  4249. }
  4250. if (isNaN(start)) {
  4251. return [];
  4252. }
  4253. }
  4254. throw new python.Error('Unsupported range(' + JSON.stringify(start) + ', ' + JSON.stringify(stop) + ', ' + JSON.stringify(step) + ')');
  4255. });
  4256. this.registerFunction('torch._utils._rebuild_sparse_tensor', function(layout, data) {
  4257. if (layout === torch.sparse_coo) {
  4258. return self.invoke('torch._sparse_coo_tensor_unsafe', data);
  4259. }
  4260. throw new python.Error("Unsupported sparse tensor layout '" + (layout ? layout.__str__() : '') + "'.");
  4261. });
  4262. this.registerFunction('torch.from_numpy', function(obj) {
  4263. const dtypes = new Map([
  4264. [ '<f2', torch.float16 ],
  4265. [ '<f4', torch.float32 ],
  4266. [ '<f8', torch.float64 ],
  4267. [ '<i2', torch.int16 ],
  4268. [ '<i4', torch.int32 ],
  4269. [ '<i8', torch.int64 ],
  4270. ]);
  4271. if (!dtypes.has(obj.dtype.str)) {
  4272. throw new python.Error("Unsupported numpy.ndarray type '" + obj.dtype.str + "'.");
  4273. }
  4274. const dtype = dtypes.get(obj.dtype.str);
  4275. const storage = execution.invoke('torch.storage._TypedStorage', [ obj.size, dtype ]);
  4276. storage._set_cdata(obj.data);
  4277. const tensor = execution.invoke('torch.Tensor', []);
  4278. tensor.__setstate__([ storage, 0, obj.shape, null ]);
  4279. return tensor;
  4280. });
  4281. this.registerFunction('torch._utils._rebuild_device_tensor_from_numpy', function(data, dtype, device, requires_grad) {
  4282. const tensor = execution.invoke('torch.from_numpy', [ data ]);
  4283. // tensor = tensor.to(dtype, device)
  4284. tensor.requires_grad = requires_grad;
  4285. return tensor;
  4286. });
  4287. this.registerFunction('torch._sparse_coo_tensor_unsafe', function(indices, values, size) {
  4288. const tensor = self.invoke('torch.Tensor', []);
  4289. tensor._layout = torch.sparse_coo;
  4290. tensor._indices = indices;
  4291. tensor._values = values;
  4292. tensor._shape = size;
  4293. return tensor;
  4294. });
  4295. this.registerFunction('torch._utils._rebuild_tensor', function (storage, storage_offset, size, stride) {
  4296. if (Array.isArray(storage) && storage.length === 5 && storage[0] === 'storage') {
  4297. const storage_type = storage[1];
  4298. const size = storage[4];
  4299. storage = new storage_type(size);
  4300. }
  4301. const name = storage.__class__.__module__ + '.' + storage.__class__.__name__.replace('Storage', 'Tensor');
  4302. const tensor = self.invoke(name, []);
  4303. tensor.__setstate__([ storage, storage_offset, size, stride ]);
  4304. return tensor;
  4305. });
  4306. this.registerFunction('torch._utils._rebuild_tensor_v2', function (storage, storage_offset, size, stride, requires_grad, backward_hooks) {
  4307. const tensor = execution.invoke('torch._utils._rebuild_tensor', [ storage, storage_offset, size, stride ]);
  4308. tensor.requires_grad = requires_grad;
  4309. tensor.backward_hooks = backward_hooks;
  4310. return tensor;
  4311. });
  4312. this.registerFunction('torch._utils._rebuild_parameter', function(data, requires_grad, backward_hooks) {
  4313. const obj = self.invoke('torch.nn.parameter.Parameter', [ data, requires_grad ]);
  4314. obj.backward_hooks = backward_hooks;
  4315. return obj;
  4316. });
  4317. this.registerFunction('torch._utils._rebuild_qtensor', function(storage, storage_offset, size, stride, quantizer_params, requires_grad, backward_hooks) {
  4318. const tensor = execution.invoke('torch._utils._rebuild_tensor_v2', [ storage, storage_offset, size, stride, requires_grad, backward_hooks ]);
  4319. tensor.quantizer_params = quantizer_params;
  4320. return tensor;
  4321. });
  4322. this.registerFunction('torch._set_item', function(dict, key, value) {
  4323. dict[key] = value;
  4324. });
  4325. this.registerFunction('torch.__and__', function(left, right) {
  4326. return left && right;
  4327. });
  4328. this.registerFunction('torch.__contains__', function(dict, key) {
  4329. return dict[key] !== undefined;
  4330. });
  4331. this.registerFunction('torch.__derive_index', function(index, start, step) {
  4332. return start + index * step;
  4333. });
  4334. this.registerFunction('torch.__is__', function(left, right) {
  4335. if (left === null && right === null) {
  4336. return true;
  4337. }
  4338. if ((left !== null && right === null) || (left === null && right !== null)) {
  4339. return false;
  4340. }
  4341. throw new python.Error("Unsupported 'torch.__is__' expression type.");
  4342. });
  4343. this.registerFunction('torch.__isnot__', function(left, right) {
  4344. if (left === null && right === null) {
  4345. return false;
  4346. }
  4347. if ((left !== null && right === null) || (left === null && right !== null)) {
  4348. return true;
  4349. }
  4350. throw new python.Error("Unsupported 'torch.__isnot__' expression type.");
  4351. });
  4352. this.registerFunction('torch.__not__', function(value) {
  4353. if (typeof value === 'boolean') {
  4354. return !value;
  4355. }
  4356. throw new python.Error("Unsupported 'torch.__not__' expression type.");
  4357. });
  4358. this.registerFunction('torch.__range_length', function(lo, hi, step) {
  4359. if (step === 0) {
  4360. throw new python.Error('range() arg 3 must not be zero');
  4361. }
  4362. if (step > 0 && lo < hi) {
  4363. return 1 + (hi - 1 - lo) / step;
  4364. }
  4365. else if (step < 0 && lo > hi) {
  4366. return 1 + (lo - 1 - hi) / (0 - step);
  4367. }
  4368. return 0;
  4369. });
  4370. this.registerFunction('torch._unwrap_optional', function(value) {
  4371. return value; // TODO
  4372. });
  4373. this.registerFunction('torch.add', function(left, right) {
  4374. if (typeof left === 'number' && typeof right === 'number') {
  4375. return left * right;
  4376. }
  4377. if (Array.isArray(left) && Array.isArray(right)) {
  4378. return left.concat(right);
  4379. }
  4380. if (typeof left === 'string' && typeof right === 'string') {
  4381. return left + right;
  4382. }
  4383. throw new python.Error('Unsupported torch.add expression type.');
  4384. });
  4385. this.registerFunction('torch.append', function(list, value) {
  4386. list.push(value);
  4387. return value;
  4388. });
  4389. this.registerFunction('torch.extend', function(list, value) {
  4390. list.push(...value);
  4391. });
  4392. this.registerFunction('torch.insert', function(list, index, value) {
  4393. list.splice(index, 0, value);
  4394. return value;
  4395. });
  4396. this.registerFunction('torch.clear', function(value) {
  4397. if (Object(value) === value) {
  4398. for (const key of Object.keys(value)) {
  4399. delete value[key];
  4400. }
  4401. }
  4402. });
  4403. this.registerFunction('torch.replace', function(value) {
  4404. return value;
  4405. });
  4406. this.registerFunction('torch.dict', function(args) {
  4407. const obj = {};
  4408. if (args) {
  4409. if (Array.isArray(args)) {
  4410. for (const pair of args) {
  4411. const key = pair[0];
  4412. const value = pair[1];
  4413. obj[key] = value;
  4414. }
  4415. }
  4416. else {
  4417. throw new python.Error("'torch.dict' arguments not supported.");
  4418. }
  4419. }
  4420. return obj;
  4421. });
  4422. this.registerFunction('torch.dim', function(tensor) {
  4423. if (tensor && tensor.size) {
  4424. const size = tensor.size();
  4425. if (size) {
  4426. return size.length;
  4427. }
  4428. }
  4429. return NaN; // TODO
  4430. });
  4431. this.registerFunction('torch.numel', function(tensor) {
  4432. if (tensor && tensor.size) {
  4433. const size = tensor.size();
  4434. if (size) {
  4435. return size.reduce((a, b) => a * b, 1);
  4436. }
  4437. }
  4438. return NaN;
  4439. });
  4440. this.registerFunction('torch.eq', function(left, right) {
  4441. if (typeof left === 'string' && typeof right === 'string') {
  4442. return left === right;
  4443. }
  4444. if (typeof left === 'number' && typeof right === 'number') {
  4445. if (isNaN(left) && isNaN(right)) {
  4446. return true;
  4447. }
  4448. return left === right;
  4449. }
  4450. if (left === undefined || right === undefined) {
  4451. return true;
  4452. }
  4453. if (Array.isArray(left) && Array.isArray(right)) {
  4454. return left.length === right.length && left.every((item, index) => item === right[index]);
  4455. }
  4456. throw new python.Error("Unsupported 'torch.eq' expression type.");
  4457. });
  4458. this.registerFunction('torch.floor', function(value) {
  4459. return Math.floor(value);
  4460. });
  4461. this.registerFunction('torch.ceil', function(value) {
  4462. return Math.ceil(value);
  4463. });
  4464. this.registerFunction('torch.floordiv', function(left, right) {
  4465. return Math.floor(left / right);
  4466. });
  4467. this.registerFunction('torch.format', function() {
  4468. const args = Array.from(arguments);
  4469. const list = args.shift().split(/({}D?)/);
  4470. return list.map((text) => {
  4471. if (text === '{}' || text === '{}D') {
  4472. const arg = args.shift();
  4473. return Array.isArray(arg) ? '[' + arg.map((item) => item.toString()).join(', ') + ']' : arg ? arg.toString() : '?';
  4474. }
  4475. return text;
  4476. }).join('');
  4477. });
  4478. this.registerFunction('torch.gt', function(left, right) {
  4479. if (typeof left === 'number' && typeof right === 'number') {
  4480. if (!isNaN(left) && !isNaN(right)) {
  4481. return left > right;
  4482. }
  4483. }
  4484. if (isNaN(left) && !isNaN(right)) {
  4485. return true;
  4486. }
  4487. throw new python.Error("Unsupported 'torch.gt' expression type.");
  4488. });
  4489. this.registerFunction('torch.ge', function(left, right) {
  4490. if (typeof left === 'number' && typeof right === 'number') {
  4491. if (!isNaN(left) && !isNaN(right)) {
  4492. return left > right;
  4493. }
  4494. }
  4495. if (isNaN(left) && !isNaN(right)) {
  4496. return true;
  4497. }
  4498. throw new python.Error("Unsupported 'torch.ge' expression type.");
  4499. });
  4500. this.registerFunction('torch.is_floating_point', function(tensor) {
  4501. const type = tensor.dtype.scalar_type();
  4502. return (type === 5 || type === 6 || type === 7);
  4503. });
  4504. this.registerFunction('torch.is_grad_enabled', function() {
  4505. return false;
  4506. });
  4507. this.registerFunction('torch.set_grad_enabled', function(/* value */) {
  4508. });
  4509. this.registerFunction('torch.serialization._get_layout', function(name) {
  4510. const value = name.startsWith('torch.') ? torch[name.split('.')[1]] : null;
  4511. return value instanceof torch.layout ? value : null;
  4512. });
  4513. this.registerFunction('torch.storage._load_from_bytes', function(b) {
  4514. return execution.invoke('torch.load', [ b ]);
  4515. });
  4516. this.registerFunction('torch.jit._pickle.build_boollist', function(data) {
  4517. return data;
  4518. });
  4519. this.registerFunction('torch.jit._pickle.build_doublelist', function(data) {
  4520. return data;
  4521. });
  4522. this.registerFunction('torch.jit._pickle.build_intlist', function(data) {
  4523. return data;
  4524. });
  4525. this.registerFunction('torch.jit._pickle.build_tensorlist', function(data) {
  4526. return data;
  4527. });
  4528. this.registerFunction('torch.jit._pickle.build_tensor_from_id', function(data) {
  4529. return self.builtins.CONSTANTS['c' + data.toString()];
  4530. });
  4531. this.registerFunction('torch.jit._pickle.restore_type_tag', function(value /*, type_str */) {
  4532. return value;
  4533. });
  4534. this.registerFunction('torch.keys', function(dict) {
  4535. return Object.keys(dict);
  4536. });
  4537. this.registerFunction('torch.len', function(value) {
  4538. if (Array.isArray(value)) {
  4539. return value.length;
  4540. }
  4541. if (value && value.shape && value.__len__) {
  4542. return value.__len__();
  4543. }
  4544. return NaN;
  4545. });
  4546. this.registerFunction('torch.le', function(left, right) {
  4547. if (typeof left === 'number' && typeof right === 'number') {
  4548. if (isNaN(left) || isNaN(right)) {
  4549. return false;
  4550. }
  4551. return left <= right;
  4552. }
  4553. if (left === undefined || right === undefined) {
  4554. return true;
  4555. }
  4556. throw new python.Error("Unsupported 'torch.le' expression type.");
  4557. });
  4558. this.registerFunction('torch.list', function(args) {
  4559. return args;
  4560. });
  4561. this.registerFunction('torch.list_with_default', function(size /*, defaults */) {
  4562. return size;
  4563. });
  4564. this.registerFunction('torch.load', function(f) {
  4565. const legacy_load = (entries) => {
  4566. const deserialized_objects = {};
  4567. if (entries.has('storages')) {
  4568. const data = entries.get('storages');
  4569. const unpickler = execution.invoke('pickle.Unpickler', [ data ]);
  4570. const num_storages = unpickler.load();
  4571. for (let i = 0; i < num_storages; i++) {
  4572. const args = unpickler.load();
  4573. const key = args[0];
  4574. const storage_type = args[2];
  4575. const obj = storage_type._new_with_file(unpickler);
  4576. deserialized_objects[key] = obj;
  4577. }
  4578. /*
  4579. let storage_views = unpickler.load();
  4580. for target_cdata, root_cdata, offset, size in storage_views:
  4581. root = deserialized_objects[root_cdata]
  4582. deserialized_objects[target_cdata] = root[offset:offset + size]
  4583. */
  4584. }
  4585. if (entries.has('tensors')) {
  4586. const data = entries.get('tensors');
  4587. const unpickler = execution.invoke('pickle.Unpickler', [ data ]);
  4588. const num_tensors = unpickler.load();
  4589. const int32 = (unpickler) => {
  4590. const buffer = unpickler.read(4);
  4591. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24);
  4592. };
  4593. const int64 = (unpickler) => {
  4594. const buffer = unpickler.read(8);
  4595. if (buffer[6] !== 0 && buffer[7] !== 0) {
  4596. throw new python.Error('Unsigned 64-bit value exceeds 32-bit range.');
  4597. }
  4598. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24) + (buffer[4] * 4294967296) + (buffer[5] * 1099511627776);
  4599. };
  4600. for (let i = 0; i < num_tensors; i++) {
  4601. const args = unpickler.load();
  4602. const key = args[0];
  4603. const storage_id = args[1];
  4604. const storage = deserialized_objects[storage_id];
  4605. const ndim = int32(unpickler);
  4606. unpickler.read(4);
  4607. const shape = Array.from(new Array(ndim)).map(() => int64(unpickler));
  4608. const stride = Array.from(new Array(ndim)).map(() => int64(unpickler));
  4609. const storage_offset = int64(unpickler);
  4610. const tensor = execution.invoke('torch._utils._rebuild_tensor', [ storage, storage_offset, shape, stride ]);
  4611. deserialized_objects[key] = tensor;
  4612. }
  4613. }
  4614. const data = entries.get('pickle');
  4615. const unpickler = execution.invoke('pickle.Unpickler', [ data ]);
  4616. unpickler.persistent_load = (saved_id) => deserialized_objects[saved_id];
  4617. return unpickler.load();
  4618. };
  4619. if (f instanceof Map) {
  4620. if (f.has('pickle')) {
  4621. return legacy_load(f);
  4622. }
  4623. throw new python.Error("Unsupported 'torch.load' input '" + JSON.stringify(Array.from(f.keys())) + "'.");
  4624. }
  4625. const unpickler = execution.invoke('pickle.Unpickler', [ f ]);
  4626. unpickler.load(); // magic_number
  4627. const protocol_version = unpickler.load();
  4628. if (protocol_version != 1001) {
  4629. throw new python.Error("Unsupported protocol version '" + protocol_version + "'.");
  4630. }
  4631. const sys_info = unpickler.load();
  4632. if (sys_info.protocol_version != 1001) {
  4633. throw new python.Error("Unsupported protocol version '" + sys_info.protocol_version + "'.");
  4634. }
  4635. if (sys_info.little_endian === false) {
  4636. throw new python.Error("Unsupported big-endian storage data.");
  4637. }
  4638. const module_source_map = new Map();
  4639. const deserialized_objects = new Map();
  4640. unpickler.persistent_load = (saved_id) => {
  4641. const typename = saved_id[0];
  4642. switch (typename) {
  4643. case 'module': {
  4644. const module = saved_id[1];
  4645. const source = saved_id[3];
  4646. module_source_map.set(module, source);
  4647. return saved_id[1];
  4648. }
  4649. case 'storage': {
  4650. const storage_type = saved_id[1];
  4651. const root_key = saved_id[2];
  4652. /// const location = saved_id[3];
  4653. const size = saved_id[4];
  4654. const view_metadata = saved_id[5];
  4655. if (!deserialized_objects.has(root_key)) {
  4656. const obj = new storage_type(size);
  4657. deserialized_objects.set(root_key, obj);
  4658. }
  4659. if (view_metadata) {
  4660. const view_key = view_metadata.shift();
  4661. view_metadata.shift(); // view_offset
  4662. view_metadata.shift(); // view_size
  4663. if (!deserialized_objects.has(view_key)) {
  4664. const view = null; // storage.slice(view_offset, view_offset + view_size);
  4665. deserialized_objects.set(view_key, view);
  4666. }
  4667. return deserialized_objects.get(view_key);
  4668. }
  4669. return deserialized_objects.get(root_key);
  4670. }
  4671. default: {
  4672. throw new python.Error("Unsupported persistent load type '" + typename + "'.");
  4673. }
  4674. }
  4675. };
  4676. const obj = unpickler.load();
  4677. const deserialized_storage_keys = unpickler.load();
  4678. for (const deserialized_storage_key of deserialized_storage_keys) {
  4679. const storage = deserialized_objects.get(deserialized_storage_key);
  4680. storage._set_from_file(unpickler);
  4681. }
  4682. if (!obj) {
  4683. throw new python.Error('File format is not PyTorch.');
  4684. }
  4685. if (obj === 'None') {
  4686. throw new python.Error("File contains 'None' root object.");
  4687. }
  4688. return obj;
  4689. });
  4690. this.registerFunction('torch.lt', function(left, right) {
  4691. if (typeof left === 'number' && typeof right === 'number') {
  4692. return left < right;
  4693. }
  4694. throw new python.Error("Unsupported 'torch.lt' expression type.");
  4695. });
  4696. this.registerFunction('torch.mul', function(left, right) {
  4697. if (typeof left === 'number' && typeof right === 'number') {
  4698. return left * right;
  4699. }
  4700. if (isNaN(left) || isNaN(right)) {
  4701. return NaN;
  4702. }
  4703. if (Array.isArray(left) && left.every((value) => typeof value === 'number') && typeof right === 'number') {
  4704. return left.map((value) => value * right);
  4705. }
  4706. throw new python.Error("Unsupported 'torch.mul' expression type.");
  4707. });
  4708. this.registerFunction('torch.div', function(left, right) {
  4709. if (typeof left === 'number' && typeof right === 'number') {
  4710. return left / right;
  4711. }
  4712. if (isNaN(left) || isNaN(right)) {
  4713. return NaN;
  4714. }
  4715. throw new python.Error("Unsupported 'torch.div' expression type.");
  4716. });
  4717. this.registerFunction('torch.round', function(value) {
  4718. if (typeof value === 'number') {
  4719. return Math.round(value);
  4720. }
  4721. if (isNaN(value)) {
  4722. return value;
  4723. }
  4724. throw new python.Error("Unsupported 'torch.round' expression type.");
  4725. });
  4726. this.registerFunction('torch.remainder', function(left, right) {
  4727. if (typeof left === 'number' && typeof right === 'number') {
  4728. return left % right;
  4729. }
  4730. if (isNaN(left) || isNaN(right)) {
  4731. return NaN;
  4732. }
  4733. throw new python.Error("Unsupported 'torch.remainder' expression type.");
  4734. });
  4735. this.registerFunction('torch.ne', function(left, right) {
  4736. if (typeof left === 'boolean' && typeof right === 'boolean') {
  4737. return left !== right;
  4738. }
  4739. if (typeof left === 'number' && typeof right === 'number') {
  4740. if (isNaN(left) || isNaN(right)) {
  4741. return false;
  4742. }
  4743. return left !== right;
  4744. }
  4745. if (Array.isArray(left) && Array.isArray(right) && left.length === right.length) {
  4746. return false;
  4747. }
  4748. if (typeof left === 'string' && typeof right === 'string') {
  4749. return left !== right;
  4750. }
  4751. if (left === undefined || right === undefined) {
  4752. return true;
  4753. }
  4754. throw new python.Error("Unsupported 'torch.ne' expression type.");
  4755. });
  4756. this.registerFunction('torch.neg', function(value) {
  4757. if (typeof value === 'number') {
  4758. return -value;
  4759. }
  4760. throw new python.Error("Unsupported 'torch.neg' expression type.");
  4761. });
  4762. this.registerFunction('torch.q_scale', function(/* tensor */) {
  4763. return -1; // TODO
  4764. });
  4765. this.registerFunction('torch.t', function(tensor) {
  4766. return tensor;
  4767. });
  4768. this.registerFunction('torch.size', function(tensor, dim) {
  4769. if (tensor && tensor.size) {
  4770. const size = tensor.size();
  4771. if (Array.isArray(size)) {
  4772. if (dim === undefined) {
  4773. return size;
  4774. }
  4775. if (Number.isInteger(dim)) {
  4776. if (dim >= 0 && dim < size.length) {
  4777. return size[dim];
  4778. }
  4779. if (dim < 0 && -dim < size.length) {
  4780. return size[size.length + dim];
  4781. }
  4782. }
  4783. throw new python.Error('Dimension out of range (expected to be in range of ' + JSON.stringify(size) + ', but got ' + JSON.stringify(dim) + ').');
  4784. }
  4785. }
  4786. if (Number.isInteger(dim)) {
  4787. return NaN;
  4788. }
  4789. return [];
  4790. });
  4791. this.registerFunction('torch.slice', function(l, start, end, step) {
  4792. if (!Array.isArray(l)) {
  4793. throw new python.Error('Slicing expected array');
  4794. }
  4795. step = step || 1;
  4796. if (step !== 1) {
  4797. throw new python.Error('Slicing only supports step=1');
  4798. }
  4799. start = Math.max(0, start >= 0 ? start : l.length + start);
  4800. end = Math.min(l.length, end || Number.MAX_SAFE_INTEGER);
  4801. return l.slice(start, end);
  4802. });
  4803. this.registerFunction('torch.sub', function(left, right) {
  4804. if (typeof left === 'number' && typeof right === 'number') {
  4805. return left - right;
  4806. }
  4807. throw new python.Error("Unsupported 'torch.sub' expression type.");
  4808. });
  4809. this.registerFunction('torch.nn.functional.gelu', function(/* input */) {
  4810. throw new python.Error("Function not implemented.");
  4811. });
  4812. this.registerFunction('torch.nn.functional.interpolate', function(/* input */) {
  4813. throw new python.Error("Function not implemented.");
  4814. });
  4815. this.registerFunction('torch.nn.functional.leaky_relu', function(/* input */) {
  4816. throw new python.Error("Function not implemented.");
  4817. });
  4818. this.registerFunction('torch.nn.functional.linear', function(/* input */) {
  4819. throw new python.Error("Function not implemented.");
  4820. });
  4821. this.registerFunction('torch.nn.functional.relu', function(/* input */) {
  4822. throw new python.Error("Function not implemented.");
  4823. });
  4824. this.registerFunction('torch.nn.functional.tanh', function(/* input */) {
  4825. throw new python.Error("Function not implemented.");
  4826. });
  4827. this.registerFunction('torch.values', function(dict) {
  4828. return Object.keys(dict).map((key) => dict[key]);
  4829. });
  4830. this.registerFunction('torch.warn', function() {
  4831. });
  4832. this.registerFunction('torch.fx.graph_module.reduce_graph_module', function(body /*, import_block */) {
  4833. // https://github.com/pytorch/pytorch/blob/master/torch/fx/graph_module.py
  4834. return body;
  4835. });
  4836. this.registerFunction('torch_utils.persistence._reconstruct_persistent_obj', function(meta) {
  4837. const name = '_imported_module_' + Math.floor(Math.random() * 10000).toString();
  4838. const module = execution.invoke('types.ModuleType', [ name ]);
  4839. execution.register('sys').modules.set(name, module);
  4840. const context = new python.Execution.Context(module, null);
  4841. execution.exec(meta.module_src, context);
  4842. const obj = execution.invoke(name + '.' + meta.class_name, []);
  4843. if (meta.state) {
  4844. if (obj.__setstate__) {
  4845. obj.__setstate__(meta.state);
  4846. }
  4847. else {
  4848. Object.assign(obj, meta.state);
  4849. }
  4850. }
  4851. return obj;
  4852. });
  4853. this.registerFunction('torch_utils.misc.assert_shape', function(/* tensor, ref_shape */) {});
  4854. this.registerFunction('torch_utils.ops.conv2d_resample.conv2d_resample', function(/* x, w, f, up, down, padding, groups, flip_weight, flip_filter */) {});
  4855. this.registerFunction('torch_utils.ops.upfirdn2d.setup_filter', function(/* x, f, up, down, padding, flip_filter, gain, impl */) {});
  4856. this.registerFunction('torch_utils.ops.bias_act', function(/* x, b, dim, act, alpha, gain, clamp, impl */) {});
  4857. this.registerFunction('torch_utils.ops.fma.fma', function(/* a, b, c */) {});
  4858. this.registerType('torch.device', class {
  4859. constructor(type, index) {
  4860. this.type = type;
  4861. if (index) {
  4862. this.index = index;
  4863. }
  4864. }
  4865. });
  4866. this.registerType('torch.dtype', class {
  4867. constructor(data) {
  4868. this._type = data.type;
  4869. this._data = data;
  4870. }
  4871. scalar_type() {
  4872. return this._type;
  4873. }
  4874. itemsize() {
  4875. return this._data.itemsize;
  4876. }
  4877. __reduce__() {
  4878. return this._data.name;
  4879. }
  4880. __str__() {
  4881. return 'torch.' + this._data.name;
  4882. }
  4883. toString() {
  4884. return this.__str__();
  4885. }
  4886. });
  4887. this.registerType('torch.layout', class {
  4888. constructor(name) {
  4889. this._name = name;
  4890. }
  4891. __str__() {
  4892. return this._name;
  4893. }
  4894. toString() {
  4895. return this.__str__();
  4896. }
  4897. });
  4898. this.registerType('torch.qscheme', class {
  4899. constructor(name) {
  4900. this._name = name;
  4901. }
  4902. __str__() {
  4903. return this._name;
  4904. }
  4905. toString() {
  4906. return this.__str__();
  4907. }
  4908. });
  4909. this.registerType('torch.utils.hooks.RemovableHandle', class {
  4910. __setstate__(state) {
  4911. this.hooks_dict_ref = state[0] || new Map();
  4912. this.id = state[1];
  4913. }
  4914. });
  4915. this.registerType('torch.storage._StorageBase', class {
  4916. constructor(size, dtype) {
  4917. this._size = size;
  4918. this._dtype = dtype;
  4919. this._device = null;
  4920. }
  4921. get device() {
  4922. return this._device;
  4923. }
  4924. get dtype() {
  4925. return this._dtype;
  4926. }
  4927. element_size() {
  4928. return this._dtype.element_size;
  4929. }
  4930. size() {
  4931. return this._size;
  4932. }
  4933. get data() {
  4934. return this._cdata;
  4935. }
  4936. _set_cdata(data) {
  4937. const length = this.size() * this.dtype.itemsize();
  4938. if (length !== data.length) {
  4939. throw new python.Error('Storage data size mismatch.');
  4940. }
  4941. this._cdata = data;
  4942. }
  4943. _set_from_file(unpickler) {
  4944. const buffer = unpickler.read(8);
  4945. const size = buffer.reverse().reduce((a, b) => (a*256)+b, 0);
  4946. if (size !== this.size()) {
  4947. throw new python.Error('Storage size mismatch.');
  4948. }
  4949. const itemsize = this.dtype.itemsize();
  4950. const data = unpickler.stream(itemsize * size);
  4951. this._set_cdata(data);
  4952. }
  4953. static _new_with_file(unpickler) {
  4954. const buffer = unpickler.read(8);
  4955. const size = buffer.reverse().reduce((a, b) => (a*256)+b, 0);
  4956. const storage = new this(size);
  4957. const itemsize = storage.dtype.itemsize();
  4958. const data = unpickler.stream(itemsize * size);
  4959. storage._set_cdata(data);
  4960. return storage;
  4961. }
  4962. });
  4963. this.registerType('torch.storage._UntypedStorage', class extends torch_storage._StorageBase {
  4964. constructor() {
  4965. super();
  4966. throw new python.Error('_UntypedStorage not implemented.');
  4967. }
  4968. });
  4969. this.registerType('torch.storage._TypedStorage', class {
  4970. constructor() {
  4971. if (arguments.length >= 2 && Number.isInteger(arguments[0]) && arguments[1] instanceof torch.dtype) {
  4972. this._size = arguments[0];
  4973. this._dtype = arguments[1];
  4974. if (arguments[3] instanceof torch.device) {
  4975. this._device = arguments[3];
  4976. }
  4977. }
  4978. else {
  4979. throw new python.Error("Unsupported _TypedStorage arguments '" + JSON.stringify(arguments) + "'.");
  4980. }
  4981. }
  4982. get device() {
  4983. return this._device;
  4984. }
  4985. get dtype() {
  4986. return this._dtype;
  4987. }
  4988. element_size() {
  4989. return this._dtype.element_size;
  4990. }
  4991. size() {
  4992. return this._size;
  4993. }
  4994. get data() {
  4995. return this._cdata;
  4996. }
  4997. _set_cdata(data) {
  4998. const length = this.size() * this.dtype.itemsize();
  4999. if (length !== data.length) {
  5000. throw new python.Error('Storage data size mismatch.');
  5001. }
  5002. this._cdata = data;
  5003. }
  5004. _set_from_file(unpickler) {
  5005. const buffer = unpickler.read(8);
  5006. const size = buffer.reverse().reduce((a, b) => (a*256)+b, 0);
  5007. if (size !== this.size()) {
  5008. throw new python.Error('Storage size mismatch.');
  5009. }
  5010. const itemsize = this.dtype.itemsize();
  5011. const data = unpickler.stream(itemsize * size);
  5012. this._set_cdata(data);
  5013. }
  5014. static _new_with_file(unpickler) {
  5015. const buffer = unpickler.read(8);
  5016. const size = buffer.reverse().reduce((a, b) => (a*256)+b, 0);
  5017. const storage = new this(size);
  5018. const itemsize = storage.dtype.itemsize();
  5019. const data = unpickler.stream(itemsize * size);
  5020. storage._set_cdata(data);
  5021. return storage;
  5022. }
  5023. });
  5024. this.registerType('torch.storage._LegacyStorage', class extends torch_storage._TypedStorage {
  5025. constructor() {
  5026. super();
  5027. throw new python.Error('_LegacyStorage not implemented.');
  5028. }
  5029. });
  5030. this.registerType('torch.BoolStorage', class extends torch_storage._StorageBase {
  5031. constructor(size) {
  5032. super(size, torch.bool);
  5033. }
  5034. });
  5035. this.registerType('torch.ByteStorage', class extends torch_storage._StorageBase {
  5036. constructor(size) {
  5037. super(size, torch.uint8);
  5038. }
  5039. });
  5040. this.registerType('torch.CharStorage', class extends torch_storage._StorageBase {
  5041. constructor(size) {
  5042. super(size, torch.int8);
  5043. }
  5044. });
  5045. this.registerType('torch.ShortStorage', class extends torch_storage._StorageBase {
  5046. constructor(size) {
  5047. super(size, torch.int16);
  5048. }
  5049. });
  5050. this.registerType('torch.IntStorage', class extends torch_storage._StorageBase {
  5051. constructor(size) {
  5052. super(size, torch.int32);
  5053. }
  5054. });
  5055. this.registerType('torch.LongStorage', class extends torch_storage._StorageBase {
  5056. constructor(size) {
  5057. super(size, torch.int64);
  5058. }
  5059. });
  5060. this.registerType('torch.HalfStorage', class extends torch_storage._StorageBase {
  5061. constructor(size) {
  5062. super(size, torch.float16);
  5063. }
  5064. });
  5065. this.registerType('torch.FloatStorage', class extends torch_storage._StorageBase {
  5066. constructor(size) {
  5067. super(size, torch.float32);
  5068. }
  5069. });
  5070. this.registerType('torch.DoubleStorage', class extends torch_storage._StorageBase {
  5071. constructor(size) {
  5072. super(size, torch.float64);
  5073. }
  5074. });
  5075. this.registerType('torch.ComplexHalfStorage', class extends torch_storage._StorageBase {
  5076. constructor(size) {
  5077. super(size, torch.complex32);
  5078. }
  5079. });
  5080. this.registerType('torch.ComplexFloatStorage', class extends torch_storage._StorageBase {
  5081. constructor(size) {
  5082. super(size, torch.complex64);
  5083. }
  5084. });
  5085. this.registerType('torch.ComplexDoubleStorage', class extends torch_storage._StorageBase {
  5086. constructor(size) {
  5087. super(size, torch.complex128);
  5088. }
  5089. });
  5090. this.registerType('torch.QInt8Storage', class extends torch_storage._StorageBase {
  5091. constructor(size) {
  5092. super(size, torch.qint8);
  5093. }
  5094. });
  5095. this.registerType('torch.QUInt8Storage', class extends torch_storage._StorageBase {
  5096. constructor(size) {
  5097. super(size, torch.quint8);
  5098. }
  5099. });
  5100. this.registerType('torch.QInt32Storage', class extends torch_storage._StorageBase {
  5101. constructor(size) {
  5102. super(size, torch.qint32);
  5103. }
  5104. });
  5105. this.registerType('torch.BFloat16Storage', class extends torch_storage._StorageBase {
  5106. constructor(size) {
  5107. super(size, torch.bfloat16);
  5108. }
  5109. });
  5110. this.registerType('torch.Size', class extends Array {
  5111. constructor(size) {
  5112. super(size.length);
  5113. for (let i = 0; i < size.length; i++) {
  5114. this[i] = size[i];
  5115. }
  5116. }
  5117. __len__() {
  5118. return this.length;
  5119. }
  5120. });
  5121. this.registerType('torch.Tensor', class {
  5122. constructor() {
  5123. this._layout = torch.strided;
  5124. }
  5125. get device() {
  5126. return this.storage().device;
  5127. }
  5128. get dtype() {
  5129. if (this._layout === torch.sparse_coo) {
  5130. return this._values.dtype();
  5131. }
  5132. return this.storage().dtype;
  5133. }
  5134. get shape() {
  5135. return this._shape;
  5136. }
  5137. get layout() {
  5138. return this._layout;
  5139. }
  5140. get values() {
  5141. if (this._layout === torch.sparse_coo) {
  5142. return this._values;
  5143. }
  5144. throw new python.Error("Unsupported values in layout'" + this._layout.__str__() + "'.");
  5145. }
  5146. get indices() {
  5147. if (this._layout === torch.sparse_coo) {
  5148. return this._indices;
  5149. }
  5150. throw new python.Error("Unsupported indices in layout'" + this._indices.__str__() + "'.");
  5151. }
  5152. size() {
  5153. return this._shape;
  5154. }
  5155. storage() {
  5156. if (!this._storage) {
  5157. const name = this.__class__.__name__ == 'Tensor' ? 'FloatStorage' : this.__storage__.__name__.replace('Tensor', 'Storage');
  5158. this._storage = self.invoke(this.__class__.__module__ + '.' + name, []);
  5159. }
  5160. return this._storage;
  5161. }
  5162. storage_offset() {
  5163. return this._storage_offset;
  5164. }
  5165. stride() {
  5166. return this._stride;
  5167. }
  5168. resize_(shape) {
  5169. this._shape = shape;
  5170. }
  5171. __len__() {
  5172. return this._shape[0];
  5173. }
  5174. __setstate__(state) {
  5175. this._storage = state[0];
  5176. this._storage_offset = state[1];
  5177. this._shape = state[2];
  5178. this._stride = state[3];
  5179. }
  5180. __bool__() {
  5181. return true;
  5182. }
  5183. __int__() {
  5184. const storage = this.storage();
  5185. if (storage && storage.dtype.__reduce__() === 'int64' && storage.data.length === 8) {
  5186. const buffer = storage.data;
  5187. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  5188. return view.getInt64(0, true);
  5189. }
  5190. return NaN;
  5191. }
  5192. __float__() {
  5193. const storage = this.storage();
  5194. if (storage && storage.dtype.__reduce__() === 'float32') {
  5195. if (storage.size() !== undefined && storage.data.length === 4) {
  5196. const buffer = storage.data;
  5197. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  5198. return view.getFloat32(0, true);
  5199. }
  5200. }
  5201. return NaN;
  5202. }
  5203. __str__() {
  5204. return 'tensor(...)';
  5205. }
  5206. });
  5207. this.registerType('torch.nn.parameter.Parameter', class extends torch.Tensor {
  5208. constructor(data, requires_grad) {
  5209. super();
  5210. if (!data) {
  5211. data = self.invoke('torch.Tensor', [[]]);
  5212. }
  5213. this.data = data;
  5214. this.requires_grad = requires_grad !== undefined ? requires_grad : true;
  5215. }
  5216. __setstate__(state) {
  5217. switch (state.length) {
  5218. case 3:
  5219. this.data = null;
  5220. break;
  5221. case 4:
  5222. this.data = state[0];
  5223. break;
  5224. case 5:
  5225. this.data = state[0];
  5226. break;
  5227. default:
  5228. throw new python.Error("Unsupported parameter state length '" + state.length + "'.");
  5229. }
  5230. }
  5231. });
  5232. this.registerType('torch.nn.parameter.UninitializedParameter', class extends torch_nn_parameter.Parameter {
  5233. constructor(requires_grad /*, device, dtype */) {
  5234. super(undefined, requires_grad);
  5235. }
  5236. });
  5237. this.registerType('torch.BoolTensor', class extends torch.Tensor {});
  5238. this.registerType('torch.ByteTensor', class extends torch.Tensor {});
  5239. this.registerType('torch.CharTensor', class extends torch.Tensor {});
  5240. this.registerType('torch.ShortTensor', class extends torch.Tensor {});
  5241. this.registerType('torch.IntTensor', class extends torch.Tensor {});
  5242. this.registerType('torch.LongTensor', class extends torch.Tensor {});
  5243. this.registerType('torch.HalfTensor', class extends torch.Tensor {});
  5244. this.registerType('torch.FloatTensor', class extends torch.Tensor {});
  5245. this.registerType('torch.DoubleTensor', class extends torch.Tensor {});
  5246. this.registerType('torch.ComplexFloatTensor', class extends torch.Tensor {});
  5247. this.registerType('torch.ComplexDoubleTensor', class extends torch.Tensor {});
  5248. this.registerType('torch.QInt8Tensor', class extends torch.Tensor {});
  5249. this.registerType('torch.QUInt8Tensor', class extends torch.Tensor {});
  5250. this.registerType('torch.QInt32Tensor', class extends torch.Tensor {});
  5251. this.registerType('torch.BFloat16Tensor', class extends torch.Tensor {});
  5252. this.registerType('torch.cuda.FloatTensor', class extends torch.Tensor {});
  5253. this.registerType('torch.cuda.DoubleTensor', class extends torch.Tensor {});
  5254. this.register('torch.nn').Module = this.register('torch.nn.modules.module').Module;
  5255. this.register('torch.optim').Adam = this.register('torch.optim.adam').Adam;
  5256. this.register('torch.nn').ReLU = this.register('torch.nn.modules.activation').ReLU;
  5257. this.register('sklearn.utils').Bunch = this.register('sklearn.utils._bunch').Bunch;
  5258. torch.uint8 = torch.ByteStorage.dtype = new torch.dtype({ type: 0, name: 'uint8', itemsize: 1 });
  5259. torch.int8 = torch.CharStorage.dtype = new torch.dtype({ type: 1, name: 'int8', itemsize: 1 });
  5260. torch.int16 = torch.ShortStorage.dtype = new torch.dtype({ type: 2, name: 'int16', itemsize: 2 });
  5261. torch.int32 = torch.IntStorage.dtype = new torch.dtype({ type: 3, name: 'int32', itemsize: 4 });
  5262. torch.int64 = torch.LongStorage.dtype = new torch.dtype({ type: 4, name: 'int64', itemsize: 8 });
  5263. torch.float16 = torch.HalfStorage.dtype = new torch.dtype({ type: 5, name: 'float16', itemsize: 2 });
  5264. torch.float32 = torch.FloatStorage.dtype = new torch.dtype({ type: 6, name: 'float32', itemsize: 4 });
  5265. torch.float64 = torch.DoubleStorage.dtype = new torch.dtype({ type: 7, name: 'float64', itemsize: 8 });
  5266. torch.complex32 = torch.ComplexHalfStorage.dtype = new torch.dtype({ type: 8, name: 'complex32', itemsize: 4 });
  5267. torch.complex64 = torch.ComplexFloatStorage.dtype = new torch.dtype({ type: 9, name: 'complex64', itemsize: 8 });
  5268. torch.complex128 = torch.ComplexDoubleStorage.dtype = new torch.dtype({ type: 10, name: 'complex128', itemsize: 16 });
  5269. torch.bool = torch.BoolStorage.dtype = new torch.dtype({ type: 11, name: 'boolean', itemsize: 1 });
  5270. torch.qint8 = torch.QInt8Storage.dtype = new torch.dtype({ type: 12, name: 'qint8', itemsize: 1 });
  5271. torch.quint8 = torch.QUInt8Storage.dtype = new torch.dtype({ type: 13, name: 'quint8', itemsize: 1 });
  5272. torch.qint32 = torch.QInt32Storage.dtype = new torch.dtype({ type: 14, name: 'qint32', itemsize: 4 });
  5273. torch.bfloat16 = torch.BFloat16Storage.dtype = new torch.dtype({ type: 15, name: 'bfloat16', itemsize: 2 });
  5274. torch.quint4x2 = new torch.dtype({ type: 16, name: 'quint4x2' });
  5275. torch.strided = new torch.layout('torch.strided');
  5276. torch.sparse_coo = new torch.layout('torch.sparse_coo');
  5277. torch.sparse_csr = new torch.layout('torch.sparse_csr');
  5278. torch.sparse_csc = new torch.layout('torch.sparse_csc');
  5279. torch.sparse_bsr = new torch.layout('torch.sparse_bsr');
  5280. torch.sparse_bsc = new torch.layout('torch.sparse_bsc');
  5281. torch._mkldnn = new torch.layout('torch._mkldnn');
  5282. torch.per_tensor_affine = new torch.qscheme('torch.per_tensor_affine');
  5283. torch.per_channel_affine = new torch.qscheme('torch.per_channel_affine');
  5284. torch.per_tensor_symmetric = new torch.qscheme('torch.per_tensor_symmetric');
  5285. torch.per_channel_symmetric = new torch.qscheme('torch.per_channel_symmetric');
  5286. torch.per_channel_affine_float_qparams = new torch.qscheme('torch.per_channel_affine_float_qparams');
  5287. torch.inf = this.register('math').inf;
  5288. }
  5289. get builtins() {
  5290. return this._builtins;
  5291. }
  5292. source(file) {
  5293. return this._sources.has(file) ? this._sources.get(file) : null;
  5294. }
  5295. debug(/* file */) {
  5296. }
  5297. exec(code , context) {
  5298. const reader = new python.Parser(code, '', null);
  5299. const program = reader.parse();
  5300. if (!program) {
  5301. throw new python.Error("Module '" + '?' + "' parse error.");
  5302. }
  5303. this.block(program.body, context);
  5304. }
  5305. parse(file) {
  5306. const buffer = this.source(file);
  5307. if (buffer) {
  5308. const debug = this.debug(file);
  5309. const code = this._utf8Decoder.decode(buffer);
  5310. const reader = new python.Parser(code, file, debug);
  5311. const program = reader.parse();
  5312. if (!program) {
  5313. throw new python.Error("Module '" + file + "' parse error.");
  5314. }
  5315. return program;
  5316. }
  5317. return null;
  5318. }
  5319. import(name, current, level) {
  5320. if (level) {
  5321. let bits = current.split('.');
  5322. if (bits.length < level) {
  5323. throw new python.Error('Invalid relative import beyond top-level package.');
  5324. }
  5325. bits = bits.slice(0, bits.length - level);
  5326. const base = bits.join('.');
  5327. name = name ? [ base, name ].join('.') : base;
  5328. }
  5329. const index = name.lastIndexOf('.');
  5330. let parent = null;
  5331. let child = null;
  5332. if (index > 0) {
  5333. parent = name.substring(0, index);
  5334. child = name.substring(index + 1);
  5335. this.import(parent);
  5336. }
  5337. if (!this._modules.has(name)) {
  5338. const module = this._registry.get(name) || new this._builtins.module(name);
  5339. module.__package__ = name;
  5340. this._modules.set(name, module);
  5341. const path = name.split('.').join('/');
  5342. module.__path__ = [ path ];
  5343. const file = path + '.py';
  5344. const program = this.parse(file);
  5345. if (program) {
  5346. module.__file__ = file;
  5347. for (const entry of Object.entries(this.builtins)) {
  5348. switch (entry[0]) {
  5349. case '__class__':
  5350. case '__package__':
  5351. case '__module__':
  5352. case '__name__':
  5353. case '__path__':
  5354. case '__file__':
  5355. break;
  5356. default:
  5357. module[entry[0]] = entry[1];
  5358. break;
  5359. }
  5360. }
  5361. const context = new python.Execution.Context(module, null);
  5362. if (name !== 'builtins') {
  5363. context.set('__builtins__', this._modules.get('builtins'));
  5364. }
  5365. this.block(program.body, context);
  5366. }
  5367. if (parent) {
  5368. const parent_module = this._modules.get(parent);
  5369. parent_module[child] = module;
  5370. }
  5371. }
  5372. return this._modules.get(name);
  5373. }
  5374. __import__(name, globals, locals, fromlist, level) {
  5375. let module = null;
  5376. level = level || 0;
  5377. if (level === 0) {
  5378. module = this.import(name);
  5379. }
  5380. else {
  5381. globals = globals || {};
  5382. let current = globals.__package__;
  5383. if (!current) {
  5384. const spec = globals.__spec__;
  5385. if (spec) {
  5386. current = spec.parent;
  5387. }
  5388. else {
  5389. const name = globals.__name__;
  5390. const bits = name.split('.');
  5391. bits.pop();
  5392. current = bits.join('.');
  5393. }
  5394. }
  5395. module = this.import(name, current, level);
  5396. }
  5397. if (!fromlist) {
  5398. if (level === 0) {
  5399. return this.import(name.split('.')[0]);
  5400. }
  5401. else if (name) {
  5402. throw new python.Error("Unsupported relative import '" + name + "'.");
  5403. // cut_off = len(name) - len(name.partition('.')[0])
  5404. // return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
  5405. }
  5406. }
  5407. else if (module.__path__) {
  5408. const handle_fromlist = (module, fromlist, recursive) => {
  5409. for (const name of fromlist) {
  5410. if (name == '*') {
  5411. if (!recursive && module.__all__) {
  5412. handle_fromlist(module, module.__all__, true);
  5413. }
  5414. }
  5415. else if (!module[name]) {
  5416. this.import(module.__name__ + '.' + name);
  5417. }
  5418. }
  5419. return module;
  5420. };
  5421. handle_fromlist(module, fromlist);
  5422. }
  5423. return module;
  5424. }
  5425. module(name) {
  5426. return this._modules.get(name);
  5427. }
  5428. resolve(name) {
  5429. const index = name.lastIndexOf('.');
  5430. const memberName = index === -1 ? name : name.substring(index + 1, name.length);
  5431. const moduleName = index === -1 ? '' : name.substring(0, index);
  5432. const module = this.import(moduleName);
  5433. let type = module ? module[memberName] : null;
  5434. if (!type) {
  5435. if (!this._unresolved.has(name)) {
  5436. const moduleName = name.split('.').shift();
  5437. if (this._registry.has(moduleName) && moduleName !== '__main__') {
  5438. this.emit('resolve', name);
  5439. }
  5440. const type = this._createType(name, class {});
  5441. this._unresolved.set(name, type);
  5442. }
  5443. type = this._unresolved.get(name);
  5444. }
  5445. return type;
  5446. }
  5447. invoke(target, args) {
  5448. if (typeof target === 'string') {
  5449. target = this.resolve(target);
  5450. }
  5451. if (target) {
  5452. if (target.__class__ === this._builtins.type) {
  5453. if (target.prototype && target.prototype.__class__ === target) {
  5454. return Reflect.construct(target, args);
  5455. }
  5456. const obj = Object.create(target);
  5457. if (obj.__init__ && typeof obj.__init__ === 'function') {
  5458. obj.__init__.apply(obj, args);
  5459. }
  5460. return obj;
  5461. }
  5462. else if (target.__class__ === this._builtins.function) {
  5463. if (target.__call__) {
  5464. return target.__call__(args);
  5465. }
  5466. return target.apply(null, args);
  5467. }
  5468. }
  5469. throw new python.Error('Unsupported invoke target.');
  5470. }
  5471. call(target, name, args, context) {
  5472. const callTarget = this.target(target, context);
  5473. const callArguments = args.map((argument) => this.expression(argument, context));
  5474. if (!callTarget || (name !== null && !callTarget[name])) {
  5475. if (name === '__new__' && callArguments.length === 1 && callArguments[0] == callTarget) {
  5476. name = null;
  5477. callArguments.shift();
  5478. }
  5479. else {
  5480. const format = (expression) => {
  5481. if (expression.type == 'id') {
  5482. return expression.value;
  5483. }
  5484. if (expression.type == '.') {
  5485. return format(expression.target) + '.' + format(expression.member);
  5486. }
  5487. return null;
  5488. };
  5489. const targetName = format(target) + '.' + name;
  5490. throw new python.Error("Unknown function '" + targetName + "'.");
  5491. }
  5492. }
  5493. const func = name ? callTarget[name] : callTarget;
  5494. if (func.__class__ === this._builtins.type) {
  5495. if (func.prototype && func.prototype.__class__ === func) {
  5496. return Reflect.construct(func, args);
  5497. }
  5498. const obj = Object.create(func);
  5499. obj.__class__ = func;
  5500. if (obj.__init__ && typeof obj.__init__ === 'function') {
  5501. obj.__init__.apply(obj, args);
  5502. }
  5503. return obj;
  5504. }
  5505. if (func.__class__ === this._builtins.function) {
  5506. if (func.__call__) {
  5507. return func.__call__(callArguments);
  5508. }
  5509. }
  5510. if (func.__class__ === this._builtins.method) {
  5511. if (func.__call__) {
  5512. return func.__call__([ callTarget ].concat(callArguments));
  5513. }
  5514. }
  5515. if (typeof func === 'function') {
  5516. return func.apply(callTarget, callArguments);
  5517. }
  5518. throw new python.Error("Unsupported call expression.");
  5519. }
  5520. apply(method, args, context) {
  5521. const locals = Array.prototype.slice.call(args);
  5522. context = new python.Execution.Context(context.globals, {});
  5523. for (const parameter of method.parameters) {
  5524. let value = locals.shift();
  5525. if (value === undefined && parameter.initializer) {
  5526. value = this.expression(parameter.initializer, context);
  5527. }
  5528. context.set(parameter.name, value);
  5529. }
  5530. return this.block(method.body.statements, context);
  5531. }
  5532. block(statements, context) {
  5533. statements = Array.prototype.slice.call(statements);
  5534. while (statements.length > 0) {
  5535. const statement = statements.shift();
  5536. const value = this.statement(statement, context);
  5537. if (value !== undefined) {
  5538. return value;
  5539. }
  5540. }
  5541. return undefined;
  5542. }
  5543. statement(statement, context) {
  5544. switch (statement.type) {
  5545. case 'pass': {
  5546. break;
  5547. }
  5548. case 'return': {
  5549. return this.expression(statement.expression, context);
  5550. }
  5551. case 'def': {
  5552. const module = context.get('__name__');
  5553. const self = this;
  5554. const parent = context.get('__class__');
  5555. const type = (parent === this._builtins.module) ? this._builtins.function : this._builtins.method;
  5556. const func = {
  5557. __class__: type,
  5558. __globals__: context,
  5559. __module__: module,
  5560. __name__: statement.name,
  5561. __code__: statement,
  5562. __call__: function(args) {
  5563. return self.apply(this.__code__, args, this.__globals__);
  5564. }
  5565. };
  5566. context.set(statement.name, func);
  5567. break;
  5568. }
  5569. case 'class': {
  5570. const bases = statement.bases.map((arg) => this.expression(arg, context));
  5571. if (bases.length > 1) {
  5572. throw new python.Error("Unsupported multiple bases for class '" + statement.name + "'.");
  5573. }
  5574. const base = bases.length === 1 ? bases[0] : null;
  5575. const name = context.get('__name__') + '.' + statement.name;
  5576. const value = this._createType(name, base ? class extends base {} : class {});
  5577. value.__bases__ = bases;
  5578. context.set(statement.name, value);
  5579. this.block(statement.body.statements, new python.Execution.Context(context.globals, value.prototype));
  5580. break;
  5581. }
  5582. case 'var': {
  5583. context.set(statement.name, statement.initializer ? this.expression(statement.initializer, context) : undefined);
  5584. break;
  5585. }
  5586. case '=': {
  5587. this.expression(statement, context);
  5588. break;
  5589. }
  5590. case 'if': {
  5591. const condition = this.expression(statement.condition, context);
  5592. if (condition === true || condition) {
  5593. const value = this.block(statement.then.statements, context);
  5594. if (value !== undefined) {
  5595. return value;
  5596. }
  5597. break;
  5598. }
  5599. else if (condition === false) {
  5600. const value = this.block(statement.else.statements, context);
  5601. if (value !== undefined) {
  5602. return value;
  5603. }
  5604. break;
  5605. }
  5606. throw new python.Error("Unsupported condition.");
  5607. }
  5608. case 'for': {
  5609. if (statement.target.length == 1 &&
  5610. statement.variable.length === 1 && statement.variable[0].type === 'id') {
  5611. const range = this.expression(statement.target[0], context);
  5612. const variable = statement.variable[0];
  5613. for (const current of range) {
  5614. this.statement({ type: '=', target: variable, expression: { type: 'number', value: current }}, context);
  5615. const value = this.block(statement.body.statements, context);
  5616. if (value !== undefined) {
  5617. return value;
  5618. }
  5619. }
  5620. break;
  5621. }
  5622. throw new python.Error("Unsupported 'for' statement.");
  5623. }
  5624. case 'while': {
  5625. const condition = this.expression(statement.condition, context);
  5626. if (condition) {
  5627. const value = this.block(statement.body.statements, context);
  5628. if (value !== undefined) {
  5629. return value;
  5630. }
  5631. }
  5632. break;
  5633. }
  5634. case 'with': {
  5635. const items = [];
  5636. for (const item of statement.item) {
  5637. items.push(this.expression(item.expression, context));
  5638. }
  5639. for (const item of items) {
  5640. if (item.__enter__ && item.__enter__.__call__) {
  5641. item.__enter__.__call__([ item ]);
  5642. }
  5643. }
  5644. const value = this.block(statement.body.statements, context);
  5645. for (const item of items) {
  5646. if (item.__exit__ && item.__exit__.__call__) {
  5647. item.__exit__.__call__([ item ]);
  5648. }
  5649. }
  5650. if (value !== undefined) {
  5651. return value;
  5652. }
  5653. break;
  5654. }
  5655. case 'call': {
  5656. this.expression(statement, context);
  5657. break;
  5658. }
  5659. case 'import': {
  5660. for (const alias of statement.names) {
  5661. let module = this.__import__(alias.name, context);
  5662. if (alias.asname) {
  5663. const bits = alias.name.split('.').reverse();
  5664. bits.pop();
  5665. while (bits.length > 0) {
  5666. module = module[bits.pop()];
  5667. }
  5668. context.set(alias.asname, module);
  5669. }
  5670. else {
  5671. context.set(alias.name.split('.')[0], module);
  5672. }
  5673. }
  5674. break;
  5675. }
  5676. case 'import_from': {
  5677. const fromlist = statement.names.map((name) => name.name);
  5678. const module = this.__import__(statement.module, context.globals, context.locals, fromlist, statement.level);
  5679. for (const entry of statement.names) {
  5680. const name = entry.name;
  5681. const asname = entry.asname ? entry.asname : null;
  5682. if (!module[name]) {
  5683. throw new python.Error("Cannot import '" + name + "' from '" + statement.module + "'.");
  5684. }
  5685. context.set(asname ? asname : name, module[name]);
  5686. }
  5687. break;
  5688. }
  5689. case 'string': {
  5690. break;
  5691. }
  5692. default: {
  5693. throw new python.Error("Unsupported statement '" + statement.type + "'.");
  5694. }
  5695. }
  5696. return undefined;
  5697. }
  5698. expression(expression, context) {
  5699. const self = context.get('self');
  5700. switch (expression.type) {
  5701. case '=': {
  5702. const target = expression.target;
  5703. if (target.type === 'id') {
  5704. context.set(target.value, this.expression(expression.expression, context));
  5705. return undefined;
  5706. }
  5707. else if (target.type === '[]') {
  5708. if (target.target.type === 'id' &&
  5709. target.arguments.type === 'list' &&
  5710. target.arguments.value.length === 1) {
  5711. const index = this.expression(target.arguments.value[0], context);
  5712. if (target.target.value === '__annotations__') {
  5713. context.set(target.target.value, context.get(target.target.value) || {});
  5714. }
  5715. const obj = context.get(target.target.value);
  5716. const value = this.expression(expression.expression, context);
  5717. if (obj instanceof Map) {
  5718. obj.set(index, value);
  5719. }
  5720. else {
  5721. obj[index] = value;
  5722. }
  5723. return undefined;
  5724. }
  5725. }
  5726. else if (target.type === '.' &&
  5727. target.member.type === 'id') {
  5728. this.expression(target.target, context)[target.member.value] = this.expression(expression.expression, context);
  5729. return undefined;
  5730. }
  5731. else if (target.type === 'tuple') {
  5732. context.target.push(target.value);
  5733. const value = this.expression(expression.expression, context);
  5734. context.target.pop();
  5735. if (target.value.every((item) => item.type === 'id')) {
  5736. if (target.value.length < value.length) {
  5737. throw new python.Error('ValueError: too many values to unpack (expected ' + target.value.length + ', actual ' + value.length + ').');
  5738. }
  5739. if (target.value.length > value.length) {
  5740. throw new python.Error('ValueError: not enough values to unpack (expected ' + target.value.length + ', actual ' + value.length + ').');
  5741. }
  5742. for (let i = 0; i < value.length; i++) {
  5743. context.set(target.value[i].value, value[i]);
  5744. }
  5745. return undefined;
  5746. }
  5747. }
  5748. break;
  5749. }
  5750. case 'list': {
  5751. return expression.value.map((item) => this.expression(item, context));
  5752. }
  5753. case 'string': {
  5754. return expression.value.substring(1, expression.value.length - 1);
  5755. }
  5756. case 'number': {
  5757. return Number(expression.value);
  5758. }
  5759. case '[]': {
  5760. if (expression.target.type === 'id' &&
  5761. expression.arguments.type === 'list' &&
  5762. expression.arguments.value.length === 1) {
  5763. if (context.get(expression.target.value)) {
  5764. const index = this.expression(expression.arguments.value[0], context);
  5765. const target = context.get(expression.target.value);
  5766. if (target instanceof Map) {
  5767. return target.get(index);
  5768. }
  5769. return target[index < 0 ? target.length + index : index];
  5770. }
  5771. }
  5772. const target = this.expression(expression.target, context);
  5773. if (target && expression.arguments.type === 'list' &&
  5774. (target.__class__ === this._typing._TupleType ||
  5775. target.__class__ === this._typing._SpecialGenericAlias ||
  5776. target.__class__ === this._typing._SpecialForm)) {
  5777. const type = Object.assign({}, target);
  5778. type.__args__ = expression.arguments.value.map((arg) => this.expression(arg, context));
  5779. return type;
  5780. }
  5781. if (expression.arguments.type === 'list' && expression.arguments.value.length === 1) {
  5782. const index = this.expression(expression.arguments.value[0], context);
  5783. if (target instanceof Map) {
  5784. return target.get(index);
  5785. }
  5786. return target[index < 0 ? target.length + index : index];
  5787. }
  5788. break;
  5789. }
  5790. case '.': {
  5791. if (expression.member.type == 'id') {
  5792. const target = this.target(expression.target, context);
  5793. return target[expression.member.value];
  5794. }
  5795. throw new python.Error("Unsupported field expression.");
  5796. }
  5797. case 'call': {
  5798. if (expression.target.type === 'id' && expression.target.value === 'unchecked_cast' && expression.arguments.length === 2) {
  5799. return this.expression(expression.arguments[1], context);
  5800. }
  5801. if (expression.target.type === '.') {
  5802. return this.call(expression.target.target, expression.target.member.value, expression.arguments, context);
  5803. }
  5804. return this.call(expression.target, null, expression.arguments, context);
  5805. }
  5806. case 'id': {
  5807. switch (expression.value) {
  5808. case 'self': return self;
  5809. case 'None': return null;
  5810. case 'True': return true;
  5811. case 'False': return false;
  5812. default: {
  5813. const type = (value) => {
  5814. return value &&
  5815. (value.__class__ === this._builtins.type ||
  5816. value.__class__ === this._typing._TupleType ||
  5817. value.__class__ === this._typing._SpecialGenericAlias ||
  5818. value.__class__ === this._typing._SpecialForm);
  5819. };
  5820. const builtin = this._builtins[expression.value];
  5821. if (type(builtin)) {
  5822. return builtin;
  5823. }
  5824. const value = context.get(expression.value);
  5825. if (value === undefined) {
  5826. const typing = this._typing[expression.value];
  5827. if (type(typing)) {
  5828. return typing;
  5829. }
  5830. const torch = this._registry.get('torch');
  5831. if (torch) {
  5832. const value = torch[expression.value]; // TODO
  5833. if (type(value)) {
  5834. return value;
  5835. }
  5836. }
  5837. }
  5838. return value;
  5839. }
  5840. }
  5841. }
  5842. case 'tuple': {
  5843. return expression.value.map((expression) => this.expression(expression, context));
  5844. }
  5845. case 'dict': {
  5846. const dict = {};
  5847. for (const pair of expression.value) {
  5848. if (pair.type !== 'pair') {
  5849. throw new python.Error("Unsupported dict item type '" + pair.type + "'.");
  5850. }
  5851. const key = this.expression(pair.key, context);
  5852. const value = this.expression(pair.value, context);
  5853. dict[key] = value;
  5854. }
  5855. return dict;
  5856. }
  5857. case 'unary': {
  5858. switch (expression.op) {
  5859. case '-': {
  5860. return -this.expression(expression.operand, context);
  5861. }
  5862. default: {
  5863. throw new python.Error("Unsupported unary expression '" + expression.op + "'.");
  5864. }
  5865. }
  5866. }
  5867. default: {
  5868. throw new python.Error("Unsupported expression '" + expression.type + "'.");
  5869. }
  5870. }
  5871. return undefined;
  5872. }
  5873. target(expression, context) {
  5874. let current = expression;
  5875. let path = [];
  5876. for (;;) {
  5877. if (current.type === '.' && current.member && current.member.type === 'id') {
  5878. path.push(current.member.value);
  5879. current = current.target;
  5880. }
  5881. else if (current.type === 'id' && current.value !== 'self' && current.value !== 'CONSTANTS') {
  5882. path.push(current.value);
  5883. break;
  5884. }
  5885. else {
  5886. path = null;
  5887. break;
  5888. }
  5889. }
  5890. if (path) {
  5891. let target = null;
  5892. for (let i = path.length - 1; i >= 0; i--) {
  5893. target = target ? target[path[i]] : context.get(path[i]);
  5894. if (!target) {
  5895. break;
  5896. }
  5897. }
  5898. if (!target) {
  5899. path.reverse();
  5900. const name = path.join('.');
  5901. const file = path.join('/') + '.py';
  5902. if (this._sources.has(file)) {
  5903. target = this.import(name);
  5904. }
  5905. else {
  5906. target = this.resolve(name);
  5907. }
  5908. }
  5909. return target;
  5910. }
  5911. return this.expression(expression, context);
  5912. }
  5913. add(name, source) {
  5914. this._sources.set(name, source);
  5915. }
  5916. on(event, listener) {
  5917. const value = this._events.get(event) || [];
  5918. value.push(listener);
  5919. this._events.set(event, value);
  5920. }
  5921. emit(event, ...args) {
  5922. if (this._events.has(event)) {
  5923. for (const callback of this._events.get(event)) {
  5924. callback(this, ...args);
  5925. }
  5926. }
  5927. }
  5928. register(name, value) {
  5929. if (!this._registry.has(name)) {
  5930. value = value || new (this._registry.get('builtins').module)(name);
  5931. this._registry.set(name, value);
  5932. let current = name;
  5933. for (;;) {
  5934. const index = current.lastIndexOf('.');
  5935. if (index === -1) {
  5936. break;
  5937. }
  5938. const child = current.substring(index + 1);
  5939. current = current.substring(0, index);
  5940. const parent = this.register(current);
  5941. parent[child] = value;
  5942. }
  5943. }
  5944. return this._registry.get(name);
  5945. }
  5946. registerFunction(name, value) {
  5947. const parts = name.split('.');
  5948. value.__class__ = this._builtins.function;
  5949. value.__name__ = parts.pop();
  5950. value.__module__ = parts.join('.');
  5951. const module = this.register(value.__module__);
  5952. if (module[name]) {
  5953. throw new python.Error("Function '" + name + "' is already registered.");
  5954. }
  5955. module[value.__name__] = value;
  5956. return value;
  5957. }
  5958. _createType(name, value) {
  5959. const parts = name.split('.');
  5960. value.__class__ = this._builtins.type;
  5961. value.__name__ = parts.pop();
  5962. value.__module__ = parts.join('.');
  5963. value.prototype.__class__ = value;
  5964. return value;
  5965. }
  5966. registerType(name, value) {
  5967. value = this._createType(name, value);
  5968. const parts = name.split('.');
  5969. const memberName = parts.pop();
  5970. const moduleName = parts.join('.');
  5971. const module = this.register(moduleName);
  5972. if (module[memberName]) {
  5973. throw new python.Error("Class '" + memberName + "' is already registered.");
  5974. }
  5975. module[memberName] = value;
  5976. return value;
  5977. }
  5978. };
  5979. python.Execution.Context = class {
  5980. constructor(globals, locals) {
  5981. this.globals = globals;
  5982. this.locals = locals;
  5983. }
  5984. set(name, value) {
  5985. if (this.locals) {
  5986. this.locals[name] = value;
  5987. }
  5988. else {
  5989. this.globals[name] = value;
  5990. }
  5991. }
  5992. get(name) {
  5993. if (this.locals && name in this.locals) {
  5994. return this.locals[name];
  5995. }
  5996. if (name in this.globals) {
  5997. return this.globals[name];
  5998. }
  5999. return undefined;
  6000. }
  6001. get target() {
  6002. this._target = this._target || [];
  6003. return this._target;
  6004. }
  6005. };
  6006. python.Unpickler = class {
  6007. static open(data, execution) {
  6008. const reader = data instanceof Uint8Array ? new python.Unpickler.BinaryReader(data) : new python.Unpickler.StreamReader(data);
  6009. if (reader.length > 2) {
  6010. const head = reader.peek(2);
  6011. if (head[0] === 0x80 && head[1] < 7) {
  6012. execution = typeof execution === 'function' ? execution() : execution;
  6013. return execution.invoke('pickle.Unpickler', [ data ]);
  6014. }
  6015. reader.seek(-1);
  6016. const tail = reader.peek(1);
  6017. reader.seek(0);
  6018. if (tail[0] === 0x2e) {
  6019. execution = typeof execution === 'function' ? execution() : execution;
  6020. return execution.invoke('pickle.Unpickler', [ data ]);
  6021. }
  6022. }
  6023. return null;
  6024. }
  6025. };
  6026. // https://svn.python.org/projects/python/trunk/Lib/pickletools.py
  6027. // https://github.com/python/cpython/blob/master/Lib/pickle.py
  6028. python.Unpickler.OpCode = {
  6029. MARK: 40, // '('
  6030. EMPTY_TUPLE: 41, // ')'
  6031. STOP: 46, // '.'
  6032. POP: 48, // '0'
  6033. POP_MARK: 49, // '1'
  6034. DUP: 50, // '2'
  6035. BINBYTES: 66, // 'B' (Protocol 3)
  6036. SHORT_BINBYTES: 67, // 'C' (Protocol 3)
  6037. FLOAT: 70, // 'F'
  6038. BINFLOAT: 71, // 'G'
  6039. INT: 73, // 'I'
  6040. BININT: 74, // 'J'
  6041. BININT1: 75, // 'K'
  6042. LONG: 76, // 'L'
  6043. BININT2: 77, // 'M'
  6044. NONE: 78, // 'N'
  6045. PERSID: 80, // 'P'
  6046. BINPERSID: 81, // 'Q'
  6047. REDUCE: 82, // 'R'
  6048. STRING: 83, // 'S'
  6049. BINSTRING: 84, // 'T'
  6050. SHORT_BINSTRING: 85, // 'U'
  6051. UNICODE: 86, // 'V'
  6052. BINUNICODE: 88, // 'X'
  6053. EMPTY_LIST: 93, // ']'
  6054. APPEND: 97, // 'a'
  6055. BUILD: 98, // 'b'
  6056. GLOBAL: 99, // 'c'
  6057. DICT: 100, // 'd'
  6058. APPENDS: 101, // 'e'
  6059. GET: 103, // 'g'
  6060. BINGET: 104, // 'h'
  6061. INST: 105, // 'i'
  6062. LONG_BINGET: 106, // 'j'
  6063. LIST: 108, // 'l'
  6064. OBJ: 111, // 'o'
  6065. PUT: 112, // 'p'
  6066. BINPUT: 113, // 'q'
  6067. LONG_BINPUT: 114, // 'r'
  6068. SETITEM: 115, // 's'
  6069. TUPLE: 116, // 't'
  6070. SETITEMS: 117, // 'u'
  6071. EMPTY_DICT: 125, // '}'
  6072. PROTO: 128,
  6073. NEWOBJ: 129,
  6074. TUPLE1: 133, // '\x85'
  6075. TUPLE2: 134, // '\x86'
  6076. TUPLE3: 135, // '\x87'
  6077. NEWTRUE: 136, // '\x88'
  6078. NEWFALSE: 137, // '\x89'
  6079. LONG1: 138, // '\x8a'
  6080. LONG4: 139, // '\x8b'
  6081. SHORT_BINUNICODE: 140, // '\x8c' (Protocol 4)
  6082. BINUNICODE8: 141, // '\x8d' (Protocol 4)
  6083. BINBYTES8: 142, // '\x8e' (Protocol 4)
  6084. EMPTY_SET: 143, // '\x8f' (Protocol 4)
  6085. ADDITEMS: 144, // '\x90' (Protocol 4)
  6086. FROZENSET: 145, // '\x91' (Protocol 4)
  6087. NEWOBJ_EX: 146, // '\x92' (Protocol 4)
  6088. STACK_GLOBAL: 147, // '\x93' (Protocol 4)
  6089. MEMOIZE: 148, // '\x94' (Protocol 4)
  6090. FRAME: 149, // '\x95' (Protocol 4)
  6091. BYTEARRAY8: 150, // '\x96' (Protocol 5)
  6092. NEXT_BUFFER: 151, // '\x97' (Protocol 5)
  6093. READONLY_BUFFER: 152 // '\x98' (Protocol 5)
  6094. };
  6095. python.Unpickler.BinaryReader = class {
  6096. constructor(buffer) {
  6097. this._buffer = buffer;
  6098. this._length = buffer.length;
  6099. this._position = 0;
  6100. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  6101. this._utf8Decoder = new TextDecoder('utf-8');
  6102. this._asciiDecoder = new TextDecoder('ascii');
  6103. }
  6104. get position() {
  6105. return this._position;
  6106. }
  6107. get length() {
  6108. return this._length;
  6109. }
  6110. seek(position) {
  6111. this._position = position >= 0 ? position : this._length + position;
  6112. if (this._position > this._buffer.length) {
  6113. throw new Error('Expected ' + (this._position - this._buffer.length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  6114. }
  6115. }
  6116. skip(offset) {
  6117. this._position += offset;
  6118. if (this._position > this._buffer.length) {
  6119. throw new python.Error('Expected ' + (this._position - this._buffer.length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  6120. }
  6121. }
  6122. stream(length) {
  6123. const buffer = this.read(length);
  6124. return new python.Unpickler.BinaryReader(buffer);
  6125. }
  6126. peek(length) {
  6127. const position = this._position;
  6128. length = length !== undefined ? length : this._length - this._position;
  6129. this.skip(length);
  6130. const end = this._position;
  6131. this.skip(-length);
  6132. if (position === 0 && length === this._length) {
  6133. return this._buffer;
  6134. }
  6135. return this._buffer.subarray(position, end);
  6136. }
  6137. read(length) {
  6138. const position = this._position;
  6139. length = length !== undefined ? length : this._length - this._position;
  6140. this.skip(length);
  6141. if (position === 0 && length === this._length) {
  6142. return this._buffer;
  6143. }
  6144. return this._buffer.subarray(position, this._position);
  6145. }
  6146. byte() {
  6147. const position = this._position;
  6148. this.skip(1);
  6149. return this._view.getUint8(position);
  6150. }
  6151. uint16() {
  6152. const position = this._position;
  6153. this.skip(2);
  6154. return this._view.getUint16(position, true);
  6155. }
  6156. int32() {
  6157. const position = this._position;
  6158. this.skip(4);
  6159. return this._view.getInt32(position, true);
  6160. }
  6161. uint32() {
  6162. const position = this._position;
  6163. this.skip(4);
  6164. return this._view.getUint32(position, true);
  6165. }
  6166. int64() {
  6167. const position = this._position;
  6168. this.skip(8);
  6169. return this._view.getInt64(position, true).toNumber();
  6170. }
  6171. float64() {
  6172. const position = this._position;
  6173. this.skip(8);
  6174. return this._view.getFloat64(position, false);
  6175. }
  6176. string(size, encoding) {
  6177. const data = this.read(size);
  6178. return (encoding == 'utf-8') ?
  6179. this._utf8Decoder.decode(data) :
  6180. this._asciiDecoder.decode(data);
  6181. }
  6182. line() {
  6183. const index = this._buffer.indexOf(0x0A, this._position);
  6184. if (index == -1) {
  6185. throw new python.Error("Could not find end of line.");
  6186. }
  6187. const size = index - this._position;
  6188. const text = this.string(size, 'ascii');
  6189. this.skip(1);
  6190. return text;
  6191. }
  6192. };
  6193. python.Unpickler.StreamReader = class {
  6194. constructor(stream) {
  6195. this._stream = stream;
  6196. this._length = stream.length;
  6197. this._position = 0;
  6198. this._utf8Decoder = new TextDecoder('utf-8');
  6199. this._asciiDecoder = new TextDecoder('ascii');
  6200. }
  6201. get position() {
  6202. return this._position;
  6203. }
  6204. get length() {
  6205. return this._length;
  6206. }
  6207. seek(position) {
  6208. this._stream.seek(position);
  6209. this._position = this._stream.position;
  6210. }
  6211. skip(offset) {
  6212. this._position += offset;
  6213. if (this._position > this._length) {
  6214. throw new python.Error('Expected ' + (this._position - this._length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  6215. }
  6216. }
  6217. stream(length) {
  6218. this._stream.seek(this._position);
  6219. this.skip(length);
  6220. return this._stream.stream(length);
  6221. }
  6222. peek(length) {
  6223. this._stream.seek(this._position);
  6224. return this._stream.peek(length);
  6225. }
  6226. read(length) {
  6227. this._stream.seek(this._position);
  6228. this.skip(length);
  6229. return this._stream.read(length);
  6230. }
  6231. byte() {
  6232. const position = this._fill(1);
  6233. return this._view.getUint8(position);
  6234. }
  6235. uint16() {
  6236. const position = this._fill(2);
  6237. return this._view.getUint16(position, true);
  6238. }
  6239. int32() {
  6240. const position = this._fill(4);
  6241. return this._view.getInt32(position, true);
  6242. }
  6243. uint32() {
  6244. const position = this._fill(4);
  6245. return this._view.getUint32(position, true);
  6246. }
  6247. int64() {
  6248. const position = this._fill(8);
  6249. return this._view.getInt64(position, true).toNumber();
  6250. }
  6251. float64() {
  6252. const position = this._fill(8);
  6253. return this._view.getFloat64(position, true);
  6254. }
  6255. string(size, encoding) {
  6256. const data = this.read(size);
  6257. return (encoding == 'utf-8') ?
  6258. this._utf8Decoder.decode(data) :
  6259. this._asciiDecoder.decode(data);
  6260. }
  6261. line() {
  6262. let position = this._fill(0);
  6263. let index = this._buffer.indexOf(0x0A, position);
  6264. if (index == -1) {
  6265. const size = Math.min(0x1000000, this._stream.length - this._position);
  6266. this._fill(size);
  6267. this.skip(-size);
  6268. position = this._fill(0);
  6269. index = this._buffer.indexOf(0x0A, position);
  6270. if (index == -1) {
  6271. throw new python.Error("Could not find end of line.");
  6272. }
  6273. }
  6274. const size = index - position;
  6275. const text = this.string(size, 'ascii');
  6276. this.skip(1);
  6277. return text;
  6278. }
  6279. _fill(length) {
  6280. if (this._position + length > this._length) {
  6281. throw new Error('Expected ' + (this._position + length - this._length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  6282. }
  6283. if (!this._buffer || this._position < this._offset || this._position + length > this._offset + this._buffer.length) {
  6284. this._offset = this._position;
  6285. this._stream.seek(this._offset);
  6286. this._buffer = this._stream.read(Math.min(0x10000000, this._length - this._offset));
  6287. this._view = new DataView(this._buffer.buffer, this._buffer.byteOffset, this._buffer.byteLength);
  6288. }
  6289. const position = this._position;
  6290. this._position += length;
  6291. return position - this._offset;
  6292. }
  6293. };
  6294. python.Error = class extends Error {
  6295. constructor(message) {
  6296. super(message);
  6297. this.name = 'Python Error';
  6298. }
  6299. };
  6300. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  6301. module.exports.Execution = python.Execution;
  6302. module.exports.Unpickler = python.Unpickler;
  6303. }