init
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+4
- .gitignoreAdded+64
- data/alphabet-all-v5.txtAdded+19264
- data/alphabet-all-v7.txtAdded
- data/libs/opencv_world455.dllAdded+3
- data/libs/patchmatch_inpaint.dllAdded+3
- data/models/aot_inpainter.ckptAdded+3
- data/models/comictextdetector.ptAdded+3
- data/models/comictextdetector.pt.onnxAdded+3
- data/models/lama_large_512px.ckptAdded+3
- data/models/lama_mpe.ckptAdded+3
- data/models/manga-ocr-base/README.mdAdded+24
- data/models/manga-ocr-base/config.jsonAdded+2164
- data/models/manga-ocr-base/preprocessor_config.jsonAdded+17
- data/models/manga-ocr-base/pytorch_model.binAdded+3
- data/models/manga-ocr-base/special_tokens_map.jsonAdded+1
- data/models/manga-ocr-base/tokenizer_config.jsonAdded+1
- data/models/manga-ocr-base/vocab.txtAdded+6144
- data/models/mit32px_ocr.ckptAdded+3
- data/models/mit48pxctc_ocr.ckptAdded+3
- data/models/ocr_ar_48px.ckptAdded+3
- data/models/pkuseg/postag/features.pklAdded+3
- data/models/pkuseg/postag/weights.npzAdded+3
- data/models/pkuseg/spacy_ontonotes/features.msgpackAdded+3
- data/models/pkuseg/spacy_ontonotes/weights.npzAdded+3
- data/pkusegscores.jsonAdded+1
- freeze.txtAdded+446
- main.pyAdded+146
- modules/__init__.pyAdded+21
- modules/base.pyAdded+364
- modules/inpaint/__init__.pyAdded+1
- modules/inpaint/aot.pyAdded+259
- modules/inpaint/base.pyAdded+604
- modules/inpaint/ffc.pyAdded+312
- modules/inpaint/lama.pyAdded+430
- modules/inpaint/patch_match.pyAdded+209
- modules/ocr/__init__.pyAdded+1
- modules/ocr/base.pyAdded+55
- modules/ocr/mit32px.pyAdded+638
- modules/ocr/mit48px.pyAdded+893
- modules/ocr/mit48px_ctc.pyAdded+503
- modules/ocr/ocr_bing_lens.pyAdded+430
- modules/ocr/ocr_google_vision.pyAdded+275
- modules/ocr/ocr_lens_proto.pyAdded+593
- modules/ocr/ocr_llm_api.pyAdded+488
- modules/ocr/ocr_macos.pyAdded+151
- modules/ocr/ocr_manga.pyAdded+115
- modules/ocr/ocr_mit.pyAdded+95
- modules/ocr/ocr_none.pyAdded+19
- modules/ocr/ocr_oneocr.pyAdded+425
1234*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text12345678*.7z filter=lfs diff=lfs merge=lfs -text*.dll filter=lfs diff=lfs merge=lfs -text*.so filter=lfs diff=lfs merge=lfs -text*.exe filter=lfs diff=lfs merge=lfs -text*.icns filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364__pycache__logs# local_*# inpainted# mask# result# data/models# data/testpacks/eng_dontupload# data/testpacks/testpacks# data/*.png# data/testpacks# config/textstyles# release# libs# icons.btrans_cache
# tmp.py# dummy_scripts.py
# alphabet-all-*# *gitpython# PortableGit# test_dir# tmp# logs# ballontrans_pylibs_win# config/config.json# localtmp*
# .vscode# .VSCodeCounter# .idea# *.zip# *.ipynb# *.dll# *.so# *.docx# *.doc# *.pt# *.ckpt# *.onnx# *.7z# venv# pip# .DS_Store# *.dic# *.aff# *.exc
# fonts/*# !fonts/put fonts here.txt
#venv and autoinstaller folders# aria2c# python# git# modules/experiments# update_git.bat# launch_win_venv.bat# install_venv.bat# install-BT.cmd# download_models.bat# Ultralytics/settings.json12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264<PAD><S></S><SEP><UNK><SP><LF><UNUSED3><UNUSED4><UNUSED5><UNUSED6><UNUSED7><UNUSED8><UNUSED9><UNUSED10><UNUSED11><UNUSED12><UNUSED13><UNUSED14><UNUSED15><UNUSED16><UNUSED17><UNUSED18><UNUSED19><UNUSED20><UNUSED21><UNUSED22><UNUSED23><UNUSED24><UNUSED25><UNUSED26><UNUSED27><UNUSED28><UNUSED29><UNUSED30><UNUSED31><UNUSED32><UNUSED33><UNUSED34><UNUSED35><UNUSED36><UNUSED37><UNUSED38><UNUSED39><UNUSED40><UNUSED41><UNUSED42><UNUSED43><UNUSED44><UNUSED45><UNUSED46><UNUSED47><UNUSED48><UNUSED49><UNUSED50><UNUSED51>!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĭĮįİıIJĴĵĶķĸĺĻļĽľŁłŃńŅņŇňŊŋŌōŏŐőŒœŕŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŵŸŹźŻżŽžſƏƒơƣưƶǀǁǂǎǐǒǔǖǚǜǝǣǧǫǯǰǵȘșțȟȡȵɐɑɒɔɕɗəɚɛɜɞɟɡɢɣɤɥɦɨɪɫɬɯɰɲɳɴɵɸɹɾɿʀʁʂʃʅʈʉʊʋʌʍʏʐʑʒʔʕʖʘʚʣʤʥʦʧʨʰʱʲʷʹʺʻʼʽʾʿˀ˂˃ˆˇˈˉˊˋˌˍˎˏː˖˘˙˚˝ˢ˥˦˧˨˩˫ˬ˵˶̴̵̶̷̡̙̟̠̣̤̥̦̩̪̫̭̮̯̰̱̳͈͙̀́̂̃̄̆̇̈̉̊̌̍̑͒͛̚͘͜͟͞͡͵΄ΆΈΉΊΌΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩάέήίαβγδεζηθικλμνξοπρςστυφχψωϊόύώϘϚϜϝϺЁЂЃЄЅІЇЈЉЊЋЌЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяёђѓєѕіїјљњћќѝўџѠѡѢѣѦѧѪѫѭѮѯѰѲѳѴѵѾҀ҆ҐґҒғҔҕҖҗҚқҜҝҟҢңҤҥҧҭҮүҰұҲҳҵҶҷҸҹҺһӀӂӃӄӇӈӋӌӐӑӕӗӘәӠӡӢӣӦӧӨөӮӯӰӱӲӳԅԭԱԲԳԴԵԹԼՀՂՄՆՈՊՍՎՔ՞աբգդեզըթժիլխծկհձղմյնշոչպջռսվտրցւփքօև։ְֲִֵֶַָֹּ־ֿׁׂאבגדהוזחטיךכלםמןנסעףפץצקרשת،؟ءآأؤإئابةتثجحخدذرزسشصضطظعغـفقكلمنهوىيًٌٍَُِّْ١٢٣٤٥٦٩٭ٰٱٴټپچژڠڡڤکڭگڼھہۅۆۇۈۉۋیېە۳۶۹܌ܐܒܕܗܘܚܝܟܠܡܢܣܩܪܫܬܼܲܵހށނރބކއވމފދތލގސޔަާިީުެޮްँंःअआइईउऊएऐओऔकखगघङचछजझञटठडढणतथदधनपफबभमयरलवशषसह़ािीुूृेैोौ्॑।ংঅআইকখগচছজটডণতদধনপবভমযরলশষসহ়ািীুেো্৹ਊਰਾੀ੭ੰકજતરાીુ୧୨ஃஅஆஇஈஉஎஐஒஓகஙசஜஞடணதநனபமயரறலளழவஶஷஸஹாிீுூெேைொோௌ்௰ంకఖగ��తనపమరలవాిుె్౪ಕಗಚಠಡತದನಪಬಮಯರಲಳವಹಾಿುೂೆ್ഀംകചടതനപമയരറലളവാിുോ്ංඅකජතදනපබමයරලවසහ්ාැිීුේෝกขคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลวศษสหฬอฮฯะัาำิีึืุู฿เแโใไๆ็่้๊์๏๑๛ກຂຄງຈຊຍດຕທນບປພມລວສຫອຮະັາິີືູົເໂໃໄ່້໒་།༥ཀཁགངཅཆཉཏདནཔཕབམཙཚཛཞའཡརལཤསཧཨཫཱིེོུྐྒྗྟྡྨྩྫྱྲླྷ࿀࿁ကခငစညတနပဘမယရလသအာိုေ့း္်ျြွ၊აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჲᄀᄂᄃᄇᄉᄌᄒᄙᅀᅟᅠᅡᅢᅣᅤᅥᅦᅧᅨᅩᅪᅫᅬᅭᅮᅯᅰᅱᅲᅳᅴᅵᆜᆝᆞᆡᆢᆨᆫᆯᇂᇃᇰህለላልመማምረሪራርሰስሽበባብተትቶችነናንአኢኤእከክውዓዕዝየያይዮደድግጵ፡᎑Ꮄᐛᐜᐝᐞᐡᐢᐨᐱᑭᕕᕗᕤᕦᕱᗜᗨកខគងចជដតទនបពមយរលវសអាិីុូេែំះ់័្ᠠᠣᠨᠰᡠᡥᡳᥒᥰᯅᴇᴑᴖᴗᴥᵈᵏᵐᵒᵕ᷄᷅᷆᷇ḇḍḏḤḥḪḫḳḷṃṅṇṉṗṛṢṣṭṯẋẓẖạảấầẩậắằặẻẼẽếềểễệỉịọỏốồổỗộớờởợụủứừửữựỳỷỹἀἄἈἐἘἙἨἩἰἱἴἸἹὁὐὢὴὶὺᾤᾥῆῖῦῬῶ῾‐‑‒–—―‖‘’‚“”„‟†‡•‣․‥…‧‰‱′″‵‶‸‹›※‼‽‿⁂⁄⁇⁈⁉⁰⁴⁶⁺⁻⁾ⁿ₁₂₃₄₆₋₍₎₤₦₧₩₪₫€₲₹⃘⃙⃔⃕⃛⃝⃣℃℅℉ℊℓ№ℝ℡™KÅℯℱℵ⅓⅔⅛⅜⅝⅞ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫⅮⅯⅰⅱⅲⅳⅹ←↑→↓↔↕↖↗↘↙↝↪↴↷↺↻⇀⇄⇆⇈⇌⇐⇒⇓⇔⇗⇘⇛⇠⇢⇦⇨⇵⇸∀∂∃∅∇∈∉∋∎∏∑−∕∗∘∙√∝∞∟∠∣∥∧∨∩∪∫∬∮∴∵∶∷∼∽≅≈≌≒≖≠≡≣≤≥≦≧≪≫≯≳≻≼≽⊂⊃⊆⊇⊊⊋⊕⊗⊙⊡⊥⊰⊱⊿⋅⋆⋈⋊⋮⋯⋰⋱⌂⌈⌋⌒⌓⌖⌘⌜⌟〈〉⌯⎝⎞⏩␣⑅⑉①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳⑴⑵⑶⑷⑸⑹⑺⑻⑼⑽⑾⑿⒀⒁⒂⒆⒈⒉⒊⒋⒍⒎⒏⒖ⒶⓁⓄⓋⓐⓒⓛ⓪─━│┃┄┅┈┉┋┌┍┎┏┐┑┓└┕┖┗┘┚┛├┝┞┢┣┤┥┦┨┪┫┬┮┯┰┳┴┵┶┷┸┺┻┼┾┿╀╁╂╃╄╅╆╇╈╊╋═║╝╟╢╣╧╩╪╬╭╮╯╰╱╳╹▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏░▒▓▔▕■□▢▣▤▦▧▨▩▪▫▰▱▲△▵▶▷▸▹►▼▽▿◀◁◄◆◇◈◉◊○◌◍◎●◐◔◕◘◙◜◝◞◟◠◡◢◣◤◦◪◯◻◼◽◾☀☁☂☃★☆☉☍☎☏☑☓☔☕☗☘☜☝☞☟☠☣☨☪☰☱☲☳☴☵☶��☸☹☺☻☼☽☾♀♂♄♈♊♋♌♍♎♏♒♔♞♠♡♢♣♤♥♦♧♨♩♪♫♬♭♯♾⚓⚔⚖⚠⚡⚪⚫⚬✂✄✆✈✊✋✌✍✎✓✔✕✖✗✛✜✝✟✡✢✣✤✥✦✧✨✩✪✬✭✮✯✰✱✲✳✴✵✶✺✻✼✽✾✿❀❁❄❅❆❇❊❋❌❏❐❑❒❓❕❖❗❛❝❞❢❣❤❥❦❧❨❩❶❷❸❹❺❻❼❽➀➁➂➃➕➖➡➤➳➸⟨⟩⟪⟫⠀⡱⤴⤵⥤⥧⥴⬅⬆⬇⬛⬜⭐⭕ⴰⴳⴷⴻⴾⵉⵍⵎⵏⵓⵔⵙⵜⵡⵢⵣ⸜⸝⺟⺼⻄⻅⻆⻉⻋⻓⻔⻛⻝⻢⻣⻤⻩⻰⼀⼆⼈⼉⼊⼏⼑⼒⼗⼜⼝⼠⼤⼥⼦⼨⼩⼯⼰⼱⼲⼼⼿⽂⽃⽅⽆⽇⽌⽐⽑⽓⽔⽕⽗⽚⽛⽟⽢⽣⽤⽩⽪⽬⽳⽴⽵⽹⽼⽽⽿⾁⾃⾄⾆⾊⾎⾏⾐⾔⾚⾛⾜⾥⾬⾯⾳⾹⾼⿊⿐⿰⿴⿸⿻、。〃々〆〇〈〉《》「」『』【】〒〓〔〕〖〗〘〙〚〛〜〝〞〟〡〢〣〤〥〦〨〩〮〰〱〼〽ぁあぃいぅうぇえぉおかがきぎくぐけげこごさざしじすずせぜそぞただちぢっつづてでとどなにぬねのはばぱひびぴふぶぷへべぺほぼぽまみむめもゃやゅゆょよらりるれろゎわゐゑをんゔゕ゙゚゛゜ゝゞァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶ・ーヽヾㄅㄆㄇㄈㄉㄊㄋㄌㄍㄎㄏㄐㄑㄒㄓㄔㄕㄖㄗㄘㄙㄚㄛㄜㄝㄞㄟㄠㄡㄢㄣㄤㄥㄦㄧㄨㄩㄪㄫㄬㄭㄱㄲㄳㄴㄵㄶㄷㄸㄹㄺㄻㄼㄽㄾㄿㅀㅁㅂㅃㅄㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅣㅤㅥㅦㅭㅱㅲㅳㅴㅵㅸㅹㅺㅼㅽㅾㅿㆀㆁㆄㆅㆆㆇㆉㆊㆋㆌㆍㆎㆡㆢㆤㆥㆦㆨㆩㆪㆫㆬㆭㆰㆲㆴㆵㆶㆷㇱㇲㇵㇶㇸㇺㇼㇽ㈜㈠㈡㈢㈩㈱㉝㊗㊙㊟㊣㊤㊥㊦㊨㋐㋖㋣㋬㋷㌍㌔㌢㌦㌧㍉㍍㍑㎍㎎㎏㎐㎑㎒㎖㎘㎛㎜㎝㎞㎟㎡㎢㎥㎳㎾㏄㏊㏎㏑㏒㏕㐅㐌㒼㓦㕲㗎㗏㗑㘄㘗㘥㘵㙍㙘㙟㙦㚻㝹㞎㟂㦃㧐㧟㨶㩟㬌㬎㬤㭭㮾㳇㴩㴭㵐㵲㶁㶞㷩㸆㹢㹴㺢㻋㼁㼅㽏䀹䁖䃍䃎䄄䄉䄙䇲䍉䏝䓪䓬䖢䙌䜣䜺䝉䝤䞍䢺䣤䥑䦃䦆䱻䲟䳭䴉䴘䴙䴥䵚䶄一丁丂七丄丆万丈三上下丌不与丏丐丑丒专且丕世丘丙业丛东丝丞丟両丢两严並丧丨个丫中丰串临丵丶丷丸丹为主丼丽举丿乀乁乂乃久乇么义乊之乌乍乎乏乐乒乓乔乕乖乗乘乙乚乛乜九乞也习乡乢书乧乩乫乭买乱乲乳乸乾亀亁亂亅了予争亊事二亍于亏亐云互亓五井亖亘亙亚些亜亞亟亠亡亢亣交亥亦产亨亩享京亭亮亯亰亲亳亵亶亹人亻亼亿什仁仂仃仄仅仆仇仉今介仌仍从仏仑仓仔仕他仗付仙仚仝仞仟仡代令以仧仨仪仫们仮仰仲仳仵件价仸仹仺任仼份仿企伂伃伅伈伉伊伋伍伎伏伐休伒伓伔伕众优伙会伛伝伞伟传伢伤伥伦伧伪伫伬伯估伱伲伴伶伷伸伹伺似伽伾佂佃但佇佈佉佋位低住佐佑体佔何��佗佘余佚佛作佝佞佟你佢佣佤佥佧佩佬佮佯佰佳併佶佷佺佻佼佽佾使侁侂侃侄侅來侈侉侊例侍侏侐侑侔侖侗侘侚供侜依侠価侣侥侦侧侨侩侪侬侭侮侯侰侳侵侶侷侹便俀俁係促俄俅俇俊俋俌俍俎俏俐俑俓俔俖俗俘俙俚俛保俞俟俠信俣俥俦俨俩俪俬俭修俯俱俳俴俵俶俸俺俽俾倀倂倅倆倈倉個倌倍倎倏們倒倓倔倕倖倗倘候倚倜倞借倡倢倣値倥倦倧倨倩倪倫倬倭倮倯倰倱倲倳倴倶倷倹债倻值倾偁偂偃偅假偈偉偊偋偌偎偏偐偑偓偕做停偟健偨偩偪偬偭偯偰偲側偵偶偷偸偹偻偽偾偿傀傁傂傅傈傉傌傍傑傒傕傖傘備傚傜傞傟傢傣傥傧储傩催傭傯傲傳傴債傷傺傻傾僂僄僅僇僉僊働僎像僐僑僔僕僖僘僙僚僝僞僣僥僦僧僨僩僬僭僮僰僱僳僵價僻僽僿儀儁儂儃億儅儆儇儈儉儋儍儐儒儔儕儘儚儞償儡優儲儷儸儺儻儼儿兀允元兄充兆兇先光兊克兌免兎児兑兒兔兕兖兗党兜兟兢入內全兩兪八公六兮兰共兲关兴兵其具典兹养兼兽冀冂冄内円冇冈冉冊冋册再冎冏冑冒冕冖冗写冚军农冝冞冠冢冤冥冧冨冩冪冫冬冯冰冲决冴况冶冷冻冼冽净凃凄准凇凈凉凊凋凌凍凎减凐凑凓凔凖凛凜凝凞凟几凡凤処凧凩凪凫凭凯凰凱凳凴凵凶凸凹出击凼函凾凿刀刁刂刃刄分切刈刊刋刍刎刑划刓刕刖列刘则刚创刜初删判別刦刧刨利刪别刬刭刮到刳刵制刷券刹刺刻刼刽剀剁剂剃剄剅剆則剉削剋剌前剎剐剑剒剔剕剖剗剛剜剝剠剡剣剤剥剧剩剪剫剬剮副剰剱割剴創剷剽剿劁劂劃劄劇劈劉劊劌劍劏劐劑劒劓劔力劝办功加务劢劣劦动助努劫劬劭励劲劳労劵効劻劼劾势勀勁勃勅勇勉勋勍勐勑勒勔動勖勗勘務勚勛勝勞募勠勢勣勤勦勧勫勭勰勱勲勳勵勷勸勹勺勻勾勿匀匁匂匄包匆匈匋匍匏匐匕化北匘匙匚匜匝匠匡匢匣匤匪匭匮匯匱匸匹区医匽匾匿區十千卄卅升午卉半卋卌卍华协卐卑卒卓協单卖南単博卜卝卞卟占卡卢卣卤卦卧卨卩卫卬卮卯印危卲即却卵卷卸卹卺卻卽卿厂厄厅历厇厈厉压厌厍厒厓厔厕厖厘厙厚厝原厠厢厣厤厥厦厨厩厭厮厰厲厳厴厶厷厹去厾县叁参參叄叅叆又叉及友双反収发叒叔叕取受变叙叚叛叟叠叡叢口古句另叨叩只叫召叭叮可台叱史右叵叶号司叹叻叼叽吁吃各吆吇合吉吊吋同名后吏吐向吒吓吔吕吖吗吚君吝吞吟吠吡吣吤吥否吧吨吩含听吭吮启吱吲吳吴吵吶吸吹吺吻吼吽吾吿呀呂呃呆呇呈呉告呋呎呏呐呑呒呓呔呕呖呗员呙呛呜呟呡呢呣呤呥呦周呪呮呯呱呲味呴呵呶呷呸呻呼命呾呿咀咁咂咄咅咆咇咈咋和咍咎咏咐咑咒咔咕咖咗咘咙咚咛咜咝咡咢咣咤咥咦咧咨咩咪咫咬咭咯咱咲咳咴咵咶咷咸咺咻咼咽咾咿哀品哂哄哆哇哈哉哋哌响哎哏哐哑哒哓哔哕哖哗哙哚哜哝哞哟員哢哥哦哧哨哩哪哫哬哭哮哱哲哺哼哽哿唀唁唃唄唅唆唇唈唉唌唎唏唐唑唔唖唛唝唞唠��唣唤唦唧唪唬唭售唯唰唱唳唵唶唷唸唹唼唾唿啀啁啃啄商啉啊啋啌啍啎問啐啑啓啕啖啗啘啜啞啟啡啣啤啥啦啧啨啪啫啬啭啮啯啰啱啲啵啶啷啸啹啻啼啾喀喁喂喃善喆喇喈喉喊喋喎喏喑喓喔喘喙喚喜喝喟喣喦喧喨喩喪喫喬喭單喰喱喲喳喵営喷喹喺喻喼喽喾嗄嗅嗆嗇嗉嗊嗌嗍嗎嗐嗑嗒嗓嗔嗖嗙嗚嗜嗝嗞嗟嗡嗢嗣嗤嗥嗦嗧嗨嗩嗪嗫嗬嗮嗯嗰嗱嗲嗳嗵嗶嗷嗹嗻嗽嗾嘀嘁嘅嘆嘈嘉嘌嘍嘎嘏嘓嘔嘖嘗嘘嘙嘚嘛嘜嘞嘟嘡嘢嘣嘤嘥嘦嘧嘩嘬嘭嘮嘯嘰嘱嘲嘴嘵嘶嘸嘹嘻嘿噀噁噂噇噉噌噍噎噏噑噓噔噗噘噙噚噛噜噝噠噢噤噥噦器噩噪噫噬噯噱噲噴噶噸噹噺噻噼嚀嚃嚄嚅嚆嚇嚈嚌嚎嚏嚐嚓嚕嚙嚝嚟嚢嚣嚤嚥嚦嚧嚨嚩嚭嚮嚯嚳嚴嚶嚷嚼嚿囀囁囂囃囈囉囊囌囍囏囑囒囓囔囗囘囚四囝回囟因囡团団囤囥囧囨囪囫园囮囯困囱囲図围囵囷囹固国图囿圀圂圃圄圆圇圈圉圊國圌圍圏圑園圓圔圖團圚圜土圣圦圧在圩圪圬圭圮圯地圳圴圹场圻圾址坂坃均坊坋坌坍坎坏坐坑坒坔坖块坚坛坜坝坞坟坠坡坢坤坦坧坨坩坪坫坭坮坯坰坳坴坵坷坺坻坼垀垂垃垄垅垆垈型垌垍垒垓垕垚垛垝垞垟垠垡垢垣垤垦垩垪垫垭垮垱垲垳垴垵垸垻埀埂埃埆埇埈埋城埏埒埓埔埕埗埘埙埚埜埝域埠埡埣埤埧埫埭埯埰埴埵埶執埸培基埻埼埽埿堀堂堃堅堆堇堈堉堊堋堌堍堎堑堔堕堙堝堞堠堡堣堤堦堧堪堯堰報場堵堺堽堿塀塁塅塊塋塌塍塏塑塒塔塗塘塙塚塜塞塡塢塤塨塩填塬塭塮塱塲塳塵塹塼塽塾塿墀墁境墅墈墉墊墌墒墓増墘墙墜增墟墠墡墦墨墩墬墭墮墲墳墺墻墼墾壁壅壆壇壊壋壌壎壐壑壓壕壘壙壚壜壝壞壟壠壢壤壩士壬壮壯声壱売壳壶壷壸壹壺壻壼壽夂处夆备変复夏夐夔夕外夙多夜够夠夢夤夥大夨天太夫夬夭央夯失夲头夷夸夹夺夻夼夾夿奀奁奂奄奇奈奉奊奋奎奏奐契奓奔奕奖套奘奚奠奢奣奤奥奧奨奩奪奫奬奭奮奲女奴奵奶奷奸她奻奼好妀妁如妃妄妅妆妇妈妊妍妎妏妒妓妖妗妘妙妝妞妠妢妣妤妥妦妨妩妪妫妬妮妯妲妳妸妹妺妻妾姁姃姆姇姈姉姊始姌姍姐姑姒姓委姗姘姙姚姜姝姞姣姤姥姦姨姪姫姬姮姵姶姸姹姻姿娀威娃娄娅娆娇娈娉娌娎娑娓娖娘娛娜娟娠娣娥娩娫娯娱娲娴娵娶娸娼娿婀婁婆婈婉婊婌婓婕婖婚婞婢婥婦婧婪婬婭婰婴婵婶婷婺婼婿媎媒媖媚媛媜媞媤媧媪媯媲媳媵媸媺媼媽媾媿嫁嫂嫄嫉嫋嫌嫐嫒嫔嫖嫗嫘嫚嫜嫡嫣嫦嫩嫪嫫嫮嫰嫱嫲嫵嫺嫻嫽嫿嬀嬁嬅嬈嬉嬋嬌嬖嬗嬙嬛嬝嬡嬢嬤嬪嬬嬭嬰嬲嬴嬶嬷嬸嬿孀孃孅孆孋孌子孑孓孔孕孖字存孙孚孛孜孝孟孢季孤孥学孨孩孪孫孬孮孰孱孳孵學孺孻孼孽孿宀宁它宄宅宇守安宋完宍宎宏宒宓宕宗官宙定宛宜宝实実宠审客宣室宥宦宧宪宫宬宮宰害宴宵家宸容宽宾宿寀寁寂寃寄寅密寇富寐寑寒寓寔寖寗寘寛寝寞察寠寡寢寤寥實��寨審寫寬寮寯寰寳寵寶寸对寺寻导対寿封専射尅将將專尉尊尋對導小少尒尓尔尕尖尘尙尚尜尝尢尤尥尧尨尪尬尭就尴尷尸尹尺尻尼尽尾尿局屁层屃屄居屆屇屈屉届屋屌屍屎屏屐屑屓展屘屙屛屜屝属屠屡屢屣層履屦屨屬屭屮屯山屲屹屺屻屾屿岀岁岂岆岈岊岌岍岏岐岑岔岖岗岘岙岚岛岜岞岠岡岢岣岦岧岩岫岬岭岱岳岵岷岸岹岽岾岿峁峂峃峄峇峈峉峋峒峓峔峘峙峚峠峡峣峤峥峦峨峩峪峭峯峰峴島峻峼峽崀崁崂崃崄崆崇崋崍崎崐崑崔崖崗崘崙崚崛崞崟崠崢崤崦崧崩崭崮崱崴崽崾嵇嵊嵋嵌嵎嵐嵒嵓嵕嵖嵗嵘嵙嵚嵛嵜嵝嵨嵩嵫嵬嵯嵴嶁嶂嶄嶅嶇嶋嶌嶍嶓嶔嶗嶙嶚嶝嶠嶢嶧嶮嶰嶲嶴嶷嶸嶺嶼嶽巂巃巅巇巉巋巌巍巒巔巖巘川州巠巡巢巣工左巧巨巩巫差巯巰己已巳巴巵巷巹巻巽巾巿币市布帅帆师希帏帐帑帔帕帖帘帙帚帛帜帝帡帢帣帤帥带帧帨帩師席帮帯帰帳帶帷常帻帼帽幀幂幃幄幅幇幌幔幕幗幘幛幞幟幡幢幣幪幫幬干平年幵并幷幸幹幺幻幼幽幾广庀庁広庄庆庇床庋序庐庑庒库应底庖店庙庚府庝庞废庠庢庤庥度座庨庫庭庯庲庵庶康庸庹庾廁廂廃廄廆廈廉廊廋廌廍廏廐廑廒廓廔廕廖廙廚廛廝廞廟廠廡廢廣廨廩廪廬廮廰廱廳廴延廷廸建廻廼廿开弁异弃弄弇弈弉弊弋弌弍式弐弑弒弓弔引弖弗弘弛弝弟张弡弢弥弦弧弨弩弪弭弯弰弱弳弴張弶強弹强弼弾彀彁彅彆彈彊彌彎彐归当彔录彖彗彘彙彛彜彝彞彠彡形彤彥彦彧彩彪彫彬彭彰影彳彴彶彷彸役彻彼彽彾彿往征徂径待徇很徉徊律後徍徐徑徒従徕得徘徙徜從徠御徧徨復循徬徭微徳徴徵德徹徼徽心忄必忆忉忌忍忏忐忑忒忖志忘忙応忝忞忠忡忤忥忧忨忪快忭忮忱忳忴念忸忻忽忾忿怀态怂怃怄怅怆怍怎怏怐怒怔怕怖怙怚怛怜思怠怡急怦性怨怩怪怫怬怮怯怱怳怵怶怹怺总怼怿恀恁恂恃恆恇恊恋恍恏恐恒恓恕恖恘恙恚恛恢恣恤恥恧恨恩恪恫恬恭恮息恰恳恵恶恸恹恺恻恼恽恾恿悃悄悅悆悉悊悋悌悍悒悔悖悚悛悝悟悠患悦悧您悩悪悫悬悭悮悯悰悱悲悳悴悵悶悸悻悼悽情惆惇惊惋惎惑惓惔惕惘惙惚惜惝惟惠惡惣惦惧惨惩惪惫惬惭惮惯惰惱惲想惴惶惹惺惻愀愁愃愆愈愉愊愍愎意愒愓愔愕愚愛愜感愠愣愤愦愧愨愫愬愭愴愷愼愾愿慄慇慈慊態慌慍慎慑慒慓慕慘慙慚慜慝慟慢慣慤慥慧慨慫慬慮慯慰慳慴慵慶慷慹慼慽慾慿憂憊憋憍憎憐憑憒憔憕憖憘憙憚憜憤憧憨憩憫憬憮憲憶憷憺憾懂懃懆懇懈應懊懋懌懍懐懑懒懔懞懟懣懦懨懲懵懶懷懸懺懼懽懾懿戀戆戇戈戉戊戋戌戍戎戏成我戒戔戕或戗战戚戛戟戡戢戥戦戧戩截戬戮戯戰戱戲戳戴戶户戸戺戻戽戾房所扁扂扃扆扇扈扉手扌才扎扏扑扒打扔払扖托扙扛扞扠扣扥扦执扨扩扪扫扬扭扮扯扰扱扳扵扶扷批扺扼扽找承技抃抄抆抇抈抉把抋抌抑抒抓抔投抖抗折抙��抛抜抝択抟抠抡抢抣护报抨抩披抬抭抮抯抱抵抶抹抺抻押抽抿拂拃拄担拆拇拈拉拊拋拌拍拎拏拐拑拒拓拔拖拗拘拙拚招拜拝拟拠拡拢拣拥拦拧拨择拪拫括拭拮拯拱拳拴拵拶拷拸拺拻拼拽拾拿持挂挃指挈按挌挍挎挑挓挕挖挙挚挛挜挝挞挟挠挡挢挣挤挥挦挧挨挪挫挭振挲挴挹挺挻挼挽挾挿捂捄捅捆捈捉捊捋捌捍捎捏捐捒捕捗捜捞损捡换捣捤捥捧捨捩捫捭据捯捱捲捶捷捺捻捼捽捿掀掁掂掃掄掇授掉掊掌掍掎掏掐排掖掘掙掛掞掟掠採探掣掤接掦控推掩措掬掭掮掯掰掲掳掴掷掸掹掺掻掼掾揀揃揄揆揉揍揎描提揑插揔揖揚換揜揞揠握揢揣揤揨揩揪揭揮揲揳援揵揶揷揸揹揺揼揽揾揿搀搁搂搅搆搉搋搌損搏搐搓搔搖搗搜搞搠搡搢搣搥搦搧搨搪搫搬搭搯搰搴搵搶携搽搾搿摀摁摂摃摄摅摆摇摈摊摎摑摒摔摘摛摜摞摟摠摡摧摩摭摯摰摳摶摸摹摺摻摽撂撃撄撅撇撈撐撑撒撓撕撖撗撘撙撚撝撞撟撢撣撤撥撩撫撬播撮撰撲撳撵撷撸撹撺撻撼撾撿擀擁擂擄擅擇擊擋操擎擐擒擔擕擖擗擘據擞擠擡擢擣擤擥擦擧擩擬擭擯擰擱擲擴擷擺擻擼擽擾攀攄攅攆攉攏攒攔攖攗攘攙攛攜攝攞攢攣攤攥攪攫攬攮支攰攲攴攵收攷攸改攻攽放政敁敃故敆效敉敌敍敎敏救敔敕敖敗敘教敛敝敞敢散敦敫敬数敲整敵敷數敻斂斃斄斅文斈斉斋斌斎斐斑斓斕斗料斛斜斝斟斡斤斥斧斩斫斬断斯新斱斲斷斸方斻於施斿旁旂旃旄旅旆旉旋旌旎族旒旖旗旛无旡既旣日旦旧旨早旬旭旮旯旰旱旲旳旴旵时旷旸旺旻旼旽旿昀昁昂昃昆昇昉昊昌昍明昏昐昑易昔昕昖昙昚昜昝昞星映昡昢昣昤春昧昨昪昫昭是昰昱昳昴昵昶昹昺昻昼显晁時晃晄晅晈晉晊晋晌晏晒晓晔晕晖晗晙晚晛晜晝晞晟晡晢晤晥晦晧晨晩晪晫晬晭普景晰晲晳晴晶晷晸智晾暁暂暄暅暇暈暉暊暌暍暎暐暑暔暕暖暗暘暝暠暢暦暧暨暪暫暭暮暱暲暴暸暹暻暼暾曁曄曆曇曈曉曌曎曏曔曕曖曙曛曜曝曠曡曦曩曬曮曰曱曲曳更曷書曹曺曼曽曾替最會朅月有朊朋服朏朐朒朓朔朕朖朗望朝朞期朥朦朧木未末本札朮术朱朲朴朵朶朸机朼朽朿杀杁杂权杄杅杆杈杉杌李杏材村杓杖杙杜杞束杠条杢杣来杦杨杩杪杬杭杮杯杰東杲杳杵杶杷杸杺杻杼松板枀极构枅枆枇枉枋枍枏析枑枒枓枕枖林枙枚果枝枞枠枡枢枣枥枧枪枫枭枯枰枱枳枴枵架枷枸枹枺枾柁柃柄柆柊柏某柑柒染柔柘柙柚柜柝柞柟柠柡柢查柩柬柭柯柰柱柲柳柴柵柷柸柺査柽柾柿栀栁栂栃栄栅标栈栉栊栋栌栎栏树栒栓栖栗栘栝栞栟栠校栢栨栩株栫栯栱栲栳栴样核根栺栻格栽栾桀桁桂桃桄桅框案桉桊桌桍桎桐桑桓桔桕桖桜桝桟桠桡桢档桤桥桦桧桨桩桫桯桱桲桴桵桶桷桸桽桿梀梁梃梅梆梉梏梑梓梔梖梗梘梛條梟梠梢梣梦梧梨梩梪梭梯械梱梲梳梵梶梹梺梼梽梾梿检棁棂棄棆棈棉棊棋棍棎棐��棓棕棖棗棘棚棟棠棡棣棧棨棩棪棫森棰棱棲棵棸棹棺棻棼椀椁椅椆椈椋植椎椏椐椒椗椙椚椛検椝椟椠椤椥椪椭椰椴椵椹椼椽椾椿楂楃楊楓楔楕楗楙楚楛楝楞楠楡楢楣楦楨楩楪楫楬業楮楯楳極楶楷楸楹楼楽榀概榄榆榇榈榉榊榍榎榑榔榕榖榘榚榛榜榥榦榧榨榫榭榮榰榴榷榻榿槁槃槅槇槊構槌槍槎槐槓槔様槙槚槛槟槠槤槧槨槩槪槫槭槮槰槱槲槳槴槺槻槼槽槿樁樂樅樉樊樋樑樒樓樗樘標樛樞樟模樢樣樨権横樫樯樱樵樸樹樺樽樾橄橇橈橋橐橓橘橙橚橛橞機橡橢橤橥橦橫橱橹橼橾橿檀檁檄檈檉檍檎檐檑檔檗檜檞檟檢檣檨檩檫檬檮檯檳檷檸檻櫁櫂櫃櫆櫈櫓櫚櫛櫝櫞櫟櫥櫧櫨櫪櫫櫬櫳櫶櫸櫺櫻欄欅欉權欌欏欒欖欝欞欟欠次欢欣欤欧欬欭欱欲欴欵欷欸欹欺欻欽款歃歆歇歉歌歎歐歓歔歘歙歛歜歟歠歡止正此步武歧歩歪歯歲歳歴歷歸歹死歼歿殁殂殃殄殅殆殇殉殊残殍殐殒殓殖殘殚殛殞殡殢殤殪殫殭殮殯殱殲殳殴段殷殺殻殼殽殿毀毁毂毅毆毋毌母毎每毐毒毓比毕毖毗毘毙毛毞毟毡毫毬毯毳毵毽毿氂氄氅氆氇氈氏氐民氓气氖気氘氙氚氛氜氟氡氢氣氤氦氧氨氩氪氫氬氮氯氰氲氳水氵氶氷永氹氽氾氿汀汁求汃汆汇汈汉汊汍汎汏汐汒汔汕汗汙汚汛汜汝汞江池污汢汤汧汨汩汪汫汭汰汲汴汶汸汹決汻汽汾沁沂沃沄沅沆沇沈沉沌沏沐沒沓沔沖沘沙沚沛沟没沢沣沤沥沦沧沨沩沪沫沬沭沮沰沱沲河沵沸油沺治沼沽沾沿泀況泂泃泄泅泆泉泊泌泐泓泔法泖泗泙泚泛泜泝泞泠泡波泣泤泥泦泧注泪泫泬泭泮泯泰泱泳泵泶泷泸泺泻泼泽泾洁洄洇洈洉洊洋洌洎洏洑洒洗洘洙洚洛洞洟洢洣津洧洨洩洪洫洭洮洱洲洳洵洶洷洸洹洺活洼洽派流浃浄浅浆浇浈浉浊测浍济浏浐浑浒浓浔浕浙浚浛浜浞浟浠浡浣浤浥浦浩浪浬浭浮浯浴海浸浹浿涂涅涇消涉涌涍涎涑涓涔涕涙涛涜涝涞涟涠涡涢涣涤润涧涨涩涪涫涮涯液涴涵涷涸涼涽涾涿淀淂淄淅淆淇淋淌淍淏淐淑淒淓淕淖淘淙淚淛淜淝淞淟淠淡淤淥淦淨淩淪淫淬淮淯淰深淲淳淵淶混淸淹淺添淼清渇済渉渊渋渌渍渎渐渑渓渔渕渖渗渙渚減渝渟渠渡渢渣渤渥渦温渫測渭港渰渲渴渷游渺渼渽渾湃湄湉湊湋湌湍湎湑湓湔湖湘湛湜湝湞湟湣湧湨湫湮湯湲湳湴湼湾湿満溁溂溃溅溆溇溈溉溌溍溎溏源準溘溚溜溝溟溠溢溥溧溪溫溯溱溲溴溵溶溷溺溻溼溽滀滁滂滃滄滅滆滇滈滉滋滌滍滎滏滑滓滔滕滗滘滙滚滝滞滟滠满滢滤滥滦滨滩滪滬滯滲滴滷滸滹滻滾滿漁漂漆漈漉漊漍漏漑漓演漕漖漚漟漠漢漣漤漥漩漪漫漬漭漯漱漲漳漵漶漷漸漹漼漾漿潁潅潆潇潋潍潏潑潔潕潖潗潘潚潛潜潞潟潠潡潢潤潦潩潭潮潯潰潲潴潵潸潺潼潽潾澀澁澂澄澆澇澈澉澋澌澍澎澐澔澗澚澜澟澠澡澣澤澥澦澧澩澪澫澭澮澯澱澳澴澶澹澽激濁濂濃濆濉濊濎濑濒濔濕濘濙��濞濟濠濡濤濩濫濬濮濯濰濱濶濺濼濾瀁瀅瀆瀉瀋瀍瀏瀑瀔瀕瀘瀚瀛瀝瀞瀟瀠瀣瀦瀧瀨瀬瀰瀲瀷瀹瀼瀾灃灄灊灌灏灐灑灕灘灝灞灣灤灧灩火灬灭灯灰灱灳灴灵灶灸灻灼災灾灿炀炁炅炆炉炊炎炒炓炔炕炖炘炙炜炝炟炡炤炫炬炭炮炯炰炳炵炶炷炸点為炼炽炾烁烂烃烇烈烊烋烏烒烔烕烘烙烚烛烜烝烟烤烦烧烨烩烫烬热烯烱烴烷烹烺烽焄焉焊焌焐焓焔焕焖焗焘焙焚焜焞無焦焮焯焰焱焴然焼焾焿煃煅煇煉煊煌煎煐煒煕煖煘煙煚煜煞煠煢煤煥煦照煨煩煬煮煲煳煴煸煺煽熄熅熈熊熏熒熔熗熘熙熜熟熠熤熥熨熬熱熲熳熵熹熺熾熿燁燃燄燈燉燊燎燏燐燒燔燕燗燙燜燝營燠燡燥燦燧燫燬燭燮燴燵燹燻燼燾燿爀爆爌爍爐爔爕爚爛爝爟爨爪爫爬爭爰爱爲爵父爷爸爹爺爻爽爾爿牀牁牂牃牆片版牉牊牌牍牎牐牒牖牘牙牛牝牟牠牡牢牣牤牥牦牧物牫牭牮牯牲牴牵牶牷特牺牻牽牾犀犁犂犄犆犇犊犋犍犒犖犛犟犠犢犧犨犬犭犯犰犴状犷犸犹犼犽犾狀狁狂狃狄狆狈狌狍狎狐狒狓狔狗狙狛狝狞狟狠狡狢狣狤狥狦狨狩独狭狮狯狰狱狲狳狴狵狶狷狸狹狺狻狼狽狾猀猁猂猃猅猇猊猋猌猍猎猐猓猔猕猖猗猘猙猚猛猜猝猞猟猠猡猢猤猥猧猩猪猫猬猭献猯猱猲猳猴猵猶猷猹猻猽猾猿獀獁獃獄獅獎獏獐獒獗獠獢獣獨獪獫獬獭獮獰獲獴獵獶獷獸獹獺獻獼獽獾獿玀玁玂玃玄玅玆率玉王玌玍玎玏玐玑玒玕玖玗玘玙玚玛玜玟玠玡玢玥玦玧玨玩玪玫玭玮环现玱玲玳玴玵玶玷玸玹玺玻玼玾珀珂珃珅珆珇珈珉珊珋珌珍珎珏珐珑珒珓珖珗珘珙珝珞珠珣珤珥珦珧珨珩珪珫班珮珰珱珲珵珷珸珹珺珼珽現珿琁琂球琄琅理琇琈琉琊琋琌琍琎琏琐琓琕琖琗琘琚琛琜琞琠琡琢琤琥琦琨琩琪琫琬琭琮琯琰琲琳琴琵琶琸琹琺琻琼琿瑀瑁瑂瑃瑄瑅瑆瑈瑊瑋瑌瑍瑎瑑瑒瑔瑕瑗瑙瑚瑛瑜瑝瑞瑟瑠瑢瑣瑤瑨瑩瑪瑬瑭瑮瑯瑰瑱瑲瑳瑴瑶瑷瑺瑻瑼瑾瑿璀璁璂璃璅璆璇璈璉璊璋璍璎璏璐璓璔璖璘璚璛璜璝璞璟璠璡璢璣璥璦璧璨璩璪璫璬璮璯環璲璵璶璸璹璺璼璽璾璿瓀瓁瓂瓆瓈瓊瓌瓏瓐瓒瓔瓖瓘瓚瓛瓜瓠瓢瓣瓤瓦瓧瓩瓮瓯瓳瓶瓷瓿甀甁甃甄甅甉甊甌甍甐甑甓甕甗甘甙甚甛甜甝甞生甠甡產産甤甥甦甧用甩甪甫甬甭甮甯田由甲申甴电甶男甸町画甽甾畀畃畄畅畇畈畉畊畋界畍畎畏畐畑畒畓畔畕畖留畚畛畜畝畠畢畤略畦畧番畫畬畮畯異畲畳畴畵當畷畸畹畿疃疆疇疉疊疋疍疎疏疐疑疔疖疗疙疚疝疞疟疠疡疣疤疥疦疨疩疪疫疬疭疮疯疱疲疳疴疵疶疸疹疻疼疽疾痁痂痃痄病症痈痉痊痌痍痑痒痔痕痘痙痚痛痜痝痞痟痠痡痢痣痤痥痦痧痨痩痪痫痰痱痲痳痴痷痸痹痺痻痼痽痾痿瘀瘁瘂瘆瘉瘋瘌瘍瘐瘓瘕瘖瘗瘘瘙瘛瘜瘞瘟瘠瘡瘢瘣瘤瘦瘧瘩瘪瘫瘮瘰瘲瘴瘵瘸瘺瘻瘾瘿療癆癇癈癌癍癎癐癑癒癔癖癗癘癙癚癜癝癞癟癠癡癢��癤癥癦癨癩癪癫癬癭癮癯癰癱癲癳癴癵癶癸癹発登發白百皁皂皃的皆皇皈皊皋皌皎皏皐皑皓皖皗皘皙皚皝皞皤皥皦皮皰皱皲皴皸皹皺皿盂盃盅盆盈盉益盋盌盍盎盏盐监盒盓盔盖盗盘盙盚盛盜盝盞盟盠盡盢監盤盥盦盧盩盪盫目盯盰盱盲盳直相盹盺盻盼盽盾盿眀省眃眄眅眇眈眉看県眍眎眏眒眔眕眖眘眙眚眛眜眝眞真眠眡眢眤眥眦眧眨眩眪眫眬眭眯眲眳眵眶眷眸眺眻眼眾着睁睆睇睍睏睐睑睗睚睛睜睝睞睟睡睢督睤睥睦睨睪睫睬睭睲睳睴睵睹睺睼睽睾睿瞀瞁瞄瞅瞇瞊瞋瞌瞎瞏瞐瞑瞒瞓瞔瞙瞚瞜瞞瞟瞠瞡瞢瞣瞥瞦瞧瞨瞩瞪瞬瞭瞯瞰瞳瞴瞵瞶瞷瞹瞺瞻瞼瞽瞾瞿矇矍矓矗矚矛矜矞矟矢矣知矧矩矪矫矬短矮矯矰石矴矶矸矹矻矽矾矿砀码砂砃砆砈砉砊砋砌砍砎砏砐砑砒砓研砕砖砗砘砚砛砜砝砞砟砠砢砣砥砦砧砩砪砫砬砭砮砯砰砱砲破砵砷砸砹砺砻砼砾础硁硂硃硄硅硆硇硈硉硊硋硌硍硎硏硐硑硒硓硔硕硖硗硚硜硝硤硨硪硫硬硭确硯硲硷硼硿碁碅碇碈碉碌碍碎碏碑碒碓碔碕碗碘碙碚碛碜碝碞碟碠碡碣碥碧碩碪碭碮碯碰碱碲碳碴碵碶碸碹確碻碼碽碾碿磀磁磂磃磄磅磆磈磉磊磋磌磎磏磐磑磔磕磖磘磙磚磜磝磞磡磣磦磧磨磬磯磲磴磷磺磻磽磾礁礄礅礎礐礑礒礓礗礘礙礚礛礜礞礟礠礡礢礤礥礦礧礨礩礪礫礬礮礱礳礴礵礶礷礹示礻礼礽社礿祀祁祂祄祅祆祇祈祉祊祋祌祍祎祏祐祑祓祔祕祖祗祘祙祚祛祜祝神祟祠祡祢祤祥祦祧票祩祪祫祭祯祳祷祸祹祺祼祽祾祿禀禁禄禅禇禊禋禍禎福禑禔禕禗禘禛禜禝禟禠禡禣禤禥禦禧禨禩禪禫禬禭禮禯禰禱禲禳禴禵禶禸禹禺离禽禾禿秀私秂秃秅秆秇秈秉秊秋种秎秏科秒秔秕秖秗秘秙秝秞租秣秤秦秧秨秩秪秫秬秭积称秶秷秸移秽秾稀稃稅稆稈稉程稌稍税稔稗稙稚稜稞稟稠稣稦稧稩稬稭種稯稰稱稲稳稴稵稶稷稸稹稺稻稼稽稿穀穂穃穄穆穉穌積穎穏穐穑穒穓穔穕穖穗穘穙穛穝穞穟穠穡穢穣穦穨穩穫穰穱穴究穷穹空穽穿突窂窃窄窈窊窋窍窑窒窓窕窖窗窘窜窝窟窠窣窥窦窨窩窪窬窭窮窯窰窱窲窶窸窺窽窾窿竀竂竃竄竅竇竈竉竊立竑竒竕竖竘站竚竛竜竝竞竟章竡竢竣竤童竦竧竨竩竪竭端竰竲竳競竹竺竽竿笃笄笅笆笈笊笋笏笑笔笕笘笙笚笛笝笞笠笢笣笤笥符笨笪笫第笭笮笰笱笲笳笴笵笷笸笹笺笻笼笾笿筁筂筅筆筇筈等筊筋筌筍筏筐筑筒筓答策筚筛筝筞筠筢筣筥筦筧筬筮筯筰筱筲筳筴筵筷筹筺筻筽签筿简箂箄箅箆箇箉箋箍箎箏箐箒箓箔箕算箙箚箜箝管箦箧箩箪箫箬箭箱箴箸節篁範篆篇篈築篊篋篌篏篑篒篓篔篕篖篗篘篙篝篟篠篡篢篣篤篥篦篨篩篪篭篮篱篳篴篶篷篸篼篽篾簀簁簃簆簇簈簋簌簍簎簏簑簒簓簔簕簗簘簙簞簟簠簡簣簦簧簪簫簱簷簸簺簽簾簿籀籁籃籄籅籇籈籊籋籌籍籏籐籓籔籖籙籛籜籟籠籣籤籥籨籩��籮籯籲米籴籵籷籸籹类籼籽籾粁粂粄粆粇粉粋粍粑粒粕粗粘粛粜粝粟粢粣粤粥粦粧粨粪粮粱粲粳粵粹粼粽精粿糀糁糃糅糈糉糊糌糍糎糐糑糒糔糕糖糗糙糛糜糝糞糟糠糢糤糦糧糨糬糯糰糱糲糴糵糶糷糸糹糺系糾紀紁紂約紅紆紇紈紉紊紋紌納紏紐紓純紕紗紘紙級紛紜紝紞素紡索紥紧紫紬紮累細紱紲紳紵紹紺紻紼紽紾紿絀終絃組絅絆絊絋経絎絏結絔絕絖絘絙絚絛絜絝絞絡絢絣絤給絧絨絩絪絫絬絮絯絰統絲絳絴絵絶絷絹絺絽絿綁綃綆綈綉綎綏綑經綘継続綛綜綝綞綟綠綡綢綣綤綦綧綪綫綬維綮綯綰綱網綳綴綵綷綸綹綺綻綼綽綾綿緃緄緅緇緈緊緋緍総緐緑緒緓緔緕緖緗緘緙線緜緝緞締緡緣緤編緩緬緯緱緲練緹緻緼緽縀縁縂縄縈縉縊縋縎縐縑縒縕縗縛縜縝縞縟縠縡縢縣縤縦縩縫縬縭縮縯縱縲縳縴縵縶縷縸縹縺縻總績繁繃繄繅繆繇繊繋繍繒織繕繖繙繚繝繞繡繢繤繥繦繧繨繩繪繫繬繭繮繯繰繳繴繵繷繹繺繻繼繽繾纀纁纂纃纅纇纈纉纊續纍纏纐纑纒纓纔纕纖纗纘纛纜纞纟纠纡红纣纤纥约级纨纩纪纫纬纭纮纯纰纱纲纳纵纶纷纸纹纺纻纽纾线绀绁绂练组绅细织终绉绊绋绌绍绎经绐绑绒结绔绕绖绗绘给绚绛络绝绞统绠绡绢绣绥绦继绨绩绪绫续绮绯绰绱绲绳维绵绶绷绸绹绺绻综绽绾绿缀缁缂缃缄缅缆缇缈缉缊缍缎缐缑缒缓缔缕编缗缘缙缚缛缜缝缟缠缡缢缣缤缥缦缧缨缩缪缫缬缭缮缯缰缱缲缳缴缵缶缸缺缼缽罂罃罄罅罇罈罌罍罐网罒罔罕罖罗罘罙罚罛罟罠罡罢罣罨罩罪罫置罰罱署罴罵罷罸罹罺罻罽罾罿羁羂羅羆羇羈羉羊羋羌羍美羑羔羕羖羗羘羙羚羛羝羞羟羡羣群羥羧羨義羪羬羭羮羯羰羱羲羶羸羹羼羽羿翀翁翃翅翆翊翋翌翎翑習翔翕翘翙翚翛翟翠翡翤翥翦翧翩翫翬翭翮翰翱翲翳翴翷翹翺翻翼翽翾翿耀老耂考耄者耆耇耉耋而耍耎耐耑耒耕耗耘耙耚耜耝耞耠耢耦耧耨耩耪耫耬耰耳耴耶耷耸耻耽耾耿聀聂聃聄聆聊聋职聐聒联聖聘聚聜聞聡聢聦聨聩聪聯聰聱聲聳聴聵聶職聼聽聾聿肂肃肄肅肆肇肈肉肋肌肏肐肓肕肖肘肚肛肜肝肞肟肠股肢肤肥肦肨肩肪肫肮肯肱育肴肵肷肸肹肺肼肽肾肿胀胁胂胃胄胆胊背胍胎胐胑胓胔胕胖胗胙胚胛胜胝胞胠胡胤胥胧胨胩胪胫胬胭胯胰胱胳胴胵胶胸胺胼能脁脂脄脅脆脇脈脉脊脋脍脏脐脑脓脔脖脘脚脛脣脤脥脦脩脫脬脯脰脱脲脳脷脸脹脺脾腀腁腃腆腇腈腉腊腋腌腎腐腑腓腔腕腘腙腚腞腟腢腣腥腦腧腨腩腪腫腭腮腰腱腲腳腴腶腷腸腹腺腻腼腾腿膀膁膂膈膊膌膍膏膐膑膒膓膗膘膙膚膛膜膝膞膟膠膢膣膥膦膨膩膳膵膺膻膽膾膿臀臂臃臆臈臉臊臌臍臏臑臓臔臕臖臘臙臚臛臜臟臠臢臣臥臦臧臨臩自臫臬臭臮臯臱至致臷臸臺臻臼臾舀舁舂舄舅舆與興舉舊舋舌舍舎舏舐舒舔舖舗舘舛舜舞舟舠舡舢舥舦舧舨舩航舫般舭��舯舰舱舲舳舴舵舶舷舸船舺舻舽舾艀艄艅艇艉艋艏艘艙艚艟艤艦艨艪艫艮良艰艱色艳艴艶艷艸艹艺艼艽艾艿节芃芄芈芉芊芋芍芎芐芑芒芓芔芗芘芙芚芛芜芝芞芟芠芡芣芤芥芦芧芨芩芪芫芬芭芮芯芰花芲芳芴芶芷芸芹芺芻芼芽芾苀苁苂苃苄苅苇苊苋苌苍苎苏苐苑苒苓苔苕苗苘苙苛苜苝苞苟苡苣苤若苦苧苩苪苫苭苯英苳苴苶苷苹苺苻苾茀茁茂范茄茅茆茈茉茌茍茎茏茑茓茔茕茖茗茘茚茛茜茣茦茧茨茩茪茫茬茭茯茱茲茳茴茵茶茸茹茺茼荀荃荅荆荇草荊荋荌荎荏荐荑荒荔荖荘荚荛荜荞荟荠荡荣荤荥荦荧荨荩荪荫药荳荷荸荺荻荼荽荿莃莅莆莇莉莊莎莒莓莕莖莗莘莙莛莜莞莟莠莢莧莨莩莪莫莱莲莳莴莶获莸莹莺莼莽莿菀菁菅菇菈菉菊菌菏菑菓菔菖菘菜菝菟菠菡菩菪菫華菰菱菲菴菷菸菹菻菼菽萁萃萄萆萇萊萋萌萍萎萑萘萙萜萝萠萢萣萤营萦萧萨萩萫萬萭萱萵萸萺萼落葅葆葉葎葑葒葖著葙葚葛葜葟葡葢董葦葩葫葬葭葯葰葱葳葴葵葶葷葸葺蒂蒆蒈蒉蒋蒌蒍蒎蒐蒓蒔蒗蒙蒜蒞蒟蒡蒤蒨蒯蒲蒴蒸蒹蒺蒻蒼蒽蒾蒿蓀蓁蓂蓄蓆蓇蓉蓊蓋蓍蓐蓑蓓蓖蓙蓝蓟蓠蓢蓣蓥蓦蓧蓨蓬蓮蓯蓰蓴蓺蓼蓽蓿蔀蔆蔌蔑蔓蔔蔕蔗蔘蔚蔞蔟蔡蔣蔥蔦蔪蔫蔬蔭蔲蔴蔵蔷蔹蔺蔻蔼蔽蔿蕀蕁蕃蕅蕆蕈蕉蕊蕎蕓蕕蕖蕗蕘蕙蕞蕡蕢蕤蕨蕩蕪蕭蕯蕰蕲蕴蕷蕸蕹蕺蕻蕾薀薄薅薇薈薊薌薏薑薔薗薙薛薜薤薦薨薩薪薫薬薮薯薰薳薴薵薷薹薺藁藉藍藎藏藐藓藔藕藜藝藠藤藥藦藨藩藪藷藹藺藻藿蘂蘃蘄蘅蘆蘇蘉蘊蘋蘑蘖蘗蘚蘢蘧蘩蘭蘸蘺蘼蘿虀虎虏虐虑虒虓虔處虖虚虛虜虞號虢虤虧虫虬虮虯虱虳虴虷虹虺虻虽虾虿蚀蚁蚂蚇蚊蚋蚌蚍蚐蚓蚕蚖蚗蚚蚜蚝蚡蚣蚤蚥蚧蚨蚩蚪蚬蚯蚰蚱蚳蚴蚵蚶蚺蚽蚾蛀蛁蛂蛄蛅蛆蛇蛈蛉蛊蛋蛌蛍蛎蛏蛐蛔蛙蛛蛞蛟蛤蛩蛭蛮蛯蛰蛱蛲蛳蛷蛸蛹蛺蛻蛾蜀蜂蜃蜆蜇蜈蜉蜊蜍蜑蜒蜓蜕蜗蜘蜚蜜蜞蜡蜢蜣蜥蜩蜮蜱蜴蜷蜺蜻蜽蜾蜿蝀蝂蝇蝈蝉蝋蝌蝎蝒蝓蝕蝗蝘蝙蝜蝟蝠蝣蝥蝦蝨蝪蝬蝮蝰蝲蝴蝶蝸蝺蝻蝼蝽蝾蝿螁螂螃螄螅螆螇螈螉螋螌融螏螐螑螒螓螔螕螖螘螙螚螛螜螝螞螟螠螡螢螣螤螨螫螭螯螳螵螺螻螽蟀蟁蟄蟆蟇蟈蟊蟋蟌蟎蟑蟒蟖蟛蟜蟠蟡蟥蟧蟪蟬蟯蟲蟳蟴蟵蟶蟷蟹蟺蟻蟼蟽蟾蟿蠀蠁蠂蠃蠄蠅蠆蠈蠉蠊蠋蠌蠍蠎蠑蠓蠔蠕蠖蠛蠟蠡蠢蠣蠭蠱蠲蠵蠶蠹蠻蠼血衄衅衆衊行衍衎衏衒術衔衕衖街衙衚衛衜衝衞衡衢衣衤补表衩衪衫衬衭衮衰衱衲衵衷衹衽衾衿袁袂袄袅袆袈袋袍袐袒袓袖袗袚袛袜袞袠袡袢袤袧袪被袭袮袯袰袱袴袷袼袿裀裁裂裃装裆裇裈裉裊裎裏裒裓裔裕裘裙補裝裟裡裢裤裥裨裱裲裳裴裵裸裹製裾裿褂褄褆複褈褊褌褐褒褓褔褕褖褘褙褚褛褞褟褡褢褥褦褧褪褫褰褲褳褴褵褶褸褹褻襀襁襃襄襌襕襖襛襞襟襠襤襦襪襬襯襲襴襶襷襻西要覂覃覅覆覇覈覊見規覓��覗覘覚覜覡覦覧覩親覬覯覲観覷覺覽覿觀见观觃规觅视觇览觉觊觋觌觍觎觏觐觑角觔觚觜觞解觥触觯觱觳觴觸觿言訂訃訇計訊訌討訏訐訑訒訓訔訕訖託記訚訛訝訟訢訣訥訧訪設許訳訴訶診註証訾詁詃詆詈詉詎詐詑詒詔評詖詗詘詛詝詞詟詠詡詢詣試詧詩詪詫詬詭詮詰話該詳詵詹詻詼詾誂誄誅誆誇誉誊誌認誑誒誓誔誕誘誚語誠誡誣誤誥誦誧誨說説読誰課誴誶誹誼誾調諂諄談諉請諌諍諏諒論諗諘諚諛諜諝諞諟諠諡諢諤諦諧諪諫諭諮諱諲諳諴諶諷諸諺諼諾謀謁謂謄謅謇謊謌謍謎謏謐謔謖謗謙謚講謜謝謠謡謢謦謨謩謫謬謳謹謾譁譂證譌譎譏譓譔譖識譙譚譛譜譞譟譥警譫譬譭譯議譲譴護譽譾讀讃讉變讋讌讎讐讒讓讕讖讙讚讜讞讠计订讣认讥讦讧讨让讪讫讬训议讯记讱讲讳讴讵讶讷许讹论讼讽设访诀证诂诃评诅识诇诈诉诊诋诌词诎诏译诒诓诔试诗诘诙诚诛诜话诞诟诠诡询诣诤该详诧诨诩诫诬语诮误诰诱诲诳说诵诶请诸诹诺读诽课诿谀谁谂调谄谅谆谇谈谊谋谌谍谎谏谐谑谒谓谔谕谖谗谘谙谚谛谜谝谞谟谠谡谢谣谤谥谦谧谨谩谪谫谬谭谮谯谰谱谲谳谴谵谶谷谺谿豁豆豇豈豉豊豌豎豐豔豕豖豚象豢豨豪豫豬豮豳豶豷豸豹豺豻貂貅貉貊貌貍貎貒貓貔貘貝貞負財貢貧貨販貪貫責貭貮貯貰貲貳貴貶買貸貺費貼貽貿賀賁賂賃賄賅資賈賊賎賑賒賓賕賖賙賚賛賜賞賠賡賢賣賤賦賧賨質賬賭賴賸賺賻購賽賾贄贅贇贈贊贋贌贍贏贓贔贖贗贛贜贝贞负贡财责贤败账货质贩贪贫贬购贮贯贰贱贲贳贴贵贶贷贸费贺贻贼贽贾贿赀赁赂赃资赅赈赉赊赋赌赍赎赏赐赑赓赔赕赖赘赚赛赜赝赞赟赠赡赢赣赤赦赧赫赭赯走赳赴赵赶起赸赻赽趁趄超越趋趐趑趔趕趙趟趣趨足趴趵趸趺趼趾趿跃跄跅跆跊跋跌跎跏跐跑跕跖跗跘跚跛距跞跟跡跢跣跤跦跨跩跪跫跬路跳践跶跷跸跹跺跻跼跽踅踈踉踊踌踎踏踐踒踖踘踝踞踟踠踡踢踦踧踨踩踪踫踬踭踮踯踰踱踴踵踶踹踼踽蹀蹁蹂蹄蹅蹇蹈蹉蹊蹋蹌蹍蹐蹑蹒蹓蹕蹙蹚蹟蹠蹡蹣蹤蹦蹧蹩蹪蹬蹭蹰蹱蹲蹴蹶蹷蹺蹻蹼蹽蹿躁躂躄躅躇躉躊躋躍躏躐躑躒躓躔躕躙躚躜躡躥躦躪身躬躭躮躯躰躱躲躴躺躾躿軀軈車軋軌軍軏軑軒軔軗軘軚軛軞軟転軨軫軸軹軺軻軼軽軾輁較輅輈載輊輋輌輒輓輔輕輗輚輛輜輝輞輟輥輦輩輪輯輳輶輸輻輾輿轀轂轄轅轆轉轍轎轒轔轘轟轡轢轣轤车轧轨轩轫转轭轮软轰轱轲轳轴轵轶轸轹轺轻轼载轾轿辂较辄辅辆辇辈辉辊辋辍辎辏辐辑辒输辔辕辖辗辘辙辚辛辜辝辞辟辣辦辧辨辩辫辭辮辯辰辱農辵辶辷边辺辻込辽达辿迁迂迄迅迆过迈迍迎运近迓返迕还这迚进远违连迟迡迢迤迥迦迨迩迪迫迭迮述迳迴迵迷迸迹迺迻迼追迾退送适逃逄逅逆逈选逊逋逌逍透逐逑递逓途逕逖逗這通逛逜逝逞速造逡逢連逦逭逮逯週進逵��逸逹逺逻逼逾遁遂遄遅遇遊運遍過遏遐遑遒道達違遖遗遘遙遛遜遝遞遟遠遡遢遣遥遨適遫遭遮遯遲遴遵遶遷選遹遺遼遽避邀邁邂邃還邅邆邇邈邉邊邋邏邐邑邓邕邗邘邙邛邝邟邠邡邢那邦邧邨邪邬邮邯邰邱邲邳邴邵邶邸邹邺邻邽邾郁郃郄郅郇郈郊郎郏郐郑郓郔郕郗郚郛郜郝郞郟郠郡郢郤郦郧部郪郫郭郯郲郳郴郵郷郸郺都郾郿鄀鄂鄃鄄鄆鄉鄌鄏鄒鄔鄕鄖鄗鄘鄙鄚鄜鄞鄠鄢鄣鄧鄩鄫鄭鄮鄯鄰鄱鄲鄴鄶鄹鄺酂酃酆酇酈酉酊酋酌配酎酐酒酓酔酕酖酗酘酙酚酝酞酡酢酣酥酩酪酬酮酯酰酱酲酴酵酶酷酸酹酺酽酾酿醂醃醅醇醉醋醌醍醐醑醒醖醘醚醛醜醞醠醢醣醤醪醫醬醭醮醯醱醴醵醸醺釀釁釃釅釆采釈釉释釋里重野量釐金釒釓釔釕釗釘釙釜針釡釣釤釦釧釩釬釭釱釲釴釵釷釹釼釿鈀鈁鈃鈇鈈鈉鈊鈍鈎鈐鈑鈔鈕鈗鈞鈣鈥鈦鈧鈪鈮鈰鈳鈴鈷鈸鈹鈺鈽鈾鈿鉀鉄鉅鉆鉈鉉鉊鉋鉍鉎鉏鉑鉕鉖鉗鉚鉛鉝鉞鉢鉣鉤鉦鉨鉬鉭鉰鉱鉲鉴鉶鉷鉸鉺鉻鉼鉾鉿銀銃銅銍銑銓銖銘銚銛銜銠銣銥銦銨銩銪銫銬銭銮銲銳銶銷銹銻銼銾鋁鋂鋃鋅鋆鋇鋉鋌鋏鋐鋒鋗鋙鋤鋥鋦鋨鋩鋪鋬鋭鋮鋯鋰鋱鋲鋳鋸鋹鋼錀錁錄錆錇錏錐錒錕錘錙錚錛錞錟錠錡錢錤錦錧錨錩錫錬錮錯録錳錶錸錻錼錾鍀鍃鍅鍆鍇鍈鍊鍋鍌鍍鍔鍘鍙鍚鍛鍜鍝鍠鍥鍪鍬鍮鍰鍱鍳鍵鍶鍺鍼鍾鎂鎇鎊鎌鎏鎓鎔鎖鎗鎘鎚鎛鎡鎢鎣鎦鎧鎩鎪鎬鎭鎮鎯鎰鎳鎵鎶鎹鎺鎿鏃鏇鏈鏊鏌鏍鏐鏑鏓鏖鏗鏘鏛鏜鏝鏞鏟鏡鏢鏤鏨鏪鏳鏵鏷鏸鏹鏻鏽鐃鐄鐇鐏鐐鐒鐓鐔鐘鐙鐚鐛鐡鐥鐧鐨鐫鐮鐲鐳鐵鐶鐸鐺鐽鐾鐿鑀鑁鑄鑅鑊鑌鑑鑒鑓鑕鑚鑛鑞鑠鑢鑣鑥鑨鑪鑫鑭鑰鑲鑴鑷鑼鑽鑾鑿钂钅钆钇针钉钊钋钌钍钎钏钐钒钓钔钕钖钗钘钙钚钛钜钝钞钟钠钡钢钣钤钥钦钧钨钩钪钫钬钭钮钯钰钱钲钳钴钵钶钷钸钹钺钻钼钽钾钿铀铁铂铃铄铅铆铈铉铊铋铌铍铎铏铐铑铒铓铕铖铙铚铛铜铝铟铠铡铢铣铤铥铧铨铩铪铫铬铭铮铯铰铱铲铳铵银铷铸铹铺铻铼铽链铿销锁锂锃锄锅锆锇锈锉锋锌锍锎锏锐锑锒锔锕锖锗锘错锚锛锜锝锞锟锡锢锣锤锥锦锨锩锫锭键锯锰锱锲锳锴锵锶锷锹锺锻锼锽锾锿镀镁镂镃镄镅镆镇镈镉镊镋镌镍镎镏镐镑镒镓镔镕镖镗镘镚镛镜镝镞镟镠镡镢镣镤镥镧镨镩镪镫镬镭镯镰镱镲镳镴镶長长門閂閃閆閇閈閉閊開閌閎閏閑閒間閔閘閙閞閟閡関閣閤閥閦閧閨閩閪閫閬閭閰閱閲閶閹閻閼閽閾閿闃闆闇闈闊闋闌闍闐闓闔闕闖闘關闞闡闢闥门闩闪闫闭问闯闰闱闲闳间闵闶闷闸闹闺闻闼闽闾闿阀阁阂阃阄阅阆阇阈阉阊阋阌阍阎阏阐阑阒阔阕阖阗阙阚阜阝阞队阡阢阨阪阬阮阯阰阱防阳阴阵阶阷阹阺阻阼阽阿陀陁陂附际陆陇陈陉陋陌降陎限陑陓陔陕陘陛陜陝陞陟陡院陣除陥陧陨险陪陬陰陲陳陴陵陶陷陸険陽隃隄隅隆隈隉隊隋隍階随隐隑隔隕隗��隙際障隞隠隣隧隨險隰隱隳隴隶隷隸隹隻隼隽难雀雁雄雅集雇雉雊雋雌雍雎雏雑雒雕雖雙雛雜雞雟雠離難雨雩雪雫雯雰雱雲雳零雷雹電雾需霁霄霅霆震霈霉霊霍霎霏霑霓霖霙霛霜霞霡霢霤霧霨霪霫霭霰露霸霹霽霾靂靄靆靈靉靑青靓靖静靚靛靜非靠靡面靥靦靧靨革靪靫靬靭靱靳靴靶靸靺靼靿鞄鞅鞆鞋鞌鞍鞏鞑鞔鞘鞞鞠鞢鞣鞥鞦鞧鞨鞫鞬鞭鞮鞯鞲鞴鞾韁韃韆韉韋韌韎韏韓韙韜韞韡韦韧韩韪韫韬韭韮音韵韶韻韾響頀頁頂頃項順頇須頊頌頎頏預頑頒頓頔頗領頚頜頞頠頡頤頦頧頫頬頭頰頲頴頵頷頸頹頻頼頽顆題額顎顏顒顓顔顕顗願顙顚顛類顢顥顧顫顬顯顰顱顳顴页顶顷顸项顺须顼顽顾顿颀颁颂颃预颅领颇颈颉颊颋颌颍颎颏颐频颓颔颖颗题颙颚颛颜额颞颟颠颡颢颤颦颧風颪颮颯颱颳颶颺颼颿飀飃飄飆飇飈风飏飑飒飓飕飗飘飙飚飛飜飞食飡飢飣飥飧飨飩飪飫飭飮飯飲飴飼飽飾餃餅餈餉養餌餍餐餑餒餓餗餘餚餛餜餞餠餡餦館餬餮餯餳餵餸餺餼餽餾餿饂饃饅饈饉饋饌饍饐饑饒饔饕饗饜饞饟饣饥饧饨饪饫饬饭饮饯饰饱饲饴饵饶饷饸饹饺饼饽饿馀馁馃馄馅馆馇馈馊馋馍馏馐馑馒馓馔馕首馗馘香馝馥馨馬馭馮馱馳馴馹馼馿駁駄駅駆駈駉駐駑駒駔駕駘駙駛駝駟駡駢駭駮駰駱駸駻駿騁騂騃騄騅騈騍騎騏騑騒験騖騗騙騤騧騨騫騭騮騰騲騶騷騸騺騻騾驀驁驂驃驄驅驊驌驍驎驒驕驗驚驛驟驢驣驤驥驩驪驫马驭驮驯驰驱驳驴驵驶驷驸驹驺驻驼驽驾驿骀骁骂骃骄骅骆骇骈骊骋验骍骎骏骐骑骒骓骕骖骗骘骙骚骛骜骝骞骟骠骡骢骣骤骥骦骧骨骯骰骱骶骷骸骺骻骼髀髁髂髄髅髆髋髌髎髏髐髑髒髓體髖高髙髡髢髣髥髦髪髭髮髯髱髴髷髹髻髽鬂鬃鬆鬈鬍鬐鬓鬘鬚鬛鬟鬢鬣鬥鬧鬨鬩鬪鬬鬮鬯鬱鬲鬷鬻鬼魁魂魃魄魅魆魇魈魉魋魍魎魏魑魔魘魚魟魢魣魨魮魯魴魷鮀鮁鮃鮆鮈鮊鮋鮍鮎鮐鮑鮒鮓鮗鮚鮜鮟鮣鮦鮨鮪鮫鮭鮮鮰鮻鯀鯁鯆鯇鯉鯊鯓鯔鯖鯛鯝鯡鯢鯤鯥鯧鯨鯪鯭鯰鯱鯵鯷鯽鯿鰁鰂鰆鰈鰌鰍鰐鰒鰓鰕鰜鰞鰟鰣鰤鰥鰨鰩鰭鰯鰱鰲鰶鰹鰺鰻鰼鰾鱀鱂鱆鱇鱈鱉鱊鱒鱓鱔鱖鱗鱘鱚鱛鱝鱟鱠鱣鱤鱥鱧鱭鱲鱵鱷鱸鱺鱼鱿鲀鲁鲂鲃鲅鲆鲇鲈鲉鲊鲋鲌鲍鲎鲑鲒鲔鲖鲗鲘鲚鲛鲜鲝鲞鲟鲠鲡鲢鲣鲤鲥鲧鲨鲩鲪鲫鲭鲮鲱鲲鲳鲵鲶鲷鲸鲹鲻鲼鲽鳀鳃鳄鳅鳆鳇鳉鳊鳌鳍鳎鳏鳐鳒鳔鳕鳖鳗鳘鳙鳚鳛鳜鳝鳞鳟鳢鳣鳥鳧鳩鳫鳯鳳鳴鳶鳽鳾鴃鴆鴇鴈鴉鴌鴎鴒鴕鴗鴛鴝鴞鴟鴣鴦鴨鴫鴬鴯鴰鴴鴷鴻鴿鵂鵄鵆鵐鵑鵒鵙鵜鵝鵞鵟鵠鵡鵩鵪鵬鵯鵰鵲鵶鵷鵺鵼鵾鶇鶉鶏鶓鶖鶘鶚鶡鶤鶥鶩鶫鶯鶲鶴鶸鶹鶺鶻鶼鶿鷀鷂鷄鷈鷉鷓鷖鷗鷙鷚鷟鷥鷦鷭鷯鷰鷲鷳鷴鷸鷹鷺鷽鷿鸇鸊鸌鸏鸕鸚鸛鸝鸞鸟鸠鸡鸢鸣鸥鸦鸨鸩鸪鸫鸬鸭鸮鸯鸰鸱鸲鸳鸴鸵鸶鸷鸸鸹鸺鸻鸽鸾鸿鹀鹁鹂鹃鹄鹅鹆鹇鹈鹉鹊鹋鹌鹍鹎鹏鹐鹑鹓鹕��鹘鹚鹛鹜鹞鹟鹠鹡鹣鹤鹥鹦鹧鹨鹩鹪鹫鹬鹭鹮鹰鹱鹲鹳鹵鹸鹹鹺鹼鹽鹾鹿麁麂麃麇麈麊麋麌麐麒麓麖麗麘麚麜麝麟麤麥麦麩麪麫麯麴麵麸麹麺麻麼麽麾麿黁黃黄黇黈黉黌黍黎黏黐黑黒黔默黙黛黜黝點黟黠黡黢黥黧黨黩黪黯黴黵黶黷黹黻黼黽黾黿鼁鼂鼇鼈鼉鼊鼋鼍鼎鼐鼒鼓鼔鼕鼙鼟鼠鼢鼩鼫鼬鼯鼱鼲鼴鼷鼹鼻鼾齁齄齉齊齋齎齏齐齑齒齔齕齘齙齜齟齡齢齣齤齦齧齪齬齮齲齶齷齿龁龃龄龅龇龈龉龊龋龌龍龎龐龑龔龕龘龙龚龛龜龟龠龢鿕鿫鿬ꇴꉂꐦ꒪꒫꒰꒱꒳꒵ꓫꓵꓽꙋꙬ꙳꜄꜆ꠥꫛ가각간갇갈갉감갑값갓갔강갖갗같갚갛개객갠갤갬갭갯갰갱갸갹갼걀걍걔걘거걱건걷걸검겁것겄겅겉겊겋게겍겐겔겜겝겟겠겡겨격겪견결겸겹겼경곁계곗곘고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괌광괘괜괭괴괵괸괼굄굉교굣구국군굳굴굵굶굼굽굿궁궂궃궈궉권궐궜궤궬귀귁귄귈귐귓규균귤귬그극근귿글긁금급긋긍긑긔기긱긴긷길김깁깃깄깅깊까깍깎깐깔깜깝깟깡깥깨깬깰깸깻깼깽꺄꺅꺼꺽꺾껀껄껌껍껏껐껑께껫껭껴껸꼇꼈꼐꼬꼭꼰꼴꼼꼽꼿꽁꽂꽃꽈꽉꽌꽝꽤꽥꽹꾀꾐꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿑꿔꿨꿩꿰꿴뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끗끙끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남납낫났낭낮낯낱낳내낵낸낼냄냅냇냈냉냌냐냑냔냘냠냣냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녓녔녕녘녜녠녤노녹논놀놈놉놋농높놓놔놘놨뇌뇨뇩뇬뇰뇽누눅눈눌눔눕눗눙눠눴뉘뉙뉜뉠뉨뉩뉴뉵뉸뉼늄늉느늑는늘늙늠능늦늪늬늴니닉닌닐님닙닛닝닢다닥닦단닫달닭닮닯닳담답닷당닻닿대댁댄댈댐댑댓댔댕댜댠더덕덖던덜덞덟덤덥덧덩덫덮데덱덴델뎀뎁뎃뎅뎌뎐뎠뎨뎬도독돈돋돌돐돔돕돗동돛돝돟돠돤돱돼됀됐되된될됨됩됬됭됴됸두둑둔둘둠둡둣둥둬뒀뒈뒤뒨뒬뒴뒷뒹듀듄듈듐드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪딫따딱딴딸땀땃땄땅땋때땐땔땜땝땟땠땡떄떠떡떤떨떫떰떳떴떵떻떼떽뗀뗄뗏뗐뗙뗴또똑똔똘똠똣똥똬뙤뚜뚝뚠뚤뚧뚫뚬뚱뛰뛴뛸뜀뜨뜩뜬뜯뜰뜷뜸뜹뜻띄띈띌띔띕띠띡띤띨띰띵라락란랄람랍랏랐랑랖랗래랙랜랠램랩랫랬랭랴략랸랼럅량러럭런럴럼럽럿렀렁렆렇레렉렌렐렘렙렛렝렠려력련렬렴렵렷렸령례롄로록론롤롬롭롯롱롸롹롼뢰뢴뢸룀룅료룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륍륑류륙륜률륨륩륫륭르륵륶른를름릅릇릉릎릐리릭린릴림립릿링맄마막만많맏말맑맘맙맛망맞맟맡맣매맥맨맬맴맵맷맸맹맺먀먁먄먕머먹먼멀멈멉멋멍멎멓메멕멘멜멤멥멧멩며멱면멸몁몃몄명몆몇몌몐모목몫몬몰몱몸몹못몽뫼묀묄묏묑묘묜묠묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭥뮈뮌뮐뮤뮨뮬뮴므믄믈��믑믜미믹민믿밀밂밈밉밋밌밍밎및밑바박밖밗반받발밝밞밟밤밥밧방밪밭배백밴밸뱀뱁뱃뱅뱉뱌뱍뱐뱟뱡버벅번벋벌범법벗벙벚벛베벡벤벧벨벰벱벳벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봤봬뵈뵌뵐뵘뵙뵤뵨부북붂분붇불붉붐붑붓붕붙붚붜붸뷁뷔뷘뷜뷰뷴뷸븀븃브븍븐블븡븥븨비빅빈빌빔빕빗빙빚빛빠빡빤빨빰빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺨뻐뻑뻔뻗뻘뻣뻤뻥뻬뻰뼈뼉뼘뼛뽀뽁뽄뽈뽐뽑뽕뾰뿅뿌뿍뿐뿔뿜뿡쁘쁜쁠쁨쁩삐삑삔삘삠삣삥사삭삯산살삵삶삼삽삿샀상샅새색샊샌샐샘샙샛샜생샤샥샨샬샴샵샷샹샾섀섄섈섐섕서석섞선섣설섬섭섯섰성섶세섹센섿셀셈셉셋셌셍셔션셜셤셧셨셩셰셱셴셸솀솁솃솅소속솎손솔솜솝솟송솥솨솬솽쇄쇠쇤쇨쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭숯숱숲숴쉈쉐쉑쉔쉘쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슌슐슘슙슛슝스슥슨슬슭슴습슷승슽싀시식신싣실싫심십싯싱싶싸싹싼쌀쌈쌉쌋쌌쌍쌓쌔쌕쌘쌤쌩쌰썅썖써썩썬썰썸썹썻썼썽쎄쎈쎌쏘쏙쏜쏟쏠쏨쏭쏱쏴쐈쐐쐬쑈쑤쑥쑨쑬쑹쒀쒸쓩쓰쓱쓴쓸씀씁씌씐씨씩씬씰씸씹씻씽씾아악안앉않알앎앓암압앗았앙앝앞앟애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얔얕얗얘얜얭어억언얹얻얼얽엄업없엇었엉엊엌엎에엑엔엗엘엠엡엣엥엩여역엮연엳열엶엷염엽엾엿였영옅옆옇예옌옐옘옙옛옝오옥온올옭옮옯옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왱외왼욀욋욍요욕욘욜욤욥욧용우욱운울움웁웃웅워웍원월웜웟웠웡웨웩웬웰웸웹웻웽윁위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽윾은읃을읊음읍읎읏응읒읓읔읕읖읗의읜읠이익인읺읻일읽잃임입잇있잉잊잌잍잎자작잔잖잘잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟐쟛쟝쟤저적전절젊젋점접젓정젖제젝젠젤젬젭젯젱져젹젼젿졀졋졌졍졔졘조족존졸좀좁좃종좆좇좋좌좍좐좡좨죄죈죌죔죗죠죤죵주죽준줄줌줍줏중줘줬줭줴쥐쥔쥘쥠쥣쥬쥰쥴즁즈즉즌즐즘즙즛증즤지직진짇질짊짐집짓징짖짙짚짜짝짠짢짤짦짧짬짭짯짰짱째짹짼쨈쨋쨌쨍쨔쨩쩌쩍쩐쩔쩜쩝쩡쩨쩬쩰쪄쪘쪠쪼쪽쫀쫄쫌쫏쫑쫒쫓쫘쫙쬐쬘쬬쭈쭉쭌쭐쭘쭙쭝쭤쮸쯉쯔쯕쯤쯧쯩찌찍찐찔찜찝찟찡찢찧차착찬찮찰찲참찹찻찼창찾찿채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳥쳬쳰초촉촌촐촘촙촛총촤촥촨촬촹최쵸춉춍추축춘출춤춥춧충춰췄췌췐취췬췰츄츈츕츠측츤츨츰츳층치칙친칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑캔캘캠캡캣캥캬캰캴컘커컥컨컫컬컴컵컷컸컹컽케켁켄켈켐켑켓켕켜켠켤켬켰켸코콕콘콜콤콥콧콩콰콱콴콸쾃쾅쾌쾡쾨쾰쿄쿈쿠쿡쿤쿨쿰쿱쿳쿵쿼쿽퀀퀄퀌퀘퀜퀠퀭퀴퀵퀸퀼큄큅큇큉큐큔큘��크큭큰클큼큽큿킁키킥킨킬킴킵킷킹타탁탄탈탉탐탑탓탔탕탘태택탠탤탬탭탯탰탱탸탼터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통퇀퇘퇴퇸퇼툇툉툐툠투툭툰툴툼툽툿퉁퉈퉜퉤튀튁튄튈튐튕튜튝튠튤튬트특튼튿틀틈틉틋틍틑틔티틱틴틸팀팁팃팅파팍팎판팔팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폈평폐포폭폰폴폼폽폿퐁퐈푀푄푈푕표푤푯푸푹푼풀풂품풉풋풍퓌퓐퓔퓨퓰퓸퓻프픈플픔픕픗픚피픽핀핃필핌핍핏핑하학한할핥함합핫항핳해핵핸핼햄햅햇했행햋햏햐햑햔햘햝햣향헀허헉헌헐험헙헛헝헤헥헨헬헴헵헷헹헿혀혁현혈혐협혓혔형혜호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱횃회획횐횔횟횡효횬횹횽후훅훈훌훑훔훕훗훙훠훡훤훨훵훼휀휑휘휙휜휠휨휩휫휭휴휼흄흉흐흑흔흗흘흙흠흡흣흥흩희흭흰히힉힌힐힘힙힛힝��金勞盧綾率不女年聯瑩零龍劉六李梨理林宅塚﨑神諸逸鶴社禍者逸fl︎️︒︙︰︱︳︴︵︶︸︹︺︽︾︿﹀﹁﹂﹃﹄﹅﹉﹊﹋﹌﹍﹎﹏﹐﹑﹒﹔﹕﹖﹗﹙﹚﹛﹜﹝﹞﹟﹠﹡﹣﹦﹪ﺍﺕﺝﺭﺯﻁﻌﻑﻕﻥﻩﻭﻮ!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~⦅⦆。「」、・ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙゚¢£¬ ̄¦¥₩�𐩅𓂃𓈒𓏸𝐹𝐼𝑁𝑓𝑖𝑛𝑨𝑫𝑬𝑯𝑵𝑷𝒀𝒾𝓃𝔸𝕖𝕚𝕟𝕠𝕥🆖🆗🆚🇫🇷🌈🌉🌊🌏🌓🌔🌕🌖🌙🌚🌟🌠🌱🌳🌷🌸🌹🌺🍀🍁🍂🍆🍉🍌🍎🍏🍓🍖🍚🍛🍣🍥🍩🍪🍫🍬🍭🍮🍰🍵🍸🍹🍼🎀🎂🎉🎊🎋🎤🎨🎭🎲🎵🎶🎸🎺🎼🏍🏐🏕🏖🏜🏠🏹🏻🐆🐈🐉🐍🐑🐒🐔🐕🐗🐙🐚🐟🐢🐥🐦🐧🐨🐩🐬🐭🐯🐰🐱🐲🐴🐶🐷🐹🐺🐻🐼🐾👀👂👄👅👇👉👊👋👌👍👏👐👑👔👗👤👦👧👳👹👻👼👿💀💁💄💉💊💋💌💍💐💓💔💕💖💗💙💚💛💜💝💞💟💠💡💢💣💤💥💦💧💨💩💪💫💬💭💮💰💻📑📖📚📝📞📯📱📷📿🔐🔚🔛🔜🔝🔞🔥🔪🔫🔳🔴🔶🔸🔹🕊🕌🕘🖐🖖🖤🗻😀😁😂😃😄😅😆😇😈😉😊😋😌😎😏😒😓😔😕😖😘😚😜😝😟😠😡😢😣😤😥😨😩😫😭😯😰😱😲😳😴😵😸😺🙁🙄🙅🙆🙇🙈🙋🙌🙏🚀🚌🚧🚨🚪🚫🚬🚹🚺🛁🟩🤎🤓🤔🤖🤗🤘🤙🤚🤜🤞🤣🤦🤧🤨🤪🤫🤬🤭🤮🤯🤲🤴🥀🥁🥂🥕🥛🥜🥞🥰🥳🥺🦀🦁🦂🦄🦇🦈🦋🦍🦐🦒🦞🦮🦷🦸🦾🧁🧜🧡🧥𠀤𠀧𠃍𠊎𠒇𠮟𠮷𡃁𡒉𡰥𡳞𣋉𣴓𤅶𤸇𥅴𥙿𧊒𧸘𨋢𨥈𨧀𨨏𨭆𨮁𪚥𪸛𪹚𫲨󠄀123version https://git-lfs.github.com/spec/v1oid sha256:3b7619caa29dc3352b939de4e9981217a9585a13a756e1101a50c90c100acd8dsize 55521280123version https://git-lfs.github.com/spec/v1oid sha256:0ba60cfe664c97629daa7e4d05c0888ebfe3edcb3feaf1ed5a14544079c6d7afsize 50176123version https://git-lfs.github.com/spec/v1oid sha256:878d541c68648969bc1b042a6e997f3a58e49b6c07c5636ad55130736977149fsize 22785303123version https://git-lfs.github.com/spec/v1oid sha256:1f90fa60aeeb1eb82e2ac1167a66bf139a8a61b8780acd351ead55268540cccbsize 79948869123version https://git-lfs.github.com/spec/v1oid sha256:1a86ace74961413cbd650002e7bb4dcec4980ffa21b2f19b86933372071d718fsize 94669756123version https://git-lfs.github.com/spec/v1oid sha256:11d30fbb3000fb2eceae318b75d9ced9229d99ae990a7f8b3ac35c8d31f2c935size 204544673123version https://git-lfs.github.com/spec/v1oid sha256:d625aa1b3e0d0408acfd6928aa84f005867aa8dbb9162480346a4e20660786ccsize 108580583123456789101112131415161718192021222324---language: jatags:- image-to-textlicense: apache-2.0datasets:- manga109s---
# Manga OCR
Optical character recognition for Japanese text, with the main focus being Japanese manga.
It uses [Vision Encoder Decoder](https://huggingface.co/docs/transformers/model_doc/vision-encoder-decoder) framework.
Manga OCR can be used as a general purpose printed Japanese OCR, but its main goal was to provide a high qualitytext recognition, robust against various scenarios specific to manga:- both vertical and horizontal text- text with furigana- text overlaid on images- wide variety of fonts and font styles- low quality images
Code is available [here](https://github.com/kha-white/manga_ocr).1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164{ "architectures": [ "VisionEncoderDecoderModel" ], "decoder": { "_name_or_path": "cl-tohoku/bert-base-japanese-char-v2", "add_cross_attention": true, "architectures": [ "BertForMaskedLM" ], "attention_probs_dropout_prob": 0.1, "bad_words_ids": null, "bos_token_id": null, "chunk_size_feed_forward": 0, "classifier_dropout": null, "cross_attention_hidden_size": null, "decoder_start_token_id": null, "diversity_penalty": 0.0, "do_sample": false, "early_stopping": false, "encoder_no_repeat_ngram_size": 0, "eos_token_id": null, "finetuning_task": null, "forced_bos_token_id": null, "forced_eos_token_id": null, "hidden_act": "gelu", "hidden_dropout_prob": 0.1, "hidden_size": 768, "id2label": { "0": "LABEL_0", "1": "LABEL_1" }, "initializer_range": 0.02, "intermediate_size": 3072, "is_decoder": true, "is_encoder_decoder": false, "label2id": { "LABEL_0": 0, "LABEL_1": 1 }, "layer_norm_eps": 1e-12, "length_penalty": 1.0, "max_length": 300, "max_position_embeddings": 512, "min_length": 0, "model_type": "bert", "no_repeat_ngram_size": 0, "num_attention_heads": 12, "num_beam_groups": 1, "num_beams": 1, "num_hidden_layers": 2, "num_return_sequences": 1, "output_attentions": false, "output_hidden_states": false, "output_scores": false, "pad_token_id": 0, "position_embedding_type": "absolute", "prefix": null, "problem_type": null, "pruned_heads": {}, "remove_invalid_values": false, "repetition_penalty": 1.0, "return_dict": true, "return_dict_in_generate": false, "sep_token_id": null, "task_specific_params": null, "temperature": 1.0, "tie_encoder_decoder": false, "tie_word_embeddings": true, "tokenizer_class": "BertJapaneseTokenizer", "top_k": 50, "top_p": 1.0, "torch_dtype": null, "torchscript": false, "transformers_version": "4.15.0", "type_vocab_size": 2, "use_bfloat16": false, "use_cache": true, "vocab_size": 6144 }, "decoder_start_token_id": 2, "early_stopping": true, "encoder": { "_name_or_path": "facebook/deit-base-patch16-224", "add_cross_attention": false, "architectures": [ "ViTForImageClassification" ], "attention_probs_dropout_prob": 0.0, "bad_words_ids": null, "bos_token_id": null, "chunk_size_feed_forward": 0, "cross_attention_hidden_size": null, "decoder_start_token_id": null, "diversity_penalty": 0.0, "do_sample": false, "early_stopping": false, "encoder_no_repeat_ngram_size": 0, "eos_token_id": null, "finetuning_task": null, "forced_bos_token_id": null, "forced_eos_token_id": null, "hidden_act": "gelu", "hidden_dropout_prob": 0.0, "hidden_size": 768, "id2label": { "0": "tench, Tinca tinca", "1": "goldfish, Carassius auratus", "2": "great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias", "3": "tiger shark, Galeocerdo cuvieri", "4": "hammerhead, hammerhead shark", "5": "electric ray, crampfish, numbfish, torpedo", "6": "stingray", "7": "cock", "8": "hen", "9": "ostrich, Struthio camelus", "10": "brambling, Fringilla montifringilla", "11": "goldfinch, Carduelis carduelis", "12": "house finch, linnet, Carpodacus mexicanus", "13": "junco, snowbird", "14": "indigo bunting, indigo finch, indigo bird, Passerina cyanea", "15": "robin, American robin, Turdus migratorius", "16": "bulbul", "17": "jay", "18": "magpie", "19": "chickadee", "20": "water ouzel, dipper", "21": "kite", "22": "bald eagle, American eagle, Haliaeetus leucocephalus", "23": "vulture", "24": "great grey owl, great gray owl, Strix nebulosa", "25": "European fire salamander, Salamandra salamandra", "26": "common newt, Triturus vulgaris", "27": "eft", "28": "spotted salamander, Ambystoma maculatum", "29": "axolotl, mud puppy, Ambystoma mexicanum", "30": "bullfrog, Rana catesbeiana", "31": "tree frog, tree-frog", "32": "tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui", "33": "loggerhead, loggerhead turtle, Caretta caretta", "34": "leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea", "35": "mud turtle", "36": "terrapin", "37": "box turtle, box tortoise", "38": "banded gecko", "39": "common iguana, iguana, Iguana iguana", "40": "American chameleon, anole, Anolis carolinensis", "41": "whiptail, whiptail lizard", "42": "agama", "43": "frilled lizard, Chlamydosaurus kingi", "44": "alligator lizard", "45": "Gila monster, Heloderma suspectum", "46": "green lizard, Lacerta viridis", "47": "African chameleon, Chamaeleo chamaeleon", "48": "Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis", "49": "African crocodile, Nile crocodile, Crocodylus niloticus", "50": "American alligator, Alligator mississipiensis", "51": "triceratops", "52": "thunder snake, worm snake, Carphophis amoenus", "53": "ringneck snake, ring-necked snake, ring snake", "54": "hognose snake, puff adder, sand viper", "55": "green snake, grass snake", "56": "king snake, kingsnake", "57": "garter snake, grass snake", "58": "water snake", "59": "vine snake", "60": "night snake, Hypsiglena torquata", "61": "boa constrictor, Constrictor constrictor", "62": "rock python, rock snake, Python sebae", "63": "Indian cobra, Naja naja", "64": "green mamba", "65": "sea snake", "66": "horned viper, cerastes, sand viper, horned asp, Cerastes cornutus", "67": "diamondback, diamondback rattlesnake, Crotalus adamanteus", "68": "sidewinder, horned rattlesnake, Crotalus cerastes", "69": "trilobite", "70": "harvestman, daddy longlegs, Phalangium opilio", "71": "scorpion", "72": "black and gold garden spider, Argiope aurantia", "73": "barn spider, Araneus cavaticus", "74": "garden spider, Aranea diademata", "75": "black widow, Latrodectus mactans", "76": "tarantula", "77": "wolf spider, hunting spider", "78": "tick", "79": "centipede", "80": "black grouse", "81": "ptarmigan", "82": "ruffed grouse, partridge, Bonasa umbellus", "83": "prairie chicken, prairie grouse, prairie fowl", "84": "peacock", "85": "quail", "86": "partridge", "87": "African grey, African gray, Psittacus erithacus", "88": "macaw", "89": "sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita", "90": "lorikeet", "91": "coucal", "92": "bee eater", "93": "hornbill", "94": "hummingbird", "95": "jacamar", "96": "toucan", "97": "drake", "98": "red-breasted merganser, Mergus serrator", "99": "goose", "100": "black swan, Cygnus atratus", "101": "tusker", "102": "echidna, spiny anteater, anteater", "103": "platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus", "104": "wallaby, brush kangaroo", "105": "koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus", "106": "wombat", "107": "jellyfish", "108": "sea anemone, anemone", "109": "brain coral", "110": "flatworm, platyhelminth", "111": "nematode, nematode worm, roundworm", "112": "conch", "113": "snail", "114": "slug", "115": "sea slug, nudibranch", "116": "chiton, coat-of-mail shell, sea cradle, polyplacophore", "117": "chambered nautilus, pearly nautilus, nautilus", "118": "Dungeness crab, Cancer magister", "119": "rock crab, Cancer irroratus", "120": "fiddler crab", "121": "king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica", "122": "American lobster, Northern lobster, Maine lobster, Homarus americanus", "123": "spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish", "124": "crayfish, crawfish, crawdad, crawdaddy", "125": "hermit crab", "126": "isopod", "127": "white stork, Ciconia ciconia", "128": "black stork, Ciconia nigra", "129": "spoonbill", "130": "flamingo", "131": "little blue heron, Egretta caerulea", "132": "American egret, great white heron, Egretta albus", "133": "bittern", "134": "crane", "135": "limpkin, Aramus pictus", "136": "European gallinule, Porphyrio porphyrio", "137": "American coot, marsh hen, mud hen, water hen, Fulica americana", "138": "bustard", "139": "ruddy turnstone, Arenaria interpres", "140": "red-backed sandpiper, dunlin, Erolia alpina", "141": "redshank, Tringa totanus", "142": "dowitcher", "143": "oystercatcher, oyster catcher", "144": "pelican", "145": "king penguin, Aptenodytes patagonica", "146": "albatross, mollymawk", "147": "grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus", "148": "killer whale, killer, orca, grampus, sea wolf, Orcinus orca", "149": "dugong, Dugong dugon", "150": "sea lion", "151": "Chihuahua", "152": "Japanese spaniel", "153": "Maltese dog, Maltese terrier, Maltese", "154": "Pekinese, Pekingese, Peke", "155": "Shih-Tzu", "156": "Blenheim spaniel", "157": "papillon", "158": "toy terrier", "159": "Rhodesian ridgeback", "160": "Afghan hound, Afghan", "161": "basset, basset hound", "162": "beagle", "163": "bloodhound, sleuthhound", "164": "bluetick", "165": "black-and-tan coonhound", "166": "Walker hound, Walker foxhound", "167": "English foxhound", "168": "redbone", "169": "borzoi, Russian wolfhound", "170": "Irish wolfhound", "171": "Italian greyhound", "172": "whippet", "173": "Ibizan hound, Ibizan Podenco", "174": "Norwegian elkhound, elkhound", "175": "otterhound, otter hound", "176": "Saluki, gazelle hound", "177": "Scottish deerhound, deerhound", "178": "Weimaraner", "179": "Staffordshire bullterrier, Staffordshire bull terrier", "180": "American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier", "181": "Bedlington terrier", "182": "Border terrier", "183": "Kerry blue terrier", "184": "Irish terrier", "185": "Norfolk terrier", "186": "Norwich terrier", "187": "Yorkshire terrier", "188": "wire-haired fox terrier", "189": "Lakeland terrier", "190": "Sealyham terrier, Sealyham", "191": "Airedale, Airedale terrier", "192": "cairn, cairn terrier", "193": "Australian terrier", "194": "Dandie Dinmont, Dandie Dinmont terrier", "195": "Boston bull, Boston terrier", "196": "miniature schnauzer", "197": "giant schnauzer", "198": "standard schnauzer", "199": "Scotch terrier, Scottish terrier, Scottie", "200": "Tibetan terrier, chrysanthemum dog", "201": "silky terrier, Sydney silky", "202": "soft-coated wheaten terrier", "203": "West Highland white terrier", "204": "Lhasa, Lhasa apso", "205": "flat-coated retriever", "206": "curly-coated retriever", "207": "golden retriever", "208": "Labrador retriever", "209": "Chesapeake Bay retriever", "210": "German short-haired pointer", "211": "vizsla, Hungarian pointer", "212": "English setter", "213": "Irish setter, red setter", "214": "Gordon setter", "215": "Brittany spaniel", "216": "clumber, clumber spaniel", "217": "English springer, English springer spaniel", "218": "Welsh springer spaniel", "219": "cocker spaniel, English cocker spaniel, cocker", "220": "Sussex spaniel", "221": "Irish water spaniel", "222": "kuvasz", "223": "schipperke", "224": "groenendael", "225": "malinois", "226": "briard", "227": "kelpie", "228": "komondor", "229": "Old English sheepdog, bobtail", "230": "Shetland sheepdog, Shetland sheep dog, Shetland", "231": "collie", "232": "Border collie", "233": "Bouvier des Flandres, Bouviers des Flandres", "234": "Rottweiler", "235": "German shepherd, German shepherd dog, German police dog, alsatian", "236": "Doberman, Doberman pinscher", "237": "miniature pinscher", "238": "Greater Swiss Mountain dog", "239": "Bernese mountain dog", "240": "Appenzeller", "241": "EntleBucher", "242": "boxer", "243": "bull mastiff", "244": "Tibetan mastiff", "245": "French bulldog", "246": "Great Dane", "247": "Saint Bernard, St Bernard", "248": "Eskimo dog, husky", "249": "malamute, malemute, Alaskan malamute", "250": "Siberian husky", "251": "dalmatian, coach dog, carriage dog", "252": "affenpinscher, monkey pinscher, monkey dog", "253": "basenji", "254": "pug, pug-dog", "255": "Leonberg", "256": "Newfoundland, Newfoundland dog", "257": "Great Pyrenees", "258": "Samoyed, Samoyede", "259": "Pomeranian", "260": "chow, chow chow", "261": "keeshond", "262": "Brabancon griffon", "263": "Pembroke, Pembroke Welsh corgi", "264": "Cardigan, Cardigan Welsh corgi", "265": "toy poodle", "266": "miniature poodle", "267": "standard poodle", "268": "Mexican hairless", "269": "timber wolf, grey wolf, gray wolf, Canis lupus", "270": "white wolf, Arctic wolf, Canis lupus tundrarum", "271": "red wolf, maned wolf, Canis rufus, Canis niger", "272": "coyote, prairie wolf, brush wolf, Canis latrans", "273": "dingo, warrigal, warragal, Canis dingo", "274": "dhole, Cuon alpinus", "275": "African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus", "276": "hyena, hyaena", "277": "red fox, Vulpes vulpes", "278": "kit fox, Vulpes macrotis", "279": "Arctic fox, white fox, Alopex lagopus", "280": "grey fox, gray fox, Urocyon cinereoargenteus", "281": "tabby, tabby cat", "282": "tiger cat", "283": "Persian cat", "284": "Siamese cat, Siamese", "285": "Egyptian cat", "286": "cougar, puma, catamount, mountain lion, painter, panther, Felis concolor", "287": "lynx, catamount", "288": "leopard, Panthera pardus", "289": "snow leopard, ounce, Panthera uncia", "290": "jaguar, panther, Panthera onca, Felis onca", "291": "lion, king of beasts, Panthera leo", "292": "tiger, Panthera tigris", "293": "cheetah, chetah, Acinonyx jubatus", "294": "brown bear, bruin, Ursus arctos", "295": "American black bear, black bear, Ursus americanus, Euarctos americanus", "296": "ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus", "297": "sloth bear, Melursus ursinus, Ursus ursinus", "298": "mongoose", "299": "meerkat, mierkat", "300": "tiger beetle", "301": "ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle", "302": "ground beetle, carabid beetle", "303": "long-horned beetle, longicorn, longicorn beetle", "304": "leaf beetle, chrysomelid", "305": "dung beetle", "306": "rhinoceros beetle", "307": "weevil", "308": "fly", "309": "bee", "310": "ant, emmet, pismire", "311": "grasshopper, hopper", "312": "cricket", "313": "walking stick, walkingstick, stick insect", "314": "cockroach, roach", "315": "mantis, mantid", "316": "cicada, cicala", "317": "leafhopper", "318": "lacewing, lacewing fly", "319": "dragonfly, darning needle, devil's darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk", "320": "damselfly", "321": "admiral", "322": "ringlet, ringlet butterfly", "323": "monarch, monarch butterfly, milkweed butterfly, Danaus plexippus", "324": "cabbage butterfly", "325": "sulphur butterfly, sulfur butterfly", "326": "lycaenid, lycaenid butterfly", "327": "starfish, sea star", "328": "sea urchin", "329": "sea cucumber, holothurian", "330": "wood rabbit, cottontail, cottontail rabbit", "331": "hare", "332": "Angora, Angora rabbit", "333": "hamster", "334": "porcupine, hedgehog", "335": "fox squirrel, eastern fox squirrel, Sciurus niger", "336": "marmot", "337": "beaver", "338": "guinea pig, Cavia cobaya", "339": "sorrel", "340": "zebra", "341": "hog, pig, grunter, squealer, Sus scrofa", "342": "wild boar, boar, Sus scrofa", "343": "warthog", "344": "hippopotamus, hippo, river horse, Hippopotamus amphibius", "345": "ox", "346": "water buffalo, water ox, Asiatic buffalo, Bubalus bubalis", "347": "bison", "348": "ram, tup", "349": "bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis", "350": "ibex, Capra ibex", "351": "hartebeest", "352": "impala, Aepyceros melampus", "353": "gazelle", "354": "Arabian camel, dromedary, Camelus dromedarius", "355": "llama", "356": "weasel", "357": "mink", "358": "polecat, fitch, foulmart, foumart, Mustela putorius", "359": "black-footed ferret, ferret, Mustela nigripes", "360": "otter", "361": "skunk, polecat, wood pussy", "362": "badger", "363": "armadillo", "364": "three-toed sloth, ai, Bradypus tridactylus", "365": "orangutan, orang, orangutang, Pongo pygmaeus", "366": "gorilla, Gorilla gorilla", "367": "chimpanzee, chimp, Pan troglodytes", "368": "gibbon, Hylobates lar", "369": "siamang, Hylobates syndactylus, Symphalangus syndactylus", "370": "guenon, guenon monkey", "371": "patas, hussar monkey, Erythrocebus patas", "372": "baboon", "373": "macaque", "374": "langur", "375": "colobus, colobus monkey", "376": "proboscis monkey, Nasalis larvatus", "377": "marmoset", "378": "capuchin, ringtail, Cebus capucinus", "379": "howler monkey, howler", "380": "titi, titi monkey", "381": "spider monkey, Ateles geoffroyi", "382": "squirrel monkey, Saimiri sciureus", "383": "Madagascar cat, ring-tailed lemur, Lemur catta", "384": "indri, indris, Indri indri, Indri brevicaudatus", "385": "Indian elephant, Elephas maximus", "386": "African elephant, Loxodonta africana", "387": "lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens", "388": "giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca", "389": "barracouta, snoek", "390": "eel", "391": "coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch", "392": "rock beauty, Holocanthus tricolor", "393": "anemone fish", "394": "sturgeon", "395": "gar, garfish, garpike, billfish, Lepisosteus osseus", "396": "lionfish", "397": "puffer, pufferfish, blowfish, globefish", "398": "abacus", "399": "abaya", "400": "academic gown, academic robe, judge's robe", "401": "accordion, piano accordion, squeeze box", "402": "acoustic guitar", "403": "aircraft carrier, carrier, flattop, attack aircraft carrier", "404": "airliner", "405": "airship, dirigible", "406": "altar", "407": "ambulance", "408": "amphibian, amphibious vehicle", "409": "analog clock", "410": "apiary, bee house", "411": "apron", "412": "ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin", "413": "assault rifle, assault gun", "414": "backpack, back pack, knapsack, packsack, rucksack, haversack", "415": "bakery, bakeshop, bakehouse", "416": "balance beam, beam", "417": "balloon", "418": "ballpoint, ballpoint pen, ballpen, Biro", "419": "Band Aid", "420": "banjo", "421": "bannister, banister, balustrade, balusters, handrail", "422": "barbell", "423": "barber chair", "424": "barbershop", "425": "barn", "426": "barometer", "427": "barrel, cask", "428": "barrow, garden cart, lawn cart, wheelbarrow", "429": "baseball", "430": "basketball", "431": "bassinet", "432": "bassoon", "433": "bathing cap, swimming cap", "434": "bath towel", "435": "bathtub, bathing tub, bath, tub", "436": "beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon", "437": "beacon, lighthouse, beacon light, pharos", "438": "beaker", "439": "bearskin, busby, shako", "440": "beer bottle", "441": "beer glass", "442": "bell cote, bell cot", "443": "bib", "444": "bicycle-built-for-two, tandem bicycle, tandem", "445": "bikini, two-piece", "446": "binder, ring-binder", "447": "binoculars, field glasses, opera glasses", "448": "birdhouse", "449": "boathouse", "450": "bobsled, bobsleigh, bob", "451": "bolo tie, bolo, bola tie, bola", "452": "bonnet, poke bonnet", "453": "bookcase", "454": "bookshop, bookstore, bookstall", "455": "bottlecap", "456": "bow", "457": "bow tie, bow-tie, bowtie", "458": "brass, memorial tablet, plaque", "459": "brassiere, bra, bandeau", "460": "breakwater, groin, groyne, mole, bulwark, seawall, jetty", "461": "breastplate, aegis, egis", "462": "broom", "463": "bucket, pail", "464": "buckle", "465": "bulletproof vest", "466": "bullet train, bullet", "467": "butcher shop, meat market", "468": "cab, hack, taxi, taxicab", "469": "caldron, cauldron", "470": "candle, taper, wax light", "471": "cannon", "472": "canoe", "473": "can opener, tin opener", "474": "cardigan", "475": "car mirror", "476": "carousel, carrousel, merry-go-round, roundabout, whirligig", "477": "carpenter's kit, tool kit", "478": "carton", "479": "car wheel", "480": "cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM", "481": "cassette", "482": "cassette player", "483": "castle", "484": "catamaran", "485": "CD player", "486": "cello, violoncello", "487": "cellular telephone, cellular phone, cellphone, cell, mobile phone", "488": "chain", "489": "chainlink fence", "490": "chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour", "491": "chain saw, chainsaw", "492": "chest", "493": "chiffonier, commode", "494": "chime, bell, gong", "495": "china cabinet, china closet", "496": "Christmas stocking", "497": "church, church building", "498": "cinema, movie theater, movie theatre, movie house, picture palace", "499": "cleaver, meat cleaver, chopper", "500": "cliff dwelling", "501": "cloak", "502": "clog, geta, patten, sabot", "503": "cocktail shaker", "504": "coffee mug", "505": "coffeepot", "506": "coil, spiral, volute, whorl, helix", "507": "combination lock", "508": "computer keyboard, keypad", "509": "confectionery, confectionary, candy store", "510": "container ship, containership, container vessel", "511": "convertible", "512": "corkscrew, bottle screw", "513": "cornet, horn, trumpet, trump", "514": "cowboy boot", "515": "cowboy hat, ten-gallon hat", "516": "cradle", "517": "crane", "518": "crash helmet", "519": "crate", "520": "crib, cot", "521": "Crock Pot", "522": "croquet ball", "523": "crutch", "524": "cuirass", "525": "dam, dike, dyke", "526": "desk", "527": "desktop computer", "528": "dial telephone, dial phone", "529": "diaper, nappy, napkin", "530": "digital clock", "531": "digital watch", "532": "dining table, board", "533": "dishrag, dishcloth", "534": "dishwasher, dish washer, dishwashing machine", "535": "disk brake, disc brake", "536": "dock, dockage, docking facility", "537": "dogsled, dog sled, dog sleigh", "538": "dome", "539": "doormat, welcome mat", "540": "drilling platform, offshore rig", "541": "drum, membranophone, tympan", "542": "drumstick", "543": "dumbbell", "544": "Dutch oven", "545": "electric fan, blower", "546": "electric guitar", "547": "electric locomotive", "548": "entertainment center", "549": "envelope", "550": "espresso maker", "551": "face powder", "552": "feather boa, boa", "553": "file, file cabinet, filing cabinet", "554": "fireboat", "555": "fire engine, fire truck", "556": "fire screen, fireguard", "557": "flagpole, flagstaff", "558": "flute, transverse flute", "559": "folding chair", "560": "football helmet", "561": "forklift", "562": "fountain", "563": "fountain pen", "564": "four-poster", "565": "freight car", "566": "French horn, horn", "567": "frying pan, frypan, skillet", "568": "fur coat", "569": "garbage truck, dustcart", "570": "gasmask, respirator, gas helmet", "571": "gas pump, gasoline pump, petrol pump, island dispenser", "572": "goblet", "573": "go-kart", "574": "golf ball", "575": "golfcart, golf cart", "576": "gondola", "577": "gong, tam-tam", "578": "gown", "579": "grand piano, grand", "580": "greenhouse, nursery, glasshouse", "581": "grille, radiator grille", "582": "grocery store, grocery, food market, market", "583": "guillotine", "584": "hair slide", "585": "hair spray", "586": "half track", "587": "hammer", "588": "hamper", "589": "hand blower, blow dryer, blow drier, hair dryer, hair drier", "590": "hand-held computer, hand-held microcomputer", "591": "handkerchief, hankie, hanky, hankey", "592": "hard disc, hard disk, fixed disk", "593": "harmonica, mouth organ, harp, mouth harp", "594": "harp", "595": "harvester, reaper", "596": "hatchet", "597": "holster", "598": "home theater, home theatre", "599": "honeycomb", "600": "hook, claw", "601": "hoopskirt, crinoline", "602": "horizontal bar, high bar", "603": "horse cart, horse-cart", "604": "hourglass", "605": "iPod", "606": "iron, smoothing iron", "607": "jack-o'-lantern", "608": "jean, blue jean, denim", "609": "jeep, landrover", "610": "jersey, T-shirt, tee shirt", "611": "jigsaw puzzle", "612": "jinrikisha, ricksha, rickshaw", "613": "joystick", "614": "kimono", "615": "knee pad", "616": "knot", "617": "lab coat, laboratory coat", "618": "ladle", "619": "lampshade, lamp shade", "620": "laptop, laptop computer", "621": "lawn mower, mower", "622": "lens cap, lens cover", "623": "letter opener, paper knife, paperknife", "624": "library", "625": "lifeboat", "626": "lighter, light, igniter, ignitor", "627": "limousine, limo", "628": "liner, ocean liner", "629": "lipstick, lip rouge", "630": "Loafer", "631": "lotion", "632": "loudspeaker, speaker, speaker unit, loudspeaker system, speaker system", "633": "loupe, jeweler's loupe", "634": "lumbermill, sawmill", "635": "magnetic compass", "636": "mailbag, postbag", "637": "mailbox, letter box", "638": "maillot", "639": "maillot, tank suit", "640": "manhole cover", "641": "maraca", "642": "marimba, xylophone", "643": "mask", "644": "matchstick", "645": "maypole", "646": "maze, labyrinth", "647": "measuring cup", "648": "medicine chest, medicine cabinet", "649": "megalith, megalithic structure", "650": "microphone, mike", "651": "microwave, microwave oven", "652": "military uniform", "653": "milk can", "654": "minibus", "655": "miniskirt, mini", "656": "minivan", "657": "missile", "658": "mitten", "659": "mixing bowl", "660": "mobile home, manufactured home", "661": "Model T", "662": "modem", "663": "monastery", "664": "monitor", "665": "moped", "666": "mortar", "667": "mortarboard", "668": "mosque", "669": "mosquito net", "670": "motor scooter, scooter", "671": "mountain bike, all-terrain bike, off-roader", "672": "mountain tent", "673": "mouse, computer mouse", "674": "mousetrap", "675": "moving van", "676": "muzzle", "677": "nail", "678": "neck brace", "679": "necklace", "680": "nipple", "681": "notebook, notebook computer", "682": "obelisk", "683": "oboe, hautboy, hautbois", "684": "ocarina, sweet potato", "685": "odometer, hodometer, mileometer, milometer", "686": "oil filter", "687": "organ, pipe organ", "688": "oscilloscope, scope, cathode-ray oscilloscope, CRO", "689": "overskirt", "690": "oxcart", "691": "oxygen mask", "692": "packet", "693": "paddle, boat paddle", "694": "paddlewheel, paddle wheel", "695": "padlock", "696": "paintbrush", "697": "pajama, pyjama, pj's, jammies", "698": "palace", "699": "panpipe, pandean pipe, syrinx", "700": "paper towel", "701": "parachute, chute", "702": "parallel bars, bars", "703": "park bench", "704": "parking meter", "705": "passenger car, coach, carriage", "706": "patio, terrace", "707": "pay-phone, pay-station", "708": "pedestal, plinth, footstall", "709": "pencil box, pencil case", "710": "pencil sharpener", "711": "perfume, essence", "712": "Petri dish", "713": "photocopier", "714": "pick, plectrum, plectron", "715": "pickelhaube", "716": "picket fence, paling", "717": "pickup, pickup truck", "718": "pier", "719": "piggy bank, penny bank", "720": "pill bottle", "721": "pillow", "722": "ping-pong ball", "723": "pinwheel", "724": "pirate, pirate ship", "725": "pitcher, ewer", "726": "plane, carpenter's plane, woodworking plane", "727": "planetarium", "728": "plastic bag", "729": "plate rack", "730": "plow, plough", "731": "plunger, plumber's helper", "732": "Polaroid camera, Polaroid Land camera", "733": "pole", "734": "police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria", "735": "poncho", "736": "pool table, billiard table, snooker table", "737": "pop bottle, soda bottle", "738": "pot, flowerpot", "739": "potter's wheel", "740": "power drill", "741": "prayer rug, prayer mat", "742": "printer", "743": "prison, prison house", "744": "projectile, missile", "745": "projector", "746": "puck, hockey puck", "747": "punching bag, punch bag, punching ball, punchball", "748": "purse", "749": "quill, quill pen", "750": "quilt, comforter, comfort, puff", "751": "racer, race car, racing car", "752": "racket, racquet", "753": "radiator", "754": "radio, wireless", "755": "radio telescope, radio reflector", "756": "rain barrel", "757": "recreational vehicle, RV, R.V.", "758": "reel", "759": "reflex camera", "760": "refrigerator, icebox", "761": "remote control, remote", "762": "restaurant, eating house, eating place, eatery", "763": "revolver, six-gun, six-shooter", "764": "rifle", "765": "rocking chair, rocker", "766": "rotisserie", "767": "rubber eraser, rubber, pencil eraser", "768": "rugby ball", "769": "rule, ruler", "770": "running shoe", "771": "safe", "772": "safety pin", "773": "saltshaker, salt shaker", "774": "sandal", "775": "sarong", "776": "sax, saxophone", "777": "scabbard", "778": "scale, weighing machine", "779": "school bus", "780": "schooner", "781": "scoreboard", "782": "screen, CRT screen", "783": "screw", "784": "screwdriver", "785": "seat belt, seatbelt", "786": "sewing machine", "787": "shield, buckler", "788": "shoe shop, shoe-shop, shoe store", "789": "shoji", "790": "shopping basket", "791": "shopping cart", "792": "shovel", "793": "shower cap", "794": "shower curtain", "795": "ski", "796": "ski mask", "797": "sleeping bag", "798": "slide rule, slipstick", "799": "sliding door", "800": "slot, one-armed bandit", "801": "snorkel", "802": "snowmobile", "803": "snowplow, snowplough", "804": "soap dispenser", "805": "soccer ball", "806": "sock", "807": "solar dish, solar collector, solar furnace", "808": "sombrero", "809": "soup bowl", "810": "space bar", "811": "space heater", "812": "space shuttle", "813": "spatula", "814": "speedboat", "815": "spider web, spider's web", "816": "spindle", "817": "sports car, sport car", "818": "spotlight, spot", "819": "stage", "820": "steam locomotive", "821": "steel arch bridge", "822": "steel drum", "823": "stethoscope", "824": "stole", "825": "stone wall", "826": "stopwatch, stop watch", "827": "stove", "828": "strainer", "829": "streetcar, tram, tramcar, trolley, trolley car", "830": "stretcher", "831": "studio couch, day bed", "832": "stupa, tope", "833": "submarine, pigboat, sub, U-boat", "834": "suit, suit of clothes", "835": "sundial", "836": "sunglass", "837": "sunglasses, dark glasses, shades", "838": "sunscreen, sunblock, sun blocker", "839": "suspension bridge", "840": "swab, swob, mop", "841": "sweatshirt", "842": "swimming trunks, bathing trunks", "843": "swing", "844": "switch, electric switch, electrical switch", "845": "syringe", "846": "table lamp", "847": "tank, army tank, armored combat vehicle, armoured combat vehicle", "848": "tape player", "849": "teapot", "850": "teddy, teddy bear", "851": "television, television system", "852": "tennis ball", "853": "thatch, thatched roof", "854": "theater curtain, theatre curtain", "855": "thimble", "856": "thresher, thrasher, threshing machine", "857": "throne", "858": "tile roof", "859": "toaster", "860": "tobacco shop, tobacconist shop, tobacconist", "861": "toilet seat", "862": "torch", "863": "totem pole", "864": "tow truck, tow car, wrecker", "865": "toyshop", "866": "tractor", "867": "trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi", "868": "tray", "869": "trench coat", "870": "tricycle, trike, velocipede", "871": "trimaran", "872": "tripod", "873": "triumphal arch", "874": "trolleybus, trolley coach, trackless trolley", "875": "trombone", "876": "tub, vat", "877": "turnstile", "878": "typewriter keyboard", "879": "umbrella", "880": "unicycle, monocycle", "881": "upright, upright piano", "882": "vacuum, vacuum cleaner", "883": "vase", "884": "vault", "885": "velvet", "886": "vending machine", "887": "vestment", "888": "viaduct", "889": "violin, fiddle", "890": "volleyball", "891": "waffle iron", "892": "wall clock", "893": "wallet, billfold, notecase, pocketbook", "894": "wardrobe, closet, press", "895": "warplane, military plane", "896": "washbasin, handbasin, washbowl, lavabo, wash-hand basin", "897": "washer, automatic washer, washing machine", "898": "water bottle", "899": "water jug", "900": "water tower", "901": "whiskey jug", "902": "whistle", "903": "wig", "904": "window screen", "905": "window shade", "906": "Windsor tie", "907": "wine bottle", "908": "wing", "909": "wok", "910": "wooden spoon", "911": "wool, woolen, woollen", "912": "worm fence, snake fence, snake-rail fence, Virginia fence", "913": "wreck", "914": "yawl", "915": "yurt", "916": "web site, website, internet site, site", "917": "comic book", "918": "crossword puzzle, crossword", "919": "street sign", "920": "traffic light, traffic signal, stoplight", "921": "book jacket, dust cover, dust jacket, dust wrapper", "922": "menu", "923": "plate", "924": "guacamole", "925": "consomme", "926": "hot pot, hotpot", "927": "trifle", "928": "ice cream, icecream", "929": "ice lolly, lolly, lollipop, popsicle", "930": "French loaf", "931": "bagel, beigel", "932": "pretzel", "933": "cheeseburger", "934": "hotdog, hot dog, red hot", "935": "mashed potato", "936": "head cabbage", "937": "broccoli", "938": "cauliflower", "939": "zucchini, courgette", "940": "spaghetti squash", "941": "acorn squash", "942": "butternut squash", "943": "cucumber, cuke", "944": "artichoke, globe artichoke", "945": "bell pepper", "946": "cardoon", "947": "mushroom", "948": "Granny Smith", "949": "strawberry", "950": "orange", "951": "lemon", "952": "fig", "953": "pineapple, ananas", "954": "banana", "955": "jackfruit, jak, jack", "956": "custard apple", "957": "pomegranate", "958": "hay", "959": "carbonara", "960": "chocolate sauce, chocolate syrup", "961": "dough", "962": "meat loaf, meatloaf", "963": "pizza, pizza pie", "964": "potpie", "965": "burrito", "966": "red wine", "967": "espresso", "968": "cup", "969": "eggnog", "970": "alp", "971": "bubble", "972": "cliff, drop, drop-off", "973": "coral reef", "974": "geyser", "975": "lakeside, lakeshore", "976": "promontory, headland, head, foreland", "977": "sandbar, sand bar", "978": "seashore, coast, seacoast, sea-coast", "979": "valley, vale", "980": "volcano", "981": "ballplayer, baseball player", "982": "groom, bridegroom", "983": "scuba diver", "984": "rapeseed", "985": "daisy", "986": "yellow lady's slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum", "987": "corn", "988": "acorn", "989": "hip, rose hip, rosehip", "990": "buckeye, horse chestnut, conker", "991": "coral fungus", "992": "agaric", "993": "gyromitra", "994": "stinkhorn, carrion fungus", "995": "earthstar", "996": "hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa", "997": "bolete", "998": "ear, spike, capitulum", "999": "toilet tissue, toilet paper, bathroom tissue" }, "image_size": 224, "initializer_range": 0.02, "intermediate_size": 3072, "is_decoder": false, "is_encoder_decoder": false, "label2id": { "Afghan hound, Afghan": 160, "African chameleon, Chamaeleo chamaeleon": 47, "African crocodile, Nile crocodile, Crocodylus niloticus": 49, "African elephant, Loxodonta africana": 386, "African grey, African gray, Psittacus erithacus": 87, "African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus": 275, "Airedale, Airedale terrier": 191, "American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier": 180, "American alligator, Alligator mississipiensis": 50, "American black bear, black bear, Ursus americanus, Euarctos americanus": 295, "American chameleon, anole, Anolis carolinensis": 40, "American coot, marsh hen, mud hen, water hen, Fulica americana": 137, "American egret, great white heron, Egretta albus": 132, "American lobster, Northern lobster, Maine lobster, Homarus americanus": 122, "Angora, Angora rabbit": 332, "Appenzeller": 240, "Arabian camel, dromedary, Camelus dromedarius": 354, "Arctic fox, white fox, Alopex lagopus": 279, "Australian terrier": 193, "Band Aid": 419, "Bedlington terrier": 181, "Bernese mountain dog": 239, "Blenheim spaniel": 156, "Border collie": 232, "Border terrier": 182, "Boston bull, Boston terrier": 195, "Bouvier des Flandres, Bouviers des Flandres": 233, "Brabancon griffon": 262, "Brittany spaniel": 215, "CD player": 485, "Cardigan, Cardigan Welsh corgi": 264, "Chesapeake Bay retriever": 209, "Chihuahua": 151, "Christmas stocking": 496, "Crock Pot": 521, "Dandie Dinmont, Dandie Dinmont terrier": 194, "Doberman, Doberman pinscher": 236, "Dungeness crab, Cancer magister": 118, "Dutch oven": 544, "Egyptian cat": 285, "English foxhound": 167, "English setter": 212, "English springer, English springer spaniel": 217, "EntleBucher": 241, "Eskimo dog, husky": 248, "European fire salamander, Salamandra salamandra": 25, "European gallinule, Porphyrio porphyrio": 136, "French bulldog": 245, "French horn, horn": 566, "French loaf": 930, "German shepherd, German shepherd dog, German police dog, alsatian": 235, "German short-haired pointer": 210, "Gila monster, Heloderma suspectum": 45, "Gordon setter": 214, "Granny Smith": 948, "Great Dane": 246, "Great Pyrenees": 257, "Greater Swiss Mountain dog": 238, "Ibizan hound, Ibizan Podenco": 173, "Indian cobra, Naja naja": 63, "Indian elephant, Elephas maximus": 385, "Irish setter, red setter": 213, "Irish terrier": 184, "Irish water spaniel": 221, "Irish wolfhound": 170, "Italian greyhound": 171, "Japanese spaniel": 152, "Kerry blue terrier": 183, "Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis": 48, "Labrador retriever": 208, "Lakeland terrier": 189, "Leonberg": 255, "Lhasa, Lhasa apso": 204, "Loafer": 630, "Madagascar cat, ring-tailed lemur, Lemur catta": 383, "Maltese dog, Maltese terrier, Maltese": 153, "Mexican hairless": 268, "Model T": 661, "Newfoundland, Newfoundland dog": 256, "Norfolk terrier": 185, "Norwegian elkhound, elkhound": 174, "Norwich terrier": 186, "Old English sheepdog, bobtail": 229, "Pekinese, Pekingese, Peke": 154, "Pembroke, Pembroke Welsh corgi": 263, "Persian cat": 283, "Petri dish": 712, "Polaroid camera, Polaroid Land camera": 732, "Pomeranian": 259, "Rhodesian ridgeback": 159, "Rottweiler": 234, "Saint Bernard, St Bernard": 247, "Saluki, gazelle hound": 176, "Samoyed, Samoyede": 258, "Scotch terrier, Scottish terrier, Scottie": 199, "Scottish deerhound, deerhound": 177, "Sealyham terrier, Sealyham": 190, "Shetland sheepdog, Shetland sheep dog, Shetland": 230, "Shih-Tzu": 155, "Siamese cat, Siamese": 284, "Siberian husky": 250, "Staffordshire bullterrier, Staffordshire bull terrier": 179, "Sussex spaniel": 220, "Tibetan mastiff": 244, "Tibetan terrier, chrysanthemum dog": 200, "Walker hound, Walker foxhound": 166, "Weimaraner": 178, "Welsh springer spaniel": 218, "West Highland white terrier": 203, "Windsor tie": 906, "Yorkshire terrier": 187, "abacus": 398, "abaya": 399, "academic gown, academic robe, judge's robe": 400, "accordion, piano accordion, squeeze box": 401, "acorn": 988, "acorn squash": 941, "acoustic guitar": 402, "admiral": 321, "affenpinscher, monkey pinscher, monkey dog": 252, "agama": 42, "agaric": 992, "aircraft carrier, carrier, flattop, attack aircraft carrier": 403, "airliner": 404, "airship, dirigible": 405, "albatross, mollymawk": 146, "alligator lizard": 44, "alp": 970, "altar": 406, "ambulance": 407, "amphibian, amphibious vehicle": 408, "analog clock": 409, "anemone fish": 393, "ant, emmet, pismire": 310, "apiary, bee house": 410, "apron": 411, "armadillo": 363, "artichoke, globe artichoke": 944, "ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin": 412, "assault rifle, assault gun": 413, "axolotl, mud puppy, Ambystoma mexicanum": 29, "baboon": 372, "backpack, back pack, knapsack, packsack, rucksack, haversack": 414, "badger": 362, "bagel, beigel": 931, "bakery, bakeshop, bakehouse": 415, "balance beam, beam": 416, "bald eagle, American eagle, Haliaeetus leucocephalus": 22, "balloon": 417, "ballplayer, baseball player": 981, "ballpoint, ballpoint pen, ballpen, Biro": 418, "banana": 954, "banded gecko": 38, "banjo": 420, "bannister, banister, balustrade, balusters, handrail": 421, "barbell": 422, "barber chair": 423, "barbershop": 424, "barn": 425, "barn spider, Araneus cavaticus": 73, "barometer": 426, "barracouta, snoek": 389, "barrel, cask": 427, "barrow, garden cart, lawn cart, wheelbarrow": 428, "baseball": 429, "basenji": 253, "basketball": 430, "basset, basset hound": 161, "bassinet": 431, "bassoon": 432, "bath towel": 434, "bathing cap, swimming cap": 433, "bathtub, bathing tub, bath, tub": 435, "beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon": 436, "beacon, lighthouse, beacon light, pharos": 437, "beagle": 162, "beaker": 438, "bearskin, busby, shako": 439, "beaver": 337, "bee": 309, "bee eater": 92, "beer bottle": 440, "beer glass": 441, "bell cote, bell cot": 442, "bell pepper": 945, "bib": 443, "bicycle-built-for-two, tandem bicycle, tandem": 444, "bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis": 349, "bikini, two-piece": 445, "binder, ring-binder": 446, "binoculars, field glasses, opera glasses": 447, "birdhouse": 448, "bison": 347, "bittern": 133, "black and gold garden spider, Argiope aurantia": 72, "black grouse": 80, "black stork, Ciconia nigra": 128, "black swan, Cygnus atratus": 100, "black widow, Latrodectus mactans": 75, "black-and-tan coonhound": 165, "black-footed ferret, ferret, Mustela nigripes": 359, "bloodhound, sleuthhound": 163, "bluetick": 164, "boa constrictor, Constrictor constrictor": 61, "boathouse": 449, "bobsled, bobsleigh, bob": 450, "bolete": 997, "bolo tie, bolo, bola tie, bola": 451, "bonnet, poke bonnet": 452, "book jacket, dust cover, dust jacket, dust wrapper": 921, "bookcase": 453, "bookshop, bookstore, bookstall": 454, "borzoi, Russian wolfhound": 169, "bottlecap": 455, "bow": 456, "bow tie, bow-tie, bowtie": 457, "box turtle, box tortoise": 37, "boxer": 242, "brain coral": 109, "brambling, Fringilla montifringilla": 10, "brass, memorial tablet, plaque": 458, "brassiere, bra, bandeau": 459, "breakwater, groin, groyne, mole, bulwark, seawall, jetty": 460, "breastplate, aegis, egis": 461, "briard": 226, "broccoli": 937, "broom": 462, "brown bear, bruin, Ursus arctos": 294, "bubble": 971, "bucket, pail": 463, "buckeye, horse chestnut, conker": 990, "buckle": 464, "bulbul": 16, "bull mastiff": 243, "bullet train, bullet": 466, "bulletproof vest": 465, "bullfrog, Rana catesbeiana": 30, "burrito": 965, "bustard": 138, "butcher shop, meat market": 467, "butternut squash": 942, "cab, hack, taxi, taxicab": 468, "cabbage butterfly": 324, "cairn, cairn terrier": 192, "caldron, cauldron": 469, "can opener, tin opener": 473, "candle, taper, wax light": 470, "cannon": 471, "canoe": 472, "capuchin, ringtail, Cebus capucinus": 378, "car mirror": 475, "car wheel": 479, "carbonara": 959, "cardigan": 474, "cardoon": 946, "carousel, carrousel, merry-go-round, roundabout, whirligig": 476, "carpenter's kit, tool kit": 477, "carton": 478, "cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM": 480, "cassette": 481, "cassette player": 482, "castle": 483, "catamaran": 484, "cauliflower": 938, "cello, violoncello": 486, "cellular telephone, cellular phone, cellphone, cell, mobile phone": 487, "centipede": 79, "chain": 488, "chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour": 490, "chain saw, chainsaw": 491, "chainlink fence": 489, "chambered nautilus, pearly nautilus, nautilus": 117, "cheeseburger": 933, "cheetah, chetah, Acinonyx jubatus": 293, "chest": 492, "chickadee": 19, "chiffonier, commode": 493, "chime, bell, gong": 494, "chimpanzee, chimp, Pan troglodytes": 367, "china cabinet, china closet": 495, "chiton, coat-of-mail shell, sea cradle, polyplacophore": 116, "chocolate sauce, chocolate syrup": 960, "chow, chow chow": 260, "church, church building": 497, "cicada, cicala": 316, "cinema, movie theater, movie theatre, movie house, picture palace": 498, "cleaver, meat cleaver, chopper": 499, "cliff dwelling": 500, "cliff, drop, drop-off": 972, "cloak": 501, "clog, geta, patten, sabot": 502, "clumber, clumber spaniel": 216, "cock": 7, "cocker spaniel, English cocker spaniel, cocker": 219, "cockroach, roach": 314, "cocktail shaker": 503, "coffee mug": 504, "coffeepot": 505, "coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch": 391, "coil, spiral, volute, whorl, helix": 506, "collie": 231, "colobus, colobus monkey": 375, "combination lock": 507, "comic book": 917, "common iguana, iguana, Iguana iguana": 39, "common newt, Triturus vulgaris": 26, "computer keyboard, keypad": 508, "conch": 112, "confectionery, confectionary, candy store": 509, "consomme": 925, "container ship, containership, container vessel": 510, "convertible": 511, "coral fungus": 991, "coral reef": 973, "corkscrew, bottle screw": 512, "corn": 987, "cornet, horn, trumpet, trump": 513, "coucal": 91, "cougar, puma, catamount, mountain lion, painter, panther, Felis concolor": 286, "cowboy boot": 514, "cowboy hat, ten-gallon hat": 515, "coyote, prairie wolf, brush wolf, Canis latrans": 272, "cradle": 516, "crane": 517, "crash helmet": 518, "crate": 519, "crayfish, crawfish, crawdad, crawdaddy": 124, "crib, cot": 520, "cricket": 312, "croquet ball": 522, "crossword puzzle, crossword": 918, "crutch": 523, "cucumber, cuke": 943, "cuirass": 524, "cup": 968, "curly-coated retriever": 206, "custard apple": 956, "daisy": 985, "dalmatian, coach dog, carriage dog": 251, "dam, dike, dyke": 525, "damselfly": 320, "desk": 526, "desktop computer": 527, "dhole, Cuon alpinus": 274, "dial telephone, dial phone": 528, "diamondback, diamondback rattlesnake, Crotalus adamanteus": 67, "diaper, nappy, napkin": 529, "digital clock": 530, "digital watch": 531, "dingo, warrigal, warragal, Canis dingo": 273, "dining table, board": 532, "dishrag, dishcloth": 533, "dishwasher, dish washer, dishwashing machine": 534, "disk brake, disc brake": 535, "dock, dockage, docking facility": 536, "dogsled, dog sled, dog sleigh": 537, "dome": 538, "doormat, welcome mat": 539, "dough": 961, "dowitcher": 142, "dragonfly, darning needle, devil's darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk": 319, "drake": 97, "drilling platform, offshore rig": 540, "drum, membranophone, tympan": 541, "drumstick": 542, "dugong, Dugong dugon": 149, "dumbbell": 543, "dung beetle": 305, "ear, spike, capitulum": 998, "earthstar": 995, "echidna, spiny anteater, anteater": 102, "eel": 390, "eft": 27, "eggnog": 969, "electric fan, blower": 545, "electric guitar": 546, "electric locomotive": 547, "electric ray, crampfish, numbfish, torpedo": 5, "entertainment center": 548, "envelope": 549, "espresso": 967, "espresso maker": 550, "face powder": 551, "feather boa, boa": 552, "fiddler crab": 120, "fig": 952, "file, file cabinet, filing cabinet": 553, "fire engine, fire truck": 555, "fire screen, fireguard": 556, "fireboat": 554, "flagpole, flagstaff": 557, "flamingo": 130, "flat-coated retriever": 205, "flatworm, platyhelminth": 110, "flute, transverse flute": 558, "fly": 308, "folding chair": 559, "football helmet": 560, "forklift": 561, "fountain": 562, "fountain pen": 563, "four-poster": 564, "fox squirrel, eastern fox squirrel, Sciurus niger": 335, "freight car": 565, "frilled lizard, Chlamydosaurus kingi": 43, "frying pan, frypan, skillet": 567, "fur coat": 568, "gar, garfish, garpike, billfish, Lepisosteus osseus": 395, "garbage truck, dustcart": 569, "garden spider, Aranea diademata": 74, "garter snake, grass snake": 57, "gas pump, gasoline pump, petrol pump, island dispenser": 571, "gasmask, respirator, gas helmet": 570, "gazelle": 353, "geyser": 974, "giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca": 388, "giant schnauzer": 197, "gibbon, Hylobates lar": 368, "go-kart": 573, "goblet": 572, "golden retriever": 207, "goldfinch, Carduelis carduelis": 11, "goldfish, Carassius auratus": 1, "golf ball": 574, "golfcart, golf cart": 575, "gondola": 576, "gong, tam-tam": 577, "goose": 99, "gorilla, Gorilla gorilla": 366, "gown": 578, "grand piano, grand": 579, "grasshopper, hopper": 311, "great grey owl, great gray owl, Strix nebulosa": 24, "great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias": 2, "green lizard, Lacerta viridis": 46, "green mamba": 64, "green snake, grass snake": 55, "greenhouse, nursery, glasshouse": 580, "grey fox, gray fox, Urocyon cinereoargenteus": 280, "grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus": 147, "grille, radiator grille": 581, "grocery store, grocery, food market, market": 582, "groenendael": 224, "groom, bridegroom": 982, "ground beetle, carabid beetle": 302, "guacamole": 924, "guenon, guenon monkey": 370, "guillotine": 583, "guinea pig, Cavia cobaya": 338, "gyromitra": 993, "hair slide": 584, "hair spray": 585, "half track": 586, "hammer": 587, "hammerhead, hammerhead shark": 4, "hamper": 588, "hamster": 333, "hand blower, blow dryer, blow drier, hair dryer, hair drier": 589, "hand-held computer, hand-held microcomputer": 590, "handkerchief, hankie, hanky, hankey": 591, "hard disc, hard disk, fixed disk": 592, "hare": 331, "harmonica, mouth organ, harp, mouth harp": 593, "harp": 594, "hartebeest": 351, "harvester, reaper": 595, "harvestman, daddy longlegs, Phalangium opilio": 70, "hatchet": 596, "hay": 958, "head cabbage": 936, "hen": 8, "hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa": 996, "hermit crab": 125, "hip, rose hip, rosehip": 989, "hippopotamus, hippo, river horse, Hippopotamus amphibius": 344, "hog, pig, grunter, squealer, Sus scrofa": 341, "hognose snake, puff adder, sand viper": 54, "holster": 597, "home theater, home theatre": 598, "honeycomb": 599, "hook, claw": 600, "hoopskirt, crinoline": 601, "horizontal bar, high bar": 602, "hornbill": 93, "horned viper, cerastes, sand viper, horned asp, Cerastes cornutus": 66, "horse cart, horse-cart": 603, "hot pot, hotpot": 926, "hotdog, hot dog, red hot": 934, "hourglass": 604, "house finch, linnet, Carpodacus mexicanus": 12, "howler monkey, howler": 379, "hummingbird": 94, "hyena, hyaena": 276, "iPod": 605, "ibex, Capra ibex": 350, "ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus": 296, "ice cream, icecream": 928, "ice lolly, lolly, lollipop, popsicle": 929, "impala, Aepyceros melampus": 352, "indigo bunting, indigo finch, indigo bird, Passerina cyanea": 14, "indri, indris, Indri indri, Indri brevicaudatus": 384, "iron, smoothing iron": 606, "isopod": 126, "jacamar": 95, "jack-o'-lantern": 607, "jackfruit, jak, jack": 955, "jaguar, panther, Panthera onca, Felis onca": 290, "jay": 17, "jean, blue jean, denim": 608, "jeep, landrover": 609, "jellyfish": 107, "jersey, T-shirt, tee shirt": 610, "jigsaw puzzle": 611, "jinrikisha, ricksha, rickshaw": 612, "joystick": 613, "junco, snowbird": 13, "keeshond": 261, "kelpie": 227, "killer whale, killer, orca, grampus, sea wolf, Orcinus orca": 148, "kimono": 614, "king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica": 121, "king penguin, Aptenodytes patagonica": 145, "king snake, kingsnake": 56, "kit fox, Vulpes macrotis": 278, "kite": 21, "knee pad": 615, "knot": 616, "koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus": 105, "komondor": 228, "kuvasz": 222, "lab coat, laboratory coat": 617, "lacewing, lacewing fly": 318, "ladle": 618, "ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle": 301, "lakeside, lakeshore": 975, "lampshade, lamp shade": 619, "langur": 374, "laptop, laptop computer": 620, "lawn mower, mower": 621, "leaf beetle, chrysomelid": 304, "leafhopper": 317, "leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea": 34, "lemon": 951, "lens cap, lens cover": 622, "leopard, Panthera pardus": 288, "lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens": 387, "letter opener, paper knife, paperknife": 623, "library": 624, "lifeboat": 625, "lighter, light, igniter, ignitor": 626, "limousine, limo": 627, "limpkin, Aramus pictus": 135, "liner, ocean liner": 628, "lion, king of beasts, Panthera leo": 291, "lionfish": 396, "lipstick, lip rouge": 629, "little blue heron, Egretta caerulea": 131, "llama": 355, "loggerhead, loggerhead turtle, Caretta caretta": 33, "long-horned beetle, longicorn, longicorn beetle": 303, "lorikeet": 90, "lotion": 631, "loudspeaker, speaker, speaker unit, loudspeaker system, speaker system": 632, "loupe, jeweler's loupe": 633, "lumbermill, sawmill": 634, "lycaenid, lycaenid butterfly": 326, "lynx, catamount": 287, "macaque": 373, "macaw": 88, "magnetic compass": 635, "magpie": 18, "mailbag, postbag": 636, "mailbox, letter box": 637, "maillot": 638, "maillot, tank suit": 639, "malamute, malemute, Alaskan malamute": 249, "malinois": 225, "manhole cover": 640, "mantis, mantid": 315, "maraca": 641, "marimba, xylophone": 642, "marmoset": 377, "marmot": 336, "mashed potato": 935, "mask": 643, "matchstick": 644, "maypole": 645, "maze, labyrinth": 646, "measuring cup": 647, "meat loaf, meatloaf": 962, "medicine chest, medicine cabinet": 648, "meerkat, mierkat": 299, "megalith, megalithic structure": 649, "menu": 922, "microphone, mike": 650, "microwave, microwave oven": 651, "military uniform": 652, "milk can": 653, "miniature pinscher": 237, "miniature poodle": 266, "miniature schnauzer": 196, "minibus": 654, "miniskirt, mini": 655, "minivan": 656, "mink": 357, "missile": 657, "mitten": 658, "mixing bowl": 659, "mobile home, manufactured home": 660, "modem": 662, "monarch, monarch butterfly, milkweed butterfly, Danaus plexippus": 323, "monastery": 663, "mongoose": 298, "monitor": 664, "moped": 665, "mortar": 666, "mortarboard": 667, "mosque": 668, "mosquito net": 669, "motor scooter, scooter": 670, "mountain bike, all-terrain bike, off-roader": 671, "mountain tent": 672, "mouse, computer mouse": 673, "mousetrap": 674, "moving van": 675, "mud turtle": 35, "mushroom": 947, "muzzle": 676, "nail": 677, "neck brace": 678, "necklace": 679, "nematode, nematode worm, roundworm": 111, "night snake, Hypsiglena torquata": 60, "nipple": 680, "notebook, notebook computer": 681, "obelisk": 682, "oboe, hautboy, hautbois": 683, "ocarina, sweet potato": 684, "odometer, hodometer, mileometer, milometer": 685, "oil filter": 686, "orange": 950, "orangutan, orang, orangutang, Pongo pygmaeus": 365, "organ, pipe organ": 687, "oscilloscope, scope, cathode-ray oscilloscope, CRO": 688, "ostrich, Struthio camelus": 9, "otter": 360, "otterhound, otter hound": 175, "overskirt": 689, "ox": 345, "oxcart": 690, "oxygen mask": 691, "oystercatcher, oyster catcher": 143, "packet": 692, "paddle, boat paddle": 693, "paddlewheel, paddle wheel": 694, "padlock": 695, "paintbrush": 696, "pajama, pyjama, pj's, jammies": 697, "palace": 698, "panpipe, pandean pipe, syrinx": 699, "paper towel": 700, "papillon": 157, "parachute, chute": 701, "parallel bars, bars": 702, "park bench": 703, "parking meter": 704, "partridge": 86, "passenger car, coach, carriage": 705, "patas, hussar monkey, Erythrocebus patas": 371, "patio, terrace": 706, "pay-phone, pay-station": 707, "peacock": 84, "pedestal, plinth, footstall": 708, "pelican": 144, "pencil box, pencil case": 709, "pencil sharpener": 710, "perfume, essence": 711, "photocopier": 713, "pick, plectrum, plectron": 714, "pickelhaube": 715, "picket fence, paling": 716, "pickup, pickup truck": 717, "pier": 718, "piggy bank, penny bank": 719, "pill bottle": 720, "pillow": 721, "pineapple, ananas": 953, "ping-pong ball": 722, "pinwheel": 723, "pirate, pirate ship": 724, "pitcher, ewer": 725, "pizza, pizza pie": 963, "plane, carpenter's plane, woodworking plane": 726, "planetarium": 727, "plastic bag": 728, "plate": 923, "plate rack": 729, "platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus": 103, "plow, plough": 730, "plunger, plumber's helper": 731, "pole": 733, "polecat, fitch, foulmart, foumart, Mustela putorius": 358, "police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria": 734, "pomegranate": 957, "poncho": 735, "pool table, billiard table, snooker table": 736, "pop bottle, soda bottle": 737, "porcupine, hedgehog": 334, "pot, flowerpot": 738, "potpie": 964, "potter's wheel": 739, "power drill": 740, "prairie chicken, prairie grouse, prairie fowl": 83, "prayer rug, prayer mat": 741, "pretzel": 932, "printer": 742, "prison, prison house": 743, "proboscis monkey, Nasalis larvatus": 376, "projectile, missile": 744, "projector": 745, "promontory, headland, head, foreland": 976, "ptarmigan": 81, "puck, hockey puck": 746, "puffer, pufferfish, blowfish, globefish": 397, "pug, pug-dog": 254, "punching bag, punch bag, punching ball, punchball": 747, "purse": 748, "quail": 85, "quill, quill pen": 749, "quilt, comforter, comfort, puff": 750, "racer, race car, racing car": 751, "racket, racquet": 752, "radiator": 753, "radio telescope, radio reflector": 755, "radio, wireless": 754, "rain barrel": 756, "ram, tup": 348, "rapeseed": 984, "recreational vehicle, RV, R.V.": 757, "red fox, Vulpes vulpes": 277, "red wine": 966, "red wolf, maned wolf, Canis rufus, Canis niger": 271, "red-backed sandpiper, dunlin, Erolia alpina": 140, "red-breasted merganser, Mergus serrator": 98, "redbone": 168, "redshank, Tringa totanus": 141, "reel": 758, "reflex camera": 759, "refrigerator, icebox": 760, "remote control, remote": 761, "restaurant, eating house, eating place, eatery": 762, "revolver, six-gun, six-shooter": 763, "rhinoceros beetle": 306, "rifle": 764, "ringlet, ringlet butterfly": 322, "ringneck snake, ring-necked snake, ring snake": 53, "robin, American robin, Turdus migratorius": 15, "rock beauty, Holocanthus tricolor": 392, "rock crab, Cancer irroratus": 119, "rock python, rock snake, Python sebae": 62, "rocking chair, rocker": 765, "rotisserie": 766, "rubber eraser, rubber, pencil eraser": 767, "ruddy turnstone, Arenaria interpres": 139, "ruffed grouse, partridge, Bonasa umbellus": 82, "rugby ball": 768, "rule, ruler": 769, "running shoe": 770, "safe": 771, "safety pin": 772, "saltshaker, salt shaker": 773, "sandal": 774, "sandbar, sand bar": 977, "sarong": 775, "sax, saxophone": 776, "scabbard": 777, "scale, weighing machine": 778, "schipperke": 223, "school bus": 779, "schooner": 780, "scoreboard": 781, "scorpion": 71, "screen, CRT screen": 782, "screw": 783, "screwdriver": 784, "scuba diver": 983, "sea anemone, anemone": 108, "sea cucumber, holothurian": 329, "sea lion": 150, "sea slug, nudibranch": 115, "sea snake": 65, "sea urchin": 328, "seashore, coast, seacoast, sea-coast": 978, "seat belt, seatbelt": 785, "sewing machine": 786, "shield, buckler": 787, "shoe shop, shoe-shop, shoe store": 788, "shoji": 789, "shopping basket": 790, "shopping cart": 791, "shovel": 792, "shower cap": 793, "shower curtain": 794, "siamang, Hylobates syndactylus, Symphalangus syndactylus": 369, "sidewinder, horned rattlesnake, Crotalus cerastes": 68, "silky terrier, Sydney silky": 201, "ski": 795, "ski mask": 796, "skunk, polecat, wood pussy": 361, "sleeping bag": 797, "slide rule, slipstick": 798, "sliding door": 799, "slot, one-armed bandit": 800, "sloth bear, Melursus ursinus, Ursus ursinus": 297, "slug": 114, "snail": 113, "snorkel": 801, "snow leopard, ounce, Panthera uncia": 289, "snowmobile": 802, "snowplow, snowplough": 803, "soap dispenser": 804, "soccer ball": 805, "sock": 806, "soft-coated wheaten terrier": 202, "solar dish, solar collector, solar furnace": 807, "sombrero": 808, "sorrel": 339, "soup bowl": 809, "space bar": 810, "space heater": 811, "space shuttle": 812, "spaghetti squash": 940, "spatula": 813, "speedboat": 814, "spider monkey, Ateles geoffroyi": 381, "spider web, spider's web": 815, "spindle": 816, "spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish": 123, "spoonbill": 129, "sports car, sport car": 817, "spotlight, spot": 818, "spotted salamander, Ambystoma maculatum": 28, "squirrel monkey, Saimiri sciureus": 382, "stage": 819, "standard poodle": 267, "standard schnauzer": 198, "starfish, sea star": 327, "steam locomotive": 820, "steel arch bridge": 821, "steel drum": 822, "stethoscope": 823, "stingray": 6, "stinkhorn, carrion fungus": 994, "stole": 824, "stone wall": 825, "stopwatch, stop watch": 826, "stove": 827, "strainer": 828, "strawberry": 949, "street sign": 919, "streetcar, tram, tramcar, trolley, trolley car": 829, "stretcher": 830, "studio couch, day bed": 831, "stupa, tope": 832, "sturgeon": 394, "submarine, pigboat, sub, U-boat": 833, "suit, suit of clothes": 834, "sulphur butterfly, sulfur butterfly": 325, "sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita": 89, "sundial": 835, "sunglass": 836, "sunglasses, dark glasses, shades": 837, "sunscreen, sunblock, sun blocker": 838, "suspension bridge": 839, "swab, swob, mop": 840, "sweatshirt": 841, "swimming trunks, bathing trunks": 842, "swing": 843, "switch, electric switch, electrical switch": 844, "syringe": 845, "tabby, tabby cat": 281, "table lamp": 846, "tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui": 32, "tank, army tank, armored combat vehicle, armoured combat vehicle": 847, "tape player": 848, "tarantula": 76, "teapot": 849, "teddy, teddy bear": 850, "television, television system": 851, "tench, Tinca tinca": 0, "tennis ball": 852, "terrapin": 36, "thatch, thatched roof": 853, "theater curtain, theatre curtain": 854, "thimble": 855, "three-toed sloth, ai, Bradypus tridactylus": 364, "thresher, thrasher, threshing machine": 856, "throne": 857, "thunder snake, worm snake, Carphophis amoenus": 52, "tick": 78, "tiger beetle": 300, "tiger cat": 282, "tiger shark, Galeocerdo cuvieri": 3, "tiger, Panthera tigris": 292, "tile roof": 858, "timber wolf, grey wolf, gray wolf, Canis lupus": 269, "titi, titi monkey": 380, "toaster": 859, "tobacco shop, tobacconist shop, tobacconist": 860, "toilet seat": 861, "toilet tissue, toilet paper, bathroom tissue": 999, "torch": 862, "totem pole": 863, "toucan": 96, "tow truck, tow car, wrecker": 864, "toy poodle": 265, "toy terrier": 158, "toyshop": 865, "tractor": 866, "traffic light, traffic signal, stoplight": 920, "trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi": 867, "tray": 868, "tree frog, tree-frog": 31, "trench coat": 869, "triceratops": 51, "tricycle, trike, velocipede": 870, "trifle": 927, "trilobite": 69, "trimaran": 871, "tripod": 872, "triumphal arch": 873, "trolleybus, trolley coach, trackless trolley": 874, "trombone": 875, "tub, vat": 876, "turnstile": 877, "tusker": 101, "typewriter keyboard": 878, "umbrella": 879, "unicycle, monocycle": 880, "upright, upright piano": 881, "vacuum, vacuum cleaner": 882, "valley, vale": 979, "vase": 883, "vault": 884, "velvet": 885, "vending machine": 886, "vestment": 887, "viaduct": 888, "vine snake": 59, "violin, fiddle": 889, "vizsla, Hungarian pointer": 211, "volcano": 980, "volleyball": 890, "vulture": 23, "waffle iron": 891, "walking stick, walkingstick, stick insect": 313, "wall clock": 892, "wallaby, brush kangaroo": 104, "wallet, billfold, notecase, pocketbook": 893, "wardrobe, closet, press": 894, "warplane, military plane": 895, "warthog": 343, "washbasin, handbasin, washbowl, lavabo, wash-hand basin": 896, "washer, automatic washer, washing machine": 897, "water bottle": 898, "water buffalo, water ox, Asiatic buffalo, Bubalus bubalis": 346, "water jug": 899, "water ouzel, dipper": 20, "water snake": 58, "water tower": 900, "weasel": 356, "web site, website, internet site, site": 916, "weevil": 307, "whippet": 172, "whiptail, whiptail lizard": 41, "whiskey jug": 901, "whistle": 902, "white stork, Ciconia ciconia": 127, "white wolf, Arctic wolf, Canis lupus tundrarum": 270, "wig": 903, "wild boar, boar, Sus scrofa": 342, "window screen": 904, "window shade": 905, "wine bottle": 907, "wing": 908, "wire-haired fox terrier": 188, "wok": 909, "wolf spider, hunting spider": 77, "wombat": 106, "wood rabbit, cottontail, cottontail rabbit": 330, "wooden spoon": 910, "wool, woolen, woollen": 911, "worm fence, snake fence, snake-rail fence, Virginia fence": 912, "wreck": 913, "yawl": 914, "yellow lady's slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum": 986, "yurt": 915, "zebra": 340, "zucchini, courgette": 939 }, "layer_norm_eps": 1e-12, "length_penalty": 1.0, "max_length": 20, "min_length": 0, "model_type": "vit", "no_repeat_ngram_size": 0, "num_attention_heads": 12, "num_beam_groups": 1, "num_beams": 1, "num_channels": 3, "num_hidden_layers": 12, "num_return_sequences": 1, "output_attentions": false, "output_hidden_states": false, "output_scores": false, "pad_token_id": null, "patch_size": 16, "prefix": null, "problem_type": null, "pruned_heads": {}, "qkv_bias": true, "remove_invalid_values": false, "repetition_penalty": 1.0, "return_dict": true, "return_dict_in_generate": false, "sep_token_id": null, "task_specific_params": null, "temperature": 1.0, "tie_encoder_decoder": false, "tie_word_embeddings": true, "tokenizer_class": null, "top_k": 50, "top_p": 1.0, "torch_dtype": null, "torchscript": false, "transformers_version": "4.15.0", "use_bfloat16": false }, "eos_token_id": 3, "is_encoder_decoder": true, "length_penalty": 2.0, "max_length": 300, "model_type": "vision-encoder-decoder", "no_repeat_ngram_size": 3, "num_beams": 4, "pad_token_id": 0, "tie_word_embeddings": false, "torch_dtype": "float32", "transformers_version": null, "vocab_size": 6144}1234567891011121314151617{ "do_normalize": true, "do_resize": true, "feature_extractor_type": "ViTFeatureExtractor", "image_mean": [ 0.5, 0.5, 0.5 ], "image_std": [ 0.5, 0.5, 0.5 ], "resample": 2, "size": 224}123version https://git-lfs.github.com/spec/v1oid sha256:c63e0bb5b3ff798c5991de18a8e0956c7ee6d1563aca6729029815eda6f5c2ebsize 4441354751{"unk_token": "[UNK]", "sep_token": "[SEP]", "pad_token": "[PAD]", "cls_token": "[CLS]", "mask_token": "[MASK]"}1{"unk_token": "[UNK]", "sep_token": "[SEP]", "pad_token": "[PAD]", "cls_token": "[CLS]", "mask_token": "[MASK]", "do_lower_case": false, "do_word_tokenize": true, "do_subword_tokenize": true, "word_tokenizer_type": "mecab", "subword_tokenizer_type": "character", "never_split": null, "mecab_kwargs": {"mecab_dic": "unidic_lite"}, "special_tokens_map_file": null, "tokenizer_file": null, "name_or_path": "cl-tohoku/bert-base-japanese-char-v2", "tokenizer_class": "BertJapaneseTokenizer"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144[PAD][UNK][CLS][SEP][MASK]<unused0><unused1><unused2><unused3><unused4><unused5><unused6><unused7><unused8><unused9>!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~¡¢£¥§©«¬®°±·»¿ÀÁÄÅÆÇÉÍÎÓÖרÚÜÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþĀāăąĆćČčĐđēĕėęěĝğħĩĪīİıŁłńňŋōŏőœřŚśŞşŠšţťũūŭůźŻżŽžơưǁǎǐǒǔǰșȝɐɑɒɔɕəɛɟɡɣɦɨɪɫɯɲɴɸɹɾʁʃʊʌʎʏʑʒʔʕʧʻʼʿˀˈˌː̝̥̩̯́̃̈̓͡ΆΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΦΧΨΩάέήίαβγδεζηθικλμνξοπρςστυφχψωόύώЁІЈАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяёіїјњћқүөԱագեիյնոտրւְִֵֶַָֹּׁאבגדהוזחטיכלםמןנסעפצקרשת،ءآأإئابةتثجحخدرزسشصضطظعغـفقكلمنهوىيَِْپچکگھہیەंअकखगचजटडणतदधनपबभमयरलवशसह़ािीुूेो्মরাু্அகசடதனபமயரறலழவாிுை்రರುി്කතදනපමයරවස්ාිුกขคงจชญณดตถทธนบปผพฟภมยรลวศสหอะัาิีืุูเแโไ็่้์ํດນປວສະາເ་གངདནབམརལསིོླကငတနပရာိုေး်ြაბგდევთილმნორსტუქყწ비አកងតនពរា្ᠠᠡᠢᠣᠤᠨᠩᠪᠭᠮᠯᠷᡝᡞᡠᡥḍḤḥḫṃṅṇṛṣṭạảấầếềệịốồộờụἀἈἐἙἰὁὰὶῖ‐–—―‖‘’“”„†‡•‧‰′※⁄←↑→↓↦⇒⇔∀∂∃∈∑−∖∗√∞∠∧∨∩∪∽≈≒≠≡≤≥≦≧≪≫⊂⊆⊗⊿⋅⋯─━│┃┏┓┗┣┳█■□▲△▼▽◆◇○◎●◯★☆☉♀♂♠♡♣♥♦♪♭♯✩⟨⟩ⴰ、。〃々〆〇〈〉《》「」『』【】〒〔〕〜〝〟〰ぁあぃいぅうぇえぉおかがきぎくぐけげこごさざしじすずせぜそぞただちぢっつづてでとどなにぬねのはばぱひびぴふぶぷへべぺほぼぽまみむめもゃやゅゆょよらりるれろゎわゐゑをん゙゚ゝゞ゠ァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶ・ー㆑ㇱㇷㇼ一丁七万丈三上下不与丑且丕世丘丙东丞両並个中串丸丹主丼乂乃久么之乍乎乏乐乖乗乘乙九乞也乭乱乳乾亀了予争事二于云互五井亘亙些亜亞亡亢交亥亦亨享京亭亮人什仁仄仇今介仍仏仔仕他仗付仙代令以仮仰仲件价任份企伊伍伎伏伐休会伝伯伴伶伸伺似伽佃但佇位低住佐佑体何佗余佚佛作佞佟你佩佬佰佳併佼使侂侃來侈例侍侏侑侗侘供依侠価侭侮侯侵侶便俀係促俄俊俎俑俗俘俚保俟俠信俣修俯俱俳俵俶俸俺倅倉個倍們倒倖候倚借倡倣値倦倧倩倪倫倭倶倹偃假偈偉偏偕做停健偲側偵偶偽傀傅傍傑傕傘備催傭傲傳債傷傾僅僉僊働像僑僕僖僚僥僧僭僻儀儁儂億儋儒儔儘儚償儡優儲儺儼兀允元兄充兆兇先光克兌免兎児兒兗党兜入內全兩兪八公六兮共兴兵其具典兼冀内円冉冊册再冏冑冒冕冗写军冠冤冥冨冪冬冰冲决冴冶冷冼凄准凉凋凌凍凛凜凝几凡処凧凪凰凱凶凸凹出函刀刁刃刄分切刈刊刎刑列初判別利刪到刳制刷券刹刺刻剃剄則削剋剌前剖剛剝剣剤剥剪副剰剱割創剽劃劇劈劉劍劔力功加劣动助努劫劭励労効劾勁勃勅勇勉勒動勗勘務勛勝募勢勣勤勧勲勳勺勾勿匁匂包匈匍匐匕化北匙匝匠匡匣匪匯匱匹区医匿區十千升午卉半卍华卑卒卓協南単博卜卞占卡卦卬卯印危即却卵卷卸卿厄厘厙厚厝原厠厥厦厨厩厭厲厳去参參又叉及友双反収叔取受叙叛叟叡叢口古句叩只叫召叭可台叱史右叶号司吃各合吉吊吋同名后吏吐向吒君吝吟吠否含吳吶吸吹吻吼吽吾呀呂呆呈呉告呑呟周呪呰味呵呻呼命咀咄咆咋和咎咒咢咤咥咨咩咫咬咲咳咸咽哀品哈哉員哥哨哩哭哮哲哺唄唆唇唐唖唯唱唸唹唾啄商問啓啖啜啤啦啼喀善喆喇喉喊喋喘喙喚喜喝喧喩喪喫喬喰営嗄嗅嗇嗚嗜嗟嗣嗽嘆嘉嘎嘔嘗嘘嘩嘯嘱嘲嘴噂噌噛器噲噴噺嚆嚇嚢嚥嚮嚴嚶嚼囁囂囃囎囚四回因团団园囮困囲図围固国囿圀圃圉國圏園圓圖團土圧在圩圭地圳圻址坂均坊坎坏坐坑坡坤坦坪坳垂型垓垠垢垣埃埈埋城埒埔埕埜域埠埣埴埵執培基埼堀堂堅堆堕堡堤堪堯堰報場堵堺塀塁塊塑塔塗塘塙塚塞塢塩填塵塹塾境墅墉墓増墜墟墨墩墳墺墻墾壁壇壊壌壕壙壜壢壩士壬壮声壱売壷壹壺壽変夏夔夕外夙多夛夜夢大天太夫夭央失夷夾奄奇奈奉奎奏奐契奔奕套奘奚奠奢奥奧奨奪奭奮女奴奸好如妃妄妊妍妓妖妙妤妥妨妬妲妹妻妾姆姉始姐姑姓委姚姜姥姦姨姪姫姶姻姿威娃娑娘娜娟娠娥娩娯娶娼婁婆婉婕婚婢婦婷婿媒媚媛媯媽嫁嫉嫌嫡嫦嫩嬉嬌嬛嬢嬪嬬嬰嬲嬴嬶孁子孔孕字存孚孜孝孟季孤学孩孫孵學孺宅宇守安宋完宍宏宕宗官宙定宛宜宝実客宣室宥宦宮宰害宴宵家宸容宿寂寄寅密寇富寒寓寔寛寝察寡實寧寨審寫寬寮寳寵寶寸对寺対寿封専射将將專尉尊尋對導小少尓尖尚尤尭就尸尹尺尻尼尽尾尿局屁居屈届屋屍屎屏屑屓展属屠層履屬屯山岌岐岑岔岡岩岫岬岱岳岷岸峅峙峠峡峨峪峯峰峴島峻崇崋崎崑崔崖崗崙崧崩嵆嵊嵌嵐嵜嵩嵬嵯嶋嶌嶝嶠嶷嶺嶼嶽巌巍巒巖川州巡巣工左巧巨巫差己已巳巴巷巻巽巾市布帆希帖帙帚帛帝帥師席帯帰帳帶帷常帽幀幄幅幇幌幔幕幟幡幢幣干平年并幸幹幺幻幼幽幾广庁広庄庇床序底店庚府庠度座庫庭庵庶康庸庾廂廃廆廈廉廊廓廖廙廞廟廠廣廩廬廳延廷建廻廼廿弁弄弈弉弊弋弌式弐弑弓弔引弖弗弘弛弟张弥弦弧弩弯弱張強弼弾彅彊彌彎当彗彙彝彡形彤彦彧彩彪彫彬彭彰影彷役彼彿往征徂径待徊律後徐徒従得徘徙從徠御徧徨復循徭微徳徴德徹徽心必忌忍志忘忙応忠快忱念忻忽怒怖怜思怠怡急性怨怪怯恂恆恋恍恐恒恕恢恣恤恥恨恩恪恫恬恭息恰恵悉悌悍悔悛悝悟悠患悦悧悩悪悲悳悴悶悸悼情惇惑惚惜惟惠惡惣惧惨惰想惹惺愁愈愉愍意愔愕愚愛感愴愷愼愾愿慄慇慈慊態慌慎慕慟慢慣慧慨慮慰慶慾憂憊憎憐憑憔憚憤憧憩憫憬憮憲憶憺憾懃懇應懊懋懐懣懲懸懺懼懿戀戈戊戌戍戎成我戒戔或战戚戛戟戡戦戩截戮戯戰戴戸戻房所扁扇扈扉手才扎打払托扮扱扶批扼承技抄抉把抑抒投抗折抜択披抱抵抹押抽担拉拌拍拐拒拓拔拗拘拙招拝拠拡括拭拮拯拱拳拵拶拷拼拾拿持挂指按挑挖挙挟挨挫振挹挺挽挾挿捉捌捏捐捕捗捜捧捨捩据捲捷捺捻掃授掌掏排掖掘掛掟掠採探掣接控推掩措掬掲掴掻掾揃揄揆揉描提揖揚換握揮援揶揺損搗搦搬搭携搾摂摔摘摠摩摯摸摺撃撈撒撓撚撞撤撥撫播撮撰撲撹撻撼擁擂擅操擢擦擬擱擲擾攀攘攝攣攪攫攬支收攷攸改攻放政故效敎敏救敖敗教敞敢散敦敬数敲整敵敷數斂斃文斉斌斎斐斑斗料斛斜斟斡斤斥斧斫斬断斯新方於施旁旅旋旌族旒旗旛无既日旦旧旨早旬旭旱旺旻昀昂昆昇昉昊昌明昏易昔昕星映春昧昨昭是昱昴昵昶昼晁時晃晄晋晏晒晟晤晦晧晨晩普景晰晴晶智暁暇暈暉暎暐暑暖暗暘暢暦暫暮暲暴暹曁曄曇曉曖曙曜曝曠曰曲曳更曷書曹曺曼曽曾替最會月有朋服朐朔朕朗望朝期朦朧木未末本札朮朱朴朶机朽杁杉李杏材村杓杖杙杜杞束条杢杣来杭杮杯杰東杲杳杵杷杼松板枇枉枋析枓枕林枚果枝枠枡枢枯枳架枷枹柄柊柏某柑染柔柘柚柞柩柯柱柳柴柵査柾柿栂栃栄栓栖栗栞校栢栩株栴核根格栽桀桁桂桃框案桐桑桓桔桙桜桝桟桧桴桶桿梁梃梅梓梔梗條梟梠梢梧梨梭梯械梱梳梵梶棄棋棍棒棕棗棘棚棟棠棣森棲棹棺椀椅椋植椎椏椒椙椚椛検椰椴椿楊楓楔楕楚楠楡楢楨楫業楮楯楳極楷楸楼楽概榊榎榑榔榕榛榜榧榮榴槃槇槊構槌槍槎槐槓様槙槨槻槽槿樂樅樊樋樒樓樗標樟模樣権横樫樵樹樺樽橇橈橋橘橙機橡橿檀檄檎檗檜檢檣檬檮檳檸檻櫂櫃櫓櫚櫛櫟櫨櫻欄欅權欒欠次欣欧欲欺欽款歆歌歎歓歙止正此步武歩歪歯歳歴歸死歿殆殉殊残殖殘殤殲殴段殷殺殻殼殿毀毅毋母毎毐毒毓比毖毗毘毛毫毬毯氈氏氐民気氣水氷永氾汀汁求汎汐汕汗汚汜汝江池汪汰汲汴汶決汽汾沁沂沃沅沈沌沐沓沔沖沙沛没沢沪沫沮沱河沸油治沼沽沾沿況泄泉泊泌泓法泗泛泠泡波泣泥注泪泮泰泳洄洋洌洒洗洙洛洞津洩洪洮洱洲洵洸活洽派流浄浅浙浚浜浣浦浩浪浬浮浴海浸涂涅涇消涌涎涙涛涜涪涯液涵涸涼涿淀淄淅淆淇淋淑淘淝淞淡淤淦淨淪淫淮深淳淵混淸淹淺添清渇済渉渋渓渕渙渚減渝渟渠渡渣渤渥渦温渫測渭港游渺渾湊湍湖湘湛湟湣湧湫湯湾湿満源準溜溝溟溢溥溪溯溶溺滄滅滇滉滋滎滑滓滔滕滝滞滬滲滴滷滸滾滿漁漂漆漉漏漑演漕漠漢漣漫漬漱漲漳漸漿潁潅潔潘潜潟潤潭潮潰潴潼澁澂澄澈澎澗澤澧澪澱澳澹激濁濂濃濊濘濟濠濡濤濫濬濮濯濰濱濵濾瀉瀋瀏瀑瀕瀘瀚瀛瀝瀞瀟瀧瀬瀾灌灘灞灣灤火灯灰灸灼災炅炉炊炎炒炙炫炬炭炮炯炳炸点為烈烏烙烟烹烽焉焔焙焚無焦焰然焼煉煌煎煒煕煖煙煜煤煥照煨煩煬煮煽熈熊熏熔熕熙熟熨熱熹熾燁燃燈燎燐燕燗營燥燦燧燭燮燵燻燼燾燿爆爛爨爪爬爲爵父爺爻爽爾牆片版牌牒牘牙牛牝牟牡牢牧物牲特牽犀犁犂犍犠犢犬犯状狂狄狆狐狗狙狛狡狩独狭狸狼狽猊猗猛猜猟猥猩猪猫献猴猶猷猾猿獄獅獏獠獣獨獪獰獲獺玄率玉王玖玩玫玲玻珀珂珈珉珊珍珠珥珪班珸現球琅理琉琛琢琥琦琨琪琬琮琰琲琳琴琵琶琺琿瑀瑁瑋瑕瑗瑙瑚瑛瑜瑞瑟瑠瑣瑤瑩瑪瑯瑰瑳瑶瑾璃璇璋璐璜璞璟璠璧璩環璽璿瓊瓌瓏瓔瓘瓚瓜瓠瓢瓦瓶瓷甄甌甑甕甘甚甜生產産甥甦用甫甯田由甲申男甸町画界畏畑畔留畚畜畝畠畢畤略畦番畫異畳當畷畸畿疆疇疋疎疏疑疝疣疫疱疲疵疸疹疼疽疾病症痍痒痔痕痘痙痛痢痣痩痰痴痺瘍瘡瘢瘤瘴瘻療癇癌癒癖癩癪癬癲癸発登發白百的皆皇皋皎皐皓皖皝皮皴皺皿盂盃盆盈益盒盗盛盞盟監盤盥盧盪目盲直相盾省眈眉看県眞真眠眩眷眸眺眼着睡睢督睦睨睫睺睾睿瞑瞞瞥瞬瞭瞰瞳瞻瞼瞽瞿矗矛矜矢矣知矧矩短矮矯石砂砌砒研砕砥砦砧砲破砺砿硝硫硬硯碁碇碌碍碑碓碕碗碣碧碩碭確碼碾磁磊磋磐磔磧磨磯磾礁礎礒礙礦礪礫礬示礼礽社祀祁祇祈祉祐祓祖祗祚祜祝神祟祠祢祥票祭祷祺禁禄禅禊禍禎福禕禦禧禪禮禰禹禺禽禾禿秀私秉秋科秒秘租秣秤秦秩称移稀稈程稍税稔稗稙稚稜稟稠種稲稷稻稼稽稿穀穂穆積穎穏穢穣穫穴究穹空穿突窃窄窈窒窓窘窟窠窩窪窮窯窺竃竄竇竈立站竜竟章竣童竪端竴競竹竺竿笄笈笊笏笑笘笙笛笞笠笥符第笹筆筈等筋筌筍筏筐筑筒答策筝筠筥筧筬筮筰筵筺箆箇箋箍箏箒箔箕算箙箚管箪箭箱箴箸節篁範篆篇築篋篝篠篤篥篩篪篭篳簀簑簒簗簡簪簫簸簾簿籃籌籍籐籔籟籠籤籬米籾粁粂粃粉粋粍粒粕粗粘粛粟粤粥粧粲粽精糀糊糎糖糜糞糟糠糧糸糺系糾紀紂約紅紆紇紊紋納紐純紗紘紙級紛素紡索紫紬紮累細紳紹紺終絃組絅絆経結絞絡絢絣給絨統絲絳絵絶絹綏經継続綜綝綠綫綬維綰綱網綴綵綸綺綻綽綾綿緊緋総緑緒緘線緝緞締編緩緬緯練緻縁縄縅縉縊縋縒縛縝縞縢縣縦縫縮縯縵縷縹縺總績繁繆繇繊繋繍織繕繚繞繪繭繰繹繼纂續纏纒纓红级线缶罐网罔罕罘罠罪罫置罰署罵罷罹羂羅羆羊羋羌美羚羞羣群羨義羯羲羹羽翁翅翊翌翎習翔翟翠翡翦翫翰翳翹翻翼耀老考者耆而耐耕耗耘耳耶耽耿聊聖聘聚聞聟聡聯聰聲聳聴聶職聾肄肆肇肉肋肌肖肘肛肜肝股肢肥肩肪肯肱育肴肺胃胆背胎胖胚胝胞胡胤胥胱胴胸能脂脅脆脇脈脊脚脛脩脱脳脹脾腋腎腐腑腓腔腕腫腰腱腸腹腺腿膀膂膊膏膚膜膝膠膣膨膳膵膺膾膿臀臂臆臈臍臓臘臙臚臣臥臧臨自臭至致臺臻臼舁舂舅與興舊舌舍舎舐舒舗舘舛舜舞舟舩航舫般舳舵舶舷船艀艇艘艙艤艦艮良艱色艶艸艾芋芍芎芒芙芝芥芦芬芭芮芯花芳芷芸芹芻芽芾苅苑苓苔苗苛苞苟若苦苧苫英苴苺苻茂范茄茅茉茎茗茘茜茨茫茯茱茲茶茸茹荀荃草荊荏荒荘荷荻荼莆莇莉莊莎莒莘莚莞莢莫莱莽菁菅菊菌菓菖菘菜菟菩菫華菰菱菲菴萄萇萊萌萍萎萠萩萬萱萸萼落葆葉著葛葡董葦葫葬葭葯葱葵葺蒋蒐蒔蒙蒜蒟蒯蒲蒴蒸蒹蒻蒼蒿蓁蓄蓉蓋蓑蓬蓮蓼蔀蔑蔓蔗蔚蔡蔣蔦蔬蔭蔵蔽蕁蕃蕉蕊蕎蕗蕙蕤蕨蕩蕪蕭蕷蕾薀薁薄薇薈薊薔薗薙薛薦薨薩薪薫薬薭薮薯藁藉藍藏藝藤藥藩藪藷藺藻蘂蘄蘆蘇蘊蘋蘚蘭蘿虎虐虔處虚虜虞號虢虫虹虻蚊蚕蚤蚩蛆蛇蛉蛋蛍蛎蛙蛛蛟蛤蛭蛮蛯蛸蛹蛾蜀蜂蜃蜆蜉蜘蜚蜜蜥蜴蜷蜻蝉蝋蝎蝕蝗蝙蝠蝣蝦蝮蝶蝸蝿螂融螢螳螺蟄蟇蟠蟲蟷蟹蟻蟾蠅蠍蠕蠡蠢蠣蠱血衆行衍衒術街衙衛衝衞衡衢衣表衫衰衷衾衿袁袂袈袋袍袖袞袢被袰袱袴袷袿裁裂裃装裏裒裔裕補裝裟裡裳裴裵裸製裾褄複褌褐褒褚褥褪褶褸褻襄襖襞襟襤襦襲襴襷西要覆覇覈見規視覗覚覧親覯観覺覽觀视角觚觜解触言訂訃計訊訌討訓託記訛訝訟訢訣訥訪設許訳訴訶診註証詁詈詐詔評詛詞詠詡詢詣試詧詩詫詭詮詰話該詳詵詹誄誅誇誉誌認誑誓誕誘語誠誡誣誤誥誦誨說説読誰課誹誼誾調談請諌諍諏諒論諜諝諡諦諧諫諭諮諱諳諶諷諸諺諾謀謁謂謄謎謐謔謗謙講謝謡謨謬謳謹證譏識譙譚譜警譬議譲譴護譽讀讃變讎讐讒讓讖谷谺谿豆豉豊豎豐豚象豪豫豬豳豹豺貂貉貊貌貘貝貞負財貢貧貨販貪貫責貯貰貳貴貶買貸費貼貽貿賀賁賂賃賄資賈賊賎賑賓賛賜賞賠賢賣賤賦質賭購賽贄贅贈贋贍贔贖贛赛赤赦赧赫赭走赳赴起超越趙趣趨足趾跆跋跎跏跗跛距跡跨跪路跳践踊踏踞踪踰踵蹂蹄蹉蹊蹋蹙蹟蹠蹲蹴蹶躁躅躇躊躍躑躓躙身躬躯躰躱躾軀車軋軌軍軒軕軛軟転軫軸軻軼軽軾較載輌輓輔輛輜輝輦輩輪輯輳輸輻輿轄轅轆轍轟轡轢车辛辜辞辟辣辦辨辭辮辯辰辱農辷辺辻込辿迂迄迅迎运近返迢迥迦迩迪迫迭述迴迷迹追退送逃逅逆逍透逐逓途逖逗這通逝逞速造逡逢連逮週進逵逸逹逼遁遂遅遇遊運遍過遐道達違遙遜遠遡遣遥適遭遮遵遷選遹遺遼遽避邀邁邂邃還邇邈邉邊邏邑邕邙邠邢那邦邨邪邯邱邳邵邸邽邾郁郃郅郊郎郗郛郝郞郡郢郤部郭郯郵郷都鄂鄄鄒鄔鄖鄙鄢鄧鄭鄯鄰鄱鄲鄴酈酉酊酋酌配酎酒酔酘酛酢酩酪酬酵酷酸醂醇醉醍醐醒醗醜醤醪醫醸采釈釉釋里重野量釐金釗釘釜針釣釦釧釵鈍鈎鈑鈔鈕鈞鈴鈷鈺鈿鉄鉅鉈鉉鉋鉗鉛鉞鉢鉤鉦鉱鉾銀銃銅銈銑銓銕銘銚銛銜銭鋏鋒鋤鋪鋭鋲鋳鋸鋺鋼錆錐錕錘錚錠錢錣錦錨錫錬錮錯録鍋鍍鍔鍛鍬鍮鍵鍼鍾鎌鎔鎖鎗鎚鎧鎬鎭鎮鎰鎹鏃鏑鏞鏡鏢鐐鐔鐘鐙鐡鐵鐸鑁鑑鑒鑓鑚鑢鑫鑰鑲鑼鑽鑿铁長长門閂閃閉開閏閑閒間閔閖閘関閣閤閥閨閩閬閭閲閻閼閾闇闊闍闐闓闕闖闘關闡闢闥阜阪阮阯防阻阿陀陂附陋陌降限陕陘陛陝陞陟院陣除陥陪陰陳陵陶陷陸険陽隅隆隈隊隋階随隔隕隗隘隙際障隠隣隧隨隴隷隻隼雀雁雄雅集雇雉雌雍雎雑雒雕雖雙雛雜雞離難雨雪雫雰雲零雷雹電需霄霆震霊霍霑霓霖霜霞霧霰露霸霹霽靂靄靈靏青靖静靚靜非靡面革靫靭靱靳靴靺靼鞄鞅鞆鞋鞍鞏鞘鞜鞠鞨鞬鞭鞮鞴韃韋韓韜韮音韶韻響頁頂頃項順須頊頌預頑頒頓頗領頚頠頡頤頬頭頴頷頸頻頼頽顆題額顎顒顓顔顕顗願顛類顥顧顯顰風颪颯飄飛飜食飡飢飫飯飲飴飼飽飾餃餅餉養餌餐餓餘餞餡館饅饉饋饌饒饗首馗香馥馨馬馮馳馴駁駄駅駆駈駐駒駕駙駝駢駱駿騎騏騒験騙騨騫騭騰騸驀驃驍驕驚驛驟驢驤驥驩驪骨骸髄髏髑體高髙髠髢髣髦髪髭髯髴髷髻鬆鬘鬚鬢鬣鬨鬬鬱鬲鬼魁魂魃魄魅魍魎魏魑魔魚魯鮎鮑鮒鮓鮨鮪鮫鮭鮮鯉鯏鯖鯛鯨鯰鯱鯵鰊鰍鰐鰒鰓鰕鰭鰯鰹鰺鰻鱈鱒鱗鳥鳧鳩鳰鳳鳴鳶鴇鴈鴉鴎鴛鴦鴨鴫鴬鴻鵄鵜鵝鵞鵠鵡鵬鵯鵰鵲鵺鶉鶏鶚鶯鶴鶻鷗鷦鷯鷲鷹鷺鸕鸚鸞鹵鹸鹹鹽鹿麁麒麓麗麝麟麥麦麩麵麹麺麻麾麿黃黄黌黍黎黑黒黔默黙黛點鼈鼎鼓鼠鼬鼻鼾齊齋齎齟齢齧齬齮齲龍龐龔龕龗龙龜가간강개거건검경계고곡공과관광교구국군권규그글금기길김나낙남내년노는니다단당대더도독동드들디라랑래레력로르리립마만말면명몬무문물미민바박반방배버법베병보부북비빠사산삼상새서석선성세소송수순스습승시식신씨아안야약양어언에여역연영오온와완요용우운울원위유윤으은을음의이인일자장재전점정제조종주준중지진집차찬천철총추츠카코크타태터통트파평포표프피하학한함합항해행허혁현협호홍화환황회훈휘희﨑﨟︎󠄁123version https://git-lfs.github.com/spec/v1oid sha256:d9f619a9dccce8ce88357d1b17d25f07806f225c033ea42c64e86c45446cfe71size 171278875123version https://git-lfs.github.com/spec/v1oid sha256:8b0837a24da5fde96c23ca47bb7abd590cd5b185c307e348c6e0b7238178ed89size 169075247123version https://git-lfs.github.com/spec/v1oid sha256:29daa46d080818bb4ab239a518a88338cbccff8f901bef8c9db191a7cb97671dsize 204290192123version https://git-lfs.github.com/spec/v1oid sha256:17d734c186a0f6e76d15f4990e766a00eed5f72bea099575df23677435ee749dsize 3974710123version https://git-lfs.github.com/spec/v1oid sha256:2bbd53b366be82a1becedb4d29f76296b36ad7560b6a8c85d54054900336d59asize 46563354123version https://git-lfs.github.com/spec/v1oid sha256:fd4322482a7018b9bce9216173ae9d2848efe6d310b468bbb4383fb55c874a18size 22685181123version https://git-lfs.github.com/spec/v1oid sha256:5ada075eb25a854f71d6e6fa4e7d55e7be0ae049255b1f8f19d05c13b1b68c9esize 375087541{"n": {"n": 0.0622, "t": 0, "s": 0, "f": 0.0405, "m": 0, "q": 0, "b": 0, "r": 0, "v": 0.1921, "a": 0, "z": 0, "d": 0.0891, "p": 0.0258, "c": 0.0228, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "t": {"n": 0.0736, "t": 1, "s": 0, "f": 0.027, "m": 0, "q": 0, "b": 0, "r": 0.172, "v": 0.2027, "a": 0, "z": 0, "d": 0.1426, "p": 0.0384, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "s": {"n": 0.0578, "t": 0, "s": 0, "f": 0, "m": 0, "q": 0, "b": 0, "r": 0, "v": 0.3442, "a": 0, "z": 0, "d": 0.102, "p": 0, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "f": {"n": 0.0501, "t": 0, "s": 0, "f": 0, "m": 0.0305, "q": 0, "b": 0, "r": 0.0302, "v": 0.2821, "a": 0, "z": 0, "d": 0.0829, "p": 0, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "m": {"n": 0.2381, "t": 0, "s": 0, "f": 0, "m": 0, "q": 0.4929, "b": 0, "r": 0, "v": 0.0675, "a": 0.0355, "z": 0, "d": 0.0297, "p": 0, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "q": {"n": 0.4815, "t": 0, "s": 0, "f": 0, "m": 0, "q": 0, "b": 0, "r": 0.0329, "v": 0.0943, "a": 0.0826, "z": 0, "d": 0.0447, "p": 0, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "b": {"n": 0.3708, "t": 0, "s": 0, "f": 0, "m": 0, "q": 0, "b": 0, "r": 0, "v": 0.026, "a": 0, "z": 0, "d": 0, "p": 0, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0.0207, "vx": 0, "ad": 0, "an": 0}, "r": {"n": 0.1064, "t": 0, "s": 0, "f": 0, "m": 0.0341, "q": 0, "b": 0, "r": 0.0441, "v": 0.2954, "a": 0.027, "z": 0, "d": 0.1562, "p": 0.0429, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "v": {"n": 0.1081, "t": 0, "s": 0, "f": 0, "m": 0.0432, "q": 0, "b": 0, "r": 0.1591, "v": 0.1757, "a": 0.0224, "z": 0, "d": 0.036, "p": 0.0421, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "a": {"n": 0.1464, "t": 0, "s": 0, "f": 0, "m": 0, "q": 0, "b": 0, "r": 0, "v": 0.0333, "a": 0.0281, "z": 0, "d": 0, "p": 0, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "z": {"n": 0.0737, "t": 0, "s": 0, "f": 0, "m": 0, "q": 0, "b": 0, "r": 0, "v": 0.1117, "a": 0.0306, "z": 0, "d": 0, "p": 0, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "d": {"n": 0, "t": 0, "s": 0, "f": 0, "m": 0, "q": 0, "b": 0, "r": 0.0313, "v": 0.5905, "a": 0.1047, "z": 0, "d": 0.1317, "p": 0.0626, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "p": {"n": 0.2263, "t": 0.0201, "s": 0.034, "f": 0, "m": 0.0314, "q": 0, "b": 0, "r": 0.4427, "v": 0.0835, "a": 0.0232, "z": 0, "d": 0, "p": 0, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0.0318, "ns": 0.0314, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "c": {"n": 0.1367, "t": 0, "s": 0, "f": 0, "m": 0.0253, "q": 0, "b": 0, "r": 0.2692, "v": 0.2089, "a": 0.0321, "z": 0, "d": 0.108, "p": 0.0514, "c": 0.0296, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0.0274, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "u": {"n": 0.5251, "t": 0, "s": 0, "f": 0, "m": 0.043, "q": 0, "b": 0, "r": 0.0581, "v": 0.0781, "a": 0.0424, "z": 0, "d": 0.0276, "p": 0, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0.0414, "vx": 0, "ad": 0, "an": 0}, "y": {"n": 0, "t": 0, "s": 0, "f": 0, "m": 0, "q": 0, "b": 0, "r": 0, "v": 0, "a": 0, "z": 0, "d": 0, "p": 0, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "e": {"n": 0, "t": 0, "s": 0, "f": 0, "m": 0, "q": 0, "b": 0, "r": 0, "v": 0, "a": 0, "z": 0, "d": 0, "p": 0, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "o": {"n": 0, "t": 0, "s": 0, "f": 0, "m": 0.0412, "q": 0, "b": 0, "r": 0, "v": 0.1031, "a": 0, "z": 0, "d": 0, "p": 0, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "i": {"n": 0, "t": 0, "s": 0, "f": 0, "m": 0, "q": 0, "b": 0, "r": 0, "v": 0.0205, "a": 0, "z": 0, "d": 0, "p": 0, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "l": {"n": 0.0289, "t": 0, "s": 0, "f": 0, "m": 0, "q": 0, "b": 0, "r": 0, "v": 0.0433, "a": 0, "z": 0, "d": 0.0409, "p": 0, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "j": {"n": 0.2866, "t": 0, "s": 0, "f": 0.0258, "m": 0, "q": 0, "b": 0, "r": 0, "v": 0.0789, "a": 0, "z": 0, "d": 0.0304, "p": 0, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0.1251, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0.1348, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "h": {"n": 0.5789, "t": 0, "s": 0, "f": 0, "m": 0, "q": 0, "b": 0, "r": 0.0351, "v": 0.0526, "a": 0.1228, "z": 0, "d": 0.0526, "p": 0, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0.0351, "vx": 0, "ad": 0, "an": 0}, "k": {"n": 0.0236, "t": 0, "s": 0, "f": 0, "m": 0, "q": 0, "b": 0, "r": 0.0236, "v": 0.2505, "a": 0, "z": 0, "d": 0.1234, "p": 0.0526, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "g": {}, "x": {}, "w": {"n": 0.0859, "t": 0, "s": 0, "f": 0, "m": 0, "q": 0, "b": 0, "r": 0.2504, "v": 0.1699, "a": 0, "z": 0, "d": 0.1199, "p": 0.0597, "c": 0.1215, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0.0376, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "nr": {"n": 0.1627, "t": 0, "s": 0, "f": 0, "m": 0, "q": 0, "b": 0, "r": 0, "v": 0.1824, "a": 0, "z": 0, "d": 0.0654, "p": 0.0393, "c": 0.0417, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0.1234, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "ns": {"n": 0.2905, "t": 0, "s": 0.0305, "f": 0.0397, "m": 0.0257, "q": 0, "b": 0, "r": 0, "v": 0.1452, "a": 0, "z": 0, "d": 0.0317, "p": 0, "c": 0.0274, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0.03, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "nt": {"n": 0.2051, "t": 0, "s": 0, "f": 0.0897, "m": 0, "q": 0, "b": 0, "r": 0, "v": 0.2436, "a": 0, "z": 0, "d": 0, "p": 0.0385, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0.0256, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0.0513, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "nx": {"n": 1.0, "t": 0, "s": 0, "f": 0, "m": 0, "q": 0, "b": 0, "r": 0, "v": 0, "a": 0, "z": 0, "d": 0, "p": 0, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "nz": {"n": 0.3944, "t": 0, "s": 0, "f": 0, "m": 0, "q": 0, "b": 0, "r": 0, "v": 0.0646, "a": 0, "z": 0, "d": 0.0347, "p": 0, "c": 0.0221, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "vd": {"n": 0, "t": 0, "s": 0, "f": 0, "m": 0, "q": 0, "b": 0, "r": 0, "v": 0.7857, "a": 0, "z": 0, "d": 0.119, "p": 0, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "vn": {"n": 0.2322, "t": 0, "s": 0, "f": 0.0323, "m": 0, "q": 0, "b": 0, "r": 0, "v": 0.0619, "a": 0, "z": 0, "d": 0.0467, "p": 0, "c": 0.033, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0.0201, "vx": 0, "ad": 0, "an": 0}, "vx": {"n": 0.0396, "t": 0, "s": 0, "f": 0, "m": 0.0223, "q": 0, "b": 0, "r": 0.1609, "v": 0, "a": 0.052, "z": 0, "d": 0.0223, "p": 0, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0.4728, "vx": 0, "ad": 0, "an": 0.047}, "ad": {"n": 0, "t": 0, "s": 0, "f": 0, "m": 0, "q": 0, "b": 0, "r": 0, "v": 0.844, "a": 0.0336, "z": 0, "d": 0.0519, "p": 0.0528, "c": 0, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}, "an": {"n": 0, "t": 0, "s": 0, "f": 0.0246, "m": 0, "q": 0, "b": 0, "r": 0, "v": 0.1258, "a": 0, "z": 0, "d": 0.0912, "p": 0, "c": 0.0629, "u": 1, "y": 1, "e": 0, "o": 0, "i": 0, "l": 0, "j": 0, "h": 0, "k": 0, "g": 0, "x": 0, "w": 1, "nr": 0, "ns": 0, "nt": 0, "nx": 0, "nz": 0, "vd": 0, "vn": 0, "vx": 0, "ad": 0, "an": 0}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446absl-py==2.1.0addict==2.4.0aiofiles==24.1.0aiohttp==3.9.5aiosignal==1.3.1albucore==0.0.13albumentations==1.4.10alibabacloud-credentials==1.0.2alibabacloud-credentials-api==1.0.0alibabacloud-darabonba-stream==0.0.2alibabacloud-endpoint-util==0.0.4alibabacloud-gateway-spi==0.0.3alibabacloud-ocr-api20210707==3.1.3alibabacloud-openapi-util==0.2.2alibabacloud-tea==0.4.3alibabacloud-tea-console==0.0.1alibabacloud-tea-openapi==0.4.1alibabacloud-tea-util==0.3.13altair==5.3.0altgraph==0.17.4annotated-doc==0.0.2annotated-types==0.6.0anyio==4.3.0appdirs==1.4.4APScheduler==3.11.0asgiref==3.8.1astor==0.8.1asttokens==3.0.0async-timeout==4.0.3asyncio-atexit==1.0.1attrdict==2.0.1attrs==23.2.0azure-ai-translation-text==1.0.1azure-core==1.36.0Babel==2.15.0BabelDOC==0.2.33backoff==2.2.1backports.tarfile==1.2.0bce-python-sdk==0.9.17beautifulsoup4==4.12.3betterproto==1.2.5bitarray==3.7.2bitstring==4.3.1blinker==1.8.2Brotli==1.1.0brotlicffi==1.1.0.0bs4==0.0.2build==1.3.0CacheControl==0.14.3cachetools==5.3.3catalogue==2.0.10certifi==2024.2.2cffi==1.17.1chardet==5.2.0charset-normalizer==3.3.2chex==0.1.86chinese_calendar==1.10.0cleo==2.1.0click==8.1.7click-default-group==1.2.4colorama==0.4.6coloredlogs==15.0.1colorlog==6.9.0colorthief==0.2.1colour==0.1.5comtypes==1.4.13ConfigArgParse==1.7.1contourpy==1.2.1cramjam==2.9.1crashtest==0.4.1cryptography==44.0.0cssselect==1.2.0cssutils==2.11.1ctranslate2==4.6.1cycler==0.12.1Cython==3.0.10darabonba-core==1.0.3darkdetect==0.8.0dataclasses-json==0.6.5datasets==2.20.0decorator==5.1.1deepl==1.23.0Deprecated==1.2.18dill==0.4.0diskcache==5.6.3distlib==0.4.0distro==1.9.0Django==5.1.5docformatter==1.7.7docker-pycreds==0.4.0docx2txt==0.9dulwich==0.24.6einops==0.8.1emoji==2.14.0erniebot==0.5.0erniebot_agent==0.5.0et-xmlfile==1.1.0eval_type_backport==0.2.0exceptiongroup==1.2.1executing==2.2.0faiss-cpu==1.8.0.post1fastapi==0.120.0fasteners==0.19fastjsonschema==2.21.2ffmpy==0.3.2filelock==3.14.0filesplit==3.0.2filetype==1.2.0findpython==0.7.0fire==0.6.0Flask==3.0.3flask-babel==4.0.0flatbuffers==25.9.23fonttools==4.51.0freetype-py==2.5.1frozenlist==1.4.1fsspec==2024.3.1fugashi==1.5.2future==1.0.0gitdb==4.0.11GitPython==3.1.43glcontext==3.0.0GPUtil==1.4.0gradio==5.35.0gradio_client==1.10.4gradio_pdf==0.0.22greenlet==3.0.3groovy==0.1.2grpclib==0.4.8h11==0.14.0h2==4.3.0hf-xet==1.2.0hpack==4.1.0html5lib==1.1httpcore==1.0.5httpx==0.28.1huggingface-hub==0.36.0humanfriendly==10.0hyperframe==6.1.0idna==3.7image==1.5.33imageio==2.34.1imagesize==1.4.1imgaug==0.4.0importlib_metadata==8.7.0importlib_resources==6.4.0inflate64==1.0.0installer==0.7.0ipython==8.37.0isodate==0.7.2isosurfaces==0.1.2itsdangerous==2.2.0jaconv==0.4.0jaraco.classes==3.4.0jaraco.context==6.0.1jaraco.functools==4.3.0jax==0.4.30jaxlib==0.4.30jedi==0.19.2jh2==5.0.10Jinja2==3.1.3jiter==0.11.1joblib==1.4.2json-lines==0.5.0json5==0.12.1jsonpatch==1.33jsonpath-python==1.0.6jsonpointer==2.4jsonschema==4.21.1jsonschema-path==0.3.3jsonschema-specifications==2023.12.1keyboard==0.13.5keyring==25.6.0kiwisolver==1.4.5langchain==0.1.5langchain-community==0.0.17langchain-core==0.1.23langchain-openai==0.1.4langchain-text-splitters==0.0.1langdetect==1.0.9langsmith==0.0.87lanms_neo==1.0.2lazy-object-proxy==1.10.0lazy_loader==0.4Levenshtein==0.27.1lmdb==1.2.1lxml==6.0.2# Editable install with no version control (manimgl==1.7.2)-e e:\t\manimManimPango==0.6.0mapbox_earcut==1.0.3markdown-it-py==3.0.0MarkupSafe==2.1.5marshmallow==3.21.1matplotlib==3.5.2matplotlib-inline==0.1.7mdict-utils==1.3.12mdurl==0.1.2ml_dtypes==0.5.3moderngl==5.12.0moderngl-window==3.1.1more-itertools==10.3.0MouseInfo==0.1.3mpmath==1.3.0msgpack==1.1.2msl-loadlib==1.0.0multidict==6.0.5multiprocess==0.70.18multivolumefile==0.2.3mypy-extensions==1.0.0natsort==8.4.0nest-asyncio==1.6.0networkx==3.3niquests==3.15.2nltk==3.9.1numpy==1.26.4olefile==0.47ollama==0.6.0onnx==1.19.1onnxruntime==1.23.1openai==2.6.0openapi-schema-validator==0.6.2openapi-spec-validator==0.7.1OpenCC==1.1.1opencc-python-reimplemented==0.1.7opencv-contrib-python==4.10.0.84opencv-python==4.11.0.86opencv-python-headless==4.10.0.84openpyxl==3.1.4opt-einsum==3.3.0optax==0.2.2ordered-set==4.1.0orjson==3.11.3packaging==25.0paddle-bfloat==0.1.7paddleocr==2.9.1paddlepaddle==3.0.0b2paddlex==3.0.0b2pandarallel==1.6.5pandas==2.2.2Parsley==1.3parso==0.8.4patch-ng==1.17.4pathable==0.4.3pathos==0.3.4pbs-installer==2025.10.14pdf2docx==0.5.8pdf2zh==1.9.11pdfminer.six==20250416peewee==3.18.2pefile==2023.2.7pgserver==0.1.4piexif==1.1.3pikepdf==9.11.0Pillow==10.1.0pillow-jxl-plugin==1.3.5pkginfo==1.12.1.2platformdirs==4.5.0poetry==2.2.1poetry-core==2.2.1polars==1.9.0Polygon3==3.0.9.1pox==0.3.6ppft==1.7.7premailer==3.10.0prettytable==3.12.0prompt_toolkit==3.0.51protobuf==5.28.3proxynt @ https://github.com/sazima/proxynt/archive/refs/heads/snappy.zip#sha256=af54e78001fac868d94a73bc461fdec69476a997900c55a5ffe013b516d2ae58psutil==7.1.1psycopg==3.2.3psycopg-binary==3.2.3pure_eval==0.2.3py-cpuinfo==9.0.0py7zr==0.22.0pyarrow==16.1.0pyarrow-hotfix==0.6PyAutoGUI==0.9.54pybcj==1.0.2pyclipper==1.3.0.post2pycocotools==2.0.8pycparser==2.22pycryptodome==3.20.0pycryptodomex==3.21.0pydantic==2.11.10pydantic_core==2.33.2pydub==0.25.1PyExecJS==1.5.1PyGetWindow==0.0.9pyglet==2.1.6pyglm==2.8.2Pygments==2.17.2pyinstaller==6.11.0pyinstaller-hooks-contrib==2024.9PyMsgBox==1.0.9PyMuPDF==1.23.6PyMuPDFb==1.23.6PyMySQL==1.1.1pynput==1.7.6PyOpenGL==3.1.9pyparsing==3.1.2pypdf==5.0.0pyperclip==1.8.2pyppmd==1.1.0pyproject_hooks==1.2.0PyQt5==5.15.10PyQt5-Qt5==5.15.2PyQt5-sip==12.13.0PyQt6==6.10.0PyQt6-Qt6==6.10.0PyQt6_sip==13.10.2pyreadline3==3.5.4PyRect==0.2.0PyScreeze==0.1.30PySide6==6.6.2PySide6-Fluent-Widgets==1.7.0PySide6_Addons==6.6.2PySide6_Essentials==6.6.2PySideSix-Frameless-Window==0.4.3PySimpleGUI==4.55.1pysrt==1.1.2python-dateutil==2.9.0.post0python-docx==1.1.2python-iso639==2024.10.22python-Levenshtein==0.27.1python-Levenshtein-wheels==0.13.2python-magic==0.4.27python-multipart==0.0.20python-oxmsg==0.0.1python-snappy==0.7.3pytweening==1.2.0pytz==2024.1PyWavelets==1.6.0pywin32==306pywin32-ctypes==0.2.2pywinauto==0.6.8PyYAML==6.0.1pyzstd==0.16.2qh3==1.5.6qianfan==0.0.3QtPy==2.4.3rapidfuzz==3.9.1rapidocr-onnxruntime==1.4.4rarfile==4.2referencing==0.35.0regex==2024.4.28requests==2.32.5requests-toolbelt==1.0.0rfc3339-validator==0.1.4rich==14.2.0rpds-py==0.18.0ruamel.yaml==0.18.6ruamel.yaml.clib==0.2.12ruff==0.14.2safehttpx==0.1.6safetensors==0.6.2scikit-image==0.25.2scikit-learn==1.5.2scipy==1.13.0screeninfo==0.8.1seaborn==0.13.2semantic-version==2.10.0sentencepiece==0.2.1sentry-sdk==2.6.0setproctitle==1.3.3shapely==2.1.2shellingham==1.5.4shiboken6==6.6.2six==1.16.0skia-pathops==0.8.0.post2smmap==5.0.1sniffio==1.3.1socksio==1.0.0soupsieve==2.5spacy_pkuseg==1.0.1SQLAlchemy==2.0.29sqlean.py==3.47.0sqlite-vec==0.1.6sqlparse==0.5.3srsly==2.5.1stack-data==0.6.3starlette==0.48.0stringcase==1.2.0svgelements==1.9.6sympy==1.14.0tenacity==9.1.2tencentcloud-sdk-python-common==3.0.1479tencentcloud-sdk-python-tmt==3.0.1478termcolor==2.4.0texttable==1.7.0threadpoolctl==3.5.0tifffile==2024.4.24tiktoken==0.12.0tokenizers==0.22.1toml==0.10.2tomli==2.0.1tomlkit==0.12.2toolz==0.12.1toposort==1.10torch==2.9.0torchvision==0.24.0tornado==6.4.1tqdm==4.67.1traitlets==5.14.3transformers==4.57.1translators==5.9.5trove-classifiers==2025.9.11.17typer==0.12.3typer-slim==0.20.0typing-inspect==0.9.0typing-inspection==0.4.2typing_extensions==4.15.0tzdata==2024.1tzlocal==5.2ujson==5.10.0ultralytics==8.3.90ultralytics-thop==2.0.18unidic-lite==1.0.8unstructured==0.16.9unstructured-client==0.28.1untokenize==0.1.1urllib3==2.5.0urllib3-future==2.14.906uvicorn==0.29.0validators==0.35.0virtualenv==20.35.3visualdl==2.5.3wandb==0.17.2wassima==2.0.2wcwidth==0.2.13webencodings==0.5.1websockets==11.0.3Werkzeug==3.0.3winsdk==1.0.0b10WMI==1.5.1wordsegment==1.3.1wrapt==1.17.0x32dbg==1.1.0x64dbg==1.1.0xinference-client==1.11.0.post1xlrd==2.0.1xsdata==25.7xxhash==3.4.1yarl==1.9.4zipp==3.23.0zstandard==0.25.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146# see huggingface\BallonsTranslator\main.pyimport json, os, sys, time, ioimport os.path as osp
from PIL import Imageimport PILimport cv2import numpy as np
# see utils\io_utils.pydef imread(imgpath, read_type=cv2.IMREAD_COLOR, max_retry_limit=5, retry_interval=0.1): if not osp.exists(imgpath): return None num_tries = 0 while True: try: img = Image.open(imgpath) if read_type == cv2.IMREAD_GRAYSCALE: img = img.convert('L') img = np.array(img) if read_type != cv2.IMREAD_GRAYSCALE: if img.ndim == 3 and img.shape[-1] == 1: img = img[..., :2] if img.ndim == 2: img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
if img.ndim == 3 and img.shape[-1] == 4: if np.all(img[..., -1] == 255): img = np.ascontiguousarray(img[..., :3]) break except PIL.UnidentifiedImageError as e: # IMG I/O thread might not finished yet num_tries += 1 if max_retry_limit is not None and num_tries >= max_retry_limit: return None time.sleep(retry_interval) return img
def chunks(lst, n): """Yield successive n-sized chunks from lst.""" for i in range(0, len(lst), n): yield lst[i:i + n]
if __name__ == '__main__':
from modules.textdetector.ctd.inference import TextDetector as CTDModel from modules.ocr.mit48px import Model48pxOCR
CTD_ONNX_PATH = 'data/models/comictextdetector.pt.onnx' device = 'cpu' detect_size = 1280
ctd_model = CTDModel(CTD_ONNX_PATH, detect_size=detect_size, device=device)
OCR48PXMODEL_PATH = 'data/models/ocr_ar_48px.ckpt' ocr_model = Model48pxOCR(OCR48PXMODEL_PATH, device)
img = imread('E:/huggingface/BallonsTranslator/assets/kcc-0010.jpg') # All text detectors only support 3 channels input if img.ndim == 3 and img.shape[2] == 4: img = cv2.cvtColor(img, cv2.COLOR_RGBA2RGB)
_, mask, blk_list = ctd_model(img)
fnt_rsz = 1.0 fnt_max = -1 fnt_min = -1 for blk in blk_list: sz = blk._detected_font_size * fnt_rsz if fnt_max > 0: sz = min(fnt_max, sz) if fnt_min > 0: sz = max(fnt_min, sz) blk.font_size = sz blk._detected_font_size = sz
ksize = 2 if ksize > 0: element = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * ksize + 1, 2 * ksize + 1),(ksize, ksize)) # 创建一个椭圆形的结构元素(kernel),用于后续的形态学操作 # 元素的尺寸 # (ksize, ksize) :椭圆的锚点(中心点) mask = cv2.dilate(mask, element) # 对 mask 图像进行膨胀操作(dilate),使用上面创建的椭圆结构元素。膨胀操作可以让白色区域(通常是前景或目标区域)变大,常用于去除小的黑洞、连接断开的区域等。
for blk in blk_list: blk.det_model = 'ctd'
need_save_mask = True detect_counter = 0
detect_counter += 1
# self.ocr.run_ocr(img, blk_list)
for blk in blk_list: blk.text = []
split_textblk = False seg_func = None
model_text_height = 48 model_maxwidth = 8100
from utils.textblock import collect_textblock_regions
chunk_size = 16
regions, textblk_lst_indices = collect_textblock_regions(img, blk_list, model_text_height, model_maxwidth, split_textblk, seg_func)
ocr_model(blk_list, regions, textblk_lst_indices, chunk_size=chunk_size)
img_draw = img.copy()
# from qtpy.QtWidgets import QApplication # from qtpy.QtGui import QIcon, QFontDatabase, QGuiApplication, QFont, QFontMetrics
# ui\mainwindow.py for blk in blk_list: text = blk.get_text() for line in blk.lines: img_draw = cv2.rectangle(img_draw, line[0], line[3], (0, 0, 255), 2) # 在一行坚排文字的左边画一条红线 # app_font = QFont('Microsoft YaHei UI') # fontMetrics = QFontMetrics(app_font)
# rect = fontMetrics.boundingRect(text[0]) # textWidth = rect.width() pass # blk.text = self.ocrSubWidget.sub_text(text)
cv2.imwrite("E:/xxxxxxxxxxxxxxxx.jpg", img_draw)
pass
123456789101112131415161718192021from .ocr import OCR, OCRBasefrom .textdetector import TEXTDETECTORS, TextDetectorBasefrom .translators import TRANSLATORS, BaseTranslatorfrom .inpaint import INPAINTERS, InpainterBasefrom .base import DEFAULT_DEVICE, GPUINTENSIVE_SET, LOGGER, merge_config_module_params, \ init_module_registries, init_textdetector_registries, init_inpainter_registries, init_ocr_registries, init_translator_registries
GET_VALID_TEXTDETECTORS = lambda : list(TEXTDETECTORS.module_dict.keys())GET_VALID_TRANSLATORS = lambda : list(TRANSLATORS.module_dict.keys())GET_VALID_INPAINTERS = lambda : list(INPAINTERS.module_dict.keys())GET_VALID_OCR = lambda : list(OCR.module_dict.keys())
MODULETYPE_TO_REGISTRIES = { 'textdetector': TEXTDETECTORS, 'ocr': OCR, 'inpainter': INPAINTERS, 'translator': TRANSLATORS}
# TODO: use manga-image-translator as backend...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364import gcimport osimport timefrom typing import Dict, List, Callable, Unionfrom copy import deepcopyfrom collections import OrderedDictimport reimport importlib
from utils.logger import logger as LOGGERfrom utils import shared
GPUINTENSIVE_SET = {'cuda', 'mps', 'xpu', 'privateuseone'}
def register_hooks(hooks_registered: OrderedDict, callbacks: Union[List, Callable, Dict]): if callbacks is None: return if isinstance(callbacks, (Dict, OrderedDict)): for k, v in callbacks.items(): hooks_registered[k] = v else: nhooks = len(hooks_registered)
if isinstance(callbacks, Callable): callbacks = [callbacks] for callback in callbacks: hk = 'hook_' + str(nhooks).zfill(2) while True: if hk not in hooks_registered: break hk = hk + '_' + str(time.time_ns()) hooks_registered[hk] = callback nhooks += 1
def patch_module_params(cfg_param, module_params, module_name: str = ''): # cfg_param = config_params[module_key] cfg_key_set = set(cfg_param.keys()) module_key_set = set(module_params.keys()) for ck in cfg_key_set: if ck not in module_key_set: LOGGER.warning(f'Found invalid {module_name} config: {ck}') cfg_param.pop(ck)
for mk in module_key_set: if mk not in cfg_key_set: if not mk.startswith('__') and mk != 'description': LOGGER.info(f'Found new {module_name} config: {mk}') cfg_param[mk] = module_params[mk] else: mparam = module_params[mk] cparam = cfg_param[mk] if isinstance(mparam, dict): tgt_type = mparam.get('data_type', type(mparam['value'])) if isinstance(cparam, dict): if 'value' in cparam: v = cparam['value'] elif isinstance(mparam['value'], dict): for k in mparam['value']: if k in cparam: mparam['value'][k] = cparam[k] v = mparam['value'] else: v = mparam['value'] else: v = cparam valid = True if tgt_type != type(v): try: v = tgt_type(v) except: valid = False LOGGER.warning(f'Invalid param value {v} for defined dtype: {tgt_type}, it will be set to default value: {mparam}') if valid: mparam['value'] = v cfg_param[mk] = mparam else: if type(cparam) != type(mparam): if not isinstance(mparam, dict) and isinstance(cparam, dict): cparam = cparam['value'] try: cfg_param[mk] = type(mparam)(cparam) except ValueError: LOGGER.warning(f'Invalid param value {cparam} for defined dtype: {type(mparam)}, it will be set to default value: {mparam}') cfg_param[mk] = mparam cfg_key_list = list(cfg_param.keys()) module_key_list = list(module_params.keys()) if cfg_key_list != module_key_list: new_params = {key: cfg_param[key] for key in module_key_list} cfg_param.clear() cfg_param.update(new_params) module_key_set = set(module_params.keys()) cfg_param['__param_patched'] = True return cfg_param
def merge_config_module_params(config_params: Dict, module_keys: List, get_module: Callable) -> Dict: for module_key in module_keys: module_params = get_module(module_key).params if module_key not in config_params or config_params[module_key] is None: config_params[module_key] = module_params else: patch_module_params(config_params[module_key], module_params, module_key) return config_params
def standardize_module_params(params): if params is None: return for k, v in params.items(): if not isinstance(v, dict): v = {'value': v} if 'data_type' not in v: v['data_type'] = type(v['value']) params[k] = v
class BaseModule:
params: Dict = None logger = LOGGER
_preprocess_hooks: OrderedDict = None _postprocess_hooks: OrderedDict = None
download_file_list: List = None download_file_on_load = False
_load_model_keys: set = None
def __init__(self, **params) -> None: standardize_module_params(self.params) if self.params is not None and '__param_patched' not in params: params = patch_module_params(params, self.params, self) if params: if self.params is None: self.params = params else: self.params.update(params)
@classmethod def register_postprocess_hooks(cls, callbacks: Union[List, Callable]): """ these hooks would be shared among all objects inherited from the same super class """ assert cls._postprocess_hooks is not None register_hooks(cls._postprocess_hooks, callbacks)
@classmethod def register_preprocess_hooks(cls, callbacks: Union[List, Callable, Dict]): """ these hooks would be shared among all objects inherited from the same super class """ assert cls._preprocess_hooks is not None register_hooks(cls._preprocess_hooks, callbacks)
def get_param_value(self, param_key: str): assert self.params is not None and param_key in self.params p = self.params[param_key] if isinstance(p, dict): return p['value'] return p def set_param_value(self, param_key: str, param_value, convert_dtype=True): assert self.params is not None and param_key in self.params p = self.params[param_key] if isinstance(p, dict): if convert_dtype: try: val_type = p.get('data_type', type(p['value'])) param_value = val_type(param_value) except ValueError: dtype = type(p['value']) self.logger.warning(f'Invalid param value {param_value} for defined dtype: {dtype}') p['value'] = param_value else: if convert_dtype: try: param_value = type(p)(param_value) except ValueError: self.logger.warning(f'Invalid param value {param_value} for defined dtype: {type(p)}, revert to original value {p}') param_value = p self.params[param_key] = param_value
def updateParam(self, param_key: str, param_content): self.set_param_value(param_key, param_content)
@property def low_vram_mode(self): if 'low vram mode' in self.params: return self.get_param_value('low vram mode') return False
def is_cpu_intensive(self)->bool: if self.params is not None and 'device' in self.params: return self.params['device']['value'] == 'cpu' return False
def is_gpu_intensive(self) -> bool: if self.params is not None and 'device' in self.params: return self.params['device']['value'] in GPUINTENSIVE_SET return False
def is_computational_intensive(self) -> bool: if self.params is not None and 'device' in self.params: return True return False def unload_model(self, empty_cache=False): model_deleted = False if self._load_model_keys is not None: for k in self._load_model_keys: if hasattr(self, k): model = getattr(self, k) if model is not None: if hasattr(model, 'unload_model'): model.unload_model(empty_cache=False) del model setattr(self, k, None) model_deleted = True if empty_cache and model_deleted: soft_empty_cache()
return model_deleted
def load_model(self): # TODO: check and download files self._load_model() return
def _load_model(self): return
def all_model_loaded(self): if self._load_model_keys is None: return True for k in self._load_model_keys: if not hasattr(self, k) or getattr(self, k) is None: return False return True def __del__(self): self.unload_model()
@property def debug_mode(self): return shared.DEBUG def flush(self, param_key: str): return None
os.environ['PYTORCH_ENABLE_MPS_FALLBACK'] = '1'import torch
DEFAULT_DEVICE = 'cpu'AVAILABLE_DEVICES = ['cpu']if hasattr(torch, 'cuda') and torch.cuda.is_available(): DEFAULT_DEVICE = 'cuda' AVAILABLE_DEVICES.append(DEFAULT_DEVICE)if hasattr(torch, 'xpu') and torch.xpu.is_available(): DEFAULT_DEVICE = 'xpu' if torch.xpu.is_available() else 'cpu' AVAILABLE_DEVICES.append(DEFAULT_DEVICE)if hasattr(torch, 'backends') and hasattr(torch.backends, 'mps') and torch.backends.mps.is_available(): DEFAULT_DEVICE = 'mps' AVAILABLE_DEVICES.append(DEFAULT_DEVICE)
try: import torch_directml if hasattr(torch, 'privateuseone') and torch_directml.device_count() > 0: torch.dml = torch_directml DEFAULT_DEVICE = f'privateuseone:{torch.dml.default_device()}' AVAILABLE_DEVICES += [f"privateuseone:{d}" for d in range(torch.dml.device_count())]except: # directml is not supported passBF16_SUPPORTED = DEFAULT_DEVICE == 'cuda' and torch.cuda.is_bf16_supported() or DEFAULT_DEVICE == 'xpu' and torch.xpu.is_bf16_supported()
def is_nvidia(): if DEFAULT_DEVICE == 'cuda': if torch.version.cuda: return True return False
def is_intel(): if DEFAULT_DEVICE == 'xpu': if torch.version.xpu: return True return False
def soft_empty_cache(): gc.collect() if DEFAULT_DEVICE == 'cuda': torch.cuda.empty_cache() torch.cuda.ipc_collect() elif DEFAULT_DEVICE == 'xpu': torch.xpu.empty_cache() # torch.xpu.ipc_collect() elif DEFAULT_DEVICE == 'mps': torch.mps.empty_cache()
def DEVICE_SELECTOR(not_supported:list[str]=[]): return deepcopy( { 'type': 'selector', 'options': [opt for opt in AVAILABLE_DEVICES if all(device not in opt for device in not_supported)], 'value': DEFAULT_DEVICE if not any(DEFAULT_DEVICE in device for device in not_supported) else 'cpu' })
TORCH_DTYPE_MAP = { 'fp32': torch.float32, 'fp16': torch.float16, 'bf16': torch.bfloat16,}
MODULE_SCRIPTS = { 'translator': {'module_dir': 'modules/translators', 'module_pattern': r'trans_(.*?).py'}, 'textdetector': {'module_dir': 'modules/textdetector', 'module_pattern': r'detector_(.*?).py'}, 'inpainter': {'module_dir': 'modules/inpaint', 'module_pattern': r'inpaint_(.*?).py'}, 'ocr': {'module_dir': 'modules/ocr', 'module_pattern': r'ocr_(.*?).py'},} def init_module_registries(target_modules=None): def _load_module(module_dir: str, module_pattern: str): modules = os.listdir(module_dir) pattern = re.compile(module_pattern) module_path = module_dir.replace('/', '.') if not module_path.endswith('.'): module_path += '.' for module_name in modules: if pattern.match(module_name) is not None: try: module = module_path + module_name.replace('.py', '') importlib.import_module(module) except Exception as e: LOGGER.warning(f'Failed to import {module}: {e}')
if target_modules is None: target_modules = MODULE_SCRIPTS if isinstance(target_modules, str): target_modules = [target_modules]
for k in target_modules: _load_module(**MODULE_SCRIPTS[k])
def init_textdetector_registries(): init_module_registries('textdetector')
def init_inpainter_registries(): init_module_registries('inpainter')
def init_ocr_registries(): init_module_registries('ocr')
def init_translator_registries(): init_module_registries('translator')
1from .base import *123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259from typing import List, Optionalimport torchimport torch.nn as nnimport torch.nn.functional as Fimport numpy as npimport cv2from typing import List, Optionalimport torchimport torch.nn as nnimport torch.nn.functional as F
from utils.imgproc_utils import resize_keepasp
def relu_nf(x) : return F.relu(x) * 1.7139588594436646
def gelu_nf(x) : return F.gelu(x) * 1.7015043497085571
def silu_nf(x) : return F.silu(x) * 1.7881293296813965
class LambdaLayer(nn.Module) : def __init__(self, f): super(LambdaLayer, self).__init__() self.f = f
def forward(self, x) : return self.f(x)
class ScaledWSConv2d(nn.Conv2d): """2D Conv layer with Scaled Weight Standardization.""" def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, gain=True, eps=1e-4): nn.Conv2d.__init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias) #nn.init.kaiming_normal_(self.weight) if gain: self.gain = nn.Parameter(torch.ones(self.out_channels, 1, 1, 1)) else: self.gain = None # Epsilon, a small constant to avoid dividing by zero. self.eps = eps def get_weight(self): # Get Scaled WS weight OIHW; fan_in = np.prod(self.weight.shape[1:]) var, mean = torch.var_mean(self.weight, dim=(1, 2, 3), keepdims=True) scale = torch.rsqrt(torch.max( var * fan_in, torch.tensor(self.eps).to(var.device))) * self.gain.view_as(var).to(var.device) shift = mean * scale return self.weight * scale - shift def forward(self, x): return F.conv2d(x, self.get_weight(), self.bias, self.stride, self.padding, self.dilation, self.groups)
class ScaledWSTransposeConv2d(nn.ConvTranspose2d): """2D Transpose Conv layer with Scaled Weight Standardization.""" def __init__(self, in_channels: int, out_channels: int, kernel_size, stride = 1, padding = 0, output_padding = 0, groups: int = 1, bias: bool = True, dilation: int = 1, gain=True, eps=1e-4): nn.ConvTranspose2d.__init__(self, in_channels, out_channels, kernel_size, stride, padding, output_padding, groups, bias, dilation, 'zeros') #nn.init.kaiming_normal_(self.weight) if gain: self.gain = nn.Parameter(torch.ones(self.in_channels, 1, 1, 1)) else: self.gain = None # Epsilon, a small constant to avoid dividing by zero. self.eps = eps def get_weight(self): # Get Scaled WS weight OIHW; fan_in = np.prod(self.weight.shape[1:]) var, mean = torch.var_mean(self.weight, dim=(1, 2, 3), keepdims=True) scale = torch.rsqrt(torch.max( var * fan_in, torch.tensor(self.eps).to(var.device))) * self.gain.view_as(var).to(var.device) shift = mean * scale return self.weight * scale - shift def forward(self, x, output_size: Optional[List[int]] = None): output_padding = self._output_padding( input, output_size, self.stride, self.padding, self.kernel_size, self.dilation) return F.conv_transpose2d(x, self.get_weight(), self.bias, self.stride, self.padding, output_padding, self.groups, self.dilation)
class GatedWSConvPadded(nn.Module) : def __init__(self, in_ch, out_ch, ks, stride = 1, dilation = 1) : super(GatedWSConvPadded, self).__init__() self.in_ch = in_ch self.out_ch = out_ch self.padding = nn.ReflectionPad2d(((ks - 1) * dilation) // 2) self.conv = ScaledWSConv2d(in_ch, out_ch, kernel_size = ks, stride = stride, dilation = dilation) self.conv_gate = ScaledWSConv2d(in_ch, out_ch, kernel_size = ks, stride = stride, dilation = dilation)
def forward(self, x) : x = self.padding(x) signal = self.conv(x) gate = torch.sigmoid(self.conv_gate(x)) return signal * gate * 1.8
class GatedWSTransposeConvPadded(nn.Module) : def __init__(self, in_ch, out_ch, ks, stride = 1) : super(GatedWSTransposeConvPadded, self).__init__() self.in_ch = in_ch self.out_ch = out_ch self.conv = ScaledWSTransposeConv2d(in_ch, out_ch, kernel_size = ks, stride = stride, padding = (ks - 1) // 2) self.conv_gate = ScaledWSTransposeConv2d(in_ch, out_ch, kernel_size = ks, stride = stride, padding = (ks - 1) // 2)
def forward(self, x) : signal = self.conv(x) gate = torch.sigmoid(self.conv_gate(x)) return signal * gate * 1.8
class ResBlock(nn.Module) : def __init__(self, ch, alpha = 0.2, beta = 1.0, dilation = 1) : super(ResBlock, self).__init__() self.alpha = alpha self.beta = beta self.c1 = GatedWSConvPadded(ch, ch, 3, dilation = dilation) self.c2 = GatedWSConvPadded(ch, ch, 3, dilation = dilation)
def forward(self, x) : skip = x x = self.c1(relu_nf(x / self.beta)) x = self.c2(relu_nf(x)) x = x * self.alpha return x + skip
def my_layer_norm(feat): mean = feat.mean((2, 3), keepdim=True) std = feat.std((2, 3), keepdim=True) + 1e-9 feat = 2 * (feat - mean) / std - 1 feat = 5 * feat return feat
class AOTBlock(nn.Module): def __init__(self, dim, rates = [2, 4, 8, 16]): super(AOTBlock, self).__init__() self.rates = rates for i, rate in enumerate(rates): self.__setattr__( 'block{}'.format(str(i).zfill(2)), nn.Sequential( nn.ReflectionPad2d(rate), nn.Conv2d(dim, dim//4, 3, padding=0, dilation=rate), nn.ReLU(True))) self.fuse = nn.Sequential( nn.ReflectionPad2d(1), nn.Conv2d(dim, dim, 3, padding=0, dilation=1)) self.gate = nn.Sequential( nn.ReflectionPad2d(1), nn.Conv2d(dim, dim, 3, padding=0, dilation=1))
def forward(self, x): out = [self.__getattr__(f'block{str(i).zfill(2)}')(x) for i in range(len(self.rates))] out = torch.cat(out, 1) out = self.fuse(out) mask = my_layer_norm(self.gate(x)) mask = torch.sigmoid(mask) return x * (1 - mask) + out * mask
class ResBlockDis(nn.Module): def __init__(self, in_planes, planes, stride=1): super(ResBlockDis, self).__init__() self.bn1 = nn.InstanceNorm2d(in_planes) self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3 if stride == 1 else 4, stride=stride, padding=1) self.bn2 = nn.InstanceNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1) self.planes = planes self.in_planes = in_planes self.stride = stride
self.shortcut = nn.Sequential() if stride > 1 : self.shortcut = nn.Sequential(nn.AvgPool2d(2, 2), nn.Conv2d(in_planes, planes, kernel_size=1)) elif in_planes != planes and stride == 1 : self.shortcut = nn.Sequential(nn.Conv2d(in_planes, planes, kernel_size=1))
def forward(self, x): sc = self.shortcut(x) x = self.conv1(F.leaky_relu(self.bn1(x), 0.2)) x = self.conv2(F.leaky_relu(self.bn2(x), 0.2)) return sc + xfrom torch.nn.utils import spectral_normclass Discriminator(nn.Module) : def __init__(self, in_ch = 3, in_planes = 64, blocks = [2, 2, 2], alpha = 0.2) : super(Discriminator, self).__init__() self.in_planes = in_planes
self.conv = nn.Sequential( spectral_norm(nn.Conv2d(in_ch, in_planes, 4, stride=2, padding=1, bias=False)), nn.LeakyReLU(0.2, inplace=True), spectral_norm(nn.Conv2d(in_planes, in_planes*2, 4, stride=2, padding=1, bias=False)), nn.LeakyReLU(0.2, inplace=True), spectral_norm(nn.Conv2d(in_planes*2, in_planes*4, 4, stride=2, padding=1, bias=False)), nn.LeakyReLU(0.2, inplace=True), spectral_norm(nn.Conv2d(in_planes*4, in_planes*8, 4, stride=1, padding=1, bias=False)), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(512, 1, 4, stride=1, padding=1) )
def forward(self, x) : x = self.conv(x) return x
class AOTGenerator(nn.Module) : def __init__(self, in_ch = 4, out_ch = 3, ch = 32, alpha = 0.0) : super(AOTGenerator, self).__init__()
self.head = nn.Sequential( GatedWSConvPadded(in_ch, ch, 3, stride = 1), LambdaLayer(relu_nf), GatedWSConvPadded(ch, ch * 2, 4, stride = 2), LambdaLayer(relu_nf), GatedWSConvPadded(ch * 2, ch * 4, 4, stride = 2), )
self.body_conv = nn.Sequential(*[AOTBlock(ch * 4) for _ in range(10)])
self.tail = nn.Sequential( GatedWSConvPadded(ch * 4, ch * 4, 3, 1), LambdaLayer(relu_nf), GatedWSConvPadded(ch * 4, ch * 4, 3, 1), LambdaLayer(relu_nf), GatedWSTransposeConvPadded(ch * 4, ch * 2, 4, 2), LambdaLayer(relu_nf), GatedWSTransposeConvPadded(ch * 2, ch, 4, 2), LambdaLayer(relu_nf), GatedWSConvPadded(ch, out_ch, 3, stride = 1), )
def forward(self, img, mask) : x = torch.cat([mask, img], dim = 1) x = self.head(x) conv = self.body_conv(x) x = self.tail(conv) if self.training : return x else : return torch.clip(x, -1, 1)
def load_aot_model(model_path, device) -> AOTGenerator: model = AOTGenerator(in_ch=4, out_ch=3, ch=32, alpha=0.0) sd = torch.load(model_path, map_location = 'cpu') model.load_state_dict(sd['model'] if 'model' in sd else sd) model.eval().to(device) return model123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604import numpy as npimport cv2from typing import Dict, Listfrom collections import OrderedDictimport sys
from utils.registry import Registryfrom utils.textblock_mask import extract_ballon_maskfrom utils.imgproc_utils import enlarge_window
from ..base import BaseModule, DEFAULT_DEVICE, soft_empty_cache, DEVICE_SELECTOR, GPUINTENSIVE_SET, TORCH_DTYPE_MAP, BF16_SUPPORTEDfrom ..textdetector import TextBlock
INPAINTERS = Registry('inpainters')register_inpainter = INPAINTERS.register_module
def inpaint_handle_alpha_channel(original_alpha, mask): ''' perhaps a better idea is to feed the alpha into inpainting model, but it'll double the cost for now it just return the original alpha '''
result_alpha = original_alpha.copy()
# Analyze the alpha values around the original mask to determine appropriate transparency mask_dilated = cv2.dilate((mask > 127).astype(np.uint8), np.ones((15, 15), np.uint8), iterations=1) surrounding_mask = mask_dilated - (mask > 127).astype(np.uint8)
if np.any(surrounding_mask > 0): surrounding_alpha = original_alpha[surrounding_mask > 0] if len(surrounding_alpha) > 0: median_surrounding_alpha = np.median(surrounding_alpha) # If surrounding area is mostly transparent (median alpha < 128), # make inpainted areas transparent too if median_surrounding_alpha < 128: inpainted_mask = (mask > 127) result_alpha[inpainted_mask] = median_surrounding_alpha
return result_alpha
class InpainterBase(BaseModule):
inpaint_by_block = True check_need_inpaint = True
_postprocess_hooks = OrderedDict() _preprocess_hooks = OrderedDict()
def __init__(self, **params) -> None: super().__init__(**params) self.name = '' for key in INPAINTERS.module_dict: if INPAINTERS.module_dict[key] == self.__class__: self.name = key break def memory_safe_inpaint(self, img: np.ndarray, mask: np.ndarray, textblock_list: List[TextBlock] = None) -> np.ndarray: ''' handle cuda out of memory ''' try: return self._inpaint(img, mask, textblock_list) except Exception as e: if DEFAULT_DEVICE == 'cuda' and isinstance(e, torch.cuda.OutOfMemoryError): soft_empty_cache() try: return self._inpaint(img, mask, textblock_list) except Exception as ee: if isinstance(ee, torch.cuda.OutOfMemoryError): self.logger.warning(f'CUDA out of memory while calling {self.name}, fall back to cpu...\n\ if running into it frequently, consider lowering the inpaint_size') self.moveToDevice('cpu') inpainted = self._inpaint(img, mask, textblock_list) precision = None if hasattr(self, 'precision'): precision = self.precision self.moveToDevice('cuda', precision)
return inpainted else: raise e
def inpaint(self, img: np.ndarray, mask: np.ndarray, textblock_list: List[TextBlock] = None, check_need_inpaint: bool = False) -> np.ndarray: if not self.all_model_loaded(): self.load_model() # Handle RGBA images by preserving alpha channel original_alpha = None if len(img.shape) == 3 and img.shape[2] == 4: original_alpha = img[:, :, 3:4] # Keep alpha channel img_rgb = img[:, :, :3] # Use only RGB for inpainting else: img_rgb = img if not self.inpaint_by_block or textblock_list is None: if check_need_inpaint: ballon_msk, non_text_msk = extract_ballon_mask(img_rgb, mask) if ballon_msk is not None: non_text_region = np.where(non_text_msk > 0) non_text_px = img_rgb[non_text_region] average_bg_color = np.median(non_text_px, axis=0) std_rgb = np.std(non_text_px - average_bg_color, axis=0) std_max = np.max(std_rgb) inpaint_thresh = 7 if np.std(std_rgb) > 1 else 10 if std_max < inpaint_thresh: result_rgb = img_rgb.copy() result_rgb[np.where(ballon_msk > 0)] = average_bg_color # Recombine with alpha if original was RGBA if original_alpha is not None: return np.concatenate([result_rgb, original_alpha], axis=2) return result_rgb result_rgb = self.memory_safe_inpaint(img_rgb, mask, textblock_list) # Recombine with alpha if original was RGBA if original_alpha is not None: result_alpha = inpaint_handle_alpha_channel(original_alpha, mask) return np.concatenate([result_rgb, result_alpha], axis=2) return result_rgb else: im_h, im_w = img_rgb.shape[:2] inpainted = np.copy(img_rgb) # Preserve original mask for transparency analysis original_mask = mask.copy() for blk in textblock_list: xyxy = blk.xyxy xyxy_e = enlarge_window(xyxy, im_w, im_h, ratio=1.7) im = inpainted[xyxy_e[1]:xyxy_e[3], xyxy_e[0]:xyxy_e[2]] msk = mask[xyxy_e[1]:xyxy_e[3], xyxy_e[0]:xyxy_e[2]] need_inpaint = True if self.check_need_inpaint or check_need_inpaint: ballon_msk, non_text_msk = extract_ballon_mask(im, msk) if ballon_msk is not None: non_text_region = np.where(non_text_msk > 0) non_text_px = im[non_text_region] average_bg_color = np.median(non_text_px, axis=0) std_rgb = np.std(non_text_px - average_bg_color, axis=0) std_max = np.max(std_rgb) inpaint_thresh = 7 if np.std(std_rgb) > 1 else 10 if std_max < inpaint_thresh: need_inpaint = False im[np.where(ballon_msk > 0)] = average_bg_color # cv2.imshow('im', im) # cv2.imshow('ballon', ballon_msk) # cv2.imshow('non_text', non_text_msk) # cv2.waitKey(0) if need_inpaint: inpainted[xyxy_e[1]:xyxy_e[3], xyxy_e[0]:xyxy_e[2]] = self.memory_safe_inpaint(im, msk)
mask[xyxy[1]:xyxy[3], xyxy[0]:xyxy[2]] = 0 # Recombine with alpha if original was RGBA if original_alpha is not None: result_alpha = inpaint_handle_alpha_channel(original_alpha, original_mask) return np.concatenate([inpainted, result_alpha], axis=2) return inpainted
def _inpaint(self, img: np.ndarray, mask: np.ndarray, textblock_list: List[TextBlock] = None) -> np.ndarray: raise NotImplementedError def moveToDevice(self, device: str, precision: str = None): raise not NotImplementedError
@register_inpainter('opencv-tela')class OpenCVInpainter(InpainterBase):
def __init__(self, **params) -> None: super().__init__(**params) self.inpaint_method = lambda img, mask, *args, **kwargs: cv2.inpaint(img, mask, 3, cv2.INPAINT_NS) def _inpaint(self, img: np.ndarray, mask: np.ndarray, textblock_list: List[TextBlock] = None) -> np.ndarray: return self.inpaint_method(img, mask)
def is_computational_intensive(self) -> bool: return True def is_cpu_intensive(self) -> bool: return True
@register_inpainter('patchmatch')class PatchmatchInpainter(InpainterBase):
if sys.platform == 'darwin': download_file_list = [{ 'url': 'https://github.com/dmMaze/PyPatchMatchInpaint/releases/download/v1.0/macos_arm64_patchmatch_libs.7z', 'sha256_pre_calculated': ['843704ab096d3afd8709abe2a2c525ce3a836bb0a629ed1ee9b8f5cee9938310', '849ca84759385d410c9587d69690e668822a3fc376ce2219e583e7e0be5b5e9a'], 'files': ['macos_libopencv_world.4.8.0.dylib', 'macos_libpatchmatch_inpaint.dylib'], 'save_dir': 'data/libs', 'archived_files': 'macos_patchmatch_libs.7z', 'archive_sha256_pre_calculated': '9f332c888be0f160dbe9f6d6887eb698a302e62f4c102a0f24359c540d5858ea' }] elif sys.platform == 'win32': download_file_list = [{ 'url': 'https://github.com/dmMaze/PyPatchMatchInpaint/releases/download/v1.0/windows_patchmatch_libs.7z', 'sha256_pre_calculated': ['3b7619caa29dc3352b939de4e9981217a9585a13a756e1101a50c90c100acd8d', '0ba60cfe664c97629daa7e4d05c0888ebfe3edcb3feaf1ed5a14544079c6d7af'], 'files': ['opencv_world455.dll', 'patchmatch_inpaint.dll'], 'save_dir': 'data/libs', 'archived_files': 'windows_patchmatch_libs.7z', 'archive_sha256_pre_calculated': 'c991ff61f7cb3efaf8e75d957e62d56ba646083bc25535f913ac65775c16ca65' }]
def __init__(self, **params) -> None: super().__init__(**params) from . import patch_match self.inpaint_method = lambda img, mask, *args, **kwargs: patch_match.inpaint(img, mask, patch_size=3) def _inpaint(self, img: np.ndarray, mask: np.ndarray, textblock_list: List[TextBlock] = None) -> np.ndarray: return self.inpaint_method(img, mask)
def is_computational_intensive(self) -> bool: return True def is_cpu_intensive(self) -> bool: return True
import torchfrom utils.imgproc_utils import resize_keepaspfrom .aot import AOTGenerator, load_aot_model
@register_inpainter('aot')class AOTInpainter(InpainterBase):
params = { 'inpaint_size': { 'type': 'selector', 'options': [ 1024, 2048 ], 'value': 2048 }, 'device': DEVICE_SELECTOR(), 'description': 'manga-image-translator inpainter' }
device = DEFAULT_DEVICE inpaint_size = 2048 model: AOTGenerator = None _load_model_keys = {'model'}
download_file_list = [{ 'url': 'https://github.com/zyddnys/manga-image-translator/releases/download/beta-0.3/inpainting.ckpt', 'sha256_pre_calculated': '878d541c68648969bc1b042a6e997f3a58e49b6c07c5636ad55130736977149f', 'files': 'data/models/aot_inpainter.ckpt', }]
def __init__(self, **params) -> None: super().__init__(**params) self.device = self.params['device']['value'] self.inpaint_size = int(self.params['inpaint_size']['value']) self.model: AOTGenerator = None def _load_model(self): AOTMODEL_PATH = 'data/models/aot_inpainter.ckpt' self.model = load_aot_model(AOTMODEL_PATH, self.device)
def moveToDevice(self, device: str, precision: str = None): self.model.to(device) self.device = device
def inpaint_preprocess(self, img: np.ndarray, mask: np.ndarray) -> np.ndarray:
img_original = np.copy(img) mask_original = np.copy(mask) mask_original[mask_original < 127] = 0 mask_original[mask_original >= 127] = 1 mask_original = mask_original[:, :, None]
new_shape = self.inpaint_size if max(img.shape[0: 2]) > self.inpaint_size else None
img = resize_keepasp(img, new_shape, stride=None) mask = resize_keepasp(mask, new_shape, stride=None)
im_h, im_w = img.shape[:2] pad_bottom = 128 - im_h if im_h < 128 else 0 pad_right = 128 - im_w if im_w < 128 else 0 mask = cv2.copyMakeBorder(mask, 0, pad_bottom, 0, pad_right, cv2.BORDER_REFLECT) img = cv2.copyMakeBorder(img, 0, pad_bottom, 0, pad_right, cv2.BORDER_REFLECT)
img_torch = torch.from_numpy(img).permute(2, 0, 1).unsqueeze_(0).float() / 127.5 - 1.0 mask_torch = torch.from_numpy(mask).unsqueeze_(0).unsqueeze_(0).float() / 255.0 mask_torch[mask_torch < 0.5] = 0 mask_torch[mask_torch >= 0.5] = 1
if self.device != 'cpu': img_torch = img_torch.to(self.device) mask_torch = mask_torch.to(self.device) img_torch *= (1 - mask_torch) return img_torch, mask_torch, img_original, mask_original, pad_bottom, pad_right
@torch.no_grad() def _inpaint(self, img: np.ndarray, mask: np.ndarray, textblock_list: List[TextBlock] = None) -> np.ndarray:
im_h, im_w = img.shape[:2] img_torch, mask_torch, img_original, mask_original, pad_bottom, pad_right = self.inpaint_preprocess(img, mask) img_inpainted_torch = self.model(img_torch, mask_torch) img_inpainted = ((img_inpainted_torch.cpu().squeeze_(0).permute(1, 2, 0).numpy() + 1.0) * 127.5) img_inpainted = (np.clip(np.round(img_inpainted), 0, 255)).astype(np.uint8) if pad_bottom > 0: img_inpainted = img_inpainted[:-pad_bottom] if pad_right > 0: img_inpainted = img_inpainted[:, :-pad_right] new_shape = img_inpainted.shape[:2] if new_shape[0] != im_h or new_shape[1] != im_w : img_inpainted = cv2.resize(img_inpainted, (im_w, im_h), interpolation = cv2.INTER_LINEAR) img_inpainted = img_inpainted * mask_original + img_original * (1 - mask_original) return img_inpainted
def updateParam(self, param_key: str, param_content): super().updateParam(param_key, param_content)
if param_key == 'device': param_device = self.params['device']['value'] if self.model is not None: self.model.to(param_device) self.device = param_device
elif param_key == 'inpaint_size': self.inpaint_size = int(self.params['inpaint_size']['value'])
from .lama import LamaFourier, load_lama_mpe
@register_inpainter('lama_mpe')class LamaInpainterMPE(InpainterBase):
params = { 'inpaint_size': { 'type': 'selector', 'options': [ 1024, 2048 ], 'value': 2048 }, 'device': DEVICE_SELECTOR(not_supported=['privateuseone']) }
download_file_list = [{ 'url': 'https://github.com/zyddnys/manga-image-translator/releases/download/beta-0.3/inpainting_lama_mpe.ckpt', 'sha256_pre_calculated': 'd625aa1b3e0d0408acfd6928aa84f005867aa8dbb9162480346a4e20660786cc', 'files': 'data/models/lama_mpe.ckpt', }] _load_model_keys = {'model'}
def __init__(self, **params) -> None: super().__init__(**params) self.device = self.params['device']['value'] self.inpaint_size = int(self.params['inpaint_size']['value']) self.precision = 'fp32' self.model: LamaFourier = None
def _load_model(self): self.model = load_lama_mpe(r'data/models/lama_mpe.ckpt', self.device)
def inpaint_preprocess(self, img: np.ndarray, mask: np.ndarray) -> np.ndarray:
img_original = np.copy(img) mask_original = np.copy(mask) mask_original[mask_original < 127] = 0 mask_original[mask_original >= 127] = 1 mask_original = mask_original[:, :, None]
new_shape = self.inpaint_size if max(img.shape[0: 2]) > self.inpaint_size else None # high resolution input could produce cloudy artifacts img = resize_keepasp(img, new_shape, stride=64) mask = resize_keepasp(mask, new_shape, stride=64)
im_h, im_w = img.shape[:2] longer = max(im_h, im_w) pad_bottom = longer - im_h if im_h < longer else 0 pad_right = longer - im_w if im_w < longer else 0 mask = cv2.copyMakeBorder(mask, 0, pad_bottom, 0, pad_right, cv2.BORDER_REFLECT) img = cv2.copyMakeBorder(img, 0, pad_bottom, 0, pad_right, cv2.BORDER_REFLECT)
img_torch = torch.from_numpy(img).permute(2, 0, 1).unsqueeze_(0).float() / 255.0 mask_torch = torch.from_numpy(mask).unsqueeze_(0).unsqueeze_(0).float() / 255.0 mask_torch[mask_torch < 0.5] = 0 mask_torch[mask_torch >= 0.5] = 1 rel_pos, _, direct = self.model.load_masked_position_encoding(mask_torch[0][0].numpy()) rel_pos = torch.LongTensor(rel_pos).unsqueeze_(0) direct = torch.LongTensor(direct).unsqueeze_(0)
if self.device != 'cpu': img_torch = img_torch.to(self.device) mask_torch = mask_torch.to(self.device) rel_pos = rel_pos.to(self.device) direct = direct.to(self.device) img_torch *= (1 - mask_torch) return img_torch, mask_torch, rel_pos, direct, img_original, mask_original, pad_bottom, pad_right
@torch.no_grad() def _inpaint(self, img: np.ndarray, mask: np.ndarray, textblock_list: List[TextBlock] = None) -> np.ndarray:
im_h, im_w = img.shape[:2] img_torch, mask_torch, rel_pos, direct, img_original, mask_original, pad_bottom, pad_right = self.inpaint_preprocess(img, mask) precision = TORCH_DTYPE_MAP[self.precision] if self.device in {'cuda'}: try: with torch.autocast(device_type=self.device, dtype=precision): img_inpainted_torch = self.model(img_torch, mask_torch, rel_pos, direct) except Exception as e: self.logger.error(e) self.logger.error(f'{precision} inference is not supported for this device, use fp32 instead.') img_inpainted_torch = self.model(img_torch, mask_torch, rel_pos, direct) else: img_inpainted_torch = self.model(img_torch, mask_torch, rel_pos, direct)
img_inpainted = (img_inpainted_torch.to(device='cpu', dtype=torch.float32).squeeze_(0).permute(1, 2, 0).numpy() * 255) img_inpainted = (np.clip(np.round(img_inpainted), 0, 255)).astype(np.uint8) if pad_bottom > 0: img_inpainted = img_inpainted[:-pad_bottom] if pad_right > 0: img_inpainted = img_inpainted[:, :-pad_right] new_shape = img_inpainted.shape[:2] if new_shape[0] != im_h or new_shape[1] != im_w : img_inpainted = cv2.resize(img_inpainted, (im_w, im_h), interpolation = cv2.INTER_LINEAR) img_inpainted = img_inpainted * mask_original + img_original * (1 - mask_original) return img_inpainted
def updateParam(self, param_key: str, param_content): super().updateParam(param_key, param_content)
if param_key == 'device': param_device = self.params['device']['value'] if self.model is not None: self.model.to(param_device) self.device = param_device
elif param_key == 'inpaint_size': self.inpaint_size = int(self.params['inpaint_size']['value'])
elif param_key == 'precision': precision = self.params['precision']['value'] self.precision = precision
def moveToDevice(self, device: str, precision: str = None): self.model.to(device) self.device = device if precision is not None: self.precision = precision
@register_inpainter('lama_large_512px')class LamaLarge(LamaInpainterMPE):
params = { 'inpaint_size': { 'type': 'selector', 'options': [ 512, 768, 1024, 1536, 2048 ], 'value': 1536, }, 'device': DEVICE_SELECTOR(not_supported=['privateuseone']), 'precision': { 'type': 'selector', 'options': [ 'fp32', 'bf16' ], 'value': 'bf16' if BF16_SUPPORTED == 'cuda' else 'fp32' }, }
download_file_list = [{ 'url': 'https://huggingface.co/dreMaz/AnimeMangaInpainting/resolve/main/lama_large_512px.ckpt', 'sha256_pre_calculated': '11d30fbb3000fb2eceae318b75d9ced9229d99ae990a7f8b3ac35c8d31f2c935', 'files': 'data/models/lama_large_512px.ckpt', }]
def __init__(self, **params) -> None: super().__init__(**params) self.precision = self.params['precision']['value']
def _load_model(self): device = self.params['device']['value'] precision = self.params['precision']['value']
self.model = load_lama_mpe(r'data/models/lama_large_512px.ckpt', device='cpu', use_mpe=False, large_arch=True) self.moveToDevice(device, precision=precision)
# LAMA_ORI: LamaFourier = None# @register_inpainter('lama_ori')# class LamaInpainterORI(InpainterBase):
# params = {# 'inpaint_size': {# 'type': 'selector',# 'options': [# 1024, # 2048# ], # 'value': 2048# }, # 'device': {# 'type': 'selector',# 'options': [# 'cpu',# 'cuda'# ],# 'value': DEFAULT_DEVICE# }# }
# device = DEFAULT_DEVICE# inpaint_size = 2048
# def setup_inpainter(self):# global LAMA_ORI
# self.device = self.params['device']['value']# if LAMA_ORI is None:# self.model = LAMA_ORI = load_lama_mpe(r'data/models/lama_org.ckpt', self.device, False)# else:# self.model = LAMA_ORI# self.model.to(self.device)# self.inpaint_by_block = True if self.device == 'cuda' else False# self.inpaint_size = int(self.params['inpaint_size']['value'])
# def inpaint_preprocess(self, img: np.ndarray, mask: np.ndarray) -> np.ndarray:
# img_original = np.copy(img)# mask_original = np.copy(mask)# mask_original[mask_original < 127] = 0# mask_original[mask_original >= 127] = 1# mask_original = mask_original[:, :, None]
# new_shape = self.inpaint_size if max(img.shape[0: 2]) > self.inpaint_size else None# # high resolution input could produce cloudy artifacts# img = resize_keepasp(img, new_shape, stride=64)# mask = resize_keepasp(mask, new_shape, stride=64)
# im_h, im_w = img.shape[:2]# longer = max(im_h, im_w)# pad_bottom = longer - im_h if im_h < longer else 0# pad_right = longer - im_w if im_w < longer else 0# mask = cv2.copyMakeBorder(mask, 0, pad_bottom, 0, pad_right, cv2.BORDER_REFLECT)# img = cv2.copyMakeBorder(img, 0, pad_bottom, 0, pad_right, cv2.BORDER_REFLECT)
# img_torch = torch.from_numpy(img).permute(2, 0, 1).unsqueeze_(0).float() / 255.0# mask_torch = torch.from_numpy(mask).unsqueeze_(0).unsqueeze_(0).float() / 255.0# mask_torch[mask_torch < 0.5] = 0# mask_torch[mask_torch >= 0.5] = 1# rel_pos, _, direct = self.model.load_masked_position_encoding(mask_torch[0][0].numpy())# rel_pos = torch.LongTensor(rel_pos).unsqueeze_(0)# direct = torch.LongTensor(direct).unsqueeze_(0)
# if self.device == 'cuda':# img_torch = img_torch.cuda()# mask_torch = mask_torch.cuda()# rel_pos = rel_pos.cuda()# direct = direct.cuda()# img_torch *= (1 - mask_torch)# return img_torch, mask_torch, rel_pos, direct, img_original, mask_original, pad_bottom, pad_right
# @torch.no_grad()# def _inpaint(self, img: np.ndarray, mask: np.ndarray, textblock_list: List[TextBlock] = None) -> np.ndarray:
# im_h, im_w = img.shape[:2]# img_torch, mask_torch, rel_pos, direct, img_original, mask_original, pad_bottom, pad_right = self.inpaint_preprocess(img, mask)# img_inpainted_torch = self.model(img_torch, mask_torch, rel_pos, direct) # img_inpainted = (img_inpainted_torch.cpu().squeeze_(0).permute(1, 2, 0).numpy() * 255).astype(np.uint8)# if pad_bottom > 0:# img_inpainted = img_inpainted[:-pad_bottom]# if pad_right > 0:# img_inpainted = img_inpainted[:, :-pad_right]# new_shape = img_inpainted.shape[:2]# if new_shape[0] != im_h or new_shape[1] != im_w :# img_inpainted = cv2.resize(img_inpainted, (im_w, im_h), interpolation = cv2.INTER_LINEAR)# img_inpainted = img_inpainted * mask_original + img_original * (1 - mask_original) # return img_inpainted
# def updateParam(self, param_key: str, param_content):# super().updateParam(param_key, param_content)
# if param_key == 'device':# param_device = self.params['device']['value']# self.model.to(param_device)# self.device = param_device# if param_device == 'cuda':# self.inpaint_by_block = False# else:# self.inpaint_by_block = True
# elif param_key == 'inpaint_size':# self.inpaint_size = int(self.params['inpaint_size']['value'])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312# Fast Fourier Convolution NeurIPS 2020# original implementation https://github.com/pkumivision/FFC/blob/main/model_zoo/ffc.py# paper https://proceedings.neurips.cc/paper/2020/file/2fd5d41ec6cfab47e32164d5624269b1-Paper.pdf
import torchimport torch.nn as nnimport torch.nn.functional as F
class FFCSE_block(nn.Module):
def __init__(self, channels, ratio_g): super(FFCSE_block, self).__init__() in_cg = int(channels * ratio_g) in_cl = channels - in_cg r = 16
self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.conv1 = nn.Conv2d(channels, channels // r, kernel_size=1, bias=True) self.relu1 = nn.ReLU(inplace=True) self.conv_a2l = None if in_cl == 0 else nn.Conv2d( channels // r, in_cl, kernel_size=1, bias=True) self.conv_a2g = None if in_cg == 0 else nn.Conv2d( channels // r, in_cg, kernel_size=1, bias=True) self.sigmoid = nn.Sigmoid()
def forward(self, x): x = x if type(x) is tuple else (x, 0) id_l, id_g = x
x = id_l if type(id_g) is int else torch.cat([id_l, id_g], dim=1) x = self.avgpool(x) x = self.relu1(self.conv1(x))
x_l = 0 if self.conv_a2l is None else id_l * \ self.sigmoid(self.conv_a2l(x)) x_g = 0 if self.conv_a2g is None else id_g * \ self.sigmoid(self.conv_a2g(x)) return x_l, x_g
FFT_OP_SUPPORT = True
class FourierUnit(nn.Module):
def __init__(self, in_channels, out_channels, groups=1, spatial_scale_factor=None, spatial_scale_mode='bilinear', spectral_pos_encoding=False, use_se=False, se_kwargs=None, ffc3d=False, fft_norm='ortho'): # bn_layer not used super(FourierUnit, self).__init__() self.groups = groups
self.conv_layer = torch.nn.Conv2d(in_channels=in_channels * 2 + (2 if spectral_pos_encoding else 0), out_channels=out_channels * 2, kernel_size=1, stride=1, padding=0, groups=self.groups, bias=False) self.bn = torch.nn.BatchNorm2d(out_channels * 2) self.relu = torch.nn.ReLU(inplace=True)
# squeeze and excitation block self.use_se = use_se # if use_se: # if se_kwargs is None: # se_kwargs = {} # self.se = SELayer(self.conv_layer.in_channels, **se_kwargs)
self.spatial_scale_factor = spatial_scale_factor self.spatial_scale_mode = spatial_scale_mode self.spectral_pos_encoding = spectral_pos_encoding self.ffc3d = ffc3d self.fft_norm = fft_norm
def forward(self, x): batch = x.shape[0] input_dtype = x.dtype
if self.spatial_scale_factor is not None: orig_size = x.shape[-2:] x = F.interpolate(x, scale_factor=self.spatial_scale_factor, mode=self.spatial_scale_mode, align_corners=False)
r_size = x.size() # (batch, c, h, w/2+1, 2) fft_dim = (-3, -2, -1) if self.ffc3d else (-2, -1)
if x.dtype in (torch.float16, torch.bfloat16): x = x.type(torch.float32)
global FFT_OP_SUPPORT if FFT_OP_SUPPORT: try: ffted = torch.fft.rfftn(x, dim=fft_dim, norm=self.fft_norm) except: FFT_OP_SUPPORT = False print(f'FFT OP not supported with this card, try run it with cpu...') if not FFT_OP_SUPPORT: # dont use else, it would not be the same ffted = torch.fft.rfftn(x.to(device='cpu', dtype=torch.float32), dim=fft_dim, norm=self.fft_norm).to( device=x.device)
ffted = torch.stack((ffted.real, ffted.imag), dim=-1) ffted = ffted.permute(0, 1, 4, 2, 3).contiguous() # (batch, c, 2, h, w/2+1) ffted = ffted.view((batch, -1,) + ffted.size()[3:])
if self.spectral_pos_encoding: height, width = ffted.shape[-2:] coords_vert = torch.linspace(0, 1, height)[None, None, :, None].expand(batch, 1, height, width).to(ffted) coords_hor = torch.linspace(0, 1, width)[None, None, None, :].expand(batch, 1, height, width).to(ffted) ffted = torch.cat((coords_vert, coords_hor, ffted), dim=1)
if self.use_se: ffted = self.se(ffted)
ffted = self.conv_layer(ffted) # (batch, c*2, h, w/2+1) ffted = self.relu(self.bn(ffted))
ffted = ffted.view((batch, -1, 2,) + ffted.size()[2:]).permute( 0, 1, 3, 4, 2).contiguous() # (batch,c, t, h, w/2+1, 2) if ffted.dtype in (torch.float16, torch.bfloat16): ffted = ffted.type(torch.float32) ffted = torch.complex(ffted[..., 0], ffted[..., 1])
ifft_shape_slice = x.shape[-3:] if self.ffc3d else x.shape[-2:] if FFT_OP_SUPPORT: output = torch.fft.irfftn(ffted, s=ifft_shape_slice, dim=fft_dim, norm=self.fft_norm) else: output = torch.fft.irfftn(ffted.to(device='cpu', dtype=torch.float32), s=ifft_shape_slice, dim=fft_dim, norm=self.fft_norm).to(device=ffted.device, dtype=input_dtype)
if self.spatial_scale_factor is not None: output = F.interpolate(output, size=orig_size, mode=self.spatial_scale_mode, align_corners=False)
return output
class SpectralTransform(nn.Module):
def __init__(self, in_channels, out_channels, stride=1, groups=1, enable_lfu=True, **fu_kwargs): # bn_layer not used super(SpectralTransform, self).__init__() self.enable_lfu = enable_lfu if stride == 2: self.downsample = nn.AvgPool2d(kernel_size=(2, 2), stride=2) else: self.downsample = nn.Identity()
self.stride = stride self.conv1 = nn.Sequential( nn.Conv2d(in_channels, out_channels // 2, kernel_size=1, groups=groups, bias=False), nn.BatchNorm2d(out_channels // 2), nn.ReLU(inplace=True) ) self.fu = FourierUnit( out_channels // 2, out_channels // 2, groups, **fu_kwargs) if self.enable_lfu: self.lfu = FourierUnit( out_channels // 2, out_channels // 2, groups) self.conv2 = torch.nn.Conv2d( out_channels // 2, out_channels, kernel_size=1, groups=groups, bias=False)
def forward(self, x):
x = self.downsample(x) x = self.conv1(x) output = self.fu(x)
if self.enable_lfu: n, c, h, w = x.shape split_no = 2 split_s = h // split_no xs = torch.cat(torch.split( x[:, :c // 4], split_s, dim=-2), dim=1).contiguous() xs = torch.cat(torch.split(xs, split_s, dim=-1), dim=1).contiguous() xs = self.lfu(xs) xs = xs.repeat(1, 1, split_no, split_no).contiguous() else: xs = 0
output = self.conv2(x + output + xs)
return output
class FFC(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, ratio_gin, ratio_gout, stride=1, padding=0, dilation=1, groups=1, bias=False, enable_lfu=True, padding_type='reflect', gated=False, **spectral_kwargs): super(FFC, self).__init__()
assert stride == 1 or stride == 2, "Stride should be 1 or 2." self.stride = stride
in_cg = int(in_channels * ratio_gin) in_cl = in_channels - in_cg out_cg = int(out_channels * ratio_gout) out_cl = out_channels - out_cg # groups_g = 1 if groups == 1 else int(groups * ratio_gout) # groups_l = 1 if groups == 1 else groups - groups_g
self.ratio_gin = ratio_gin self.ratio_gout = ratio_gout self.global_in_num = in_cg
module = nn.Identity if in_cl == 0 or out_cl == 0 else nn.Conv2d self.convl2l = module(in_cl, out_cl, kernel_size, stride, padding, dilation, groups, bias, padding_mode=padding_type) module = nn.Identity if in_cl == 0 or out_cg == 0 else nn.Conv2d self.convl2g = module(in_cl, out_cg, kernel_size, stride, padding, dilation, groups, bias, padding_mode=padding_type) module = nn.Identity if in_cg == 0 or out_cl == 0 else nn.Conv2d self.convg2l = module(in_cg, out_cl, kernel_size, stride, padding, dilation, groups, bias, padding_mode=padding_type) module = nn.Identity if in_cg == 0 or out_cg == 0 else SpectralTransform self.convg2g = module( in_cg, out_cg, stride, 1 if groups == 1 else groups // 2, enable_lfu, **spectral_kwargs)
self.gated = gated module = nn.Identity if in_cg == 0 or out_cl == 0 or not self.gated else nn.Conv2d self.gate = module(in_channels, 2, 1)
def forward(self, x): x_l, x_g = x if type(x) is tuple else (x, 0) out_xl, out_xg = 0, 0
if self.gated: total_input_parts = [x_l] if torch.is_tensor(x_g): total_input_parts.append(x_g) total_input = torch.cat(total_input_parts, dim=1)
gates = torch.sigmoid(self.gate(total_input)) g2l_gate, l2g_gate = gates.chunk(2, dim=1) else: g2l_gate, l2g_gate = 1, 1
if self.ratio_gout != 1: out_xl = self.convl2l(x_l) + self.convg2l(x_g) * g2l_gate if self.ratio_gout != 0: out_xg = self.convl2g(x_l) * l2g_gate + self.convg2g(x_g)
return out_xl, out_xg
class FFC_BN_ACT(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, ratio_gin, ratio_gout, stride=1, padding=0, dilation=1, groups=1, bias=False, norm_layer=nn.BatchNorm2d, activation_layer=nn.Identity, padding_type='reflect', enable_lfu=True, **kwargs): super(FFC_BN_ACT, self).__init__() self.ffc = FFC(in_channels, out_channels, kernel_size, ratio_gin, ratio_gout, stride, padding, dilation, groups, bias, enable_lfu, padding_type=padding_type, **kwargs) lnorm = nn.Identity if ratio_gout == 1 else norm_layer gnorm = nn.Identity if ratio_gout == 0 else norm_layer global_channels = int(out_channels * ratio_gout) self.bn_l = lnorm(out_channels - global_channels) self.bn_g = gnorm(global_channels)
lact = nn.Identity if ratio_gout == 1 else activation_layer gact = nn.Identity if ratio_gout == 0 else activation_layer self.act_l = lact(inplace=True) self.act_g = gact(inplace=True)
def forward(self, x): x_l, x_g = self.ffc(x) x_l = self.act_l(self.bn_l(x_l)) x_g = self.act_g(self.bn_g(x_g)) return x_l, x_g
class FFCResnetBlock(nn.Module): def __init__(self, dim, padding_type, norm_layer, activation_layer=nn.ReLU, dilation=1, spatial_transform_kwargs=None, inline=False, **conv_kwargs): super().__init__() self.conv1 = FFC_BN_ACT(dim, dim, kernel_size=3, padding=dilation, dilation=dilation, norm_layer=norm_layer, activation_layer=activation_layer, padding_type=padding_type, **conv_kwargs) self.conv2 = FFC_BN_ACT(dim, dim, kernel_size=3, padding=dilation, dilation=dilation, norm_layer=norm_layer, activation_layer=activation_layer, padding_type=padding_type, **conv_kwargs) # if spatial_transform_kwargs is not None: # self.conv1 = LearnableSpatialTransformWrapper(self.conv1, **spatial_transform_kwargs) # self.conv2 = LearnableSpatialTransformWrapper(self.conv2, **spatial_transform_kwargs) self.inline = inline
def forward(self, x): if self.inline: x_l, x_g = x[:, :-self.conv1.ffc.global_in_num], x[:, -self.conv1.ffc.global_in_num:] else: x_l, x_g = x if type(x) is tuple else (x, 0)
id_l, id_g = x_l, x_g
x_l, x_g = self.conv1((x_l, x_g)) x_l, x_g = self.conv2((x_l, x_g))
x_l, x_g = id_l + x_l, id_g + x_g out = x_l, x_g if self.inline: out = torch.cat(out, dim=1) return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
import torchimport torch.nn as nnfrom torch import Tensorimport numpy as npimport cv2
from .ffc import FFC_BN_ACT
def get_activation(kind='tanh'): if kind == 'tanh': return nn.Tanh() if kind == 'sigmoid': return nn.Sigmoid() if kind is False: return nn.Identity() raise ValueError(f'Unknown activation kind {kind}')
class FFCResnetBlock(nn.Module): def __init__(self, dim, padding_type, norm_layer, activation_layer=nn.ReLU, dilation=1, inline=False, **conv_kwargs): super().__init__() self.conv1 = FFC_BN_ACT(dim, dim, kernel_size=3, padding=dilation, dilation=dilation, norm_layer=norm_layer, activation_layer=activation_layer, padding_type=padding_type, **conv_kwargs) self.conv2 = FFC_BN_ACT(dim, dim, kernel_size=3, padding=dilation, dilation=dilation, norm_layer=norm_layer, activation_layer=activation_layer, padding_type=padding_type, **conv_kwargs) self.inline = inline
def forward(self, x): if self.inline: x_l, x_g = x[:, :-self.conv1.ffc.global_in_num], x[:, -self.conv1.ffc.global_in_num:] else: x_l, x_g = x if type(x) is tuple else (x, 0)
id_l, id_g = x_l, x_g
x_l, x_g = self.conv1((x_l, x_g)) x_l, x_g = self.conv2((x_l, x_g))
x_l, x_g = id_l + x_l, id_g + x_g out = x_l, x_g if self.inline: out = torch.cat(out, dim=1) return out
class ConcatTupleLayer(nn.Module): def forward(self, x): assert isinstance(x, tuple) x_l, x_g = x assert torch.is_tensor(x_l) or torch.is_tensor(x_g) if not torch.is_tensor(x_g): return x_l return torch.cat(x, dim=1)
class FFCResNetGenerator(nn.Module): def __init__(self, input_nc=4, output_nc=3, ngf=64, n_downsampling=3, n_blocks=9, norm_layer=nn.BatchNorm2d, padding_type='reflect', activation_layer=nn.ReLU, up_norm_layer=nn.BatchNorm2d, up_activation=nn.ReLU(True), init_conv_kwargs={}, downsample_conv_kwargs={}, resnet_conv_kwargs={}, spatial_transform_kwargs={}, add_out_act=True, max_features=1024, out_ffc=False, out_ffc_kwargs={}): assert (n_blocks >= 0) super().__init__()
model = [nn.ReflectionPad2d(3), FFC_BN_ACT(input_nc, ngf, kernel_size=7, padding=0, norm_layer=norm_layer, activation_layer=activation_layer, **init_conv_kwargs)]
### downsample for i in range(n_downsampling): mult = 2 ** i if i == n_downsampling - 1: cur_conv_kwargs = dict(downsample_conv_kwargs) cur_conv_kwargs['ratio_gout'] = resnet_conv_kwargs.get('ratio_gin', 0) else: cur_conv_kwargs = downsample_conv_kwargs model += [FFC_BN_ACT(min(max_features, ngf * mult), min(max_features, ngf * mult * 2), kernel_size=3, stride=2, padding=1, norm_layer=norm_layer, activation_layer=activation_layer, **cur_conv_kwargs)]
mult = 2 ** n_downsampling feats_num_bottleneck = min(max_features, ngf * mult)
### resnet blocks for i in range(n_blocks): cur_resblock = FFCResnetBlock(feats_num_bottleneck, padding_type=padding_type, activation_layer=activation_layer, norm_layer=norm_layer, **resnet_conv_kwargs) model += [cur_resblock]
model += [ConcatTupleLayer()]
### upsample for i in range(n_downsampling): mult = 2 ** (n_downsampling - i) model += [nn.ConvTranspose2d(min(max_features, ngf * mult), min(max_features, int(ngf * mult / 2)), kernel_size=3, stride=2, padding=1, output_padding=1), up_norm_layer(min(max_features, int(ngf * mult / 2))), up_activation]
if out_ffc: model += [FFCResnetBlock(ngf, padding_type=padding_type, activation_layer=activation_layer, norm_layer=norm_layer, inline=True, **out_ffc_kwargs)]
model += [nn.ReflectionPad2d(3), nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)] if add_out_act: model.append(get_activation('tanh' if add_out_act is True else add_out_act)) self.model = nn.Sequential(*model)
def forward(self, img, mask, rel_pos=None, direct=None) -> Tensor: masked_img = torch.cat([img * (1 - mask), mask], dim=1) if rel_pos is None: return self.model(masked_img) else: x_l, x_g = self.model[:2](masked_img) x_l = x_l.to(torch.float32) x_l += rel_pos x_l += direct return self.model[2:]((x_l, x_g))
class NLayerDiscriminator(nn.Module): def __init__(self, input_nc=3, ndf=64, n_layers=4, norm_layer=nn.BatchNorm2d,): super().__init__() self.n_layers = n_layers
kw = 4 padw = int(np.ceil((kw-1.0)/2)) sequence = [[nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)]]
nf = ndf for n in range(1, n_layers): nf_prev = nf nf = min(nf * 2, 512)
cur_model = [] cur_model += [ nn.Conv2d(nf_prev, nf, kernel_size=kw, stride=2, padding=padw), norm_layer(nf), nn.LeakyReLU(0.2, True) ] sequence.append(cur_model)
nf_prev = nf nf = min(nf * 2, 512)
cur_model = [] cur_model += [ nn.Conv2d(nf_prev, nf, kernel_size=kw, stride=1, padding=padw), norm_layer(nf), nn.LeakyReLU(0.2, True) ] sequence.append(cur_model)
sequence += [[nn.Conv2d(nf, 1, kernel_size=kw, stride=1, padding=padw)]]
for n in range(len(sequence)): setattr(self, 'model'+str(n), nn.Sequential(*sequence[n]))
def get_all_activations(self, x): res = [x] for n in range(self.n_layers + 2): model = getattr(self, 'model' + str(n)) res.append(model(res[-1])) return res[1:]
def forward(self, x): act = self.get_all_activations(x) return act[-1], act[:-1]
def set_requires_grad(module, value): for param in module.parameters(): param.requires_grad = value
class MaskedSinusoidalPositionalEmbedding(nn.Embedding): """This module produces sinusoidal positional embeddings of any length."""
def __init__(self, num_embeddings: int, embedding_dim: int): super().__init__(num_embeddings, embedding_dim) self.weight = self._init_weight(self.weight)
@staticmethod def _init_weight(out: nn.Parameter): """ Identical to the XLM create_sinusoidal_embeddings except features are not interleaved. The cos features are in the 2nd half of the vector. [dim // 2:] """ n_pos, dim = out.shape position_enc = np.array( [[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos)] ) out.requires_grad = False # set early to avoid an error in pytorch-1.8+ sentinel = dim // 2 if dim % 2 == 0 else (dim // 2) + 1 out[:, 0:sentinel] = torch.FloatTensor(np.sin(position_enc[:, 0::2])) out[:, sentinel:] = torch.FloatTensor(np.cos(position_enc[:, 1::2])) out.detach_() return out
@torch.no_grad() def forward(self, input_ids): """`input_ids` is expected to be [bsz x seqlen].""" return super().forward(input_ids)
class MultiLabelEmbedding(nn.Module): def __init__(self, num_positions: int, embedding_dim: int): super().__init__() self.weight = nn.Parameter(torch.Tensor(num_positions, embedding_dim)) self.reset_parameters()
def reset_parameters(self): nn.init.normal_(self.weight)
def forward(self, input_ids): # input_ids:[B,HW,4](onehot) out = torch.matmul(input_ids, self.weight) # [B,HW,dim] return out
class MPE(nn.Module): def __init__(self): super().__init__() self.rel_pos_emb = MaskedSinusoidalPositionalEmbedding(num_embeddings=128, embedding_dim=64) self.direct_emb = MultiLabelEmbedding(num_positions=4, embedding_dim=64) self.alpha5 = nn.Parameter(torch.tensor(0, dtype=torch.float32), requires_grad=True) self.alpha6 = nn.Parameter(torch.tensor(0, dtype=torch.float32), requires_grad=True)
def forward(self, rel_pos=None, direct=None): b, h, w = rel_pos.shape rel_pos = rel_pos.reshape(b, h * w) rel_pos_emb = self.rel_pos_emb(rel_pos).reshape(b, h, w, -1).permute(0, 3, 1, 2) * self.alpha5 direct = direct.reshape(b, h * w, 4).to(torch.float32) direct_emb = self.direct_emb(direct).reshape(b, h, w, -1).permute(0, 3, 1, 2) * self.alpha6 return rel_pos_emb, direct_emb
class LamaFourier: def __init__(self, build_discriminator=True, use_mpe=False, large_arch: bool = False) -> None: # super().__init__()
n_blocks = 9 if large_arch: n_blocks = 18 self.generator = FFCResNetGenerator(4, 3, add_out_act='sigmoid', n_blocks = n_blocks, init_conv_kwargs={ 'ratio_gin': 0, 'ratio_gout': 0, 'enable_lfu': False }, downsample_conv_kwargs={ 'ratio_gin': 0, 'ratio_gout': 0, 'enable_lfu': False }, resnet_conv_kwargs={ 'ratio_gin': 0.75, 'ratio_gout': 0.75, 'enable_lfu': False }, ) self.discriminator = NLayerDiscriminator() if build_discriminator else None self.inpaint_only = False if use_mpe: self.mpe = MPE() else: self.mpe = None
def train_generator(self): self.inpaint_only = False self.forward_generator = True self.forward_discriminator = False self.generator.train() self.discriminator.eval() set_requires_grad(self.discriminator, False) set_requires_grad(self.generator, True) if self.mpe is not None: set_requires_grad(self.mpe, True)
def train_discriminator(self): self.inpaint_only = False self.forward_generator = False self.forward_discriminator = True self.discriminator.train() self.generator.eval() set_requires_grad(self.discriminator, True) set_requires_grad(self.generator, False) if self.mpe is not None: set_requires_grad(self.mpe, False)
def to(self, device): self.generator.to(device) if self.discriminator is not None: self.discriminator.to(device) if self.mpe is not None: self.mpe.to(device)
def eval(self): self.inpaint_only = True self.generator.eval() if self.mpe is not None: self.mpe.eval() return self
def __call__(self, img: Tensor, mask: Tensor, rel_pos=None, direct=None):
if self.mpe is not None: rel_pos, direct = self.mpe(rel_pos, direct) else: rel_pos, direct = None, None predicted_img = self.generator(img, mask, rel_pos, direct)
if self.inpaint_only: return predicted_img * mask + (1 - mask) * img
if self.forward_discriminator: predicted_img = predicted_img.detach() img.requires_grad = True
discr_real_pred, discr_real_features = self.discriminator(img) discr_fake_pred, discr_fake_features = self.discriminator(predicted_img) # fp = discr_fake_pred.detach().mean() if self.forward_discriminator: return { 'predicted_img': predicted_img, 'discr_real_pred': discr_real_pred, 'discr_fake_pred':discr_fake_pred } else: return { 'predicted_img': predicted_img, 'discr_real_features': discr_real_features, 'discr_fake_features': discr_fake_features, 'discr_fake_pred': discr_fake_pred }
def load_masked_position_encoding(self, mask): mask = (mask * 255).astype(np.uint8) ones_filter = np.ones((3, 3), dtype=np.float32) d_filter1 = np.array([[1, 1, 0], [1, 1, 0], [0, 0, 0]], dtype=np.float32) d_filter2 = np.array([[0, 0, 0], [1, 1, 0], [1, 1, 0]], dtype=np.float32) d_filter3 = np.array([[0, 1, 1], [0, 1, 1], [0, 0, 0]], dtype=np.float32) d_filter4 = np.array([[0, 0, 0], [0, 1, 1], [0, 1, 1]], dtype=np.float32) str_size = 256 pos_num = 128
ori_mask = mask.copy() ori_h, ori_w = ori_mask.shape[0:2] ori_mask = ori_mask / 255 mask = cv2.resize(mask, (str_size, str_size), interpolation=cv2.INTER_AREA) mask[mask > 0] = 255 h, w = mask.shape[0:2] mask3 = mask.copy() mask3 = 1. - (mask3 / 255.0) pos = np.zeros((h, w), dtype=np.int32) direct = np.zeros((h, w, 4), dtype=np.int32) i = 0
if mask3.max() > 0: # otherwise it will cause infinity loop while np.sum(1 - mask3) > 0: i += 1 mask3_ = cv2.filter2D(mask3, -1, ones_filter) mask3_[mask3_ > 0] = 1 sub_mask = mask3_ - mask3 pos[sub_mask == 1] = i
m = cv2.filter2D(mask3, -1, d_filter1) m[m > 0] = 1 m = m - mask3 direct[m == 1, 0] = 1
m = cv2.filter2D(mask3, -1, d_filter2) m[m > 0] = 1 m = m - mask3 direct[m == 1, 1] = 1
m = cv2.filter2D(mask3, -1, d_filter3) m[m > 0] = 1 m = m - mask3 direct[m == 1, 2] = 1
m = cv2.filter2D(mask3, -1, d_filter4) m[m > 0] = 1 m = m - mask3 direct[m == 1, 3] = 1
mask3 = mask3_
abs_pos = pos.copy() rel_pos = pos / (str_size / 2) # to 0~1 maybe larger than 1 rel_pos = (rel_pos * pos_num).astype(np.int32) rel_pos = np.clip(rel_pos, 0, pos_num - 1)
if ori_w != w or ori_h != h: rel_pos = cv2.resize(rel_pos, (ori_w, ori_h), interpolation=cv2.INTER_NEAREST) rel_pos[ori_mask == 0] = 0 direct = cv2.resize(direct, (ori_w, ori_h), interpolation=cv2.INTER_NEAREST) direct[ori_mask == 0, :] = 0
return rel_pos, abs_pos, direct
def load_lama_mpe(model_path, device, use_mpe=True, large_arch: bool = False) -> LamaFourier: model = LamaFourier(build_discriminator=False, use_mpe=use_mpe, large_arch=large_arch) sd = torch.load(model_path, map_location = 'cpu') model.generator.load_state_dict(sd['gen_state_dict']) if use_mpe: model.mpe.load_state_dict(sd['str_state_dict']) model.eval().to(device) return model123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209#! /usr/bin/env python3# -*- coding: utf-8 -*-# File : patch_match.py# Author : Jiayuan Mao# Email : maojiayuan@gmail.com# Date : 01/09/2020## Distributed under terms of the MIT license.
import ctypes, osimport sysfrom typing import Optional, Unionfrom glob import glob
import numpy as npfrom PIL import Image
# try:# # If the Jacinle library (https://github.com/vacancy/Jacinle) is present, use its auto_travis feature.# from jacinle.jit.cext import auto_travis# auto_travis(__file__, required_files=['*.so'])# except ImportError as e:# # Otherwise, fall back to the subprocess.# import subprocess# print('Compiling and loading c extensions from "{}".'.format(osp.realpath(osp.dirname(__file__))))# subprocess.check_call(['./travis.sh'], cwd=osp.dirname(__file__))
__all__ = ['set_random_seed', 'set_verbose', 'inpaint', 'inpaint_regularity']
class CShapeT(ctypes.Structure): _fields_ = [ ('width', ctypes.c_int), ('height', ctypes.c_int), ('channels', ctypes.c_int), ]
class CMatT(ctypes.Structure): _fields_ = [ ('data_ptr', ctypes.c_void_p), ('shape', CShapeT), ('dtype', ctypes.c_int) ] if sys.platform == "win32": patchmatchlib = 'data/libs/patchmatch_inpaint.dll'elif sys.platform == "darwin": patchmatchlib = 'data/libs/macos_libpatchmatch_inpaint.dylib' opencv_world = glob('data/libs/macos_libopencv_world.*.dylib') if opencv_world: ctypes.CDLL(opencv_world[0])else: patchmatchlib = 'data/libs/libpatchmatch.so'
PMLIB = ctypes.CDLL(patchmatchlib)PMLIB.PM_set_random_seed.argtypes = [ctypes.c_uint]PMLIB.PM_set_verbose.argtypes = [ctypes.c_int]PMLIB.PM_free_pymat.argtypes = [CMatT]PMLIB.PM_inpaint.argtypes = [CMatT, CMatT, ctypes.c_int]PMLIB.PM_inpaint.restype = CMatTPMLIB.PM_inpaint_regularity.argtypes = [CMatT, CMatT, CMatT, ctypes.c_int, ctypes.c_float]PMLIB.PM_inpaint_regularity.restype = CMatTPMLIB.PM_inpaint2.argtypes = [CMatT, CMatT, CMatT, ctypes.c_int]PMLIB.PM_inpaint2.restype = CMatTPMLIB.PM_inpaint2_regularity.argtypes = [CMatT, CMatT, CMatT, CMatT, ctypes.c_int, ctypes.c_float]PMLIB.PM_inpaint2_regularity.restype = CMatT
def set_random_seed(seed: int): PMLIB.PM_set_random_seed(ctypes.c_uint(seed))
def set_verbose(verbose: bool): PMLIB.PM_set_verbose(ctypes.c_int(verbose))
def inpaint( image: Union[np.ndarray, Image.Image], mask: Optional[Union[np.ndarray, Image.Image]] = None, *, global_mask: Optional[Union[np.ndarray, Image.Image]] = None, patch_size: int = 15) -> np.ndarray: """ PatchMatch based inpainting proposed in:
PatchMatch : A Randomized Correspondence Algorithm for Structural Image Editing C.Barnes, E.Shechtman, A.Finkelstein and Dan B.Goldman SIGGRAPH 2009
Args: image (Union[np.ndarray, Image.Image]): the input image, should be 3-channel RGB/BGR. mask (Union[np.array, Image.Image], optional): the mask of the hole(s) to be filled, should be 1-channel. If not provided (None), the algorithm will treat all purely white pixels as the holes (255, 255, 255). global_mask (Union[np.array, Image.Image], optional): the target mask of the output image. patch_size (int): the patch size for the inpainting algorithm.
Return: result (np.ndarray): the repaired image, of the same size as the input image. """
if isinstance(image, Image.Image): image = np.array(image) image = np.ascontiguousarray(image) assert image.ndim == 3 and image.shape[2] == 3 and image.dtype == 'uint8'
if mask is None: mask = (image == (255, 255, 255)).all(axis=2, keepdims=True).astype('uint8') mask = np.ascontiguousarray(mask) else: mask = _canonize_mask_array(mask)
if global_mask is None: ret_pymat = PMLIB.PM_inpaint(np_to_pymat(image), np_to_pymat(mask), ctypes.c_int(patch_size)) else: global_mask = _canonize_mask_array(global_mask) ret_pymat = PMLIB.PM_inpaint2(np_to_pymat(image), np_to_pymat(mask), np_to_pymat(global_mask), ctypes.c_int(patch_size))
ret_npmat = pymat_to_np(ret_pymat) PMLIB.PM_free_pymat(ret_pymat)
return ret_npmat
def inpaint_regularity( image: Union[np.ndarray, Image.Image], mask: Optional[Union[np.ndarray, Image.Image]], ijmap: np.ndarray, *, global_mask: Optional[Union[np.ndarray, Image.Image]] = None, patch_size: int = 15, guide_weight: float = 0.25) -> np.ndarray: if isinstance(image, Image.Image): image = np.array(image) image = np.ascontiguousarray(image)
assert isinstance(ijmap, np.ndarray) and ijmap.ndim == 3 and ijmap.shape[2] == 3 and ijmap.dtype == 'float32' ijmap = np.ascontiguousarray(ijmap)
assert image.ndim == 3 and image.shape[2] == 3 and image.dtype == 'uint8' if mask is None: mask = (image == (255, 255, 255)).all(axis=2, keepdims=True).astype('uint8') mask = np.ascontiguousarray(mask) else: mask = _canonize_mask_array(mask)
if global_mask is None: ret_pymat = PMLIB.PM_inpaint_regularity(np_to_pymat(image), np_to_pymat(mask), np_to_pymat(ijmap), ctypes.c_int(patch_size), ctypes.c_float(guide_weight)) else: global_mask = _canonize_mask_array(global_mask) ret_pymat = PMLIB.PM_inpaint2_regularity(np_to_pymat(image), np_to_pymat(mask), np_to_pymat(global_mask), np_to_pymat(ijmap), ctypes.c_int(patch_size), ctypes.c_float(guide_weight))
ret_npmat = pymat_to_np(ret_pymat) PMLIB.PM_free_pymat(ret_pymat)
return ret_npmat
def _canonize_mask_array(mask): if isinstance(mask, Image.Image): mask = np.array(mask) if mask.ndim == 2 and mask.dtype == 'uint8': mask = mask[..., np.newaxis] assert mask.ndim == 3 and mask.shape[2] == 1 and mask.dtype == 'uint8' return np.ascontiguousarray(mask)
dtype_pymat_to_ctypes = [ ctypes.c_uint8, ctypes.c_int8, ctypes.c_uint16, ctypes.c_int16, ctypes.c_int32, ctypes.c_float, ctypes.c_double,]
dtype_np_to_pymat = { 'uint8': 0, 'int8': 1, 'uint16': 2, 'int16': 3, 'int32': 4, 'float32': 5, 'float64': 6,}
def np_to_pymat(npmat): assert npmat.ndim == 3 return CMatT( ctypes.cast(npmat.ctypes.data, ctypes.c_void_p), CShapeT(npmat.shape[1], npmat.shape[0], npmat.shape[2]), dtype_np_to_pymat[str(npmat.dtype)] )
def pymat_to_np(pymat): npmat = np.ctypeslib.as_array( ctypes.cast(pymat.data_ptr, ctypes.POINTER(dtype_pymat_to_ctypes[pymat.dtype])), (pymat.shape.height, pymat.shape.width, pymat.shape.channels) ) ret = np.empty(npmat.shape, npmat.dtype) ret[:] = npmat return ret
1from .base import OCRBase, register_OCR, DEVICE_SELECTOR, DEFAULT_DEVICE, TextBlock, OCR12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455from typing import Tuple, List, Dict, Union, Callableimport numpy as npimport cv2from collections import OrderedDict
from utils.textblock import TextBlockfrom utils.registry import RegistryOCR = Registry('OCR')register_OCR = OCR.register_module
from ..base import BaseModule, DEFAULT_DEVICE, DEVICE_SELECTOR, LOGGER
class OCRBase(BaseModule):
_postprocess_hooks = OrderedDict() _preprocess_hooks = OrderedDict() _line_only: bool = False
def __init__(self, **params) -> None: super().__init__(**params) self.name = '' for key in OCR.module_dict: if OCR.module_dict[key] == self.__class__: self.name = key break
def run_ocr(self, img: np.ndarray, blk_list: List[TextBlock] = None, *args, **kwargs) -> Union[List[TextBlock], str]:
if not self.all_model_loaded(): self.load_model()
if img.ndim == 3 and img.shape[-1] == 4: img = cv2.cvtColor(img, cv2.COLOR_RGBA2RGB)
if blk_list is None: text = self.ocr_img(img) return text elif isinstance(blk_list, TextBlock): blk_list = [blk_list]
for blk in blk_list: if self.name != 'none_ocr': blk.text = [] self._ocr_blk_list(img, blk_list, *args, **kwargs) for callback_name, callback in self._postprocess_hooks.items(): callback(textblocks=blk_list, img=img, ocr_module=self)
return blk_list
def _ocr_blk_list(self, img: np.ndarray, blk_list: List[TextBlock], *args, **kwargs) -> None: raise NotImplementedError
def ocr_img(self, img: np.ndarray) -> str: raise NotImplementedError123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638# modified from https://github.com/zyddnys/manga-image-translator/blob/main/ocr/model_32px.py
from collections import defaultdictimport torchimport torch.nn as nnimport torch.nn.functional as F
import cv2import mathimport einopsimport numpy as npfrom typing import List, Tuple, Optional
from utils.textblock import TextBlock
class ResNet(nn.Module):
def __init__(self, input_channel, output_channel, block, layers): super(ResNet, self).__init__()
self.output_channel_block = [int(output_channel / 4), int(output_channel / 2), output_channel, output_channel]
self.inplanes = int(output_channel / 8) self.conv0_1 = nn.Conv2d(input_channel, int(output_channel / 8), kernel_size=3, stride=1, padding=1, bias=False) self.bn0_1 = nn.BatchNorm2d(int(output_channel / 8)) self.conv0_2 = nn.Conv2d(int(output_channel / 8), self.inplanes, kernel_size=3, stride=1, padding=1, bias=False)
self.maxpool1 = nn.AvgPool2d(kernel_size=2, stride=2, padding=0) self.layer1 = self._make_layer(block, self.output_channel_block[0], layers[0]) self.bn1 = nn.BatchNorm2d(self.output_channel_block[0]) self.conv1 = nn.Conv2d(self.output_channel_block[0], self.output_channel_block[ 0], kernel_size=3, stride=1, padding=1, bias=False)
self.maxpool2 = nn.AvgPool2d(kernel_size=2, stride=2, padding=0) self.layer2 = self._make_layer(block, self.output_channel_block[1], layers[1], stride=1) self.bn2 = nn.BatchNorm2d(self.output_channel_block[1]) self.conv2 = nn.Conv2d(self.output_channel_block[1], self.output_channel_block[ 1], kernel_size=3, stride=1, padding=1, bias=False)
self.maxpool3 = nn.AvgPool2d(kernel_size=2, stride=(2, 1), padding=(0, 1)) self.layer3 = self._make_layer(block, self.output_channel_block[2], layers[2], stride=1) self.bn3 = nn.BatchNorm2d(self.output_channel_block[2]) self.conv3 = nn.Conv2d(self.output_channel_block[2], self.output_channel_block[ 2], kernel_size=3, stride=1, padding=1, bias=False)
self.layer4 = self._make_layer(block, self.output_channel_block[3], layers[3], stride=1) self.bn4_1 = nn.BatchNorm2d(self.output_channel_block[3]) self.conv4_1 = nn.Conv2d(self.output_channel_block[3], self.output_channel_block[ 3], kernel_size=2, stride=(2, 1), padding=(0, 1), bias=False) self.bn4_2 = nn.BatchNorm2d(self.output_channel_block[3]) self.conv4_2 = nn.Conv2d(self.output_channel_block[3], self.output_channel_block[ 3], kernel_size=2, stride=1, padding=0, bias=False) self.bn4_3 = nn.BatchNorm2d(self.output_channel_block[3])
def _make_layer(self, block, planes, blocks, stride=1): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.BatchNorm2d(self.inplanes), nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), )
layers = [] layers.append(block(self.inplanes, planes, stride, downsample)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes))
return nn.Sequential(*layers)
def forward(self, x): x = self.conv0_1(x) x = self.bn0_1(x) x = F.relu(x) x = self.conv0_2(x)
x = self.maxpool1(x) x = self.layer1(x) x = self.bn1(x) x = F.relu(x) x = self.conv1(x)
x = self.maxpool2(x) x = self.layer2(x) x = self.bn2(x) x = F.relu(x) x = self.conv2(x)
x = self.maxpool3(x) x = self.layer3(x) x = self.bn3(x) x = F.relu(x) x = self.conv3(x)
x = self.layer4(x) x = self.bn4_1(x) x = F.relu(x) x = self.conv4_1(x) x = self.bn4_2(x) x = F.relu(x) x = self.conv4_2(x) x = self.bn4_3(x)
return x
class BasicBlock(nn.Module): expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.bn1 = nn.BatchNorm2d(inplanes) self.conv1 = self._conv3x3(inplanes, planes) self.bn2 = nn.BatchNorm2d(planes) self.conv2 = self._conv3x3(planes, planes) self.downsample = downsample self.stride = stride
def _conv3x3(self, in_planes, out_planes, stride=1): "3x3 convolution with padding" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
def forward(self, x): residual = x
out = self.bn1(x) out = F.relu(out) out = self.conv1(out)
out = self.bn2(out) out = F.relu(out) out = self.conv2(out)
if self.downsample is not None: residual = self.downsample(residual)
return out + residual
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
def conv1x1(in_planes, out_planes, stride=1): """1x1 convolution""" return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
class ResNet_FeatureExtractor(nn.Module): """ FeatureExtractor of FAN (http://openaccess.thecvf.com/content_ICCV_2017/papers/Cheng_Focusing_Attention_Towards_ICCV_2017_paper.pdf) """
def __init__(self, input_channel, output_channel=128): super(ResNet_FeatureExtractor, self).__init__() self.ConvNet = ResNet(input_channel, output_channel, BasicBlock, [3, 6, 7, 5])
def forward(self, input): return self.ConvNet(input)
class PositionalEncoding(nn.Module): def __init__(self, d_model, dropout=0.1, max_len=5000): super(PositionalEncoding, self).__init__() self.dropout = nn.Dropout(p=dropout)
pe = torch.zeros(max_len, d_model) position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) pe = pe.unsqueeze(0).transpose(0, 1) self.register_buffer('pe', pe)
def forward(self, x, offset = 0): x = x + self.pe[offset: offset + x.size(0), :] return x#self.dropout(x)
def generate_square_subsequent_mask(sz): mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1) mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0)) return mask
class AddCoords(nn.Module):
def __init__(self, with_r=False): super().__init__() self.with_r = with_r
def forward(self, input_tensor): """ Args: input_tensor: shape(batch, channel, x_dim, y_dim) """ batch_size, _, x_dim, y_dim = input_tensor.size()
xx_channel = torch.arange(x_dim).repeat(1, y_dim, 1) yy_channel = torch.arange(y_dim).repeat(1, x_dim, 1).transpose(1, 2)
xx_channel = xx_channel.float() / (x_dim - 1) yy_channel = yy_channel.float() / (y_dim - 1)
xx_channel = xx_channel * 2 - 1 yy_channel = yy_channel * 2 - 1
xx_channel = xx_channel.repeat(batch_size, 1, 1, 1).transpose(2, 3) yy_channel = yy_channel.repeat(batch_size, 1, 1, 1).transpose(2, 3)
ret = torch.cat([ input_tensor, xx_channel.type_as(input_tensor), yy_channel.type_as(input_tensor)], dim=1)
if self.with_r: rr = torch.sqrt(torch.pow(xx_channel.type_as(input_tensor) - 0.5, 2) + torch.pow(yy_channel.type_as(input_tensor) - 0.5, 2)) ret = torch.cat([ret, rr], dim=1)
return ret
class Beam : def __init__(self, char_seq = [], logprobs = []) : # L if isinstance(char_seq, list) : self.chars = torch.tensor(char_seq, dtype=torch.long) self.logprobs = torch.tensor(logprobs, dtype=torch.float32) else : self.chars = char_seq.clone() self.logprobs = logprobs.clone()
def avg_logprob(self) : return self.logprobs.mean().item() def sort_key(self) : return -self.avg_logprob() def seq_end(self, end_tok) : return self.chars.view(-1)[-1] == end_tok
def extend(self, idx, logprob) : return Beam( torch.cat([self.chars, idx.unsqueeze(0)], dim = -1), torch.cat([self.logprobs, logprob.unsqueeze(0)], dim = -1), )
DECODE_BLOCK_LENGTH = 8
class Hypothesis : def __init__(self, device, start_tok: int, end_tok: int, padding_tok: int, memory_idx: int, num_layers: int, embd_dim: int) : self.device = device self.start_tok = start_tok self.end_tok = end_tok self.padding_tok = padding_tok self.memory_idx = memory_idx self.embd_size = embd_dim self.num_layers = num_layers # L, 1, E self.cached_activations = [torch.zeros(0, 1, self.embd_size).to(self.device)] * (num_layers + 1) self.out_idx = torch.LongTensor([start_tok]).to(self.device) self.out_logprobs = torch.FloatTensor([0]).to(self.device) self.length = 0
def seq_end(self) : return self.out_idx.view(-1)[-1] == self.end_tok
def logprob(self) : return self.out_logprobs.mean().item()
def sort_key(self) : return -self.logprob()
def prob(self) : return self.out_logprobs.mean().exp().item()
def __len__(self) : return self.length
def extend(self, idx, logprob) : ret = Hypothesis(self.device, self.start_tok, self.end_tok, self.padding_tok, self.memory_idx, self.num_layers, self.embd_size) ret.cached_activations = [item.clone() for item in self.cached_activations] ret.length = self.length + 1 ret.out_idx = torch.cat([self.out_idx, torch.LongTensor([idx]).to(self.device)], dim = 0) ret.out_logprobs = torch.cat([self.out_logprobs, torch.FloatTensor([logprob]).to(self.device)], dim = 0) return ret
def output(self) : return self.cached_activations[-1]
def next_token_batch( hyps: List[Hypothesis], memory: torch.Tensor, # S, K, E memory_mask: torch.BoolTensor, decoders: nn.TransformerDecoder, pe: PositionalEncoding, embd: nn.Embedding ) : layer: nn.TransformerDecoderLayer N = len(hyps)
# N last_toks = torch.stack([item.out_idx[-1] for item in hyps], dim = 0) # 1, N, E tgt: torch.FloatTensor = pe(embd(last_toks).unsqueeze_(0), offset = len(hyps[0]))
# # L, N # out_idxs = torch.stack([item.out_idx for item in hyps], dim = 0).permute(1, 0) # # L, N, E # tgt2: torch.FloatTensor = pe(embd(out_idxs)) # # 1, N, E # tgt_v2 = tgt2[-1, :, :].unsqueeze_(0) # print(((tgt_v1 - tgt_v2) ** 2).sum())
# tgt = tgt_v2
# S, N, E memory = torch.stack([memory[:, idx, :] for idx in [item.memory_idx for item in hyps]], dim = 1) for l, layer in enumerate(decoders.layers) : # TODO: keys and values are recomputed everytime # L - 1, N, E combined_activations = torch.cat([item.cached_activations[l] for item in hyps], dim = 1) # L, N, E combined_activations = torch.cat([combined_activations, tgt], dim = 0) for i in range(N) : hyps[i].cached_activations[l] = combined_activations[:, i: i + 1, :] tgt2 = layer.self_attn(tgt, combined_activations, combined_activations)[0] tgt = tgt + layer.dropout1(tgt2) tgt = layer.norm1(tgt) tgt2 = layer.multihead_attn(tgt, memory, memory, key_padding_mask = memory_mask)[0] tgt = tgt + layer.dropout2(tgt2) tgt = layer.norm2(tgt) tgt2 = layer.linear2(layer.dropout(layer.activation(layer.linear1(tgt)))) tgt = tgt + layer.dropout3(tgt2) # 1, N, E tgt = layer.norm3(tgt) #print(tgt[0, 0, 0]) for i in range(N) : hyps[i].cached_activations[decoders.num_layers] = torch.cat([hyps[i].cached_activations[decoders.num_layers], tgt[:, i: i + 1, :]], dim = 0) # N, E return tgt.squeeze_(0)
class OCR(nn.Module) : def __init__(self, dictionary, max_len): super(OCR, self).__init__() self.max_len = max_len self.dictionary = dictionary self.dict_size = len(dictionary) self.backbone = ResNet_FeatureExtractor(3, 320) encoder = nn.TransformerEncoderLayer(320, 4, dropout = 0.0) decoder = nn.TransformerDecoderLayer(320, 4, dropout = 0.0) self.encoders = nn.TransformerEncoder(encoder, 3) self.decoders = nn.TransformerDecoder(decoder, 2) self.pe = PositionalEncoding(320, max_len = max_len) self.embd = nn.Embedding(self.dict_size, 320) self.pred1 = nn.Sequential(nn.Linear(320, 320), nn.ReLU(), nn.Dropout(0.1)) self.pred = nn.Linear(320, self.dict_size) self.pred.weight = self.embd.weight self.color_pred1 = nn.Sequential(nn.Linear(320, 64), nn.ReLU()) self.fg_r_pred = nn.Linear(64, 1) self.fg_g_pred = nn.Linear(64, 1) self.fg_b_pred = nn.Linear(64, 1) self.bg_r_pred = nn.Linear(64, 1) self.bg_g_pred = nn.Linear(64, 1) self.bg_b_pred = nn.Linear(64, 1)
def forward(self, img: torch.FloatTensor, char_idx: torch.LongTensor, mask: torch.BoolTensor, source_mask: torch.BoolTensor ) : feats = self.backbone(img) feats = torch.einsum('n e h s -> s n e', feats) feats = self.pe(feats) memory = self.encoders(feats, src_key_padding_mask = source_mask) N, L = char_idx.shape char_embd = self.embd(char_idx) char_embd = torch.einsum('n t e -> t n e', char_embd) char_embd = self.pe(char_embd) casual_mask = generate_square_subsequent_mask(L).to(img.device) decoded = self.decoders(char_embd, memory, tgt_mask = casual_mask, tgt_key_padding_mask = mask, memory_key_padding_mask = source_mask) decoded = decoded.permute(1, 0, 2) pred_char_logits = self.pred(self.pred1(decoded)) color_feats = self.color_pred1(decoded) return pred_char_logits, \ self.fg_r_pred(color_feats), \ self.fg_g_pred(color_feats), \ self.fg_b_pred(color_feats), \ self.bg_r_pred(color_feats), \ self.bg_g_pred(color_feats), \ self.bg_b_pred(color_feats)
def infer_beam_batch(self, img: torch.FloatTensor, img_widths: List[int], beams_k: int = 5, start_tok = 1, end_tok = 2, pad_tok = 0, max_finished_hypos: int = 2, max_seq_length = 384) : N, C, H, W = img.shape assert H == 32 and C == 3 feats = self.backbone(img) feats = torch.einsum('n e h s -> s n e', feats) valid_feats_length = [(x + 3) // 4 + 2 for x in img_widths] input_mask = torch.zeros(N, feats.size(0), dtype = torch.bool).to(img.device) for i, l in enumerate(valid_feats_length) : input_mask[i, l:] = True feats = self.pe(feats) memory = self.encoders(feats, src_key_padding_mask = input_mask) hypos = [Hypothesis(img.device, start_tok, end_tok, pad_tok, i, self.decoders.num_layers, 320) for i in range(N)] # N, E decoded = next_token_batch(hypos, memory, input_mask, self.decoders, self.pe, self.embd) # N, n_chars pred_char_logprob = self.pred(self.pred1(decoded)).log_softmax(-1) # N, k pred_chars_values, pred_chars_index = torch.topk(pred_char_logprob, beams_k, dim = 1) new_hypos = [] finished_hypos = defaultdict(list) for i in range(N) : for k in range(beams_k) : new_hypos.append(hypos[i].extend(pred_chars_index[i, k], pred_chars_values[i, k])) hypos = new_hypos for _ in range(max_seq_length) : # N * k, E decoded = next_token_batch(hypos, memory, torch.stack([input_mask[hyp.memory_idx] for hyp in hypos]) , self.decoders, self.pe, self.embd) # N * k, n_chars pred_char_logprob = self.pred(self.pred1(decoded)).log_softmax(-1) # N * k, k pred_chars_values, pred_chars_index = torch.topk(pred_char_logprob, beams_k, dim = 1) hypos_per_sample = defaultdict(list) h: Hypothesis for i, h in enumerate(hypos) : for k in range(beams_k) : hypos_per_sample[h.memory_idx].append(h.extend(pred_chars_index[i, k], pred_chars_values[i, k])) hypos = [] # hypos_per_sample now contains N * k^2 hypos for i in hypos_per_sample.keys() : cur_hypos: List[Hypothesis] = hypos_per_sample[i] cur_hypos = sorted(cur_hypos, key = lambda a: a.sort_key())[: beams_k + 1] #print(cur_hypos[0].out_idx[-1]) to_added_hypos = [] sample_done = False for h in cur_hypos : if h.seq_end() : finished_hypos[i].append(h) if len(finished_hypos[i]) >= max_finished_hypos : sample_done = True break else : if len(to_added_hypos) < beams_k : to_added_hypos.append(h) if not sample_done : hypos.extend(to_added_hypos) if len(hypos) == 0 : break # add remaining hypos to finished for i in range(N) : if i not in finished_hypos : cur_hypos: List[Hypothesis] = hypos_per_sample[i] cur_hypo = sorted(cur_hypos, key = lambda a: a.sort_key())[0] finished_hypos[i].append(cur_hypo) assert len(finished_hypos) == N result = [] for i in range(N) : cur_hypos = finished_hypos[i] cur_hypo = sorted(cur_hypos, key = lambda a: a.sort_key())[0] decoded = cur_hypo.output() color_feats = self.color_pred1(decoded) fg_r, fg_g, fg_b, bg_r, bg_g, bg_b = self.fg_r_pred(color_feats), \ self.fg_g_pred(color_feats), \ self.fg_b_pred(color_feats), \ self.bg_r_pred(color_feats), \ self.bg_g_pred(color_feats), \ self.bg_b_pred(color_feats) result.append((cur_hypo.out_idx, cur_hypo.prob(), fg_r, fg_g, fg_b, bg_r, bg_g, bg_b)) return result
def infer_beam(self, img: torch.FloatTensor, beams_k: int = 5, start_tok = 1, end_tok = 2, pad_tok = 0, max_seq_length = 384) : N, C, H, W = img.shape assert H == 32 and N == 1 and C == 3 feats = self.backbone(img) feats = torch.einsum('n e h s -> s n e', feats) feats = self.pe(feats) memory = self.encoders(feats) def run(tokens, add_start_tok = True, char_only = True) : if add_start_tok : if isinstance(tokens, list) : # N(=1), L tokens = torch.tensor([start_tok] + tokens, dtype = torch.long, device = img.device).unsqueeze_(0) else : # N, L tokens = torch.cat([torch.tensor([start_tok], dtype = torch.long, device = img.device), tokens], dim = -1).unsqueeze_(0) N, L = tokens.shape embd = self.embd(tokens) embd = torch.einsum('n t e -> t n e', embd) embd = self.pe(embd) casual_mask = generate_square_subsequent_mask(L).to(img.device) decoded = self.decoders(embd, memory, tgt_mask = casual_mask) decoded = decoded.permute(1, 0, 2) pred_char_logprob = self.pred(self.pred1(decoded)).log_softmax(-1) if char_only : return pred_char_logprob else : color_feats = self.color_pred1(decoded) return pred_char_logprob, \ self.fg_r_pred(color_feats), \ self.fg_g_pred(color_feats), \ self.fg_b_pred(color_feats), \ self.bg_r_pred(color_feats), \ self.bg_g_pred(color_feats), \ self.bg_b_pred(color_feats) # N, L, embd_size initial_char_logprob = run([]) # N, L initial_pred_chars_values, initial_pred_chars_index = torch.topk(initial_char_logprob, beams_k, dim = 2) # beams_k, L initial_pred_chars_values = initial_pred_chars_values.squeeze(0).permute(1, 0) initial_pred_chars_index = initial_pred_chars_index.squeeze(0).permute(1, 0) beams = sorted([Beam(tok, logprob) for tok, logprob in zip(initial_pred_chars_index, initial_pred_chars_values)], key = lambda a: a.sort_key()) for _ in range(max_seq_length) : new_beams = [] all_ended = True for beam in beams : if not beam.seq_end(end_tok) : logprobs = run(beam.chars) pred_chars_values, pred_chars_index = torch.topk(logprobs, beams_k, dim = 2) # beams_k, L pred_chars_values = pred_chars_values.squeeze(0).permute(1, 0) pred_chars_index = pred_chars_index.squeeze(0).permute(1, 0) #print(pred_chars_index.view(-1)[-1]) new_beams.extend([beam.extend(tok[-1], logprob[-1]) for tok, logprob in zip(pred_chars_index, pred_chars_values)]) #new_beams.extend([Beam(tok, logprob) for tok, logprob in zip(pred_chars_index, pred_chars_values)]) # extend other top k all_ended = False else : new_beams.append(beam) # seq ended, add back to queue beams = sorted(new_beams, key = lambda a: a.sort_key())[: beams_k] # keep top k #print(beams[0].chars) if all_ended : break final_tokens = beams[0].chars[:-1] #print(beams[0].logprobs.mean().exp()) return run(final_tokens, char_only = False), beams[0].logprobs.mean().exp().item()
def chunks(lst, n): """Yield successive n-sized chunks from lst.""" for i in range(0, len(lst), n): yield lst[i:i + n]
class OCR32pxModel: def __init__(self, model_path, device='cpu') -> None: self.device = device self.text_height = 32 self.maxwidth = 3064
self.net = None with open('data/alphabet-all-v5.txt', 'r', encoding = 'utf-8') as fp : dictionary = [s[:-1] for s in fp.readlines()] model = OCR(dictionary, 768) sd = torch.load(model_path, map_location = 'cpu') model.load_state_dict(sd['model'] if 'model' in sd else sd) model.eval() if device != 'cpu': model = model.to(device) self.net = model
def to(self, device: str) -> None: self.net.to(device) self.device = device
@torch.no_grad() def __call__(self, textblk_lst: List[TextBlock], regions: List[np.ndarray], textblk_lst_indices: List, chunk_size = 16) -> None:
perm = range(len(regions)) chunck_idx = 0 for indices in chunks(perm, chunk_size) : N = len(indices) widths = [regions[i].shape[1] for i in indices] max_width = 4 * (max(widths) + 7) // 4 region = np.zeros((N, self.text_height, max_width, 3), dtype = np.uint8) for i, idx in enumerate(indices) : W = regions[idx].shape[1] # Convert RGBA to RGB if necessary for model input region_data = regions[idx] region[i, :, : W, :] = region_data images = (torch.from_numpy(region).float() - 127.5) / 127.5 images = einops.rearrange(images, 'N H W C -> N C H W') if self.device != 'cpu': images = images.to(self.device) ret = self.net.infer_beam_batch(images, widths, beams_k = 5, max_seq_length = 255) for i, (pred_chars_index, prob, fr, fg, fb, br, bg, bb) in enumerate(ret) : textblk = textblk_lst[textblk_lst_indices[i+chunck_idx]] if prob < 0.5 : continue fr = (torch.clip(fr.view(-1), 0, 1).mean() * 255).long().item() fg = (torch.clip(fg.view(-1), 0, 1).mean() * 255).long().item() fb = (torch.clip(fb.view(-1), 0, 1).mean() * 255).long().item() br = (torch.clip(br.view(-1), 0, 1).mean() * 255).long().item() bg = (torch.clip(bg.view(-1), 0, 1).mean() * 255).long().item() bb = (torch.clip(bb.view(-1), 0, 1).mean() * 255).long().item() seq = [] for chid in pred_chars_index : ch = self.net.dictionary[chid] if ch == '<S>' : continue if ch == '</S>' : break if ch == '<SP>' : ch = ' ' seq.append(ch) textblk.text.append(''.join(seq)) textblk.update_font_colors( [fr, fg, fb], [br, bg, bb] ) chunck_idx += N
@torch.no_grad() def ocr_img(self, img: np.ndarray) -> str: im_h, im_w = img.shape[:2] img = cv2.resize(img, (int(im_w * 32 / im_h), 32)) widths = [img.shape[1]] img = (torch.from_numpy(img[np.newaxis, ...]).float() - 127.5) / 127.5 img = einops.rearrange(img, 'N H W C -> N C H W') if self.device != 'cpu': images = images.to(self.device) ret = self.net.infer_beam_batch(img, widths, beams_k = 5, max_seq_length = 255) for i, (pred_chars_index, prob, fr, fg, fb, br, bg, bb) in enumerate(ret) : if prob < 0.5 : continue seq = [] for chid in pred_chars_index : ch = self.net.dictionary[chid] if ch == '<S>' : continue if ch == '</S>' : break if ch == '<SP>' : ch = ' ' seq.append(ch) txt = ''.join(seq) return txt 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893# from https://github.com/zyddnys/manga-image-translator/blob/main/manga_translator/ocr/model_48px.py# Roformer with Xpos and Local Attention ViT
import mathfrom typing import Callable, List, Optional, Tuple, Unionfrom collections import defaultdictimport osimport shutilimport cv2import numpy as npimport einops
import torchimport torch.nn as nnimport torch.nn.functional as F
from .mit48px_ctc import AvgMeter, chunks, TextBlock
def fixed_pos_embedding(x): seq_len, dim = x.shape inv_freq = 1.0 / (10000 ** (torch.arange(0, dim) / dim)) sinusoid_inp = ( torch.einsum("i , j -> i j", torch.arange(0, seq_len, dtype=torch.float), inv_freq).to(x) ) return torch.sin(sinusoid_inp), torch.cos(sinusoid_inp)
def rotate_every_two(x): x1 = x[:, :, ::2] x2 = x[:, :, 1::2] x = torch.stack((-x2, x1), dim=-1) return x.flatten(-2) # in einsum notation: rearrange(x, '... d j -> ... (d j)')\
def duplicate_interleave(m): """ A simple version of `torch.repeat_interleave` for duplicating a matrix while interleaving the copy. """ dim0 = m.shape[0] m = m.view(-1, 1) # flatten the matrix m = m.repeat(1, 2) # repeat all elements into the 2nd dimension m = m.view(dim0, -1) # reshape into a matrix, interleaving the copy return m
def apply_rotary_pos_emb(x, sin, cos, scale=1): sin, cos = map(lambda t: duplicate_interleave(t * scale), (sin, cos)) # einsum notation for lambda t: repeat(t[offset:x.shape[1]+offset,:], "n d -> () n () (d j)", j=2) return (x * cos) + (rotate_every_two(x) * sin)
def apply_rotary_pos_emb2d(x, sin, cos, scale=1): breakpoint() sin, cos = map(lambda t: duplicate_interleave(t * scale), (sin, cos)) # einsum notation for lambda t: repeat(t[offset:x.shape[1]+offset,:], "n d -> () n () (d j)", j=2) return (x * cos) + (rotate_every_two(x) * sin)
class XPOS(nn.Module): def __init__( self, head_dim, scale_base=512 ): super().__init__() self.head_dim = head_dim self.scale_base = scale_base self.register_buffer( "scale", (torch.arange(0, head_dim, 2) + 0.4 * head_dim) / (1.4 * head_dim) )
def forward(self, x, offset=0, downscale=False): length = x.shape[1] min_pos = -(length + offset) // 2 max_pos = length + offset + min_pos scale = self.scale ** torch.arange(min_pos, max_pos, 1).to(self.scale).div(self.scale_base)[:, None] sin, cos = fixed_pos_embedding(scale)
if scale.shape[0] > length: scale = scale[-length:] sin = sin[-length:] cos = cos[-length:] if downscale: scale = 1 / scale
x = apply_rotary_pos_emb(x, sin, cos, scale) return x
class XPOS2D(nn.Module): def __init__( self, head_dim, scale_base=512 ): super().__init__() self.xpos = XPOS(head_dim // 2, scale_base)
def forward(self, x: torch.Tensor, offset_x = 0, offset_y = 0, downscale=False): """ x: N, H, W, C """ N, H, W, C = x.shape C = C // 2 [dir_x, dir_y] = x.chunk(2, dim = 3) dir_x = einops.rearrange(dir_x, 'N H W C -> (N H) W C', N = N, H = H, W = W, C = C) dir_y = einops.rearrange(dir_y, 'N H W C -> (N W) H C', N = N, H = H, W = W, C = C) dir_x = self.xpos(dir_x, offset = offset_x, downscale = downscale) dir_y = self.xpos(dir_y, offset = offset_y, downscale = downscale) dir_x = einops.rearrange(dir_x, '(N H) W C -> N H W C', N = N, H = H, W = W, C = C) dir_y = einops.rearrange(dir_y, '(N W) H C -> N H W C', N = N, H = H, W = W, C = C) return torch.cat([dir_x, dir_y], dim = 3)
# Roformer with Xpos
class Model48pxOCR: _MODEL_MAPPING = { 'model': { 'url': 'https://huggingface.co/zyddnys/manga-image-translator/resolve/main/ocr_ar_48px.ckpt', 'hash': '29daa46d080818bb4ab239a518a88338cbccff8f901bef8c9db191a7cb97671d', }, 'dict': { 'url': 'https://huggingface.co/zyddnys/manga-image-translator/resolve/main/alphabet-all-v7.txt', 'hash': 'f5722368146aa0fbcc9f4726866e4efc3203318ebb66c811d8cbbe915576538a', }, }
def __init__(self, model_path: str, device='cpu', *args, **kwargs):
super().__init__(*args, **kwargs)
self.device = device self.text_height = 48 self.maxwidth = 8100
with open('data/alphabet-all-v7.txt', 'r', encoding = 'utf-8') as fp: dictionary = [s[:-1] for s in fp.readlines()] self.model = OCR(dictionary, 768) sd = torch.load('data/models/ocr_ar_48px.ckpt', map_location='cpu') self.model.load_state_dict(sd) self.model.eval() if self.device != 'cpu' : self.model = self.model.to(self.device)
def to(self, device: str) -> None: self.model.to(device) self.device = device def __call__(self, textblk_lst: List[TextBlock], regions: List[np.ndarray], textblk_lst_indices: List, chunk_size = 16) -> None: perm = range(len(regions)) chunck_idx = 0 for indices in chunks(perm, chunk_size): N = len(indices) widths = [regions[i].shape[1] for i in indices] max_width = 4 * (max(widths) + 7) // 4 region = np.zeros((N, self.text_height, max_width, 3), dtype = np.uint8) for i, idx in enumerate(indices): W = regions[idx].shape[1] # Convert RGBA to RGB if necessary for model input region_data = regions[idx] region[i, :, : W, :]=region_data
image_tensor = (torch.from_numpy(region).float() - 127.5) / 127.5 image_tensor = einops.rearrange(image_tensor, 'N H W C -> N C H W') if self.device != 'cpu': image_tensor = image_tensor.to(self.device)
with torch.no_grad(): ret = self.model.infer_beam_batch_tensor(image_tensor, widths, beams_k = 5, max_seq_length = 255) for i, (pred_chars_index, prob, fg_pred, bg_pred, fg_ind_pred, bg_ind_pred) in enumerate(ret): if prob < 0.2: continue has_fg = (fg_ind_pred[:, 1] > fg_ind_pred[:, 0]) has_bg = (bg_ind_pred[:, 1] > bg_ind_pred[:, 0]) seq = [] fr = AvgMeter() fg = AvgMeter() fb = AvgMeter() br = AvgMeter() bg = AvgMeter() bb = AvgMeter() for chid, c_fg, c_bg, h_fg, h_bg in zip(pred_chars_index, fg_pred, bg_pred, has_fg, has_bg) : ch = self.model.dictionary[chid] if ch == '<S>': continue if ch == '</S>': break if ch == '<SP>': ch = ' ' seq.append(ch) if h_fg.item() : fr(int(c_fg[0] * 255)) fg(int(c_fg[1] * 255)) fb(int(c_fg[2] * 255)) if h_bg.item() : br(int(c_bg[0] * 255)) bg(int(c_bg[1] * 255)) bb(int(c_bg[2] * 255)) else : br(int(c_fg[0] * 255)) bg(int(c_fg[1] * 255)) bb(int(c_fg[2] * 255)) txt = ''.join(seq) fr = min(max(int(fr()), 0), 255) fg = min(max(int(fg()), 0), 255) fb = min(max(int(fb()), 0), 255) br = min(max(int(br()), 0), 255) bg = min(max(int(bg()), 0), 255) bb = min(max(int(bb()), 0), 255) # self.logger.info(f'prob: {prob} {txt} fg: ({fr}, {fg}, {fb}) bg: ({br}, {bg}, {bb})') cur_region = textblk_lst[textblk_lst_indices[i+chunck_idx]] cur_region.text.append(txt) cur_region.update_font_colors(np.array([fr, fg, fb]), np.array([br, bg, bb]))
chunck_idx += N
class ConvNeXtBlock(nn.Module): r""" ConvNeXt Block. There are two equivalent implementations: (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W) (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back We use (2) as we find it slightly faster in PyTorch Args: dim (int): Number of input channels. drop_path (float): Stochastic depth rate. Default: 0.0 layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6. """ def __init__(self, dim, layer_scale_init_value=1e-6, ks = 7, padding = 3): super().__init__() self.dwconv = nn.Conv2d(dim, dim, kernel_size=ks, padding=padding, groups=dim) # depthwise conv self.norm = nn.BatchNorm2d(dim, eps=1e-6) self.pwconv1 = nn.Conv2d(dim, 4 * dim, 1, 1, 0) # pointwise/1x1 convs, implemented with linear layers self.act = nn.GELU() self.pwconv2 = nn.Conv2d(4 * dim, dim, 1, 1, 0) self.gamma = nn.Parameter(layer_scale_init_value * torch.ones(1, dim, 1, 1), requires_grad=True) if layer_scale_init_value > 0 else None
def forward(self, x): input = x x = self.dwconv(x) x = self.norm(x) x = self.pwconv1(x) x = self.act(x) x = self.pwconv2(x) if self.gamma is not None: x = self.gamma * x
x = input + x return x
class ConvNext_FeatureExtractor(nn.Module) : def __init__(self, img_height = 48, in_dim = 3, dim = 512, n_layers = 12) -> None: super().__init__() base = dim // 8 self.stem = nn.Sequential( nn.Conv2d(in_dim, base, kernel_size = 7, stride = 1, padding = 3), nn.BatchNorm2d(base), nn.ReLU(), nn.Conv2d(base, base * 2, kernel_size = 2, stride = 2, padding = 0), nn.BatchNorm2d(base * 2), nn.ReLU(), nn.Conv2d(base * 2, base * 2, kernel_size = 3, stride = 1, padding = 1), nn.BatchNorm2d(base * 2), nn.ReLU(), ) self.block1 = self.make_layers(base * 2, 4) self.down1 = nn.Sequential( nn.Conv2d(base * 2, base * 4, kernel_size = 2, stride = 2, padding = 0), nn.BatchNorm2d(base * 4), nn.ReLU(), ) self.block2 = self.make_layers(base * 4, 12) self.down2 = nn.Sequential( nn.Conv2d(base * 4, base * 8, kernel_size = (2, 1), stride = (2, 1), padding = (0, 0)), nn.BatchNorm2d(base * 8), nn.ReLU(), ) self.block3 = self.make_layers(base * 8, 10, ks = 5, padding = 2) self.down3 = nn.Sequential( nn.Conv2d(base * 8, base * 8, kernel_size = (2, 1), stride = (2, 1), padding = (0, 0)), nn.BatchNorm2d(base * 8), nn.ReLU(), ) self.block4 = self.make_layers(base * 8, 8, ks = 3, padding = 1) self.down4 = nn.Sequential( nn.Conv2d(base * 8, base * 8, kernel_size = (3, 1), stride = (1, 1), padding = (0, 0)), nn.BatchNorm2d(base * 8), nn.ReLU(), )
def make_layers(self, dim, n, ks = 7, padding = 3) : layers = [] for i in range(n) : layers.append(ConvNeXtBlock(dim, ks = ks, padding = padding)) return nn.Sequential(*layers) def forward(self, x) : x = self.stem(x) # h//2, w//2 x = self.block1(x) x = self.down1(x) # h//4, w//4 x = self.block2(x) x = self.down2(x) # h//8, w//4 x = self.block3(x) x = self.down3(x) # h//16, w//4 x = self.block4(x) x = self.down4(x) return x
def transformer_encoder_forward( self, src: torch.Tensor, src_mask: Optional[torch.Tensor] = None, src_key_padding_mask: Optional[torch.Tensor] = None, is_causal: bool = False) -> torch.Tensor: x = src if self.norm_first: x = x + self._sa_block(self.norm1(x), src_mask, src_key_padding_mask) x = x + self._ff_block(self.norm2(x)) else: x = self.norm1(x + self._sa_block(x, src_mask, src_key_padding_mask)) x = self.norm2(x + self._ff_block(x))
return x
class XposMultiheadAttention(nn.Module): def __init__( self, embed_dim, num_heads, self_attention=False, encoder_decoder_attention=False, ): super().__init__() self.embed_dim = embed_dim self.num_heads = num_heads self.head_dim = embed_dim // num_heads self.scaling = self.head_dim**-0.5
self.self_attention = self_attention self.encoder_decoder_attention = encoder_decoder_attention assert self.self_attention ^ self.encoder_decoder_attention
self.k_proj = nn.Linear(embed_dim, embed_dim, bias = True) self.v_proj = nn.Linear(embed_dim, embed_dim, bias = True) self.q_proj = nn.Linear(embed_dim, embed_dim, bias = True) self.out_proj = nn.Linear(embed_dim, embed_dim, bias = True) self.xpos = XPOS(self.head_dim, embed_dim) self.batch_first = True self._qkv_same_embed_dim = True
def reset_parameters(self): nn.init.xavier_uniform_(self.k_proj.weight, gain=1 / math.sqrt(2)) nn.init.xavier_uniform_(self.v_proj.weight, gain=1 / math.sqrt(2)) nn.init.xavier_uniform_(self.q_proj.weight, gain=1 / math.sqrt(2)) nn.init.xavier_uniform_(self.out_proj.weight) nn.init.constant_(self.out_proj.bias, 0.0)
def forward( self, query, key, value, key_padding_mask=None, attn_mask=None, need_weights = False, is_causal = False, k_offset = 0, q_offset = 0 ): assert not is_causal bsz, tgt_len, embed_dim = query.size() src_len = tgt_len assert embed_dim == self.embed_dim, f"query dim {embed_dim} != {self.embed_dim}"
key_bsz, src_len, _ = key.size() assert key_bsz == bsz, f"{query.size(), key.size()}" assert value is not None assert bsz, src_len == value.shape[:2]
q = self.q_proj(query) k = self.k_proj(key) v = self.v_proj(value) q *= self.scaling
q = q.view(bsz, tgt_len, self.num_heads, self.head_dim).transpose(1, 2) k = k.view(bsz, src_len, self.num_heads, self.head_dim).transpose(1, 2) v = v.view(bsz, src_len, self.num_heads, self.head_dim).transpose(1, 2) q = q.reshape(bsz * self.num_heads, tgt_len, self.head_dim) k = k.reshape(bsz * self.num_heads, src_len, self.head_dim) v = v.reshape(bsz * self.num_heads, src_len, self.head_dim)
if self.xpos is not None: k = self.xpos(k, offset=k_offset, downscale=True) # TODO: read paper q = self.xpos(q, offset=q_offset, downscale=False)
attn_weights = torch.bmm(q, k.transpose(1, 2))
if attn_mask is not None: attn_weights = torch.nan_to_num(attn_weights) attn_mask = attn_mask.unsqueeze(0) attn_weights += attn_mask
if key_padding_mask is not None: attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) attn_weights = attn_weights.masked_fill( key_padding_mask.unsqueeze(1).unsqueeze(2).to(torch.bool), float("-inf"), ) attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).type_as( attn_weights ) attn = torch.bmm(attn_weights, v) attn = attn.transpose(0, 1).reshape(tgt_len, bsz, embed_dim).transpose(0, 1)
attn = self.out_proj(attn) attn_weights = attn_weights.view( bsz, self.num_heads, tgt_len, src_len ).transpose(1, 0)
if need_weights: return attn, attn_weights else : return attn, None
def generate_square_subsequent_mask(sz): mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1) mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0)) return mask
class Beam: def __init__(self, char_seq = [], logprobs = []): # L if isinstance(char_seq, list): self.chars = torch.tensor(char_seq, dtype=torch.long) self.logprobs = torch.tensor(logprobs, dtype=torch.float32) else: self.chars = char_seq.clone() self.logprobs = logprobs.clone()
def avg_logprob(self): return self.logprobs.mean().item()
def sort_key(self): return -self.avg_logprob()
def seq_end(self, end_tok): return self.chars.view(-1)[-1] == end_tok
def extend(self, idx, logprob): return Beam( torch.cat([self.chars, idx.unsqueeze(0)], dim = -1), torch.cat([self.logprobs, logprob.unsqueeze(0)], dim = -1), )
DECODE_BLOCK_LENGTH = 8
class Hypothesis: def __init__(self, device, start_tok: int, end_tok: int, padding_tok: int, memory_idx: int, num_layers: int, embd_dim: int): self.device = device self.start_tok = start_tok self.end_tok = end_tok self.padding_tok = padding_tok self.memory_idx = memory_idx self.embd_size = embd_dim self.num_layers = num_layers # 1, L, E self.cached_activations = [torch.zeros(1, 0, self.embd_size).to(self.device)] * (num_layers + 1) self.out_idx = torch.LongTensor([start_tok]).to(self.device) self.out_logprobs = torch.FloatTensor([0]).to(self.device) self.length = 0
def seq_end(self): return self.out_idx.view(-1)[-1] == self.end_tok
def logprob(self): return self.out_logprobs.mean().item()
def sort_key(self): return -self.logprob()
def prob(self): return self.out_logprobs.mean().exp().item()
def __len__(self): return self.length
def extend(self, idx, logprob): ret = Hypothesis(self.device, self.start_tok, self.end_tok, self.padding_tok, self.memory_idx, self.num_layers, self.embd_size) ret.cached_activations = [item.clone() for item in self.cached_activations] ret.length = self.length + 1 ret.out_idx = torch.cat([self.out_idx, torch.LongTensor([idx]).to(self.device)], dim = 0) ret.out_logprobs = torch.cat([self.out_logprobs, torch.FloatTensor([logprob]).to(self.device)], dim = 0) return ret
def output(self): return self.cached_activations[-1]
def next_token_batch( hyps: List[Hypothesis], memory: torch.Tensor, # N, H, W, C memory_mask: torch.BoolTensor, decoders: nn.ModuleList, embd: nn.Embedding ): layer: nn.TransformerDecoderLayer N = len(hyps) offset = len(hyps[0])
# N last_toks = torch.stack([item.out_idx[-1] for item in hyps]) # N, 1, E tgt: torch.FloatTensor = embd(last_toks).unsqueeze_(1) # N, L, E memory = torch.stack([memory[idx, :, :] for idx in [item.memory_idx for item in hyps]], dim = 0) for l, layer in enumerate(decoders): # TODO: keys and values are recomputed everytime # N, L - 1, E combined_activations = torch.cat([item.cached_activations[l] for item in hyps], dim = 0) # N, L, E combined_activations = torch.cat([combined_activations, tgt], dim = 1) for i in range(N): hyps[i].cached_activations[l] = combined_activations[i: i + 1, :, :] # N, 1, E tgt = tgt + layer.self_attn(layer.norm1(tgt), layer.norm1(combined_activations), layer.norm1(combined_activations), q_offset = offset)[0] tgt = tgt + layer.multihead_attn(layer.norm2(tgt), memory, memory, key_padding_mask = memory_mask, q_offset = offset)[0] tgt = tgt + layer._ff_block(layer.norm3(tgt)) #print(tgt[0, 0, 0]) for i in range(N): hyps[i].cached_activations[len(decoders)] = torch.cat([hyps[i].cached_activations[len(decoders)], tgt[i: i + 1, :, :]], dim = 1) # N, E return tgt.squeeze_(1)
class OCR(nn.Module): def __init__(self, dictionary, max_len): super(OCR, self).__init__() self.max_len = max_len self.dictionary = dictionary self.dict_size = len(dictionary) n_decoders = 4 embd_dim = 320 nhead = 4 #self.backbone = LocalViT_FeatureExtractor(48, 3, dim = embd_dim, ff_dim = embd_dim * 4, n_layers = n_encoders) self.backbone = ConvNext_FeatureExtractor(48, 3, embd_dim) self.encoders = nn.ModuleList() self.decoders = nn.ModuleList() for i in range(4) : encoder = nn.TransformerEncoderLayer(embd_dim, nhead, dropout = 0, batch_first = True, norm_first = True) encoder.self_attn = XposMultiheadAttention(embd_dim, nhead, self_attention = True) encoder.forward = transformer_encoder_forward self.encoders.append(encoder) self.encoders.forward = self.encoder_forward
for i in range(5) : decoder = nn.TransformerDecoderLayer(embd_dim, nhead, dropout = 0, batch_first = True, norm_first = True) decoder.self_attn = XposMultiheadAttention(embd_dim, nhead, self_attention = True) decoder.multihead_attn = XposMultiheadAttention(embd_dim, nhead, encoder_decoder_attention = True) self.decoders.append(decoder) self.decoders.forward = self.decoder_forward
self.embd = nn.Embedding(self.dict_size, embd_dim) self.pred1 = nn.Sequential(nn.Linear(embd_dim, embd_dim), nn.GELU(), nn.Dropout(0.15)) self.pred = nn.Linear(embd_dim, self.dict_size) self.pred.weight = self.embd.weight self.color_pred1 = nn.Sequential(nn.Linear(embd_dim, 64), nn.ReLU()) self.color_pred_fg = nn.Linear(64, 3) self.color_pred_bg = nn.Linear(64, 3) self.color_pred_fg_ind = nn.Linear(64, 2) self.color_pred_bg_ind = nn.Linear(64, 2)
def forward(self, img: torch.FloatTensor, char_idx: torch.LongTensor, decoder_mask: torch.BoolTensor, encoder_mask: torch.BoolTensor ): memory = self.backbone(img) memory = einops.rearrange(memory, 'N C 1 W -> N W C') for layer in self.encoders : memory = layer(memory, src_key_padding_mask = encoder_mask) N, L = char_idx.shape char_embd = self.embd(char_idx) # N, L, D casual_mask = generate_square_subsequent_mask(L).to(img.device) decoded = char_embd for layer in self.decoders : decoded = layer(decoded, memory, tgt_mask = casual_mask, tgt_key_padding_mask = decoder_mask, memory_key_padding_mask = encoder_mask) pred_char_logits = self.pred(self.pred1(decoded)) color_feats = self.color_pred1(decoded) return pred_char_logits, \ self.color_pred_fg(color_feats), \ self.color_pred_bg(color_feats), \ self.color_pred_fg_ind(color_feats), \ self.color_pred_bg_ind(color_feats)
def infer_beam_batch(self, img: torch.FloatTensor, img_widths: List[int], beams_k: int = 5, start_tok = 1, end_tok = 2, pad_tok = 0, max_finished_hypos: int = 2, max_seq_length = 384): N, C, H, W = img.shape assert H == 48 and C == 3 memory = self.backbone(img) memory = einops.rearrange(memory, 'N C 1 W -> N W C') valid_feats_length = [(x + 3) // 4 + 2 for x in img_widths] input_mask = torch.zeros(N, memory.size(1), dtype = torch.bool).to(img.device) for i, l in enumerate(valid_feats_length): input_mask[i, l:] = True for layer in self.encoders : memory = layer(layer, src = memory, src_key_padding_mask = input_mask) hypos = [Hypothesis(img.device, start_tok, end_tok, pad_tok, i, len(self.decoders), 320) for i in range(N)] # N, E decoded = next_token_batch(hypos, memory, input_mask, self.decoders, self.embd) # N, n_chars pred_char_logprob = self.pred(self.pred1(decoded)).log_softmax(-1) # N, k pred_chars_values, pred_chars_index = torch.topk(pred_char_logprob, beams_k, dim = 1) new_hypos: List[Hypothesis] = [] finished_hypos = defaultdict(list) for i in range(N): for k in range(beams_k): new_hypos.append(hypos[i].extend(pred_chars_index[i, k], pred_chars_values[i, k])) hypos = new_hypos for ixx in range(max_seq_length): # N * k, E decoded = next_token_batch(hypos, memory, torch.stack([input_mask[hyp.memory_idx] for hyp in hypos]) , self.decoders, self.embd) # N * k, n_chars pred_char_logprob = self.pred(self.pred1(decoded)).log_softmax(-1) # N * k, k pred_chars_values, pred_chars_index = torch.topk(pred_char_logprob, beams_k, dim = 1) hypos_per_sample = defaultdict(list) h: Hypothesis for i, h in enumerate(hypos): for k in range(beams_k): hypos_per_sample[h.memory_idx].append(h.extend(pred_chars_index[i, k], pred_chars_values[i, k])) hypos = [] # hypos_per_sample now contains N * k^2 hypos for i in hypos_per_sample.keys(): cur_hypos: List[Hypothesis] = hypos_per_sample[i] cur_hypos = sorted(cur_hypos, key = lambda a: a.sort_key())[: beams_k + 1] #print(cur_hypos[0].out_idx[-1]) to_added_hypos = [] sample_done = False for h in cur_hypos: if h.seq_end(): finished_hypos[i].append(h) if len(finished_hypos[i]) >= max_finished_hypos: sample_done = True break else: if len(to_added_hypos) < beams_k: to_added_hypos.append(h) if not sample_done: hypos.extend(to_added_hypos) if len(hypos) == 0: break # add remaining hypos to finished for i in range(N): if i not in finished_hypos: cur_hypos: List[Hypothesis] = hypos_per_sample[i] cur_hypo = sorted(cur_hypos, key = lambda a: a.sort_key())[0] finished_hypos[i].append(cur_hypo) assert len(finished_hypos) == N result = [] for i in range(N): cur_hypos = finished_hypos[i] cur_hypo = sorted(cur_hypos, key = lambda a: a.sort_key())[0] decoded = cur_hypo.output() color_feats = self.color_pred1(decoded) fg_pred, bg_pred, fg_ind_pred, bg_ind_pred = \ self.color_pred_fg(color_feats), \ self.color_pred_bg(color_feats), \ self.color_pred_fg_ind(color_feats), \ self.color_pred_bg_ind(color_feats) result.append((cur_hypo.out_idx[1:], cur_hypo.prob(), fg_pred[0], bg_pred[0], fg_ind_pred[0], bg_ind_pred[0])) return result
def infer_beam_batch_tensor(self, img: torch.FloatTensor, img_widths: List[int], beams_k: int = 5, start_tok = 1, end_tok = 2, pad_tok = 0, max_finished_hypos: int = 2, max_seq_length = 384): N, C, H, W = img.shape assert H == 48 and C == 3
memory = self.backbone(img) memory = einops.rearrange(memory, 'N C 1 W -> N W C') valid_feats_length = [(x + 3) // 4 + 2 for x in img_widths] input_mask = torch.zeros(N, memory.size(1), dtype = torch.bool).to(img.device) for i, l in enumerate(valid_feats_length): input_mask[i, l:] = True memory = self.encoders(memory, input_mask) # N, W, Dim
out_idx = torch.full((N, 1), start_tok, dtype=torch.long, device=img.device) # Shape [N, 1] cached_activations = torch.zeros(N, len(self.decoders)+1, max_seq_length, 320, device=img.device) # [N, L, S, E] log_probs = torch.zeros(N, 1, device=img.device) # Shape [N, 1] # N, E idx_embedded = self.embd(out_idx[:, -1:])
decoded, cached_activations = self.decoders(idx_embedded, cached_activations, memory, input_mask, 0) pred_char_logprob = self.pred(self.pred1(decoded)).log_softmax(-1) # N, n_chars pred_chars_values, pred_chars_index = torch.topk(pred_char_logprob, beams_k, dim = 1) # N, k
out_idx = torch.cat([out_idx.unsqueeze(1).expand(-1, beams_k, -1), pred_chars_index.unsqueeze(-1)], dim=-1).reshape(-1, 2) # Shape [N * k, 2] log_probs = pred_chars_values.view(-1, 1) # Shape [N * k, 1] memory = memory.repeat_interleave(beams_k, dim=0) input_mask = input_mask.repeat_interleave(beams_k, dim=0) cached_activations = cached_activations.repeat_interleave(beams_k, dim=0) batch_index = torch.arange(N).repeat_interleave(beams_k, dim=0).to(img.device)
finished_hypos = defaultdict(list) N_remaining = N
for step in range(1, max_seq_length): idx_embedded = self.embd(out_idx[:, -1:]) decoded, cached_activations = self.decoders(idx_embedded, cached_activations, memory, input_mask, step) pred_char_logprob = self.pred(self.pred1(decoded)).log_softmax(-1) # Shape [N * k, dict_size] pred_chars_values, pred_chars_index = torch.topk(pred_char_logprob, beams_k, dim=1) # [N * k, k]
finished = out_idx[:, -1] == end_tok pred_chars_values[finished] = 0 pred_chars_index[finished] = end_tok
# Extend hypotheses new_out_idx = out_idx.unsqueeze(1).expand(-1, beams_k, -1) # Shape [N * k, k, seq_len] new_out_idx = torch.cat([new_out_idx, pred_chars_index.unsqueeze(-1)], dim=-1) # Shape [N * k, k, seq_len + 1] new_out_idx = new_out_idx.view(-1, step + 2) # Reshape to [N * k^2, seq_len + 1] new_log_probs = log_probs.unsqueeze(1).expand(-1, beams_k, -1) + pred_chars_values.unsqueeze(-1) # Shape [N * k^2, 1] new_log_probs = new_log_probs.view(-1, 1) # [N * k^2, 1]
# Sort and select top-k hypotheses per sample new_out_idx = new_out_idx.view(N_remaining, -1, step + 2) # [N, k^2, seq_len + 1] new_log_probs = new_log_probs.view(N_remaining, -1) # [N, k^2] batch_topk_log_probs, batch_topk_indices = new_log_probs.topk(beams_k, dim=1) # [N, k] # Gather the top-k hypotheses based on log probabilities expanded_topk_indices = batch_topk_indices.unsqueeze(-1).expand(-1, -1, new_out_idx.shape[-1]) # Shape [N, k, seq_len + 1] out_idx = torch.gather(new_out_idx, 1, expanded_topk_indices).reshape(-1, step + 2) # [N * k, seq_len + 1] log_probs = batch_topk_log_probs.view(-1, 1) # Reshape to [N * k, 1]
# Check for finished sequences finished = (out_idx[:, -1] == end_tok) # Check if the last token is the end token finished = finished.view(N_remaining, beams_k) # Reshape to [N, k] finished_counts = finished.sum(dim=1) # Count the number of finished hypotheses per sample finished_batch_indices = (finished_counts >= max_finished_hypos).nonzero(as_tuple=False).squeeze()
if finished_batch_indices.numel() == 0: continue
if finished_batch_indices.dim() == 0: finished_batch_indices = finished_batch_indices.unsqueeze(0) for idx in finished_batch_indices: batch_log_probs = batch_topk_log_probs[idx] best_beam_idx = batch_log_probs.argmax() finished_hypos[batch_index[beams_k * idx].item()] = \ out_idx[idx * beams_k + best_beam_idx], \ torch.exp(batch_log_probs[best_beam_idx]).item(), \ cached_activations[idx * beams_k + best_beam_idx]
remaining_indexs = [] for i in range(N_remaining): if i not in finished_batch_indices: for j in range(beams_k): remaining_indexs.append(i * beams_k + j)
if not remaining_indexs: break
N_remaining = int(len(remaining_indexs) / beams_k) out_idx = out_idx.index_select(0, torch.tensor(remaining_indexs, device=img.device)) log_probs = log_probs.index_select(0, torch.tensor(remaining_indexs, device=img.device)) memory = memory.index_select(0, torch.tensor(remaining_indexs, device=img.device)) cached_activations = cached_activations.index_select(0, torch.tensor(remaining_indexs, device=img.device)) input_mask = input_mask.index_select(0, torch.tensor(remaining_indexs, device=img.device)) batch_index = batch_index.index_select(0, torch.tensor(remaining_indexs, device=img.device))
# Ensure we have the correct number of finished hypotheses for each sample assert len(finished_hypos) == N
# Final output processing and color predictions result = [] for i in range(N): final_idx, prob, decoded = finished_hypos[i] color_feats = self.color_pred1(decoded[-1].unsqueeze(0)) fg_pred, bg_pred, fg_ind_pred, bg_ind_pred = \ self.color_pred_fg(color_feats), \ self.color_pred_bg(color_feats), \ self.color_pred_fg_ind(color_feats), \ self.color_pred_bg_ind(color_feats) result.append((final_idx[1:], prob, fg_pred[0], bg_pred[0], fg_ind_pred[0], bg_ind_pred[0]))
return result
def encoder_forward(self, memory, encoder_mask): for layer in self.encoders : memory = layer(layer, src = memory, src_key_padding_mask = encoder_mask) return memory
def decoder_forward( self, embd: torch.Tensor, cached_activations: torch.Tensor, # Shape [N, L, T, E] where L=num_layers, T=sequence length, E=embedding size memory: torch.Tensor, # Shape [N, H, W, C] (Encoder memory output) memory_mask: torch.BoolTensor, step: int ):
layer: nn.TransformerDecoderLayer tgt = embd # N, 1, E for the last token embedding
for l, layer in enumerate(self.decoders): combined_activations = cached_activations[:, l, :step, :] # N, T, E combined_activations = torch.cat([combined_activations, tgt], dim=1) # N, T+1, E cached_activations[:, l, step, :] = tgt.squeeze(1)
# Update cache and perform self attention tgt = tgt + layer.self_attn(layer.norm1(tgt), layer.norm1(combined_activations), layer.norm1(combined_activations), q_offset=step)[0] tgt = tgt + layer.multihead_attn(layer.norm2(tgt), memory, memory, key_padding_mask=memory_mask, q_offset=step)[0] tgt = tgt + layer._ff_block(layer.norm3(tgt))
cached_activations[:, l+1, step, :] = tgt.squeeze(1) # Append the new activations
return tgt.squeeze_(1), cached_activations
import numpy as np
def convert_pl_model(filename: str) : sd = torch.load(filename, map_location = 'cpu')['state_dict'] sd2 = {} for k, v in sd.items() : k: str k = k.removeprefix('model.') sd2[k] = v return sd2
def test_LocalViT_FeatureExtractor() : net = ConvNext_FeatureExtractor(48, 3, 320) inp = torch.randn(2, 3, 48, 512) out = net(inp) print(out.shape)
def test_infer() : with open('alphabet-all-v7.txt', 'r') as fp : dictionary = [s[:-1] for s in fp.readlines()] model = OCR(dictionary, 32) model.eval() sd = convert_pl_model('epoch=0-step=13000.ckpt') model.load_state_dict(sd) model_parameters = filter(lambda p: p.requires_grad, model.parameters()) params = sum([np.prod(p.size()) for p in model_parameters]) print(params)
img = cv2.cvtColor(cv2.imread('test3.png'), cv2.COLOR_BGR2RGB) ratio = img.shape[1] / float(img.shape[0]) new_w = int(round(ratio * 48)) #print(img.shape) img = cv2.resize(img, (new_w, 48), interpolation=cv2.INTER_AREA)
img_torch = einops.rearrange((torch.from_numpy(img) / 127.5 - 1.0), 'h w c -> 1 c h w')
with torch.no_grad() : idx, prob, fg_pred, bg_pred, fg_ind_pred, bg_ind_pred = model.infer_beam_batch_tensor(img_torch, [new_w], 5, max_seq_length = 32)[0] txt = '' for i in idx : txt += dictionary[i] print(txt, prob) for chid, fg, bg, fg_ind, bg_ind in zip(idx, fg_pred[0], bg_pred[0], fg_ind_pred[0], bg_ind_pred[0]) : has_fg = (fg_ind[1] > fg_ind[0]).item() has_bg = (bg_ind[1] > bg_ind[0]).item() if has_fg : fg = np.clip((fg * 255).numpy(), 0, 255) if has_bg : bg = np.clip((bg * 255).numpy(), 0, 255) print(f'{dictionary[chid]} {fg if has_fg else "None"} {bg if has_bg else "None"}')
if __name__ == "__main__": test_infer()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503# modified from https://github.com/zyddnys/manga-image-translator/blob/main/ocr/model_48px_ctc.py
import torchimport torch.nn as nnimport torch.nn.functional as F
import numpy as npimport mathimport einops
from typing import List, Tuple, Optional
from utils.textblock import TextBlock
class PositionalEncoding(nn.Module): def __init__(self, d_model, dropout=0.1, max_len=5000): super(PositionalEncoding, self).__init__() self.dropout = nn.Dropout(p=dropout)
pe = torch.zeros(max_len, d_model) position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) pe = pe.unsqueeze(0) self.register_buffer('pe', pe)
def forward(self, x, offset = 0): x = x + self.pe[:, offset: offset + x.size(1), :] return x
class CustomTransformerEncoderLayer(nn.Module): r"""TransformerEncoderLayer is made up of self-attn and feedforward network. This standard encoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in Neural Information Processing Systems, pages 6000-6010. Users may modify or implement in a different way during application. Args: d_model: the number of expected features in the input (required). nhead: the number of heads in the multiheadattention models (required). dim_feedforward: the dimension of the feedforward network model (default=2048). dropout: the dropout value (default=0.1). activation: the activation function of intermediate layer, relu or gelu (default=relu). layer_norm_eps: the eps value in layer normalization components (default=1e-5). batch_first: If ``True``, then the input and output tensors are provided as (batch, seq, feature). Default: ``False``. norm_first: if ``True``, layer norm is done prior to attention and feedforward operations, respectivaly. Otherwise it's done after. Default: ``False`` (after). Examples:: >>> encoder_layer = nn.TransformerEncoderLayer(d_model=512, nhead=8) >>> src = torch.rand(10, 32, 512) >>> out = encoder_layer(src) Alternatively, when ``batch_first`` is ``True``: >>> encoder_layer = nn.TransformerEncoderLayer(d_model=512, nhead=8, batch_first=True) >>> src = torch.rand(32, 10, 512) >>> out = encoder_layer(src) """ __constants__ = ['batch_first', 'norm_first']
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation="gelu", layer_norm_eps=1e-5, batch_first=False, norm_first=False, device=None, dtype=None) -> None: factory_kwargs = {'device': device, 'dtype': dtype} super(CustomTransformerEncoderLayer, self).__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout, batch_first=batch_first, **factory_kwargs) # Implementation of Feedforward model self.linear1 = nn.Linear(d_model, dim_feedforward, **factory_kwargs) self.dropout = nn.Dropout(dropout) self.linear2 = nn.Linear(dim_feedforward, d_model, **factory_kwargs)
self.norm_first = norm_first self.norm1 = nn.LayerNorm(d_model, eps=layer_norm_eps, **factory_kwargs) self.norm2 = nn.LayerNorm(d_model, eps=layer_norm_eps, **factory_kwargs) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(dropout) self.pe = PositionalEncoding(d_model, max_len = 3072)
self.activation = F.gelu
def __setstate__(self, state): if 'activation' not in state: state['activation'] = F.relu super(CustomTransformerEncoderLayer, self).__setstate__(state)
def forward(self, src: torch.Tensor, src_mask: Optional[torch.Tensor] = None, src_key_padding_mask: Optional[torch.Tensor] = None, is_causal = None) -> torch.Tensor: r"""Pass the input through the encoder layer. Args: src: the sequence to the encoder layer (required). src_mask: the mask for the src sequence (optional). src_key_padding_mask: the mask for the src keys per batch (optional). Shape: see the docs in Transformer class. """
# see Fig. 1 of https://arxiv.org/pdf/2002.04745v1.pdf
x = src if self.norm_first: x = x + self._sa_block(self.norm1(x), src_mask, src_key_padding_mask) x = x + self._ff_block(self.norm2(x)) else: x = self.norm1(x + self._sa_block(x, src_mask, src_key_padding_mask)) x = self.norm2(x + self._ff_block(x))
return x
# self-attention block def _sa_block(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor], key_padding_mask: Optional[torch.Tensor]) -> torch.Tensor: x = self.self_attn(self.pe(x), self.pe(x), x, # no PE for value attn_mask=attn_mask, key_padding_mask=key_padding_mask, need_weights=False)[0] return self.dropout1(x)
# feed forward block def _ff_block(self, x: torch.Tensor) -> torch.Tensor: x = self.linear2(self.dropout(self.activation(self.linear1(x)))) return self.dropout2(x)
class ResNet(nn.Module):
def __init__(self, input_channel, output_channel, block, layers): super(ResNet, self).__init__()
self.output_channel_block = [int(output_channel / 4), int(output_channel / 2), output_channel, output_channel]
self.inplanes = int(output_channel / 8) self.conv0_1 = nn.Conv2d(input_channel, int(output_channel / 8), kernel_size=3, stride=1, padding=1, bias=False) self.bn0_1 = nn.BatchNorm2d(int(output_channel / 8)) self.conv0_2 = nn.Conv2d(int(output_channel / 8), self.inplanes, kernel_size=3, stride=1, padding=1, bias=False)
self.maxpool1 = nn.AvgPool2d(kernel_size=2, stride=2, padding=0) self.layer1 = self._make_layer(block, self.output_channel_block[0], layers[0]) self.bn1 = nn.BatchNorm2d(self.output_channel_block[0]) self.conv1 = nn.Conv2d(self.output_channel_block[0], self.output_channel_block[ 0], kernel_size=3, stride=1, padding=1, bias=False)
self.maxpool2 = nn.AvgPool2d(kernel_size=2, stride=2, padding=0) self.layer2 = self._make_layer(block, self.output_channel_block[1], layers[1], stride=1) self.bn2 = nn.BatchNorm2d(self.output_channel_block[1]) self.conv2 = nn.Conv2d(self.output_channel_block[1], self.output_channel_block[ 1], kernel_size=3, stride=1, padding=1, bias=False)
self.maxpool3 = nn.AvgPool2d(kernel_size=2, stride=(2, 1), padding=(0, 1)) self.layer3 = self._make_layer(block, self.output_channel_block[2], layers[2], stride=1) self.bn3 = nn.BatchNorm2d(self.output_channel_block[2]) self.conv3 = nn.Conv2d(self.output_channel_block[2], self.output_channel_block[ 2], kernel_size=3, stride=1, padding=1, bias=False)
self.layer4 = self._make_layer(block, self.output_channel_block[3], layers[3], stride=1) self.bn4_1 = nn.BatchNorm2d(self.output_channel_block[3]) self.conv4_1 = nn.Conv2d(self.output_channel_block[3], self.output_channel_block[ 3], kernel_size=3, stride=(2, 1), padding=(1, 1), bias=False) self.bn4_2 = nn.BatchNorm2d(self.output_channel_block[3]) self.conv4_2 = nn.Conv2d(self.output_channel_block[3], self.output_channel_block[ 3], kernel_size=3, stride=1, padding=0, bias=False) self.bn4_3 = nn.BatchNorm2d(self.output_channel_block[3])
def _make_layer(self, block, planes, blocks, stride=1): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.BatchNorm2d(self.inplanes), nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), )
layers = [] layers.append(block(self.inplanes, planes, stride, downsample)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes))
return nn.Sequential(*layers)
def forward(self, x): x = self.conv0_1(x) x = self.bn0_1(x) x = F.relu(x) x = self.conv0_2(x)
x = self.maxpool1(x) x = self.layer1(x) x = self.bn1(x) x = F.relu(x) x = self.conv1(x)
x = self.maxpool2(x) x = self.layer2(x) x = self.bn2(x) x = F.relu(x) x = self.conv2(x)
x = self.maxpool3(x) x = self.layer3(x) x = self.bn3(x) x = F.relu(x) x = self.conv3(x)
x = self.layer4(x)
x = self.bn4_1(x) x = F.relu(x) x = self.conv4_1(x) x = self.bn4_2(x) x = F.relu(x) x = self.conv4_2(x) x = self.bn4_3(x)
return x
class BasicBlock(nn.Module): expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.bn1 = nn.BatchNorm2d(inplanes) self.conv1 = self._conv3x3(inplanes, planes) self.bn2 = nn.BatchNorm2d(planes) self.conv2 = self._conv3x3(planes, planes) self.downsample = downsample self.stride = stride
def _conv3x3(self, in_planes, out_planes, stride=1): "3x3 convolution with padding" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
def forward(self, x): residual = x
out = self.bn1(x) out = F.relu(out) out = self.conv1(out)
out = self.bn2(out) out = F.relu(out) out = self.conv2(out)
if self.downsample is not None: residual = self.downsample(residual)
return out + residual
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
def conv1x1(in_planes, out_planes, stride=1): """1x1 convolution""" return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
class ResNet_FeatureExtractor(nn.Module): """ FeatureExtractor of FAN (http://openaccess.thecvf.com/content_ICCV_2017/papers/Cheng_Focusing_Attention_Towards_ICCV_2017_paper.pdf) """
def __init__(self, input_channel, output_channel=128): super(ResNet_FeatureExtractor, self).__init__() self.ConvNet = ResNet(input_channel, output_channel, BasicBlock, [4, 6, 8, 6, 3])
def forward(self, input): return self.ConvNet(input) class OCR(nn.Module) : def __init__(self, dictionary, max_len): super(OCR, self).__init__() self.max_len = max_len self.dictionary = dictionary self.dict_size = len(dictionary) self.backbone = ResNet_FeatureExtractor(3, 320) enc = CustomTransformerEncoderLayer(320, 8, 320 * 4, dropout=0.05,batch_first=True,norm_first=True) self.encoders = nn.TransformerEncoder(enc, 3) self.char_pred_norm = nn.Sequential(nn.LayerNorm(320), nn.Dropout(0.1), nn.GELU()) self.char_pred = nn.Linear(320, self.dict_size) self.color_pred1 = nn.Sequential(nn.Linear(320, 6))
def forward(self, img: torch.FloatTensor ) : feats = self.backbone(img).squeeze(2) feats = self.encoders(feats.permute(0, 2, 1)) pred_char_logits = self.char_pred(self.char_pred_norm(feats)) pred_color_values = self.color_pred1(feats) return pred_char_logits, pred_color_values
def decode(self, img: torch.Tensor, img_widths: List[int], blank, verbose = False) -> List[List[Tuple[str, float, int, int, int, int, int, int]]] : N, C, H, W = img.shape assert H == 48 and C == 3 feats = self.backbone(img).squeeze(2) feats = self.encoders(feats.permute(0, 2, 1)) pred_char_logits = self.char_pred(self.char_pred_norm(feats)) pred_color_values = self.color_pred1(feats) return self.decode_ctc_top1(pred_char_logits, pred_color_values, blank, verbose = verbose)
def decode_ctc_top1(self, pred_char_logits, pred_color_values, blank, verbose = False) -> List[List[Tuple[str, float, int, int, int, int, int, int]]] : pred_chars: List[List[Tuple[str, float, int, int, int, int, int, int]]] = [] for _ in range(pred_char_logits.size(0)) : pred_chars.append([]) logprobs = pred_char_logits.log_softmax(2) _, preds_index = logprobs.max(2) preds_index = preds_index.cpu() pred_color_values = pred_color_values.cpu().clamp_(0, 1) for b in range(pred_char_logits.size(0)) : if verbose : print('------------------------------') last_ch = blank for t in range(pred_char_logits.size(1)) : pred_ch = preds_index[b, t] if pred_ch != last_ch and pred_ch != blank : lp = logprobs[b, t, pred_ch].item() if verbose : if lp < math.log(0.9) : top5 = torch.topk(logprobs[b, t], 5) top5_idx = top5.indices top5_val = top5.values r = '' for i in range(5) : r += f'{self.dictionary[top5_idx[i]]}: {math.exp(top5_val[i])}, ' print(r) else : print(f'{self.dictionary[pred_ch]}: {math.exp(lp)}') pred_chars[b].append(( pred_ch, lp, pred_color_values[b, t][0].item(), pred_color_values[b, t][1].item(), pred_color_values[b, t][2].item(), pred_color_values[b, t][3].item(), pred_color_values[b, t][4].item(), pred_color_values[b, t][5].item() )) last_ch = pred_ch return pred_chars
def eval_ocr(self, input_lengths, target_lengths, pred_char_logits, pred_color_values, gt_char_index, gt_color_values, blank, blank1) : correct_char = 0 total_char = 0 color_diff = 0 color_diff_dom = 0 _, preds_index = pred_char_logits.max(2) pred_chars = torch.zeros_like(gt_char_index).cpu() for b in range(pred_char_logits.size(0)) : last_ch = blank i = 0 for t in range(input_lengths[b]) : pred_ch = preds_index[b, t] if pred_ch != last_ch and pred_ch != blank : total_char += 1 if gt_char_index[b, i] == pred_ch : correct_char += 1 if pred_ch != blank1 : color_diff += ((pred_color_values[b, t] - gt_color_values[b, i]).abs().mean() * 255.0).item() color_diff_dom += 1 pred_chars[b, i] = pred_ch i += 1 if i >= gt_color_values.size(1) or i >= gt_char_index.size(1) : break last_ch = pred_ch return correct_char / (total_char + 1), color_diff / (color_diff_dom + 1), pred_chars
def chunks(lst, n): """Yield successive n-sized chunks from lst.""" for i in range(0, len(lst), n): yield lst[i:i + n]
class AvgMeter() : def __init__(self) : self.reset()
def reset(self) : self.sum = 0 self.count = 0
def __call__(self, val = None) : if val is not None : self.sum += val self.count += 1 if self.count > 0 : return self.sum / self.count else : return 0
class OCR48pxCTC:
def __init__(self, model_path: str, device='cpu'): with open('data/alphabet-all-v5.txt', 'r', encoding = 'utf-8') as fp : dictionary = [s[:-1] for s in fp.readlines()] self.device = device self.text_height = 48 self.maxwidth = 8100
model = OCR(dictionary, 768) sd = torch.load(model_path, map_location = 'cpu') del sd['encoders.layers.0.pe.pe'] del sd['encoders.layers.1.pe.pe'] del sd['encoders.layers.2.pe.pe'] model.load_state_dict(sd['model'] if 'model' in sd else sd, strict=False) model.eval() if self.device != 'cpu' : model = model.to(self.device) self.net = model
def to(self, device: str) -> None: self.net.to(device) self.device = device
@torch.no_grad() def __call__(self, textblk_lst: List[TextBlock], regions: List[np.ndarray], textblk_lst_indices: List, chunk_size = 16) -> None:
perm = range(len(regions)) chunck_idx = 0 for indices in chunks(perm, chunk_size) : N = len(indices) widths = [regions[i].shape[1] for i in indices] # max_width = 4 * (max(widths) + 7) // 4 max_width = (4 * (max(widths) + 7) // 4) + 128 region = np.zeros((N, self.text_height, max_width, 3), dtype = np.uint8) for i, idx in enumerate(indices) : W = regions[idx].shape[1] region[i, :, : W, :] = regions[idx] images = (torch.from_numpy(region).float() - 127.5) / 127.5 images = einops.rearrange(images, 'N H W C -> N C H W') if self.device != 'cpu': images = images.to(self.device) with torch.inference_mode() : texts = self.net.decode(images, widths, 0) for i, single_line in enumerate(texts) : if not single_line : continue textblk = textblk_lst[textblk_lst_indices[i+chunck_idx]] cur_texts = [] total_fr = AvgMeter() total_fg = AvgMeter() total_fb = AvgMeter() total_br = AvgMeter() total_bg = AvgMeter() total_bb = AvgMeter() total_logprob = AvgMeter() for (chid, logprob, fr, fg, fb, br, bg, bb) in single_line : ch = self.net.dictionary[chid] if ch == '<SP>' : ch = ' ' cur_texts.append(ch) total_logprob(logprob) if ch != ' ' : total_fr(int(fr * 255)) total_fg(int(fg * 255)) total_fb(int(fb * 255)) total_br(int(br * 255)) total_bg(int(bg * 255)) total_bb(int(bb * 255)) prob = np.exp(total_logprob()) if prob < 0.3 : continue textblk.text.append(''.join(cur_texts)) textblk.update_font_colors( [int(total_fr()), int(total_fg()), int(total_fb())], [int(total_br()), int(total_bg()), int(total_bb())] ) chunck_idx += N
# def test2() :# with open('alphabet-all-v5.txt', 'r') as fp :# dictionary = [s[:-1] for s in fp.readlines()]# img = torch.randn(4, 3, 48, 1536)# idx = torch.zeros(4, 32).long()# mask = torch.zeros(4, 32).bool()# model = OCR(dictionary, 1024)# pred_char_logits, pred_color_values = model(img)# print(pred_char_logits.shape, pred_color_values.shape)
# def test_inference() :# with torch.no_grad() :# with open('../SynthText/alphabet-all-v3.txt', 'r') as fp :# dictionary = [s[:-1] for s in fp.readlines()]# img = torch.zeros(1, 3, 32, 128)# model = OCR(dictionary, 32)# m = torch.load("ocr_ar_v2-3-test.ckpt", map_location='cpu')# model.load_state_dict(m['model'])# model.eval()# (char_probs, _, _, _, _, _, _, _), _ = model.infer_beam(img, max_seq_length = 20)# _, pred_chars_index = char_probs.max(2)# pred_chars_index = pred_chars_index.squeeze_(0)# seq = []# for chid in pred_chars_index :# ch = dictionary[chid]# if ch == '<SP>' :# ch == ' '# seq.append(ch)# print(''.join(seq))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430import reimport numpy as npimport timeimport cv2import randomimport stringfrom typing import Listimport osimport base64import uuidimport json
import httpxfrom PIL import Image as PilImageimport ioimport http.cookiejar as cookielibfrom urllib.parse import urlparse, parse_qs
from .base import register_OCR, OCRBase, TextBlock
class BingOCRCore: API_ENDPOINT = 'https://www.bing.com/images/api/custom/knowledge' UPLOAD_ENDPOINT = 'https://www.bing.com/images/search?view=detailv2&iss=sbiupload&FORM=SBIIDP&sbisrc=ImgDropper&idpbck=1' HEADERS = { 'accept': '*/*', 'accept-language': 'ru,en;q=0.9,en-GB;q=0.8,en-US;q=0.7', 'origin': 'https://www.bing.com', 'referer': 'https://www.bing.com/images/search?view=detailV2&iss=SBIUPLOADGET&sbisrc=ImgDropper', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0' }
def __init__(self, proxy=None): self.proxy = proxy self.cookie_jar = cookielib.CookieJar()
def _send_request(self, url, headers, data=None, files=None, cookies=None, follow_redirects=False, timeout=10.0): try: client_kwargs = {} if self.proxy: if isinstance(self.proxy, str): client_kwargs['proxy'] = self.proxy elif isinstance(self.proxy, dict): mounts = {} if 'http://' in self.proxy: mounts["http://"] = httpx.HTTPTransport(proxy=self.proxy['http://']) if 'https://' in self.proxy: mounts["https://"] = httpx.HTTPTransport(proxy=self.proxy['https://']) if mounts: client_kwargs['mounts'] = mounts else: raise ValueError("Proxy must be a string or a dictionary") client = httpx.Client(**client_kwargs, timeout=timeout) response = client.post(url, headers=headers, data=data, files=files, cookies=cookies, follow_redirects=follow_redirects) return response except httpx.TimeoutException as e: raise Exception(f"Request to {url} timed out: {e}") except httpx.HTTPError as e: # Обработка HTTP ошибок остается raise Exception(f"HTTP error {e.response.status_code} during request to {url}: {e.response.text}") except Exception as e: raise Exception(f"Request to {url} failed: {e}")
def upload_image(self, image_path=None, image_buffer=None): try: image_base64 = None
if image_path: with open(image_path, "rb") as image_file: image_data = image_file.read() image_base64 = base64.b64encode(image_data).decode('utf-8') img = PilImage.open(image_path) elif image_buffer: image_base64 = base64.b64encode(image_buffer).decode('utf-8') img = PilImage.open(io.BytesIO(image_buffer)) else: raise ValueError("Either image_path or image_buffer must be provided")
width, height = img.size file_size_bytes = len(image_buffer) if image_buffer else os.path.getsize(image_path) file_size_kb = round(file_size_bytes / 1024, 2) file_name = os.path.basename(image_path) if image_path else "image_from_buffer.jpg" file_extension = os.path.splitext(image_path)[1][1:].lower() if image_path else "jpg"
sbifsz_value = f"{width}+x+{height}+%c2%b7+{file_size_kb}+kB+%c2%b7+{file_extension}" sbifnm_value = file_name thw_value = width thh_value = height expw_value = width exph_value = height
upload_url = f'{self.UPLOAD_ENDPOINT}&sbifsz={sbifsz_value}&sbifnm={sbifnm_value}&thw={thw_value}&thh={thh_value}&ptime=26&dlen=29932&expw={expw_value}&exph={exph_value}'
boundary_upload = f"----WebKitFormBoundary{uuid.uuid4().hex}" upload_headers = self.HEADERS.copy() upload_headers['content-type'] = f'multipart/form-data; boundary={boundary_upload}'
upload_data = f'''{boundary_upload}\r\nContent-Disposition: form-data; name="imgurl"\r\n\r\n\r\n{boundary_upload}\r\nContent-Disposition: form-data; name="cbir"\r\n\r\nsbi\r\n{boundary_upload}\r\nContent-Disposition: form-data; name="imageBin"\r\n\r\n{image_base64}\r\n{boundary_upload}--\r\n'''
upload_response = self._send_request(upload_url, upload_headers, data=upload_data.encode('utf-8'), follow_redirects=False)
if upload_response.status_code == 302: redirect_url = upload_response.headers.get('Location') if not redirect_url: raise Exception("Redirect 302 received but no Location header found.") else: upload_response.raise_for_status() redirect_url = None
if not redirect_url: raise Exception("No redirect URL received after image upload (not 302).")
parsed_url = urlparse(redirect_url) query_params = parse_qs(parsed_url.query) image_insights_token = query_params.get('insightsToken') if not image_insights_token: raise Exception("Image insights token not found in redirect URL.") return image_insights_token[0], upload_response.cookies
except Exception as e: raise Exception(f"Image upload failed: {e}")
def get_ocr_json(self, image_insights_token, upload_cookies=None): api_url = self.API_ENDPOINT boundary_ocr = f"----WebKitFormBoundary{uuid.uuid4().hex}" api_headers = self.HEADERS.copy() api_headers['content-type'] = f'multipart/form-data; boundary={boundary_ocr}' api_headers['referer'] = f'https://www.bing.com/images/search?view=detailV2&insightstoken={image_insights_token}'
api_data_json = { "imageInfo": {"imageInsightsToken": image_insights_token, "source": "Url"}, "knowledgeRequest": {"invokedSkills": ["OCR"], "index": 1} } api_data = f'''{boundary_ocr}\r\nContent-Disposition: form-data; name="knowledgeRequest"\r\n\r\n{json.dumps(api_data_json)}\r\n{boundary_ocr}--\r\n'''
try: api_response = self._send_request(api_url, api_headers, data=api_data.encode('utf-8'), cookies=upload_cookies) return api_response.json() except httpx.TimeoutException as e: raise Exception(f"OCR API request timed out: {e}") except httpx.HTTPError as e: raise Exception(f"HTTP error {e.response.status_code} during OCR API request to {api_url}: {e.response.text}") except Exception as e: raise Exception(f"OCR API request failed: {e}")
class BingOCR(BingOCRCore): def __init__(self, proxy=None): super().__init__(proxy=proxy)
def scan_by_file(self, file_path): image_insights_token, upload_cookies = self.upload_image(image_path=file_path) ocr_json = self.get_ocr_json(image_insights_token, upload_cookies) return ocr_json
def scan_by_buffer(self, buffer, filename=None): image_insights_token, upload_cookies = self.upload_image(image_buffer=buffer) ocr_json = self.get_ocr_json(image_insights_token, upload_cookies) return ocr_json
class BingOCRAPI: def __init__(self, proxy=None): self.bing_ocr = BingOCR(proxy=proxy)
@staticmethod def extract_text_and_coordinates(ocr_json_data): text_with_coords = [] try: ocr_tag = ocr_json_data['tags'][1]['actions'][0] if ocr_tag['_type'] == 'ImageKnowledge/TextRecognitionAction': regions = ocr_tag['data']['regions'] for region in regions: for line in region['lines']: line_text = line['text'] line_bbox = line['boundingBox'] text_with_coords.append({"text": line_text, "boundingBox": line_bbox}) except (KeyError, IndexError, TypeError): return [] return text_with_coords
@staticmethod def stitch_text_smart(text_with_coords): if not text_with_coords: return ""
def get_bbox_coords(bbox): return bbox['topLeft']['x'], bbox['topLeft']['y'], bbox['bottomRight']['x'], bbox['bottomRight']['y']
sorted_elements = sorted(text_with_coords, key=lambda x: (get_bbox_coords(x['boundingBox'])[1], get_bbox_coords(x['boundingBox'])[0]))
stitched_text = [] current_y_start = None current_line = []
for element in sorted_elements: bbox = get_bbox_coords(element['boundingBox']) y_start = bbox[1] text = element['text']
if current_y_start is None or abs(y_start - current_y_start) > 0.03: if current_line: stitched_text.append(" ".join(current_line)) current_line = [] current_y_start = y_start current_line.append(text)
if current_line: stitched_text.append(" ".join(current_line))
return "\n".join(stitched_text).strip()
@staticmethod def stitch_text_sequential(text_with_coords): return " ".join([item['text'] for item in text_with_coords]).strip() if text_with_coords else ""
def process_image(self, image_path=None, image_buffer=None, response_method="Full Text"): if image_path: ocr_json_data = self.bing_ocr.scan_by_file(image_path) elif image_buffer: ocr_json_data = self.bing_ocr.scan_by_buffer(image_buffer) else: raise ValueError("Either image_path or image_buffer must be provided")
text_with_coords = BingOCRAPI.extract_text_and_coordinates(ocr_json_data)
if response_method == "Full Text": return { 'full_text': BingOCRAPI.stitch_text_smart(text_with_coords), 'text_with_coordinates': text_with_coords } elif response_method == "Coordinate sequence": return { 'full_text': BingOCRAPI.stitch_text_sequential(text_with_coords), 'text_with_coordinates': text_with_coords } elif response_method == "Location coordinates": return { 'full_text': BingOCRAPI.stitch_text_smart(text_with_coords), 'text_with_coordinates': text_with_coords } else: raise ValueError("Invalid response method")
def format_bing_ocr_result(result): full_text = result.get("full_text", "") if not full_text: formatted_result = { "language": result.get("language", ""), "text_with_coordinates": [ f"{item['text']}: {item['boundingBox']}" for item in result.get("text_with_coordinates", []) ] } return json.dumps(formatted_result, indent=4, ensure_ascii=False) else: return f"OCR Text: '{full_text}'"
@register_OCR('bing_ocr')class OCRBingAPI(OCRBase): params = { "delay": 1.0, 'newline_handling': { 'type': 'selector', 'options': [ 'preserve', 'remove' ], 'value': 'preserve', 'description': 'Choose how to handle newline characters in OCR result' }, 'no_uppercase': { 'type': 'checkbox', 'value': False, 'description': 'Convert text to lowercase except the first letter of each sentence' }, 'response_method': { 'type': 'selector', 'options': [ 'Full Text', 'Coordinate sequence', 'Location coordinates' ], 'value': 'Full Text', 'description': 'Choose the method for extracting text from image' }, 'proxy': { 'value': '', 'description': 'Proxy address (e.g., http(s)://user:password@host:port or socks4/5://user:password@host:port)' }, 'description': 'OCR using Bing OCR API' }
@property def request_delay(self): try: return float(self.get_param_value('delay')) except (ValueError, TypeError): return 1.0
@property def newline_handling(self): return self.get_param_value('newline_handling')
@property def no_uppercase(self): return self.get_param_value('no_uppercase')
@property def response_method(self): return self.get_param_value('response_method')
@property def proxy(self): return self.get_param_value('proxy')
def __init__(self, **params) -> None: if 'delay' in params: try: params['delay'] = float(params['delay']) except (ValueError, TypeError): params['delay'] = 1.0 super().__init__(**params) self.api = BingOCRAPI(proxy=self.proxy) self.last_request_time = 0
def _ocr_blk_list(self, img: np.ndarray, blk_list: List[TextBlock], *args, **kwargs): im_h, im_w = img.shape[:2] if self.debug_mode: self.logger.debug(f'Image size: {im_h}x{im_w}') for blk in blk_list: x1, y1, x2, y2 = blk.xyxy if self.debug_mode: self.logger.debug(f'Processing block: ({x1, y1, x2, y2})') if y2 < im_h and x2 < im_w and x1 > 0 and y1 > 0 and x1 < x2 and y1 < y2: cropped_img = img[y1:y2, x1:x2] if self.debug_mode: self.logger.debug(f'Cropped image size: {cropped_img.shape}') blk.text = self.ocr(cropped_img) else: if self.debug_mode: self.logger.warning('Invalid text bbox to target image') blk.text = ['']
def ocr_img(self, img: np.ndarray) -> str: if self.debug_mode: self.logger.debug(f'ocr_img: {img.shape}') return self.ocr(img)
def ocr(self, img: np.ndarray) -> str: if self.debug_mode: self.logger.debug(f'Starting OCR on image of shape: {img.shape}') self._respect_delay() try: if img.size > 0: if self.debug_mode: self.logger.debug(f'Input image size: {img.shape}') _, buffer = cv2.imencode('.jpg', img) result = self.api.process_image(image_buffer=buffer.tobytes(), response_method=self.response_method) if self.debug_mode: formatted_result = format_bing_ocr_result(result) self.logger.debug(f'OCR result: {formatted_result}')
full_text = result['full_text'] if self.newline_handling == 'remove': full_text = full_text.replace('\n', ' ')
full_text = self._apply_punctuation_and_spacing(full_text)
if self.no_uppercase: full_text = self._apply_no_uppercase(full_text)
if isinstance(full_text, list): return '\n'.join(full_text) else: return full_text else: if self.debug_mode: self.logger.warning('Empty image provided for OCR') return '' except Exception as e: if self.debug_mode: self.logger.error(f"OCR error: {str(e)}") return ''
def _apply_no_uppercase(self, text: str) -> str: def process_sentence(sentence): words = sentence.split() if not words: return '' processed = [words[0].capitalize()] + [word.lower() for word in words[1:]] return ' '.join(processed)
sentences = re.split(r'(?<=[.!?…])\s+', text) processed_sentences = [process_sentence(sentence) for sentence in sentences]
return ' '.join(processed_sentences)
def _apply_punctuation_and_spacing(self, text: str) -> str: text = re.sub(r'\s+([,.!?…])', r'\1', text) text = re.sub(r'([,.!?…])(?!\s)(?![,.!?…])', r'\1 ', text) text = re.sub(r'([,.!?…])\s+([,.!?…])', r'\1\2', text) return text.strip()
def _respect_delay(self): current_time = time.time() time_since_last_request = current_time - self.last_request_time if self.debug_mode: self.logger.info(f'Time since last request: {time_since_last_request} seconds')
if time_since_last_request < self.request_delay: sleep_time = self.request_delay - time_since_last_request if self.debug_mode: self.logger.info(f'Sleeping for {sleep_time} seconds') time.sleep(sleep_time) self.last_request_time = time.time()
def updateParam(self, param_key: str, param_content): if param_key == 'delay': try: param_content = float(param_content) except (ValueError, TypeError): param_content = 1.0 super().updateParam(param_key, param_content) if param_key == 'proxy': self.api.bing_ocr.proxy = self.proxy self.api.bing_ocr.client = None 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275import reimport timeimport base64import jsonimport cv2import numpy as npfrom typing import Listimport httpx
from .base import register_OCR, OCRBase, TextBlock
import logginghttpx_logger = logging.getLogger("httpx")httpx_logger.setLevel(logging.WARNING)
@register_OCR('google_vision')class OCRGoogleVisionAPI(OCRBase): params = { 'api_key': '', 'language_hints': { 'value': '', 'description': 'Language codes separated by commas (BCP-47)' }, 'proxy': { 'value': '', 'description': 'Proxy address (e.g., http(s)://user:password@host:port or socks4/5://user:password@host:port)' }, 'delay': 0.0, 'newline_handling': { 'type': 'selector', 'options': [ 'preserve', 'remove' ], 'value': 'preserve', 'description': 'Choose how to handle newline characters in OCR results' }, 'no_uppercase': { 'type': 'checkbox', 'value': False, 'description': 'Convert text to lowercase except the first letter of each sentence' }, 'description': 'OCR using Google Vision API' }
@property def request_delay(self): try: return float(self.get_param_value('delay')) except (ValueError, TypeError): return 1.0
@property def language_hints(self): hints = self.get_param_value('language_hints') return [hint.strip() for hint in hints.split(",")] if hints else None
@property def api_key(self): return self.get_param_value('api_key')
@property def proxy(self): return self.get_param_value('proxy')
@property def newline_handling(self): return self.get_param_value('newline_handling')
@property def no_uppercase(self): return self.get_param_value('no_uppercase')
def __init__(self, **params) -> None: if 'delay' in params: try: params['delay'] = float(params['delay']) except (ValueError, TypeError): params['delay'] = 1.0 super().__init__(**params) self.proxy_url = self.proxy self.last_request_time = 0
def send_to_google_vision(self, image_buffer: bytes): VISION_API_URL = f"https://vision.googleapis.com/v1/images:annotate?key={self.api_key}"
image_content = base64.b64encode(image_buffer).decode("utf-8")
request_body = { "requests": [ { "image": { "content": image_content }, "features": [ { "type": "TEXT_DETECTION" } ] } ] }
if self.language_hints: request_body["requests"][0]["imageContext"] = { "languageHints": self.language_hints }
headers = { "Content-Type": "application/json" }
client_kwargs = {'headers': headers} if self.proxy_url: mounts = {} if self.proxy_url.startswith(('http://', 'https://', 'socks4://', 'socks5://')): mounts["all://"] = httpx.HTTPTransport(proxy=self.proxy_url) else: self.logger.warning("The proxy URL does not contain a schema (http://, https://, socks4://, socks5://). The proxy may not work.") mounts["all://"] = httpx.HTTPTransport(proxy=self.proxy_url) client_kwargs['mounts'] = mounts
with httpx.Client(**client_kwargs) as client: try: if self.debug_mode: proxy_info = self.proxy_url if self.proxy_url else "No proxy" self.logger.debug(f"Sending request to Google Vision API with proxy: {proxy_info}")
response = client.post(VISION_API_URL, headers=headers, json=request_body) response.raise_for_status()
return response.json() except httpx.HTTPError as e: raise Exception(f"Error during request to Google Vision API: {e}")
def extract_text_and_coordinates(self, annotations): text_with_coords = [] for annotation in annotations: if 'description' in annotation: words = annotation.get('description', '').split() vertices = annotation.get('boundingPoly', {}).get('vertices', []) text_with_coords.append({ "text": annotation['description'], "coordinates": [(v.get("x", 0), v.get("y", 0)) for v in vertices] }) return text_with_coords
def extract_full_text(self, response_json): try: return response_json['responses'][0]['fullTextAnnotation']['text'] except (IndexError, KeyError, TypeError): return "Full text not found or not recognized"
def process_image(self, image_buffer: bytes): response = self.send_to_google_vision(image_buffer) full_text = self.extract_full_text(response)
return { 'full_text': full_text, 'language': response['responses'][0].get('language', 'und'), 'text_with_coordinates': self.extract_text_and_coordinates(response.get("responses", [{}])[0].get("textAnnotations", [])) }
def format_ocr_result(self, result): formatted_result = { "language": result.get("language", ""), "full_text": result.get("full_text", ""), "text_with_coordinates": [ f"{item['text']}: {item['coordinates']}" for item in result.get("text_with_coordinates", []) ] } return json.dumps(formatted_result, indent=4, ensure_ascii=False)
def _ocr_blk_list(self, img: np.ndarray, blk_list: List[TextBlock], *args, **kwargs): im_h, im_w = img.shape[:2] if self.debug_mode: self.logger.debug(f'Image dimensions: {im_h}x{im_w}') for blk in blk_list: x1, y1, x2, y2 = blk.xyxy if self.debug_mode: self.logger.debug(f'Processing block: ({x1}, {y1}, {x2}, {y2})') if y2 < im_h and x2 < im_w and x1 >= 0 and y1 >= 0 and x1 < x2 and y1 < y2: cropped_img = img[y1:y2, x1:x2] if self.debug_mode: self.logger.debug(f'Cropped image dimensions: {cropped_img.shape}') blk.text = self.ocr(cropped_img) else: if self.debug_mode: self.logger.warning('Invalid text block coordinates') blk.text = ''
def ocr_img(self, img: np.ndarray) -> str: return self.ocr(img)
def ocr(self, img: np.ndarray) -> str: if self.debug_mode: self.logger.debug(f'Starting OCR on image of shape: {img.shape}') self._respect_delay() try: if img.size > 0: if self.debug_mode: self.logger.debug(f'Input image size: {img.shape}') _, buffer = cv2.imencode('.jpg', img) result = self.process_image(buffer.tobytes()) if self.debug_mode: formatted_result = self.format_ocr_result(result) self.logger.debug(f'OCR result: {formatted_result}')
ignore_texts = [ 'Full text not found or not recognized' ] if result['full_text'] in ignore_texts: return '' full_text = result['full_text'] if self.newline_handling == 'remove': full_text = full_text.replace('\n', ' ')
full_text = self._apply_punctuation_and_spacing(full_text)
if self.no_uppercase: full_text = self._apply_no_uppercase(full_text)
return full_text else: if self.debug_mode: self.logger.warning('Empty image for OCR') return '' except Exception as e: if self.debug_mode: self.logger.error(f"OCR error: {str(e)}") return ''
def _apply_no_uppercase(self, text: str) -> str: def process_sentence(sentence): words = sentence.split() if not words: return '' processed = [words[0].capitalize()] + [word.lower() for word in words[1:]] return ' '.join(processed)
sentences = re.split(r'(?<=[.!?…])\s+', text) processed_sentences = [process_sentence(sentence) for sentence in sentences]
return ' '.join(processed_sentences)
def _apply_punctuation_and_spacing(self, text: str) -> str: text = re.sub(r'\s+([,.!?…])', r'\1', text) text = re.sub(r'([,.!?…])(?!\s)(?![,.!?…])', r'\1 ', text) text = re.sub(r'([,.!?…])\s+([,.!?…])', r'\1\2', text) return text.strip()
def _respect_delay(self): current_time = time.time() time_since_last_request = current_time - self.last_request_time if self.debug_mode: self.logger.info(f'Time since last request: {time_since_last_request} seconds')
if time_since_last_request < self.request_delay: sleep_time = self.request_delay - time_since_last_request if self.debug_mode: self.logger.info(f'Waiting {sleep_time} seconds before next request') time.sleep(sleep_time) self.last_request_time = time.time()
def updateParam(self, param_key: str, param_content): if param_key == 'delay': try: param_content = float(param_content) except (ValueError, TypeError): param_content = 1.0 super().updateParam(param_key, param_content) if param_key == 'proxy': self.proxy_url = param_content 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593# Lens_OCR_exp.py# https://github.com/AuroraWright/owocrimport reimport numpy as npimport timeimport randomfrom typing import List, Dict, Any, Tuple, Optional, Unionfrom math import sqrtimport ioimport osimport json
import requestsfrom PIL import Image, ImageFile
import betterproto
try: from .utils.lens_betterproto import *except ImportError: try: from .utils.lens_betterproto import * except ImportError: raise ImportError( "Could not import lens_betterproto. " "Make sure lens_betterproto.py exists." ) from None
try: from .base import register_OCR, OCRBase, TextBlockexcept ImportError:
class OCRBase: def __init__(self, **params): self.params = params self.debug_mode = int(os.environ.get("OCR_DEBUG", 0)) # Basic logger implementation if run standalone import logging
self.logger = logging.getLogger(__name__) if not self.logger.hasHandlers(): handler = logging.StreamHandler() formatter = logging.Formatter( "[%(levelname)-5s] %(name)s:%(funcName)s:%(lineno)d - %(message)s" ) handler.setFormatter(formatter) self.logger.addHandler(handler) self.logger.setLevel(logging.DEBUG if self.debug_mode else logging.INFO) self.logger.info( "Running Lens_OCR_exp without .base module. Using placeholder classes." )
def get_param_value(self, key): return self.params.get(key)
def updateParam(self, key, value): self.params[key] = value
def register_OCR(name): return lambda cls: cls
class TextBlock: def __init__(self): self.xyxy = (0, 0, 0, 0) self.text = ""
ImageFile.LOAD_TRUNCATED_IMAGES = True
try: import fpng_py
OPTIMIZED_PNG_ENCODE = Trueexcept ImportError: OPTIMIZED_PNG_ENCODE = False
def _pil_image_to_bytes( img: Image.Image, img_format="png", png_compression=6, jpeg_quality=80, optimize=False,) -> bytes: """Converts PIL Image object to bytes of the specified format.""" if img_format == "png" and OPTIMIZED_PNG_ENCODE and not optimize: try: rgba_img = img.convert("RGBA") raw_data = rgba_img.tobytes() image_bytes = fpng_py.fpng_encode_image_to_memory( raw_data, img.width, img.height ) return image_bytes except Exception: pass # Fallback to PIL
image_bytes_io = io.BytesIO() save_kwargs = {} img_to_save = img if img_format == "jpeg": if img.mode == "RGBA" or (img.mode == "P" and "transparency" in img.info): background = Image.new("RGB", img.size, (255, 255, 255)) try: background.paste(img, mask=img.split()[3]) except IndexError: background.paste(img) img_to_save = background elif img.mode != "RGB": img_to_save = img.convert("RGB")
save_kwargs["quality"] = jpeg_quality save_kwargs["subsampling"] = 0 save_kwargs["optimize"] = optimize elif img_format == "png": save_kwargs["compress_level"] = png_compression save_kwargs["optimize"] = optimize
img_to_save.save(image_bytes_io, format=img_format.upper(), **save_kwargs) return image_bytes_io.getvalue()
def _preprocess_image_for_lens(img: Image.Image) -> Tuple[Optional[bytes], int, int]: """Prepares image for Google Lens Protobuf API.""" try: original_width, original_height = img.size max_pixels = 3_000_000 if original_width * original_height > max_pixels: aspect_ratio = original_width / original_height new_w = int(sqrt(max_pixels * aspect_ratio)) new_h = int(new_w / aspect_ratio) img_to_process = ( img.resize((new_w, new_h), Image.Resampling.LANCZOS) if new_w > 0 and new_h > 0 else img ) else: img_to_process = img
img_bytes = _pil_image_to_bytes(img_to_process, img_format="png") return (img_bytes, img_to_process.width, img_to_process.height) except Exception as e: # Use print for safety if logger isn't available reliably print(f"ERROR: Image preprocessing failed: {e}") return (None, 0, 0)
@register_OCR("google_lens_exp")class OCRLensAPI_exp(OCRBase): """ OCR using the experimental Google Lens Protobuf API (using requests). Requires 'betterproto', 'requests', and 'lens_betterproto.py'. """
params = { "delay": 1.5, "newline_handling": { "type": "selector", "options": ["preserve", "remove"], "value": "preserve", "description": "Handle newline characters in the final OCR string.", }, "no_uppercase": { "type": "checkbox", "value": False, "description": "Convert text to lowercase except first letter of sentences.", }, "target_language": { "value": "ja", "description": "Target language code (e.g., 'ja', 'en', 'ru').", }, "proxy": { "value": "", "description": 'Proxy (requests format: e.g., http://user:pass@host:port or {"http": ..., "https": ...})', }, "description": "OCR using Google Lens Protobuf API (requests backend)", }
@property def request_delay(self) -> float: delay_val = self.get_param_value("delay") try: return max(0.0, float(delay_val)) except (ValueError, TypeError, AttributeError): return 1.0
@property def newline_handling(self) -> str: handling = self.get_param_value("newline_handling") return handling if handling in ["preserve", "remove"] else "preserve"
@property def no_uppercase(self) -> bool: no_upper = self.get_param_value("no_uppercase") return bool(no_upper) if no_upper is not None else False
@property def target_language(self) -> str: lang = self.get_param_value("target_language") return lang if isinstance(lang, str) and len(lang) >= 2 else "ja"
@property def proxy(self) -> Optional[Dict[str, str]]: val = self.get_param_value("proxy") proxies_dict = None if isinstance(val, str) and val.strip().startswith("{"): try: parsed_dict = json.loads(val) if isinstance(parsed_dict, dict): proxies_dict = {} # Ensure keys are 'http' and 'https' for requests http_key = next( ( k for k in parsed_dict if k.lower() == "http" or k.lower() == "http://" ), None, ) https_key = next( ( k for k in parsed_dict if k.lower() == "https" or k.lower() == "https://" ), None, ) if http_key: proxies_dict["http"] = parsed_dict[http_key] if https_key: proxies_dict["https"] = parsed_dict[https_key] return proxies_dict if proxies_dict else None except Exception: if val.strip(): proxies_dict = {"http": val.strip(), "https": val.strip()} else: return None elif isinstance(val, str) and val.strip(): proxies_dict = {"http": val.strip(), "https": val.strip()} elif isinstance(val, dict) and val: # Assume dict is already in {'http': ..., 'https': ...} format proxies_dict = val
return proxies_dict if proxies_dict else None
def __init__(self, **params) -> None: super().__init__(**params) self.last_request_time: float = 0 self._api_url = "https://lensfrontend-pa.googleapis.com/v1/crupload" self._api_key = "AIzaSyDr2UxVnv_U85AbhhY8XSHSIavUW0DC-sY" self._api_headers = { "Host": "lensfrontend-pa.googleapis.com", "Connection": "keep-alive", "Content-Type": "application/x-protobuf", "X-Goog-Api-Key": self._api_key, "Sec-Fetch-Site": "none", "Sec-Fetch-Mode": "no-cors", "Sec-Fetch-Dest": "empty", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "en-US,en;q=0.9", }
def _prepare_protobuf_request( self, image_bytes: bytes, width: int, height: int ) -> Optional[bytes]: """Creates and serializes the Protobuf request.""" try: request = LensOverlayServerRequest() req_id = request.objects_request.request_context.request_id client_ctx = request.objects_request.request_context.client_context locale_ctx = client_ctx.locale_context img_data = request.objects_request.image_data
req_id.uuid = random.randint(0, 2**64 - 1) req_id.sequence_id = 1 req_id.image_sequence_id = 1 req_id.analytics_id = random.randbytes(16)
client_ctx.platform = Platform.WEB client_ctx.surface = Surface.CHROMIUM locale_ctx.language = self.target_language locale_ctx.region = "JP" locale_ctx.time_zone = "Asia/Tokyo"
filter_obj = AppliedFilter(filter_type=LensOverlayFilterType.AUTO_FILTER) client_ctx.client_filters.filter.append(filter_obj)
img_data.payload.image_bytes = image_bytes img_data.image_metadata.width = width img_data.image_metadata.height = height
return bytes(request) except Exception as e: self.logger.error( f"Failed to prepare Protobuf request: {e}", exc_info=self.debug_mode ) return None
def _parse_protobuf_response( self, response_proto: LensOverlayServerResponse ) -> str: """Extracts text from Protobuf response, ignoring non-critical error Type=0.""" extracted_text = "" has_error_type_0 = False
try: if response_proto.error: err_type = response_proto.error.error_type if ( err_type != LensOverlayServerErrorErrorType.UNKNOWN_TYPE ): # Check against enum value 0 error_type_name = LensOverlayServerErrorErrorType(err_type).name self.logger.error( f"Lens server returned critical error: Type={err_type} ({error_type_name})" ) return "" else: self.logger.debug( "Lens server returned non-critical error: Type=0 (UNKNOWN_TYPE)." " Attempting to extract text anyway." ) has_error_type_0 = True
text_layout = getattr( getattr(response_proto, "objects_response", None), "text", None ) paragraphs = getattr( getattr(text_layout, "text_layout", None), "paragraphs", None )
if paragraphs: paragraph_texts = [] for paragraph in paragraphs: para_text_builder = io.StringIO() for line in getattr(paragraph, "lines", []): for word in getattr(line, "words", []): para_text_builder.write(getattr(word, "plain_text", "")) separator = getattr(word, "text_separator", None) if separator is not None: para_text_builder.write(separator) paragraph_texts.append(para_text_builder.getvalue()) para_text_builder.close() extracted_text = "".join(paragraph_texts).strip() extracted_text = re.sub(r"\s+", " ", extracted_text).strip()
if self.debug_mode and has_error_type_0: self.logger.debug( "Successfully extracted text despite non-critical error Type=0." )
elif not has_error_type_0: if self.debug_mode: self.logger.debug( "Text layout not found in Protobuf structure (and no error reported)." )
except Exception as e: self.logger.error( f"Failed to parse Protobuf response structure: {e}", exc_info=self.debug_mode, ) return ""
return extracted_text
def _execute_ocr_request( self, image_bytes: bytes, width: int, height: int ) -> Optional[LensOverlayServerResponse]: """Sends prepared request via requests and returns deserialized response.""" payload = self._prepare_protobuf_request(image_bytes, width, height) if not payload: return None
self._respect_delay() response_proto = None session = requests.Session()
current_proxy = self.proxy if current_proxy: session.proxies = current_proxy if self.debug_mode: self.logger.debug( f"Using requests proxy configuration: {current_proxy}" )
# Determine SSL verification skip_ssl_verify = os.environ.get("OCR_SKIP_SSL_VERIFY", "false").lower() in ( "true", "1", "yes", ) ssl_verify = not skip_ssl_verify
try: if self.debug_mode: self.logger.debug( f"Sending Protobuf request ({len(payload)} bytes) via requests " f"to lens api (SSL Verify: {ssl_verify})" )
response = session.post( self._api_url, data=payload, headers=self._api_headers, timeout=(10.0, 30.0), verify=ssl_verify, ) self.last_request_time = time.time()
if self.debug_mode: self.logger.debug( f"Received requests response status: {response.status_code}" )
response.raise_for_status()
response_proto = LensOverlayServerResponse().parse(response.content) if self.debug_mode: self.logger.debug("Protobuf response parsed successfully (requests).")
except requests.exceptions.SSLError as e: self.logger.error( f"SSL Error connecting to Lens API (requests): {e}. " f"If using a proxy or corporate network, check its configuration. " f"You might need to trust a custom CA or set OCR_SKIP_SSL_VERIFY=true (unsafe).", exc_info=self.debug_mode, ) except requests.exceptions.HTTPError as e: response_text = getattr(e.response, "text", "N/A")[:500] self.logger.error( f"HTTP error from Lens API (requests): {e.response.status_code}. " f"Response: {response_text}", exc_info=self.debug_mode, ) except requests.exceptions.RequestException as e: self.logger.error( f"Request error connecting to Lens API (requests): {e}", exc_info=self.debug_mode, ) except (betterproto.Error, ValueError, TypeError) as e: self.logger.error( f"Failed to parse Protobuf response (requests): {e}", exc_info=self.debug_mode, ) if "response" in locals() and hasattr(response, "content"): self.logger.debug( f"Raw response content (first 500 bytes): {response.content[:500]}" ) except Exception as e: self.logger.error( f"Unexpected error during OCR request (requests): {e}", exc_info=self.debug_mode, ) finally: session.close()
return response_proto
def ocr(self, img: np.ndarray) -> str: """Main OCR method for a single image (numpy array).""" if self.debug_mode > 1: self.logger.debug( f"Starting OCR (Lens Protobuf / requests) on image shape: {img.shape}" ) if img is None or img.size == 0: if self.debug_mode: self.logger.warning("Empty image provided") return ""
full_text = "" try: pil_img = Image.fromarray(img) processed_bytes, width, height = _preprocess_image_for_lens(pil_img)
if not processed_bytes: self.logger.error("Image preprocessing failed.") return "" if self.debug_mode > 1: self.logger.debug( f"Preprocessed image: {width}x{height}, {len(processed_bytes)} bytes" )
response_proto = self._execute_ocr_request(processed_bytes, width, height)
if response_proto: full_text = self._parse_protobuf_response(response_proto) if self.debug_mode and full_text: self.logger.debug(f"Parsed text preview: '{full_text[:100]}...'")
if self.newline_handling == "remove": full_text = re.sub(r"\s+", " ", full_text).strip() full_text = self._apply_punctuation_and_spacing(full_text) if self.no_uppercase: full_text = self._apply_no_uppercase(full_text) else: self.logger.warning( "OCR request did not return a valid response object." )
except Exception as e: self.logger.error( f"Unexpected error in OCR process: {e}", exc_info=self.debug_mode ) return ""
return str(full_text) if full_text is not None else ""
def ocr_img(self, img: np.ndarray) -> str: if self.debug_mode > 1: self.logger.debug(f"ocr_img shape: {img.shape}") return self.ocr(img)
def _ocr_blk_list( self, img: np.ndarray, blk_list: List[TextBlock], *args, **kwargs ): """Processes a list of text blocks on the image.""" im_h, im_w = img.shape[:2] if self.debug_mode: self.logger.debug( f"Image size: {im_h}x{im_w}. Processing {len(blk_list)} blocks." ) for i, blk in enumerate(blk_list): x1, y1, x2, y2 = blk.xyxy if self.debug_mode > 1: self.logger.debug( f"Processing block {i+1}/{len(blk_list)}: ({x1, y1, x2, y2})" )
y1c, y2c = max(0, y1), min(im_h, y2) x1c, x2c = max(0, x1), min(im_w, x2)
if y1c < y2c and x1c < x2c: try: cropped_img = img[y1c:y2c, x1c:x2c] if cropped_img.size > 0: blk.text = self.ocr(cropped_img) else: if self.debug_mode: self.logger.warning(f"Empty cropped image for block {i+1}.") blk.text = "" except Exception as crop_err: self.logger.error( f"Error cropping/processing block {i+1}: {crop_err}", exc_info=self.debug_mode, ) blk.text = "" else: if self.debug_mode: self.logger.warning( f"Invalid/zero-area bbox {blk.xyxy} (clamped: {x1c,y1c,x2c,y2c})" ) blk.text = ""
def _apply_no_uppercase(self, text: str) -> str: """Applies lowercase except for first letter of sentences."""
def process_sentence(sentence): sentence = sentence.strip() return sentence[0].upper() + sentence[1:].lower() if sentence else ""
if self.target_language.lower().startswith("ja"): return text # No case change for Japanese
sentences = re.split(r"(?<=[.!?…])\s+", text) return " ".join(process_sentence(s) for s in sentences if s)
def _apply_punctuation_and_spacing(self, text: str) -> str: """Corrects spacing around punctuation.""" text = re.sub(r"\s+([,.!?…:;])", r"\1", text) text = re.sub(r"([,.!?…:;])(?=[^\s,.!?…:;])", r"\1 ", text) text = re.sub(r"\s+", " ", text) return text.strip()
def _respect_delay(self): """Ensures minimum delay between requests.""" current_time = time.time() time_since_last = current_time - self.last_request_time required_delay = self.request_delay if time_since_last < required_delay: sleep_time = required_delay - time_since_last if self.debug_mode: self.logger.info(f"Delay: Sleeping for {sleep_time:.3f}s") time.sleep(sleep_time)
def updateParam(self, param_key: str, param_content: Any): """Updates a parameter.""" # No client re-initialization needed for requests on proxy change if param_key == "delay": try: param_content = max(0.0, float(param_content)) except (ValueError, TypeError): param_content = 1.0 super().updateParam(param_key, param_content)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488import reimport timeimport base64import jsonimport cv2import numpy as npfrom typing import List, Optional
import openaiimport httpx
from .base import register_OCR, OCRBase, TextBlock
@register_OCR("llm_ocr")class LLM_OCR(OCRBase): lang_map = { "Auto Detect": None, "Afrikaans": "af", "Albanian": "sq", "Amharic": "am", "Arabic": "ar", "Armenian": "hy", "Assamese": "as", "Azerbaijani": "az", "Bangla": "bn", "Basque": "eu", "Belarusian": "be", "Bengali": "bn", "Bosnian": "bs", "Breton": "br", "Bulgarian": "bg", "Burmese": "my", "Catalan": "ca", "Cebuano": "ceb", "Cherokee": "chr", "Chinese (Simplified)": "zh-CN", "Chinese (Traditional)": "zh-TW", "Corsican": "co", "Croatian": "hr", "Czech": "cs", "Danish": "da", "Dutch": "nl", "English": "en", "Esperanto": "eo", "Estonian": "et", "Faroese": "fo", "Filipino": "fil", "Finnish": "fi", "French": "fr", "Frisian": "fy", "Galician": "gl", "Georgian": "ka", "German": "de", "Greek": "el", "Gujarati": "gu", "Haitian Creole": "ht", "Hausa": "ha", "Hawaiian": "haw", "Hebrew": "he", "Hindi": "hi", "Hmong": "hmn", "Hungarian": "hu", "Icelandic": "is", "Igbo": "ig", "Indonesian": "id", "Interlingua": "ia", "Irish": "ga", "Italian": "it", "Japanese": "ja", "Javanese": "jv", "Kannada": "kn", "Kazakh": "kk", "Khmer": "km", "Korean": "ko", "Kurdish": "ku", "Kyrgyz": "ky", "Lao": "lo", "Latin": "la", "Latvian": "lv", "Lithuanian": "lt", "Luxembourgish": "lb", "Macedonian": "mk", "Malagasy": "mg", "Malay": "ms", "Malayalam": "ml", "Maltese": "mt", "Maori": "mi", "Marathi": "mr", "Mongolian": "mn", "Nepali": "ne", "Norwegian": "no", "Occitan": "oc", "Oriya": "or", "Pashto": "ps", "Persian": "fa", "Polish": "pl", "Portuguese": "pt", "Punjabi": "pa", "Quechua": "qu", "Romanian": "ro", "Russian": "ru", "Samoan": "sm", "Scots Gaelic": "gd", "Serbian (Cyrillic)": "sr-Cyrl", "Serbian (Latin)": "sr-Latn", "Shona": "sn", "Sindhi": "sd", "Sinhala": "si", "Slovak": "sk", "Slovenian": "sl", "Somali": "so", "Spanish": "es", "Sundanese": "su", "Swahili": "sw", "Swedish": "sv", "Tagalog": "tl", "Tajik": "tg", "Tamil": "ta", "Tatar": "tt", "Telugu": "te", "Thai": "th", "Tibetan": "bo", "Tigrinya": "ti", "Tongan": "to", "Turkish": "tr", "Ukrainian": "uk", "Urdu": "ur", "Uyghur": "ug", "Uzbek": "uz", "Vietnamese": "vi", "Welsh": "cy", "Xhosa": "xh", "Yiddish": "yi", "Yoruba": "yo", "Zulu": "zu", }
popular_models = [ "OAI: gpt-4o-mini", "OAI: gpt-4-vision-preview", "OAI: gpt-4o", "OAI: gpt-4", "GGL: gemini-1.5-pro-latest", "GGL: gemini-1.5-flash-latest", ]
params = { "provider": { "type": "selector", "options": ["OpenAI", "Google", "OpenRouter"], "value": "OpenAI", "description": "Select the LLM provider.", }, "api_key": { "value": "", "description": "API key to use if multiple keys are not provided.", }, "multiple_keys": { "type": "editor", "value": "", "description": "API keys separated by semicolons (;). Requests will rotate.", }, "endpoint": { "value": "", "description": "Base URL for the API. Leave empty for provider default.", }, "model": { "type": "selector", "options": popular_models, "value": "OAI: gpt-4o-mini", "description": "Select the model to use.", }, "override_model": { "value": "", "description": "Specify a custom model name to override the selected one.", }, "language": { "type": "selector", "options": list(lang_map.keys()), "value": "Japanese", "description": "Language for OCR.", }, "detail_level": { "type": "selector", "options": ["auto", "low", "high"], "value": "auto", "description": "Controls image detail level for vision models.", }, "prompt": { "type": "editor", "value": "Perform OCR on the provided manga image snippet. The language is **{language}**.\nRecognize all text, including handwritten sound effects (SFX).\n**CRITICAL INSTRUCTION:** If you see jumbled characters, it is likely vertical text that was read horizontally. First, mentally reconstruct the correct vertical text.\n**OUTPUT FORMATTING:** All recognized text from the image must be consolidated into a **single, continuous horizontal line**. Do not use newlines.\nYour final output must be ONLY the recognized text. No explanations.", "description": "The main prompt for the OCR task. Use {language} placeholder.", }, "system_prompt": { "type": "editor", "value": "You are a specialized OCR engine for manga and comics. Your primary function is to accurately extract and consolidate all recognized text from an image into a **single, continuous horizontal line**. You must return only the raw, recognized text. You do not interpret, translate, or explain the content. You are designed to intelligently handle common OCR errors, such as reconstructing jumbled characters that result from misreading vertical text.", "description": "Optional system prompt to guide the model's behavior.", }, "proxy": { "value": "", "description": "Proxy address (e.g., http(s)://user:password@host:port)", }, "delay": {"value": 1.0, "description": "Delay in seconds between requests."}, "requests_per_minute": { "value": 15, "description": "Maximum number of requests per minute per key.", }, "max_response_tokens": { "value": 4096, "description": "Maximum number of tokens in the LLM's response.", }, "description": "OCR using various vision-capable LLMs.", }
def __init__(self, **params) -> None: super().__init__(**params) self.last_request_time = 0 self.client = None self.request_count_minute = 0 self.minute_start_time = time.time() self.key_usage = {} self.current_key_index = 0
def _initialize_client(self, api_key_to_use: str): endpoint = self.endpoint provider = self.provider if not endpoint: if provider == "OpenAI": endpoint = "https://api.openai.com/v1" elif provider == "Google": endpoint = "https://generativelanguage.googleapis.com/v1beta/openai" elif provider == "OpenRouter": endpoint = "https://openrouter.ai/api/v1"
http_client = None if self.proxy: try: proxy_mounts = {"all://": httpx.HTTPTransport(proxy=self.proxy)} http_client = httpx.Client(mounts=proxy_mounts) except Exception as e: self.logger.error(f"Failed to initialize proxy '{self.proxy}': {e}.")
masked_key = ( api_key_to_use[:4] + "..." + api_key_to_use[-4:] if len(api_key_to_use) > 8 else api_key_to_use ) self.logger.debug( f"Initializing client for {provider} with key {masked_key} at endpoint {endpoint}" )
self.client = openai.OpenAI( api_key=api_key_to_use, base_url=endpoint, http_client=http_client )
# --- Property Getters (similar to translator) --- @property def provider(self) -> str: return self.get_param_value("provider")
@property def api_key(self) -> str: return self.get_param_value("api_key")
@property def multiple_keys_list(self) -> List[str]: keys_str = self.get_param_value("multiple_keys") if not isinstance(keys_str, str): return [] return [ key.strip() for key in keys_str.strip().replace("\n", ";").split(";") if key.strip() ]
@property def endpoint(self) -> Optional[str]: return self.get_param_value("endpoint") or None
@property def model(self) -> str: return self.get_param_value("model")
@property def override_model(self) -> Optional[str]: return self.get_param_value("override_model") or None
@property def language(self) -> str: return self.get_param_value("language")
@property def detail_level(self) -> str: return self.get_param_value("detail_level")
@property def prompt(self) -> str: return self.get_param_value("prompt")
@property def system_prompt(self) -> str: return self.get_param_value("system_prompt")
@property def proxy(self) -> str: return self.get_param_value("proxy")
@property def requests_per_minute(self) -> int: return int(self.get_param_value("requests_per_minute"))
@property def max_response_tokens(self) -> int: return int(self.get_param_value("max_response_tokens"))
@property def request_delay(self) -> float: try: return float(self.get_param_value("delay")) except (ValueError, TypeError): return 1.0
def _respect_delay(self): # This logic is identical to the one in LLM_API_Translator current_time = time.time() rpm = self.requests_per_minute if rpm > 0: if current_time - self.minute_start_time >= 60: self.request_count_minute = 0 self.minute_start_time = current_time if self.request_count_minute >= rpm: wait_time = 60.1 - (current_time - self.minute_start_time) if wait_time > 0: self.logger.warning( f"Global RPM limit ({rpm}) reached. Waiting {wait_time:.2f}s." ) time.sleep(wait_time) self.request_count_minute = 0 self.minute_start_time = time.time()
time_since_last_request = current_time - self.last_request_time if time_since_last_request < self.request_delay: sleep_time = self.request_delay - time_since_last_request if self.debug_mode: self.logger.debug(f"Global delay: Waiting {sleep_time:.3f}s.") time.sleep(sleep_time)
self.last_request_time = time.time() self.request_count_minute += 1
def _respect_key_limit(self, key: str) -> bool: # This logic is identical to the one in LLM_API_Translator rpm = self.requests_per_minute if rpm <= 0: return True now = time.time() count, start_time = self.key_usage.get(key, (0, now)) if now - start_time >= 60: count, start_time = 0, now if count >= rpm: wait_time = 60.1 - (now - start_time) if wait_time > 0: self.logger.warning( f"RPM limit ({rpm}) for key {key[:6]}... reached. Waiting {wait_time:.2f}s." ) time.sleep(wait_time) self.key_usage[key] = (0, time.time()) return False return True
def _select_api_key(self) -> Optional[str]: # This logic is identical to the one in LLM_API_Translator api_keys = self.multiple_keys_list single_key = self.api_key if not api_keys and not single_key: self.logger.error("No API keys provided.") return None
if not api_keys: if self._respect_key_limit(single_key): now = time.time() count, start_time = self.key_usage.get(single_key, (0, now)) self.key_usage[single_key] = (count + 1, start_time) return single_key return None
start_index = self.current_key_index for i in range(len(api_keys)): index = (start_index + i) % len(api_keys) key = api_keys[index] if self._respect_key_limit(key): now = time.time() count, start_time = self.key_usage.get(key, (0, now)) self.key_usage[key] = (count + 1, start_time) self.current_key_index = (index + 1) % len(api_keys) return key self.logger.error("All API keys are rate-limited.") return None
def ocr(self, img_base64: str, prompt_override: str = None) -> str: api_key_to_use = self._select_api_key() if not api_key_to_use: return "[ERROR: No available API key]"
# Re-initialize client if key is different from the last one used if not self.client or self.client.api_key != api_key_to_use: self._initialize_client(api_key_to_use)
self._respect_delay() try: lang_name = self.language prompt_text = (prompt_override or self.prompt).format(language=lang_name)
image_content_part = { "type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{img_base64}"}, }
if self.provider in ["OpenAI", "Google", "OpenRouter"]: detail_setting = self.detail_level if detail_setting in ["low", "high"]: image_content_part["image_url"]["detail"] = detail_setting
messages = [ { "role": "user", "content": [ {"type": "text", "text": prompt_text}, image_content_part, ], } ] if self.system_prompt: messages.insert(0, {"role": "system", "content": self.system_prompt})
model_name = self.override_model or self.model if ": " in model_name: model_name = model_name.split(": ", 1)[1]
self.logger.debug(f"OCR request with model: {model_name}")
response = self.client.chat.completions.create( model=model_name, messages=messages, max_tokens=self.max_response_tokens, )
if response.choices and response.choices[0].message.content: full_text = ( response.choices[0].message.content.replace("\n", " ").strip() ) self.logger.debug(f"OCR result: {full_text}") return full_text else: self.logger.warning("No text found in OCR response.") return "" except Exception as e: self.logger.error(f"OCR error: {e}") return f"[ERROR: {type(e).__name__}]"
def _ocr_blk_list( self, img: np.ndarray, blk_list: List[TextBlock], *args, **kwargs ): im_h, im_w = img.shape[:2] for blk in blk_list: x1, y1, x2, y2 = blk.xyxy if 0 <= x1 < x2 <= im_w and 0 <= y1 < y2 <= im_h: cropped_img = img[y1:y2, x1:x2] _, buffer = cv2.imencode(".jpg", cropped_img) img_base64 = base64.b64encode(buffer).decode("utf-8") blk.text = self.ocr(img_base64, prompt_override=kwargs.get("prompt")) else: blk.text = ""
def ocr_img(self, img: np.ndarray, prompt: str = "") -> str: _, buffer = cv2.imencode(".jpg", img) img_base64 = base64.b64encode(buffer).decode("utf-8") return self.ocr(img_base64, prompt_override=prompt)
def updateParam(self, param_key: str, param_content): super().updateParam(param_key, param_content) if param_key in ["api_key", "multiple_keys", "endpoint", "proxy", "provider"]: self.client = None # Force re-initialization on next call if param_key in ["requests_per_minute", "delay"]: self.request_count_minute = 0 self.minute_start_time = time.time() self.last_request_time = 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
import platform if platform.system() == 'Darwin' and platform.mac_ver()[0] >= '10.15': from typing import Tuple, List import numpy as np from PIL import Image from io import BytesIO import Vision import objc
from .base import register_OCR, OCRBase, TextBlock, LOGGER
def get_revision_level(): with objc.autorelease_pool(): ver = platform.mac_ver()[0] if ver >= '13': revision = Vision.VNRecognizeTextRequestRevision3 # python might return 10.16 instead of 11.0 for Big Sur and above elif ver >= '10.16': # ver[0] >= '11' revision = Vision.VNRecognizeTextRequestRevision2 elif ver >= '10.15': revision = Vision.VNRecognizeTextRequestRevision1 return revision
def get_supported_languages(recognition_level='accurate', revision=get_revision_level()) -> Tuple[Tuple[str], Tuple[str]]: """Get supported languages for text detection from Vision framework.
Returns: Tuple of ((language code), (error)) """
if recognition_level == 'fast': recognition_level = 1 else: recognition_level = 0 return Vision.VNRecognizeTextRequest.supportedRecognitionLanguagesForTextRecognitionLevel_revision_error_( recognition_level, revision, None )
def text_from_image(image: np.ndarray, language_preference=None, recognition_level='accurate'): recognition_level = recognition_level.lower() if language_preference == 'Auto': language_preference = None
img_buf = BytesIO() Image.fromarray(image).save(img_buf, format='PNG')
with objc.autorelease_pool(): req = Vision.VNRecognizeTextRequest.alloc().init()
if recognition_level == 'fast': req.setRecognitionLevel_(1) else: req.setRecognitionLevel_(0)
if language_preference is not None: req.setRecognitionLanguages_(language_preference)
handler = Vision.VNImageRequestHandler.alloc().initWithData_options_( img_buf.getvalue(), None )
success = handler.performRequests_error_([req], None) res = [] if success: for result in req.results(): # bbox = result.boundingBox() # w, h = bbox.size.width, bbox.size.height # x, y = bbox.origin.x, bbox.origin.y
res.append((result.text(), result.confidence())) #, [x, y, w, h]))
req.dealloc() handler.dealloc()
return res
class AppleOCR: def __init__(self, lang=[], recog_level='accurate', min_confidence='0.1'): self.lang = lang self.recog_level = recog_level self.min_confidence = min_confidence
def __call__(self, img: np.ndarray) -> str: result = [] results = text_from_image(img, self.lang, self.recog_level) for res in results: if res[1] >= float(self.min_confidence): result.append(res[0]) return '\n'.join(result)
macos_ocr_supported_languages = get_supported_languages()
if len(macos_ocr_supported_languages) > 0: @register_OCR('macos_ocr') class OCRApple(OCRBase): params = { 'language': { 'type':'selector', 'options': list(get_supported_languages()[0]), 'value': 'en-US', }, # While this does appear # it doesn't update the languages available # different recog level, different available langs # 'recognition_level': { # 'type': 'selector', # 'options': [ # 'accurate', # 'fast', # ], # 'value': 'accurate', # }, 'confidence_level': '0.1', } language = 'en-US' recognition = 'accurate' confidence = '0.1'
def __init__(self, **params) -> None: super().__init__(**params) self.model = AppleOCR(lang=[self.language])
def ocr_img(self, img: np.ndarray) -> str: return self.model(img)
def _ocr_blk_list(self, img: np.ndarray, blk_list: List[TextBlock], *args, **kwargs): im_h, im_w = img.shape[:2] for blk in blk_list: x1, y1, x2, y2 = blk.xyxy if y2 < im_h and x2 < im_w and \ x1 > 0 and y1 > 0 and x1 < x2 and y1 < y2: blk.text = self.model(img[y1:y2, x1:x2]) else: self.logger.warning('invalid textbbox to target img') blk.text = ['']
def updateParam(self, param_key: str, param_content): super().updateParam(param_key, param_content) self.language = self.params['language']['value'] self.model.lang = [self.language]
# self.recognition = self.params['recognition_level']['value'] # self.model.recog_level = self.recognition # self.params['language']['options'] = list(get_supported_languages(self.recognition)[0])
self.confidence = self.params['confidence_level'] self.model.min_confidence = self.confidence else: LOGGER.warning(f'No supported language packs found for MacOS, MacOS OCR will be unavailable.')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115# modified from https://github.com/kha-white/manga-ocr/blob/master/manga_ocr/ocr.pyimport reimport jaconvfrom transformers import AutoFeatureExtractor, AutoTokenizer, VisionEncoderDecoderModelimport numpy as npimport torchfrom typing import List
from .base import OCRBase, register_OCR, DEFAULT_DEVICE, DEVICE_SELECTOR, TextBlock
MANGA_OCR_PATH = r'data/models/manga-ocr-base'class MangaOcr: def __init__(self, pretrained_model_name_or_path=MANGA_OCR_PATH, device='cpu'): self.feature_extractor = AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path) self.tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path) self.model = VisionEncoderDecoderModel.from_pretrained(pretrained_model_name_or_path) self.to(device) def to(self, device): self.model.to(device)
@torch.no_grad() def __call__(self, img: np.ndarray): x = self.feature_extractor(img, return_tensors="pt").pixel_values.squeeze() x = self.model.generate(x[None].to(self.model.device))[0].cpu() x = self.tokenizer.decode(x, skip_special_tokens=True) x = post_process(x) return x
# todo def ocr_batch(self, im_batch: torch.Tensor): raise NotImplementedError
def post_process(text): text = ''.join(text.split()) text = text.replace('…', '...') text = re.sub('[・.]{2,}', lambda x: (x.end() - x.start()) * '.', text) text = jaconv.h2z(text, ascii=True, digit=True)
return text
@register_OCR('manga_ocr')class MangaOCR(OCRBase): params = { 'device': DEVICE_SELECTOR() } device = DEFAULT_DEVICE
download_file_list = [{ 'url': 'https://huggingface.co/kha-white/manga-ocr-base/resolve/main/', 'files': ['pytorch_model.bin', 'config.json', 'preprocessor_config.json', 'README.md', 'special_tokens_map.json', 'tokenizer_config.json', 'vocab.txt'], 'sha256_pre_calculated': ['c63e0bb5b3ff798c5991de18a8e0956c7ee6d1563aca6729029815eda6f5c2eb', None, None, None, None, None, None], 'save_dir': 'data/models/manga-ocr-base', 'concatenate_url_filename': 1, }] _load_model_keys = {'model'}
def __init__(self, **params) -> None: super().__init__(**params) self.device = self.params['device']['value'] self.model: MangaOCR = None
def _load_model(self): if self.model is None: self.model = MangaOcr(device=self.device)
def ocr_img(self, img: np.ndarray) -> str: return self.model(img)
def _ocr_blk_list(self, img: np.ndarray, blk_list: List[TextBlock], *args, **kwargs): im_h, im_w = img.shape[:2] for blk in blk_list: x1, y1, x2, y2 = blk.xyxy if y2 < im_h and x2 < im_w and \ x1 > 0 and y1 > 0 and x1 < x2 and y1 < y2: # Extract region and convert RGBA to RGB if necessary for model input region = img[y1:y2, x1:x2] blk.text = self.model(region) else: self.logger.warning('invalid textbbox to target img') blk.text = ['']
def updateParam(self, param_key: str, param_content): super().updateParam(param_key, param_content) device = self.params['device']['value'] if self.device != device and self.model is not None: self.model.to(device)
if __name__ == '__main__': import cv2
img_path = r'data/testpacks/textline/ballontranslator.png' manga_ocr = MangaOcr(pretrained_model_name_or_path=MANGA_OCR_PATH, device='cuda')
img = cv2.imread(img_path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
dummy = np.zeros((1024, 1024, 3), np.uint8) manga_ocr(dummy) # preprocessed = manga_ocr(img_path)
# im_batch = # img = (torch.from_numpy(img[np.newaxis, ...]).float() - 127.5) / 127.5 # img = einops.rearrange(img, 'N H W C -> N C H W') import time for ii in range(10): t0 = time.time() out = manga_ocr(dummy) print(out, time.time() - t0)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495from typing import Listimport numpy as npfrom copy import deepcopy
from .base import DEVICE_SELECTOR, OCRBase, register_OCR, TextBlockfrom utils.textblock import collect_textblock_regions
mit_params = { 'chunk_size': { 'type': 'selector', 'options': [8, 16, 24, 32], 'value': 16 }, 'device': DEVICE_SELECTOR(not_supported=['privateuseone']), 'description': 'OCRMIT32px'}
class MITModels(OCRBase):
_line_only = True _load_model_keys = {'model'}
def __init__(self, **params) -> None: super().__init__(**params) self.model = None
@property def chunk_size(self) -> int: return self.params['chunk_size']['value']
@property def device(self) -> str: return self.params['device']['value']
def _ocr_blk_list(self, img: np.ndarray, blk_list: List[TextBlock], split_textblk=False, seg_func=None, *args, **kwargs): regions, textblk_lst_indices = collect_textblock_regions(img, blk_list, self.model.text_height, self.model.maxwidth, split_textblk, seg_func) return self.model(blk_list, regions, textblk_lst_indices, chunk_size=self.chunk_size)
def updateParam(self, param_key: str, param_content): if param_key == 'device' and self.device != param_content and self.model is not None: self.model.to(param_content) super().updateParam(param_key, param_content)
from .mit32px import OCR32pxModel@register_OCR('mit32px')class OCRMIT32px(MITModels):
params = deepcopy(mit_params) download_file_list = [{ 'url': 'https://github.com/zyddnys/manga-image-translator/releases/download/beta-0.3/ocr.zip', 'files': ['ocr.ckpt'], 'sha256_pre_calculated': ['d9f619a9dccce8ce88357d1b17d25f07806f225c033ea42c64e86c45446cfe71'], 'save_files': ['data/models/mit32px_ocr.ckpt'], 'archived_files': 'ocr.zip', 'archive_sha256_pre_calculated': '47405638b96fa2540a5ee841a4cd792f25062c09d9458a973362d40785f95d7a', }]
def _load_model(self): self.model = OCR32pxModel(r'data/models/mit32px_ocr.ckpt', self.device)
from .mit48px_ctc import OCR48pxCTC@register_OCR('mit48px_ctc')class OCRMIT48pxCTC(MITModels):
params = deepcopy(mit_params) download_file_list = [{ 'url': 'https://github.com/zyddnys/manga-image-translator/releases/download/beta-0.3/ocr-ctc.zip', 'files': ['ocr-ctc.ckpt', 'alphabet-all-v5.txt'], 'sha256_pre_calculated': ['8b0837a24da5fde96c23ca47bb7abd590cd5b185c307e348c6e0b7238178ed89', None], 'save_files': ['data/models/mit48pxctc_ocr.ckpt', 'data/alphabet-all-v5.txt'], 'archived_files': 'ocr-ctc.zip', 'archive_sha256_pre_calculated': 'fc61c52f7a811bc72c54f6be85df814c6b60f63585175db27cb94a08e0c30101', }]
def _load_model(self): self.model = OCR48pxCTC(r'data/models/mit48pxctc_ocr.ckpt', self.device)
from .mit48px import Model48pxOCROCR48PXMODEL_PATH = r'data/models/ocr_ar_48px.ckpt'@register_OCR('mit48px')class OCRMIT48px(MITModels):
params = deepcopy(mit_params) download_file_list = [{ 'url': 'https://github.com/zyddnys/manga-image-translator/releases/download/beta-0.3/', 'files': [OCR48PXMODEL_PATH, 'data/alphabet-all-v7.txt'], 'sha256_pre_calculated': ['29daa46d080818bb4ab239a518a88338cbccff8f901bef8c9db191a7cb97671d', None], 'concatenate_url_filename': 2, }]
def _load_model(self): self.model = Model48pxOCR(OCR48PXMODEL_PATH, self.device)12345678910111213141516171819import numpy as np
from .base import OCRBase, register_OCR, List, TextBlock
@register_OCR('none_ocr')class OCRNone(OCRBase): def __init__(self, **params) -> None: super().__init__(**params)
params = { 'NOTICE': 'Not a OCR, just return original text.', 'description': 'Not a OCR, just return original text.' }
def _ocr_blk_list(self, img: np.ndarray, blk_list: List[TextBlock], *args, **kwargs): pass
def ocr_img(self, img: np.ndarray) -> str: return ''123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425import reimport numpy as npimport timeimport cv2import osfrom typing import Listimport ctypesfrom ctypes import ( Structure, byref, POINTER, c_int64, c_int32, c_float, c_ubyte, c_char, c_char_p)from PIL import Image as PilImagefrom contextlib import contextmanagerimport logging
from .base import register_OCR, OCRBase, TextBlock
ONE_OCR_PATH = os.path.join("data", "models", "one-ocr")MODEL_NAME = "oneocr.onemodel"DLL_NAME = "oneocr.dll"MODEL_KEY = b'kj)TGtrK>f]b[Piow.gU+nC@s""""""4'MIN_DIM_SIZE = 56 # Minimum height *and* width for padding
c_int64_p = POINTER(c_int64)c_float_p = POINTER(c_float)c_ubyte_p = POINTER(c_ubyte)
class ImageStructure(Structure): _fields_ = [("type", c_int32), ("width", c_int32), ("height", c_int32), ("_reserved", c_int32), ("step_size", c_int64), ("data_ptr", c_ubyte_p)]
class BoundingBox(Structure): _fields_ = [("x1", c_float), ("y1", c_float), ("x2", c_float), ("y2", c_float)]
BoundingBox_p = POINTER(BoundingBox)
DLL_FUNCTIONS = [ # Function definitions for the DLL ("CreateOcrInitOptions", [c_int64_p], c_int64), ("OcrInitOptionsSetUseModelDelayLoad", [ c_int64, c_char], c_int64), ("CreateOcrPipeline", [c_char_p, c_char_p, c_int64, c_int64_p], c_int64), ("CreateOcrProcessOptions", [c_int64_p], c_int64), ("OcrProcessOptionsSetMaxRecognitionLineCount", [c_int64, c_int64], c_int64), ( "RunOcrPipeline", [c_int64, POINTER(ImageStructure), c_int64, c_int64_p], c_int64), ("GetImageAngle", [c_int64, c_float_p], c_int64), ("GetOcrLineCount", [ c_int64, c_int64_p], c_int64), ("GetOcrLine", [c_int64, c_int64, c_int64_p], c_int64), ("GetOcrLineContent", [ c_int64, POINTER(c_char_p)], c_int64), ("GetOcrLineBoundingBox", [c_int64, POINTER( BoundingBox_p)], c_int64), ("GetOcrLineWordCount", [c_int64, c_int64_p], c_int64), ("GetOcrWord", [c_int64, c_int64, c_int64_p], c_int64), ("GetOcrWordContent", [ c_int64, POINTER(c_char_p)], c_int64), ("GetOcrWordBoundingBox", [c_int64, POINTER( BoundingBox_p)], c_int64), ("GetOcrWordConfidence", [c_int64, c_float_p], c_int64), ("ReleaseOcrResult", [c_int64], None), ("ReleaseOcrInitOptions", [c_int64], None), ("ReleaseOcrPipeline", [c_int64], None), ("ReleaseOcrProcessOptions", [c_int64], None),]
@contextmanagerdef suppress_output(): # Context manager to suppress stdout/stderr, useful for noisy DLL init devnull = os.open(os.devnull, os.O_WRONLY) original_stdout, original_stderr = os.dup(1), os.dup(2) os.dup2(devnull, 1) os.dup2(devnull, 2) try: yield finally: os.dup2(original_stdout, 1) os.dup2(original_stderr, 2) os.close(original_stdout) os.close(original_stderr) os.close(devnull)
class OcrEngine: def __init__(self, config_dir, logger=None): self.ocr_dll = self.init_options = self.pipeline = self.process_options = None self.config_dir = config_dir self.model_path = os.path.join(self.config_dir, MODEL_NAME) self.dll_path = os.path.join(self.config_dir, DLL_NAME) self.logger = logger or logging.getLogger(self.__class__.__name__) self.empty_result = {"text": "", "text_angle": None, "lines": []} try: self._load_and_bind_dll() self.init_options = self._create_init_options() self.pipeline = self._create_pipeline() self.process_options = self._create_process_options() if self.logger: self.logger.debug("OcrEngine initialized") except Exception as e: raise e # Error logged internally
def _load_and_bind_dll(self): try: if os.name == 'nt': k32 = ctypes.WinDLL("kernel32", use_last_error=True) if hasattr(k32, "SetDllDirectoryW"): k32.SetDllDirectoryW(str(self.config_dir)) self.ocr_dll = ctypes.WinDLL( str(self.dll_path), use_last_error=True) for name, argtypes, restype in DLL_FUNCTIONS: try: func = getattr(self.ocr_dll, name) func.argtypes = argtypes func.restype = restype except AttributeError as e: raise RuntimeError(f"Missing DLL func: {name}") from e except (OSError, RuntimeError, AttributeError) as e: code = ctypes.get_last_error() if os.name == "nt" else 0 msg = f"Failed load/bind DLL ({self.dll_path}) from {self.config_dir}. Code: {code}. Error: {e}" if self.logger: self.logger.error(msg) raise RuntimeError(msg) from e
def _check_dll_result(self, result_code, error_message): if result_code != 0: raise RuntimeError(f"{error_message} (Native Code: {result_code})")
def _create_init_options(self): h = c_int64() self._check_dll_result(self.ocr_dll.CreateOcrInitOptions( byref(h)), "Init options create failed") self._check_dll_result(self.ocr_dll.OcrInitOptionsSetUseModelDelayLoad( h, 0), "Model load config failed") return h
def _create_pipeline(self): mb = ctypes.create_string_buffer(self.model_path.encode("utf-8")) kb = ctypes.create_string_buffer(MODEL_KEY) h = c_int64() with suppress_output(): self._check_dll_result(self.ocr_dll.CreateOcrPipeline( mb, kb, self.init_options, byref(h)), f"Pipeline create failed ({self.model_path})") return h
def _create_process_options(self): h = c_int64() self._check_dll_result(self.ocr_dll.CreateOcrProcessOptions( byref(h)), "Process options create failed") self._check_dll_result(self.ocr_dll.OcrProcessOptionsSetMaxRecognitionLineCount( h, 1000), "Line count config failed") return h
def recognize_pil(self, image: PilImage.Image): if image.mode != 'RGBA': image = image.convert('RGBA') return self._process_image(cols=image.width, rows=image.height, step=image.width*4, data=image.tobytes())
def _process_image(self, cols, rows, step, data): dp = ctypes.cast(data, c_ubyte_p) if not isinstance( data, bytes) else (c_ubyte*len(data)).from_buffer_copy(data) img_struct = ImageStructure(3, cols, rows, 0, step, dp) return self._perform_ocr(img_struct)
def _perform_ocr(self, image_struct: ImageStructure): res_h = c_int64() code = self.ocr_dll.RunOcrPipeline(self.pipeline, byref( image_struct), self.process_options, byref(res_h)) if code != 0: # Let the caller (OCROneAPI) handle specific error code interpretation # This will raise RuntimeError self._check_dll_result(code, "RunOcrPipeline failed") # Alternative: log here and return empty, but raising is cleaner for caller # if self.logger: self.logger.warning(f"RunOcrPipeline failed: {code}") # return self.empty_result parsed = self._parse_ocr_results(res_h.value) self.ocr_dll.ReleaseOcrResult(res_h) return parsed
def _parse_ocr_results(self, res_h: int): lc = c_int64() if self.ocr_dll.GetOcrLineCount(res_h, byref(lc)) != 0: if self.logger: self.logger.warning("Failed get line count") return self.empty_result lines = self._get_lines(res_h, lc.value) angle = self._get_text_angle(res_h) return {"text": None, "text_angle": angle, "lines": lines}
def _get_text_angle(self, res_h: int): a = c_float( ); return a.value if self.ocr_dll.GetImageAngle(res_h, byref(a)) == 0 else None
def _get_lines(self, res_h: int, n: int): return [ self._process_line(res_h, i) for i in range(n)]
def _process_line(self, res_h: int, idx: int): lh = c_int64() if self.ocr_dll.GetOcrLine(res_h, idx, byref(lh)) != 0: if self.logger: self.logger.warning(f"Failed get line handle {idx}") return {"text": None, "bounding_rect": None, "words": []} lhv = lh.value text = self._get_text(lhv, self.ocr_dll.GetOcrLineContent) bbox = self._get_bounding_box(lhv, self.ocr_dll.GetOcrLineBoundingBox) words = self._get_words(lhv) return {"text": text, "bounding_rect": bbox, "words": words}
def _get_words(self, line_h: int): wc = c_int64() if self.ocr_dll.GetOcrLineWordCount(line_h, byref(wc)) != 0: return [] return [self._process_word(line_h, i) for i in range(wc.value)]
def _process_word(self, line_h: int, idx: int): wh = c_int64() if self.ocr_dll.GetOcrWord(line_h, idx, byref(wh)) != 0: if self.logger: self.logger.warning(f"Failed get word handle {idx}") return {"text": None, "bounding_rect": None, "confidence": None} whv = wh.value text = self._get_text(whv, self.ocr_dll.GetOcrWordContent) bbox = self._get_bounding_box(whv, self.ocr_dll.GetOcrWordBoundingBox) conf = self._get_word_confidence(whv) return {"text": text, "bounding_rect": bbox, "confidence": conf}
def _get_text(self, handle: int, func): content = c_char_p() if func(handle, byref(content)) == 0 and content.value: try: return content.value.decode("utf-8", errors="ignore") except Exception as e: if self.logger: self.logger.error(f"Error decoding text: {e}") return None
def _get_word_confidence(self, word_h: int): c = c_float( ); return c.value if self.ocr_dll.GetOcrWordConfidence(word_h, byref(c)) == 0 else None
def _get_bounding_box(self, handle: int, func): bp = BoundingBox_p() if func(handle, byref(bp)) == 0 and bp: b = bp.contents return {"x1": b.x1, "y1": b.y1, "x2": b.x2, "y2": b.y2} return None
@register_OCR("one_ocr")class OCROneAPI(OCRBase): params = { "expand_small_blocks": {"type": "checkbox", "value": True, "description": f"Expand image width/height if < {MIN_DIM_SIZE}px before recognition by padding (helps with small images)"}, "newline_handling": {"type": "selector", "options": ["preserve", "remove"], "value": "preserve", "description": "Newline char handling (preserve/remove)"}, "reverse_line_order": {"type": "checkbox", "value": False, "description": "Reverse line order (for vertical CJK)"}, "no_uppercase": {"type": "checkbox", "value": False, "description": "Convert text to lowercase (except sentence start)"}, "description": "Local OCR using OneOCR library (Windows Only)", }
@property def expand_small_blocks(self): v = self.get_param_value( "expand_small_blocks"); return bool(v) if v is not None else True
@property def newline_handling(self): return self.get_param_value( "newline_handling") or "preserve"
@property def no_uppercase(self): return bool(self.get_param_value("no_uppercase"))
@property def reverse_line_order(self): return bool( self.get_param_value("reverse_line_order"))
def __init__(self, **params) -> None: super().__init__(**params) self.engine = None self.available = False self.config_dir = ONE_OCR_PATH if os.name != "nt": if self.logger: self.logger.warning("OneOCR is Windows-only.") return try: os.makedirs(self.config_dir, exist_ok=True) dll_p = os.path.join(self.config_dir, DLL_NAME) model_p = os.path.join(self.config_dir, MODEL_NAME) if not os.path.exists(dll_p) or not os.path.exists(model_p): msg = f"OneOCR init fail: DLL/Model not found in '{self.config_dir}'. See guide." (self.logger or logging).warning(msg) return self.engine = OcrEngine(self.config_dir, self.logger) self.available = True if self.logger: self.logger.info("OneOCR engine ready.") except Exception as e: if self.logger: self.logger.error( f"Failed to create OcrEngine: {e}", exc_info=self.debug_mode) self.engine = None self.available = False
def _ocr_blk_list(self, img: np.ndarray, blk_list: list[TextBlock], *args, **kwargs): if not self.available: return im_h, im_w = img.shape[:2] for i, blk in enumerate(blk_list): x1, y1, x2, y2 = blk.xyxy if 0 <= y1 < y2 <= im_h and 0 <= x1 < x2 <= im_w: crop = img[y1:y2, x1:x2] if crop.size == 0: blk.text = "" continue try: blk.text = self.ocr(crop, apply_postprocessing=True) except Exception as e: # Log error from main ocr call if self.logger: self.logger.error( f"OCR err block {i+1} {blk.xyxy}: {e}", exc_info=self.debug_mode) blk.text = "" else: blk.text = "" # Invalid coords
def ocr_img(self, img: np.ndarray) -> str: return self.ocr(img, apply_postprocessing=True) if self.available else ""
def ocr(self, img: np.ndarray, apply_postprocessing: bool = True) -> str: if not self.available or self.engine is None or img is None or img.size == 0: return "" start_time = time.time() original_h, original_w = img.shape[:2] padded = False if self.debug_mode and self.logger: self.logger.debug(f"OCR start shape: {original_h}x{original_w}")
try: img_to_process = img # Start with original image if self.expand_small_blocks and (original_h < MIN_DIM_SIZE or original_w < MIN_DIM_SIZE): pad_h_total = max(0, MIN_DIM_SIZE - original_h) pad_w_total = max(0, MIN_DIM_SIZE - original_w) pad_top = pad_h_total//2 pad_bottom = pad_h_total - pad_top pad_left = pad_w_total//2 pad_right = pad_w_total - pad_left # Determine padding color (white) based on channels if len(img.shape) == 2: color = 255 # Grayscale elif img.shape[2] == 3: color = (255, 255, 255) # BGR else: color = (255, 255, 255, 255) # BGRA (or assume if > 3) img_to_process = cv2.copyMakeBorder( img, pad_top, pad_bottom, pad_left, pad_right, cv2.BORDER_CONSTANT, value=color) padded = True if self.debug_mode and self.logger: self.logger.debug( f"Padded img from {original_h}x{original_w} to {img_to_process.shape[:2]} (min={MIN_DIM_SIZE})")
# Convert potentially padded image to RGB for PIL if len(img_to_process.shape) == 2: img_rgb = cv2.cvtColor(img_to_process, cv2.COLOR_GRAY2RGB) elif img_to_process.shape[2] == 3: img_rgb = img_to_process elif img_to_process.shape[2] == 4: img_rgb = cv2.cvtColor(img_to_process, cv2.COLOR_RGBA2RGB) else: raise ValueError( f"Unsupported channels: {img_to_process.shape[2]}")
pil_image = PilImage.fromarray(img_rgb).convert("RGBA") # This might raise RuntimeError on failure code result_dict = self.engine.recognize_pil(pil_image) lines = [line["text"] for line in result_dict.get("lines", []) if line.get("text")] if self.reverse_line_order: lines.reverse() full_text = "\n".join(lines) if apply_postprocessing: full_text = self._apply_text_postprocessing(full_text)
if self.debug_mode and self.logger: self.logger.debug( f"OCR done {(time.time()-start_time):.3f}s, padded: {padded}, lines: {len(lines)}") return full_text
except RuntimeError as e: # Catch errors from _check_dll_result err_code_match = re.search(r"\(Native Code: (\d+)\)", str(e)) err_code = int(err_code_match.group(1)) if err_code_match else None log_msg = f"Critical OCR error: {e}" # Check if it's code 3 and padding *wasn't* applied to a small image if err_code == 3 and not padded and (original_h < MIN_DIM_SIZE or original_w < MIN_DIM_SIZE): log_msg += f" (Native Code 3 often means image too small. Try enabling 'expand_small_blocks' in params if disabled, or check if padding to {MIN_DIM_SIZE}px is sufficient)" if self.logger: self.logger.error(log_msg, exc_info=self.debug_mode) return "" except Exception as e: # Catch other errors (PIL conversion, etc.) if self.logger: self.logger.error( f"Unexpected OCR error: {e}", exc_info=self.debug_mode) return ""
def _apply_text_postprocessing(self, text: str) -> str: if not text: return "" if self.newline_handling == "remove": text = text.replace("\n", " ").replace("\r", "") elif self.newline_handling == "preserve": text = text.replace("\r\n", "\n").replace("\r", "\n") text = self._apply_punctuation_and_spacing(text) if self.no_uppercase: text = self._apply_no_uppercase(text) return text
def _apply_no_uppercase(self, text: str) -> str: if not text: return "" return " ".join([s[0].upper()+s[1:].lower() for s in re.split(r"(?<=[.!?…])\s+", text) if s])
def _apply_punctuation_and_spacing(self, text: str) -> str: if not text: return "" # Remove space before punct text = re.sub(r"\s+([,.!?…;:])", r"\1", text) text = re.sub(r"([,.!?…;:])(?=[^\s,.!?…;:])", r"\1 ", text) # Add space after punct if missing text = re.sub(r"\s{2,}", " ", text) # Collapse multiple spaces return text.strip()
def updateParam(self, key: str, content): super().updateParam(key, content) if self.debug_mode and self.logger: self.logger.debug(f"Param '{key}' updated in OCROneAPI.").gitattributes+4
.gitignoreAdded+64
data/alphabet-all-v5.txtAdded+19264
data/alphabet-all-v7.txtAdded
data/libs/opencv_world455.dllAdded+3
data/libs/patchmatch_inpaint.dllAdded+3
data/models/aot_inpainter.ckptAdded+3
data/models/comictextdetector.ptAdded+3
data/models/comictextdetector.pt.onnxAdded+3
data/models/lama_large_512px.ckptAdded+3
data/models/lama_mpe.ckptAdded+3
data/models/manga-ocr-base/README.mdAdded+24
data/models/manga-ocr-base/config.jsonAdded+2164
data/models/manga-ocr-base/preprocessor_config.jsonAdded+17
data/models/manga-ocr-base/pytorch_model.binAdded+3
data/models/manga-ocr-base/special_tokens_map.jsonAdded+1
data/models/manga-ocr-base/tokenizer_config.jsonAdded+1
data/models/manga-ocr-base/vocab.txtAdded+6144
data/models/mit32px_ocr.ckptAdded+3
data/models/mit48pxctc_ocr.ckptAdded+3
data/models/ocr_ar_48px.ckptAdded+3
data/models/pkuseg/postag/features.pklAdded+3
data/models/pkuseg/postag/weights.npzAdded+3
data/models/pkuseg/spacy_ontonotes/features.msgpackAdded+3
data/models/pkuseg/spacy_ontonotes/weights.npzAdded+3
data/pkusegscores.jsonAdded+1
freeze.txtAdded+446
main.pyAdded+146
modules/__init__.pyAdded+21
modules/base.pyAdded+364
modules/inpaint/__init__.pyAdded+1
modules/inpaint/aot.pyAdded+259
modules/inpaint/base.pyAdded+604
modules/inpaint/ffc.pyAdded+312
modules/inpaint/lama.pyAdded+430
modules/inpaint/patch_match.pyAdded+209
modules/ocr/__init__.pyAdded+1
modules/ocr/base.pyAdded+55
modules/ocr/mit32px.pyAdded+638
modules/ocr/mit48px.pyAdded+893
modules/ocr/mit48px_ctc.pyAdded+503
modules/ocr/ocr_bing_lens.pyAdded+430
modules/ocr/ocr_google_vision.pyAdded+275
modules/ocr/ocr_lens_proto.pyAdded+593
modules/ocr/ocr_llm_api.pyAdded+488
modules/ocr/ocr_macos.pyAdded+151
modules/ocr/ocr_manga.pyAdded+115
modules/ocr/ocr_mit.pyAdded+95
modules/ocr/ocr_none.pyAdded+19
modules/ocr/ocr_oneocr.pyAdded+425