ai.js 574 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167
  1. /*
  2. _ ___ ____ _
  3. / \ |_ _| | __ ) __ _ ___(_) ___
  4. / _ \ | | | _ \ / _` / __| |/ __|
  5. / ___ \ | | | |_) | (_| \__ \ | (__
  6. /_/ \_\___| |____/ \__,_|___/_|\___|
  7. */
  8. Blockly.Blocks['ai_v831_button_read_pressed_canvas'] = {
  9. init: function () {
  10. this.appendDummyInput()
  11. .appendField(Blockly.Msg.ai_basic_button_when)
  12. .appendField(new Blockly.FieldDropdown([
  13. ["A", "A"],
  14. ["B", "B"],
  15. ["C", "C"],
  16. ["D", "D"]
  17. ]), "button_type")
  18. .appendField(Blockly.Msg.ai_basic_pressed)
  19. this.setOutput(true, null);
  20. this.setColour("#d42b03");
  21. var thisBlock = this;
  22. this.setTooltip(function () {
  23. var mode = thisBlock.getFieldValue('button_type');
  24. var TOOLTIPS = {
  25. '0': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "A"),
  26. '1': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "B"),
  27. '2': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "C"),
  28. '3': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "D"),
  29. };
  30. return TOOLTIPS[mode];
  31. });
  32. this.setHelpUrl("");
  33. }
  34. };
  35. Blockly.Python['ai_v831_button_read_pressed_canvas'] = function (block) {
  36. var _type = block.getFieldValue('button_type');
  37. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  38. sys.path.append("/root/")`
  39. Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
  40. // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
  41. Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
  42. key_B = BUTTON(8)
  43. key_C = BUTTON(13)
  44. key_D = BUTTON(7)
  45. `
  46. var code = `key_${_type}.is_pressed()`
  47. return [code, Blockly.Python.ORDER_CONDITIONAL];
  48. };
  49. Blockly.Blocks['ai_v831_button_read_pressed'] = {
  50. init: function () {
  51. this.appendDummyInput()
  52. .appendField(Blockly.Msg.TOUCH_CASE)
  53. .appendField(new Blockly.FieldDropdown([
  54. ["A", "A"],
  55. ["B", "B"],
  56. ["C", "C"],
  57. ["D", "D"]
  58. ]), "button_type")
  59. .appendField(Blockly.Msg.ai_basic_pressed)
  60. this.appendStatementInput("input")
  61. .setCheck(null)
  62. .appendField(Blockly.Msg.basic_motion_statement_exec);
  63. // this.setOutput(true, null);
  64. this.setNextStatement(true);
  65. this.setPreviousStatement(true);
  66. this.setColour("#d42b03");
  67. var thisBlock = this;
  68. this.setTooltip(function () {
  69. var mode = thisBlock.getFieldValue('button_type');
  70. var TOOLTIPS = {
  71. '0': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "A"),
  72. '1': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "B"),
  73. '2': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "C"),
  74. '3': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "D"),
  75. };
  76. return TOOLTIPS[mode];
  77. });
  78. this.setHelpUrl("");
  79. }
  80. };
  81. Blockly.Python['ai_v831_button_read_pressed'] = function (block) {
  82. var _type = block.getFieldValue('button_type');
  83. var statements_input = Blockly.Python.statementToCode(block, 'input');
  84. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  85. sys.path.append("/root/")`
  86. Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
  87. // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
  88. Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
  89. key_B = BUTTON(8)
  90. key_C = BUTTON(13)
  91. key_D = BUTTON(7)
  92. `
  93. let allBlocks = block.workspace.getAllBlocks();
  94. let global = ""
  95. try {
  96. global = allBlocks[0].workspace.variableList.toString()
  97. }
  98. catch (e) {
  99. console.log(e)
  100. }
  101. Blockly.Python.addFunction("BUTTON" + _type, `def BUTTON${_type}():
  102. ${global ? 'global ' + global : ""}
  103. ${statements_input || " pass"}\n`, true)
  104. var code = `if key_${_type}.is_pressed():
  105. BUTTON${_type}()
  106. `
  107. return code;
  108. };
  109. Blockly.Blocks['ai_v831_button_read_released'] = {
  110. init: function () {
  111. this.appendDummyInput()
  112. .appendField(Blockly.Msg.TOUCH_CASE)
  113. .appendField(new Blockly.FieldDropdown([
  114. ["A", "A"],
  115. ["B", "B"],
  116. ["C", "C"],
  117. ["D", "D"]
  118. ]), "button_type")
  119. .appendField(Blockly.Msg.ai_basic_pressed_one)
  120. this.appendStatementInput("input")
  121. .setCheck(null)
  122. .appendField(Blockly.Msg.basic_motion_statement_exec);
  123. // this.setOutput(true, null);
  124. this.setNextStatement(true);
  125. this.setPreviousStatement(true);
  126. this.setColour("#d42b03");
  127. var thisBlock = this;
  128. this.setTooltip(function () {
  129. var mode = thisBlock.getFieldValue('button_type');
  130. var TOOLTIPS = {
  131. '0': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "A"),
  132. '1': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "B"),
  133. '2': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "C"),
  134. '3': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "D"),
  135. };
  136. return TOOLTIPS[mode];
  137. });
  138. this.setHelpUrl("");
  139. }
  140. };
  141. Blockly.Python['ai_v831_button_read_released'] = function (block) {
  142. var _type = block.getFieldValue('button_type');
  143. var statements_input = Blockly.Python.statementToCode(block, 'input');
  144. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  145. sys.path.append("/root/")`
  146. Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
  147. // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
  148. Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
  149. key_B = BUTTON(8)
  150. key_C = BUTTON(13)
  151. key_D = BUTTON(7)
  152. `
  153. let allBlocks = block.workspace.getAllBlocks();
  154. let global = ""
  155. try {
  156. global = allBlocks[0].workspace.variableList.toString()
  157. }
  158. catch (e) {
  159. console.log(e)
  160. }
  161. Blockly.Python.addFunction("BUTTONisPressed" + _type, `def BUTTONisPressed${_type}():
  162. ${global ? 'global ' + global : ""}
  163. ${statements_input || " pass"}\n`, true)
  164. var code = `if key_${_type}.is_pressed():
  165. while not (key_${_type}.is_pressed() == False):
  166. time.sleep(0.1)
  167. BUTTONisPressed${_type}()
  168. `
  169. return code;
  170. };
  171. Blockly.Blocks['ai_v831_button_loosen'] = {
  172. init: function () {
  173. this.appendDummyInput()
  174. .appendField(Blockly.Msg.TOUCH_CASE)
  175. .appendField(new Blockly.FieldDropdown([
  176. ["A", "A"],
  177. ["B", "B"],
  178. ["C", "C"],
  179. ["D", "D"]
  180. ]), "button_type")
  181. .appendField(Blockly.Msg.ESP32RELEASED)
  182. this.appendStatementInput("input")
  183. .setCheck(null)
  184. .appendField(Blockly.Msg.basic_motion_statement_exec);
  185. // this.setOutput(true, null);
  186. this.setNextStatement(true);
  187. this.setPreviousStatement(true);
  188. this.setColour("#d42b03");
  189. var thisBlock = this;
  190. this.setTooltip(function () {
  191. var mode = thisBlock.getFieldValue('button_type');
  192. var TOOLTIPS = {
  193. '0': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "A"),
  194. '1': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "B"),
  195. '2': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "C"),
  196. '3': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "D"),
  197. };
  198. return TOOLTIPS[mode];
  199. });
  200. this.setHelpUrl("");
  201. }
  202. };
  203. Blockly.Python['ai_v831_button_loosen'] = function (block) {
  204. var _type = block.getFieldValue('button_type');
  205. var statements_input = Blockly.Python.statementToCode(block, 'input');
  206. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  207. sys.path.append("/root/")`
  208. Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
  209. // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
  210. Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
  211. key_B = BUTTON(8)
  212. key_C = BUTTON(13)
  213. key_D = BUTTON(7)
  214. `
  215. let allBlocks = block.workspace.getAllBlocks();
  216. let global = ""
  217. try {
  218. global = allBlocks[0].workspace.variableList.toString()
  219. }
  220. catch (e) {
  221. console.log(e)
  222. }
  223. Blockly.Python.addFunction("NOBUTTONisPressed" + _type, `def NOBUTTONisPressed${_type}():
  224. ${global ? 'global ' + global : ""}
  225. ${statements_input || " pass"}\n`, true)
  226. var code = `if key_${_type}.is_pressed() == False:
  227. NOBUTTONisPressed${_type}()
  228. `
  229. return code;
  230. };
  231. Blockly.Blocks['ai_v831_button_del'] = {
  232. init: function () {
  233. this.appendDummyInput()
  234. .appendField(Blockly.Msg.ai_basic_button_when)
  235. .appendField(new Blockly.FieldDropdown([
  236. ["A", "A"],
  237. ["B", "B"],
  238. ["C", "C"],
  239. ["D", "D"]
  240. ]), "button_type_released")
  241. .appendField(Blockly.Msg.ai_basic_released)
  242. this.setPreviousStatement(true, null);
  243. this.setNextStatement(true, null);
  244. this.setColour("#d42b03");
  245. var thisBlock = this;
  246. this.setTooltip(function () {
  247. var mode = thisBlock.getFieldValue('button_type_released');
  248. var TOOLTIPS = {
  249. '0': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "A"),
  250. '1': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "B"),
  251. '2': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "C"),
  252. '3': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "D"),
  253. };
  254. return TOOLTIPS[mode];
  255. });
  256. this.setHelpUrl("");
  257. }
  258. };
  259. Blockly.Python['ai_v831_button_del'] = function (block) {
  260. var _type = block.getFieldValue('button_type_released');
  261. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  262. sys.path.append("/root/")`
  263. Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
  264. // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
  265. Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
  266. key_B = BUTTON(8)
  267. key_C = BUTTON(13)
  268. key_D = BUTTON(7)
  269. `
  270. var code = `key_${_type}.button.release()
  271. del key_${_type}
  272. `
  273. return code;
  274. };
  275. Blockly.Blocks['ai_v831_led_light_up'] = {
  276. init: function () {
  277. this.appendDummyInput()
  278. .appendField(Blockly.Msg.ai_basic_led_set)
  279. .appendField(new Blockly.FieldDropdown([
  280. [Blockly.Msg.ai_basic_led_blue, "blue"],
  281. // [Blockly.Msg.ai_basic_led_red, "red"]
  282. ]), "type")
  283. .appendField(Blockly.Msg.ai_basic_led_on);
  284. this.setPreviousStatement(true, null);
  285. this.setNextStatement(true, null);
  286. this.setColour("#d42b03");
  287. var thisBlock = this;
  288. this.setTooltip(function () {
  289. var mode = thisBlock.getFieldValue('type');
  290. var TOOLTIPS = {
  291. 'blue': Blockly.Msg.ai_k210_led_light_up_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_blue),
  292. 'red': Blockly.Msg.ai_k210_led_light_up_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_red)
  293. };
  294. return TOOLTIPS[mode];
  295. });
  296. this.setHelpUrl("");
  297. }
  298. };
  299. Blockly.Python['ai_v831_led_light_up'] = function (block) {
  300. var dropdown_type = block.getFieldValue('type');
  301. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  302. sys.path.append("/root/")`
  303. Blockly.Python.definitions_['v831_import_smbus2'] = `import smbus2`
  304. Blockly.Python.definitions_['v831_import_time'] = `import time`
  305. Blockly.Python.definitions_['v831_import_CocoPi_LED'] = `from CocoPi import LED
  306. LED = LED()
  307. `
  308. // TODO: Assemble Python into code variable.
  309. var code = `LED.out(1)
  310. `;
  311. return code;
  312. };
  313. Blockly.Blocks['ai_v831_led_light_off'] = {
  314. init: function () {
  315. this.appendDummyInput()
  316. .appendField(Blockly.Msg.ai_basic_led_set)
  317. .appendField(new Blockly.FieldDropdown([
  318. [Blockly.Msg.ai_basic_led_blue, "blue"],
  319. // [Blockly.Msg.ai_basic_led_red, "red"]
  320. ]), "type")
  321. .appendField(Blockly.Msg.ai_basic_led_off);
  322. this.setPreviousStatement(true, null);
  323. this.setNextStatement(true, null);
  324. this.setColour("#d42b03");
  325. var thisBlock = this;
  326. this.setTooltip(function () {
  327. var mode = thisBlock.getFieldValue('type');
  328. var TOOLTIPS = {
  329. 'blue': Blockly.Msg.ai_k210_led_light_off_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_blue),
  330. 'red': Blockly.Msg.ai_k210_led_light_off_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_red)
  331. };
  332. return TOOLTIPS[mode];
  333. });
  334. this.setHelpUrl("");
  335. }
  336. };
  337. Blockly.Python['ai_v831_led_light_off'] = function (block) {
  338. var dropdown_type = block.getFieldValue('type');
  339. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  340. sys.path.append("/root/")`
  341. Blockly.Python.definitions_['v831_import_smbus2'] = `import smbus2`
  342. Blockly.Python.definitions_['v831_import_time'] = `import time`
  343. Blockly.Python.definitions_['v831_import_CocoPi_LED'] = `from CocoPi import LED
  344. LED = LED()
  345. `
  346. // TODO: Assemble Python into code variable.
  347. var code = `LED.out(0)
  348. `;
  349. return code;
  350. };
  351. Blockly.Blocks['ai_v831_rgb_light_up'] = {
  352. init: function () {
  353. this.appendDummyInput()
  354. .appendField(Blockly.Msg.ai_basic_rgb_set_on)
  355. this.appendValueInput("rgb_value")
  356. .setCheck(null)
  357. .appendField("");
  358. this.appendDummyInput()
  359. .appendField(Blockly.Msg.LED_BRTN).appendField(new Blockly.FieldNumber(50, 0, 255), "uart_bps");
  360. this.setPreviousStatement(true, null);
  361. this.setNextStatement(true, null);
  362. this.setColour("#d42b03");
  363. this.setTooltip(Blockly.Msg.ai_basic_rgb_set_on);
  364. this.setHelpUrl("");
  365. }
  366. };
  367. Blockly.Python['ai_v831_rgb_light_up'] = function (block) {
  368. var value_name = Blockly.Python.valueToCode(block, 'rgb_value', Blockly.Python.ORDER_ATOMIC);
  369. var content = block.getFieldValue('uart_bps');
  370. console.log(value_name.slice(1, -1))
  371. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  372. sys.path.append("/root/")`
  373. Blockly.Python.definitions_['v831_import_smbus2'] = `import smbus2`
  374. Blockly.Python.definitions_['v831_import_time'] = `import time`
  375. Blockly.Python.definitions_['v831_import_CocoPi_RGB'] = `from CocoPi import singleRgb
  376. singleRgb=singleRgb()`;
  377. var code = `singleRgb.setBrightness(${content})
  378. singleRgb.setColor(${value_name.slice(1, -1)})
  379. time.sleep(0.05)
  380. singleRgb.show()
  381. `;
  382. return code;
  383. };
  384. Blockly.Blocks['ai_v831_rgb_light_off'] = {
  385. init: function () {
  386. this.appendDummyInput()
  387. .appendField(Blockly.Msg.ai_basic_rgb_set_off)
  388. this.setPreviousStatement(true, null);
  389. this.setNextStatement(true, null);
  390. this.setColour("#d42b03");
  391. this.setTooltip(Blockly.Msg.ai_basic_rgb_set_off);
  392. this.setHelpUrl("");
  393. }
  394. };
  395. Blockly.Python['ai_v831_rgb_light_off'] = function (block) {
  396. var dropdown_type = block.getFieldValue('type');
  397. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  398. sys.path.append("/root/")`
  399. Blockly.Python.definitions_['v831_import_smbus2'] = `import smbus2`
  400. Blockly.Python.definitions_['v831_import_time'] = `import time`
  401. Blockly.Python.definitions_['v831_import_CocoPi_RGB'] = `from CocoPi import singleRgb
  402. singleRgb=singleRgb()`;
  403. // TODO: Assemble Python into code variable.
  404. var code = `singleRgb.setColor(0,0,0)
  405. time.sleep(0.05)
  406. singleRgb.show()
  407. `;
  408. return code;
  409. };
  410. Blockly.Blocks['ai_basic_light_up_led_analog'] = {
  411. init: function () {
  412. this.appendValueInput("brightness")
  413. .setCheck(null)
  414. .appendField(Blockly.Msg.ai_basic_led_analog_set)
  415. .appendField(new Blockly.FieldDropdown([
  416. [Blockly.Msg.ai_basic_led_analog_led1, "1"],
  417. [Blockly.Msg.ai_basic_led_analog_led2, "2"]
  418. ]), "type")
  419. .appendField(Blockly.Msg.ai_basic_led_analog_brightness_text);
  420. this.appendDummyInput()
  421. .appendField(Blockly.Msg.ai_basic_led_analog_range_text);
  422. this.setInputsInline(true);
  423. this.setPreviousStatement(true, null);
  424. this.setNextStatement(true, null);
  425. this.setColour("#d42b03");
  426. var thisBlock = this;
  427. this.setTooltip(function () {
  428. var mode = thisBlock.getFieldValue('type');
  429. var TOOLTIPS = {
  430. '1': Blockly.Msg.ai_basic_light_up_led_analog_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_analog_led1),
  431. '2': Blockly.Msg.ai_basic_light_up_led_analog_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_analog_led2)
  432. };
  433. return TOOLTIPS[mode];
  434. });
  435. this.setHelpUrl("");
  436. }
  437. };
  438. Blockly.Python['ai_basic_light_up_led_analog'] = function (block) {
  439. var dropdown_type = block.getFieldValue('type');
  440. var value_brightness = Blockly.Python.valueToCode(block, 'brightness', Blockly.Python.ORDER_ATOMIC);
  441. Blockly.Python.definitions_['v831_import_time'] = `import time`
  442. Blockly.Python.definitions_['ai_basic_light_up_led_analog_def'] = '' +
  443. 'from machine import Timer,PWM\n' +
  444. '\n' +
  445. 'led_left_tim = Timer(Timer.TIMER2, Timer.CHANNEL0, mode=Timer.MODE_PWM)\n' +
  446. 'led_right_tim = Timer(Timer.TIMER2, Timer.CHANNEL1, mode=Timer.MODE_PWM)\n' +
  447. 'led_left_ctrl = PWM(led_left_tim, freq=500000, duty=50, pin=31)\n' +
  448. 'led_right_ctrl = PWM(led_right_tim, freq=500000, duty=50, pin=32)\n' +
  449. '\n' +
  450. 'def analog_light(which, brightness):\n' +
  451. ' if which == 1:\n' +
  452. ' led_left_ctrl.duty(brightness)\n' +
  453. ' if which == 2:\n' +
  454. ' led_right_ctrl.duty(brightness)\n' +
  455. '';
  456. // TODO: Assemble Python into code variable.
  457. var code = 'analog_light(' + dropdown_type + ',' + value_brightness + ')\n';
  458. return code;
  459. };
  460. /*
  461. _ ___ ___ ____
  462. / \ |_ _| |_ _|_ __ ___ __ _ __ _ ___ | _ \ _ __ ___ ___ ___ ___ ___
  463. / _ \ | | | || '_ ` _ \ / _` |/ _` |/ _ \ | |_) | '__/ _ \ / __/ _ \/ __/ __|
  464. / ___ \ | | | || | | | | | (_| | (_| | __/ | __/| | | (_) | (_| __/\__ \__ \
  465. /_/ \_\___| |___|_| |_| |_|\__,_|\__, |\___| |_| |_| \___/ \___\___||___/___/
  466. |___/
  467. */
  468. Blockly.Blocks["ai_lcd_screeninit"] = {
  469. init: function () {
  470. // this.appendDummyInput()
  471. // .appendField(new Blockly.FieldImage("blockly/media/screen_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  472. // this.appendDummyInput()
  473. // .appendField(Blockly.Msg.image_process_lcd_init);
  474. this.appendDummyInput().appendField(Blockly.Msg.image_process_lcd_direction)
  475. .appendField(new Blockly.FieldDropdown([
  476. [Blockly.Msg.image_process_lcd_landscape_screen, "False"],
  477. [Blockly.Msg.image_process_lcd_vertical_screen, "True"]
  478. ]), "isScreen")
  479. this.setInputsInline(false);
  480. this.setPreviousStatement(true);
  481. this.setNextStatement(true);
  482. this.setColour("#5cb2d6");
  483. this.setTooltip(Blockly.Msg.ai_lcd_screeninit_TOOLTIP);
  484. this.setHelpUrl('');
  485. }
  486. }
  487. Blockly.Python.ai_lcd_screeninit = function (block) {
  488. var isScreen = block.getFieldValue('isScreen');
  489. Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
  490. Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
  491. Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
  492. Blockly.Python.definitions_['v831_import_os'] = `import os`
  493. // Blockly.Python.addVariable("ScreenOrientation", `ScreenOrientation = ${isScreen}`, false)
  494. Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
  495. def CAMERATYPE():
  496. global cameraSize
  497. try:
  498. if os.path.exists("/etc/cameraSize.cfg"):
  499. cameraSize = True
  500. else:
  501. cameraSize = False
  502. except:
  503. cameraSize = False
  504. CAMERATYPE()
  505. `
  506. Blockly.Python.definitions_['v831_camera_set_ScreenOrientation'] = `ScreenOrientation = ${isScreen}`
  507. var _code = ``;
  508. return _code;;
  509. }
  510. Blockly.Blocks['ai_lcd_rotation'] = {
  511. init: function () {
  512. this.appendDummyInput()
  513. .appendField(Blockly.Msg.LCD_CANVAS + Blockly.Msg.image_process_set_lcd_rotation)
  514. // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  515. // .appendField()
  516. .appendField(new Blockly.FieldDropdown([
  517. ["0°", "0"],
  518. ["90°", "90"],
  519. ["180°", "180"],
  520. ["270°", "270"]
  521. ]), "DEGREE")
  522. .appendField(Blockly.Msg.CATEGORY_SHOW)
  523. this.setInputsInline(true);
  524. this.setPreviousStatement(true, null);
  525. this.setNextStatement(true, null);
  526. this.setColour("#5bb2d6");
  527. this.setTooltip(Blockly.Msg.ai_lcd_rotation_TOOLTIP);
  528. this.setHelpUrl('');
  529. }
  530. }
  531. Blockly.Python.ai_lcd_rotation = function (block) {
  532. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  533. var dropdown_name = block.getFieldValue('DEGREE');
  534. Blockly.Python.addFunction('v831_rotation_fun', `def screenShow(inputImg,rotationAngle):
  535. if rotationAngle==90 or rotationAngle == 270:
  536. screenCapture=inputImg.crop(0,0,240,320)
  537. else:
  538. screenCapture=inputImg.crop(0,0,320,240)
  539. canvas_screenShow = screenCapture.rotate(-rotationAngle,adjust=1)
  540. display.show(canvas_screenShow)
  541. `)
  542. let w = ''
  543. let h = ''
  544. if (dropdown_name == 90 || dropdown_name == 270) {
  545. w = 240
  546. h = 320
  547. } else {
  548. w = 320
  549. h = 240
  550. }
  551. var _code = `screenShow(canvas,${dropdown_name})
  552. `;
  553. return _code;;
  554. }
  555. Blockly.Blocks['ai_lcd_font'] = {
  556. init: function () {
  557. this.appendDummyInput().appendField(Blockly.Msg.image_lcd_set_font)
  558. this.appendValueInput("save_path")
  559. .setCheck(null)
  560. this.setInputsInline(true);
  561. this.setPreviousStatement(true, null);
  562. this.setNextStatement(true, null);
  563. this.setColour("#5bb2d6");
  564. this.setTooltip(Blockly.Msg.image_lcd_set_font);
  565. this.setHelpUrl('');
  566. }
  567. }
  568. Blockly.Python.ai_lcd_font = function (block) {
  569. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  570. var font_path = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC);
  571. var _code = `image.load_freetype(${font_path})\n`;
  572. return _code;;
  573. }
  574. Blockly.Blocks['ai_lcd_filp'] = {
  575. init: function () {
  576. this.appendDummyInput()
  577. .appendField(Blockly.Msg.image_process_set_lcd_mirror_flip)
  578. .appendField(new Blockly.FieldCheckbox('TRUE'), 'TextCheckBox');
  579. this.setInputsInline(true);
  580. this.setPreviousStatement(true, null);
  581. this.setNextStatement(true, null);
  582. this.setColour("#5bb2d6");
  583. this.setTooltip(Blockly.Msg.ai_lcd_filp_TOOLTIP);
  584. this.setHelpUrl('');
  585. }
  586. }
  587. Blockly.Python.ai_lcd_filp = function (block) {
  588. var _tf = block.getFieldValue('TextCheckBox') == 'TRUE' ? "True" : "False";
  589. var _code = "lcd.mirror(" + _tf + ")\n";
  590. return _code;
  591. }
  592. Blockly.Blocks['ai_lcd_screen'] = {
  593. init: function () {
  594. this.appendDummyInput()
  595. .appendField(Blockly.Msg.image_process_set_filled_screen_color)
  596. .appendField(new Blockly.FieldDropdown([
  597. [Blockly.Msg.image_process_set_filled_screen_color_red, "RED"],
  598. [Blockly.Msg.image_process_set_filled_screen_color_green, "GREEN"],
  599. [Blockly.Msg.image_process_set_filled_screen_color_blue, "BLUE"],
  600. [Blockly.Msg.image_process_set_filled_screen_color_purple, "PURPLE"],
  601. [Blockly.Msg.image_process_set_filled_screen_color_cyan, "CYAN"],
  602. [Blockly.Msg.image_process_set_filled_screen_color_orange, "ORANGE"],
  603. [Blockly.Msg.image_process_set_filled_screen_color_yellow, "YELLOW"],
  604. [Blockly.Msg.image_process_set_filled_screen_color_black, "BLACK"],
  605. [Blockly.Msg.image_process_set_filled_screen_color_white, "WHITE"]
  606. ]), "COLOR");
  607. this.setInputsInline(true);
  608. this.setPreviousStatement(true, null);
  609. this.setNextStatement(true, null);
  610. this.setColour("#5bb2d6");
  611. var thisBlock = this;
  612. this.setTooltip(function () {
  613. var mode = thisBlock.getFieldValue('COLOR');
  614. var TOOLTIPS = {
  615. 'RED': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_red),
  616. 'GREEN': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_green),
  617. 'BLUE': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_blue),
  618. 'PURPLE': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_purple),
  619. 'CYAN': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_cyan),
  620. 'ORANGE': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_orange),
  621. 'YELLOW': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_yellow),
  622. 'BLACK': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_black),
  623. 'WHITE': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_white)
  624. };
  625. return TOOLTIPS[mode];
  626. });
  627. this.setHelpUrl('');
  628. }
  629. };
  630. Blockly.Python.ai_lcd_screen = function (block) {
  631. var colour_name = block.getFieldValue('COLOR');
  632. var _code = "lcd.clear(lcd." + colour_name + ")\n";
  633. return _code;
  634. }
  635. Blockly.Blocks['ai_lcd_fill_screen_with_rgb'] = {
  636. init: function () {
  637. this.appendDummyInput()
  638. .appendField(Blockly.Msg.image_process_text_let_canvas)
  639. // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  640. .appendField(Blockly.Msg.image_process_text_let_canvas_filled_with_color);
  641. this.appendValueInput("rgb_value")
  642. .setCheck(null)
  643. .appendField("");
  644. this.setInputsInline(true);
  645. this.setPreviousStatement(true, null);
  646. this.setNextStatement(true, null);
  647. this.setColour("#5bb2d6");
  648. this.setTooltip(Blockly.Msg.ai_lcd_fill_screen_with_rgb_TOOLTIP);
  649. this.setHelpUrl("");
  650. }
  651. };
  652. Blockly.Python['ai_lcd_fill_screen_with_rgb'] = function (block) {
  653. var value_name = Blockly.Python.valueToCode(block, 'rgb_value', Blockly.Python.ORDER_ATOMIC);
  654. // TODO: Assemble Python into code variable.
  655. if (value_name.charAt(0) == '#') {
  656. var d = 0,
  657. e = 0,
  658. f = 0;
  659. try {
  660. 7 == value_name.length && (d = parseInt(value_name.substring(1, 3), 16),
  661. e = parseInt(value_name.substring(3, 5), 16),
  662. f = parseInt(value_name.substring(5, 7), 16))
  663. } catch (g) { }
  664. // TODO: Assemble Python into code variable.
  665. value_name = "(" + d + "," + e + "," + f + ")";
  666. }
  667. var code = `try:
  668. if ScreenOrientation:
  669. canvas = image.new(size = (240, 320), color = ${value_name}, mode = "RGB")
  670. else:
  671. canvas = image.new(size = (320, 240), color = ${value_name}, mode = "RGB")
  672. except:
  673. canvas = image.new(size = (320, 240), color = ${value_name}, mode = "RGB")
  674. `;
  675. return code;
  676. };
  677. Blockly.Blocks['ai_lcd_clear'] = {
  678. init: function () {
  679. this.appendDummyInput()
  680. .appendField(Blockly.Msg.image_process_clear_lcd);
  681. this.setInputsInline(true);
  682. this.setPreviousStatement(true, null);
  683. this.setNextStatement(true, null);
  684. this.setColour("#5bb2d6");
  685. this.setTooltip(Blockly.Msg.ai_lcd_clear_TOOLTIP);
  686. this.setHelpUrl('');
  687. }
  688. };
  689. Blockly.Python.ai_lcd_clear = function (block) {
  690. var _code = "lcd.clear(lcd.BLACK)\n";
  691. return _code;
  692. }
  693. Blockly.Blocks['ai_lcd_rgb_value_input'] = {
  694. init: function () {
  695. this.appendDummyInput()
  696. .appendField(Blockly.Msg.image_process_rgb_r);
  697. this.appendValueInput("rgb_value_r")
  698. .setCheck(null)
  699. .appendField("");
  700. this.appendDummyInput()
  701. .appendField(Blockly.Msg.image_process_rgb_g);
  702. this.appendValueInput("rgb_value_g")
  703. .setCheck(null)
  704. .appendField("");
  705. this.appendDummyInput()
  706. .appendField(Blockly.Msg.image_process_rgb_b);
  707. this.appendValueInput("rgb_value_b")
  708. .setCheck(null)
  709. .appendField("");
  710. this.setInputsInline(true);
  711. this.setOutput(true, null);
  712. this.setColour("#5bb2d6");
  713. this.setTooltip(Blockly.Msg.ai_lcd_rgb_value_input_TOOLTIP);
  714. this.setHelpUrl("");
  715. }
  716. };
  717. Blockly.Python['ai_lcd_rgb_value_input'] = function (block) {
  718. var value_rgb_value_r = Blockly.Python.valueToCode(block, 'rgb_value_r', Blockly.Python.ORDER_ATOMIC);
  719. var value_rgb_value_g = Blockly.Python.valueToCode(block, 'rgb_value_g', Blockly.Python.ORDER_ATOMIC);
  720. var value_rgb_value_b = Blockly.Python.valueToCode(block, 'rgb_value_b', Blockly.Python.ORDER_ATOMIC);
  721. // TODO: Assemble Python into code variable.
  722. var code = '' + value_rgb_value_r + ',' + value_rgb_value_g + ',' + value_rgb_value_b + '';
  723. // TODO: Change ORDER_NONE to the correct strength.
  724. return [code, Blockly.Python.ORDER_NONE];
  725. };
  726. Blockly.Blocks.ai_lcd_XY = {
  727. init: function () {
  728. var _input = this.appendDummyInput();
  729. this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL);
  730. this.setTooltip(Blockly.Msg.ai_lcd_XY_TOOLTIP);
  731. this.setColour("#5bb2d6");
  732. this.setOutput(!0, "Boolean");
  733. _input.appendField(Blockly.Msg.image_process_xy_x);
  734. this.appendValueInput("A").setCheck("Number");
  735. _input = this.appendDummyInput();
  736. _input.appendField(Blockly.Msg.image_process_xy_y)
  737. this.appendValueInput("B").setCheck("Number");
  738. this.setInputsInline(!0);
  739. }
  740. };
  741. Blockly.Python.ai_lcd_XY = function (block) {
  742. var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
  743. var _y = Blockly.Python.valueToCode(block, "B", Blockly.Python.ORDER_ATOMIC);
  744. var code = "" + _x + ", " + _y + "";
  745. return [code, Blockly.Python.ORDER_ATOMIC];
  746. };
  747. Blockly.Blocks.ai_lcd_WH = {
  748. init: function () {
  749. var _input = this.appendDummyInput();
  750. this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL);
  751. this.setTooltip(Blockly.Msg.ai_lcd_WH_TOOLTIP);
  752. this.setColour("#5bb2d6");
  753. this.setOutput(!0, "Boolean");
  754. _input.appendField(Blockly.Msg.image_process_wh_width);
  755. this.appendValueInput("A").setCheck("Number");
  756. _input = this.appendDummyInput();
  757. _input.appendField(Blockly.Msg.image_process_wh_height)
  758. this.appendValueInput("B").setCheck("Number");
  759. this.setInputsInline(!0);
  760. }
  761. };
  762. Blockly.Python.ai_lcd_WH = function (block) {
  763. var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
  764. var _y = Blockly.Python.valueToCode(block, "B", Blockly.Python.ORDER_ATOMIC);
  765. var code = "" + _x + ", " + _y + "";
  766. return [code, Blockly.Python.ORDER_ATOMIC];
  767. };
  768. Blockly.Blocks['ai_lcd_colortext'] = {
  769. init: function () {
  770. this.appendDummyInput()
  771. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_text.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  772. this.appendDummyInput()
  773. .appendField(Blockly.Msg.image_process_lcd_show_text);
  774. this.appendDummyInput()
  775. .appendField(Blockly.Msg.image_process_lcd_show_text_color)
  776. .appendField(new Blockly.FieldDropdown([
  777. [Blockly.Msg.image_process_lcd_show_text_color_white, "WHITE"],
  778. [Blockly.Msg.image_process_lcd_show_text_color_black, "BLACK"],
  779. [Blockly.Msg.image_process_lcd_show_text_color_red, "RED"],
  780. [Blockly.Msg.image_process_lcd_show_text_color_green, "GREEN"],
  781. [Blockly.Msg.image_process_lcd_show_text_color_blue, "BLUE"],
  782. [Blockly.Msg.image_process_lcd_show_text_color_purple, "PURPLE"],
  783. [Blockly.Msg.image_process_lcd_show_text_color_cyan, "CYAN"],
  784. [Blockly.Msg.image_process_lcd_show_text_color_orange, "ORANGE"],
  785. [Blockly.Msg.image_process_lcd_show_text_color_yellow, "YELLOW"]
  786. ]), "COLOR");
  787. this.appendDummyInput()
  788. .appendField(Blockly.Msg.image_process_lcd_show_text_bg_color)
  789. .appendField(new Blockly.FieldDropdown([
  790. [Blockly.Msg.image_process_lcd_show_text_color_black, "BLACK"],
  791. [Blockly.Msg.image_process_lcd_show_text_color_white, "WHITE"],
  792. [Blockly.Msg.image_process_lcd_show_text_color_red, "RED"],
  793. [Blockly.Msg.image_process_lcd_show_text_color_green, "GREEN"],
  794. [Blockly.Msg.image_process_lcd_show_text_color_blue, "BLUE"],
  795. [Blockly.Msg.image_process_lcd_show_text_color_purple, "PURPLE"],
  796. [Blockly.Msg.image_process_lcd_show_text_color_cyan, "CYAN"],
  797. [Blockly.Msg.image_process_lcd_show_text_color_orange, "ORANGE"],
  798. [Blockly.Msg.image_process_lcd_show_text_color_yellow, "YELLOW"]
  799. ]), "BCOLOR");
  800. this.appendValueInput("CONTENT")
  801. .setCheck("String")
  802. .appendField(Blockly.Msg.image_process_text_content);
  803. /* this.appendDummyInput()
  804. .appendField(Blockly.Msg.LCDDT); */
  805. this.appendValueInput("POSA")
  806. .setCheck("String")
  807. .appendField(Blockly.Msg.image_process_text_start_coord);
  808. this.setPreviousStatement(true, null);
  809. this.setNextStatement(true, null);
  810. this.setColour("#5bb2d6");
  811. this.setTooltip('');
  812. this.setHelpUrl('');
  813. }
  814. };
  815. Blockly.Python['ai_lcd_colortext'] = function (block) {
  816. var color = block.getFieldValue("COLOR");
  817. var bcolor = block.getFieldValue("BCOLOR");
  818. var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
  819. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  820. //var size = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
  821. var _code = "lcd_draw_string(lcd," + xy + ", " + content + ", color=" + color + ")\n"; //, scale=" + size + "
  822. // return [_code, Blockly.Python.ORDER_ATOMIC]
  823. return _code;
  824. };
  825. Blockly.Blocks["ai_lcd_createnonecarvas"] = {
  826. init: function () {
  827. this.appendDummyInput()
  828. .appendField(Blockly.Msg.image_process_create_blank_canvas)
  829. .appendField(new Blockly.FieldVariable("canvas"), "varitem");
  830. this.appendValueInput("wh")
  831. .setCheck(null)
  832. .appendField(Blockly.Msg.image_process_text_size);
  833. // this.appendDummyInput()
  834. // .appendField(Blockly.Msg.LCDDCC_F)
  835. // .appendField(new Blockly.FieldCheckbox("TRUE"), "check")
  836. // .appendField(Blockly.Msg.LCDDCC_I)
  837. // .appendField(new Blockly.FieldTextInput(""), "text");
  838. this.setInputsInline(true);
  839. this.setPreviousStatement(true, null);
  840. this.setNextStatement(true, null);
  841. this.setColour("#5cb2d6");
  842. this.setTooltip(Blockly.Msg.ai_lcd_createnonecarvas_TOOLTIP);
  843. this.setHelpUrl('');
  844. }
  845. }
  846. Blockly.Python.ai_lcd_createnonecarvas = function (block) {
  847. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  848. var value_wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  849. var _code = variable_name + " = image.new(size = (" + value_wh + "))\n";
  850. return _code;
  851. }
  852. Blockly.Blocks["ai_lcd_fillcanvas"] = {
  853. init: function () {
  854. this.appendDummyInput()
  855. .appendField(Blockly.Msg.image_process_text_let_canvas)
  856. .appendField(new Blockly.FieldVariable("canvas"), "varitem");
  857. this.appendValueInput("color")
  858. .setCheck(null)
  859. .appendField(Blockly.Msg.image_process_text_let_canvas_filled_with_color);
  860. this.setInputsInline(true);
  861. this.setPreviousStatement(true, null);
  862. this.setNextStatement(true, null);
  863. this.setColour("#5cb2d6");
  864. this.setTooltip(Blockly.Msg.ai_lcd_fillcanvas_TOOLTIP);
  865. this.setHelpUrl('');
  866. }
  867. }
  868. Blockly.Python.ai_lcd_fillcanvas = function (block) {
  869. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  870. var value_color = Blockly.Python.valueToCode(block, 'color', Blockly.Python.ORDER_ATOMIC);
  871. var _code = variable_name + '.draw_rectangle(0,0, ' + variable_name + '.width(),' + variable_name + '.height(), color=' + value_color + ', thickness=1, fill=True)\n';
  872. return _code;
  873. }
  874. Blockly.Blocks["ai_lcd_createcarvas"] = {
  875. init: function () {
  876. this.appendDummyInput()
  877. .appendField(Blockly.Msg.image_process_create_image_canvas)
  878. .appendField(new Blockly.FieldVariable("canvas"), "varitem");
  879. this.appendValueInput("path").setCheck(null).appendField(Blockly.Msg.image_process_create_image_canvas_path);
  880. this.setPreviousStatement(true, null);
  881. this.setNextStatement(true, null);
  882. // this.setInputsInline(true);
  883. this.setColour("#5cb2d6");
  884. this.setTooltip(Blockly.Msg.ai_lcd_createcarvas_TOOLTIP);
  885. this.setHelpUrl('');
  886. }
  887. }
  888. Blockly.Python.ai_lcd_createcarvas = function (block) {
  889. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  890. // var checkbox_name = block.getFieldValue('check') == 'TRUE' ? "True" : "False";
  891. var text_name = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  892. var _code = variable_name + " = image.open(" + text_name + ")\n";
  893. return _code;
  894. }
  895. Blockly.Blocks['ai_lcd_showcarvas_set_cord'] = {
  896. init: function () {
  897. this.appendDummyInput()
  898. .appendField(Blockly.Msg.image_process_text_set_canvas_setup)
  899. // .appendField(new Blockly.FieldVariable("canvas"), "varitem");
  900. this.appendValueInput("xy")
  901. .setCheck(null)
  902. .appendField(Blockly.Msg.image_process_text_start_coord_as);
  903. this.setInputsInline(true);
  904. this.setPreviousStatement(true, null);
  905. this.setNextStatement(true, null);
  906. this.setColour("#5cb2d6");
  907. this.setTooltip(Blockly.Msg.ai_lcd_showcarvas_set_cord_TOOLTIP);
  908. this.setHelpUrl("");
  909. }
  910. };
  911. Blockly.Python.ai_lcd_showcarvas_set_cord = function (block) {
  912. var value_name = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  913. // TODO: Assemble Python into code variable.
  914. var code = "_canvas_x, _canvas_y = " + value_name + "\n";
  915. return code;
  916. };
  917. Blockly.Blocks['ai_lcd_showcarvas_set_display'] = {
  918. init: function () {
  919. this.appendDummyInput()
  920. .appendField(Blockly.Msg.image_process_show_canvas)
  921. // .appendField(new Blockly.FieldVariable("canvas"), "varitem");
  922. this.setInputsInline(false);
  923. this.setPreviousStatement(true, null);
  924. this.setNextStatement(true, null);
  925. this.setColour("#5cb2d6");
  926. this.setTooltip(Blockly.Msg.ai_lcd_showcarvas_set_display_TOOLTIP);
  927. this.setHelpUrl("");
  928. }
  929. };
  930. Blockly.Python.ai_lcd_showcarvas_set_display = function (block) {
  931. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  932. Blockly.Python.definitions_['v831_import_mjpg'] = `from maix import mjpg`
  933. Blockly.Python.definitions_['v831_import_utils'] = `from maix import utils`
  934. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  935. Blockly.Python.definitions_['v831_import_time'] = `import time`
  936. Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
  937. Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
  938. Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
  939. Blockly.Python.addVariable(`_canvas_x`, `_canvas_x = 0`, true)
  940. Blockly.Python.addVariable(`_canvas_y`, `_canvas_y = 0`, true)
  941. Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
  942. def CAMERATYPE():
  943. global cameraSize
  944. try:
  945. if os.path.exists("/etc/cameraSize.cfg"):
  946. cameraSize = True
  947. else:
  948. cameraSize = False
  949. except:
  950. cameraSize = False
  951. CAMERATYPE()
  952. `
  953. Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf")
  954. if cameraSize==True:
  955. camera.camera.config(size=(320,240))
  956. else:
  957. camera.camera.config(size=(240,320))
  958. try:
  959. if ScreenOrientation==True:
  960. canvas = image.new(size = (240, 320))
  961. else:
  962. canvas = image.new(size = (320, 240))
  963. except:
  964. canvas = image.new(size = (320, 240))
  965. ScreenOrientation = False
  966. `
  967. Blockly.Python.definitions_[`v831_display_show_canvas`] = `def v831_display_show_canvas(displayShow,_canvas_x,_canvas_y):
  968. global ScreenOrientation,cameraSize
  969. try:
  970. if ScreenOrientation:
  971. displayShowCanvas = image.new(size = (240, 320))
  972. displayShowCanvas.draw_rectangle(0,0,240,320, color=(0,0,0), thickness=-1)
  973. displayShowCanvas.draw_image(displayShow,_canvas_x,_canvas_y,alpha=1)
  974. displayShowVER = displayShowCanvas.crop(0,0,240,320)
  975. displayShowVER = displayShowVER.rotate(-90, adjust=1)
  976. display.show(displayShowVER)
  977. else:
  978. displayShowCanvas = image.new(size = (320, 240))
  979. displayShowCanvas.draw_rectangle(0,0,320,240, color=(0,0,0), thickness=-1)
  980. displayShowCanvas.draw_image(displayShow,_canvas_x,_canvas_y,alpha=1)
  981. display.show(displayShowCanvas)
  982. except:
  983. displayShowCanvas = image.new(size = (320, 240))
  984. displayShowCanvas.draw_rectangle(0,0,320,240, color=(0,0,0), thickness=-1)
  985. displayShowCanvas.draw_image(displayShow,_canvas_x,_canvas_y,alpha=1)
  986. display.show(displayShowCanvas)
  987. `
  988. var code = `v831_display_show_canvas(canvas,_canvas_x,_canvas_y)
  989. `;
  990. return code;
  991. };
  992. Blockly.Blocks['ai_lcd_showcarvas'] = {
  993. init: function () {
  994. this.appendDummyInput()
  995. .appendField(Blockly.Msg.image_process_show_canvas)
  996. .appendField(new Blockly.FieldVariable("canvas"), "varitem");
  997. this.appendValueInput("xy")
  998. .setCheck(null)
  999. .appendField(Blockly.Msg.image_process_text_start_coord);
  1000. this.setInputsInline(false);
  1001. this.setPreviousStatement(true, null);
  1002. this.setNextStatement(true, null);
  1003. this.setColour("#5cb2d6");
  1004. this.setTooltip("");
  1005. this.setHelpUrl("");
  1006. }
  1007. };
  1008. Blockly.Python.ai_lcd_showcarvas = function (block) {
  1009. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1010. var value_name = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  1011. // TODO: Assemble Python into code variable.
  1012. var code = "lcd.display(" + variable_name + ", oft=(" + value_name + "))\n";
  1013. return code;
  1014. };
  1015. Blockly.Blocks['ai_lcd_clearcanvas'] = {
  1016. init: function () {
  1017. this.appendDummyInput()
  1018. .appendField(Blockly.Msg.image_process_clear_canvas_1 + Blockly.Msg.image_process_clear_canvas_2)
  1019. this.setPreviousStatement(true, null);
  1020. this.setNextStatement(true, null);
  1021. this.setColour("#5bb2d6");
  1022. this.setTooltip(Blockly.Msg.ai_lcd_clearcanvas_TOOLTIP);
  1023. this.setHelpUrl('');
  1024. }
  1025. }
  1026. Blockly.Python.ai_lcd_clearcanvas = function (block) {
  1027. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1028. var _code = "canvas.clear()\n";
  1029. return _code;;
  1030. }
  1031. Blockly.Blocks['lcd_set_position'] = {
  1032. init: function () {
  1033. this.appendValueInput("POSX")
  1034. .setCheck("Number")
  1035. .appendField("X:");
  1036. this.appendValueInput("POSY")
  1037. .setCheck("Number")
  1038. .appendField("Y:");
  1039. this.setOutput(true, "String");
  1040. this.setInputsInline(true);
  1041. this.setColour("#5bb2d6");
  1042. this.setTooltip("");
  1043. this.setHelpUrl("");
  1044. }
  1045. };
  1046. Blockly.Python['lcd_set_position'] = function (block) {
  1047. // var reg = /^?[0-9]\d*$/
  1048. var pos_x = Blockly.Python.valueToCode(block, 'POSX', Blockly.Python.ORDER_ATOMIC);
  1049. var pos_y = Blockly.Python.valueToCode(block, 'POSY', Blockly.Python.ORDER_ATOMIC);
  1050. //var code = posConvert(pos_x, pos_y);
  1051. var code = pos_x + "," + pos_y;
  1052. return [code, Blockly.Python.ORDER_ATOMIC];
  1053. };
  1054. Blockly.Blocks['lcd_set_color'] = {
  1055. init: function () {
  1056. this.appendDummyInput()
  1057. .appendField(Blockly.Msg.COLOR)
  1058. .appendField(new Blockly.FieldColour("#ff0000"), "COLOR");
  1059. this.setOutput(true, "String");
  1060. this.setColour("#5bb2d6");
  1061. this.setTooltip("");
  1062. this.setHelpUrl("");
  1063. }
  1064. };
  1065. Blockly.Python['lcd_set_color'] = function (block) {
  1066. var code = block.getFieldValue('COLOR');
  1067. return [code, Blockly.Python.ORDER_ATOMIC];
  1068. };
  1069. Blockly.Blocks['lcd_set_width_height'] = {
  1070. init: function () {
  1071. this.appendValueInput("WIDTH")
  1072. .setCheck("Number")
  1073. .appendField(Blockly.Msg.OLCD_WIDTH);
  1074. this.appendValueInput("HEIGHT")
  1075. .setCheck("Number")
  1076. .appendField(Blockly.Msg.OLCD_HEIGHT);
  1077. this.setOutput(true, "String");
  1078. this.setInputsInline(true);
  1079. this.setColour("#5bb2d6");
  1080. this.setTooltip("");
  1081. this.setHelpUrl("");
  1082. }
  1083. };
  1084. Blockly.Python['lcd_set_width_height'] = function (block) {
  1085. var width = Blockly.Python.valueToCode(block, 'WIDTH', Blockly.Python.ORDER_ATOMIC);
  1086. var height = Blockly.Python.valueToCode(block, 'HEIGHT', Blockly.Python.ORDER_ATOMIC);
  1087. var code = width + ', ' + height;
  1088. return [code, Blockly.Python.ORDER_ATOMIC];
  1089. };
  1090. // ai_lcd_textcarvas_new_line
  1091. Blockly.Blocks['ai_lcd_textcarvas_new_line'] = {
  1092. init: function () {
  1093. this.appendDummyInput()
  1094. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_text.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  1095. this.appendDummyInput()
  1096. .appendField(Blockly.Msg.image_process_text_on_canvas + Blockly.Msg.image_process_text_on_draw + Blockly.Msg.image_process_draw_text)
  1097. // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1098. // .appendField();
  1099. this.appendValueInput("POSA")
  1100. .setCheck("String")
  1101. .appendField(Blockly.Msg.image_process_text_start_coord);
  1102. this.appendValueInput("CONTENT")
  1103. .setCheck("String")
  1104. .appendField(Blockly.Msg.image_process_text_content);
  1105. this.appendValueInput("dispalyStr")
  1106. .setCheck("Number")
  1107. .appendField(Blockly.Msg.image_process_text_dispalyStr);
  1108. this.appendValueInput("buttonUp")
  1109. .setCheck("String")
  1110. .appendField(Blockly.Msg.image_process_text_buttonDown);
  1111. this.appendValueInput("buttonDown")
  1112. .setCheck("String")
  1113. .appendField(Blockly.Msg.image_process_text_buttonUp);
  1114. this.appendValueInput("COLOR")
  1115. .setCheck("String")
  1116. .appendField(Blockly.Msg.image_process_text_color);
  1117. this.appendValueInput("Scale")
  1118. .setCheck("Number")
  1119. .appendField(Blockly.Msg.image_process_draw_text_font_size);
  1120. this.appendValueInput("LineNum")
  1121. .setCheck("Number")
  1122. .appendField(Blockly.Msg.image_process_text_line_heigit);
  1123. // this.appendDummyInput()
  1124. // .appendField(Blockly.Msg.image_process_draw_text_if_monospace)
  1125. // .appendField(new Blockly.FieldCheckbox("FALSE"), "bool");
  1126. this.setInputsInline(false);
  1127. this.setPreviousStatement(true);
  1128. this.setNextStatement(true);
  1129. this.setColour("#5bb2d6");
  1130. this.setTooltip(Blockly.Msg.ai_lcd_textcarvas_TOOLTIP);
  1131. this.setHelpUrl('');
  1132. }
  1133. };
  1134. Blockly.Python.ai_lcd_textcarvas_new_line = function (block) {
  1135. var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  1136. var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
  1137. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1138. var scale = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
  1139. var LineNum = Blockly.Python.valueToCode(block, 'LineNum', Blockly.Python.ORDER_ATOMIC);
  1140. var dispalyStr = Blockly.Python.valueToCode(block, 'dispalyStr', Blockly.Python.ORDER_ATOMIC);
  1141. var buttonUp = Blockly.Python.valueToCode(block, 'buttonUp', Blockly.Python.ORDER_ATOMIC);
  1142. var buttonDown = Blockly.Python.valueToCode(block, 'buttonDown', Blockly.Python.ORDER_ATOMIC);
  1143. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1144. Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
  1145. Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
  1146. Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
  1147. Blockly.Python.definitions_['v831_import_os'] = `import os`
  1148. Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
  1149. def CAMERATYPE():
  1150. global cameraSize
  1151. try:
  1152. if os.path.exists("/etc/cameraSize.cfg"):
  1153. cameraSize = True
  1154. else:
  1155. cameraSize = False
  1156. except:
  1157. cameraSize = False
  1158. CAMERATYPE()
  1159. `
  1160. Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf")
  1161. if cameraSize==True:
  1162. camera.camera.config(size=(320,240))
  1163. else:
  1164. camera.camera.config(size=(240,320))
  1165. try:
  1166. if ScreenOrientation==True:
  1167. canvas = image.new(size = (240, 320))
  1168. else:
  1169. canvas = image.new(size = (320, 240))
  1170. except:
  1171. canvas = image.new(size = (320, 240))
  1172. ScreenOrientation = False
  1173. `
  1174. var _code = ""
  1175. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  1176. sys.path.append("/root/")`
  1177. Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
  1178. // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
  1179. Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
  1180. key_B = BUTTON(8)
  1181. key_C = BUTTON(13)
  1182. key_D = BUTTON(7)`
  1183. Blockly.Python.definitions_["ai_lcd_textcarvas_new_line"] = `BUTTONNUMBER = 0
  1184. def textCanvasNewLine(canvasName,posax,posay,text,Num,buttonUp,buttonDown,Scale,Color,LineNum):
  1185. global BUTTONNUMBER,ScreenOrientation
  1186. numText = len(text)//Num + 1
  1187. lineHeight = 240
  1188. if ScreenOrientation:
  1189. lineHeight = 320
  1190. if numText>(lineHeight//LineNum):
  1191. if buttonUp:
  1192. time.sleep(0.1)
  1193. if BUTTONNUMBER<int(numText-(lineHeight//LineNum))+ int(posay/LineNum):
  1194. BUTTONNUMBER = BUTTONNUMBER + 1
  1195. elif buttonDown:
  1196. time.sleep(0.1)
  1197. if BUTTONNUMBER>0:
  1198. BUTTONNUMBER = BUTTONNUMBER - 1
  1199. #BUTTONNUMBER = BUTTONNUMBER + (posay/LineNum)
  1200. for i in range(numText):
  1201. canvasName.draw_string(posax,posay+int(i*LineNum),text[int((i+BUTTONNUMBER)*Num):int((i+1+BUTTONNUMBER)*Num)], scale = Scale, color = Color, thickness = 1)
  1202. # canvasName.draw_string(posax,posay,str(text), scale = Scale, color = Color, thickness = 1)
  1203. `
  1204. if (color.charAt(0) == '#') {
  1205. var d = 0,
  1206. e = 0,
  1207. f = 0;
  1208. try {
  1209. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1210. e = parseInt(color.substring(3, 5), 16),
  1211. f = parseInt(color.substring(5, 7), 16))
  1212. } catch (g) { }
  1213. var bool = "False";
  1214. // var bool = block.getFieldValue('bool') == "TRUE" ? "True" : "False";
  1215. // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False";
  1216. // color=(" + d + "," + e + "," + f + ")" + ", font_size=" + size + ")\n"
  1217. _code = `textCanvasNewLine(canvas,${xy},${content},${dispalyStr},${buttonUp},${buttonDown},${scale},(${d} ,${e}, ${f}),${LineNum})\n`
  1218. // _code = variable_name + '.draw_string(' + xy + ', ' + content + ', scale = ' + scale + ', color = (' + d + ',' + e + ',' + f + ') , thickness = 1)\n'; // #在红色画布上写下hello world
  1219. } else if (color.charAt(0) != '#') {
  1220. var d = 0,
  1221. e = 0,
  1222. f = 0;
  1223. try {
  1224. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1225. e = parseInt(color.substring(3, 5), 16),
  1226. f = parseInt(color.substring(5, 7), 16))
  1227. } catch (g) { }
  1228. _code = `textCanvasNewLine(canvas,${xy},${content},${dispalyStr},${buttonUp},${buttonDown},${scale},${color},${LineNum})\n`
  1229. // _code = variable_name + '.draw_string(' + xy + ', ' + content + ', scale = ' + scale + ', color = ' + color + ', thickness = 1)\n' + // #在红色画布上写下hello world
  1230. // '';
  1231. }
  1232. return _code;
  1233. }
  1234. Blockly.Blocks['ai_lcd_textcarvas'] = {
  1235. init: function () {
  1236. this.appendDummyInput()
  1237. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_text.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  1238. this.appendDummyInput()
  1239. .appendField(Blockly.Msg.image_process_text_on_canvas + Blockly.Msg.image_process_text_on_draw + Blockly.Msg.image_process_draw_text)
  1240. // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1241. this.appendValueInput("POSA")
  1242. .setCheck("String")
  1243. .appendField(Blockly.Msg.image_process_text_start_coord);
  1244. this.appendValueInput("CONTENT")
  1245. .setCheck("String")
  1246. .appendField(Blockly.Msg.image_process_text_content);
  1247. this.appendValueInput("COLOR")
  1248. .setCheck("String")
  1249. .appendField(Blockly.Msg.image_process_text_color);
  1250. this.appendValueInput("Scale")
  1251. .setCheck("Number")
  1252. .appendField(Blockly.Msg.image_process_draw_text_font_size);
  1253. // this.appendDummyInput()
  1254. // .appendField(Blockly.Msg.image_process_draw_text_if_monospace)
  1255. // .appendField(new Blockly.FieldCheckbox("FALSE"), "bool");
  1256. this.setInputsInline(false);
  1257. this.setPreviousStatement(true);
  1258. this.setNextStatement(true);
  1259. this.setColour("#5bb2d6");
  1260. this.setTooltip(Blockly.Msg.ai_lcd_textcarvas_TOOLTIP);
  1261. this.setHelpUrl('');
  1262. }
  1263. };
  1264. Blockly.Python.ai_lcd_textcarvas = function (block) {
  1265. var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  1266. Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
  1267. Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
  1268. Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
  1269. Blockly.Python.definitions_['v831_import_os'] = `import os`
  1270. Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
  1271. def CAMERATYPE():
  1272. global cameraSize
  1273. try:
  1274. if os.path.exists("/etc/cameraSize.cfg"):
  1275. cameraSize = True
  1276. else:
  1277. cameraSize = False
  1278. except:
  1279. cameraSize = False
  1280. CAMERATYPE()
  1281. `
  1282. Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf")
  1283. if cameraSize==True:
  1284. camera.camera.config(size=(320,240))
  1285. else:
  1286. camera.camera.config(size=(240,320))
  1287. try:
  1288. if ScreenOrientation==True:
  1289. canvas = image.new(size = (240, 320))
  1290. else:
  1291. canvas = image.new(size = (320, 240))
  1292. except:
  1293. canvas = image.new(size = (320, 240))
  1294. ScreenOrientation = False
  1295. `
  1296. var _code = ""
  1297. if (color.charAt(0) == '#') {
  1298. var d = 0,
  1299. e = 0,
  1300. f = 0;
  1301. try {
  1302. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1303. e = parseInt(color.substring(3, 5), 16),
  1304. f = parseInt(color.substring(5, 7), 16))
  1305. } catch (g) { }
  1306. var bool = "False";
  1307. // var bool = block.getFieldValue('bool') == "TRUE" ? "True" : "False";
  1308. // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False";
  1309. var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
  1310. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1311. var scale = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
  1312. // color=(" + d + "," + e + "," + f + ")" + ", font_size=" + size + ")\n"
  1313. _code = 'canvas.draw_string(' + xy + ', ' + content + ', scale = ' + scale + ', color = (' + d + ',' + e + ',' + f + ') , thickness = 1)\n'; // #在红色画布上写下hello world
  1314. } else if (color.charAt(0) != '#') {
  1315. var d = 0,
  1316. e = 0,
  1317. f = 0;
  1318. try {
  1319. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1320. e = parseInt(color.substring(3, 5), 16),
  1321. f = parseInt(color.substring(5, 7), 16))
  1322. } catch (g) { }
  1323. var bool = "False";
  1324. // var bool = block.getFieldValue('bool') == "TRUE" ? "True" : "False";
  1325. // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False";
  1326. var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
  1327. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1328. var scale = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
  1329. _code = 'canvas.draw_string(' + xy + ', ' + content + ', scale = ' + scale + ', color = ' + color + ', thickness = 1)\n' + // #在红色画布上写下hello world
  1330. '';
  1331. }
  1332. return _code;
  1333. }
  1334. Blockly.Blocks['ai_lcd_characterscarvas'] = {
  1335. init: function () {
  1336. this.appendDummyInput()
  1337. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_hanzi_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  1338. this.appendDummyInput()
  1339. .appendField(Blockly.Msg.image_process_text_on_canvas)
  1340. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1341. .appendField(Blockly.Msg.image_process_text_on_draw + Blockly.Msg.image_process_draw_characters);
  1342. this.appendValueInput("POSA")
  1343. .setCheck("String")
  1344. .appendField(Blockly.Msg.image_process_text_start_coord);
  1345. this.appendValueInput("CONTENT")
  1346. .setCheck("String")
  1347. .appendField(Blockly.Msg.image_process_text_content);
  1348. this.appendValueInput("COLOR")
  1349. .setCheck("String")
  1350. .appendField(Blockly.Msg.image_process_text_color);
  1351. this.appendDummyInput()
  1352. .appendField(Blockly.Msg.image_process_draw_text_font_size + ":")
  1353. // .setCheck(null)
  1354. .appendField(new Blockly.FieldDropdown([
  1355. [Blockly.Msg.SMALL, "1"],
  1356. [Blockly.Msg.MIDDLE, "2"],
  1357. [Blockly.Msg.LARGE, "3"]
  1358. ]), "fonts");
  1359. // this.appendDummyInput()
  1360. // .appendField(Blockly.Msg.Set_Auto_Wrap + ":")
  1361. // // .setCheck(null)
  1362. // .appendField(new Blockly.FieldDropdown([
  1363. // [Blockly.Msg.LED_SCROLL_YES, "True"],
  1364. // [Blockly.Msg.LED_SCROLL_NO, "False"]
  1365. // ]), "wraps");
  1366. this.setInputsInline(false);
  1367. this.setPreviousStatement(true);
  1368. this.setNextStatement(true);
  1369. this.setColour("#5bb2d6");
  1370. this.setTooltip(Blockly.Msg.ai_lcd_characterscarvas_TOOLTIP);
  1371. this.setHelpUrl('');
  1372. }
  1373. };
  1374. Blockly.Python.ai_lcd_characterscarvas = function (block) {
  1375. var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  1376. var _code = ''
  1377. if (color.charAt(0) == '#') {
  1378. var d = 0,
  1379. e = 0,
  1380. f = 0;
  1381. try {
  1382. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1383. e = parseInt(color.substring(3, 5), 16),
  1384. f = parseInt(color.substring(5, 7), 16))
  1385. } catch (g) { }
  1386. // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False";
  1387. var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
  1388. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1389. var size = block.getFieldValue('fonts');;
  1390. // var wraps = block.getFieldValue('wraps');
  1391. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1392. _code = "lcd_draw_string(" + variable_name + ", " + xy + ", " + content + ", color=(" + d + "," + e + "," + f + ")" + ", font_size=" + size + ")\n";
  1393. } else if (color.charAt(0) != '#') {
  1394. var d = 0,
  1395. e = 0,
  1396. f = 0;
  1397. try {
  1398. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1399. e = parseInt(color.substring(3, 5), 16),
  1400. f = parseInt(color.substring(5, 7), 16))
  1401. } catch (g) { }
  1402. // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False";
  1403. var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
  1404. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1405. var size = block.getFieldValue('fonts');;
  1406. // var wraps = block.getFieldValue('wraps');
  1407. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1408. _code = "lcd_draw_string(" + variable_name + ", " + xy + ", " + content + ", color=" + color + ", font_size=" + size + ")\n";
  1409. }
  1410. return _code;
  1411. }
  1412. Blockly.Blocks['ai_lcd_linecarvas'] = {
  1413. init: function () {
  1414. this.appendDummyInput()
  1415. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_line.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  1416. this.appendDummyInput()
  1417. .appendField(Blockly.Msg.image_process_text_on_canvas + Blockly.Msg.image_process_text_on_draw + Blockly.Msg.image_process_draw_line)
  1418. // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1419. // .appendField();
  1420. this.appendValueInput("POSA")
  1421. .setCheck("String")
  1422. .appendField(Blockly.Msg.image_process_text_start_coord);
  1423. this.appendValueInput("POSB")
  1424. .setCheck("String")
  1425. .appendField(Blockly.Msg.image_process_text_end_coord);
  1426. this.appendValueInput("COLOR")
  1427. .setCheck("String")
  1428. .appendField(Blockly.Msg.image_process_text_color);
  1429. this.appendValueInput("Scale")
  1430. .setCheck("Number")
  1431. .appendField(Blockly.Msg.image_process_text_thick);
  1432. this.setInputsInline(false);
  1433. this.setPreviousStatement(true);
  1434. this.setNextStatement(true);
  1435. this.setColour("#5bb2d6");
  1436. this.setTooltip(Blockly.Msg.ai_lcd_linecarvas_TOOLTIP);
  1437. this.setHelpUrl('');
  1438. }
  1439. };
  1440. Blockly.Python.ai_lcd_linecarvas = function (block) {
  1441. var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  1442. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1443. Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
  1444. Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
  1445. Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
  1446. Blockly.Python.definitions_['v831_import_os'] = `import os`
  1447. Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
  1448. def CAMERATYPE():
  1449. global cameraSize
  1450. try:
  1451. if os.path.exists("/etc/cameraSize.cfg"):
  1452. cameraSize = True
  1453. else:
  1454. cameraSize = False
  1455. except:
  1456. cameraSize = False
  1457. CAMERATYPE()
  1458. `
  1459. Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf")
  1460. if cameraSize==True:
  1461. camera.camera.config(size=(320,240))
  1462. else:
  1463. camera.camera.config(size=(240,320))
  1464. try:
  1465. if ScreenOrientation==True:
  1466. canvas = image.new(size = (240, 320))
  1467. else:
  1468. canvas = image.new(size = (320, 240))
  1469. except:
  1470. canvas = image.new(size = (320, 240))
  1471. ScreenOrientation = False
  1472. `
  1473. if (color.charAt(0) == '#') {
  1474. var d = 0,
  1475. e = 0,
  1476. f = 0;
  1477. try {
  1478. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1479. e = parseInt(color.substring(3, 5), 16),
  1480. f = parseInt(color.substring(5, 7), 16))
  1481. } catch (g) { }
  1482. var size = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
  1483. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1484. var xy2 = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
  1485. var _code = "canvas.draw_line(" + xy + ", " + xy2 + ", color=(" + d + "," + e + "," + f + "), thickness=" + size + ")\n";
  1486. } else if (color.charAt(0) != '#') {
  1487. var d = 0,
  1488. e = 0,
  1489. f = 0;
  1490. try {
  1491. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1492. e = parseInt(color.substring(3, 5), 16),
  1493. f = parseInt(color.substring(5, 7), 16))
  1494. } catch (g) { }
  1495. var size = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
  1496. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1497. var xy2 = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
  1498. var _code = "canvas.draw_line(" + xy + ", " + xy2 + ", color=" + color + ", thickness=" + size + ")\n";
  1499. }
  1500. return _code;
  1501. }
  1502. Blockly.Blocks['ai_lcd_draw_rectangle'] = {
  1503. init: function () {
  1504. // this.appendDummyInput()
  1505. // .appendField(
  1506. // new Blockly.FieldImage("./../blockly/media/line.png", 25, 25, "15"));
  1507. this.appendDummyInput()
  1508. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_rectangle.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  1509. this.appendDummyInput()
  1510. .appendField(Blockly.Msg.image_process_text_on_canvas + Blockly.Msg.image_process_text_on_draw)
  1511. // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1512. // .appendField()
  1513. .appendField(new Blockly.FieldDropdown([
  1514. [Blockly.Msg.image_process_text_filled, "fillrect"],
  1515. [Blockly.Msg.image_process_text_stroked, "rect"]
  1516. ]), "rect_type")
  1517. .appendField(Blockly.Msg.image_process_draw_rectangle_text);
  1518. this.appendValueInput("POSA")
  1519. .setCheck("String")
  1520. .appendField(Blockly.Msg.image_process_text_start_coord);
  1521. this.appendValueInput("POSB")
  1522. .setCheck("String")
  1523. .appendField(Blockly.Msg.image_process_text_size);
  1524. this.appendValueInput("COLOR")
  1525. .setCheck("String")
  1526. .appendField(Blockly.Msg.image_process_text_color);
  1527. // this.appendValueInput("Scale")
  1528. // .setCheck("Number")
  1529. // .appendField(Blockly.Msg.image_process_text_thick);
  1530. this.setInputsInline(false);
  1531. this.setPreviousStatement(true);
  1532. this.setNextStatement(true);
  1533. this.setColour("#5bb2d6");
  1534. var thisBlock = this;
  1535. this.setTooltip(function () {
  1536. var mode = thisBlock.getFieldValue('rect_type');
  1537. var TOOLTIPS = {
  1538. 'fillrect': Blockly.Msg.ai_lcd_ractanglecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_filled),
  1539. 'rect': Blockly.Msg.ai_lcd_ractanglecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_stroked)
  1540. };
  1541. return TOOLTIPS[mode];
  1542. });
  1543. this.setHelpUrl('');
  1544. }
  1545. };
  1546. Blockly.Python.ai_lcd_draw_rectangle = function (block) {
  1547. var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  1548. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1549. var type = block.getFieldValue('rect_type') == "fillrect" ? "-1" : "1";
  1550. var th = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
  1551. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1552. var size = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
  1553. Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
  1554. Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
  1555. Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
  1556. Blockly.Python.definitions_['v831_import_os'] = `import os`
  1557. Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
  1558. def CAMERATYPE():
  1559. global cameraSize
  1560. try:
  1561. if os.path.exists("/etc/cameraSize.cfg"):
  1562. cameraSize = True
  1563. else:
  1564. cameraSize = False
  1565. except:
  1566. cameraSize = False
  1567. CAMERATYPE()
  1568. `
  1569. Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf")
  1570. if cameraSize==True:
  1571. camera.camera.config(size=(320,240))
  1572. else:
  1573. camera.camera.config(size=(240,320))
  1574. try:
  1575. if ScreenOrientation==True:
  1576. canvas = image.new(size = (240, 320))
  1577. else:
  1578. canvas = image.new(size = (320, 240))
  1579. except:
  1580. canvas = image.new(size = (320, 240))
  1581. ScreenOrientation = False
  1582. `
  1583. // console.log(xy.split(','),size.split(','))
  1584. let a = xy.split(',')
  1585. let b = size.split(',')
  1586. // let w = Number(a[0])+Number(b[0])
  1587. // let h = Number(a[1])+Number(b[1])
  1588. // let wh = `${w},${h}`
  1589. // let ai_lcd_fill_screen_with_rgb = text.includes('ai_lcd_fill_screen_with_rgb')
  1590. var _code = ''
  1591. if (color.charAt(0) == '#') {
  1592. var d = 0,
  1593. e = 0,
  1594. f = 0;
  1595. try {
  1596. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1597. e = parseInt(color.substring(3, 5), 16),
  1598. f = parseInt(color.substring(5, 7), 16))
  1599. } catch (g) { }
  1600. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1601. // var type = block.getFieldValue('rect_type') == "fillrect" ? "-1" : "1";
  1602. // var th = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
  1603. // var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1604. // var size = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
  1605. _code = `canvas.draw_rectangle(${xy}, ${a[0]}+${b[0]},${a[1]}+${b[1]}, color=(${d},${e},${f}), thickness=${type})
  1606. `
  1607. } else if (color.charAt(0) != '#') {
  1608. _code = `canvas.draw_rectangle(${xy}, ${a[0]}+${b[0]},${a[1]}+${b[1]}, color=${color}, thickness=${type})
  1609. `
  1610. }
  1611. return _code;
  1612. }
  1613. Blockly.Blocks['ai_lcd_drawcirclecarvas'] = {
  1614. init: function () {
  1615. this.appendDummyInput()
  1616. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_circle.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  1617. this.appendDummyInput()
  1618. .appendField(Blockly.Msg.image_process_text_on_canvas + Blockly.Msg.image_process_text_on_draw)
  1619. // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1620. // .appendField()
  1621. .appendField(new Blockly.FieldDropdown([
  1622. [Blockly.Msg.image_process_text_filled, "fillrect"],
  1623. [Blockly.Msg.image_process_text_stroked, "rect"]
  1624. ]), "rect_type")
  1625. .appendField(Blockly.Msg.image_process_draw_circle_text);
  1626. this.appendValueInput("POSA")
  1627. .setCheck("String")
  1628. .appendField(Blockly.Msg.image_process_draw_circle_text_start);
  1629. this.appendValueInput("Scale")
  1630. .setCheck("Number")
  1631. .appendField(Blockly.Msg.image_process_text_radius);
  1632. this.appendValueInput("COLOR")
  1633. .setCheck("String")
  1634. .appendField(Blockly.Msg.image_process_text_color);
  1635. // this.appendValueInput("Scale_0")
  1636. // .setCheck("Number")
  1637. // .appendField(Blockly.Msg.image_process_text_thick);
  1638. this.setInputsInline(false);
  1639. this.setPreviousStatement(true);
  1640. this.setNextStatement(true);
  1641. this.setColour("#5bb2d6");
  1642. var thisBlock = this;
  1643. this.setTooltip(function () {
  1644. var mode = thisBlock.getFieldValue('rect_type');
  1645. var TOOLTIPS = {
  1646. 'fillrect': Blockly.Msg.ai_lcd_drawcirclecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_filled),
  1647. 'rect': Blockly.Msg.ai_lcd_drawcirclecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_stroked)
  1648. };
  1649. return TOOLTIPS[mode];
  1650. });
  1651. this.setHelpUrl('');
  1652. }
  1653. };
  1654. Blockly.Python.ai_lcd_drawcirclecarvas = function (block) {
  1655. var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  1656. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1657. Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
  1658. Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
  1659. Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
  1660. Blockly.Python.definitions_['v831_import_os'] = `import os`
  1661. Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
  1662. def CAMERATYPE():
  1663. global cameraSize
  1664. try:
  1665. if os.path.exists("/etc/cameraSize.cfg"):
  1666. cameraSize = True
  1667. else:
  1668. cameraSize = False
  1669. except:
  1670. cameraSize = False
  1671. CAMERATYPE()
  1672. `
  1673. Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf")
  1674. if cameraSize==True:
  1675. camera.camera.config(size=(320,240))
  1676. else:
  1677. camera.camera.config(size=(240,320))
  1678. try:
  1679. if ScreenOrientation==True:
  1680. canvas = image.new(size = (240, 320))
  1681. else:
  1682. canvas = image.new(size = (320, 240))
  1683. except:
  1684. canvas = image.new(size = (320, 240))
  1685. ScreenOrientation = False
  1686. `
  1687. if (color.charAt(0) == '#') {
  1688. var d = 0,
  1689. e = 0,
  1690. f = 0;
  1691. try {
  1692. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1693. e = parseInt(color.substring(3, 5), 16),
  1694. f = parseInt(color.substring(5, 7), 16))
  1695. } catch (g) { }
  1696. var type = block.getFieldValue('rect_type') == "fillrect" ? "-1" : "1";
  1697. var th = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
  1698. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1699. var th0 = Blockly.Python.valueToCode(block, 'Scale_0', Blockly.Python.ORDER_ATOMIC);
  1700. var _code = "canvas.draw_circle(" + xy + ", " + th + ", color=(" + d + ", " + e + ", " + f + "), thickness=" + type + ")\n";
  1701. } else if (color.charAt(0) != '#') {
  1702. var d = 0,
  1703. e = 0,
  1704. f = 0;
  1705. try {
  1706. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1707. e = parseInt(color.substring(3, 5), 16),
  1708. f = parseInt(color.substring(5, 7), 16))
  1709. } catch (g) { }
  1710. var type = block.getFieldValue('rect_type') == "fillrect" ? "-1" : "1";
  1711. var th = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
  1712. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1713. var th0 = Blockly.Python.valueToCode(block, 'Scale_0', Blockly.Python.ORDER_ATOMIC);
  1714. var _code = "canvas.draw_circle(" + xy + ", " + th + ", color=" + color + ", thickness=" + type + ")\n";
  1715. }
  1716. return _code;
  1717. }
  1718. Blockly.Blocks['ai_lcd_draw_image_on_canvas'] = {
  1719. init: function () {
  1720. this.appendDummyInput()
  1721. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_image.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  1722. this.appendDummyInput()
  1723. .appendField(Blockly.Msg.image_process_text_on_canvas + Blockly.Msg.image_process_draw_image_title);
  1724. // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1725. // .appendField();
  1726. this.appendValueInput("image_path")
  1727. .setCheck(null)
  1728. .appendField(Blockly.Msg.image_process_draw_sensor_image_path);
  1729. this.appendValueInput("scale_y")
  1730. .setCheck(null)
  1731. .appendField(Blockly.Msg.OLCD_COORDINATE);
  1732. this.appendValueInput("alpha")
  1733. .setCheck(null)
  1734. .appendField(Blockly.Msg.image_process_draw_image_alpha);
  1735. this.setInputsInline(false);
  1736. this.setPreviousStatement(true, null);
  1737. this.setNextStatement(true, null);
  1738. this.setColour("#5bb2d6");
  1739. this.setTooltip(Blockly.Msg.ai_lcd_draw_image_on_canvas_TOOLTIP);
  1740. this.setHelpUrl("");
  1741. }
  1742. };
  1743. Blockly.Python['ai_lcd_draw_image_on_canvas'] = function (block) {
  1744. var value_image_path = Blockly.Python.valueToCode(block, 'image_path', Blockly.Python.ORDER_ATOMIC);
  1745. var value_scale_y = Blockly.Python.valueToCode(block, 'scale_y', Blockly.Python.ORDER_ATOMIC);
  1746. var alpha = Blockly.Python.valueToCode(block, 'alpha', Blockly.Python.ORDER_ATOMIC);
  1747. Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
  1748. Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
  1749. Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
  1750. Blockly.Python.definitions_['v831_import_os'] = `import os`
  1751. Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
  1752. def CAMERATYPE():
  1753. global cameraSize
  1754. try:
  1755. if os.path.exists("/etc/cameraSize.cfg"):
  1756. cameraSize = True
  1757. else:
  1758. cameraSize = False
  1759. except:
  1760. cameraSize = False
  1761. CAMERATYPE()
  1762. `
  1763. Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf")
  1764. if cameraSize==True:
  1765. camera.camera.config(size=(320,240))
  1766. else:
  1767. camera.camera.config(size=(240,320))
  1768. try:
  1769. if ScreenOrientation==True:
  1770. canvas = image.new(size = (240, 320))
  1771. else:
  1772. canvas = image.new(size = (320, 240))
  1773. except:
  1774. canvas = image.new(size = (320, 240))
  1775. ScreenOrientation = False
  1776. `
  1777. // let alpha = Blockly.Python.valueToCode(block, 'alpha', Blockly.Python.ORDER_ATOMIC)
  1778. // TODO: Assemble Python into code variable.
  1779. var code = 'canvas.draw_image(' + value_image_path + ',' + value_scale_y + ',alpha=' + alpha + ')\n';
  1780. return code;
  1781. };
  1782. Blockly.Blocks['v831_img_save'] = {
  1783. init: function () {
  1784. this.appendValueInput("save_path")
  1785. .setCheck(null)
  1786. .appendField(Blockly.Msg.image_process_text_let_canvas)
  1787. // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1788. .appendField(Blockly.Msg.image_process_img_save)
  1789. // .appendField(new Blockly.FieldDropdown([
  1790. // [Blockly.Msg.display_draw_vertical, "0", "img"],
  1791. // [Blockly.Msg.display_draw_horizontal, "1", "img1"]
  1792. // ]), "invert");
  1793. this.setInputsInline(false);
  1794. this.setPreviousStatement(true, null);
  1795. this.setNextStatement(true, null);
  1796. this.setColour("#f0983e");
  1797. this.setTooltip(Blockly.Msg.ai_img_save_TOOLTIP);
  1798. this.setHelpUrl("");
  1799. }
  1800. };
  1801. Blockly.Python['v831_img_save'] = function (block) {
  1802. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1803. var save_path_location = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC);
  1804. // let invert = block.getFieldValue('invert');
  1805. // console.log(document.getElementById("img").value, invert)
  1806. var code = 'canvas.save("/root/user/img/' + save_path_location.slice(1, -1) + '.jpg")\n';
  1807. if (save_path_location[0] != '"') {
  1808. code = 'canvas.save(' + save_path_location + ')\n';
  1809. }
  1810. return code;
  1811. };
  1812. Blockly.Blocks.v831_img_text = {
  1813. init: function () {
  1814. this.appendValueInput("save_path")
  1815. .setCheck(null)
  1816. .appendField(Blockly.Msg.read_img_path_to)
  1817. this.setOutput(true, null);
  1818. this.setColour("#f0983e");
  1819. this.setTooltip(Blockly.Msg.read_img_path_to);
  1820. this.setHelpUrl("");
  1821. }
  1822. };
  1823. Blockly.Python.v831_img_text = function (block) {
  1824. var save_path_location = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC);
  1825. var code = 'image.open(' + save_path_location + ')';
  1826. return [code,Blockly.Python.ORDER_NONE];
  1827. }
  1828. Blockly.Blocks['v831_img_open'] = {
  1829. init: function () {
  1830. this.appendValueInput("save_path")
  1831. .setCheck(null)
  1832. .appendField(Blockly.Msg.read_img_path_to)
  1833. // .appendField(Blockly.Msg.image_process_img_save);
  1834. // this.appendDummyInput()
  1835. // .appendField(Blockly.Msg.image_process_img_save_quality)
  1836. // .appendField(new Blockly.FieldNumber(90, 0, 100), "compression")
  1837. // .appendField("%");
  1838. // this.setInputsInline(false);
  1839. this.setNextStatement(true, null);
  1840. this.setPreviousStatement(true, null);
  1841. this.setColour("#f0983e");
  1842. this.setTooltip(Blockly.Msg.read_img_path_to);
  1843. this.setHelpUrl("");
  1844. }
  1845. };
  1846. Blockly.Python['v831_img_open'] = function (block) {
  1847. var save_path_location = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC);
  1848. var code = 'canvas = image.open(' + save_path_location + ')\n';
  1849. return code;
  1850. };
  1851. // 翻转
  1852. Blockly.Blocks['v831_lcd_invert'] = {
  1853. init: function () {
  1854. this.appendDummyInput()
  1855. .appendField(Blockly.Msg.image_process_text_let_canvas + Blockly.Msg.image_process_text_image_canvas)
  1856. // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1857. // .appendField()
  1858. .appendField(Blockly.Msg.image_process_pixtovec_text_first)
  1859. .appendField(new Blockly.FieldDropdown([
  1860. [Blockly.Msg.display_draw_vertical, "0"],
  1861. [Blockly.Msg.display_draw_horizontal, "1"]
  1862. ]), "invert")
  1863. .appendField(Blockly.Msg.MAIXDUINO_DISPLAY_ORIENTATION_ROTATE);
  1864. this.setNextStatement(true, null);
  1865. this.setPreviousStatement(true, null);
  1866. this.setColour("#f0983e");
  1867. // this.setTooltip(Blockly.Msg.ai_lcd_invert_color_TOOLTIP);
  1868. this.setHelpUrl("");
  1869. }
  1870. };
  1871. Blockly.Python['v831_lcd_invert'] = function (block) {
  1872. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1873. let invert = block.getFieldValue('invert');
  1874. // TODO: Assemble Python into code variable.
  1875. var code = `canvas = canvas.flip(${invert})\n`
  1876. // TODO: Change ORDER_NONE to the correct strength.
  1877. return code;
  1878. };
  1879. // 旋转
  1880. Blockly.Blocks['v831_lcd_rotating'] = {
  1881. init: function () {
  1882. this.appendValueInput('spend')
  1883. .setCheck(null)
  1884. .appendField(Blockly.Msg.image_process_text_let_canvas + Blockly.Msg.image_process_text_image_canvas)
  1885. // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1886. // .appendField()
  1887. .appendField(Blockly.Msg.image_process_pixtovec_text_first)
  1888. .appendField(new Blockly.FieldDropdown([
  1889. [Blockly.Msg.x_motor_cw_ai, "0"],
  1890. [Blockly.Msg.x_motor_acw_ai, "1"]
  1891. ]), "rotating")
  1892. .appendField(Blockly.Msg.x_motor_set_motor_turns_ai);
  1893. this.appendDummyInput().appendField(Blockly.Msg.robot_dog_ag);
  1894. this.setNextStatement(true, null);
  1895. this.setPreviousStatement(true, null);
  1896. this.setColour("#f0983e");
  1897. this.setTooltip(Blockly.Msg.ai_lcd_invert_color_TOOLTIP);
  1898. this.setHelpUrl("");
  1899. }
  1900. };
  1901. Blockly.Python['v831_lcd_rotating'] = function (block) {
  1902. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1903. let rotating = block.getFieldValue('rotating');
  1904. let spend = (rotating != 0 ? '+' : '-') + Blockly.Python.valueToCode(block, 'spend', Blockly.Python.ORDER_ATOMIC);
  1905. // TODO: Assemble Python into code variable.
  1906. // Blockly.Python.definitions_['lcd_invert_init'] = `def lcdRotation(inputImg,rotationAngle):
  1907. // from maix import image
  1908. // imgRotationAim = image.new(size = (320, 240),color=(0,0,0))
  1909. // imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
  1910. // return imgRotationAim.draw_image(imageRotationBuffer.rotate(rotationAngle, adjust=1),0,0,alpha=1)
  1911. // `
  1912. // console.log(rotating,spend)
  1913. var code = `canvas = canvas.rotate(${spend}, adjust=1)\n`
  1914. // variable_name+'.rotate('+ spend +', adjust=1)';
  1915. // TODO: Change ORDER_NONE to the correct strength.
  1916. return code;
  1917. };
  1918. Blockly.Blocks['ai_lcd_invert_color'] = {
  1919. init: function () {
  1920. this.appendDummyInput()
  1921. .appendField(Blockly.Msg.image_process_text_let_canvas + Blockly.Msg.image_process_color_invert)
  1922. // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1923. // .appendField();
  1924. this.setOutput(true, null);
  1925. this.setColour("#f0983e");
  1926. this.setTooltip(Blockly.Msg.ai_lcd_invert_color_TOOLTIP);
  1927. this.setHelpUrl("");
  1928. }
  1929. };
  1930. Blockly.Python['ai_lcd_invert_color'] = function (block) {
  1931. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1932. // TODO: Assemble Python into code variable.
  1933. var code = 'canvas.invert()';
  1934. // TODO: Change ORDER_NONE to the correct strength.
  1935. return [code, Blockly.Python.ORDER_NONE];
  1936. };
  1937. Blockly.Blocks['v831_lcd_resizecanvas'] = {
  1938. init: function () {
  1939. this.appendDummyInput()
  1940. .appendField(Blockly.Msg.image_process_text_let_canvas + Blockly.Msg.image_process_text_image_canvas)
  1941. // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1942. // .appendField()
  1943. .appendField(Blockly.Msg.image_process_resize_to);
  1944. this.appendValueInput("wh")
  1945. .setCheck(null);
  1946. this.setInputsInline(true);
  1947. this.setNextStatement(true, null);
  1948. this.setPreviousStatement(true, null);
  1949. this.setColour("#f0983e");
  1950. this.setTooltip(Blockly.Msg.ai_lcd_resizecanvas_TOOLTIP);
  1951. this.setHelpUrl("");
  1952. }
  1953. };
  1954. Blockly.Python['v831_lcd_resizecanvas'] = function (block) {
  1955. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1956. var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  1957. // TODO: Assemble Python into code variable.
  1958. // Blockly.Python.definitions_['lcd_invert_init'] = `CANVASINVERT = image.new(size = (240, 320), color = (0,0,0), mode = 'RGB')
  1959. // `
  1960. // var code = `CANVASINVERT.draw_image(${variable_name}.crop(0, 0, 240, 320).resize(${wh}),0,0,alpha=1)`
  1961. // variable_name + '.resize(' + wh + ')';
  1962. // TODO: Change ORDER_NONE to the correct strength.
  1963. var code = `canvas = canvas.resize(${wh}, padding = 0)\n`
  1964. return code;
  1965. };
  1966. Blockly.Blocks['ai_lcd_color_scheme'] = {
  1967. init: function () {
  1968. this.appendDummyInput()
  1969. .appendField(Blockly.Msg.image_process_text_let_canvas)
  1970. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1971. .appendField(Blockly.Msg.image_process_color_scheme_convert)
  1972. .appendField(new Blockly.FieldDropdown([
  1973. [Blockly.Msg.image_process_color_scheme_bw, "to_grayscale(1)"],
  1974. [Blockly.Msg.image_process_color_scheme_rgb, "to_rgb565(1)"]
  1975. ]), "color_scheme");
  1976. this.setOutput(true, null);
  1977. this.setColour("#f0983e");
  1978. var thisBlock = this;
  1979. this.setTooltip(function () {
  1980. var mode = thisBlock.getFieldValue('color_scheme');
  1981. var TOOLTIPS = {
  1982. 'to_grayscale(1)': Blockly.Msg.ai_lcd_color_scheme_TOOLTIP.replace('%1', Blockly.Msg.image_process_color_scheme_bw),
  1983. 'to_rgb565(1)': Blockly.Msg.ai_lcd_color_scheme_TOOLTIP.replace('%1', Blockly.Msg.image_process_color_scheme_rgb)
  1984. };
  1985. return TOOLTIPS[mode];
  1986. });
  1987. this.setHelpUrl("");
  1988. }
  1989. };
  1990. Blockly.Python['ai_lcd_color_scheme'] = function (block) {
  1991. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1992. var dropdown_vari = block.getFieldValue('color_scheme');
  1993. // TODO: Assemble Python into code variable.
  1994. var code = variable_name + '.' + dropdown_vari;
  1995. // TODO: Change ORDER_NONE to the correct strength.
  1996. return [code, Blockly.Python.ORDER_NONE];
  1997. };
  1998. Blockly.Blocks['ai_lcd_ai_pix'] = {
  1999. init: function () {
  2000. this.appendDummyInput()
  2001. .appendField(Blockly.Msg.image_process_text_let_canvas)
  2002. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  2003. .appendField(Blockly.Msg.image_process_pixtovec_text_first)
  2004. .appendField(new Blockly.FieldDropdown([
  2005. [Blockly.Msg.image_process_pixtovec_v2p, ".ai_to_pix()"],
  2006. [Blockly.Msg.image_process_pixtovec_p2v, ".pix_to_ai()"]
  2007. ]), "ai_pix_type")
  2008. .appendField(Blockly.Msg.image_process_pixtovec_conversion);
  2009. this.setInputsInline(false);
  2010. this.setPreviousStatement(true, null);
  2011. this.setNextStatement(true, null);
  2012. this.setColour("#f0983e");
  2013. this.setTooltip("");
  2014. this.setHelpUrl("");
  2015. }
  2016. };
  2017. Blockly.Python['ai_lcd_ai_pix'] = function (block) {
  2018. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2019. var dropdown_vari = block.getFieldValue('ai_pix_type');
  2020. // TODO: Assemble Python into code variable.
  2021. var code = 'a = ' + variable_name + dropdown_vari + '\n';
  2022. // TODO: Change ORDER_NONE to the correct strength.
  2023. return code;
  2024. };
  2025. Blockly.Blocks['v831_lcd_img_cut'] = {
  2026. init: function () {
  2027. this.appendDummyInput()
  2028. .appendField(Blockly.Msg.image_process_text_let_canvas + Blockly.Msg.image_process_text_image_canvas + Blockly.Msg.image_process_imgcut_cutting)
  2029. // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  2030. // .appendField()
  2031. // .appendField();
  2032. this.appendValueInput("xy")
  2033. .setCheck(null)
  2034. .appendField(Blockly.Msg.image_process_imgcut_start_coord);
  2035. this.appendValueInput("wh")
  2036. .setCheck(null)
  2037. .appendField(Blockly.Msg.image_process_imgcut_size);
  2038. this.setInputsInline(false);
  2039. this.setNextStatement(true, null);
  2040. this.setPreviousStatement(true, null)
  2041. this.setColour("#f0983e");
  2042. this.setTooltip(Blockly.Msg.ai_lcd_img_cut_TOOLTIP);
  2043. this.setHelpUrl("");
  2044. }
  2045. };
  2046. Blockly.Python['v831_lcd_img_cut'] = function (block) {
  2047. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2048. var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  2049. var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  2050. // TODO: Assemble Python into code variable.
  2051. // TODO: Change ORDER_NONE to the correct strength.
  2052. var code = `canvas = canvas.crop(${xy},${wh})\n`;
  2053. return code;
  2054. };
  2055. Blockly.Blocks['ai_vision_get_statistics'] = {
  2056. init: function () {
  2057. this.appendDummyInput()
  2058. .appendField(Blockly.Msg.image_process_get_statistics_to_canvas)
  2059. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  2060. .appendField(Blockly.Msg.image_process_get_statistics_get_analysis);
  2061. this.appendValueInput("xy")
  2062. .setCheck(null)
  2063. .appendField(Blockly.Msg.image_process_get_statistics_start_coord);
  2064. this.appendValueInput("wh")
  2065. .setCheck(null)
  2066. .appendField(Blockly.Msg.image_process_get_statistics_size);
  2067. this.appendValueInput("bins")
  2068. .setCheck(null)
  2069. .appendField(Blockly.Msg.image_process_get_statistics_boxes);
  2070. this.setInputsInline(false);
  2071. this.setOutput(true, null);
  2072. this.setColour("#f0983e");
  2073. this.setTooltip(Blockly.Msg.ai_vision_get_statistics_TOOLTIP);
  2074. this.setHelpUrl("");
  2075. }
  2076. };
  2077. Blockly.Python['ai_vision_get_statistics'] = function (block) {
  2078. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2079. var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  2080. var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  2081. var bins = Blockly.Python.valueToCode(block, 'bins', Blockly.Python.ORDER_ATOMIC);
  2082. // TODO: Assemble Python into code variable.
  2083. var code = variable_name + '.get_statistics(bins=' + bins + ',roi=(' + xy + ',' + wh + '))';
  2084. // TODO: Change ORDER_NONE to the correct strength.
  2085. return [code, Blockly.Python.ORDER_NONE];
  2086. };
  2087. Blockly.Blocks['ai_vision_get_histogram'] = {
  2088. init: function () {
  2089. this.appendDummyInput()
  2090. .appendField(Blockly.Msg.ai_vision_get_histogram_get)
  2091. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  2092. .appendField(Blockly.Msg.ai_vision_get_histogram_compute);
  2093. this.appendDummyInput()
  2094. .appendField(Blockly.Msg.ai_vision_get_histogram_region);
  2095. this.appendValueInput("xy")
  2096. .setCheck(null)
  2097. .appendField(Blockly.Msg.ai_vision_get_histogram_region_xy);
  2098. this.appendValueInput("wh")
  2099. .setCheck(null)
  2100. .appendField(Blockly.Msg.ai_vision_get_histogram_region_wh);
  2101. this.setInputsInline(false);
  2102. this.setOutput(true, null);
  2103. this.setColour("#f0983e");
  2104. this.setTooltip(Blockly.Msg.ai_vision_get_histogram_TOOLTIP);
  2105. this.setHelpUrl("");
  2106. }
  2107. };
  2108. Blockly.Python['ai_vision_get_histogram'] = function (block) {
  2109. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2110. var value_xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  2111. var value_wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  2112. // TODO: Assemble Python into code variable.
  2113. var code = variable_name + '.get_histogram(roi=(' + value_xy + ',' + value_wh + '))';
  2114. // TODO: Change ORDER_NONE to the correct strength.
  2115. return [code, Blockly.Python.ORDER_NONE];
  2116. };
  2117. Blockly.Blocks['ai_vision_get_histogram_percentile'] = {
  2118. init: function () {
  2119. this.appendDummyInput()
  2120. .appendField(Blockly.Msg.ai_vision_get_histogram_details_1)
  2121. .appendField(new Blockly.FieldVariable("hist"), "varitem")
  2122. .appendField(Blockly.Msg.ai_vision_get_histogram_details_get);
  2123. this.appendValueInput("perc")
  2124. .setCheck(null);
  2125. this.setInputsInline(true);
  2126. this.setOutput(true, null);
  2127. this.setColour("#f0983e");
  2128. this.setTooltip(Blockly.Msg.ai_vision_get_histogram_percentile_TOOLTIP);
  2129. this.setHelpUrl("https://docs.openmv.io/library/omv.image.html#id3");
  2130. }
  2131. };
  2132. Blockly.Python['ai_vision_get_histogram_percentile'] = function (block) {
  2133. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2134. var value_perc = Blockly.Python.valueToCode(block, 'perc', Blockly.Python.ORDER_ATOMIC);
  2135. // TODO: Assemble Python into code variable.
  2136. var code = variable_name + '.get_percentile(' + value_perc + ')';
  2137. // TODO: Change ORDER_NONE to the correct strength.
  2138. return [code, Blockly.Python.ORDER_NONE];
  2139. };
  2140. Blockly.Blocks['ai_vision_get_histogram_percentile_detail'] = {
  2141. init: function () {
  2142. this.appendDummyInput()
  2143. .appendField(Blockly.Msg.ai_vision_get_histogram_percentile_1)
  2144. .appendField(new Blockly.FieldVariable("percentile"), "varitem");
  2145. this.appendDummyInput()
  2146. .appendField(Blockly.Msg.ai_vision_get_histogram_percentile_2)
  2147. .appendField(new Blockly.FieldDropdown([
  2148. [Blockly.Msg.ai_vision_get_histogram_percentile_3, "value()"],
  2149. [Blockly.Msg.ai_vision_get_histogram_percentile_4, "l_value()"],
  2150. [Blockly.Msg.ai_vision_get_histogram_percentile_5, "a_value()"],
  2151. [Blockly.Msg.ai_vision_get_histogram_percentile_6, "b_value()"]
  2152. ]), "option");
  2153. this.setInputsInline(false);
  2154. this.setOutput(true, null);
  2155. this.setColour("#f0983e");
  2156. var thisBlock = this;
  2157. this.setTooltip(function () {
  2158. var mode = thisBlock.getFieldValue('option');
  2159. var TOOLTIPS = {
  2160. 'value()': Blockly.Msg.ai_vision_get_histogram_percentile_detail_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_get_histogram_percentile_3),
  2161. 'l_value()': Blockly.Msg.ai_vision_get_histogram_percentile_detail_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_get_histogram_percentile_4),
  2162. 'a_value()': Blockly.Msg.ai_vision_get_histogram_percentile_detail_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_get_histogram_percentile_5),
  2163. 'b_value()': Blockly.Msg.ai_vision_get_histogram_percentile_detail_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_get_histogram_percentile_6)
  2164. };
  2165. return TOOLTIPS[mode];
  2166. });
  2167. this.setHelpUrl("https://docs.openmv.io/library/omv.image.html#id3");
  2168. }
  2169. };
  2170. Blockly.Python['ai_vision_get_histogram_percentile_detail'] = function (block) {
  2171. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2172. var dropdown_option = block.getFieldValue('option');
  2173. var code = variable_name + '.' + dropdown_option;
  2174. // TODO: Change ORDER_NONE to the correct strength.
  2175. return [code, Blockly.Python.ORDER_NONE];
  2176. };
  2177. Blockly.Blocks['ai_vision_lab_rgb_conversion'] = {
  2178. init: function () {
  2179. this.appendDummyInput()
  2180. .appendField(Blockly.Msg.image_process_lab_rgb_conversion_exec)
  2181. .appendField(new Blockly.FieldDropdown([
  2182. [Blockly.Msg.image_process_lab_rgb_conversion_torgb, "lab_to_rgb"],
  2183. [Blockly.Msg.image_process_lab_rgb_conversion_tolab, "rgb_to_lab"]
  2184. ]), "rgblab");
  2185. this.appendValueInput("color_tuple")
  2186. .setCheck(null)
  2187. .appendField(Blockly.Msg.image_process_lab_rgb_conversion_tuple);
  2188. this.setOutput(true, null);
  2189. this.setColour("#f0983e");
  2190. var thisBlock = this;
  2191. this.setTooltip(function () {
  2192. var mode = thisBlock.getFieldValue('rgblab');
  2193. var TOOLTIPS = {
  2194. 'lab_to_rgb': Blockly.Msg.ai_vision_lab_rgb_conversion_TOOLTIP.replace('%1', Blockly.Msg.image_process_lab_rgb_conversion_torgb),
  2195. 'rgb_to_lab': Blockly.Msg.ai_vision_lab_rgb_conversion_TOOLTIP.replace('%1', Blockly.Msg.image_process_lab_rgb_conversion_tolab)
  2196. };
  2197. return TOOLTIPS[mode];
  2198. });
  2199. this.setHelpUrl("");
  2200. }
  2201. };
  2202. Blockly.Python['ai_vision_lab_rgb_conversion'] = function (block) {
  2203. var type = block.getFieldValue('rgblab');
  2204. var tuple = Blockly.Python.valueToCode(block, 'color_tuple', Blockly.Python.ORDER_ATOMIC);
  2205. // TODO: Assemble Python into code variable.
  2206. var code = 'image.' + type + '(' + tuple + ')';
  2207. // TODO: Change ORDER_NONE to the correct strength.
  2208. return [code, Blockly.Python.ORDER_NONE];
  2209. };
  2210. Blockly.Blocks['ai_vision_rgb_grayscale_conversion'] = {
  2211. init: function () {
  2212. this.appendDummyInput()
  2213. .appendField(Blockly.Msg.image_process_rgb_grayscale_conversion_exec)
  2214. .appendField(new Blockly.FieldDropdown([
  2215. [Blockly.Msg.image_process_rgb_grayscale_conversion_torgb, "grayscale_to_rgb"],
  2216. [Blockly.Msg.image_process_rgb_grayscale_conversion_togray, "rgb_to_grayscale"]
  2217. ]), "rgb_g");
  2218. this.appendValueInput("color_tuple")
  2219. .setCheck(null)
  2220. .appendField(Blockly.Msg.image_process_rgb_grayscale_conversion_set);
  2221. this.setOutput(true, null);
  2222. this.setColour("#f0983e");
  2223. var thisBlock = this;
  2224. this.setTooltip(function () {
  2225. var mode = thisBlock.getFieldValue('rgb_g');
  2226. var TOOLTIPS = {
  2227. 'grayscale_to_rgb': Blockly.Msg.ai_vision_rgb_grayscale_conversion_TOOLTIP.replace('%1', Blockly.Msg.image_process_rgb_grayscale_conversion_torgb),
  2228. 'rgb_to_grayscale': Blockly.Msg.ai_vision_rgb_grayscale_conversion_TOOLTIP.replace('%1', Blockly.Msg.image_process_rgb_grayscale_conversion_togray)
  2229. };
  2230. return TOOLTIPS[mode];
  2231. });
  2232. this.setHelpUrl("");
  2233. }
  2234. };
  2235. Blockly.Python['ai_vision_rgb_grayscale_conversion'] = function (block) {
  2236. var type = block.getFieldValue('rgb_g');
  2237. var tuple = Blockly.Python.valueToCode(block, 'color_tuple', Blockly.Python.ORDER_ATOMIC);
  2238. Blockly.Python.addVariable('rgb_tuple', "rgb_tuple = None", true);
  2239. // TODO: Assemble Python into code variable.
  2240. var code = 'image.' + type + '(' + tuple + ')';
  2241. // TODO: Change ORDER_NONE to the correct strength.
  2242. return [code, Blockly.Python.ORDER_NONE];
  2243. };
  2244. /*
  2245. _ ___ ____
  2246. / \ |_ _| / ___|__ _ _ __ ___ ___ _ __ __ _
  2247. / _ \ | | | | / _` | '_ ` _ \ / _ \ '__/ _` |
  2248. / ___ \ | | | |__| (_| | | | | | | __/ | | (_| |
  2249. /_/ \_\___| \____\__,_|_| |_| |_|\___|_| \__,_|
  2250. */
  2251. Blockly.Blocks.ai_camera_wh = {
  2252. init: function () {
  2253. var _input = this.appendDummyInput();
  2254. this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL);
  2255. this.setColour("#60c1bb");
  2256. this.setOutput(!0, "Boolean");
  2257. _input.appendField(Blockly.Msg.W);
  2258. this.appendValueInput("A").setCheck("Number");
  2259. _input = this.appendDummyInput();
  2260. _input.appendField(Blockly.Msg.H)
  2261. this.appendValueInput("B").setCheck("Number");
  2262. this.setInputsInline(!0);
  2263. }
  2264. };
  2265. Blockly.Python.ai_camera_wh = function (block) {
  2266. var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
  2267. var _y = Blockly.Python.valueToCode(block, "B", Blockly.Python.ORDER_ATOMIC);
  2268. var code = "" + _x + ", " + _y + "";
  2269. return [code, Blockly.Python.ORDER_ATOMIC];
  2270. };
  2271. Blockly.Blocks['ai_camera_init'] = {
  2272. init: function () {
  2273. this.appendDummyInput()
  2274. .appendField(new Blockly.FieldImage("blockly/media/camera_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  2275. this.appendDummyInput()
  2276. .appendField(Blockly.Msg.ai_camera_camera_init);
  2277. // this.appendDummyInput()
  2278. // .appendField(Blockly.Msg.ai_camera_camera_set_size)
  2279. // .appendField(new Blockly.FieldDropdown([
  2280. // ["QVGA (320*240)", "QVGA"],
  2281. // ["QQVGA (160*120)", "QQVGA"]
  2282. // ]), "DEGREE");
  2283. // this.appendDummyInput()
  2284. // .appendField(Blockly.Msg.ai_camera_camera_color_mode)
  2285. // .appendField(new Blockly.FieldDropdown([
  2286. // [Blockly.Msg.ai_camera_camera_color_mode_rgb, "RGB565"],
  2287. // [Blockly.Msg.ai_camera_camera_color_mode_bw, "GRAYSCALE"]
  2288. // ]), "DEGREE1");
  2289. this.setPreviousStatement(true, null);
  2290. this.setNextStatement(true, null);
  2291. this.setColour("#60c1bb");
  2292. this.setTooltip(Blockly.Msg.ai_camera_init_TOOLTIP);
  2293. this.setHelpUrl('');
  2294. }
  2295. };
  2296. Blockly.Python.ai_camera_init = function (block) {
  2297. Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`
  2298. Blockly.Python.definitions_['v831_import_os'] = `import os`
  2299. Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
  2300. def CAMERATYPE():
  2301. global cameraSize
  2302. try:
  2303. if os.path.exists("/etc/cameraSize.cfg"):
  2304. cameraSize = True
  2305. else:
  2306. cameraSize = False
  2307. except:
  2308. cameraSize = False
  2309. CAMERATYPE()
  2310. `
  2311. Blockly.Python.addVariable("SETVFLIP", "SETVFLIP = False", true)
  2312. Blockly.Python.addVariable("SETHMIRROT", "SETHMIRROT = False", true)
  2313. var _code = ``;
  2314. return _code;
  2315. }
  2316. Blockly.Blocks['ai_camera_windows'] = {
  2317. init: function () {
  2318. this.appendDummyInput()
  2319. .appendField(Blockly.Msg.ai_camera_windowing_resize);
  2320. this.appendDummyInput()
  2321. .appendField(Blockly.Msg.ai_camera_windowing_w)
  2322. .appendField(new Blockly.FieldNumber(240), "window_w")
  2323. .appendField(Blockly.Msg.ai_camera_windowing_h)
  2324. .appendField(new Blockly.FieldNumber(320), "window_h")
  2325. // .appendField(Blockly.Msg.ai_camera_windowing_unit);
  2326. this.setPreviousStatement(true, null);
  2327. this.setNextStatement(true, null);
  2328. this.setColour("#60c1bb");
  2329. this.setTooltip(Blockly.Msg.ai_camera_windows_TOOLTIP);
  2330. this.setHelpUrl("");
  2331. }
  2332. };
  2333. Blockly.Python['ai_camera_windows'] = function (block) {
  2334. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2335. var w = block.getFieldValue('window_w');
  2336. var h = block.getFieldValue('window_h');
  2337. // var code = 'sensor.set_windowing((' + w + ',' + h + '))\n';
  2338. var code = 'camera.camera.config(size=(' + w + ',' + h + '))\n';
  2339. return code;
  2340. };
  2341. Blockly.Blocks['ai_camera_fit_to_screen_size'] = {
  2342. init: function () {
  2343. this.appendDummyInput()
  2344. .appendField(Blockly.Msg.ai_camera_camera_fit_set + Blockly.Msg.ai_camera_camera_fit_to)
  2345. .appendField(new Blockly.FieldDropdown([
  2346. ["320*240", "320"],
  2347. ["224*224", "224"]
  2348. ]), "size");
  2349. this.setInputsInline(true);
  2350. this.setPreviousStatement(true, null);
  2351. this.setNextStatement(true, null);
  2352. this.setColour("#60c1bb");
  2353. this.setTooltip(Blockly.Msg.ai_camera_fit_to_screen_size_TOOLTIP);
  2354. this.setHelpUrl("");
  2355. }
  2356. };
  2357. Blockly.Python['ai_camera_fit_to_screen_size'] = function (block) {
  2358. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2359. var dropdown_size = block.getFieldValue('size');
  2360. Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`
  2361. Blockly.Python.definitions_['v831_import_os'] = `import os`
  2362. Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
  2363. Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
  2364. def CAMERATYPE():
  2365. global cameraSize
  2366. try:
  2367. if os.path.exists("/etc/cameraSize.cfg"):
  2368. cameraSize = True
  2369. else:
  2370. cameraSize = False
  2371. except:
  2372. cameraSize = False
  2373. CAMERATYPE()
  2374. `
  2375. Blockly.Python.definitions_['lcd_invert_init'] = `def lcdRotation(inputImg):
  2376. global SETVFLIP,SETHMIRROT,cameraSize,ScreenOrientation
  2377. imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
  2378. try:
  2379. if ScreenOrientation:
  2380. imgRotationAim = image.new(size = (240, 320))
  2381. rotationAngle = 180
  2382. else:
  2383. imgRotationAim = image.new(size = (320, 240))
  2384. rotationAngle = 90
  2385. except:
  2386. imgRotationAim = image.new(size = (320, 240))
  2387. rotationAngle = 90
  2388. GETROTATION = imageRotationBuffer.rotate(+rotationAngle, adjust=1)
  2389. GETROTATION = imgRotationAim.draw_image(GETROTATION,0,0,alpha=1)
  2390. return GETROTATION
  2391. `
  2392. Blockly.Python.definitions_['lcd_invert_init_new'] = `def lcdRotationNew(inputImg):
  2393. global SETVFLIP,SETHMIRROT,cameraSize,ScreenOrientation
  2394. imageRotationBuffer = inputImg.crop(0, 0, 320, 240)
  2395. try:
  2396. if ScreenOrientation:
  2397. imgRotationAim = image.new(size = (240, 320))
  2398. rotationAngle = 90
  2399. GETROTATION = imageRotationBuffer.rotate(+rotationAngle, adjust=1)
  2400. else:
  2401. imgRotationAim = image.new(size = (320, 240))
  2402. GETROTATION = imageRotationBuffer
  2403. except:
  2404. imgRotationAim = image.new(size = (320, 240))
  2405. GETROTATION = imageRotationBuffer
  2406. GETROTATION = imgRotationAim.draw_image(GETROTATION,0,0,alpha=1)
  2407. return GETROTATION
  2408. `
  2409. Blockly.Python.definitions_['lcd_invert_rotate_camera'] = `def getLcdRotation(cameraCapture):
  2410. global cameraSize
  2411. if cameraSize:
  2412. return lcdRotationNew(cameraCapture)
  2413. else:
  2414. return lcdRotation(cameraCapture)
  2415. `
  2416. // #从摄像头中获取一张图像
  2417. var code = `canvas = getLcdRotation(camera.capture())\n`;
  2418. // TODO: Assemble Python into code variable.
  2419. if (dropdown_size == "224") {
  2420. code = `canvas = getLcdRotation(camera.capture()).crop(0,0,224,224)\n`
  2421. }
  2422. return code;
  2423. };
  2424. Blockly.Blocks['ai_camera_snapshot'] = {
  2425. init: function () {
  2426. this.appendDummyInput()
  2427. .appendField(Blockly.Msg.ai_camera_snapshot);
  2428. this.setOutput(false, null);
  2429. this.setNextStatement(true, null);
  2430. this.setPreviousStatement(true, null);
  2431. this.setColour("#60c1bb");
  2432. this.setTooltip(Blockly.Msg.ai_camera_snapshot_TOOLTIP);
  2433. this.setHelpUrl('');
  2434. }
  2435. };
  2436. Blockly.Python.ai_camera_snapshot = function (block) {
  2437. Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`
  2438. Blockly.Python.definitions_['v831_import_os'] = `import os`
  2439. Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
  2440. Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
  2441. def CAMERATYPE():
  2442. global cameraSize
  2443. try:
  2444. if os.path.exists("/etc/cameraSize.cfg"):
  2445. cameraSize = True
  2446. else:
  2447. cameraSize = False
  2448. except:
  2449. cameraSize = False
  2450. CAMERATYPE()
  2451. `
  2452. Blockly.Python.definitions_['lcd_invert_init_new'] = `def lcdRotationNew(inputImg):
  2453. global SETVFLIP,SETHMIRROT,cameraSize,ScreenOrientation
  2454. imageRotationBuffer = inputImg.crop(0, 0, 320, 240)
  2455. if ScreenOrientation:
  2456. imgRotationAim = image.new(size = (240, 320))
  2457. rotationAngle = 90
  2458. GETROTATION = imageRotationBuffer.rotate(+rotationAngle, adjust=1)
  2459. else:
  2460. imgRotationAim = image.new(size = (320, 240))
  2461. GETROTATION = imageRotationBuffer
  2462. GETROTATION = imgRotationAim.draw_image(GETROTATION,0,0,alpha=1)
  2463. return GETROTATION
  2464. `
  2465. Blockly.Python.addVariable("ScreenOrientation", `ScreenOrientation = False`, true)
  2466. // #从摄像头中获取一张图像
  2467. var _code = `canvas = lcdRotationNew(camera.capture())\n`;
  2468. return _code;
  2469. }
  2470. // 图传
  2471. Blockly.Blocks['v831_camera_graph_transmission'] = {
  2472. init: function () {
  2473. this.appendDummyInput()
  2474. .appendField(Blockly.Msg.v831_transmission_setup_show);
  2475. // this.appendDummyInput()
  2476. // .appendField(Blockly.Msg.v831_transmission_init_setup_source)
  2477. // .appendField(new Blockly.FieldVariable("img_graphTransmission"), "varitem");
  2478. this.setPreviousStatement(true, null);
  2479. this.setNextStatement(true, null);
  2480. this.setColour("#60c1bb");
  2481. this.setTooltip(Blockly.Msg.v831_transmission_setup_show);
  2482. this.setHelpUrl('');
  2483. }
  2484. };
  2485. Blockly.Python.v831_camera_graph_transmission = function (block) {
  2486. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2487. Blockly.Python.definitions_['v831_import_mjpg'] = `from maix import mjpg`
  2488. Blockly.Python.definitions_['v831_import_utils'] = `from maix import utils`
  2489. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  2490. Blockly.Python.definitions_['v831_import_time'] = `import time`
  2491. // #从摄像头中获取一张图像
  2492. var _code = `jpg = utils.rgb2jpg(canvas.convert("RGB").tobytes(), canvas.width, canvas.height)
  2493. img_base64 = base64.b64encode(jpg)
  2494. img_base64_str = "data:image/jpg;base64," + str(img_base64)[2:-1]
  2495. time.sleep(0.1)
  2496. try:
  2497. print(img_base64_str)
  2498. pass
  2499. except Exception as e:
  2500. print(str(e))
  2501. pass
  2502. `;
  2503. return _code
  2504. }
  2505. Blockly.Blocks['v831_camera_internet_transmission'] = {
  2506. init: function () {
  2507. this.appendDummyInput()
  2508. .appendField(Blockly.Msg.v831_internet_transmission_setup_show);
  2509. // this.appendDummyInput()
  2510. // .appendField(Blockly.Msg.v831_transmission_init_setup_source)
  2511. // .appendField(new Blockly.FieldVariable("img_graphTransmission"), "varitem");
  2512. this.setPreviousStatement(true, null);
  2513. this.setNextStatement(true, null);
  2514. this.setColour("#60c1bb");
  2515. this.setTooltip(Blockly.Msg.v831_transmission_setup_show);
  2516. this.setHelpUrl('');
  2517. }
  2518. };
  2519. Blockly.Python.v831_camera_internet_transmission = function (block) {
  2520. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2521. Blockly.Python.definitions_['v831_import_mjpg'] = `from maix import mjpg`
  2522. Blockly.Python.definitions_['v831_import_utils'] = `from maix import utils`
  2523. Blockly.Python.definitions_['v831_import_queue'] = `queue = mjpg.Queue(maxsize=8)
  2524. mjpg.MjpgServerThread("0.0.0.0", 18811, mjpg.BytesImageHandlerFactory(q=queue)).start()`
  2525. // #从摄像头中获取一张图像
  2526. var _code = `jpg = utils.rgb2jpg(canvas.convert("RGB").tobytes(), 320, 240)
  2527. queue.put(mjpg.BytesImage(jpg))
  2528. `;
  2529. return _code
  2530. }
  2531. Blockly.Blocks['ai_camera_lens_corr'] = {
  2532. init: function () {
  2533. this.appendValueInput("lens_corr")
  2534. .setCheck(null)
  2535. .appendField(Blockly.Msg.ai_camera_set_lens_corr);
  2536. this.setInputsInline(true);
  2537. this.setOutput(true, null);
  2538. this.setColour("#60c1bb");
  2539. this.setTooltip(Blockly.Msg.ai_camera_lens_corr_TOOLTIP);
  2540. this.setHelpUrl("");
  2541. }
  2542. };
  2543. Blockly.Python['ai_camera_lens_corr'] = function (block) {
  2544. var value_lens_corr = Blockly.Python.valueToCode(block, 'lens_corr', Blockly.Python.ORDER_ATOMIC);
  2545. // TODO: Assemble Python into code variable.
  2546. var code = value_lens_corr + '.lens_corr(strength = 1.8, zoom = 1.0)';
  2547. // TODO: Change ORDER_NONE to the correct strength.
  2548. return [code, Blockly.Python.ORDER_NONE];
  2549. };
  2550. Blockly.Blocks['ai_camera_image_property_change'] = {
  2551. init: function () {
  2552. this.appendDummyInput()
  2553. .appendField(Blockly.Msg.ai_camera_bcs_set_text_2)
  2554. .appendField(new Blockly.FieldDropdown([
  2555. [Blockly.Msg.ai_camera_bcs_vflip, "set_vflip"],
  2556. [Blockly.Msg.ai_camera_bcs_hmirror, "set_hmirror"],
  2557. // [Blockly.Msg.ai_camera_bcs_wb, "set_auto_whitebal"],
  2558. // [Blockly.Msg.ai_camera_bcs_g, "set_auto_gain"],
  2559. // [Blockly.Msg.ai_camera_bcs_e, "set_auto_exposure"]
  2560. ]), "image_property")
  2561. .appendField(Blockly.Msg.ai_camera_bcs_as_2)
  2562. .appendField(new Blockly.FieldDropdown([
  2563. [Blockly.Msg.ai_camera_enable + Blockly.Msg.ai_camera_bcs_status, "True"],
  2564. [Blockly.Msg.ai_camera_disable + Blockly.Msg.ai_camera_bcs_status, "False"]
  2565. ]), "DEGREE");
  2566. this.setPreviousStatement(true, null);
  2567. this.setNextStatement(true, null);
  2568. this.setColour("#60c1bb");
  2569. var thisBlock = this;
  2570. this.setTooltip(function () {
  2571. var mode = thisBlock.getFieldValue('image_property');
  2572. var TOOLTIPS = {
  2573. 'set_vflip': Blockly.Msg.ai_camera_image_property_change_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_vflip),
  2574. 'set_hmirror': Blockly.Msg.ai_camera_image_property_change_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_hmirror),
  2575. 'set_auto_whitebal': Blockly.Msg.ai_camera_image_property_change_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_wb),
  2576. 'set_auto_gain': Blockly.Msg.ai_camera_image_property_change_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_g),
  2577. 'set_auto_exposure': Blockly.Msg.ai_camera_image_property_change_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_e)
  2578. };
  2579. return TOOLTIPS[mode];
  2580. });
  2581. this.setHelpUrl('');
  2582. }
  2583. };
  2584. Blockly.Python.ai_camera_image_property_change = function (block) {
  2585. var degee = block.getFieldValue('DEGREE');
  2586. var dropdown_image_property = block.getFieldValue('image_property');
  2587. var _code = ``;
  2588. if (dropdown_image_property == "set_vflip") {
  2589. _code = `SETVFLIP = ${degee}
  2590. `
  2591. } else if (dropdown_image_property == "set_hmirror") {
  2592. _code = `SETHMIRROT = ${degee}
  2593. `
  2594. }
  2595. return _code;
  2596. }
  2597. Blockly.Blocks['ai_camera_vflip'] = {
  2598. init: function () {
  2599. this.appendDummyInput()
  2600. .appendField(Blockly.Msg.ai_camera_set_vflip)
  2601. .appendField(new Blockly.FieldDropdown([
  2602. [Blockly.Msg.ai_camera_enable, "True"],
  2603. [Blockly.Msg.ai_camera_disable, "False"]
  2604. ]), "DEGREE")
  2605. this.setPreviousStatement(true, null);
  2606. this.setNextStatement(true, null);
  2607. this.setColour("#60c1bb");
  2608. this.setTooltip('');
  2609. this.setHelpUrl('');
  2610. }
  2611. };
  2612. Blockly.Python.ai_camera_vflip = function (block) {
  2613. var degee = block.getFieldValue('DEGREE');
  2614. var _code = "sensor.set_vflip(" + degee + ")\n";
  2615. return _code;
  2616. }
  2617. Blockly.Blocks['ai_camera_hmirror'] = {
  2618. init: function () {
  2619. this.appendDummyInput()
  2620. .appendField(Blockly.Msg.ai_camera_set_hmirror)
  2621. .appendField(new Blockly.FieldDropdown([
  2622. [Blockly.Msg.ai_camera_enable, "True"],
  2623. [Blockly.Msg.ai_camera_disable, "False"]
  2624. ]), "DEGREE")
  2625. this.setPreviousStatement(true, null);
  2626. this.setNextStatement(true, null);
  2627. this.setColour("#60c1bb");
  2628. this.setTooltip('');
  2629. this.setHelpUrl('');
  2630. }
  2631. };
  2632. Blockly.Python.ai_camera_hmirror = function (block) {
  2633. var degee = block.getFieldValue('DEGREE');
  2634. var _code = "sensor.set_hmirror(" + degee + ")\n"
  2635. return _code;
  2636. }
  2637. Blockly.Blocks['ai_camera_auto_whitebal'] = {
  2638. init: function () {
  2639. this.appendDummyInput()
  2640. .appendField(Blockly.Msg.ai_camera_set_auto_whitebal)
  2641. .appendField(new Blockly.FieldDropdown([
  2642. [Blockly.Msg.ai_camera_enable, "True"],
  2643. [Blockly.Msg.ai_camera_disable, "False"]
  2644. ]), "DEGREE")
  2645. this.setPreviousStatement(true, null);
  2646. this.setNextStatement(true, null);
  2647. this.setColour("#60c1bb");
  2648. this.setTooltip('');
  2649. this.setHelpUrl('');
  2650. }
  2651. };
  2652. Blockly.Python.ai_camera_auto_whitebal = function (block) {
  2653. var degee = block.getFieldValue('DEGREE');
  2654. var _code = "sensor.set_auto_whitebal(" + degee + ")\n"
  2655. return _code;
  2656. }
  2657. Blockly.Blocks['ai_camera_auto_gain'] = {
  2658. init: function () {
  2659. this.appendDummyInput()
  2660. .appendField(Blockly.Msg.ai_camera_set_auto_gain)
  2661. .appendField(new Blockly.FieldDropdown([
  2662. [Blockly.Msg.ai_camera_enable, "True"],
  2663. [Blockly.Msg.ai_camera_disable, "False"]
  2664. ]), "DEGREE")
  2665. this.setPreviousStatement(true, null);
  2666. this.setNextStatement(true, null);
  2667. this.setColour("#60c1bb");
  2668. this.setTooltip('');
  2669. this.setHelpUrl('');
  2670. }
  2671. };
  2672. Blockly.Python.ai_camera_auto_gain = function (block) {
  2673. var degee = block.getFieldValue('DEGREE');
  2674. var _code = "sensor.set_auto_gain(" + degee + ")\n"
  2675. return _code;
  2676. }
  2677. Blockly.Blocks['ai_camera_auto_exposure'] = {
  2678. init: function () {
  2679. this.appendDummyInput()
  2680. .appendField(Blockly.Msg.ai_camera_set_auto_exposure)
  2681. .appendField(new Blockly.FieldDropdown([
  2682. [Blockly.Msg.ai_camera_enable, "True"],
  2683. [Blockly.Msg.ai_camera_disable, "False"]
  2684. ]), "DEGREE")
  2685. this.setPreviousStatement(true, null);
  2686. this.setNextStatement(true, null);
  2687. this.setColour("#60c1bb");
  2688. this.setTooltip('');
  2689. this.setHelpUrl('');
  2690. }
  2691. };
  2692. Blockly.Python.ai_camera_auto_exposure = function (block) {
  2693. var degee = block.getFieldValue('DEGREE');
  2694. var _code = "sensor.set_auto_exposure(" + degee + ")\n"
  2695. return _code;
  2696. }
  2697. Blockly.Blocks['ai_camera_bcs_operation'] = {
  2698. init: function () {
  2699. this.appendDummyInput()
  2700. .appendField(Blockly.Msg.ai_camera_bcs_set_text)
  2701. .appendField(new Blockly.FieldDropdown([
  2702. [Blockly.Msg.ai_camera_bcs_contrast, "contrast"],
  2703. [Blockly.Msg.ai_camera_bcs_brightness, "brightness"],
  2704. [Blockly.Msg.ai_camera_bcs_saturation, "saturation"]
  2705. ]), "image_property")
  2706. .appendField(Blockly.Msg.ai_camera_bcs_as);
  2707. this.appendValueInput("A").setCheck("Number");
  2708. this.appendDummyInput()
  2709. .appendField(Blockly.Msg.ai_camera_set_range);
  2710. this.setPreviousStatement(true, null);
  2711. this.setNextStatement(true, null);
  2712. this.setInputsInline(!0);
  2713. this.setColour("#60c1bb");
  2714. var thisBlock = this;
  2715. this.setTooltip(function () {
  2716. var mode = thisBlock.getFieldValue('image_property');
  2717. var TOOLTIPS = {
  2718. 'contrast': Blockly.Msg.ai_camera_bcs_operation_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_contrast),
  2719. 'brightness': Blockly.Msg.ai_camera_bcs_operation_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_brightness),
  2720. 'saturation': Blockly.Msg.ai_camera_bcs_operation_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_saturation)
  2721. };
  2722. return TOOLTIPS[mode];
  2723. });
  2724. this.setHelpUrl('');
  2725. }
  2726. };
  2727. Blockly.Python.ai_camera_bcs_operation = function (block) {
  2728. var dropdown_image_property = block.getFieldValue('image_property');
  2729. var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
  2730. var _code = "sensor.set_" + dropdown_image_property + "(" + _x + ")\n"
  2731. return _code;
  2732. }
  2733. Blockly.Blocks['ai_camera_contrast'] = {
  2734. init: function () {
  2735. this.appendDummyInput()
  2736. .appendField(Blockly.Msg.ai_camera_set_contrast_to_value);
  2737. this.appendValueInput("A").setCheck("Number");
  2738. this.appendDummyInput()
  2739. .appendField(Blockly.Msg.ai_camera_set_range);
  2740. this.setPreviousStatement(true, null);
  2741. this.setNextStatement(true, null);
  2742. this.setInputsInline(!0);
  2743. this.setColour("#60c1bb");
  2744. this.setTooltip('');
  2745. this.setHelpUrl('');
  2746. }
  2747. };
  2748. Blockly.Python.ai_camera_contrast = function (block) {
  2749. var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
  2750. var _code = "sensor.set_contrast(" + _x + ")\n"
  2751. return _code;
  2752. }
  2753. Blockly.Blocks['ai_camera_brightness'] = {
  2754. init: function () {
  2755. this.appendDummyInput()
  2756. .appendField(Blockly.Msg.ai_camera_set_brightness_to_value);
  2757. this.appendValueInput("A").setCheck("Number");
  2758. this.appendDummyInput()
  2759. .appendField(Blockly.Msg.ai_camera_set_range);
  2760. this.setPreviousStatement(true, null);
  2761. this.setNextStatement(true, null);
  2762. this.setInputsInline(!0);
  2763. this.setColour("#60c1bb");
  2764. this.setTooltip('');
  2765. this.setHelpUrl('');
  2766. }
  2767. };
  2768. Blockly.Python.ai_camera_brightness = function (block) {
  2769. var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
  2770. var _code = "sensor.set_brightness(" + _x + ")\n"
  2771. return _code;
  2772. }
  2773. Blockly.Blocks['ai_camera_saturation'] = {
  2774. init: function () {
  2775. this.appendDummyInput()
  2776. .appendField(Blockly.Msg.ai_camera_set_saturation_value);
  2777. this.appendValueInput("A").setCheck("Number");
  2778. this.appendDummyInput()
  2779. .appendField(Blockly.Msg.ai_camera_set_range);
  2780. this.setPreviousStatement(true, null);
  2781. this.setNextStatement(true, null);
  2782. this.setInputsInline(!0);
  2783. this.setColour("#60c1bb");
  2784. this.setTooltip('');
  2785. this.setHelpUrl('');
  2786. }
  2787. };
  2788. Blockly.Python.ai_camera_saturation = function (block) {
  2789. var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
  2790. var _code = "sensor.set_saturation(" + _x + ")\n"
  2791. return _code;
  2792. }
  2793. /*
  2794. _ ___ __ ___ _
  2795. / \ |_ _| \ \ / (_)___(_) ___ _ __
  2796. / _ \ | | \ \ / /| / __| |/ _ \| '_ \
  2797. / ___ \ | | \ V / | \__ \ | (_) | | | |
  2798. /_/ \_\___| \_/ |_|___/_|\___/|_| |_|
  2799. */
  2800. Blockly.Blocks.ai_lcd_XY_vision = {
  2801. init: function () {
  2802. var _input = this.appendDummyInput();
  2803. this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL);
  2804. this.setColour("#f0983e");
  2805. this.setOutput(!0, "Boolean");
  2806. _input.appendField(Blockly.Msg.X);
  2807. this.appendValueInput("A").setCheck("Number");
  2808. _input = this.appendDummyInput();
  2809. _input.appendField(Blockly.Msg.Y)
  2810. this.appendValueInput("B").setCheck("Number");
  2811. this.setInputsInline(!0);
  2812. }
  2813. };
  2814. Blockly.Python.ai_lcd_XY_vision = function (block) {
  2815. var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
  2816. var _y = Blockly.Python.valueToCode(block, "B", Blockly.Python.ORDER_ATOMIC);
  2817. var code = "" + _x + ", " + _y + "";
  2818. return [code, Blockly.Python.ORDER_ATOMIC];
  2819. };
  2820. Blockly.Blocks.ai_lcd_WH_vision = {
  2821. init: function () {
  2822. var _input = this.appendDummyInput();
  2823. this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL);
  2824. this.setColour("#f0983e");
  2825. this.setOutput(!0, "Boolean");
  2826. _input.appendField(Blockly.Msg.W);
  2827. this.appendValueInput("A").setCheck("Number");
  2828. _input = this.appendDummyInput();
  2829. _input.appendField(Blockly.Msg.H)
  2830. this.appendValueInput("B").setCheck("Number");
  2831. this.setInputsInline(!0);
  2832. }
  2833. };
  2834. Blockly.Python.ai_lcd_WH_vision = function (block) {
  2835. var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
  2836. var _y = Blockly.Python.valueToCode(block, "B", Blockly.Python.ORDER_ATOMIC);
  2837. var code = "" + _x + ", " + _y + "";
  2838. return [code, Blockly.Python.ORDER_ATOMIC];
  2839. };
  2840. Blockly.Blocks['ai_canvas_area_tuple'] = {
  2841. init: function () {
  2842. this.appendDummyInput()
  2843. .appendField(Blockly.Msg.ai_vision_canvas_area_tuple);
  2844. this.appendValueInput("xy")
  2845. .setCheck(null)
  2846. .appendField(Blockly.Msg.ai_vision_canvas_area_tuple_xy);
  2847. this.appendValueInput("wh")
  2848. .setCheck(null)
  2849. .appendField(Blockly.Msg.ai_vision_canvas_area_tuple_wh);
  2850. this.setInputsInline(false);
  2851. this.setOutput(true, null);
  2852. this.setColour("#f0983e");
  2853. this.setTooltip(Blockly.Msg.ai_vision_canvas_area_tuple_TOOLTIP);
  2854. this.setHelpUrl("");
  2855. }
  2856. };
  2857. Blockly.Python['ai_canvas_area_tuple'] = function (block) {
  2858. var value_coordinate = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  2859. var value_size = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  2860. // TODO: Assemble Python into code variable.
  2861. var code = value_coordinate + ',' + value_size;
  2862. // TODO: Change ORDER_NONE to the correct strength.
  2863. return [code, Blockly.Python.ORDER_NONE];
  2864. };
  2865. Blockly.Blocks['ai_lane_tracking_run'] = {
  2866. init: function () {
  2867. this.appendDummyInput()
  2868. .appendField(new Blockly.FieldImage("blockly/media/lane_tracking_header.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
  2869. this.appendDummyInput()
  2870. .appendField(Blockly.Msg.ai_vision_from_canvas + Blockly.Msg.ai_vision_lane_tracking_run)
  2871. // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  2872. // .appendField();
  2873. this.appendValueInput("rgb_value")
  2874. .setCheck(null)
  2875. .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_threshold);
  2876. this.setPreviousStatement(true, null);
  2877. this.setNextStatement(true, null);
  2878. this.setColour("#f0983e");
  2879. this.setTooltip(Blockly.Msg.ai_vision_lane_tracking_setup_threshold);
  2880. this.setHelpUrl("");
  2881. }
  2882. };
  2883. Blockly.Python['ai_lane_tracking_run'] = function (block) {
  2884. var value_color = Blockly.Python.valueToCode(block, 'rgb_value', Blockly.Python.ORDER_ATOMIC)
  2885. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2886. var code = '' +
  2887. 'line = canvas.find_line()\n' +
  2888. 'canvas.draw_line(line["rect"][0], line["rect"][1], line["rect"][2],line["rect"][3], color=' + value_color + ', thickness=1)\n' +
  2889. 'canvas.draw_line(line["rect"][2], line["rect"][3], line["rect"][4],line["rect"][5], color=' + value_color + ', thickness=1)\n' +
  2890. 'canvas.draw_line(line["rect"][4], line["rect"][5], line["rect"][6],line["rect"][7], color=' + value_color + ', thickness=1)\n' +
  2891. 'canvas.draw_line(line["rect"][6], line["rect"][7], line["rect"][0],line["rect"][1], color=' + value_color + ', thickness=1)\n' +
  2892. 'canvas.draw_circle(line["cx"], line["cy"], 4,color=' + value_color + ', thickness=1)\n';
  2893. return code;
  2894. };
  2895. Blockly.Blocks['ai_vision_find_lines'] = {
  2896. init: function () {
  2897. this.appendDummyInput()
  2898. .appendField(new Blockly.FieldImage("blockly/media/ai_vision_find_line.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
  2899. this.appendDummyInput()
  2900. .appendField(Blockly.Msg.ai_vision_from_canvas)
  2901. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  2902. .appendField(Blockly.Msg.ai_vision_find_line);
  2903. this.appendValueInput("xy")
  2904. .setCheck(null)
  2905. .appendField(Blockly.Msg.ai_vision_find_line_start_coord);
  2906. this.appendValueInput("wh")
  2907. .setCheck(null)
  2908. .appendField(Blockly.Msg.ai_vision_find_line_size);
  2909. /*this.appendValueInput("threshold")
  2910. .setCheck(null)
  2911. .appendField(Blockly.Msg.ai_vision_find_line_hoffman_threshold);
  2912. this.appendValueInput("theta_margin")
  2913. .setCheck(null)
  2914. .appendField(Blockly.Msg.ai_vision_find_line_merge_theta);
  2915. this.appendValueInput("rho_margin")
  2916. .setCheck(null)
  2917. .appendField(Blockly.Msg.ai_vision_find_line_merge_rho);*/
  2918. this.setOutput(true, null);
  2919. this.setColour("#f0983e");
  2920. this.setTooltip(Blockly.Msg.ai_vision_find_lines_TOOLTIP);
  2921. this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  2922. }
  2923. };
  2924. Blockly.Python['ai_vision_find_lines'] = function (block) {
  2925. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2926. //var threshold = Blockly.Python.valueToCode(block, 'threshold', Blockly.Python.ORDER_ATOMIC);
  2927. //var theta_margin = Blockly.Python.valueToCode(block, 'theta_margin', Blockly.Python.ORDER_ATOMIC);
  2928. //var rho_margin = Blockly.Python.valueToCode(block, 'rho_margin', Blockly.Python.ORDER_ATOMIC);
  2929. var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  2930. var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  2931. // TODO: Assemble Python into code variable.
  2932. var code = variable_name + '.find_lines(roi=(' + xy + ',' + wh + '), threshold = 1000, theta_margin = 25, rho_margin = 25)';
  2933. // TODO: Change ORDER_NONE to the correct strength.
  2934. return [code, Blockly.Python.ORDER_NONE];
  2935. };
  2936. Blockly.Blocks['ai_vision_find_rects'] = {
  2937. init: function () {
  2938. this.appendDummyInput()
  2939. .appendField(new Blockly.FieldImage("blockly/media/ai_vision_find_rect.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
  2940. this.appendDummyInput()
  2941. .appendField(Blockly.Msg.ai_vision_from_canvas)
  2942. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  2943. .appendField(Blockly.Msg.ai_vision_find_rect);
  2944. this.appendValueInput("xy")
  2945. .setCheck(null)
  2946. .appendField(Blockly.Msg.ai_vision_find_rect_start_coord);
  2947. this.appendValueInput("wh")
  2948. .setCheck(null)
  2949. .appendField(Blockly.Msg.ai_vision_find_rect_region_size);
  2950. /*this.appendValueInput("threshold")
  2951. .setCheck(null)
  2952. .appendField(Blockly.Msg.ai_vision_find_rect_bounding_threshold);*/
  2953. this.setOutput(true, null);
  2954. this.setColour("#f0983e");
  2955. this.setTooltip(Blockly.Msg.ai_vision_find_rects_TOOLTIP);
  2956. this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  2957. }
  2958. };
  2959. Blockly.Python['ai_vision_find_rects'] = function (block) {
  2960. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2961. var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  2962. var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  2963. // var threshold = Blockly.Python.valueToCode(block, 'threshold', Blockly.Python.ORDER_ATOMIC);
  2964. // TODO: Assemble Python into code variable.
  2965. var code = variable_name + '.find_rects(roi=(' + xy + ',' + wh + '), threshold = 10000)';
  2966. // TODO: Change ORDER_NONE to the correct strength.
  2967. return [code, Blockly.Python.ORDER_NONE];
  2968. };
  2969. Blockly.Blocks['ai_vision_find_lines'] = {
  2970. init: function () {
  2971. this.appendDummyInput()
  2972. .appendField(new Blockly.FieldImage("blockly/media/ai_vision_find_color.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
  2973. this.appendDummyInput()
  2974. .appendField(Blockly.Msg.ai_vision_from_canvas + Blockly.Msg.ai_vision_find_blobs_color_region)
  2975. // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  2976. // .appendField();
  2977. this.appendValueInput("color")
  2978. .setCheck(null)
  2979. .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_threshold);
  2980. this.appendValueInput("xy")
  2981. .setCheck(null)
  2982. .appendField(Blockly.Msg.ai_vision_find_blobs_start_coord);
  2983. this.appendValueInput("wh")
  2984. .setCheck(null)
  2985. .appendField(Blockly.Msg.ai_vision_find_blobs_size);
  2986. this.setInputsInline(false);
  2987. this.setOutput(true, null);
  2988. this.setColour("#f0983e");
  2989. this.setTooltip(Blockly.Msg.ai_vision_find_blobs_TOOLTIP);
  2990. this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  2991. }
  2992. };
  2993. Blockly.Python['ai_vision_find_lines'] = function (block) {
  2994. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2995. var value_color = Blockly.Python.valueToCode(block, 'color', Blockly.Python.ORDER_ATOMIC);
  2996. var value_xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  2997. var value_wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  2998. Blockly.Python.definitions_[''] = `
  2999. def v831_find_blob_fun(lane_trackingimg,region1,COLOR):
  3000. IMGBLOB = lane_trackingimg.crop(region1[0],region1[1],region1[2],region1[3])
  3001. blobsCANVAS = IMGBLOB.find_blobs(COLOR, merge=True)
  3002. return blobsCANVAS
  3003. `;
  3004. var code = `v831_find_blob_fun(canvas,(${value_xy},${value_wh}),${value_color})
  3005. `;
  3006. return [code, Blockly.Python.ORDER_NONE];
  3007. };
  3008. Blockly.Blocks['ai_vision_find_blobs'] = {
  3009. init: function () {
  3010. this.appendDummyInput()
  3011. .appendField(new Blockly.FieldImage("blockly/media/ai_vision_find_color.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
  3012. this.appendDummyInput()
  3013. .appendField(Blockly.Msg.ai_vision_from_canvas + Blockly.Msg.ai_vision_find_lines_color_region)
  3014. // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  3015. // .appendField();
  3016. this.appendValueInput("color")
  3017. .setCheck(null)
  3018. .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_threshold);
  3019. this.appendValueInput("xy")
  3020. .setCheck(null)
  3021. .appendField(Blockly.Msg.ai_vision_find_blobs_start_coord);
  3022. this.appendValueInput("wh")
  3023. .setCheck(null)
  3024. .appendField(Blockly.Msg.ai_vision_find_blobs_size);
  3025. this.setInputsInline(false);
  3026. this.setOutput(true, null);
  3027. this.setColour("#f0983e");
  3028. this.setTooltip(Blockly.Msg.ai_vision_find_blobs_TOOLTIP);
  3029. this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  3030. }
  3031. };
  3032. Blockly.Python['ai_vision_find_blobs'] = function (block) {
  3033. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3034. var value_color = Blockly.Python.valueToCode(block, 'color', Blockly.Python.ORDER_ATOMIC);
  3035. var value_xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  3036. var value_wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  3037. Blockly.Python.addVariable('lane_trackingline', "lane_trackingline1 = {}", true);
  3038. Blockly.Python.definitions_['ai_vision_find_blobs_color'] = `_ld_color_detection_threshold = ${value_color}
  3039. def v831_lane_tracking_setup_one(lane_trackingimg,region1):
  3040. global lane_trackingline
  3041. lane_trackingcanvas = lane_trackingimg.crop(region1[0],region1[1],region1[2],region1[3])
  3042. lane_trackingline = lane_trackingcanvas.find_line()
  3043. lane_trackingcanvas.draw_circle(lane_trackingline["cx"], lane_trackingline["cy"], 2,color=(0,255,0), thickness=1)
  3044. lane_trackingimg.draw_image(lane_trackingcanvas,region1[0],region1[1])
  3045. lane_trackingimg.draw_rectangle(region1[0],region1[1],region1[0]+region1[2],region1[1]+region1[3], color=(255,0,0), thickness=1)
  3046. lane_trackingline["cx"] = lane_trackingline["cx"] + region1[0]
  3047. lane_trackingline["cy"] = lane_trackingline["cy"] + region1[1]
  3048. return lane_trackingline
  3049. `;
  3050. var code = `v831_lane_tracking_setup_one(canvas,(${value_xy},${value_wh}))
  3051. `;
  3052. return [code, Blockly.Python.ORDER_NONE];
  3053. };
  3054. //
  3055. Blockly.Blocks['ai_vision_find_blobs_result'] = {
  3056. init: function () {
  3057. this.appendDummyInput()
  3058. .appendField(Blockly.Msg.OLCD_LINE_START)
  3059. .appendField(new Blockly.FieldVariable("i"), "varitem")
  3060. .appendField(Blockly.Msg.ai_vision_find_lines_color_region_result)
  3061. .appendField(new Blockly.FieldDropdown([
  3062. [Blockly.Msg.ai_models_object_model_x_center, "cx"],
  3063. [Blockly.Msg.ai_models_object_model_y_center, "cy"]
  3064. ]), "value");
  3065. // this.setInputsInline(false);
  3066. this.setOutput(true, null);
  3067. this.setColour("#f0983e");
  3068. this.setTooltip(Blockly.Msg.ai_vision_find_lines_color_region_result);
  3069. }
  3070. };
  3071. Blockly.Python['ai_vision_find_blobs_result'] = function (block) {
  3072. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3073. var property = block.getFieldValue('value');
  3074. var code = `${variable_name}.get("${property}")`;
  3075. return [code, Blockly.Python.ORDER_ATOMIC];
  3076. };
  3077. Blockly.Blocks['ai_lane_tracking_setup'] = {
  3078. init: function () {
  3079. this.appendDummyInput()
  3080. .appendField(new Blockly.FieldImage("blockly/media/lane_tracking_header.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
  3081. this.appendDummyInput().appendField(Blockly.Msg.ai_vision_from_canvas + Blockly.Msg.ai_vision_lane_tracking_setup)
  3082. // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  3083. // .appendField();
  3084. this.appendValueInput("color")
  3085. .setCheck(null)
  3086. .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_threshold);
  3087. this.appendValueInput("lsize")
  3088. .setCheck(null)
  3089. .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_l);
  3090. this.appendValueInput("rsize")
  3091. .setCheck(null)
  3092. .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_r);
  3093. // this.appendValueInput("axis")
  3094. // .setCheck(null)
  3095. // .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_axis);
  3096. this.setPreviousStatement(true, null);
  3097. this.setNextStatement(true, null);
  3098. this.setColour("#f0983e");
  3099. this.setTooltip(Blockly.Msg.ai_vision_lane_tracking_setup_TOOLTIP);
  3100. this.setHelpUrl("");
  3101. }
  3102. };
  3103. Blockly.Python['ai_lane_tracking_setup'] = function (block) {
  3104. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3105. var value_color = Blockly.Python.valueToCode(block, 'color', Blockly.Python.ORDER_ATOMIC);
  3106. var value_lsize = Blockly.Python.valueToCode(block, 'lsize', Blockly.Python.ORDER_ATOMIC);
  3107. var value_rsize = Blockly.Python.valueToCode(block, 'rsize', Blockly.Python.ORDER_ATOMIC);
  3108. var value_axis = Blockly.Python.valueToCode(block, 'axis', Blockly.Python.ORDER_ATOMIC);
  3109. console.log(value_lsize[0])
  3110. Blockly.Python.addVariable('lane_trackingline1', "lane_trackingline1 = {}", true);
  3111. Blockly.Python.addVariable('lane_trackingline2', "lane_trackingline2 = {}", true);
  3112. Blockly.Python.definitions_['ai_lane_tracking_setup'] = `_ld_color_detection_threshold = ${value_color}
  3113. def v831_lane_tracking_setup(lane_trackingimg,region1,region2):
  3114. global lane_trackingline1,lane_trackingline2
  3115. lane_trackingcanvas1 = lane_trackingimg.crop(region1[0],region1[1],region1[2],region1[3])
  3116. lane_trackingcanvas2 = lane_trackingimg.crop(region2[0],region2[1],region2[2],region2[3])
  3117. lane_trackingline1 = lane_trackingcanvas1.find_line()
  3118. lane_trackingline2 = lane_trackingcanvas2.find_line()
  3119. lane_trackingcanvas1.draw_circle(lane_trackingline1["cx"], lane_trackingline1["cy"], 2,color=(0,255,0), thickness=1)
  3120. lane_trackingcanvas2.draw_circle(lane_trackingline2["cx"], lane_trackingline2["cy"], 2,color=(0,255,0), thickness=1)
  3121. lane_trackingimg.draw_image(lane_trackingcanvas1,region1[0],region1[1])
  3122. lane_trackingimg.draw_image(lane_trackingcanvas2,region2[0],region2[1])
  3123. lane_trackingimg.draw_rectangle(region1[0],region1[1],region1[0]+region1[2],region1[1]+region1[3], color=(255,0,0), thickness=1)
  3124. lane_trackingimg.draw_rectangle(region2[0],region2[1],region2[0]+region2[2],region2[1]+region2[3], color=(255,0,0), thickness=1)
  3125. `
  3126. let code = `v831_lane_tracking_setup(canvas,${value_lsize},${value_rsize})
  3127. `
  3128. return code
  3129. }
  3130. Blockly.Blocks['ai_lane_tracking_get'] = {
  3131. init: function () {
  3132. this.appendDummyInput()
  3133. .appendField(Blockly.Msg.ai_vision_lane_tracking_run_get)
  3134. .appendField(new Blockly.FieldDropdown([
  3135. [Blockly.Msg.ai_vision_lane_tracking_run_ld, "left_check"],
  3136. [Blockly.Msg.ai_vision_lane_tracking_run_lv, "left_value"],
  3137. [Blockly.Msg.ai_vision_lane_tracking_run_rd, "right_check"],
  3138. [Blockly.Msg.ai_vision_lane_tracking_run_rv, "right_value"]
  3139. ]), "return");
  3140. this.setOutput(true, null);
  3141. this.setColour("#f0983e");
  3142. this.setTooltip(Blockly.Msg.ai_vision_lane_tracking_run_get_TOOLTIP);
  3143. this.setHelpUrl("");
  3144. }
  3145. };
  3146. Blockly.Python['ai_lane_tracking_get'] = function (block) {
  3147. var dropdown_return = block.getFieldValue('return');
  3148. // TODO: Assemble Python into code variable.
  3149. var code = '_ld_return["' + dropdown_return + '"]';
  3150. // TODO: Change ORDER_NONE to the correct strength.
  3151. return [code, Blockly.Python.ORDER_NONE];
  3152. };
  3153. Blockly.Blocks['ai_vision_color_analyze'] = {
  3154. init: function () {
  3155. this.appendDummyInput()
  3156. .appendField(new Blockly.FieldImage("blockly/media/ai_vision_analyze_color.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
  3157. this.appendDummyInput()
  3158. .appendField(Blockly.Msg.ai_vision_get_canvas + Blockly.Msg.ai_vision_color_analyze_get_result)
  3159. // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  3160. // .appendField();
  3161. this.appendValueInput("xy")
  3162. .setCheck(null)
  3163. .appendField(Blockly.Msg.ai_vision_color_analyze_start_coord);
  3164. this.appendValueInput("wh")
  3165. .setCheck(null)
  3166. .appendField(Blockly.Msg.ai_vision_color_analyze_size);
  3167. this.setOutput(true, null);
  3168. this.setColour("#f0983e");
  3169. this.setTooltip(Blockly.Msg.ai_vision_color_analyze_TOOLTIP);
  3170. this.setHelpUrl("");
  3171. }
  3172. };
  3173. Blockly.Python['ai_vision_color_analyze'] = function (block) {
  3174. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3175. var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  3176. var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  3177. // TODO: Assemble Python into code variable.
  3178. var code = 'canvas.get_blob_color((' + xy + ', ' + wh + '), 0, 0)';
  3179. // TODO: Change ORDER_NONE to the correct strength.
  3180. return [code, Blockly.Python.ORDER_NONE];
  3181. };
  3182. Blockly.Blocks['ai_vision_get_blobs'] = {
  3183. init: function () {
  3184. this.appendDummyInput()
  3185. .appendField(Blockly.Msg.ai_vision_from)
  3186. .appendField(new Blockly.FieldVariable("i"), "varitem")
  3187. .appendField(Blockly.Msg.ai_vision_get_blobs_result)
  3188. .appendField(new Blockly.FieldDropdown([
  3189. [Blockly.Msg.ai_vision_detection_box_x, "x"],
  3190. [Blockly.Msg.ai_vision_detection_box_y, "y"],
  3191. [Blockly.Msg.ai_models_face_model_ws, "w"],
  3192. [Blockly.Msg.ai_models_face_model_hs, "h"],
  3193. // [Blockly.Msg.ai_vision_detection_box_pixels, "pixels()"],
  3194. [Blockly.Msg.ai_vision_detection_box_cx, "cx"],
  3195. [Blockly.Msg.ai_vision_detection_box_cy, "cy"]
  3196. // [Blockly.Msg.ai_vision_detection_box_degree, "rotation()"],
  3197. // [Blockly.Msg.ai_vision_detection_box_total, "count()"]
  3198. ]), "blob_type");
  3199. this.setInputsInline(false);
  3200. this.setOutput(true, null);
  3201. this.setColour("#f0983e");
  3202. this.setTooltip(Blockly.Msg.ai_vision_get_blobs_TOOLTIP);
  3203. this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  3204. }
  3205. };
  3206. Blockly.Python['ai_vision_get_blobs'] = function (block) {
  3207. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3208. var type = block.getFieldValue('blob_type');
  3209. // TODO: Assemble Python into code variable.
  3210. var code = `${variable_name}["${type}"]`;
  3211. if (type == "cx") {
  3212. code = `int((${variable_name}["w"] + ${variable_name}["x"] + ${variable_name}["x"])/2)`
  3213. } else if (type == "cy") {
  3214. code = `int((${variable_name}["h"] + ${variable_name}["y"] + ${variable_name}["y"])/2)`
  3215. }
  3216. // TODO: Change ORDER_NONE to the correct strength.
  3217. return [code, Blockly.Python.ORDER_NONE];
  3218. };
  3219. Blockly.Blocks['ai_vision_get_threshold_default'] = {
  3220. init: function () {
  3221. this.appendDummyInput()
  3222. .appendField(Blockly.Msg.ai_vision_detection_color_threshold_set)
  3223. .appendField(new Blockly.FieldDropdown([
  3224. [Blockly.Msg.ai_vision_detection_color_threshold_set_black, "black"],
  3225. [Blockly.Msg.ai_vision_detection_color_threshold_set_white, "white"],
  3226. [Blockly.Msg.ai_vision_detection_color_threshold_set_red, "red"],
  3227. [Blockly.Msg.ai_vision_detection_color_threshold_set_green, "green"],
  3228. [Blockly.Msg.ai_vision_detection_color_threshold_set_blue, "blue"],
  3229. [Blockly.Msg.ai_vision_detection_color_threshold_set_orange, "orange"]
  3230. ]), "color");
  3231. this.setOutput(true, null);
  3232. this.setColour("#f0983e");
  3233. var thisBlock = this;
  3234. this.setTooltip(function () {
  3235. var mode = thisBlock.getFieldValue('color');
  3236. var TOOLTIPS = {
  3237. 'black': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_black),
  3238. 'white': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_white),
  3239. 'red': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_red),
  3240. 'green': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_green),
  3241. 'blue': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_blue),
  3242. 'orange': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_orange)
  3243. };
  3244. return TOOLTIPS[mode];
  3245. });
  3246. this.setHelpUrl("");
  3247. }
  3248. };
  3249. Blockly.Python['ai_vision_get_threshold_default'] = function (block) {
  3250. var dropdown_color = block.getFieldValue('color');
  3251. // TODO: Assemble Python into code variable.
  3252. if (dropdown_color == "black") {
  3253. var code = '[(0,40)]';
  3254. } else if (dropdown_color == "white") {
  3255. var code = '[(64,100)]';
  3256. } else if (dropdown_color == "red") {
  3257. var code = '[(45, 65, 40, 80, 40, 60)]';
  3258. } else if (dropdown_color == "green") {
  3259. var code = '[(45, 65, -50, -30, 0, 40)]';
  3260. } else if (dropdown_color == "blue") {
  3261. var code = '[(45, 65, -20, 30, -60, -20)]';
  3262. } else if (dropdown_color == "orange") {
  3263. var code = '[(77, 55, 19, 61, 14, 108)]';
  3264. }
  3265. // TODO: Change ORDER_NONE to the correct strength.
  3266. return [code, Blockly.Python.ORDER_NONE];
  3267. };
  3268. Blockly.Blocks['ai_vision_find_qrcode'] = {
  3269. init: function () {
  3270. this.appendDummyInput()
  3271. .appendField(new Blockly.FieldImage("blockly/media/ai_vision_qrcode_.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  3272. this.appendDummyInput()
  3273. .appendField("开始识别二维码")
  3274. // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  3275. // .appendField();
  3276. this.setOutput(false, null);
  3277. this.setNextStatement(true, null);
  3278. this.setPreviousStatement(true, null);
  3279. this.setColour("#f0983e");
  3280. this.setTooltip(Blockly.Msg.ai_vision_find_qrcode_TOOLTIP);
  3281. this.setHelpUrl("");
  3282. }
  3283. };
  3284. Blockly.Python['ai_vision_find_qrcode'] = function (block) {
  3285. // TODO: Assemble Python into code variable.
  3286. var code = 'findQrcode = canvas.find_qrcodes() \n';
  3287. // TODO: Change ORDER_NONE to the correct strength.
  3288. return code;
  3289. };
  3290. Blockly.Blocks['ai_vision_find_qrcode_result'] = {
  3291. init: function () {
  3292. this.appendDummyInput()
  3293. .appendField("屏幕显示二维码").
  3294. appendField(new Blockly.FieldDropdown([
  3295. ["源文本", "SourceText"],
  3296. ["检测框", "CheckBox"],
  3297. ]), "qrcode_result")
  3298. // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  3299. // .appendField();
  3300. this.setOutput(false, null);
  3301. this.setNextStatement(true, null);
  3302. this.setPreviousStatement(true, null);
  3303. this.setColour("#f0983e");
  3304. this.setTooltip(Blockly.Msg.ai_vision_find_qrcode_TOOLTIP);
  3305. this.setHelpUrl("");
  3306. }
  3307. };
  3308. Blockly.Python['ai_vision_find_qrcode_result'] = function (block) {
  3309. let qrcode_result = block.getFieldValue('qrcode_result');
  3310. let qrcodeResultAllBlock = getBlocksByTypeName("ai_vision_find_qrcode_result")
  3311. // console.log("qrcode_result",qrcodeResultAllBlock[0].innerText)
  3312. let findQrcodeStr = qrcodeResultAllBlock[0].innerText
  3313. let Source = findQrcodeStr.indexOf("Source") != -1 ? "True" : "False"
  3314. let CheckBox = findQrcodeStr.indexOf("CheckBox") != -1 ? "True" : "False"
  3315. Blockly.Python.addFunction("showQRcodeResult", `def showQRcodeResult(Source,CheckBox):
  3316. global findQrcode
  3317. for i in findQrcode:
  3318. if Source:
  3319. canvas.draw_string((i["x"]),(i["y"]), (i["payload"]), scale = 1, color = (255,0,0) , thickness = 1)
  3320. if CheckBox:
  3321. canvas.draw_rectangle((i["x"]),(i["y"]), (i["x"])+(i["w"]),(i["y"])+ (i["h"]), color=(255,0,0), thickness=1)
  3322. `)
  3323. // TODO: Assemble Python into code variable.
  3324. let code = ""
  3325. if (qrcodeResultAllBlock[0].id == block.id) {
  3326. code = `showQRcodeResult(${Source},${CheckBox})
  3327. `
  3328. }
  3329. // TODO: Change ORDER_NONE to the correct strength.
  3330. return code;
  3331. };
  3332. Blockly.Blocks['ai_vision_qrcode_get_info'] = {
  3333. init: function () {
  3334. this.appendDummyInput()
  3335. .appendField(Blockly.Msg.ai_vision_qrcode_get_result + Blockly.Msg.ai_vision_pattern_detection_content)
  3336. this.setInputsInline(false);
  3337. this.setOutput(true, null);
  3338. this.setColour("#f0983e");
  3339. this.setTooltip(Blockly.Msg.ai_vision_qrcode_get_result + Blockly.Msg.ai_vision_pattern_detection_content);
  3340. this.setHelpUrl("");
  3341. }
  3342. };
  3343. Blockly.Python['ai_vision_qrcode_get_info'] = function (block) {
  3344. Blockly.Python.addFunction("getQRcodeResult", `def getQRcodeResult():
  3345. global findQrcode
  3346. qrCodeList = []
  3347. for i in findQrcode:
  3348. qrCodeList.append({i["payload"]})
  3349. return qrCodeList
  3350. `)
  3351. let code = "getQRcodeResult()"
  3352. return [code, Blockly.Python.ORDER_NONE];
  3353. };
  3354. Blockly.Blocks['ai_vision_find_apriltag'] = {
  3355. init: function () {
  3356. this.appendDummyInput()
  3357. .appendField(new Blockly.FieldImage("blockly/media/ai_vision_apriltag_.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  3358. this.appendDummyInput()
  3359. .appendField(Blockly.Msg.ai_vision_get_canvas + Blockly.Msg.ai_vision_apriltag_detected_result)
  3360. // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  3361. // .appendField();
  3362. // this.setOutput(true, null);
  3363. this.setNextStatement(true, null);
  3364. this.setPreviousStatement(true, null);
  3365. this.setColour("#f0983e");
  3366. this.setTooltip(Blockly.Msg.ai_vision_find_apriltag_TOOLTIP);
  3367. this.setHelpUrl("");
  3368. }
  3369. };
  3370. Blockly.Python['ai_vision_find_apriltag'] = function (block) {
  3371. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3372. // TODO: Assemble Python into code variable.
  3373. var code = 'findApriltags = canvas.find_apriltags(families = 16,fx = (6/5.76)*320,fy = (6/3.24)*240,cx = 160,cy = 120)';
  3374. // TODO: Change ORDER_NONE to the correct strength.
  3375. return code;
  3376. };
  3377. Blockly.Blocks['ai_vision_apriltag_get_info'] = {
  3378. init: function () {
  3379. this.appendDummyInput()
  3380. .appendField(Blockly.Msg.ai_vision_apriltag_get_result)
  3381. .appendField(new Blockly.FieldDropdown([
  3382. [Blockly.Msg.ai_vision_pattern_detection_content, "ApriltagId"],
  3383. // [Blockly.Msg.ai_vision_pattern_detection_type_id, "id"],
  3384. [Blockly.Msg.ai_vision_pattern_detection_type_family, "ApriltagCheckout"]
  3385. ]), "get_info");
  3386. this.setInputsInline(false);
  3387. // this.setOutput(true, null);
  3388. this.setNextStatement(true, null);
  3389. this.setPreviousStatement(true, null);
  3390. this.setColour("#f0983e");
  3391. var thisBlock = this;
  3392. this.setTooltip(function () {
  3393. var mode = thisBlock.getFieldValue('get_info');
  3394. var TOOLTIPS = {
  3395. 'payload': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_content),
  3396. 'id': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_content),
  3397. 'family': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_type_family),
  3398. 'x': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_x),
  3399. 'y': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_y),
  3400. 'w': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_w),
  3401. 'h': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_h)
  3402. };
  3403. return TOOLTIPS[mode];
  3404. });
  3405. this.setHelpUrl("");
  3406. }
  3407. };
  3408. Blockly.Python['ai_vision_apriltag_get_info'] = function (block) {
  3409. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3410. var dropdown_name = block.getFieldValue('get_info');
  3411. let apriltagAllBlock = getBlocksByTypeName("ai_vision_apriltag_get_info")
  3412. let findQrcodeStr = apriltagAllBlock[0].innerText
  3413. let ApriltagId = findQrcodeStr.indexOf("ApriltagId") != -1 ? "True" : "False"
  3414. let ApriltagCheckout = findQrcodeStr.indexOf("ApriltagCheckout") != -1 ? "True" : "False"
  3415. Blockly.Python.addFunction("getApriltagCanvasResult", `def getApriltagCanvasResult(ApriltagId,ApriltagCheckout):
  3416. global findApriltags
  3417. for i in findApriltags:
  3418. if apriltagId:
  3419. canvas.draw_string((i["x"]),(i["y"]), (i["id"]), scale = 1, color = (255,0,0) , thickness = 1)
  3420. if ApriltagCheckout:
  3421. canvas.draw_rectangle((i["x"]),(i["y"]), (i["x"])+(i["w"]),(i["y"])+ (i["h"]), color=(255,0,0), thickness=1)
  3422. )`)
  3423. // TODO: Assemble Python into code variable.
  3424. var code = `getApriltagCanvasResult(${ApriltagId},${ApriltagCheckout})`;
  3425. // TODO: Change ORDER_NONE to the correct strength.
  3426. return code;
  3427. };
  3428. Blockly.Blocks['ai_vision_find_datamatrices'] = {
  3429. init: function () {
  3430. this.appendDummyInput()
  3431. .appendField(Blockly.Msg.ai_vision_get_canvas + Blockly.Msg.ai_vision_apriltag_detected_result);
  3432. this.setOutput(true, null);
  3433. this.setColour("#f0983e");
  3434. this.setTooltip(Blockly.Msg.ai_vision_find_datamatrices_TOOLTIP);
  3435. this.setHelpUrl("");
  3436. }
  3437. };
  3438. Blockly.Python['ai_vision_find_datamatrices'] = function (block) {
  3439. Blockly.Python.addFunction("getApriltagResult", `def getApriltagResult():
  3440. global findApriltags
  3441. if len(findApriltags):
  3442. return findApriltags[0]["id"]
  3443. else:
  3444. return ""
  3445. )`)
  3446. var code = `getApriltagResult()`;
  3447. // TODO: Change ORDER_NONE to the correct strength.
  3448. return [code, Blockly.Python.ORDER_NONE];
  3449. };
  3450. Blockly.Blocks['ai_vision_datamatrices_get_info'] = {
  3451. init: function () {
  3452. this.appendDummyInput()
  3453. .appendField(Blockly.Msg.ai_vision_from)
  3454. .appendField(new Blockly.FieldVariable("i"), "varitem")
  3455. .appendField(Blockly.Msg.ai_vision_data_matrices_get_result)
  3456. .appendField(new Blockly.FieldDropdown([
  3457. [Blockly.Msg.ai_vision_pattern_detection_content, "payload"],
  3458. [Blockly.Msg.ai_vision_pattern_detection_rows, "rows"],
  3459. [Blockly.Msg.ai_vision_pattern_detection_cols, "columns"],
  3460. [Blockly.Msg.ai_vision_pattern_detection_can_tolerate_count, "capacity"],
  3461. [Blockly.Msg.ai_vision_pattern_detection_can_not_tolerate_count, "padding"],
  3462. [Blockly.Msg.ai_vision_pattern_detection_x, "x"],
  3463. [Blockly.Msg.ai_vision_pattern_detection_y, "y"],
  3464. [Blockly.Msg.ai_vision_pattern_detection_w, "w"],
  3465. [Blockly.Msg.ai_vision_pattern_detection_h, "h"]
  3466. ]), "get_info");
  3467. this.setInputsInline(false);
  3468. this.setOutput(true, null);
  3469. this.setColour("#f0983e");
  3470. var thisBlock = this;
  3471. this.setTooltip(function () {
  3472. var mode = thisBlock.getFieldValue('get_info');
  3473. var TOOLTIPS = {
  3474. 'payload': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_content),
  3475. 'rows': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_rows),
  3476. 'columns': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_cols),
  3477. 'capacity': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_can_tolerate_count),
  3478. 'padding': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_can_not_tolerate_count),
  3479. 'x': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_x),
  3480. 'y': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_y),
  3481. 'w': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_w),
  3482. 'h': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_h)
  3483. };
  3484. return TOOLTIPS[mode];
  3485. });
  3486. this.setHelpUrl("");
  3487. }
  3488. };
  3489. Blockly.Python['ai_vision_datamatrices_get_info'] = function (block) {
  3490. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3491. var dropdown_name = block.getFieldValue('get_info');
  3492. // TODO: Assemble Python into code variable.
  3493. var code = variable_name + '.' + dropdown_name + '()';
  3494. // TODO: Change ORDER_NONE to the correct strength.
  3495. return [code, Blockly.Python.ORDER_NONE];
  3496. };
  3497. Blockly.Blocks['ai_vision_find_barcodes'] = {
  3498. init: function () {
  3499. this.appendDummyInput()
  3500. .appendField(new Blockly.FieldImage("blockly/media/ai_vision_barcode_.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  3501. this.appendDummyInput()
  3502. .appendField(Blockly.Msg.ai_vision_get_canvas + Blockly.Msg.ai_vision_barcode_detected_result)
  3503. // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  3504. // .appendField();
  3505. this.setNextStatement(true);
  3506. this.setPreviousStatement(true);
  3507. this.setColour("#f0983e");
  3508. this.setTooltip(Blockly.Msg.ai_vision_find_barcodes_TOOLTIP);
  3509. this.setHelpUrl("");
  3510. }
  3511. };
  3512. Blockly.Python['ai_vision_find_barcodes'] = function (block) {
  3513. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3514. // TODO: Assemble Python into code variable.
  3515. var code = 'findBarcodes = canvas.find_barcodes() \n';
  3516. // TODO: Change ORDER_NONE to the correct strength.
  3517. return code;
  3518. };
  3519. Blockly.Blocks['ai_vision_barcodes_get_info'] = {
  3520. init: function () {
  3521. this.appendDummyInput()
  3522. .appendField("屏幕显示条形码")
  3523. .appendField(new Blockly.FieldDropdown([
  3524. [Blockly.Msg.ai_vision_pattern_detection_content, "barcodesPayload"],
  3525. [Blockly.Msg.ai_models_face_model_rect, "barcodesCorners"]
  3526. ]), "get_info");
  3527. this.setInputsInline(false);
  3528. this.setOutput(false, null);
  3529. this.setNextStatement(true);
  3530. this.setPreviousStatement(true);
  3531. this.setColour("#f0983e");
  3532. var thisBlock = this;
  3533. this.setTooltip(function () {
  3534. var mode = thisBlock.getFieldValue('get_info');
  3535. var TOOLTIPS = {
  3536. 'payload': Blockly.Msg.ai_vision_barcodes_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_content),
  3537. 'corners': Blockly.Msg.ai_models_face_model_rect.replace('%1', Blockly.Msg.ai_models_face_model_rect),
  3538. 'x': Blockly.Msg.ai_vision_barcodes_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_x),
  3539. 'y': Blockly.Msg.ai_vision_barcodes_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_y),
  3540. 'w': Blockly.Msg.ai_vision_barcodes_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_w),
  3541. 'h': Blockly.Msg.ai_vision_barcodes_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_h)
  3542. };
  3543. return TOOLTIPS[mode];
  3544. });
  3545. this.setHelpUrl("");
  3546. }
  3547. };
  3548. Blockly.Python['ai_vision_barcodes_get_info'] = function (block) {
  3549. var dropdown_name = block.getFieldValue('get_info');
  3550. let qrcodeResultAllBlock = getBlocksByTypeName("ai_vision_barcodes_get_info")
  3551. // console.log("qrcode_result",qrcodeResultAllBlock[0].innerText)
  3552. let findQrcodeStr = qrcodeResultAllBlock[0].innerText
  3553. let barcodesPayload = findQrcodeStr.indexOf("barcodesPayload") != -1 ? "True" : "False"
  3554. let barcodesCorners = findQrcodeStr.indexOf("barcodesCorners") != -1 ? "True" : "False"
  3555. Blockly.Python.addFunction("showBarcodesResult", `def showBarcodesResult(type1,type2):
  3556. global findBarcodes
  3557. for i in findBarcodes:
  3558. if type1:
  3559. canvas.draw_string((i["corners"][0][0]),(i["corners"][0][1]), (i["payload"]), scale = 1, color = (255,0,0) , thickness = 1)
  3560. if type2:
  3561. x1,y1 = i['corners'][0] #访问字典的列表
  3562. x2,y2 = i['corners'][1]
  3563. x3,y3 = i['corners'][2]
  3564. x4,y4 = i['corners'][3]
  3565. canvas.draw_line(x1, y1, x2, y2, color = (0, 255, 0), thickness = 3)
  3566. canvas.draw_line(x2, y2, x3, y3, color = (0, 255, 0), thickness = 3)
  3567. canvas.draw_line(x3, y3, x4, y4, color = (0, 255, 0), thickness = 3)
  3568. canvas.draw_line(x4, y4, x1, y1, color = (0, 255, 0), thickness = 3)
  3569. `)
  3570. // TODO: Assemble Python into code variable.
  3571. let code = ""
  3572. if (qrcodeResultAllBlock[0].id == block.id) {
  3573. code = `showBarcodesResult(${barcodesPayload},${barcodesCorners})
  3574. `
  3575. }
  3576. return code
  3577. };
  3578. Blockly.Blocks['ai_vision_barcodes_get_info_result'] = {
  3579. init: function () {
  3580. this.appendDummyInput()
  3581. .appendField(Blockly.Msg.uav_bar_code)
  3582. this.setInputsInline(false);
  3583. this.setOutput(true, null);
  3584. this.setColour("#f0983e");
  3585. this.setTooltip(Blockly.Msg.uav_bar_code);
  3586. }
  3587. };
  3588. Blockly.Python['ai_vision_barcodes_get_info_result'] = function (block) {
  3589. Blockly.Python.addFunction("getBarcodesResult", `def getBarcodesResult():
  3590. global findBarcodes
  3591. if len(findBarcodes)>0:
  3592. return findBarcodes[0]["payload"]
  3593. else:
  3594. return ""
  3595. `)
  3596. var code = `getBarcodesResult()`;
  3597. return [code, Blockly.Python.ORDER_NONE];
  3598. };
  3599. Blockly.Blocks['ai_vision_get_circles'] = {
  3600. init: function () {
  3601. this.appendDummyInput()
  3602. .appendField(Blockly.Msg.ai_vision_from)
  3603. .appendField(new Blockly.FieldVariable("i"), "varitem")
  3604. .appendField(Blockly.Msg.ai_vision_find_circle_detected_result)
  3605. .appendField(new Blockly.FieldDropdown([
  3606. [Blockly.Msg.ai_vision_find_circle_detected_x, "x()"],
  3607. [Blockly.Msg.ai_vision_find_circle_detected_y, "y()"],
  3608. [Blockly.Msg.ai_vision_find_circle_detected_radius, "r()"]
  3609. ]), "blob_type");
  3610. this.setInputsInline(false);
  3611. this.setOutput(true, null);
  3612. this.setColour("#f0983e");
  3613. this.setTooltip(Blockly.Msg.ai_vision_get_circles_TOOLTIP);
  3614. this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  3615. }
  3616. };
  3617. Blockly.Python['ai_vision_get_circles'] = function (block) {
  3618. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3619. var type = block.getFieldValue('blob_type');
  3620. var code = variable_name + '.' + type;
  3621. return [code, Blockly.Python.ORDER_NONE];
  3622. };
  3623. Blockly.Blocks['ai_vision_get_rects'] = {
  3624. init: function () {
  3625. this.appendDummyInput()
  3626. .appendField(Blockly.Msg.ai_vision_from)
  3627. .appendField(new Blockly.FieldVariable("i"), "varitem")
  3628. .appendField(Blockly.Msg.ai_vision_find_rect_detected_result)
  3629. .appendField(new Blockly.FieldDropdown([
  3630. [Blockly.Msg.ai_vision_find_rect_detected_x, "x()"],
  3631. [Blockly.Msg.ai_vision_find_rect_detected_y, "y()"],
  3632. [Blockly.Msg.ai_vision_find_rect_detected_w, "w()"],
  3633. [Blockly.Msg.ai_vision_find_rect_detected_h, "h()"],
  3634. [Blockly.Msg.ai_vision_find_rect_detected_tuple, "rect()"],
  3635. [Blockly.Msg.ai_vision_find_rect_detected_corners, "corners()"]
  3636. ]), "blob_type");
  3637. this.setInputsInline(false);
  3638. this.setOutput(true, null);
  3639. this.setColour("#f0983e");
  3640. this.setTooltip(Blockly.Msg.ai_vision_get_rects_TOOLTIP);
  3641. this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  3642. }
  3643. };
  3644. Blockly.Python['ai_vision_get_rects'] = function (block) {
  3645. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3646. var type = block.getFieldValue('blob_type');
  3647. // TODO: Assemble Python into code variable.
  3648. var code = variable_name + '.' + type;
  3649. // TODO: Change ORDER_NONE to the correct strength.
  3650. return [code, Blockly.Python.ORDER_NONE];
  3651. };
  3652. Blockly.Blocks['ai_vision_get_lines'] = {
  3653. init: function () {
  3654. this.appendDummyInput()
  3655. .appendField(Blockly.Msg.ai_vision_from)
  3656. .appendField(new Blockly.FieldVariable("i"), "varitem")
  3657. .appendField(Blockly.Msg.ai_vision_find_line_detected_result)
  3658. .appendField(new Blockly.FieldDropdown([
  3659. [Blockly.Msg.ai_vision_find_line_detected_start_x, "x1()"],
  3660. [Blockly.Msg.ai_vision_find_line_detected_start_y, "y1()"],
  3661. [Blockly.Msg.ai_vision_find_line_detected_end_x, "x2()"],
  3662. [Blockly.Msg.ai_vision_find_line_detected_end_y, "y2()"],
  3663. [Blockly.Msg.ai_vision_find_line_detected_length, "length()"],
  3664. [Blockly.Msg.ai_vision_find_line_detected_angle, "theta()"]
  3665. ]), "blob_type");
  3666. this.setInputsInline(false);
  3667. this.setOutput(true, null);
  3668. this.setColour("#f0983e");
  3669. this.setTooltip(Blockly.Msg.ai_vision_get_lines_TOOLTIP);
  3670. this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  3671. }
  3672. };
  3673. Blockly.Python['ai_vision_get_lines'] = function (block) {
  3674. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3675. var type = block.getFieldValue('blob_type');
  3676. // TODO: Assemble Python into code variable.
  3677. var code = variable_name + '.' + type;
  3678. // TODO: Change ORDER_NONE to the correct strength.
  3679. return [code, Blockly.Python.ORDER_NONE];
  3680. };
  3681. /*
  3682. _ ___ __ __ _ _
  3683. / \ |_ _| | \/ (_) ___ _ __ ___ _ __ | |__ ___ _ __ ___
  3684. / _ \ | | | |\/| | |/ __| '__/ _ \| '_ \| '_ \ / _ \| '_ \ / _ \
  3685. / ___ \ | | | | | | | (__| | | (_) | |_) | | | | (_) | | | | __/
  3686. /_/ \_\___| |_| |_|_|\___|_| \___/| .__/|_| |_|\___/|_| |_|\___|
  3687. |_|
  3688. */
  3689. Blockly.Blocks['ai_mphone_init'] = {
  3690. init: function () {
  3691. this.appendDummyInput()
  3692. .appendField(new Blockly.FieldImage("blockly/media/microphone_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  3693. this.appendDummyInput()
  3694. .appendField(Blockly.Msg.ai_microphone_init);
  3695. this.setPreviousStatement(true);
  3696. this.setNextStatement(true);
  3697. this.setColour("#5fcd8e");
  3698. this.setTooltip(Blockly.Msg.ai_mphone_init_TOOLTIP);
  3699. this.setHelpUrl("");
  3700. }
  3701. };
  3702. Blockly.Python.ai_mphone_init = function (block) {
  3703. Blockly.Python.definitions_.import_all_mphone = "" +
  3704. "from Maix import GPIO, I2S, FFT\n" +
  3705. "from board import board_info\n" +
  3706. "from fpioa_manager import fm\n" +
  3707. "\n" +
  3708. "sample_rate = 38640\n" +
  3709. "sample_points = 1024\n" +
  3710. "fft_points = 512\n" +
  3711. "hist_x_num = 50\n" +
  3712. "\n" +
  3713. "fm.register(20,fm.fpioa.I2S0_IN_D0, force=True)\n" +
  3714. "fm.register(19,fm.fpioa.I2S0_WS, force=True)\n" +
  3715. "fm.register(18,fm.fpioa.I2S0_SCLK, force=True)\n" +
  3716. "\n" +
  3717. "_recorder_rx = I2S(I2S.DEVICE_0)\n" +
  3718. "_recorder_rx.channel_config(_recorder_rx.CHANNEL_0, _recorder_rx.RECEIVER, align_mode = I2S.STANDARD_MODE)\n" +
  3719. "_recorder_rx.set_sample_rate(sample_rate)\n" +
  3720. "def _microphone_read_average(lst): \n" +
  3721. " return int((sum(lst)/len(lst))*100)\n" +
  3722. "";
  3723. // Blockly.Python.addVariable('sample_rate', "sample_rate = 38640", true);
  3724. // Blockly.Python.addVariable('sample_points', "sample_points = 1024", true);
  3725. // Blockly.Python.addVariable('fft_points', "fft_points = 512", true);
  3726. // Blockly.Python.addVariable('hist_x_num', "hist_x_num = 50", true);
  3727. // Blockly.Python.addVariable('_recorder_rx', "_recorder_rx = None", true);
  3728. // Blockly.Python.addVariable('fft_res', "fft_res = None", true);
  3729. // Blockly.Python.addVariable('fft_amp', "fft_amp = None", true);
  3730. Blockly.Python.addVariable('read_all_channel', "read_all_channel = [0, 0, 0, 0, 0, 0, 0, 0]", true);
  3731. // Blockly.Python.addVariable('_recorder_rx', "", true);
  3732. var _code = "" +
  3733. "";
  3734. return _code;
  3735. }
  3736. Blockly.Blocks['mphone_audio_spectrum_init'] = {
  3737. init: function () {
  3738. this.appendDummyInput()
  3739. .appendField(new Blockly.FieldImage("blockly/media/ai_audio_spectrum.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  3740. this.appendDummyInput()
  3741. .appendField(Blockly.Msg.ai_microphone_start_spectrum_analyze);
  3742. this.setPreviousStatement(true, null);
  3743. this.setNextStatement(true, null);
  3744. this.setColour("#5fcd8e");
  3745. this.setTooltip(Blockly.Msg.mphone_audio_spectrum_init_TOOLTIP);
  3746. this.setHelpUrl("");
  3747. }
  3748. };
  3749. Blockly.Python['mphone_audio_spectrum_init'] = function (block) {
  3750. // TODO: Assemble Python into code variable.
  3751. Blockly.Python.definitions_['v831_import_time'] = `import time`
  3752. var code = "" +
  3753. "time.sleep_ms(10)\n" +
  3754. "_audio = _recorder_rx.record(sample_points)\n" +
  3755. "fft_res = FFT.run(_audio.to_bytes(),fft_points)\n" +
  3756. "fft_amp = FFT.amplitude(fft_res)\n\n" +
  3757. "read_all_channel[0] = int(_microphone_read_average(fft_amp[0:63]))\n" +
  3758. "read_all_channel[1] = int(_microphone_read_average(fft_amp[64:127]))\n" +
  3759. "read_all_channel[2] = int(_microphone_read_average(fft_amp[127:191]))\n" +
  3760. "read_all_channel[3] = int(_microphone_read_average(fft_amp[192:255]))\n" +
  3761. "read_all_channel[4] = int(_microphone_read_average(fft_amp[256:319]))\n" +
  3762. "read_all_channel[5] = int(_microphone_read_average(fft_amp[320:383]))\n" +
  3763. "read_all_channel[6] = int(_microphone_read_average(fft_amp[384:447]))\n" +
  3764. "read_all_channel[7] = int(_microphone_read_average(fft_amp[448:514]))\n" +
  3765. "";
  3766. return code;
  3767. };
  3768. Blockly.Blocks['ai_mphone_read_sound_sensitivity'] = {
  3769. init: function () {
  3770. this.appendDummyInput()
  3771. .appendField(Blockly.Msg.ai_microphone_get_spectrum_analyze_result)
  3772. .appendField(new Blockly.FieldDropdown([
  3773. [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_1, "0"],
  3774. [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_2, "1"],
  3775. [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_3, "2"],
  3776. [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_4, "3"],
  3777. [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_5, "4"],
  3778. [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_6, "5"],
  3779. [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_7, "6"],
  3780. [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_8, "7"]
  3781. ]), "level");
  3782. this.setOutput(true, null);
  3783. this.setColour("#5fcd8e");
  3784. this.setTooltip(Blockly.Msg.ai_mphone_read_sound_sensitivity_TOOLTIP);
  3785. this.setHelpUrl("");
  3786. }
  3787. };
  3788. Blockly.Python['ai_mphone_read_sound_sensitivity'] = function (block) {
  3789. var dropdown_level = block.getFieldValue('level');
  3790. // TODO: Assemble Python into code variable.
  3791. var code = 'read_all_channel[' + dropdown_level + ']';
  3792. // TODO: Change ORDER_NONE to the correct strength.
  3793. return [code, Blockly.Python.ORDER_NONE];
  3794. };
  3795. Blockly.Blocks['ai_mphone_Record_audio_init'] = {
  3796. init: function () {
  3797. this.appendDummyInput()
  3798. .appendField(new Blockly.FieldImage("blockly/media/microphone_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  3799. this.appendDummyInput()
  3800. .appendField(Blockly.Msg.ai_mphone_Record_audio_init);
  3801. this.setPreviousStatement(true);
  3802. this.setNextStatement(true);
  3803. this.setColour("#5fcd8e");
  3804. this.setTooltip(Blockly.Msg.ai_mphone_Record_audio_init_TOOLTIP);
  3805. this.setHelpUrl("");
  3806. }
  3807. };
  3808. Blockly.Python.ai_mphone_Record_audio_init = function (block) {
  3809. Blockly.Python.definitions_.import_ai_mphone_Record_audio_init = "" +
  3810. "from Maix import GPIO, I2S\n" +
  3811. "from fpioa_manager import fm\n" +
  3812. 'import audio\n' +
  3813. "\n" +
  3814. '# user setting\n' +
  3815. "sample_rate = 16000\n" +
  3816. "# default seting\n" +
  3817. "sample_points = 2048\n" +
  3818. "wav_ch = 2\n" +
  3819. "\n" +
  3820. 'fm.register(8, fm.fpioa.GPIO0, force=True)\n' +
  3821. 'wifi_en = GPIO(GPIO.GPIO0, GPIO.OUT)\n' +
  3822. 'wifi_en.value(0)\n' +
  3823. "\n" +
  3824. "fm.register(20,fm.fpioa.I2S0_IN_D0, force=True)\n" +
  3825. "fm.register(19,fm.fpioa.I2S0_WS, force=True)\n" +
  3826. "fm.register(18,fm.fpioa.I2S0_SCLK, force=True)\n" +
  3827. "\n" +
  3828. "rx = I2S(I2S.DEVICE_0)\n" +
  3829. "rx.channel_config(rx.CHANNEL_0, rx.RECEIVER, align_mode=I2S.STANDARD_MODE)\n" +
  3830. "rx.set_sample_rate(sample_rate)\n" +
  3831. "print(rx)\n" +
  3832. "";
  3833. var _code = "" +
  3834. "";
  3835. return _code;
  3836. }
  3837. Blockly.Blocks['ai_mphone_record_init'] = {
  3838. init: function () {
  3839. this.appendDummyInput()
  3840. .appendField(Blockly.Msg.ai_microphone_init);
  3841. this.setPreviousStatement(true);
  3842. this.setNextStatement(true, null);
  3843. this.setColour("#5fcd8e");
  3844. this.setTooltip(Blockly.Msg.ai_microphone_init);
  3845. this.setHelpUrl("");
  3846. }
  3847. }
  3848. Blockly.Python['ai_mphone_record_init'] = function (block) {
  3849. Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio`
  3850. Blockly.Python.definitions_['v831_import_wave'] = `import wave`
  3851. Blockly.Python.definitions_['v831_import_os'] = `import os`
  3852. let code = ''
  3853. return code;
  3854. }
  3855. Blockly.Blocks['ai_mphone_record_setting'] = {
  3856. init: function () {
  3857. this.appendValueInput("record_time").setCheck(null)
  3858. .appendField(Blockly.Msg.ai_mphone_Record_audio_start_time)
  3859. this.appendValueInput("path")
  3860. .setCheck(null)
  3861. .appendField(Blockly.Msg.ai_mphone_Record_audio_start_path);
  3862. this.appendDummyInput()
  3863. .appendField(Blockly.Msg.ai_mphone_Record_audio_start);
  3864. this.setPreviousStatement(true);
  3865. this.setNextStatement(true, null);
  3866. this.setInputsInline(false);
  3867. this.setColour("#5fcd8e");
  3868. this.setTooltip(Blockly.Msg.ai_mphone_Record_audio_start);
  3869. this.setHelpUrl("");
  3870. }
  3871. }
  3872. Blockly.Python['ai_mphone_record_setting'] = function (block) {
  3873. var value_path = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  3874. var record_time = Blockly.Python.valueToCode(block, 'record_time', Blockly.Python.ORDER_ATOMIC);
  3875. Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio`
  3876. Blockly.Python.definitions_['v831_import_wave'] = `import wave`
  3877. Blockly.Python.definitions_['v831_import_os'] = `import os`
  3878. let code = `if(os.path.exists(${value_path})):
  3879. os.system("rm ${value_path.slice(1, value_path.length - 1)}")
  3880. CHUNK = 1024
  3881. FORMAT = pyaudio.paInt16
  3882. CHANNELS = 1
  3883. RATE = 16000
  3884. RECORD_SECONDS = ${Number(record_time) + 1}
  3885. WAVE_OUTPUT_FILENAME = ${value_path}
  3886. p = pyaudio.PyAudio()
  3887. stream = p.open(format=FORMAT,channels=CHANNELS,rate=RATE,input=True,frames_per_buffer=CHUNK)
  3888. print("* recording")
  3889. frames = []
  3890. for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
  3891. data = stream.read(CHUNK,exception_on_overflow = False)
  3892. frames.append(data)
  3893. print("* done recording")
  3894. stream.stop_stream()
  3895. stream.close()
  3896. p.terminate()
  3897. wf = wave.open(WAVE_OUTPUT_FILENAME, "wb")
  3898. wf.setnchannels(CHANNELS)
  3899. wf.setsampwidth(p.get_sample_size(FORMAT))
  3900. wf.setframerate(RATE)
  3901. wf.writeframes(b"".join(frames))
  3902. wf.close()
  3903. `
  3904. return code;
  3905. }
  3906. Blockly.Blocks['ai_mphone_Record_audio_start'] = {
  3907. init: function () {
  3908. this.appendDummyInput()
  3909. .appendField(Blockly.Msg.ai_mphone_Record_audio_start);
  3910. this.setPreviousStatement(true);
  3911. this.setNextStatement(true, null);
  3912. this.setColour("#5fcd8e");
  3913. this.setTooltip(Blockly.Msg.ai_mphone_Record_audio_start_TOOLTIP);
  3914. this.setHelpUrl("");
  3915. }
  3916. };
  3917. Blockly.Python['ai_mphone_Record_audio_start'] = function (block) {
  3918. var code = `
  3919. print("* recording")
  3920. frames = []
  3921. for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
  3922. data = stream.read(CHUNK,exception_on_overflow = False)
  3923. frames.append(data)
  3924. print("* done recording")
  3925. stream.stop_stream()
  3926. stream.close()
  3927. p.terminate()
  3928. wf = wave.open(WAVE_OUTPUT_FILENAME, "wb")
  3929. wf.setnchannels(CHANNELS)
  3930. wf.setsampwidth(p.get_sample_size(FORMAT))
  3931. wf.setframerate(RATE)
  3932. wf.writeframes(b"".join(frames))
  3933. wf.close()
  3934. `;
  3935. return code;
  3936. };
  3937. Blockly.Blocks['ai_audio_start_recording'] = {
  3938. init: function () {
  3939. this.appendDummyInput()
  3940. .appendField(Blockly.Msg.ai_audio_play_music_file);
  3941. this.appendValueInput("path")
  3942. .setCheck(null)
  3943. .appendField(Blockly.Msg.ai_audio_play_music_file_set_file_path);
  3944. this.setPreviousStatement(true, null);
  3945. this.setNextStatement(true, null);
  3946. this.setColour("#5fcd8e");
  3947. this.setTooltip(Blockly.Msg.ai_audio_stop_recording_TOOLTIP);
  3948. this.setHelpUrl("");
  3949. }
  3950. };
  3951. Blockly.Python['ai_audio_start_recording'] = function (block) {
  3952. // TODO: Assemble Python into code variable.
  3953. Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio`
  3954. Blockly.Python.definitions_['v831_import_wave'] = `import wave`
  3955. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  3956. sys.path.append("/root/")`
  3957. var code = `
  3958. CHUNK = 1024
  3959. wf = wave.open(r"test.wav", "rb")#(sys.argv[1], "rb"
  3960. p = pyaudio.PyAudio()
  3961. stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
  3962. channels=wf.getnchannels(),
  3963. rate=wf.getframerate(),
  3964. output=True)
  3965. data = wf.readframes(CHUNK)
  3966. while len(data) > 0:
  3967. stream.write(data)
  3968. data = wf.readframes(CHUNK)
  3969. stream.stop_stream()
  3970. stream.close()
  3971. p.terminate()
  3972. `;
  3973. return code;
  3974. };
  3975. /*
  3976. _ ___ _ _ _
  3977. / \ |_ _| / \ _ _ __| (_) ___
  3978. / _ \ | | / _ \| | | |/ _` | |/ _ \
  3979. / ___ \ | | / ___ \ |_| | (_| | | (_) |
  3980. /_/ \_\___| /_/ \_\__,_|\__,_|_|\___/
  3981. */
  3982. Blockly.Blocks['ai_audio_play_init'] = {
  3983. init: function () {
  3984. this.appendDummyInput()
  3985. .appendField(Blockly.Msg.AUDIO_S);
  3986. this.setPreviousStatement(true, null);
  3987. this.setNextStatement(true, null);
  3988. this.setColour("#603ea0");
  3989. this.setTooltip("");
  3990. this.setHelpUrl("");
  3991. }
  3992. };
  3993. Blockly.Python['ai_audio_play_init'] = function (block) {
  3994. Blockly.Python.definitions_['v831_import_os'] = `import os`
  3995. Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio`
  3996. Blockly.Python.definitions_['v831_import_wave'] = `import wave`
  3997. Blockly.Python.definitions_['v831_import_time'] = `import time`
  3998. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  3999. sys.path.append("/root/")`
  4000. Blockly.Python.addVariable("VOICESTATE", "VOICESTATE = 0", true)
  4001. Blockly.Python.addVariable("VOICEDATA", "", true)
  4002. Blockly.Python.addVariable("VOICESTREAM", 'VOICESTREAM = ""', true)
  4003. Blockly.Python.addVariable("VOICEPYAUDIO", "VOICEPYAUDIO = pyaudio.PyAudio()", true)
  4004. Blockly.Python.addVariable("CHUNK", "CHUNK = 1024", true)
  4005. Blockly.Python.addVariable("VOICEPPATH", "", true)
  4006. Blockly.Python.addVariable("VOICEPLAYSTATE", 'VOICEPLAYSTATE = True', true)
  4007. Blockly.Python.addVariable("VOICEWF", 'VOICEWF = ""', true)
  4008. var _code = ``;
  4009. return _code;
  4010. };
  4011. Blockly.Blocks['ai_audio_play_volume'] = {
  4012. init: function () {
  4013. this.appendDummyInput()
  4014. .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol)
  4015. .appendField(new Blockly.FieldNumber(25, 0, 100), "play_vol")
  4016. .appendField("(0~100)");
  4017. this.setPreviousStatement(true, null);
  4018. this.setNextStatement(true, null);
  4019. this.setColour("#603ea0");
  4020. this.setTooltip("");
  4021. this.setHelpUrl("");
  4022. }
  4023. };
  4024. Blockly.Python['ai_audio_play_volume'] = function (block) {
  4025. var number_play_vol = block.getFieldValue('play_vol');
  4026. Blockly.Python.definitions_['systemVoice_numberMap'] = `def voice_numberMap(value):
  4027. valueScaled = float(value - 0) / float(100)
  4028. return int(valueScaled * 31)
  4029. `
  4030. var _code = `VOICENUMP = str(voice_numberMap(${number_play_vol}))
  4031. time.sleep(0.01)
  4032. SYSTEMVOICE = "amixer cset numid=8,iface=MIXER,name=\\"LINEOUT volume\\" "+ VOICENUMP+""
  4033. `;
  4034. return _code;
  4035. };
  4036. Blockly.Blocks['ai_audio_play_song'] = {
  4037. init: function () {
  4038. this.appendValueInput("path")
  4039. .setCheck(null)
  4040. .appendField(Blockly.Msg.ai_audio_play_music_file_set_file_path)
  4041. this.appendDummyInput()
  4042. .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol)
  4043. .appendField(new Blockly.FieldNumber(25, 0, 100), "play_vol")
  4044. .appendField("(0~100)");
  4045. this.appendDummyInput()
  4046. .appendField(Blockly.Msg.ai_audio_start_play);
  4047. this.setPreviousStatement(true, null);
  4048. this.setNextStatement(true, null);
  4049. this.setColour("#603ea0");
  4050. this.setTooltip(Blockly.Msg.ai_audio_start_play);
  4051. this.setHelpUrl("");
  4052. }
  4053. };
  4054. Blockly.Python['ai_audio_play_song'] = function (block) {
  4055. var path_to_video = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  4056. var number_play_vol = block.getFieldValue('play_vol');
  4057. Blockly.Python.definitions_['v831_import_os'] = `import os`
  4058. Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio`
  4059. Blockly.Python.definitions_['v831_import_wave'] = `import wave`
  4060. Blockly.Python.definitions_['v831_import_time'] = `import time`
  4061. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  4062. sys.path.append("/root/")`
  4063. Blockly.Python.addVariable("CHUNK", "CHUNK = 1024", true)
  4064. Blockly.Python.definitions_['systemVoice_numberMap'] = `def voice_numberMap(value):
  4065. valueScaled = float(value - 0) / float(100)
  4066. return int(valueScaled * 31)
  4067. VOICENUMP = str(voice_numberMap(${number_play_vol}))
  4068. time.sleep(0.01)
  4069. SYSTEMVOICE = "amixer cset numid=8,iface=MIXER,name=\\"LINEOUT volume\\" "+ VOICENUMP+""
  4070. os.system(SYSTEMVOICE)
  4071. `
  4072. // Blockly.Python.addVariable("VOICEPPATH","",false)
  4073. var _code = `
  4074. wf = wave.open(${path_to_video}, "rb")#(sys.argv[1], "rb"
  4075. p = pyaudio.PyAudio()
  4076. stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),channels=wf.getnchannels(),rate=wf.getframerate(),output=True)
  4077. data = wf.readframes(CHUNK)
  4078. while len(data) > 0:
  4079. stream.write(data)
  4080. data = wf.readframes(CHUNK)
  4081. stream.stop_stream()
  4082. stream.close()
  4083. p.terminate()
  4084. `;
  4085. return _code;
  4086. };
  4087. Blockly.Blocks['ai_audio_play_start'] = {
  4088. init: function () {
  4089. this.appendDummyInput()
  4090. .appendField(Blockly.Msg.ai_audio_start_play);
  4091. this.setPreviousStatement(true, null);
  4092. this.setNextStatement(true, null);
  4093. this.setColour("#603ea0");
  4094. this.setTooltip(Blockly.Msg.ai_audio_start_play);
  4095. this.setHelpUrl("");
  4096. }
  4097. }
  4098. Blockly.Python['ai_audio_play_start'] = function (block) {
  4099. Blockly.Python.definitions_["VoicePlayState"] = `def VoicePlayState():
  4100. global VOICESTATE,VOICEDATA,CHUNK,VOICESTREAM,VOICEPYAUDIO,VOICEWF,VOICEPPATH
  4101. if VOICESTATE == 0:
  4102. VOICEWF = wave.open(VOICEPPATH, "rb")#(sys.argv[1], "rb"
  4103. VOICEPYAUDIO = pyaudio.PyAudio()
  4104. VOICESTREAM = VOICEPYAUDIO.open(format=VOICEPYAUDIO.get_format_from_width(VOICEWF.getsampwidth()),channels=VOICEWF.getnchannels(),rate=VOICEWF.getframerate(),output=True)
  4105. VOICEDATA = VOICEWF.readframes(CHUNK)
  4106. VOICESTATE = 1
  4107. return True
  4108. else:
  4109. if len(VOICEDATA) > 0:
  4110. try:
  4111. VOICESTREAM.write(VOICEDATA)
  4112. VOICEDATA = VOICEWF.readframes(CHUNK)
  4113. return True
  4114. except:
  4115. VOICESTATE = 0
  4116. else:
  4117. VOICESTREAM.stop_stream()
  4118. VOICESTREAM.close()
  4119. VOICEPYAUDIO.terminate()
  4120. VOICESTATE = 0
  4121. return False
  4122. `
  4123. let code = `VOICEPLAYSTATE = VoicePlayState()
  4124. `
  4125. return code;
  4126. }
  4127. Blockly.Blocks['ai_audio_play_finish'] = {
  4128. init: function () {
  4129. this.appendDummyInput()
  4130. .appendField(Blockly.Msg.ai_audio_end_play);
  4131. this.setPreviousStatement(true, null);
  4132. this.setNextStatement(true, null);
  4133. this.setColour("#603ea0");
  4134. this.setTooltip("");
  4135. this.setHelpUrl("");
  4136. }
  4137. };
  4138. Blockly.Python['ai_audio_play_finish'] = function (block) {
  4139. // TODO: Assemble Python into code variable.
  4140. var code = `try:
  4141. VOICESTREAM.stop_stream()
  4142. VOICESTREAM.close()
  4143. VOICEPYAUDIO.terminate()
  4144. VOICESTATE = 0
  4145. except:
  4146. pass
  4147. `;
  4148. return code;
  4149. };
  4150. Blockly.Blocks['ai_audio_get_play_status'] = {
  4151. init: function () {
  4152. this.appendDummyInput()
  4153. .appendField(Blockly.Msg.ai_audio_get_play_status);
  4154. this.setOutput(true, null);
  4155. this.setColour("#603ea0");
  4156. this.setTooltip(Blockly.Msg.ai_audio_play_state_speaker_TOOLTIP);
  4157. this.setHelpUrl("");
  4158. }
  4159. };
  4160. Blockly.Python['ai_audio_get_play_status'] = function (block) {
  4161. // TODO: Assemble Python into code variable.
  4162. var code = 'VOICEPLAYSTATE';
  4163. // TODO: Change ORDER_NONE to the correct strength.
  4164. return [code, Blockly.Python.ORDER_NONE];
  4165. };
  4166. // 在线语音识别
  4167. Blockly.Blocks['ai_online_voice_init'] = {
  4168. init: function () {
  4169. this.appendDummyInput()
  4170. .appendField(Blockly.Msg.online_voice_init); //
  4171. this.appendValueInput("A").setCheck(null).appendField('APP ID');
  4172. this.appendValueInput("B").setCheck(null).appendField('API Secret');
  4173. this.appendValueInput("C").setCheck(null).appendField('API Key'); //Blockly.Msg.online_voice_init_path
  4174. this.setPreviousStatement(true, null);
  4175. this.setNextStatement(true, null);
  4176. this.setColour("#0000ff");
  4177. this.setTooltip(Blockly.Msg.online_voice_init);
  4178. this.setHelpUrl("");
  4179. }
  4180. };
  4181. Blockly.Python['ai_online_voice_init'] = function (block) {
  4182. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  4183. var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  4184. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  4185. // TODO: Assemble Python into code variable.
  4186. Blockly.Python.definitions_['v831_import_time'] = `import time`
  4187. Blockly.Python.definitions_['v831_import_websocket'] = `import websocket`
  4188. Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
  4189. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  4190. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  4191. Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
  4192. Blockly.Python.definitions_['v831_import_json'] = `import json`
  4193. Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode`
  4194. Blockly.Python.definitions_['v831_import_ssl'] = `import ssl`
  4195. Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time`
  4196. Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime`
  4197. Blockly.Python.definitions_['v831_import_thread_as_thread'] = `import _thread as thread`
  4198. Blockly.Python.definitions_.ai_online_voice_init = `
  4199. STATUS_FIRST_FRAME = 0 # 第一帧的标识
  4200. STATUS_CONTINUE_FRAME = 1 # 中间帧标识
  4201. STATUS_LAST_FRAME = 2 # 最后一帧的标识
  4202. class Ws_Param_voice(object):
  4203. # 初始化
  4204. def __init__(self, APPID, APIKey, APISecret, AudioFile):
  4205. self.APPID_voice = APPID
  4206. self.APIKey_voice = APIKey
  4207. self.APISecret_voice = APISecret
  4208. self.AudioFile_voice = AudioFile
  4209. # 公共参数(common)
  4210. self.CommonArgs = {"app_id": self.APPID_voice}
  4211. # 业务参数(business),更多个性化参数可在官网查看
  4212. self.BusinessArgs = {"domain": "iat", "language": "zh_cn", "accent": "mandarin", "vinfo":1,"vad_eos":10000}
  4213. # 生成url
  4214. def create_url_voice(self):
  4215. url = "wss://ws-api.xfyun.cn/v2/iat"
  4216. # 生成RFC1123格式的时间戳
  4217. now = datetime.now()
  4218. date = format_date_time(mktime(now.timetuple()))
  4219. # 拼接字符串
  4220. signature_origin = "host: " + "ws-api.xfyun.cn" + "\\n"
  4221. signature_origin += "date: " + date + "\\n"
  4222. signature_origin += "GET " + "/v2/iat " + "HTTP/1.1"
  4223. # 进行hmac-sha256进行加密
  4224. signature_sha = hmac.new(self.APISecret_voice .encode("utf-8"), signature_origin.encode("utf-8"),
  4225. digestmod=hashlib.sha256).digest()
  4226. signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
  4227. authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (self.APIKey_voice , "hmac-sha256", "host date request-line", signature_sha)
  4228. authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8")
  4229. # 将请求的鉴权参数组合为字典
  4230. v = {
  4231. "authorization": authorization,
  4232. "date": date,
  4233. "host": "ws-api.xfyun.cn"
  4234. }
  4235. # 拼接鉴权参数,生成url
  4236. url = url + "?" + urlencode(v)
  4237. # print("date: ",date)
  4238. # print("v: ",v)
  4239. # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致
  4240. # print('websocket url :', url)
  4241. return url
  4242. # 收到websocket消息的处理
  4243. def on_message_voice(ws, message):
  4244. global asr_result,txt_result
  4245. try:
  4246. code = json.loads(message)["code"]
  4247. sid = json.loads(message)["sid"]
  4248. if code != 0:
  4249. errMsg = json.loads(message)["message"]
  4250. print("sid:%s call error:%s code is:%s" % (sid, errMsg, code))
  4251. else:
  4252. data = json.loads(message)["data"]["result"]["ws"]
  4253. # print(json.loads(message))
  4254. result = ""
  4255. for i in data:
  4256. for w in i["cw"]:
  4257. result += w["w"]
  4258. print("sid:%s call success!,data is:%s" % (sid, json.dumps(data, ensure_ascii=False)))
  4259. print("json.dumps(data, ensure_ascii=False)",eval(json.dumps(data, ensure_ascii=False)))
  4260. asr_result.append(eval(json.dumps(data, ensure_ascii=False)))
  4261. txt_result.append(eval(json.dumps(data, ensure_ascii=False)[1]))
  4262. except Exception as e:
  4263. print("receive msg,but parse exception:", e)
  4264. # 收到websocket错误的处理
  4265. def on_error_voice(ws, error):
  4266. print("### error:", error)
  4267. # 收到websocket关闭的处理
  4268. def on_close_voice(ws):
  4269. print("### closed ###")
  4270. # 收到websocket连接建立的处理
  4271. def on_open_voice(ws):
  4272. def run_voice(*args):
  4273. global wsParam_voice
  4274. frameSize = 8000 # 每一帧的音频大小
  4275. intervel = 0.04 # 发送音频间隔(单位:s)
  4276. status = STATUS_FIRST_FRAME # 音频的状态信息,标识音频是第一帧,还是中间帧、最后一帧
  4277. with open(wsParam_voice.AudioFile_voice, "rb") as fp:
  4278. while True:
  4279. buf = fp.read(frameSize)
  4280. # 文件结束
  4281. if not buf:
  4282. status = STATUS_LAST_FRAME
  4283. # 第一帧处理
  4284. # 发送第一帧音频,带business 参数
  4285. # appid 必须带上,只需第一帧发送
  4286. if status == STATUS_FIRST_FRAME:
  4287. d = {"common": wsParam_voice.CommonArgs,
  4288. "business": wsParam_voice.BusinessArgs,
  4289. "data": {"status": 0, "format": "audio/L16;rate=16000",
  4290. "audio": str(base64.b64encode(buf), "utf-8"),
  4291. "encoding": "raw"}}
  4292. d = json.dumps(d)
  4293. ws.send(d)
  4294. status = STATUS_CONTINUE_FRAME
  4295. # 中间帧处理
  4296. elif status == STATUS_CONTINUE_FRAME:
  4297. d = {"data": {"status": 1, "format": "audio/L16;rate=16000",
  4298. "audio": str(base64.b64encode(buf), "utf-8"),
  4299. "encoding": "raw"}}
  4300. ws.send(json.dumps(d))
  4301. # 最后一帧处理
  4302. elif status == STATUS_LAST_FRAME:
  4303. d = {"data": {"status": 2, "format": "audio/L16;rate=16000",
  4304. "audio": str(base64.b64encode(buf), "utf-8"),
  4305. "encoding": "raw"}}
  4306. ws.send(json.dumps(d))
  4307. time.sleep(1)
  4308. break
  4309. # 模拟音频采样间隔
  4310. time.sleep(intervel)
  4311. ws.close()
  4312. thread.start_new_thread(run_voice, ())
  4313. asr_result=[]
  4314. txt_result=[]
  4315. APPId_voice = ${APPId}
  4316. APISecret_voice = ${APISecret}
  4317. APIKey_voice = ${APIKey}
  4318. `
  4319. var code = '';
  4320. return code;
  4321. };
  4322. // 在线语音识别加载
  4323. Blockly.Blocks['ai_online_voice_loading'] = {
  4324. init: function () {
  4325. this.appendDummyInput()
  4326. .appendField(Blockly.Msg.online_voice_loading); //
  4327. this.appendValueInput("A").setCheck(null).appendField('APP ID');
  4328. this.appendValueInput("B").setCheck(null).appendField('API Secret');
  4329. this.appendValueInput("C").setCheck(null).appendField('API Key');
  4330. this.appendValueInput("path").setCheck(null).appendField(Blockly.Msg.online_voice_init_path);
  4331. this.setPreviousStatement(true, null);
  4332. this.setNextStatement(true, null);
  4333. this.setColour("#0000ff");
  4334. this.setTooltip(Blockly.Msg.online_voice_loading);
  4335. this.setHelpUrl("");
  4336. }
  4337. };
  4338. Blockly.Python['ai_online_voice_loading'] = function (block) {
  4339. var AudioFile = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  4340. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  4341. var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  4342. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  4343. // TODO: Assemble Python into code variable.
  4344. Blockly.Python.definitions_['v831_import_time'] = `import time`
  4345. Blockly.Python.definitions_['v831_import_websocket'] = `import websocket`
  4346. Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
  4347. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  4348. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  4349. Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
  4350. Blockly.Python.definitions_['v831_import_json'] = `import json`
  4351. Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode`
  4352. Blockly.Python.definitions_['v831_import_ssl'] = `import ssl`
  4353. Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time`
  4354. Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime`
  4355. Blockly.Python.definitions_['v831_import_thread_as_thread'] = `import _thread as thread`
  4356. Blockly.Python.definitions_.ai_online_voice_init = `
  4357. STATUS_FIRST_FRAME = 0 # 第一帧的标识
  4358. STATUS_CONTINUE_FRAME = 1 # 中间帧标识
  4359. STATUS_LAST_FRAME = 2 # 最后一帧的标识
  4360. class Ws_Param_voice(object):
  4361. # 初始化
  4362. def __init__(self, APPID, APIKey, APISecret, AudioFile):
  4363. self.APPID_voice = APPID
  4364. self.APIKey_voice = APIKey
  4365. self.APISecret_voice = APISecret
  4366. self.AudioFile_voice = AudioFile
  4367. # 公共参数(common)
  4368. self.CommonArgs = {"app_id": self.APPID_voice}
  4369. # 业务参数(business),更多个性化参数可在官网查看
  4370. self.BusinessArgs = {"domain": "iat", "language": "zh_cn", "accent": "mandarin", "vinfo":1,"vad_eos":10000}
  4371. # 生成url
  4372. def create_url_voice(self):
  4373. url = "wss://ws-api.xfyun.cn/v2/iat"
  4374. # 生成RFC1123格式的时间戳
  4375. now = datetime.now()
  4376. date = format_date_time(mktime(now.timetuple()))
  4377. # 拼接字符串
  4378. signature_origin = "host: " + "ws-api.xfyun.cn" + "\\n"
  4379. signature_origin += "date: " + date + "\\n"
  4380. signature_origin += "GET " + "/v2/iat " + "HTTP/1.1"
  4381. # 进行hmac-sha256进行加密
  4382. signature_sha = hmac.new(self.APISecret_voice .encode("utf-8"), signature_origin.encode("utf-8"),
  4383. digestmod=hashlib.sha256).digest()
  4384. signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
  4385. authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (self.APIKey_voice , "hmac-sha256", "host date request-line", signature_sha)
  4386. authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8")
  4387. # 将请求的鉴权参数组合为字典
  4388. v = {
  4389. "authorization": authorization,
  4390. "date": date,
  4391. "host": "ws-api.xfyun.cn"
  4392. }
  4393. # 拼接鉴权参数,生成url
  4394. url = url + "?" + urlencode(v)
  4395. # print("date: ",date)
  4396. # print("v: ",v)
  4397. # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致
  4398. # print('websocket url :', url)
  4399. return url
  4400. # 收到websocket消息的处理
  4401. def on_message_voice(ws, message):
  4402. global asr_result,txt_result
  4403. try:
  4404. code = json.loads(message)["code"]
  4405. sid = json.loads(message)["sid"]
  4406. if code != 0:
  4407. errMsg = json.loads(message)["message"]
  4408. print("sid:%s call error:%s code is:%s" % (sid, errMsg, code))
  4409. else:
  4410. data = json.loads(message)["data"]["result"]["ws"]
  4411. # print(json.loads(message))
  4412. result = ""
  4413. for i in data:
  4414. for w in i["cw"]:
  4415. result += w["w"]
  4416. print("sid:%s call success!,data is:%s" % (sid, json.dumps(data, ensure_ascii=False)))
  4417. print("json.dumps(data, ensure_ascii=False)",eval(json.dumps(data, ensure_ascii=False)))
  4418. asr_result.append(eval(json.dumps(data, ensure_ascii=False)))
  4419. txt_result.append(eval(json.dumps(data, ensure_ascii=False)[1]))
  4420. except Exception as e:
  4421. print("receive msg,but parse exception:", e)
  4422. # 收到websocket错误的处理
  4423. def on_error_voice(ws, error):
  4424. print("### error:", error)
  4425. # 收到websocket关闭的处理
  4426. def on_close_voice(ws):
  4427. print("### closed ###")
  4428. # 收到websocket连接建立的处理
  4429. def on_open_voice(ws):
  4430. def run_voice(*args):
  4431. global wsParam_voice
  4432. frameSize = 8000 # 每一帧的音频大小
  4433. intervel = 0.04 # 发送音频间隔(单位:s)
  4434. status = STATUS_FIRST_FRAME # 音频的状态信息,标识音频是第一帧,还是中间帧、最后一帧
  4435. with open(wsParam_voice.AudioFile_voice, "rb") as fp:
  4436. while True:
  4437. buf = fp.read(frameSize)
  4438. # 文件结束
  4439. if not buf:
  4440. status = STATUS_LAST_FRAME
  4441. # 第一帧处理
  4442. # 发送第一帧音频,带business 参数
  4443. # appid 必须带上,只需第一帧发送
  4444. if status == STATUS_FIRST_FRAME:
  4445. d = {"common": wsParam_voice.CommonArgs,
  4446. "business": wsParam_voice.BusinessArgs,
  4447. "data": {"status": 0, "format": "audio/L16;rate=16000",
  4448. "audio": str(base64.b64encode(buf), "utf-8"),
  4449. "encoding": "raw"}}
  4450. d = json.dumps(d)
  4451. ws.send(d)
  4452. status = STATUS_CONTINUE_FRAME
  4453. # 中间帧处理
  4454. elif status == STATUS_CONTINUE_FRAME:
  4455. d = {"data": {"status": 1, "format": "audio/L16;rate=16000",
  4456. "audio": str(base64.b64encode(buf), "utf-8"),
  4457. "encoding": "raw"}}
  4458. ws.send(json.dumps(d))
  4459. # 最后一帧处理
  4460. elif status == STATUS_LAST_FRAME:
  4461. d = {"data": {"status": 2, "format": "audio/L16;rate=16000",
  4462. "audio": str(base64.b64encode(buf), "utf-8"),
  4463. "encoding": "raw"}}
  4464. ws.send(json.dumps(d))
  4465. time.sleep(1)
  4466. break
  4467. # 模拟音频采样间隔
  4468. time.sleep(intervel)
  4469. ws.close()
  4470. thread.start_new_thread(run_voice, ())
  4471. asr_result=[]
  4472. txt_result=[]
  4473. APPId_voice = ${APPId}
  4474. APISecret_voice = ${APISecret}
  4475. APIKey_voice = ${APIKey}
  4476. `
  4477. Blockly.Python.definitions_['get_online_voice_data'] = `asr_string=""
  4478. def getVoiceData():
  4479. global wsParam_voice,asr_string,txt_result,asr_result
  4480. # 测试时候在此处正确填写相关信息即可运行
  4481. asr_string = ""
  4482. txt_result = []
  4483. asr_result = []
  4484. time1 = datetime.now()
  4485. wsParam_voice = Ws_Param_voice(APPID=APPId_voice, APISecret=APISecret_voice,
  4486. APIKey=APIKey_voice,
  4487. AudioFile=${AudioFile})
  4488. websocket.enableTrace(False)
  4489. wsUrl = wsParam_voice.create_url_voice()
  4490. ws = websocket.WebSocketApp(wsUrl, on_message=on_message_voice, on_error=on_error_voice)
  4491. ws.on_open = on_open_voice
  4492. ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
  4493. time2 = datetime.now()
  4494. for i in range(len(asr_result)):
  4495. for j in range(len(asr_result[i])):
  4496. txt_result.append(asr_result[i][j]["cw"][0]["w"])
  4497. print("txt_result:", txt_result)
  4498. for i in range(len(txt_result)):
  4499. asr_string=asr_string+txt_result[i]
  4500. print("asr_string:", asr_string)
  4501. return asr_string
  4502. `
  4503. let code = `VoiceResult = getVoiceData()
  4504. `;
  4505. return code;
  4506. };
  4507. Blockly.Blocks['ai_online_voice_result'] = {
  4508. init: function () {
  4509. this.appendDummyInput()
  4510. .appendField(Blockly.Msg.online_voice_result); //
  4511. this.setOutput(true, null);
  4512. this.setColour("#0000ff");
  4513. this.setTooltip(Blockly.Msg.online_voice_result);
  4514. this.setHelpUrl("");
  4515. }
  4516. };
  4517. Blockly.Python['ai_online_voice_result'] = function (block) {
  4518. let code = `VoiceResult`;
  4519. return [code, Blockly.Python.ORDER_ATOMIC];
  4520. };
  4521. // 在线人脸识别
  4522. Blockly.Blocks['ai_online_ident_init'] = {
  4523. init: function () {
  4524. this.appendDummyInput()
  4525. .appendField(Blockly.Msg.online_face_init); //
  4526. this.appendValueInput("A").setCheck(null).appendField('APP ID');
  4527. this.appendValueInput("B").setCheck(null).appendField('API Secret');
  4528. this.appendValueInput("C").setCheck(null).appendField('API Key');
  4529. this.setPreviousStatement(true, null);
  4530. this.setNextStatement(true, null);
  4531. this.setColour("#0000ff");
  4532. this.setTooltip(Blockly.Msg.online_face_init);
  4533. this.setHelpUrl("");
  4534. }
  4535. };
  4536. Blockly.Python['ai_online_ident_init'] = function (block) {
  4537. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  4538. var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  4539. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  4540. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  4541. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  4542. Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
  4543. Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime`
  4544. Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
  4545. Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time`
  4546. Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode`
  4547. Blockly.Python.definitions_['v831_import_os'] = `import os`
  4548. Blockly.Python.definitions_['v831_import_traceback'] = `import traceback`
  4549. Blockly.Python.definitions_['v831_import_json'] = `import json`
  4550. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  4551. Blockly.Python.definitions_.ai_online_ident_init = `
  4552. class AssembleHeaderException(Exception):
  4553. def __init__(self, msg):
  4554. self.message = msg
  4555. class Url:
  4556. def __init__(this, host, path, schema):
  4557. this.host = host
  4558. this.path = path
  4559. this.schema = schema
  4560. pass
  4561. # 进行sha256加密和base64编码
  4562. def sha256base64(data):
  4563. sha256 = hashlib.sha256()
  4564. sha256.update(data)
  4565. digest = base64.b64encode(sha256.digest()).decode(encoding="utf-8")
  4566. return digest
  4567. def parse_url_face(requset_url):
  4568. stidx = requset_url.index("://")
  4569. host = requset_url[stidx + 3:]
  4570. schema = requset_url[:stidx + 3]
  4571. edidx = host.index("/")
  4572. if edidx <= 0:
  4573. raise AssembleHeaderException("invalid request url:" + requset_url)
  4574. path = host[edidx:]
  4575. host = host[:edidx]
  4576. u = Url(host, path, schema)
  4577. return u
  4578. def assemble_ws_auth_url_face(requset_url, method="GET", api_key="", api_secret=""):
  4579. u = parse_url_face(requset_url)
  4580. host = u.host
  4581. path = u.path
  4582. now = datetime.now()
  4583. date = format_date_time(mktime(now.timetuple()))
  4584. print(date)
  4585. # date = "Thu, 12 Dec 2019 01:57:27 GMT"
  4586. signature_origin = "host: {}\\ndate: {}\\n{} {} HTTP/1.1".format(host, date, method, path)
  4587. print(signature_origin)
  4588. signature_sha = hmac.new(api_secret.encode("utf-8"), signature_origin.encode("utf-8"),
  4589. digestmod=hashlib.sha256).digest()
  4590. signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
  4591. authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (
  4592. api_key, "hmac-sha256", "host date request-line", signature_sha)
  4593. authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8")
  4594. print(authorization_origin)
  4595. values = {
  4596. "host": host,
  4597. "date": date,
  4598. "authorization": authorization
  4599. }
  4600. return requset_url + "?" + urlencode(values)
  4601. def gen_body_face(appid, img_path, server_id):
  4602. with open(img_path, "rb") as f:
  4603. img_data = f.read()
  4604. body = {
  4605. "header": {
  4606. "app_id": appid,
  4607. "status": 3
  4608. },
  4609. "parameter": {
  4610. server_id: {
  4611. "service_kind": "face_detect",
  4612. #"detect_points": "1", #检测特征点
  4613. #"detect_property": "1", #检测人脸属性
  4614. "face_detect_result": {
  4615. "encoding": "utf8",
  4616. "compress": "raw",
  4617. "format": "json"
  4618. }
  4619. }
  4620. },
  4621. "payload": {
  4622. "input1": {
  4623. "encoding": "jpg",
  4624. "status": 3,
  4625. "image": str(base64.b64encode(img_data), "utf-8")
  4626. }
  4627. }
  4628. }
  4629. return json.dumps(body)
  4630. APPId_face = ${APPId}
  4631. APISecret_face = ${APISecret}
  4632. APIKey_face = ${APIKey}
  4633. `;
  4634. let code = ''
  4635. return code;
  4636. };
  4637. // 在线人脸识别加载
  4638. Blockly.Blocks['ai_online_ident_loading'] = {
  4639. init: function () {
  4640. this.appendDummyInput()
  4641. .appendField(Blockly.Msg.online_face_loading); //
  4642. this.appendValueInput("A").setCheck(null).appendField('APP ID');
  4643. this.appendValueInput("B").setCheck(null).appendField('API Secret');
  4644. this.appendValueInput("C").setCheck(null).appendField('API Key');
  4645. this.appendValueInput("path")
  4646. .setCheck(null)
  4647. .appendField(Blockly.Msg.online_face_init_path); //
  4648. this.setPreviousStatement(true, null);
  4649. this.setNextStatement(true, null);
  4650. this.setColour("#0000ff");
  4651. this.setTooltip(Blockly.Msg.online_face_loading);
  4652. this.setHelpUrl("");
  4653. }
  4654. };
  4655. Blockly.Python['ai_online_ident_loading'] = function (block) {
  4656. var path = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  4657. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  4658. var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  4659. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  4660. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  4661. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  4662. Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
  4663. Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime`
  4664. Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
  4665. Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time`
  4666. Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode`
  4667. Blockly.Python.definitions_['v831_import_os'] = `import os`
  4668. Blockly.Python.definitions_['v831_import_traceback'] = `import traceback`
  4669. Blockly.Python.definitions_['v831_import_json'] = `import json`
  4670. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  4671. Blockly.Python.definitions_.ai_online_ident_init = `
  4672. class AssembleHeaderException(Exception):
  4673. def __init__(self, msg):
  4674. self.message = msg
  4675. class Url:
  4676. def __init__(this, host, path, schema):
  4677. this.host = host
  4678. this.path = path
  4679. this.schema = schema
  4680. pass
  4681. # 进行sha256加密和base64编码
  4682. def sha256base64(data):
  4683. sha256 = hashlib.sha256()
  4684. sha256.update(data)
  4685. digest = base64.b64encode(sha256.digest()).decode(encoding="utf-8")
  4686. return digest
  4687. def parse_url_face(requset_url):
  4688. stidx = requset_url.index("://")
  4689. host = requset_url[stidx + 3:]
  4690. schema = requset_url[:stidx + 3]
  4691. edidx = host.index("/")
  4692. if edidx <= 0:
  4693. raise AssembleHeaderException("invalid request url:" + requset_url)
  4694. path = host[edidx:]
  4695. host = host[:edidx]
  4696. u = Url(host, path, schema)
  4697. return u
  4698. def assemble_ws_auth_url_face(requset_url, method="GET", api_key="", api_secret=""):
  4699. u = parse_url_face(requset_url)
  4700. host = u.host
  4701. path = u.path
  4702. now = datetime.now()
  4703. date = format_date_time(mktime(now.timetuple()))
  4704. print(date)
  4705. # date = "Thu, 12 Dec 2019 01:57:27 GMT"
  4706. signature_origin = "host: {}\\ndate: {}\\n{} {} HTTP/1.1".format(host, date, method, path)
  4707. print(signature_origin)
  4708. signature_sha = hmac.new(api_secret.encode("utf-8"), signature_origin.encode("utf-8"),
  4709. digestmod=hashlib.sha256).digest()
  4710. signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
  4711. authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (
  4712. api_key, "hmac-sha256", "host date request-line", signature_sha)
  4713. authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8")
  4714. print(authorization_origin)
  4715. values = {
  4716. "host": host,
  4717. "date": date,
  4718. "authorization": authorization
  4719. }
  4720. return requset_url + "?" + urlencode(values)
  4721. def gen_body_face(appid, img_path, server_id):
  4722. with open(img_path, "rb") as f:
  4723. img_data = f.read()
  4724. body = {
  4725. "header": {
  4726. "app_id": appid,
  4727. "status": 3
  4728. },
  4729. "parameter": {
  4730. server_id: {
  4731. "service_kind": "face_detect",
  4732. #"detect_points": "1", #检测特征点
  4733. #"detect_property": "1", #检测人脸属性
  4734. "face_detect_result": {
  4735. "encoding": "utf8",
  4736. "compress": "raw",
  4737. "format": "json"
  4738. }
  4739. }
  4740. },
  4741. "payload": {
  4742. "input1": {
  4743. "encoding": "jpg",
  4744. "status": 3,
  4745. "image": str(base64.b64encode(img_data), "utf-8")
  4746. }
  4747. }
  4748. }
  4749. return json.dumps(body)
  4750. APPId_face = ${APPId}
  4751. APISecret_face = ${APISecret}
  4752. APIKey_face = ${APIKey}
  4753. `;
  4754. Blockly.Python.definitions_.online_ident = `
  4755. ONLINE_IDENT_DATA = ""
  4756. def run_face(appid, apikey, apisecret, img_path, server_id="s67c9c78c"):
  4757. url = "http://api.xf-yun.com/v1/private/{}".format(server_id)
  4758. request_url = assemble_ws_auth_url_face(url, "POST", apikey, apisecret)
  4759. headers = {"content-type": "application/json", "host": "api.xf-yun.com", "app_id": appid}
  4760. print(request_url)
  4761. response = requests.post(request_url, data=gen_body_face(appid, img_path, server_id), headers=headers)
  4762. resp_data = json.loads(response.content.decode("utf-8"))
  4763. print(resp_data)
  4764. picRes=base64.b64decode(resp_data["payload"]["face_detect_result"]["text"]).decode()
  4765. print(picRes)
  4766. with open("/root/pic0.txt","w") as f:
  4767. f.write(picRes)
  4768. return eval(picRes)
  4769. `
  4770. let code = `
  4771. if __name__ == "__main__":
  4772. img_path_face = ${path}
  4773. ONLINE_IDENT_DATA = run_face(appid=APPId_face,apisecret=APISecret_face,apikey=APIKey_face,img_path=img_path_face,)
  4774. `;
  4775. return code;
  4776. };
  4777. // 在线人脸识别结果
  4778. Blockly.Blocks['ai_online_ident_result'] = {
  4779. init: function () {
  4780. this.appendDummyInput()
  4781. .appendField(Blockly.Msg.online_face_result); //
  4782. this.setOutput(true, null);
  4783. this.setColour("#0000ff");
  4784. this.setTooltip(Blockly.Msg.online_face_result);
  4785. this.setHelpUrl("");
  4786. }
  4787. };
  4788. Blockly.Python['ai_online_ident_result'] = function (block) {
  4789. let code = `ONLINE_IDENT_DATA["face_num"]`;
  4790. return [code, Blockly.Python.ORDER_ATOMIC];
  4791. };
  4792. Blockly.Blocks['ai_online_ident_result_people'] = {
  4793. init: function () {
  4794. this.appendDummyInput()
  4795. .appendField(Blockly.Msg.serialcomm_write_item_first)
  4796. .appendField(new Blockly.FieldVariable("i"), "varitem")
  4797. .appendField(Blockly.Msg.face_information)
  4798. .appendField(new Blockly.FieldDropdown([
  4799. [Blockly.Msg.ai_models_object_model_x, "x"],
  4800. [Blockly.Msg.ai_models_object_model_y, "y"],
  4801. [Blockly.Msg.ai_models_object_model_w, "w"],
  4802. [Blockly.Msg.ai_models_object_model_h, "h"],
  4803. // ['人脸属性信息', "property"],
  4804. [Blockly.Msg.ai_models_object_model_confidence, "score"]
  4805. ]), "TYPE");
  4806. this.setOutput(true, null);
  4807. this.setColour("#0000ff");
  4808. this.setTooltip('');
  4809. this.setHelpUrl("");
  4810. }
  4811. }
  4812. Blockly.Python['ai_online_ident_result_people'] = function (block) {
  4813. var type = block.getFieldValue('TYPE');
  4814. var i = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  4815. let code = '';
  4816. if (type == "w") {
  4817. code = `ONLINE_IDENT_DATA.get('face_'+str(${i})).get('${type}') + ONLINE_IDENT_DATA.get('face_'+str(${i})).get('x')`
  4818. } else if (type == "h") {
  4819. code = `ONLINE_IDENT_DATA.get('face_'+str(${i})).get('${type}') + ONLINE_IDENT_DATA.get('face_'+str(${i})).get('y')`
  4820. } else {
  4821. code = `ONLINE_IDENT_DATA.get('face_'+str(${i})).get('${type}')`
  4822. }
  4823. return [code, Blockly.Python.ORDER_ATOMIC];
  4824. };
  4825. Blockly.Blocks['ai_audio_init'] = {
  4826. init: function () {
  4827. this.appendDummyInput()
  4828. .appendField(new Blockly.FieldImage("blockly/media/speaker_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  4829. this.appendDummyInput()
  4830. .appendField(Blockly.Msg.Text_to_speech_initialization); //
  4831. this.appendValueInput("A")
  4832. .setCheck(null)
  4833. .appendField('APP ID');
  4834. this.appendValueInput("B")
  4835. .setCheck(null)
  4836. .appendField('API Secret');
  4837. this.appendValueInput("C")
  4838. .setCheck(null)
  4839. .appendField('API Key');
  4840. this.setPreviousStatement(true, null);
  4841. this.setNextStatement(true, null);
  4842. this.setColour("#0000ff");
  4843. this.setTooltip(Blockly.Msg.Text_to_speech_initialization);
  4844. this.setHelpUrl("");
  4845. }
  4846. };
  4847. // 在线文本转语音初始化
  4848. Blockly.Python.ai_audio_init = function (block) {
  4849. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  4850. var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  4851. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  4852. Blockly.Python.definitions_['v831_import_time'] = `import time`
  4853. Blockly.Python.definitions_['v831_import_os'] = `import os`
  4854. Blockly.Python.definitions_['v831_import_json'] = `import json`
  4855. Blockly.Python.definitions_['v831_import_wave'] = `import wave`
  4856. Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode`
  4857. Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time`
  4858. Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime`
  4859. Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
  4860. // Blockly.Python.definitions_['v831_import_datetime'] = `import datetime`
  4861. Blockly.Python.definitions_['v831_import_websocket'] = `import websocket`
  4862. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  4863. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  4864. Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
  4865. Blockly.Python.definitions_['v831_import_ssl'] = `import ssl`
  4866. Blockly.Python.definitions_['v831_import_thread_as_thread'] = `import _thread as thread`
  4867. Blockly.Python.definitions_.ai_audio_init_function = `
  4868. STATUS_FIRST_FRAME = 0 # 第一帧的标识
  4869. STATUS_CONTINUE_FRAME = 1 # 中间帧标识
  4870. STATUS_LAST_FRAME = 2 # 最后一帧的标识
  4871. class Ws_Param_Audio(object):
  4872. # 初始化
  4873. def __init__(self, APPID, APIKey, APISecret, Text):
  4874. self.APPID = APPID
  4875. self.APIKey = APIKey
  4876. self.APISecret = APISecret
  4877. self.Text = Text
  4878. # 公共参数(common)
  4879. self.CommonArgs = {"app_id": self.APPID}
  4880. # 业务参数(business),更多个性化参数可在官网查看
  4881. self.BusinessArgs = {"aue": "raw", "auf": "audio/L16;rate=16000", "vcn": "xiaoyan", "tte": "utf8"}
  4882. self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode("utf-8")), "UTF8")}
  4883. #使用小语种须使用以下方式,此处的unicode指的是 utf16小端的编码方式,即"UTF-16LE"”
  4884. #self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode('utf-16')), "UTF8")}
  4885. # 生成url
  4886. def create_url(self):
  4887. url = "wss://tts-api.xfyun.cn/v2/tts"
  4888. # 生成RFC1123格式的时间戳
  4889. now = datetime.now()
  4890. date = format_date_time(mktime(now.timetuple()))
  4891. # 拼接字符串
  4892. signature_origin = "host: " + "ws-api.xfyun.cn" + "\\n"
  4893. signature_origin += "date: " + date + "\\n"
  4894. signature_origin += "GET " + "/v2/tts " + "HTTP/1.1"
  4895. # 进行hmac-sha256进行加密
  4896. signature_sha = hmac.new(self.APISecret.encode("utf-8"), signature_origin.encode("utf-8"),digestmod=hashlib.sha256).digest()
  4897. signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
  4898. authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (self.APIKey, "hmac-sha256", "host date request-line", signature_sha)
  4899. authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8")
  4900. # 将请求的鉴权参数组合为字典
  4901. v = {
  4902. "authorization": authorization,
  4903. "date": date,
  4904. "host": "ws-api.xfyun.cn"
  4905. }
  4906. # 拼接鉴权参数,生成url
  4907. url = url + "?" + urlencode(v)
  4908. # print("date: ",date)
  4909. # print("v: ",v)
  4910. # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致
  4911. # print('websocket url :', url)
  4912. return url
  4913. APPId_Audio = ${APPId}
  4914. APISecret_Audio = ${APISecret}
  4915. APIKey_Audio = ${APIKey}
  4916. `;
  4917. var _code = "";
  4918. return _code;
  4919. }
  4920. Blockly.Blocks['ai_audio_play_state'] = {
  4921. init: function () {
  4922. this.appendDummyInput()
  4923. .appendField(Blockly.Msg.text_conversion_voice); //
  4924. this.appendValueInput("A")
  4925. .setCheck(null)
  4926. .appendField('APP ID');
  4927. this.appendValueInput("B")
  4928. .setCheck(null)
  4929. .appendField('API Secret');
  4930. this.appendValueInput("C")
  4931. .setCheck(null)
  4932. .appendField('API Key');
  4933. this.appendValueInput("NAME")
  4934. .setCheck(null)
  4935. .appendField(Blockly.Msg.Content_of_text); //
  4936. this.appendValueInput("path")
  4937. .setCheck(null)
  4938. .appendField(Blockly.Msg.Voice_path); //
  4939. this.setPreviousStatement(true, null);
  4940. this.setNextStatement(true, null);
  4941. this.setColour("#0000ff");
  4942. this.setTooltip(Blockly.Msg.text_conversion_voice);
  4943. this.setHelpUrl("");
  4944. }
  4945. };
  4946. Blockly.Python['ai_audio_play_state'] = function (block) {
  4947. // TODO: Assemble Python into code variable.
  4948. let text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC)
  4949. let url = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC)
  4950. let path = `${url.slice(1, url.length - 1)}`
  4951. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  4952. var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  4953. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  4954. Blockly.Python.definitions_['v831_import_time'] = `import time`
  4955. Blockly.Python.definitions_['v831_import_os'] = `import os`
  4956. Blockly.Python.definitions_['v831_import_json'] = `import json`
  4957. Blockly.Python.definitions_['v831_import_wave'] = `import wave`
  4958. Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode`
  4959. Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time`
  4960. Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime`
  4961. Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
  4962. // Blockly.Python.definitions_['v831_import_datetime'] = `import datetime`
  4963. Blockly.Python.definitions_['v831_import_websocket'] = `import websocket`
  4964. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  4965. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  4966. Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
  4967. Blockly.Python.definitions_['v831_import_ssl'] = `import ssl`
  4968. Blockly.Python.definitions_['v831_import_thread_as_thread'] = `import _thread as thread`
  4969. Blockly.Python.definitions_.ai_audio_init_function = `
  4970. STATUS_FIRST_FRAME = 0 # 第一帧的标识
  4971. STATUS_CONTINUE_FRAME = 1 # 中间帧标识
  4972. STATUS_LAST_FRAME = 2 # 最后一帧的标识
  4973. class Ws_Param_Audio(object):
  4974. # 初始化
  4975. def __init__(self, APPID, APIKey, APISecret, Text):
  4976. self.APPID = APPID
  4977. self.APIKey = APIKey
  4978. self.APISecret = APISecret
  4979. self.Text = Text
  4980. # 公共参数(common)
  4981. self.CommonArgs = {"app_id": self.APPID}
  4982. # 业务参数(business),更多个性化参数可在官网查看
  4983. self.BusinessArgs = {"aue": "raw", "auf": "audio/L16;rate=16000", "vcn": "xiaoyan", "tte": "utf8"}
  4984. self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode("utf-8")), "UTF8")}
  4985. #使用小语种须使用以下方式,此处的unicode指的是 utf16小端的编码方式,即"UTF-16LE"”
  4986. #self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode('utf-16')), "UTF8")}
  4987. # 生成url
  4988. def create_url(self):
  4989. url = "wss://tts-api.xfyun.cn/v2/tts"
  4990. # 生成RFC1123格式的时间戳
  4991. now = datetime.now()
  4992. date = format_date_time(mktime(now.timetuple()))
  4993. # 拼接字符串
  4994. signature_origin = "host: " + "ws-api.xfyun.cn" + "\\n"
  4995. signature_origin += "date: " + date + "\\n"
  4996. signature_origin += "GET " + "/v2/tts " + "HTTP/1.1"
  4997. # 进行hmac-sha256进行加密
  4998. signature_sha = hmac.new(self.APISecret.encode("utf-8"), signature_origin.encode("utf-8"),digestmod=hashlib.sha256).digest()
  4999. signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
  5000. authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (self.APIKey, "hmac-sha256", "host date request-line", signature_sha)
  5001. authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8")
  5002. # 将请求的鉴权参数组合为字典
  5003. v = {
  5004. "authorization": authorization,
  5005. "date": date,
  5006. "host": "ws-api.xfyun.cn"
  5007. }
  5008. # 拼接鉴权参数,生成url
  5009. url = url + "?" + urlencode(v)
  5010. # print("date: ",date)
  5011. # print("v: ",v)
  5012. # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致
  5013. # print('websocket url :', url)
  5014. return url
  5015. APPId_Audio = ${APPId}
  5016. APISecret_Audio = ${APISecret}
  5017. APIKey_Audio = ${APIKey}
  5018. `;
  5019. Blockly.Python.definitions_.on_message = `
  5020. def on_message(ws, message):
  5021. try:
  5022. message =json.loads(message)
  5023. code = message["code"]
  5024. sid = message["sid"]
  5025. audio = message["data"]["audio"]
  5026. audio = base64.b64decode(audio)
  5027. status = message["data"]["status"]
  5028. #print(message)
  5029. if status == 2:
  5030. print("ws is closed")
  5031. ws.close()
  5032. if code != 0:
  5033. errMsg = message["message"]
  5034. print("sid:%s call error:%s code is:%s" % (sid, errMsg, code))
  5035. else:
  5036. pcm_path = "${path}"
  5037. with open(pcm_path, "ab") as f:
  5038. f.write(audio)
  5039. print("tts")
  5040. with open(pcm_path, "rb") as pcmfile:
  5041. pcmdata = pcmfile.read()
  5042. with wave.open(pcm_path + ".wav", "wb") as wavfile:
  5043. wavfile.setparams((1, 2, 16000, 0, "NONE", "NONE"))
  5044. wavfile.writeframes(pcmdata)
  5045. except Exception as e:
  5046. print("receive msg,but parse exception:", e)
  5047. # 收到websocket错误的处理
  5048. def on_error(ws, error):
  5049. print("### error:", error)
  5050. # 收到websocket关闭的处理
  5051. def on_close(ws):
  5052. print("### closed ###")
  5053. # 收到websocket连接建立的处理
  5054. def on_open(ws):
  5055. def run(*args):
  5056. global wsParam_Audio
  5057. d = {"common": wsParam_Audio.CommonArgs,"business": wsParam_Audio.BusinessArgs,"data": wsParam_Audio.Data,}
  5058. d = json.dumps(d)
  5059. print("------>开始发送文本数据")
  5060. ws.send(d)
  5061. if os.path.exists(${url}):
  5062. os.remove(${url})
  5063. thread.start_new_thread(run, ())
  5064. `
  5065. Blockly.Python.addVariable('wsParam_Audio', 'wsParam_Audio = ""', true);
  5066. let code = `if __name__ == "__main__":
  5067. #with open('word.txt', 'r',encoding="UTF-8")as f:#txt= f.read()
  5068. txt_Audio=${text}
  5069. if os.path.exists(${url}):
  5070. os.remove(${url})
  5071. # 测试时候在此处正确填写相关信息即可运行
  5072. wsParam_Audio = Ws_Param_Audio(APPID=APPId_Audio, APISecret=APISecret_Audio,APIKey=APIKey_Audio,Text=txt_Audio)
  5073. websocket.enableTrace(False)
  5074. wsUrl = wsParam_Audio.create_url()
  5075. ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close)
  5076. ws.on_open = on_open
  5077. ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
  5078. `
  5079. // TODO: Change ORDER_NONE to the correct strength.
  5080. return code
  5081. };
  5082. // 在线物体识别
  5083. Blockly.Blocks['ai_online_object_init'] = {
  5084. init: function () {
  5085. this.appendDummyInput()
  5086. .appendField(Blockly.Msg.online_object_init); //
  5087. this.appendValueInput("A").setCheck(null).appendField('APP ID');
  5088. // this.appendValueInput("B").setCheck(null).appendField('APISecret');
  5089. this.appendValueInput("C").setCheck(null).appendField('API Key'); //Blockly.Msg.online_voice_init_path
  5090. this.setPreviousStatement(true, null);
  5091. this.setNextStatement(true, null);
  5092. this.setColour("#0000ff");
  5093. this.setTooltip(Blockly.Msg.online_object_init);
  5094. this.setHelpUrl("");
  5095. }
  5096. };
  5097. Blockly.Python['ai_online_object_init'] = function (block) {
  5098. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  5099. var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  5100. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  5101. // TODO: Assemble Python into code variable.
  5102. Blockly.Python.definitions_['v831_import_time'] = `import time`
  5103. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  5104. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  5105. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  5106. Blockly.Python.definitions_.ai_online_object_init = `
  5107. API_KEY = ${APIKey}
  5108. APPID = ${APPId}
  5109. def objectGetHeader(APPID, image_url, API_KEY):
  5110. with open(image_url, "rb") as f:
  5111. img_data = f.read()
  5112. curTime = str(int(time.time()))
  5113. paramBase64 = base64.b64encode(img_data)
  5114. tmp = str(paramBase64, "utf-8")
  5115. m2 = hashlib.md5()
  5116. m2.update((API_KEY + curTime + tmp).encode("utf-8"))
  5117. checkSum = m2.hexdigest()
  5118. header = {
  5119. 'X-CurTime': curTime,
  5120. 'X-Param': paramBase64,
  5121. 'X-Appid': APPID,
  5122. 'X-CheckSum': checkSum,
  5123. }
  5124. return header
  5125. `
  5126. var code = '';
  5127. return code;
  5128. };
  5129. Blockly.Blocks['ai_online_object_loading'] = {
  5130. init: function () {
  5131. this.appendDummyInput()
  5132. .appendField(Blockly.Msg.online_object_load); //
  5133. this.appendValueInput("path").setCheck(null).appendField(Blockly.Msg.online_face_init_path);
  5134. this.setPreviousStatement(true, null);
  5135. this.setNextStatement(true, null);
  5136. this.setColour("#0000ff");
  5137. this.setTooltip(Blockly.Msg.online_object_load);
  5138. this.setHelpUrl("");
  5139. }
  5140. }
  5141. Blockly.Python.ai_online_object_loading = function (block) {
  5142. var AudioFile = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  5143. let code = `ImageUrl = ${AudioFile}
  5144. OBJECTRESULT = requests.post("http://tupapi.xfyun.cn/v1/currency", headers=objectGetHeader(APPID, ImageUrl,API_KEY))
  5145. `
  5146. return code
  5147. }
  5148. Blockly.Blocks['ai_online_object_result'] = {
  5149. init: function () {
  5150. this.appendDummyInput()
  5151. .appendField(Blockly.Msg.online_object_result); //
  5152. this.setOutput(true, null);
  5153. this.setColour("#0000ff");
  5154. this.setTooltip(Blockly.Msg.online_object_result);
  5155. this.setHelpUrl("");
  5156. }
  5157. };
  5158. Blockly.Python['ai_online_object_result'] = function (block) {
  5159. let code = `OBJECTRESULT.content`;
  5160. return [code, Blockly.Python.ORDER_ATOMIC];
  5161. };
  5162. // 在线车牌识别
  5163. Blockly.Blocks['ai_online_card_init'] = {
  5164. init: function () {
  5165. this.appendDummyInput()
  5166. .appendField(Blockly.Msg.online_card_init); //
  5167. this.appendValueInput("A").setCheck(null).appendField('APP ID');
  5168. this.appendValueInput("B").setCheck(null).appendField('API Secret');
  5169. this.appendValueInput("C").setCheck(null).appendField('API Key'); //Blockly.Msg.online_voice_init_path
  5170. this.setPreviousStatement(true, null);
  5171. this.setNextStatement(true, null);
  5172. this.setColour("#0000ff");
  5173. this.setTooltip(Blockly.Msg.online_card_init);
  5174. this.setHelpUrl("");
  5175. }
  5176. };
  5177. Blockly.Python['ai_online_card_init'] = function (block) {
  5178. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  5179. var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  5180. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  5181. // TODO: Assemble Python into code variable.
  5182. Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode`
  5183. Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time`
  5184. Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime`
  5185. Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
  5186. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  5187. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  5188. Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
  5189. Blockly.Python.definitions_['v831_import_traceback'] = `import traceback`
  5190. Blockly.Python.definitions_['v831_import_json'] = `import json`
  5191. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  5192. Blockly.Python.definitions_.ai_online_card_init = `
  5193. APPId_Card = ${APPId}
  5194. APISecret_Card = ${APISecret}
  5195. APIKey_Card = ${APIKey}
  5196. class AssembleHeaderException_Card(Exception):
  5197. def __init__(self, msg):
  5198. self.message = msg
  5199. class Url_Card:
  5200. def __init__(this, host, path, schema):
  5201. this.host = host
  5202. this.path = path
  5203. this.schema = schema
  5204. pass
  5205. # 进行sha256加密和base64编码
  5206. def sha256base64_Card(data):
  5207. sha256 = hashlib.sha256()
  5208. sha256.update(data)
  5209. digest = base64.b64encode(sha256.digest()).decode(encoding="utf-8")
  5210. return digest
  5211. def parse_url_Card(requset_url):
  5212. stidx = requset_url.index("://")
  5213. host = requset_url[stidx + 3:]
  5214. schema = requset_url[:stidx + 3]
  5215. edidx = host.index("/")
  5216. if edidx <= 0:
  5217. raise AssembleHeaderException_Card("invalid request url:" + requset_url)
  5218. path = host[edidx:]
  5219. host = host[:edidx]
  5220. u = Url_Card(host, path, schema)
  5221. return u
  5222. def assemble_ws_auth_url_Card(requset_url, method="GET", api_key="", api_secret=""):
  5223. u = parse_url_Card(requset_url)
  5224. host = u.host
  5225. path = u.path
  5226. now = datetime.now()
  5227. date = format_date_time(mktime(now.timetuple()))
  5228. print(date)
  5229. # date = "Thu, 12 Dec 2019 01:57:27 GMT"
  5230. signature_origin = "host: {}\\ndate: {}\\n{} {} HTTP/1.1".format(host, date, method, path)
  5231. print(signature_origin)
  5232. signature_sha = hmac.new(api_secret.encode("utf-8"), signature_origin.encode("utf-8"),
  5233. digestmod=hashlib.sha256).digest()
  5234. signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
  5235. authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (
  5236. api_key, "hmac-sha256", "host date request-line", signature_sha)
  5237. authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8")
  5238. print(authorization_origin)
  5239. values = {
  5240. "host": host,
  5241. "date": date,
  5242. "authorization": authorization
  5243. }
  5244. return requset_url + "?" + urlencode(values)
  5245. def gen_body_Card(appid, img_path, server_id):
  5246. with open(img_path, "rb") as f:
  5247. img_data = f.read()
  5248. body = {
  5249. "header": {
  5250. "app_id": appid,
  5251. "status": 3
  5252. },
  5253. "parameter": {
  5254. server_id: {
  5255. "carLicenseRes": {
  5256. "encoding": "utf8",
  5257. "compress": "raw",
  5258. "format": "json"
  5259. }
  5260. }
  5261. },
  5262. "payload": {
  5263. "carImgBase64Str": {
  5264. "encoding": "jpg",
  5265. "status": 3,
  5266. "image": str(base64.b64encode(img_data), "utf-8")
  5267. }
  5268. }
  5269. }
  5270. return json.dumps(body)
  5271. `
  5272. var code = '';
  5273. return code;
  5274. };
  5275. Blockly.Blocks['ai_online_card_loading'] = {
  5276. init: function () {
  5277. this.appendDummyInput()
  5278. .appendField(Blockly.Msg.online_card_load); //
  5279. this.appendValueInput("path").setCheck(null).appendField(Blockly.Msg.online_face_init_path);
  5280. this.setPreviousStatement(true, null);
  5281. this.setNextStatement(true, null);
  5282. this.setColour("#0000ff");
  5283. this.setTooltip(Blockly.Msg.online_card_load);
  5284. this.setHelpUrl("");
  5285. }
  5286. }
  5287. Blockly.Python.ai_online_card_loading = function (block) {
  5288. var AudioFile = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  5289. Blockly.Python.definitions_.ai_online_card_load = `def run_Card(appid, apikey, apisecret, img_path, server_id="jd_ocr_car"):
  5290. url = "http://api.xf-yun.com/v1/private/{}".format(server_id)
  5291. request_url = assemble_ws_auth_url_Card(url, "POST", apikey, apisecret)
  5292. headers = {"content-type": "application/json", "host": "api.xf-yun.com", "app_id": appid}
  5293. #print(request_url)
  5294. response = requests.post(request_url, data=gen_body_Card(appid, img_path, server_id), headers=headers)
  5295. resp_data = json.loads(response.content.decode("utf-8"))
  5296. print(resp_data)
  5297. resultCard = base64.b64decode(resp_data["payload"]["carLicenseRes"]["text"]).decode("utf-8")
  5298. return json.loads(resultCard)
  5299. CARDRESULT = ""
  5300. `
  5301. let code = `if __name__ == "__main__":
  5302. img_path_Card = ${AudioFile}
  5303. CARDRESULT = run_Card(appid=APPId_Card,apisecret=APISecret_Card,apikey=APIKey_Card,img_path=img_path_Card,)
  5304. `
  5305. return code
  5306. }
  5307. Blockly.Blocks['ai_online_card_result'] = {
  5308. init: function () {
  5309. this.appendDummyInput()
  5310. .appendField(Blockly.Msg.online_card_result); //
  5311. this.setOutput(true, null);
  5312. this.setColour("#0000ff");
  5313. this.setTooltip(Blockly.Msg.online_card_result);
  5314. this.setHelpUrl("");
  5315. }
  5316. };
  5317. Blockly.Python['ai_online_card_result'] = function (block) {
  5318. let code = `CARDRESULT`;
  5319. return [code, Blockly.Python.ORDER_ATOMIC];
  5320. };
  5321. // 机器翻译
  5322. Blockly.Blocks['ai_online_machine_translation_init'] = {
  5323. init: function () {
  5324. this.appendDummyInput()
  5325. .appendField(Blockly.Msg.machine_translation_init); //
  5326. this.appendDummyInput()
  5327. .appendField(Blockly.Msg.BLYNK_GET_DATANAME)
  5328. .appendField(new Blockly.FieldDropdown([
  5329. [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "cn"],
  5330. [Blockly.Msg.ai_speech_recognition_setup_set_english, "en"],
  5331. ]), "from")
  5332. .appendField(Blockly.Msg.machine_translation_to)
  5333. .appendField(new Blockly.FieldDropdown([
  5334. [Blockly.Msg.ai_speech_recognition_setup_set_english, "en"],
  5335. [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "cn"],
  5336. ]), "to");
  5337. this.appendValueInput("A").setCheck(null).appendField('APP ID');
  5338. this.appendValueInput("B").setCheck(null).appendField('API Secret');
  5339. this.appendValueInput("C").setCheck(null).appendField('API Key');
  5340. this.setPreviousStatement(true, null);
  5341. this.setNextStatement(true, null);
  5342. this.setColour("#0000ff");
  5343. this.setTooltip(Blockly.Msg.machine_translation_init);
  5344. this.setHelpUrl("");
  5345. }
  5346. };
  5347. Blockly.Python['ai_online_machine_translation_init'] = function (block) {
  5348. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  5349. var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  5350. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  5351. let FROM = block.getFieldValue('from')
  5352. let TO = block.getFieldValue('to')
  5353. // TODO: Assemble Python into code variable.
  5354. Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
  5355. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  5356. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  5357. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  5358. Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
  5359. Blockly.Python.definitions_['v831_import_json'] = `import json`
  5360. Blockly.Python.definitions_.ai_online_machine_translation_init = `
  5361. APPId_machine = ${APPId}
  5362. APISecret_machine = ${APISecret}
  5363. APIKey_machine = ${APIKey}
  5364. TRANSLATIONTEXT = ""
  5365. class get_result_machine(object):
  5366. def __init__(self,host,TRANSLATIONTEXT):
  5367. # 应用ID(到控制台获取)
  5368. self.APPID_machine = ${APPId}
  5369. # 接口APISercet(到控制台机器翻译服务页面获取)
  5370. self.Secret_machine = ${APISecret}
  5371. # 接口APIKey(到控制台机器翻译服务页面获取)
  5372. self.APIKey_machine= ${APIKey}
  5373. # 以下为POST请求
  5374. self.Host = "itrans.xfyun.cn"
  5375. self.RequestUri = "/v2/its"
  5376. # 设置url
  5377. # print(host)
  5378. self.url="https://"+host+self.RequestUri
  5379. self.HttpMethod = "POST"
  5380. self.Algorithm = "hmac-sha256"
  5381. self.HttpProto = "HTTP/1.1"
  5382. # 设置当前时间
  5383. curTime_utc = datetime.utcnow()
  5384. self.Date = self.httpdate_machine(curTime_utc)
  5385. # 设置业务参数
  5386. # 语种列表参数值请参照接口文档:https://www.xfyun.cn/doc/nlp/xftrans/API.html
  5387. self.Text=TRANSLATIONTEXT
  5388. self.BusinessArgs={
  5389. "from": "${FROM}",
  5390. "to": "${TO}",
  5391. }
  5392. def hashlib_256_machine(self, res):
  5393. m = hashlib.sha256(bytes(res.encode(encoding="utf-8"))).digest()
  5394. result = "SHA-256=" + base64.b64encode(m).decode(encoding="utf-8")
  5395. return result
  5396. def httpdate_machine(self, dt):
  5397. """
  5398. Return a string representation of a date according to RFC 1123
  5399. (HTTP/1.1).
  5400. The supplied date must be in UTC.
  5401. """
  5402. weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
  5403. month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
  5404. "Oct", "Nov", "Dec"][dt.month - 1]
  5405. return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month,
  5406. dt.year, dt.hour, dt.minute, dt.second)
  5407. def generateSignature_machine(self, digest):
  5408. signatureStr = "host: " + self.Host + "\\n"
  5409. signatureStr += "date: " + self.Date + "\\n"
  5410. signatureStr += self.HttpMethod + " " + self.RequestUri \\
  5411. + " " + self.HttpProto + "\\n"
  5412. signatureStr += "digest: " + digest
  5413. signature = hmac.new(bytes(self.Secret_machine.encode(encoding="utf-8")),
  5414. bytes(signatureStr.encode(encoding="utf-8")),
  5415. digestmod=hashlib.sha256).digest()
  5416. result = base64.b64encode(signature)
  5417. return result.decode(encoding="utf-8")
  5418. def init_header_machine(self, data):
  5419. digest = self.hashlib_256_machine(data)
  5420. #print(digest)
  5421. sign = self.generateSignature_machine(digest)
  5422. authHeader = "api_key=\\""+self.APIKey_machine+"\\", algorithm=\\""+self.Algorithm+"\\", headers=\\"host date request-line digest\\", signature=\\""+sign+"\\""
  5423. #print(authHeader)
  5424. headers = {
  5425. "Content-Type": "application/json",
  5426. "Accept": "application/json",
  5427. "Method": "POST",
  5428. "Host": self.Host,
  5429. "Date": self.Date,
  5430. "Digest": digest,
  5431. "Authorization": authHeader
  5432. }
  5433. return headers
  5434. def get_body_machine(self):
  5435. content = str(base64.b64encode(self.Text.encode("utf-8")), "utf-8")
  5436. postdata = {
  5437. "common": {"app_id": self.APPID_machine},
  5438. "business": self.BusinessArgs,
  5439. "data": {
  5440. "text": content,
  5441. }
  5442. }
  5443. body = json.dumps(postdata)
  5444. #print(body)
  5445. return body
  5446. def call_url_machine(self):
  5447. if self.APPID_machine == "" or self.APIKey_machine == "" or self.Secret_machine == "":
  5448. print("Appid 或APIKey 或APISecret 为空!请打开demo代码,填写相关信息。")
  5449. else:
  5450. code = 0
  5451. body=self.get_body_machine()
  5452. headers=self.init_header_machine(body)
  5453. #print(self.url)
  5454. response = requests.post(self.url, data=body, headers=headers,timeout=8)
  5455. status_code = response.status_code
  5456. #print(response.content)
  5457. if status_code!=200:
  5458. # 鉴权失败
  5459. print("Http请求失败,状态码:" + str(status_code) + ",错误信息:" + response.text)
  5460. print("请根据错误信息检查代码,接口文档:https://www.xfyun.cn/doc/nlp/xftrans/API.html")
  5461. else:
  5462. # 鉴权成功
  5463. respData = json.loads(response.text)
  5464. #print('result',respData["data"]['result']['trans_result']['dst'])
  5465. # return
  5466. # 以下仅用于调试
  5467. code = str(respData["code"])
  5468. if code=="0":
  5469. return respData["data"]["result"]["trans_result"]["dst"]
  5470. else:
  5471. print("请前往https://www.xfyun.cn/document/error-code?code=" + code + "查询解决办法")
  5472. `
  5473. var code = '';
  5474. return code;
  5475. };
  5476. Blockly.Blocks['ai_online_machine_translation_loading'] = {
  5477. init: function () {
  5478. this.appendDummyInput()
  5479. .appendField(Blockly.Msg.machine_translation_load); //
  5480. this.appendDummyInput()
  5481. .appendField(Blockly.Msg.BLYNK_GET_DATANAME)
  5482. .appendField(new Blockly.FieldDropdown([
  5483. [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "cn"],
  5484. [Blockly.Msg.ai_speech_recognition_setup_set_english, "en"],
  5485. ]), "from")
  5486. .appendField(Blockly.Msg.machine_translation_to)
  5487. .appendField(new Blockly.FieldDropdown([
  5488. [Blockly.Msg.ai_speech_recognition_setup_set_english, "en"],
  5489. [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "cn"],
  5490. ]), "to");
  5491. this.appendValueInput("A").setCheck(null).appendField('APP ID');
  5492. this.appendValueInput("B").setCheck(null).appendField('API Secret');
  5493. this.appendValueInput("C").setCheck(null).appendField('API Key');
  5494. this.appendValueInput("NAME")
  5495. .setCheck(null)
  5496. .appendField(Blockly.Msg.Content_of_text); //
  5497. this.setPreviousStatement(true, null);
  5498. this.setNextStatement(true, null);
  5499. this.setColour("#0000ff");
  5500. this.setTooltip(Blockly.Msg.machine_translation_load);
  5501. this.setHelpUrl("");
  5502. }
  5503. }
  5504. Blockly.Python.ai_online_machine_translation_loading = function (block) {
  5505. let text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC)
  5506. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  5507. var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  5508. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  5509. let FROM = block.getFieldValue('from')
  5510. let TO = block.getFieldValue('to')
  5511. // TODO: Assemble Python into code variable.
  5512. Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
  5513. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  5514. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  5515. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  5516. Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
  5517. Blockly.Python.definitions_['v831_import_json'] = `import json`
  5518. Blockly.Python.definitions_.ai_online_machine_translation_init = `
  5519. APPId_machine = ${APPId}
  5520. APISecret_machine = ${APISecret}
  5521. APIKey_machine = ${APIKey}
  5522. TRANSLATIONTEXT = ""
  5523. class get_result_machine(object):
  5524. def __init__(self,host,TRANSLATIONTEXT):
  5525. # 应用ID(到控制台获取)
  5526. self.APPID_machine = ${APPId}
  5527. # 接口APISercet(到控制台机器翻译服务页面获取)
  5528. self.Secret_machine = ${APISecret}
  5529. # 接口APIKey(到控制台机器翻译服务页面获取)
  5530. self.APIKey_machine= ${APIKey}
  5531. # 以下为POST请求
  5532. self.Host = "itrans.xfyun.cn"
  5533. self.RequestUri = "/v2/its"
  5534. # 设置url
  5535. # print(host)
  5536. self.url="https://"+host+self.RequestUri
  5537. self.HttpMethod = "POST"
  5538. self.Algorithm = "hmac-sha256"
  5539. self.HttpProto = "HTTP/1.1"
  5540. # 设置当前时间
  5541. curTime_utc = datetime.utcnow()
  5542. self.Date = self.httpdate_machine(curTime_utc)
  5543. # 设置业务参数
  5544. # 语种列表参数值请参照接口文档:https://www.xfyun.cn/doc/nlp/xftrans/API.html
  5545. self.Text=TRANSLATIONTEXT
  5546. self.BusinessArgs={
  5547. "from": "${FROM}",
  5548. "to": "${TO}",
  5549. }
  5550. def hashlib_256_machine(self, res):
  5551. m = hashlib.sha256(bytes(res.encode(encoding="utf-8"))).digest()
  5552. result = "SHA-256=" + base64.b64encode(m).decode(encoding="utf-8")
  5553. return result
  5554. def httpdate_machine(self, dt):
  5555. """
  5556. Return a string representation of a date according to RFC 1123
  5557. (HTTP/1.1).
  5558. The supplied date must be in UTC.
  5559. """
  5560. weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
  5561. month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
  5562. "Oct", "Nov", "Dec"][dt.month - 1]
  5563. return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month,
  5564. dt.year, dt.hour, dt.minute, dt.second)
  5565. def generateSignature_machine(self, digest):
  5566. signatureStr = "host: " + self.Host + "\\n"
  5567. signatureStr += "date: " + self.Date + "\\n"
  5568. signatureStr += self.HttpMethod + " " + self.RequestUri \\
  5569. + " " + self.HttpProto + "\\n"
  5570. signatureStr += "digest: " + digest
  5571. signature = hmac.new(bytes(self.Secret_machine.encode(encoding="utf-8")),
  5572. bytes(signatureStr.encode(encoding="utf-8")),
  5573. digestmod=hashlib.sha256).digest()
  5574. result = base64.b64encode(signature)
  5575. return result.decode(encoding="utf-8")
  5576. def init_header_machine(self, data):
  5577. digest = self.hashlib_256_machine(data)
  5578. #print(digest)
  5579. sign = self.generateSignature_machine(digest)
  5580. authHeader = "api_key=\\""+self.APIKey_machine+"\\", algorithm=\\""+self.Algorithm+"\\", headers=\\"host date request-line digest\\", signature=\\""+sign+"\\""
  5581. #print(authHeader)
  5582. headers = {
  5583. "Content-Type": "application/json",
  5584. "Accept": "application/json",
  5585. "Method": "POST",
  5586. "Host": self.Host,
  5587. "Date": self.Date,
  5588. "Digest": digest,
  5589. "Authorization": authHeader
  5590. }
  5591. return headers
  5592. def get_body_machine(self):
  5593. content = str(base64.b64encode(self.Text.encode("utf-8")), "utf-8")
  5594. postdata = {
  5595. "common": {"app_id": self.APPID_machine},
  5596. "business": self.BusinessArgs,
  5597. "data": {
  5598. "text": content,
  5599. }
  5600. }
  5601. body = json.dumps(postdata)
  5602. #print(body)
  5603. return body
  5604. def call_url_machine(self):
  5605. if self.APPID_machine == "" or self.APIKey_machine == "" or self.Secret_machine == "":
  5606. print("Appid 或APIKey 或APISecret 为空!请打开demo代码,填写相关信息。")
  5607. else:
  5608. code = 0
  5609. body=self.get_body_machine()
  5610. headers=self.init_header_machine(body)
  5611. #print(self.url)
  5612. response = requests.post(self.url, data=body, headers=headers,timeout=8)
  5613. status_code = response.status_code
  5614. #print(response.content)
  5615. if status_code!=200:
  5616. # 鉴权失败
  5617. print("Http请求失败,状态码:" + str(status_code) + ",错误信息:" + response.text)
  5618. print("请根据错误信息检查代码,接口文档:https://www.xfyun.cn/doc/nlp/xftrans/API.html")
  5619. else:
  5620. # 鉴权成功
  5621. respData = json.loads(response.text)
  5622. #print('result',respData["data"]['result']['trans_result']['dst'])
  5623. # return
  5624. # 以下仅用于调试
  5625. code = str(respData["code"])
  5626. if code=="0":
  5627. return respData["data"]["result"]["trans_result"]["dst"]
  5628. else:
  5629. print("请前往https://www.xfyun.cn/document/error-code?code=" + code + "查询解决办法")
  5630. `
  5631. let code = `TRANSLATIONTEXT = ${text}
  5632. machinehost = "itrans.xfyun.cn"
  5633. #初始化类
  5634. gClass=get_result_machine(host=machinehost,TRANSLATIONTEXT=TRANSLATIONTEXT)
  5635. TRANSLATIONRESULT = gClass.call_url_machine()
  5636. `
  5637. return code
  5638. }
  5639. Blockly.Blocks['ai_online_machine_translation_result'] = {
  5640. init: function () {
  5641. this.appendDummyInput()
  5642. .appendField(Blockly.Msg.machine_translation_result); //
  5643. this.setOutput(true, null);
  5644. this.setColour("#0000ff");
  5645. this.setTooltip(Blockly.Msg.machine_translation_result);
  5646. this.setHelpUrl("");
  5647. }
  5648. };
  5649. Blockly.Python['ai_online_machine_translation_result'] = function (block) {
  5650. let code = `TRANSLATIONRESULT`;
  5651. return [code, Blockly.Python.ORDER_ATOMIC];
  5652. };
  5653. // 手写文字识别
  5654. Blockly.Blocks['ai_online_handwritten_text_init'] = {
  5655. init: function () {
  5656. this.appendDummyInput()
  5657. .appendField(Blockly.Msg.handwritten_text_init); //
  5658. this.appendValueInput("A").setCheck(null).appendField('APP ID');
  5659. // this.appendValueInput("B").setCheck(null).appendField('API Secret');
  5660. this.appendValueInput("C").setCheck(null).appendField('API Key');
  5661. this.setPreviousStatement(true, null);
  5662. this.setNextStatement(true, null);
  5663. this.setColour("#0000ff");
  5664. this.setTooltip(Blockly.Msg.handwritten_text_init);
  5665. this.setHelpUrl("");
  5666. }
  5667. };
  5668. Blockly.Python['ai_online_handwritten_text_init'] = function (block) {
  5669. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  5670. // var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  5671. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  5672. // TODO: Assemble Python into code variable.
  5673. Blockly.Python.definitions_['v831_import_time'] = `import time`
  5674. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  5675. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  5676. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  5677. Blockly.Python.definitions_['v831_import_json'] = `import json`
  5678. Blockly.Python.definitions_['v831_import_from_urllib_parse'] = `from urllib import parse`
  5679. Blockly.Python.definitions_.ai_online_handwritten_text_init = `
  5680. URL_handwritten_text = "http://webapi.xfyun.cn/v1/service/v1/ocr/handwriting"
  5681. APPId_handwritten_text = ${APPId}
  5682. APIKey_handwritten_text = ${APIKey}
  5683. def textGetHeader_handwritten_text(language, location):
  5684. curTime = str(int(time.time()))
  5685. param = "{\\"language\\":\\""+language+"\\",\\"location\\":\\""+location+"\\"}"
  5686. paramBase64 = base64.b64encode(param.encode("utf-8"))
  5687. m2 = hashlib.md5()
  5688. str1 = APIKey_handwritten_text + curTime + str(paramBase64, "utf-8")
  5689. m2.update(str1.encode("utf-8"))
  5690. checkSum = m2.hexdigest()
  5691. # 组装http请求头
  5692. header = {
  5693. "X-CurTime": curTime,
  5694. "X-Param": paramBase64,
  5695. "X-Appid": APPId_handwritten_text,
  5696. "X-CheckSum": checkSum,
  5697. "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
  5698. }
  5699. return header
  5700. def getBody_handwritten_text(filepath):
  5701. with open(filepath, "rb") as f:
  5702. imgfile = f.read()
  5703. data = {"image": str(base64.b64encode(imgfile), "utf-8")}
  5704. return data
  5705. `
  5706. var code = '';
  5707. return code;
  5708. };
  5709. Blockly.Blocks['ai_online_handwritten_text_loading'] = {
  5710. init: function () {
  5711. this.appendDummyInput()
  5712. .appendField(Blockly.Msg.handwritten_text_load); //
  5713. this.appendValueInput("A").setCheck(null).appendField('APP ID');
  5714. // this.appendValueInput("B").setCheck(null).appendField('API Secret');
  5715. this.appendValueInput("C").setCheck(null).appendField('API Key');
  5716. this.appendValueInput("path")
  5717. .setCheck(null)
  5718. .appendField(Blockly.Msg.online_face_init_path); //
  5719. this.setPreviousStatement(true, null);
  5720. this.setNextStatement(true, null);
  5721. this.setColour("#0000ff");
  5722. this.setTooltip(Blockly.Msg.handwritten_text_load);
  5723. this.setHelpUrl("");
  5724. }
  5725. }
  5726. Blockly.Python.ai_online_handwritten_text_loading = function (block) {
  5727. let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC)
  5728. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  5729. // var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  5730. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  5731. // TODO: Assemble Python into code variable.
  5732. Blockly.Python.definitions_['v831_import_time'] = `import time`
  5733. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  5734. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  5735. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  5736. Blockly.Python.definitions_['v831_import_json'] = `import json`
  5737. Blockly.Python.definitions_['v831_import_from_urllib_parse'] = `from urllib import parse`
  5738. Blockly.Python.definitions_.ai_online_handwritten_text_init = `
  5739. URL_handwritten_text = "http://webapi.xfyun.cn/v1/service/v1/ocr/handwriting"
  5740. APPId_handwritten_text = ${APPId}
  5741. APIKey_handwritten_text = ${APIKey}
  5742. def textGetHeader_handwritten_text(language, location):
  5743. curTime = str(int(time.time()))
  5744. param = "{\\"language\\":\\""+language+"\\",\\"location\\":\\""+location+"\\"}"
  5745. paramBase64 = base64.b64encode(param.encode("utf-8"))
  5746. m2 = hashlib.md5()
  5747. str1 = APIKey_handwritten_text + curTime + str(paramBase64, "utf-8")
  5748. m2.update(str1.encode("utf-8"))
  5749. checkSum = m2.hexdigest()
  5750. # 组装http请求头
  5751. header = {
  5752. "X-CurTime": curTime,
  5753. "X-Param": paramBase64,
  5754. "X-Appid": APPId_handwritten_text,
  5755. "X-CheckSum": checkSum,
  5756. "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
  5757. }
  5758. return header
  5759. def getBody_handwritten_text(filepath):
  5760. with open(filepath, "rb") as f:
  5761. imgfile = f.read()
  5762. data = {"image": str(base64.b64encode(imgfile), "utf-8")}
  5763. return data
  5764. `
  5765. let code = `# 语种设置
  5766. textLanguage = "cn|en"
  5767. # 是否返回文本位置信息
  5768. textLocation = "false"
  5769. # 图片上传接口地址
  5770. picFilePath_handwritten_text = ${text}
  5771. HandwrittenTextData = requests.post(URL_handwritten_text, headers=textGetHeader_handwritten_text(textLanguage, textLocation), data=getBody_handwritten_text(picFilePath_handwritten_text))
  5772. `
  5773. return code
  5774. }
  5775. Blockly.Blocks['ai_online_handwritten_text_result'] = {
  5776. init: function () {
  5777. this.appendDummyInput()
  5778. .appendField(Blockly.Msg.handwritten_text_result); //
  5779. this.setOutput(true, null);
  5780. this.setColour("#0000ff");
  5781. this.setTooltip(Blockly.Msg.handwritten_text_result);
  5782. this.setHelpUrl("");
  5783. }
  5784. };
  5785. Blockly.Python['ai_online_handwritten_text_result'] = function (block) {
  5786. Blockly.Python.definitions_.ai_online_handwritten_text_result = `def handwrittenTextDatas_handwritten_text(r):
  5787. my_json_data = r.content.decode("utf8")
  5788. # print(type(my_json))
  5789. loadsData = json.loads(my_json_data)
  5790. # s = json.dumps(data, indent=4, sort_keys=True)
  5791. print("data",my_json_data)
  5792. deal_data = ""
  5793. if loadsData["code"] == "0" :
  5794. t = loadsData["data"]["block"][0]["line"]
  5795. for i in t:
  5796. print(i)
  5797. for j in i["word"]:
  5798. print(j["content"])
  5799. deal_data = deal_data + j["content"] + " "
  5800. #print('deal_data',deal_data)
  5801. return deal_data
  5802. `
  5803. let code = `handwrittenTextDatas_handwritten_text(HandwrittenTextData)`;
  5804. return [code, Blockly.Python.ORDER_ATOMIC];
  5805. };
  5806. // 公式识别
  5807. Blockly.Blocks['ai_online_formula_init'] = {
  5808. init: function () {
  5809. this.appendDummyInput()
  5810. .appendField(Blockly.Msg.formula_init); //
  5811. this.appendValueInput("A").setCheck(null).appendField('APP ID');
  5812. this.appendValueInput("B").setCheck(null).appendField('API Secret');
  5813. this.appendValueInput("C").setCheck(null).appendField('API Key');
  5814. this.setPreviousStatement(true, null);
  5815. this.setNextStatement(true, null);
  5816. this.setColour("#0000ff");
  5817. this.setTooltip(Blockly.Msg.formula_init);
  5818. this.setHelpUrl("");
  5819. }
  5820. };
  5821. Blockly.Python['ai_online_formula_init'] = function (block) {
  5822. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  5823. var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  5824. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  5825. // TODO: Assemble Python into code variable.
  5826. Blockly.Python.definitions_['v831_import_time'] = `import time`
  5827. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  5828. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  5829. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  5830. Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
  5831. Blockly.Python.definitions_['v831_import_json'] = `import json`
  5832. Blockly.Python.definitions_['v831_import_from_urllib_parse'] = `from urllib import parse`
  5833. Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
  5834. Blockly.Python.definitions_.ai_online_formula_init = `class get_result_formula(object):
  5835. def __init__(self,host,path):
  5836. # 应用ID(到控制台获取)
  5837. self.APPID_formula = ${APPId}
  5838. # 接口APISercet(到控制台公式识别服务页面获取)
  5839. self.Secret_formula = ${APISecret}
  5840. # 接口APIKey(到控制台公式识别服务页面获取)
  5841. self.APIKey_formula = ${APIKey}
  5842. # 以下为POST请求
  5843. self.Host_formula = host
  5844. self.RequestUri_formula = "/v2/itr"
  5845. # 设置url
  5846. # print(host)
  5847. self.url_formula="https://"+host+self.RequestUri_formula
  5848. self.HttpMethod_formula = "POST"
  5849. self.Algorithm_formula = "hmac-sha256"
  5850. self.HttpProto_formula = "HTTP/1.1"
  5851. # 设置当前时间
  5852. curTime_utc = datetime.utcnow()
  5853. self.Date_formula = self.httpdate_formula(curTime_utc)
  5854. #设置测试图片文件
  5855. self.AudioPath_formula = path
  5856. self.BusinessArgs_formula={
  5857. "ent": "teach-photo-print",
  5858. "aue": "raw",
  5859. }
  5860. def imgRead_formula(self, path):
  5861. with open(path, "rb") as fo:
  5862. return fo.read()
  5863. def hashlib_256_formula(self, res):
  5864. m = hashlib.sha256(bytes(res.encode(encoding="utf-8"))).digest()
  5865. result = "SHA-256=" + base64.b64encode(m).decode(encoding="utf-8")
  5866. return result
  5867. def httpdate_formula(self, dt):
  5868. """
  5869. Return a string representation of a date according to RFC 1123
  5870. (HTTP/1.1).
  5871. The supplied date must be in UTC.
  5872. """
  5873. weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
  5874. month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
  5875. "Oct", "Nov", "Dec"][dt.month - 1]
  5876. return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month,
  5877. dt.year, dt.hour, dt.minute, dt.second)
  5878. def generateSignature_formula(self, digest):
  5879. signatureStr = "host: " + self.Host_formula + "\\n"
  5880. signatureStr += "date: " + self.Date_formula + "\\n"
  5881. signatureStr += self.HttpMethod_formula + " " + self.RequestUri_formula \\
  5882. + " " + self.HttpProto_formula + "\\n"
  5883. signatureStr += "digest: " + digest
  5884. signature = hmac.new(bytes(self.Secret_formula.encode(encoding="utf-8")),
  5885. bytes(signatureStr.encode(encoding="utf-8")),
  5886. digestmod=hashlib.sha256).digest()
  5887. result = base64.b64encode(signature)
  5888. return result.decode(encoding="utf-8")
  5889. def init_header_formula(self, data):
  5890. digest = self.hashlib_256_formula(data)
  5891. #print(digest)
  5892. sign = self.generateSignature_formula(digest)
  5893. authHeader = "api_key=\\""+self.APIKey_formula+"\\", algorithm=\\""+self.Algorithm_formula+"\\", headers=\\"host date request-line digest\\", signature=\\""+sign+"\\""
  5894. #print(authHeader)
  5895. headers = {
  5896. "Content-Type": "application/json",
  5897. "Accept": "application/json",
  5898. "Method": "POST",
  5899. "Host": self.Host_formula,
  5900. "Date": self.Date_formula,
  5901. "Digest": digest,
  5902. "Authorization": authHeader
  5903. }
  5904. return headers
  5905. def get_body_formula(self):
  5906. audioData = self.imgRead_formula(self.AudioPath_formula)
  5907. content = base64.b64encode(audioData).decode(encoding="utf-8")
  5908. postdata = {
  5909. "common": {"app_id": self.APPID_formula},
  5910. "business": self.BusinessArgs_formula,
  5911. "data": {
  5912. "image": content,
  5913. }
  5914. }
  5915. body = json.dumps(postdata)
  5916. #print(body)
  5917. return body
  5918. def call_url_formula(self):
  5919. if self.APPID_formula == "" or self.APIKey_formula == "" or self.Secret_formula == "":
  5920. print("Appid 或APIKey 或APISecret 为空!请打开demo代码,填写相关信息。")
  5921. else:
  5922. code = 0
  5923. body=self.get_body_formula()
  5924. headers=self.init_header_formula(body)
  5925. #print(self.url_formula)
  5926. response = requests.post(self.url_formula, data=body, headers=headers,timeout=8)
  5927. status_code = response.status_code
  5928. #print(response.content)
  5929. if status_code!=200:
  5930. # 鉴权失败
  5931. print("Http请求失败,状态码:" + str(status_code) + ",错误信息:" + response.text)
  5932. print("请根据错误信息检查代码,接口文档:https://www.xfyun.cn/doc/words/formula-discern/API.html")
  5933. else:
  5934. # 鉴权成功
  5935. respData = json.loads(response.text)
  5936. dataCotent = ""
  5937. try:
  5938. for i in respData["data"]["region"]:
  5939. dataCotent += i["recog"]["content"]
  5940. except:
  5941. dataCotent = "Failure"
  5942. return dataCotent
  5943. FORMULARESULT = ""
  5944. `
  5945. var code = '';
  5946. return code;
  5947. };
  5948. Blockly.Blocks['ai_online_formula_loading'] = {
  5949. init: function () {
  5950. this.appendDummyInput()
  5951. .appendField(Blockly.Msg.formula_load); //
  5952. this.appendValueInput("A").setCheck(null).appendField('APP ID');
  5953. this.appendValueInput("B").setCheck(null).appendField('API Secret');
  5954. this.appendValueInput("C").setCheck(null).appendField('API Key');
  5955. this.appendValueInput("path")
  5956. .setCheck(null)
  5957. .appendField(Blockly.Msg.online_face_init_path); //
  5958. this.setPreviousStatement(true, null);
  5959. this.setNextStatement(true, null);
  5960. this.setColour("#0000ff");
  5961. this.setTooltip(Blockly.Msg.formula_load);
  5962. this.setHelpUrl("");
  5963. }
  5964. }
  5965. Blockly.Python.ai_online_formula_loading = function (block) {
  5966. let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC)
  5967. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  5968. var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  5969. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  5970. // TODO: Assemble Python into code variable.
  5971. Blockly.Python.definitions_['v831_import_time'] = `import time`
  5972. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  5973. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  5974. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  5975. Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
  5976. Blockly.Python.definitions_['v831_import_json'] = `import json`
  5977. Blockly.Python.definitions_['v831_import_from_urllib_parse'] = `from urllib import parse`
  5978. Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
  5979. Blockly.Python.definitions_.ai_online_formula_init = `class get_result_formula(object):
  5980. def __init__(self,host,path):
  5981. # 应用ID(到控制台获取)
  5982. self.APPID_formula = ${APPId}
  5983. # 接口APISercet(到控制台公式识别服务页面获取)
  5984. self.Secret_formula = ${APISecret}
  5985. # 接口APIKey(到控制台公式识别服务页面获取)
  5986. self.APIKey_formula = ${APIKey}
  5987. # 以下为POST请求
  5988. self.Host_formula = host
  5989. self.RequestUri_formula = "/v2/itr"
  5990. # 设置url
  5991. # print(host)
  5992. self.url_formula="https://"+host+self.RequestUri_formula
  5993. self.HttpMethod_formula = "POST"
  5994. self.Algorithm_formula = "hmac-sha256"
  5995. self.HttpProto_formula = "HTTP/1.1"
  5996. # 设置当前时间
  5997. curTime_utc = datetime.utcnow()
  5998. self.Date_formula = self.httpdate_formula(curTime_utc)
  5999. #设置测试图片文件
  6000. self.AudioPath_formula = path
  6001. self.BusinessArgs_formula={
  6002. "ent": "teach-photo-print",
  6003. "aue": "raw",
  6004. }
  6005. def imgRead_formula(self, path):
  6006. with open(path, "rb") as fo:
  6007. return fo.read()
  6008. def hashlib_256_formula(self, res):
  6009. m = hashlib.sha256(bytes(res.encode(encoding="utf-8"))).digest()
  6010. result = "SHA-256=" + base64.b64encode(m).decode(encoding="utf-8")
  6011. return result
  6012. def httpdate_formula(self, dt):
  6013. """
  6014. Return a string representation of a date according to RFC 1123
  6015. (HTTP/1.1).
  6016. The supplied date must be in UTC.
  6017. """
  6018. weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
  6019. month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
  6020. "Oct", "Nov", "Dec"][dt.month - 1]
  6021. return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month,
  6022. dt.year, dt.hour, dt.minute, dt.second)
  6023. def generateSignature_formula(self, digest):
  6024. signatureStr = "host: " + self.Host_formula + "\\n"
  6025. signatureStr += "date: " + self.Date_formula + "\\n"
  6026. signatureStr += self.HttpMethod_formula + " " + self.RequestUri_formula \\
  6027. + " " + self.HttpProto_formula + "\\n"
  6028. signatureStr += "digest: " + digest
  6029. signature = hmac.new(bytes(self.Secret_formula.encode(encoding="utf-8")),
  6030. bytes(signatureStr.encode(encoding="utf-8")),
  6031. digestmod=hashlib.sha256).digest()
  6032. result = base64.b64encode(signature)
  6033. return result.decode(encoding="utf-8")
  6034. def init_header_formula(self, data):
  6035. digest = self.hashlib_256_formula(data)
  6036. #print(digest)
  6037. sign = self.generateSignature_formula(digest)
  6038. authHeader = "api_key=\\""+self.APIKey_formula+"\\", algorithm=\\""+self.Algorithm_formula+"\\", headers=\\"host date request-line digest\\", signature=\\""+sign+"\\""
  6039. #print(authHeader)
  6040. headers = {
  6041. "Content-Type": "application/json",
  6042. "Accept": "application/json",
  6043. "Method": "POST",
  6044. "Host": self.Host_formula,
  6045. "Date": self.Date_formula,
  6046. "Digest": digest,
  6047. "Authorization": authHeader
  6048. }
  6049. return headers
  6050. def get_body_formula(self):
  6051. audioData = self.imgRead_formula(self.AudioPath_formula)
  6052. content = base64.b64encode(audioData).decode(encoding="utf-8")
  6053. postdata = {
  6054. "common": {"app_id": self.APPID_formula},
  6055. "business": self.BusinessArgs_formula,
  6056. "data": {
  6057. "image": content,
  6058. }
  6059. }
  6060. body = json.dumps(postdata)
  6061. #print(body)
  6062. return body
  6063. def call_url_formula(self):
  6064. if self.APPID_formula == "" or self.APIKey_formula == "" or self.Secret_formula == "":
  6065. print("Appid 或APIKey 或APISecret 为空!请打开demo代码,填写相关信息。")
  6066. else:
  6067. code = 0
  6068. body=self.get_body_formula()
  6069. headers=self.init_header_formula(body)
  6070. #print(self.url_formula)
  6071. response = requests.post(self.url_formula, data=body, headers=headers,timeout=8)
  6072. status_code = response.status_code
  6073. #print(response.content)
  6074. if status_code!=200:
  6075. # 鉴权失败
  6076. print("Http请求失败,状态码:" + str(status_code) + ",错误信息:" + response.text)
  6077. print("请根据错误信息检查代码,接口文档:https://www.xfyun.cn/doc/words/formula-discern/API.html")
  6078. else:
  6079. # 鉴权成功
  6080. respData = json.loads(response.text)
  6081. dataCotent = ""
  6082. try:
  6083. for i in respData["data"]["region"]:
  6084. dataCotent += i["recog"]["content"]
  6085. except:
  6086. dataCotent = "Failure"
  6087. return dataCotent
  6088. FORMULARESULT = ""
  6089. `
  6090. let code = `
  6091. if __name__ == "__main__":
  6092. formulaUrlPath_formula = ${text}
  6093. ##示例: host="rest-api.xfyun.cn"域名形式
  6094. host = "rest-api.xfyun.cn"
  6095. #初始化类
  6096. gClass=get_result_formula(host,path=formulaUrlPath_formula)
  6097. FORMULARESULT = gClass.call_url_formula()
  6098. `
  6099. return code
  6100. }
  6101. Blockly.Blocks['ai_online_formula_result'] = {
  6102. init: function () {
  6103. this.appendDummyInput()
  6104. .appendField(Blockly.Msg.formula_result); //
  6105. this.setOutput(true, null);
  6106. this.setColour("#0000ff");
  6107. this.setTooltip(Blockly.Msg.formula_result);
  6108. this.setHelpUrl("");
  6109. }
  6110. };
  6111. Blockly.Python['ai_online_formula_result'] = function (block) {
  6112. let code = `FORMULARESULT`;
  6113. return [code, Blockly.Python.ORDER_ATOMIC];
  6114. };
  6115. // 身份证识别
  6116. Blockly.Blocks['ai_online_ID_card_init'] = {
  6117. init: function () {
  6118. this.appendDummyInput()
  6119. .appendField('身份证识别初始化'); //
  6120. this.appendValueInput("A").setCheck(null).appendField('APP ID');
  6121. this.appendValueInput("B").setCheck(null).appendField('API Secret');
  6122. this.appendValueInput("C").setCheck(null).appendField('API Key');
  6123. this.setPreviousStatement(true, null);
  6124. this.setNextStatement(true, null);
  6125. this.setColour("#0000ff");
  6126. this.setTooltip(Blockly.Msg.handwritten_text_init);
  6127. this.setHelpUrl("");
  6128. }
  6129. };
  6130. Blockly.Python['ai_online_ID_card_init'] = function (block) {
  6131. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  6132. var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  6133. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  6134. // TODO: Assemble Python into code variable.
  6135. Blockly.Python.definitions_['v831_import_time'] = `import time`
  6136. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  6137. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  6138. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  6139. Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
  6140. Blockly.Python.definitions_['v831_import_json'] = `import json`
  6141. Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime`
  6142. Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
  6143. Blockly.Python.definitions_['v831_import_from_urllib_parse'] = `from urllib import parse`
  6144. Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time`
  6145. Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode`
  6146. Blockly.Python.definitions_.ai_online_formula_init = `class AssembleHeaderException(Exception):
  6147. def __init__(self, msg):
  6148. self.message = msg
  6149. class Url:
  6150. def __init__(this, host, path, schema):
  6151. this.host = host
  6152. this.path = path
  6153. this.schema = schema
  6154. pass
  6155. # calculate sha256 and encode to base64
  6156. def sha256base64(data):
  6157. sha256 = hashlib.sha256()
  6158. sha256.update(data)
  6159. digest = base64.b64encode(sha256.digest()).decode(encoding="utf-8")
  6160. return digest
  6161. def parse_url(requset_url):
  6162. stidx = requset_url.index("://")
  6163. host = requset_url[stidx + 3:]
  6164. schema = requset_url[:stidx + 3]
  6165. edidx = host.index("/")
  6166. if edidx <= 0:
  6167. raise AssembleHeaderException("invalid request url:" + requset_url)
  6168. path = host[edidx:]
  6169. host = host[:edidx]
  6170. u = Url(host, path, schema)
  6171. return u
  6172. # build websocket auth request url
  6173. def assemble_ws_auth_url(requset_url, method="POST", api_key="", api_secret=""):
  6174. u = parse_url(requset_url)
  6175. host = u.host
  6176. path = u.path
  6177. now = datetime.now()
  6178. date = format_date_time(mktime(now.timetuple()))
  6179. #print(date)
  6180. # date = "Thu, 12 Dec 2019 01:57:27 GMT"
  6181. signature_origin = "host: {}\\ndate: {}\\n{} {} HTTP/1.1".format(host, date, method, path)
  6182. #print(signature_origin)
  6183. signature_sha = hmac.new(api_secret.encode("utf-8"), signature_origin.encode("utf-8"),
  6184. digestmod=hashlib.sha256).digest()
  6185. signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
  6186. authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (
  6187. api_key, "hmac-sha256", "host date request-line", signature_sha)
  6188. authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8")
  6189. #print(authorization_origin)
  6190. values = {
  6191. "host": host,
  6192. "date": date,
  6193. "authorization": authorization
  6194. }
  6195. return requset_url + "?" + urlencode(values)
  6196. # 控制台获取以下信息
  6197. APPId = ${APPId}
  6198. APISecret = ${APISecret}
  6199. APIKey = ${APIKey}
  6200. `
  6201. var code = '';
  6202. return code;
  6203. };
  6204. Blockly.Blocks['ai_online_ID_card_loading'] = {
  6205. init: function () {
  6206. this.appendDummyInput()
  6207. .appendField('身份证识别加载'); //
  6208. // this.appendDummyInput()
  6209. // .appendField('设置识别语种')
  6210. // .appendField(new Blockly.FieldDropdown([
  6211. // ["en", "en"],
  6212. // ["cn|en", "cn|en"],
  6213. // ]), "language");
  6214. this.appendValueInput("path")
  6215. .setCheck(null)
  6216. .appendField(Blockly.Msg.online_face_init_path); //
  6217. this.setPreviousStatement(true, null);
  6218. this.setNextStatement(true, null);
  6219. this.setColour("#0000ff");
  6220. this.setTooltip(Blockly.Msg.handwritten_text_load);
  6221. this.setHelpUrl("");
  6222. }
  6223. }
  6224. Blockly.Python.ai_online_ID_card_loading = function (block) {
  6225. let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC)
  6226. // let language = Blockly.Python.valueToCode(block, 'language', Blockly.Python.ORDER_ATOMIC);
  6227. let code = `with open(${text}, "rb") as f:
  6228. imageBytes = f.read()
  6229. url = 'http://api.xf-yun.com/v1/private/s5ccecfce'
  6230. body = {
  6231. "header": {
  6232. "app_id": APPId,
  6233. "status": 3,
  6234. },
  6235. "parameter": {
  6236. "s5ccecfce": {
  6237. "template_list": "id_card",
  6238. "result": {
  6239. "encoding": "utf8",
  6240. "compress": "raw",
  6241. "format": "json"
  6242. }
  6243. }
  6244. },
  6245. "payload": {
  6246. "s5ccecfce_data_1": {
  6247. "encoding": "jpg",
  6248. "image": str(base64.b64encode(imageBytes), 'UTF-8'),
  6249. "status": 3
  6250. }
  6251. }
  6252. }
  6253. request_Id_card_url = assemble_ws_auth_url(url, "POST", APIKey, APISecret)
  6254. headers = {'content-type': "application/json", 'host': 'api.xf-yun.com', 'app_id': APPId}
  6255. #print(request_url)
  6256. Id_card_response = requests.post(request_Id_card_url, data=json.dumps(body), headers=headers)
  6257. IDCardtempResult = json.loads(Id_card_response.content.decode())
  6258. IDCardfinalResult = base64.b64decode(IDCard['payload']['result']['text']).decode()
  6259. IDCardfinalResult = IDCardfinalResult.replace(" ", "").replace("\n", "").replace("\t", "").strip()
  6260. `
  6261. return code
  6262. }
  6263. Blockly.Blocks['ai_online_ID_card_result'] = {
  6264. init: function () {
  6265. this.appendDummyInput()
  6266. .appendField('身份证识别结果'); //
  6267. this.setOutput(true, null);
  6268. this.setColour("#0000ff");
  6269. this.setTooltip(Blockly.Msg.handwritten_text_result);
  6270. this.setHelpUrl("");
  6271. }
  6272. };
  6273. Blockly.Python['ai_online_ID_card_result'] = function (block) {
  6274. let code = `IDCardfinalResult`;
  6275. return [code, Blockly.Python.ORDER_ATOMIC];
  6276. };
  6277. // 情绪识别
  6278. Blockly.Blocks['ai_online_emotion_init'] = {
  6279. init: function () {
  6280. this.appendDummyInput()
  6281. .appendField(Blockly.Msg.emotion_init);
  6282. // this.appendValueInput("path")
  6283. // .setCheck(null).appendField(Blockly.Msg.set_dictionary)
  6284. // .appendField(new Blockly.FieldVariable("emotion_recognize_result"), "varitem");
  6285. // this.appendDummyInput().appendField(Blockly.Msg.dictionary_contain);
  6286. this.setInputsInline(false)
  6287. this.setPreviousStatement(true, null);
  6288. this.setNextStatement(true, null);; //
  6289. this.setColour("#0000ff");
  6290. this.setTooltip(Blockly.Msg.emotion_init);
  6291. this.setHelpUrl("");
  6292. }
  6293. };
  6294. Blockly.Python['ai_online_emotion_init'] = function (block) {
  6295. // let = []
  6296. // let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC)
  6297. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  6298. // TODO: Assemble Python into code variable.
  6299. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  6300. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  6301. Blockly.Python.definitions_['v831_import_json'] = `import json`
  6302. Blockly.Python.addVariable("EMOTION_SEND_REQUEST", "EMOTION_SEND_REQUEST = {}", true);
  6303. Blockly.Python.definitions_['emotion_init'] = `def get_img_base64str(single_image_path):
  6304. with open(single_image_path, "rb") as fp:
  6305. imgbase64 = base64.b64encode(fp.read())
  6306. return imgbase64.decode()
  6307. url = "https://ai-api.cocorobo.hk/face"
  6308. `
  6309. // ${variable_name} =${text}
  6310. var code = ``;
  6311. return code;
  6312. };
  6313. Blockly.Blocks['ai_online_emotion_loading'] = {
  6314. init: function () {
  6315. this.appendDummyInput()
  6316. .appendField(Blockly.Msg.emotion_load); //
  6317. this.appendValueInput("path")
  6318. .setCheck(null)
  6319. .appendField(Blockly.Msg.online_face_init_path); //
  6320. this.setPreviousStatement(true, null);
  6321. this.setNextStatement(true, null);
  6322. this.setColour("#0000ff");
  6323. this.setTooltip(Blockly.Msg.emotion_load);
  6324. this.setHelpUrl("");
  6325. }
  6326. }
  6327. Blockly.Python.ai_online_emotion_loading = function (block) {
  6328. let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC)
  6329. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  6330. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  6331. Blockly.Python.definitions_['v831_import_json'] = `import json`
  6332. Blockly.Python.addVariable("EMOTION_SEND_REQUEST", "EMOTION_SEND_REQUEST = {}", true);
  6333. Blockly.Python.definitions_['emotion_init'] = `def get_img_base64str(single_image_path):
  6334. with open(single_image_path, "rb") as fp:
  6335. imgbase64 = base64.b64encode(fp.read())
  6336. return imgbase64.decode()
  6337. url = "https://ai-api.cocorobo.cn/face"
  6338. `
  6339. // let language = Blockly.Python.valueToCode(block, 'language', Blockly.Python.ORDER_ATOMIC);
  6340. let code = `imageEmotionURLbase64 = str(get_img_base64str(${text}))
  6341. # print(imageURLbase64)
  6342. data = "{\\"image\\":\\"" + str(imageEmotionURLbase64) + "\\"}"
  6343. try:
  6344. EMOTION_SEND_REQUEST = requests.post(url, data = data , headers = { "Ocp-Apim-Subscription-Key": "6baf787532ef4eec8bc93c88518b8916", "Content-type": "application/json" }, timeout = 10000)
  6345. EMOTION_SEND_REQUEST = json.loads(EMOTION_SEND_REQUEST.content)["data"]["result"]["face_list"][0]
  6346. # print(str(_COCOCLOUD_SEND_REQUEST.status_code)+", "+str(_COCOCLOUD_SEND_REQUEST.content))
  6347. except BaseException as e:
  6348. EMOTION_SEND_REQUEST = "no result"
  6349. pass
  6350. `
  6351. return code
  6352. }
  6353. Blockly.Blocks['ai_online_emotion_result'] = {
  6354. init: function () {
  6355. this.appendDummyInput()
  6356. .appendField(Blockly.Msg.emotion_result)
  6357. .appendField(new Blockly.FieldDropdown([
  6358. [Blockly.Msg.emotion_result_age, "age"],
  6359. [Blockly.Msg.emotion_result_emotion, "emotion"],
  6360. [Blockly.Msg.emotion_result_gender, "gender"],
  6361. [Blockly.Msg.emotion_result_expression, "expression"]
  6362. ]), "emotion_type");
  6363. this.setOutput(true, null);
  6364. this.setColour("#0000ff");
  6365. this.setTooltip(Blockly.Msg.emotion_result);
  6366. this.setHelpUrl("");
  6367. }
  6368. };
  6369. Blockly.Python['ai_online_emotion_result'] = function (block) {
  6370. var type = block.getFieldValue('emotion_type');
  6371. let code = ""
  6372. // console.log(type)
  6373. if (type == "age") {
  6374. code = `EMOTION_SEND_REQUEST["age"]`
  6375. } else {
  6376. code = `EMOTION_SEND_REQUEST["${type}"]["type"]`
  6377. }
  6378. return [code, Blockly.Python.ORDER_ATOMIC];
  6379. };
  6380. // 手势识别
  6381. Blockly.Blocks['ai_online_gesture_init'] = {
  6382. init: function () {
  6383. this.appendDummyInput()
  6384. .appendField(Blockly.Msg.gesture_init); //
  6385. this.setPreviousStatement(true, null);
  6386. this.setNextStatement(true, null);
  6387. this.setColour("#0000ff");
  6388. this.setTooltip(Blockly.Msg.gesture_init);
  6389. this.setHelpUrl("");
  6390. }
  6391. };
  6392. Blockly.Python['ai_online_gesture_init'] = function (block) {
  6393. // let = []
  6394. // TODO: Assemble Python into code variable.
  6395. Blockly.Python.definitions_['v831_import_fromPIL_Image'] = `from PIL import Image`
  6396. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  6397. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  6398. Blockly.Python.definitions_['v831_import_json'] = `import json`
  6399. Blockly.Python.definitions_['emotion_init'] = `
  6400. def getImgData(single_image_path):
  6401. imgGesture = Image.open(single_image_path).convert("RGB")
  6402. imgGesture.save(single_image_path.split(".")[0] + ".png", "png")
  6403. with open(single_image_path.split(".")[0] + ".png", "rb") as fp:
  6404. return fp.read()
  6405. url = "https://ai-api.cocorobo.hk/gesture"
  6406. `
  6407. var code = '';
  6408. return code;
  6409. };
  6410. Blockly.Blocks['ai_online_gesture_loading'] = {
  6411. init: function () {
  6412. this.appendDummyInput()
  6413. .appendField(Blockly.Msg.gesture_load);
  6414. this.appendValueInput("path")
  6415. .setCheck(null)
  6416. .appendField(Blockly.Msg.online_face_init_path); //
  6417. this.setPreviousStatement(true, null);
  6418. this.setNextStatement(true, null);
  6419. this.setColour("#0000ff");
  6420. this.setTooltip(Blockly.Msg.gesture_load);
  6421. this.setHelpUrl("");
  6422. }
  6423. }
  6424. Blockly.Python.ai_online_gesture_loading = function (block) {
  6425. let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC)
  6426. Blockly.Python.definitions_['v831_import_fromPIL_Image'] = `from PIL import Image`
  6427. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  6428. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  6429. Blockly.Python.definitions_['v831_import_json'] = `import json`
  6430. Blockly.Python.definitions_['emotion_init'] = `
  6431. def getImgData(single_image_path):
  6432. imgGesture = Image.open(single_image_path).convert("RGB")
  6433. imgGesture.save(single_image_path.split(".")[0] + ".png", "png")
  6434. with open(single_image_path.split(".")[0] + ".png", "rb") as fp:
  6435. return fp.read()
  6436. url = "https://ai-api.cocorobo.cn/gesture"
  6437. `
  6438. let code = `try:
  6439. payload={}
  6440. files=[("image",("filename.png", getImgData(${text}),"image/png"))]
  6441. headers = {}
  6442. GESTURE_SEND_REQUEST = requests.post(url, headers=headers, data=payload, files=files, timeout = 10000)
  6443. GESTURE_SEND_REQUEST = json.loads(GESTURE_SEND_REQUEST.content)["data"]["result"][0]["classname"]
  6444. # print(str(_COCOCLOUD_SEND_REQUEST.status_code)+", "+str(_COCOCLOUD_SEND_REQUEST.content))
  6445. except BaseException as e:
  6446. GESTURE_SEND_REQUEST = "no result"
  6447. pass
  6448. `
  6449. return code
  6450. }
  6451. Blockly.Blocks['ai_online_gesture_result'] = {
  6452. init: function () {
  6453. this.appendDummyInput()
  6454. .appendField(Blockly.Msg.gesture_result);
  6455. this.setOutput(true, null);
  6456. this.setColour("#0000ff");
  6457. this.setTooltip(Blockly.Msg.gesture_result);
  6458. this.setHelpUrl("");
  6459. }
  6460. };
  6461. Blockly.Python['ai_online_gesture_result'] = function (block) {
  6462. let code = `GESTURE_SEND_REQUEST`
  6463. return [code, Blockly.Python.ORDER_ATOMIC];
  6464. };
  6465. Blockly.Blocks['ai_audio_set'] = {
  6466. init: function () {
  6467. this.appendValueInput("Num")
  6468. .setCheck(null)
  6469. .appendField(Blockly.Msg.ai_audio_set_music_vol);
  6470. this.setInputsInline(true);
  6471. this.setPreviousStatement(true, null);
  6472. this.setNextStatement(true, null);
  6473. this.setColour("#603ea0");
  6474. this.setTooltip("");
  6475. this.setHelpUrl("");
  6476. }
  6477. };
  6478. Blockly.Python.ai_audio_set = function (block) {
  6479. var _num = Blockly.Python.valueToCode(block, 'Num', Blockly.Python.ORDER_ATOMIC);
  6480. var _code = "_player.volume(" + _num + ")\n"
  6481. return _code;
  6482. }
  6483. var SPEECH_RECOGNITION_BLOCK_COLOR = "230";
  6484. Blockly.Blocks['speech_recognition_new_setup'] = {
  6485. init: function () {
  6486. this.appendDummyInput()
  6487. .appendField(new Blockly.FieldImage("blockly/media/speech_recognition_header_new.png", 70, 70, { alt: "*", flipRtl: "FALSE" }));
  6488. this.appendDummyInput()
  6489. .appendField(Blockly.Msg.ai_speech_recognition_setup);
  6490. this.setPreviousStatement(true, null);
  6491. this.setNextStatement(true, null);
  6492. this.setColour("#ee783a");
  6493. this.setTooltip(Blockly.Msg.speech_recognition_new_setup_TOOLTIP);
  6494. this.setHelpUrl("");
  6495. }
  6496. };
  6497. Blockly.Python['speech_recognition_new_setup'] = function (block) {
  6498. Blockly.Python.definitions_["v831_import_coco_mfcc"] = `import _coco_mfcc`
  6499. Blockly.Python.definitions_["v831_import_time"] = `import time`
  6500. Blockly.Python.definitions_["v831_coco_mfcc_init"] = `mfcc = _coco_mfcc.MFCC(is_reply=False)`;
  6501. Blockly.Python.addVariable("RecordState", "RecordState = 0", true);
  6502. Blockly.Python.addVariable("recordFrequency", "recordFrequency = 0", true);
  6503. Blockly.Python.addVariable("recordResultData", `recordResultData = None`, true);
  6504. let code = ""
  6505. return code;
  6506. };
  6507. Blockly.Blocks['speech_recognition_clear'] = {
  6508. init: function () {
  6509. // this.appendDummyInput()
  6510. // .appendField(new Blockly.FieldImage("blockly/media/speech_recognition_header_new.png", 70, 70, { alt: "*", flipRtl: "FALSE" }));
  6511. this.appendDummyInput()
  6512. .appendField(Blockly.Msg.speech_recognition_Clean_up_the_last_study_result);
  6513. this.setPreviousStatement(true, null);
  6514. this.setNextStatement(true, null);
  6515. this.setColour("#ee783a");
  6516. this.setTooltip(Blockly.Msg.speech_recognition_Clean_up_the_last_study_result);
  6517. this.setHelpUrl("");
  6518. }
  6519. };
  6520. Blockly.Python['speech_recognition_clear'] = function (block) {
  6521. Blockly.Python.definitions_["v831_import_coco_mfcc"] = `import _coco_mfcc`
  6522. Blockly.Python.definitions_["v831_coco_mfcc_init"] = `mfcc = _coco_mfcc.MFCC(is_reply=False)`;
  6523. var code = `mfcc.clear()
  6524. `;
  6525. return code;
  6526. };
  6527. Blockly.Blocks['speech_recognition_record_start_result'] = {
  6528. init: function () {
  6529. this.appendDummyInput()
  6530. .appendField(new Blockly.FieldImage("blockly/media/speech_recognition_header_recording_new.png", 130, 60, { alt: "*", flipRtl: "FALSE" }));
  6531. this.appendDummyInput()
  6532. .appendField(Blockly.Msg.ai_speech_recognition_start_recording);
  6533. this.appendDummyInput()
  6534. .appendField(Blockly.Msg.ai_speech_recognition_start_recording_clip_text)
  6535. .appendField(new Blockly.FieldNumber(2, 1, 6, 1), "clip")
  6536. // .appendField(Blockly.Msg.ai_speech_recognition_start_recording_take_note);
  6537. this.appendDummyInput()
  6538. .appendField(Blockly.Msg.image_process_interface)
  6539. .appendField(new Blockly.FieldVariable("recordCanvas"), "varitem");
  6540. this.setPreviousStatement(true, null);
  6541. this.setNextStatement(true, null);
  6542. this.setColour("#ee783a");
  6543. this.setTooltip(Blockly.Msg.ai_speech_recognition_start_recording);
  6544. this.setHelpUrl("");
  6545. }
  6546. };
  6547. Blockly.Python['speech_recognition_record_start_result'] = function (block) {
  6548. var number_take = block.getFieldValue('clip');
  6549. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  6550. Blockly.Python.definitions_["v831_import_coco_mfcc"] = `import _coco_mfcc`
  6551. Blockly.Python.definitions_["v831_import_time"] = `import time`
  6552. Blockly.Python.definitions_["v831_coco_mfcc_init"] = `mfcc = _coco_mfcc.MFCC(is_reply=False)`;
  6553. Blockly.Python.addVariable("RecordState", "RecordState = 0", true);
  6554. Blockly.Python.addVariable("recordFrequency", "recordFrequency = 0", true);
  6555. Blockly.Python.addVariable("recordResultData", `recordResultData = None`, true);
  6556. Blockly.Python.addVariable('number_take', `number_take = ${number_take}`, true)
  6557. Blockly.Python.definitions_["v831_mfcc_clear"] = `mfcc.clear()
  6558. `
  6559. Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
  6560. Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
  6561. Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
  6562. Blockly.Python.definitions_['v831_import_os'] = `import os`
  6563. Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
  6564. def CAMERATYPE():
  6565. global cameraSize
  6566. try:
  6567. if os.path.exists("/etc/cameraSize.cfg"):
  6568. cameraSize = True
  6569. else:
  6570. cameraSize = False
  6571. except:
  6572. cameraSize = False
  6573. CAMERATYPE()
  6574. `
  6575. Blockly.Python.addVariable("ScreenOrientation", `ScreenOrientation = False`, true)
  6576. Blockly.Python.addVariable(variable_name, `${variable_name} = image.new(size = (320, 240))`, true)
  6577. Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf")
  6578. if cameraSize==True:
  6579. camera.camera.config(size=(320,240))
  6580. else:
  6581. camera.camera.config(size=(240,320))
  6582. `
  6583. let idenSuccess = "录制成功";
  6584. let speek = "说第";
  6585. let SpeechFragment = "语音片段";
  6586. if (localStorage.getItem('handPyLanguage') == "zh-hant") {
  6587. idenSuccess = "錄製成功";
  6588. speek = "說第 ";
  6589. SpeechFragment = "語音片段";
  6590. } else if (localStorage.getItem('handPyLanguage') == "en") {
  6591. idenSuccess = "Recorded successfully";
  6592. speek = "Speek ";
  6593. SpeechFragment = "Speech fragment";
  6594. }
  6595. var code = `if RecordState == 0:
  6596. mfcc.recording(recordFrequency)
  6597. recordFrequency = recordFrequency + 1
  6598. time.sleep(1)
  6599. RecordState = 1
  6600. if RecordState == 1:
  6601. recordData = mfcc.state()
  6602. if recordData == mfcc._mfcc_result:
  6603. ${variable_name}.draw_string(0,80,"${idenSuccess}", scale = 2, color = (0,204,204) , thickness = 1)
  6604. time.sleep(1)
  6605. if recordFrequency < number_take:
  6606. RecordState = 0
  6607. else:
  6608. ${variable_name}.draw_string(0,80, "${speek} "+str(recordFrequency)+" ${SpeechFragment}", scale = 2, color = (0,204,204) , thickness = 1)
  6609. `
  6610. return code
  6611. };
  6612. Blockly.Blocks['speech_recognition_new_start_recognition'] = {
  6613. init: function () {
  6614. this.appendDummyInput()
  6615. .appendField(new Blockly.FieldImage("blockly/media/speech_recognition_header_recognition_new.png", 130, 60, { alt: "*", flipRtl: "FALSE" }));
  6616. this.appendDummyInput()
  6617. .appendField(Blockly.Msg.ai_speech_recognition_start_recognizing);
  6618. this.setPreviousStatement(true, null);
  6619. this.setNextStatement(true, null);
  6620. this.setColour("#ee783a");
  6621. this.setTooltip(Blockly.Msg.speech_recognition_new_start_recognition_TOOLTIP);
  6622. this.setHelpUrl("");
  6623. }
  6624. };
  6625. Blockly.Python['speech_recognition_new_start_recognition'] = function (block) {
  6626. Blockly.Python.definitions_["v831_import_coco_mfcc"] = `import _coco_mfcc`
  6627. Blockly.Python.definitions_["v831_import_time"] = `import time`
  6628. Blockly.Python.definitions_["v831_coco_mfcc_init"] = `mfcc = _coco_mfcc.MFCC(is_reply=False)`;
  6629. Blockly.Python.addVariable("RecordState", "RecordState = 0", true);
  6630. Blockly.Python.addVariable("recordFrequency", "recordFrequency = 0", true);
  6631. Blockly.Python.addVariable("recordResultData", `recordResultData = None`, true);
  6632. var code = `if RecordState == 0:
  6633. mfcc.recognize()
  6634. recordResultData = None
  6635. time.sleep(1)
  6636. RecordState = 1
  6637. `
  6638. return code
  6639. };
  6640. Blockly.Blocks['speech_recognition_new_recognition_get_any_result'] = {
  6641. init: function () {
  6642. this.appendDummyInput()
  6643. .appendField(Blockly.Msg.ai_speech_recognition_any_result_text);
  6644. this.appendStatementInput("NAME")
  6645. .setCheck(null)
  6646. .appendField(Blockly.Msg.ai_speech_recognition_any_result_text_do);
  6647. this.setPreviousStatement(true, null);
  6648. this.setNextStatement(true, null);
  6649. this.setColour("#ee783a");
  6650. this.setTooltip(Blockly.Msg.speech_recognition_new_recognition_get_any_result_TOOLTIP);
  6651. this.setHelpUrl("");
  6652. }
  6653. };
  6654. Blockly.Python['speech_recognition_new_recognition_get_any_result'] = function (block) {
  6655. var statements_name = Blockly.Python.statementToCode(block, 'NAME');
  6656. // TODO: Assemble Python into code variable.
  6657. var code = `if RecordState == 1:
  6658. recordData = mfcc.state()
  6659. if recordData == mfcc._mfcc_result:
  6660. recordResultData = mfcc.result()
  6661. time.sleep(1)
  6662. RecordState = 0
  6663. ${statements_name}
  6664. `;
  6665. return code;
  6666. };
  6667. Blockly.Blocks['speech_recognition_new_recognition_get_result'] = {
  6668. init: function () {
  6669. this.appendDummyInput()
  6670. .appendField(Blockly.Msg.ai_speech_recognition_get_result)
  6671. .appendField(new Blockly.FieldNumber(1, 1, 6, 1), "index")
  6672. .appendField(Blockly.Msg.ai_speech_recognition_get_result_after);
  6673. this.setOutput(true, null);
  6674. this.setColour("#ee783a");
  6675. this.setTooltip(Blockly.Msg.speech_recognition_new_recognition_get_result_TOOLTIP);
  6676. this.setHelpUrl("");
  6677. }
  6678. };
  6679. Blockly.Python['speech_recognition_new_recognition_get_result'] = function (block) {
  6680. var number_index = block.getFieldValue('index');
  6681. // TODO: Assemble Python into code variable.
  6682. var code = `recordResultData == ${number_index - 1}`;
  6683. // TODO: Change ORDER_NONE to the correct strength.
  6684. return [code, Blockly.Python.ORDER_NONE];
  6685. };
  6686. /*
  6687. _ ___ ____ _
  6688. / \ |_ _| / ___| _ __ ___ __ _| | _____ _ __
  6689. / _ \ | | \___ \| '_ \ / _ \/ _` | |/ / _ \ '__|
  6690. / ___ \ _ | | _ ___) | |_) | __/ (_| | < __/ |
  6691. /_/ \_(_)___(_) |____/| .__/ \___|\__,_|_|\_\___|_|
  6692. |_|
  6693. */
  6694. Blockly.Blocks['ai_audio_init_speaker'] = {
  6695. init: function () {
  6696. this.appendDummyInput()
  6697. .appendField(new Blockly.FieldImage("blockly/media/speaker_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  6698. this.appendDummyInput()
  6699. .appendField(Blockly.Msg.ai_audio_init);
  6700. this.setColour("#5f7fc1");
  6701. this.setTooltip(Blockly.Msg.ai_audio_init_speaker_TOOLTIP);
  6702. this.setHelpUrl("");
  6703. this.setPreviousStatement(true);
  6704. this.setNextStatement(true);
  6705. }
  6706. };
  6707. Blockly.Python.ai_audio_init_speaker = function (block) {
  6708. Blockly.Python.definitions_.import_Maix = "from Maix import I2S, GPIO";
  6709. Blockly.Python.definitions_.import_fpioa_manager = "from fpioa_manager import *";
  6710. Blockly.Python.definitions_.import_audio = "import audio";
  6711. var _code = "";
  6712. return _code;
  6713. }
  6714. Blockly.Blocks['ai_audio_play_song_speaker'] = {
  6715. init: function () {
  6716. this.appendDummyInput()
  6717. .appendField(Blockly.Msg.ai_audio_play_music_file);
  6718. // this.appendDummyInput()
  6719. // .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol)
  6720. // .appendField(new Blockly.FieldNumber(95, 0, 100, 1), "play_vol");
  6721. this.appendValueInput("volume")
  6722. .setCheck(null)
  6723. .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol);
  6724. this.appendValueInput("path")
  6725. .setCheck(null)
  6726. .appendField(Blockly.Msg.ai_audio_play_music_file_set_file_path);
  6727. this.setPreviousStatement(true, null);
  6728. this.setNextStatement(true, null);
  6729. this.setColour("#5f7fc1");
  6730. this.setTooltip(Blockly.Msg.ai_audio_play_song_speaker_TOOLTIP);
  6731. this.setHelpUrl("");
  6732. }
  6733. };
  6734. Blockly.Python['ai_audio_play_song_speaker'] = function (block) {
  6735. // var number_play_vol = block.getFieldValue('play_vol');
  6736. var number_play_vol = Blockly.Python.valueToCode(block, 'volume', Blockly.Python.ORDER_ATOMIC);
  6737. var value_name = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  6738. var _in = "" +
  6739. "_audio_rx = I2S(I2S.DEVICE_1)\n" +
  6740. "\n" +
  6741. "def _speaker_play_song(path, volume):\n" +
  6742. " global _audio_play_state,_player\n" +
  6743. " _player = audio.Audio(path = path)\n" +
  6744. " _player.volume(volume)\n" +
  6745. " try:\n" +
  6746. " _wav_info = _player.play_process(_audio_rx)\n" +
  6747. " _audio_rx.channel_config(_audio_rx.CHANNEL_1, I2S.TRANSMITTER, resolution = I2S.RESOLUTION_16_BIT, align_mode = I2S.STANDARD_MODE)\n" +
  6748. " _audio_rx.set_sample_rate(_wav_info[1])\n" +
  6749. " _audio_play_state = 0\n" +
  6750. "\n" +
  6751. " fm.register(34,fm.fpioa.I2S1_OUT_D1)\n" +
  6752. " fm.register(35,fm.fpioa.I2S1_SCLK)\n" +
  6753. " fm.register(33,fm.fpioa.I2S1_WS)\n" +
  6754. "\n" +
  6755. " while True:\n" +
  6756. " _audio_play_state = _player.play()\n" +
  6757. " if (_audio_play_state) == True:\n" +
  6758. " print(\"Playing.\")\n" +
  6759. " elif (_audio_play_state) == False:\n" +
  6760. " print(\"Done.\")\n" +
  6761. " break\n" +
  6762. "\n" +
  6763. " except:\n" +
  6764. " pass\n" +
  6765. "\n";
  6766. // Blockly.Python.definitions_.import_audio = _in;
  6767. Blockly.Python.addVariable('_audio_play_state', _in, true);
  6768. // Blockly.Python.addSetup("ai_audio_read", _in);
  6769. var _code = "_speaker_play_song(path=" + value_name + ", volume=" + number_play_vol + ")\n";
  6770. return _code;
  6771. };
  6772. Blockly.Blocks['ai_audio_play_finish_speaker'] = {
  6773. init: function () {
  6774. this.appendDummyInput()
  6775. .appendField(Blockly.Msg.ai_audio_end_play);
  6776. this.setPreviousStatement(true, null);
  6777. this.setNextStatement(true, null);
  6778. this.setColour("#5f7fc1");
  6779. this.setTooltip(Blockly.Msg.ai_audio_play_finish_speaker_TOOLTIP);
  6780. this.setHelpUrl("");
  6781. }
  6782. };
  6783. Blockly.Python['ai_audio_play_finish_speaker'] = function (block) {
  6784. // TODO: Assemble Python into code variable.
  6785. var code = '_player.finish()\n';
  6786. return code;
  6787. };
  6788. Blockly.Blocks['ai_audio_set_speaker'] = {
  6789. init: function () {
  6790. this.appendValueInput("Num")
  6791. .setCheck(null)
  6792. .appendField(Blockly.Msg.ai_audio_set_music_vol);
  6793. this.setInputsInline(true);
  6794. this.setPreviousStatement(true, null);
  6795. this.setNextStatement(true, null);
  6796. this.setColour("#5f7fc1");
  6797. this.setTooltip(Blockly.Msg.ai_audio_set_speaker_TOOLTIP);
  6798. this.setHelpUrl("");
  6799. }
  6800. };
  6801. Blockly.Python.ai_audio_set_speaker = function (block) {
  6802. var _num = Blockly.Python.valueToCode(block, 'Num', Blockly.Python.ORDER_ATOMIC);
  6803. var _code = "_player.volume(" + _num + ")\n"
  6804. return _code;
  6805. }
  6806. Blockly.Blocks['ai_audio_files_list'] = {
  6807. init: function () {
  6808. this.appendDummyInput()
  6809. .appendField(Blockly.Msg.ai_audio_files_list);
  6810. this.appendValueInput("path")
  6811. .setCheck(null)
  6812. .appendField(Blockly.Msg.ai_audio_files_list_set_file_path);
  6813. this.setOutput(true, null);
  6814. this.setColour("#5f7fc1");
  6815. this.setTooltip(Blockly.Msg.ai_audio_files_list_TOOLTIP);
  6816. this.setHelpUrl("");
  6817. }
  6818. };
  6819. Blockly.Python.ai_audio_files_list = function (block) {
  6820. var value_name = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  6821. Blockly.Python.definitions_['v831_import_os'] = `import os`
  6822. Blockly.Python.definitions_.import_ai_audio_files_list = '' +
  6823. 'def getRawFileList(path):\n' +
  6824. ' files = []\n' +
  6825. ' for f in os.listdir(path):\n' +
  6826. ' if (not f.endswith("~") or not f == "") and f.split(".")[1] == "wav":\n' +
  6827. ' files.append(path + "/" + f)\n' +
  6828. ' return files\n' +
  6829. '\n';
  6830. var code = 'getRawFileList(' + value_name + ')';
  6831. return [code, Blockly.Python.ORDER_NONE];
  6832. };
  6833. Blockly.Blocks['ai_audio_play_song_list_loop_speaker'] = {
  6834. init: function () {
  6835. this.appendDummyInput()
  6836. .appendField(Blockly.Msg.ai_audio_play_music_file_list_loop);
  6837. // this.appendDummyInput()
  6838. // .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol)
  6839. // .appendField(new Blockly.FieldNumber(95, 0, 100, 1), "play_vol");
  6840. this.appendValueInput("volume")
  6841. .setCheck(null)
  6842. .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol);
  6843. // this.appendValueInput("path")
  6844. // .setCheck(null)
  6845. // .appendField(Blockly.Msg.ai_audio_play_music_file_set_file_path);
  6846. this.appendValueInput("my_list")
  6847. .setCheck(null)
  6848. .appendField(Blockly.Msg.ai_audio_play_music_file_set_files_list);
  6849. this.appendValueInput("firstIndex")
  6850. .setCheck(null)
  6851. .appendField(Blockly.Msg.ai_audio_play_music_file_set_first_index);
  6852. this.setPreviousStatement(true, null);
  6853. this.setNextStatement(true, null);
  6854. this.setColour("#5f7fc1");
  6855. this.setTooltip(Blockly.Msg.ai_audio_play_song_speaker_list_loop_TOOLTIP);
  6856. this.setHelpUrl("");
  6857. }
  6858. };
  6859. Blockly.Python['ai_audio_play_song_list_loop_speaker'] = function (block) {
  6860. // var number_play_vol = block.getFieldValue('play_vol');
  6861. var number_play_vol = Blockly.Python.valueToCode(block, 'volume', Blockly.Python.ORDER_ATOMIC);
  6862. // var value_name = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  6863. var my_list = Blockly.Python.valueToCode(block, 'my_list', Blockly.Python.ORDER_ATOMIC);
  6864. var firstIndex = Blockly.Python.valueToCode(block, 'firstIndex', Blockly.Python.ORDER_ATOMIC);
  6865. var _in = "" +
  6866. "_audio_rx = I2S(I2S.DEVICE_1)\n" +
  6867. "direction = 0\n" +
  6868. "firstIndex = " + firstIndex + "\n" +
  6869. "\n" +
  6870. "# 上一首\n" +
  6871. "def previous_song(index,my_list):\n" +
  6872. " global direction\n" +
  6873. " index = index - 1\n" +
  6874. " direction = 1\n" +
  6875. " if index == -1:\n" +
  6876. " index = len(my_list) - 1\n" +
  6877. " return index\n" +
  6878. "\n" +
  6879. "# 切换上一首\n" +
  6880. "def change_previous_song(index):\n" +
  6881. " global _audio_play_state,direction,firstIndex,_player\n" +
  6882. " _player.finish()\n" +
  6883. " _audio_play_state = 0\n" +
  6884. " firstIndex = index\n" +
  6885. " direction = 1\n" +
  6886. "\n" +
  6887. "# 下一首\n" +
  6888. "def next_song(index,my_list):\n" +
  6889. " global direction\n" +
  6890. " index = index + 1\n" +
  6891. " direction = 2\n" +
  6892. " if index == len(my_list):\n" +
  6893. " index = 0\n" +
  6894. " return index\n" +
  6895. "\n" +
  6896. "# 切换下一首\n" +
  6897. "def change_next_song(index):\n" +
  6898. " global _audio_play_state,direction,firstIndex,_player\n" +
  6899. " _player.finish()\n" +
  6900. " _audio_play_state = 0\n" +
  6901. " firstIndex = index\n" +
  6902. " direction = 2\n" +
  6903. "\n" +
  6904. "def _speaker_play_song_list_loop(volume, my_list):\n" +
  6905. " global _audio_play_state,_player,firstIndex,play_again,direction\n" +
  6906. " _player = audio.Audio(path = my_list[firstIndex])\n" +
  6907. " _player.volume(volume)\n" +
  6908. " try:\n" +
  6909. // " firstIndex = index\n" +
  6910. " _wav_info = _player.play_process(_audio_rx)\n" +
  6911. " _audio_rx.channel_config(_audio_rx.CHANNEL_1, I2S.TRANSMITTER, resolution = I2S.RESOLUTION_16_BIT, align_mode = I2S.STANDARD_MODE)\n" +
  6912. " _audio_rx.set_sample_rate(_wav_info[1])\n" +
  6913. " _audio_play_state = 0\n" +
  6914. "\n" +
  6915. " fm.register(34,fm.fpioa.I2S1_OUT_D1)\n" +
  6916. " fm.register(35,fm.fpioa.I2S1_SCLK)\n" +
  6917. " fm.register(33,fm.fpioa.I2S1_WS)\n" +
  6918. "\n" +
  6919. " button_a_state = False\n" +
  6920. " button_b_state = False\n" +
  6921. " while True:\n" +
  6922. " _audio_play_state = _player.play()\n" +
  6923. " if (_audio_play_state) == True:\n" +
  6924. " #print(\"Playing.\")\n" +
  6925. " if (_gp_side_a.value() == 1) and button_a_state == False:\n" +
  6926. " index = previous_song(firstIndex,my_list)\n" +
  6927. " button_a_state = True\n" +
  6928. " elif (_gp_side_a.value() == 0) and button_a_state == True:\n" +
  6929. " button_a_state = False\n" +
  6930. " change_previous_song(index)\n" +
  6931. " break\n" +
  6932. " if (_gp_side_b.value() == 1) and button_b_state == False:\n" +
  6933. " index = next_song(firstIndex,my_list)\n" +
  6934. " button_b_state = True\n" +
  6935. " elif (_gp_side_b.value() == 0) and button_b_state == True:\n" +
  6936. " button_b_state = False\n" +
  6937. " change_next_song(index)\n" +
  6938. " break\n" +
  6939. "\n" +
  6940. " elif (_audio_play_state) == False:\n" +
  6941. " #print(\"Done.\")\n" +
  6942. " index = firstIndex + 1\n" +
  6943. " if index == len(my_list):\n" +
  6944. " index = 0\n" +
  6945. " firstIndex = index\n" +
  6946. " break\n" +
  6947. "\n" +
  6948. " except:\n" +
  6949. " play_again = True\n" +
  6950. " if direction == 0:\n" +
  6951. " direction = 3\n" +
  6952. " return\n" +
  6953. "\n";
  6954. // Blockly.Python.definitions_.import_audio = _in;
  6955. Blockly.Python.addVariable('_audio_play_list_loop_state', _in, true);
  6956. Blockly.Python.definitions_['import_define_x_ai_button'] = '' +
  6957. 'from fpioa_manager import *\n' +
  6958. 'from Maix import FPIOA, GPIO\n' +
  6959. '\n' +
  6960. '_gp_side_buttons = [9, 10, 11]\n' +
  6961. '\n' +
  6962. 'FPIOA().set_function(_gp_side_buttons[0],FPIOA.GPIO0)\n' +
  6963. 'FPIOA().set_function(_gp_side_buttons[1],FPIOA.GPIO1)\n' +
  6964. 'FPIOA().set_function(_gp_side_buttons[2],FPIOA.GPIO2)\n' +
  6965. '\n' +
  6966. '_gp_side_a = GPIO(GPIO.GPIO0,GPIO.IN,GPIO.PULL_UP)\n' +
  6967. '_gp_side_b = GPIO(GPIO.GPIO1,GPIO.IN,GPIO.PULL_UP)\n' +
  6968. '_gp_side_c = GPIO(GPIO.GPIO2,GPIO.IN,GPIO.PULL_UP)\n' +
  6969. '\n';
  6970. // Blockly.Python.addSetup("ai_audio_read", _in);
  6971. var _code = "_speaker_play_song_list_loop(volume=" + number_play_vol + ", my_list=" + my_list + ")\n";
  6972. return _code;
  6973. };
  6974. Blockly.Blocks['ai_audio_play_song_list_random_speaker'] = {
  6975. init: function () {
  6976. this.appendDummyInput()
  6977. .appendField(Blockly.Msg.ai_audio_play_music_file_list_random);
  6978. // this.appendDummyInput()
  6979. // .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol)
  6980. // .appendField(new Blockly.FieldNumber(95, 0, 100, 1), "play_vol");
  6981. this.appendValueInput("volume")
  6982. .setCheck(null)
  6983. .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol);
  6984. // this.appendValueInput("path")
  6985. // .setCheck(null)
  6986. // .appendField(Blockly.Msg.ai_audio_play_music_file_set_file_path);
  6987. this.appendValueInput("my_list")
  6988. .setCheck(null)
  6989. .appendField(Blockly.Msg.ai_audio_play_music_file_set_files_list);
  6990. this.appendValueInput("firstIndex")
  6991. .setCheck(null)
  6992. .appendField(Blockly.Msg.ai_audio_play_music_file_set_first_index);
  6993. this.setPreviousStatement(true, null);
  6994. this.setNextStatement(true, null);
  6995. this.setColour("#5f7fc1");
  6996. this.setTooltip(Blockly.Msg.ai_audio_play_music_file_list_random_TOOLTIP);
  6997. this.setHelpUrl("");
  6998. }
  6999. };
  7000. Blockly.Python['ai_audio_play_song_list_random_speaker'] = function (block) {
  7001. // var number_play_vol = block.getFieldValue('play_vol');
  7002. var number_play_vol = Blockly.Python.valueToCode(block, 'volume', Blockly.Python.ORDER_ATOMIC);
  7003. // var value_name = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  7004. var my_list = Blockly.Python.valueToCode(block, 'my_list', Blockly.Python.ORDER_ATOMIC);
  7005. var firstIndex = Blockly.Python.valueToCode(block, 'firstIndex', Blockly.Python.ORDER_ATOMIC);
  7006. Blockly.Python.definitions_['v831_import_time'] = `import time`
  7007. Blockly.Python.definitions_['v831_import_random'] = `import random`
  7008. var _in = "" +
  7009. "random.seed(time.ticks_cpu())\n" +
  7010. "\n" +
  7011. "_audio_rx = I2S(I2S.DEVICE_1)\n" +
  7012. "firstIndex = " + firstIndex + "\n" +
  7013. "\n" +
  7014. "# 随机一首\n" +
  7015. "def random_song(index,my_list):\n" +
  7016. " index = random.randrange(0, len(my_list), 1)\n" +
  7017. " return index\n" +
  7018. "\n" +
  7019. "# 切换歌曲\n" +
  7020. "def change_random_song(index):\n" +
  7021. " global _audio_play_state,firstIndex,_player\n" +
  7022. " _player.finish()\n" +
  7023. " _audio_play_state = 0\n" +
  7024. " firstIndex = index\n" +
  7025. "\n" +
  7026. "def _speaker_play_song_list_random(volume, my_list):\n" +
  7027. " global _audio_play_state,_player,firstIndex,play_again\n" +
  7028. " _player = audio.Audio(path = my_list[firstIndex])\n" +
  7029. " _player.volume(volume)\n" +
  7030. " try:\n" +
  7031. // " firstIndex = index\n" +
  7032. " _wav_info = _player.play_process(_audio_rx)\n" +
  7033. " _audio_rx.channel_config(_audio_rx.CHANNEL_1, I2S.TRANSMITTER, resolution = I2S.RESOLUTION_16_BIT, align_mode = I2S.STANDARD_MODE)\n" +
  7034. " _audio_rx.set_sample_rate(_wav_info[1])\n" +
  7035. " _audio_play_state = 0\n" +
  7036. "\n" +
  7037. " fm.register(34,fm.fpioa.I2S1_OUT_D1)\n" +
  7038. " fm.register(35,fm.fpioa.I2S1_SCLK)\n" +
  7039. " fm.register(33,fm.fpioa.I2S1_WS)\n" +
  7040. "\n" +
  7041. " button_a_state = False\n" +
  7042. " while True:\n" +
  7043. " _audio_play_state = _player.play()\n" +
  7044. " if (_audio_play_state) == True:\n" +
  7045. " #print(\"Playing.\")\n" +
  7046. " if (_gp_side_a.value() == 1) and button_a_state == False:\n" +
  7047. " index = random_song(firstIndex,my_list)\n" +
  7048. " button_a_state = True\n" +
  7049. " elif (_gp_side_a.value() == 0) and button_a_state == True:\n" +
  7050. " button_a_state = False\n" +
  7051. " change_random_song(index)\n" +
  7052. " break\n" +
  7053. "\n" +
  7054. " elif (_audio_play_state) == False:\n" +
  7055. " #print(\"Done.\")\n" +
  7056. " index = random_song(firstIndex,my_list)\n" +
  7057. " firstIndex = index\n" +
  7058. " break\n" +
  7059. "\n" +
  7060. " except:\n" +
  7061. " play_again = True\n" +
  7062. " return\n" +
  7063. "\n";
  7064. // Blockly.Python.definitions_.import_audio = _in;
  7065. Blockly.Python.addVariable('_audio_play_list_random_state', _in, true);
  7066. Blockly.Python.definitions_['import_define_x_ai_button'] = '' +
  7067. 'from fpioa_manager import *\n' +
  7068. 'from Maix import FPIOA, GPIO\n' +
  7069. '\n' +
  7070. '_gp_side_buttons = [9, 10, 11]\n' +
  7071. '\n' +
  7072. 'FPIOA().set_function(_gp_side_buttons[0],FPIOA.GPIO0)\n' +
  7073. 'FPIOA().set_function(_gp_side_buttons[1],FPIOA.GPIO1)\n' +
  7074. 'FPIOA().set_function(_gp_side_buttons[2],FPIOA.GPIO2)\n' +
  7075. '\n' +
  7076. '_gp_side_a = GPIO(GPIO.GPIO0,GPIO.IN,GPIO.PULL_UP)\n' +
  7077. '_gp_side_b = GPIO(GPIO.GPIO1,GPIO.IN,GPIO.PULL_UP)\n' +
  7078. '_gp_side_c = GPIO(GPIO.GPIO2,GPIO.IN,GPIO.PULL_UP)\n' +
  7079. '\n';
  7080. // Blockly.Python.addSetup("ai_audio_read", _in);
  7081. var _code = "_speaker_play_song_list_random(volume=" + number_play_vol + ", my_list=" + my_list + ")\n";
  7082. return _code;
  7083. };
  7084. /*
  7085. _ ___ __ ___ _
  7086. / \ |_ _| \ \ / (_) __| | ___ ___
  7087. / _ \ | | \ \ / /| |/ _` |/ _ \/ _ \
  7088. / ___ \ | | \ V / | | (_| | __/ (_) |
  7089. /_/ \_\___| \_/ |_|\__,_|\___|\___/
  7090. */
  7091. Blockly.Blocks['ai_video_record_setup'] = {
  7092. init: function () {
  7093. this.appendDummyInput()
  7094. .appendField(new Blockly.FieldImage("blockly/media/video_record_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  7095. this.appendDummyInput()
  7096. .appendField(Blockly.Msg.ai_video_start_recording);
  7097. this.appendValueInput("save_path")
  7098. .setCheck(null)
  7099. .appendField(Blockly.Msg.ai_video_start_recording_file_path);
  7100. this.appendValueInput("w")
  7101. .setCheck(null)
  7102. .appendField(Blockly.Msg.ai_video_start_recording_width);
  7103. this.appendValueInput("h")
  7104. .setCheck(null)
  7105. .appendField(Blockly.Msg.ai_video_start_recording_height);
  7106. this.setPreviousStatement(true, null);
  7107. this.setNextStatement(true, null);
  7108. this.setColour("#60c1bb");
  7109. this.setTooltip(Blockly.Msg.ai_video_record_setup_TOOLTIP);
  7110. this.setHelpUrl("");
  7111. }
  7112. };
  7113. Blockly.Python['ai_video_record_setup'] = function (block) {
  7114. var value_save_path = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC);
  7115. var value_w = Blockly.Python.valueToCode(block, 'w', Blockly.Python.ORDER_ATOMIC);
  7116. var value_h = Blockly.Python.valueToCode(block, 'h', Blockly.Python.ORDER_ATOMIC);
  7117. Blockly.Python.definitions_.import_video = "import video";
  7118. Blockly.Python.definitions_.import_Maix = "from Maix import GPIO";
  7119. Blockly.Python.addVariable('record_vid', 'record_vid = None', true);
  7120. // TODO: Assemble Python into code variable.
  7121. var code = "_record_vid = video.open(" + value_save_path + ", record=1, width=" + value_w + ", height=" + value_h + ", interval=20000, quality=80)\n";
  7122. return code;
  7123. };
  7124. Blockly.Blocks['ai_video_get'] = {
  7125. init: function () {
  7126. this.appendDummyInput()
  7127. .appendField(Blockly.Msg.ai_video_to_canvas)
  7128. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  7129. .appendField(Blockly.Msg.ai_video_record);
  7130. this.setInputsInline(false);
  7131. this.setPreviousStatement(true, null);
  7132. this.setNextStatement(true, null);
  7133. this.setColour("#60c1bb");
  7134. this.setTooltip(Blockly.Msg.ai_video_get_TOOLTIP);
  7135. this.setHelpUrl("");
  7136. }
  7137. };
  7138. Blockly.Python.ai_video_get = function (block) {
  7139. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  7140. var _code = "_record_vid.record(" + variable_name + ")\n"
  7141. return _code;
  7142. }
  7143. Blockly.Blocks['ai_video_stop'] = {
  7144. init: function () {
  7145. this.appendDummyInput()
  7146. .appendField(Blockly.Msg.ai_video_stop_recording);
  7147. this.setPreviousStatement(true);
  7148. this.setNextStatement(true);
  7149. this.setColour("#60c1bb");
  7150. this.setTooltip(Blockly.Msg.ai_video_stop_TOOLTIP);
  7151. this.setHelpUrl("");
  7152. }
  7153. };
  7154. Blockly.Python.ai_video_stop = function (block) {
  7155. var _code = "_record_vid.record_finish()\n"
  7156. return _code;
  7157. }
  7158. Blockly.Blocks['ai_video_set_init'] = {
  7159. init: function () {
  7160. this.appendDummyInput()
  7161. .appendField(new Blockly.FieldImage("blockly/media/video_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  7162. this.appendDummyInput()
  7163. .appendField(Blockly.Msg.ai_video_set_play_init);
  7164. this.setPreviousStatement(true, null);
  7165. this.setNextStatement(true, null);
  7166. this.setColour("#4d9994");
  7167. this.setTooltip(Blockly.Msg.ai_video_set_play_init);
  7168. this.setHelpUrl("");
  7169. }
  7170. }
  7171. Blockly.Python['ai_video_set_init'] = function (block) {
  7172. Blockly.Python.definitions_['v831_import_os'] = `import os`
  7173. Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio`
  7174. Blockly.Python.definitions_['v831_import_av'] = `import av`
  7175. Blockly.Python.definitions_['v831_import_from_maix_display'] = `from maix import display`
  7176. Blockly.Python.definitions_['v831_import_from_maix_camera'] = `from maix import camera`
  7177. Blockly.Python.definitions_['v831_import_from_maix_image'] = `from maix import image`
  7178. // Blockly.Python.addVariable("VIDEOPLAY",`VIDEOPLAY = False`,true)
  7179. let code = ``
  7180. return code;
  7181. }
  7182. Blockly.Blocks['ai_video_set'] = {
  7183. init: function () {
  7184. // this.appendDummyInput()
  7185. // .appendField(Blockly.Msg.ai_video_play_video);
  7186. this.appendValueInput("path")
  7187. .setCheck(null)
  7188. .appendField(Blockly.Msg.ai_video_play_video_file_path);
  7189. // this.appendDummyInput()
  7190. // .appendField(Blockly.Msg.ai_video_play_video_2);
  7191. this.setPreviousStatement(true, null);
  7192. this.setNextStatement(true, null);
  7193. this.setColour("#4d9994");
  7194. this.setTooltip(Blockly.Msg.ai_video_play_video);
  7195. this.setHelpUrl("https://cn.maixpy.sipeed.com/maixpy/zh/api_reference/media/video.html#1-avi");
  7196. }
  7197. };
  7198. Blockly.Python['ai_video_set'] = function (block) {
  7199. // Blockly.Python.definitions_.import_Maix = "from maix import display, camera, image";
  7200. var value_path = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  7201. var code = `pathToVideo = ${value_path}
  7202. containerVideo = av.open(pathToVideo)
  7203. streamVideo = containerVideo.streams.video[0]
  7204. `
  7205. return code;
  7206. };
  7207. Blockly.Blocks['ai_video_set_stats'] = {
  7208. init: function () {
  7209. this.appendDummyInput()
  7210. .appendField(Blockly.Msg.ai_video_set_play_stats);
  7211. // this.appendDummyInput()
  7212. // .appendField(Blockly.Msg.ai_video_play_video_2);
  7213. this.setOutput(true, null)
  7214. this.setColour("#4d9994");
  7215. this.setTooltip(Blockly.Msg.ai_video_set_play_stats);
  7216. this.setHelpUrl("https://cn.maixpy.sipeed.com/maixpy/zh/api_reference/media/video.html#1-avi");
  7217. }
  7218. };
  7219. Blockly.Python['ai_video_set_stats'] = function (block) {
  7220. var code = `containerVideo.decode(video=0)`
  7221. return [code, Blockly.Python.ORDER_NONE];
  7222. };
  7223. Blockly.Blocks['ai_video_set_play'] = {
  7224. init: function () {
  7225. this.appendDummyInput().appendField(Blockly.Msg.ai_models_from)
  7226. .appendField(new Blockly.FieldVariable("i"), "varitem")
  7227. .appendField(Blockly.Msg.ai_video_set_play);
  7228. this.setPreviousStatement(true, null);
  7229. this.setNextStatement(true, null);
  7230. this.setColour("#4d9994");
  7231. this.setTooltip(Blockly.Msg.ai_video_set_play);
  7232. this.setHelpUrl("");
  7233. }
  7234. }
  7235. Blockly.Python['ai_video_set_play'] = function (block) {
  7236. var value = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  7237. let code = `if "Video" in repr(${value}):
  7238. VideoImg = image.load(bytes(${value}.to_rgb().planes[0]), (streamVideo.width, streamVideo.height))
  7239. display.show(VideoImg)
  7240. `
  7241. return code;
  7242. }
  7243. Blockly.Blocks['ai_video_stop_play'] = {
  7244. init: function () {
  7245. this.appendDummyInput()
  7246. .appendField(Blockly.Msg.ai_video_stop_video_playing);
  7247. this.setPreviousStatement(true, null);
  7248. this.setNextStatement(true, null);
  7249. this.setColour("#4d9994");
  7250. this.setTooltip(Blockly.Msg.ai_video_stop_play_TOOLTIP);
  7251. this.setHelpUrl("");
  7252. }
  7253. };
  7254. Blockly.Python['ai_video_stop_play'] = function (block) {
  7255. // TODO: Assemble Python into code variable.
  7256. var code = `break
  7257. `;
  7258. return code;
  7259. };
  7260. Blockly.Blocks['ai_video_record_init'] = {
  7261. init: function () {
  7262. this.appendDummyInput()
  7263. .appendField(new Blockly.FieldImage("blockly/media/video_record_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  7264. this.appendDummyInput()
  7265. .appendField(Blockly.Msg.ai_video_start_recording);
  7266. this.appendValueInput("save_path")
  7267. .setCheck(null)
  7268. .appendField(Blockly.Msg.ai_video_start_recording_file_path);
  7269. this.appendValueInput("w")
  7270. .setCheck(null)
  7271. .appendField(Blockly.Msg.ai_video_start_recording_width);
  7272. this.appendValueInput("h")
  7273. .setCheck(null)
  7274. .appendField(Blockly.Msg.ai_video_start_recording_height);
  7275. this.setPreviousStatement(true, null);
  7276. this.setNextStatement(true, null);
  7277. this.setColour("#4d9994");
  7278. this.setTooltip(Blockly.Msg.ai_video_record_setup_TOOLTIP);
  7279. // this.setHelpUrl("https://cn.maixpy.sipeed.com/maixpy/zh/api_reference/media/video.html#1-avi");
  7280. }
  7281. };
  7282. Blockly.Python['ai_video_record_init'] = function (block) {
  7283. Blockly.Python.definitions_['v831_import_os'] = `import os`
  7284. Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio`
  7285. Blockly.Python.definitions_['v831_import_av'] = `import av`
  7286. Blockly.Python.definitions_['v831_import_from_maix_display'] = `from maix import display`
  7287. Blockly.Python.definitions_['v831_import_from_maix_camera'] = `from maix import camera`
  7288. Blockly.Python.definitions_['v831_import_from_maix_image'] = `from maix import image`
  7289. var value_path = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC);
  7290. var w = Blockly.Python.valueToCode(block, 'w', Blockly.Python.ORDER_ATOMIC);
  7291. var h = Blockly.Python.valueToCode(block, 'h', Blockly.Python.ORDER_ATOMIC);
  7292. var code = `path_to_video = ${value_path}
  7293. fps = 10
  7294. container = av.open(path_to_video, mode='w')
  7295. stream = container.add_stream('h264', rate=fps) # h264 or mpeg4
  7296. stream.width = ${w}
  7297. stream.height = ${h}
  7298. stream.pix_fmt = 'yuv420p'
  7299. `
  7300. return code;
  7301. };
  7302. Blockly.Blocks['ai_video_record_get'] = {
  7303. init: function () {
  7304. this.appendDummyInput()
  7305. .appendField(Blockly.Msg.ai_video_to_canvas)
  7306. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  7307. .appendField(Blockly.Msg.ai_video_record);
  7308. this.setInputsInline(false);
  7309. this.setPreviousStatement(true, null);
  7310. this.setNextStatement(true, null);
  7311. this.setColour("#4d9994");
  7312. this.setTooltip(Blockly.Msg.ai_video_get_TOOLTIP);
  7313. this.setHelpUrl("");
  7314. }
  7315. };
  7316. Blockly.Python.ai_video_record_get = function (block) {
  7317. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  7318. var _code = `frame = av.VideoFrame(${variable_name}.width, ${variable_name}.height, 'rgb24')
  7319. frame.planes[0].update(${variable_name}.tobytes())
  7320. for packet in stream.encode(frame):
  7321. container.mux(packet)
  7322. `
  7323. return _code;
  7324. }
  7325. Blockly.Blocks['ai_video_record_stop'] = {
  7326. init: function () {
  7327. this.appendDummyInput()
  7328. .appendField(Blockly.Msg.ai_video_stop_recording);
  7329. this.setPreviousStatement(true);
  7330. this.setNextStatement(true);
  7331. this.setColour("#4d9994");
  7332. this.setTooltip(Blockly.Msg.ai_video_stop_TOOLTIP);
  7333. this.setHelpUrl("");
  7334. }
  7335. };
  7336. Blockly.Python.ai_video_record_stop = function (block) {
  7337. var _code = `
  7338. #Flush stream
  7339. for packet in stream.encode():
  7340. container.mux(packet)
  7341. #Close the file
  7342. container.close()
  7343. `
  7344. return _code;
  7345. }
  7346. // 视频录制
  7347. Blockly.Blocks['ai_video_record'] = {
  7348. init: function () {
  7349. this.appendDummyInput()
  7350. .appendField(new Blockly.FieldImage("blockly/media/video_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  7351. this.appendDummyInput()
  7352. .appendField(Blockly.Msg.ai_video_recording_and_save);
  7353. this.appendValueInput("path")
  7354. .setCheck(null)
  7355. .appendField(Blockly.Msg.VIDEO_SET_P);
  7356. this.appendDummyInput()
  7357. .appendField(Blockly.Msg.ai_video_play_video_2);
  7358. this.setPreviousStatement(true, null);
  7359. this.setNextStatement(true, null);
  7360. this.setColour("#4d9994");
  7361. this.setTooltip(Blockly.Msg.ai_video_set_TOOLTIP);
  7362. this.setHelpUrl("https://cn.maixpy.sipeed.com/maixpy/zh/api_reference/media/video.html#1-avi");
  7363. }
  7364. };
  7365. Blockly.Python['ai_video_record'] = function (block) {
  7366. var value_path = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  7367. Blockly.Python.definitions_['v831_import_time'] = `import time`
  7368. Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio`
  7369. Blockly.Python.definitions_['v831_import_av'] = `import av`
  7370. Blockly.Python.definitions_['v831_import_os'] = `import os`
  7371. Blockly.Python.definitions_['v831_import_from_maix_display'] = `import display`
  7372. Blockly.Python.definitions_['v831_import_from_maix_camera'] = `import camera`
  7373. Blockly.Python.definitions_['v831_import_from_maix_image'] = `import image`
  7374. var code = `path_to_video = ${value_path};
  7375. duration, fps = 4, 10
  7376. total_frames = duration * fps
  7377. container = av.open(path_to_video, mode='w')
  7378. stream = container.add_stream('h264', rate=fps) # h264 or mpeg4
  7379. stream.width = 320
  7380. stream.height = 240
  7381. stream.pix_fmt = 'yuv420p'
  7382. for frame_i in range(total_frames):
  7383. img = image.new(size=(stream.width, stream.height), mode='RGB')
  7384. img.draw_string(0, 0, str(time.time()), 2)
  7385. frame = av.VideoFrame(img.width, img.height, 'rgb24')
  7386. frame.planes[0].update(img.tobytes())
  7387. for packet in stream.encode(frame):
  7388. container.mux(packet)
  7389. #Flush stream
  7390. for packet in stream.encode():
  7391. container.mux(packet)
  7392. #Close the file
  7393. container.close()
  7394. #Play the video
  7395. container = av.open(path_to_video)
  7396. stream = container.streams.video[0]
  7397. for frame in container.decode(video=0):
  7398. if 'Video' in repr(frame):
  7399. img = image.load(bytes(frame.to_rgb().planes[0]), (stream.width, stream.height))
  7400. display.show(img)`
  7401. return code;
  7402. };
  7403. Blockly.Blocks['ai_video_status'] = {
  7404. init: function () {
  7405. this.appendDummyInput()
  7406. .appendField(Blockly.Msg.ai_video_get_video_playing_status);
  7407. this.setOutput(true, null);
  7408. this.setColour("#4d9994");
  7409. this.setTooltip(Blockly.Msg.ai_video_status_TOOLTIP);
  7410. this.setHelpUrl("");
  7411. }
  7412. };
  7413. Blockly.Python.ai_video_status = function (block) {
  7414. var code = "_video_play.play()";
  7415. return [code, Blockly.Python.ORDER_NONE];
  7416. }
  7417. /*
  7418. _ ___ __ __ _ _
  7419. / \ |_ _| | \/ | ___ __| | ___| |___
  7420. / _ \ | | | |\/| |/ _ \ / _` |/ _ \ / __|
  7421. / ___ \ | | | | | | (_) | (_| | __/ \__ \
  7422. /_/ \_\___| |_| |_|\___/ \__,_|\___|_|___/
  7423. */
  7424. Blockly.Blocks['ai_model_allinit'] = {
  7425. init: function () {
  7426. // let types = getLocalStorage("isQiehuan");
  7427. // if (!types) {
  7428. // saveLocalStorage("isQiehuan", 0);
  7429. // }
  7430. this.appendDummyInput()
  7431. .appendField(Blockly.Msg.ai_models_init_title)
  7432. .appendField(new Blockly.FieldDropdown([
  7433. [Blockly.Msg.ai_models_init_hand_written_model, "Single Digit Recognition"],
  7434. [Blockly.Msg.ai_models_init_object_model, "Common Object Recognition"],
  7435. [Blockly.Msg.ai_models_init_face_model, "Human Face Recognition"]
  7436. ]), "DEGREE");
  7437. this.appendDummyInput().appendField(Blockly.Msg.ai_model_allinit_language).appendField(new Blockly.FieldDropdown([
  7438. [Blockly.Msg.ai_speech_recognition_setup_set_english, "English"],
  7439. [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "Simplified Chinese"],
  7440. [Blockly.Msg.ai_speech_recognition_setup_set_traditional_chinese, "Traditional Chinese"]
  7441. ]), "interface")
  7442. // this.appendDummyInput()
  7443. // .appendField(Blockly.Msg.ai_camera_camera_fit_set1)
  7444. // .appendField(new Blockly.FieldVariable("img_mnist"), "camera_varitem");
  7445. // this.appendDummyInput()
  7446. // .appendField(Blockly.Msg.ai_models_init_source)
  7447. // .appendField(new Blockly.FieldVariable("img_mnist"), "varitem");
  7448. this.setPreviousStatement(true, null);
  7449. this.setNextStatement(true, null);
  7450. this.setColour("#ee783a");
  7451. var thisBlock = this;
  7452. this.setTooltip(function () {
  7453. var mode = thisBlock.getFieldValue('DEGREE');
  7454. var TOOLTIPS = {
  7455. 'Single Digit Recognition': Blockly.Msg.ai_model_allinit_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_hand_written_model),
  7456. 'Common Object Recognition': Blockly.Msg.ai_model_allinit_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model),
  7457. 'Human Face Recognition': Blockly.Msg.ai_model_allinit_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_face_model)
  7458. };
  7459. return TOOLTIPS[mode];
  7460. });
  7461. this.setHelpUrl('');
  7462. }
  7463. };
  7464. Blockly.Python.ai_model_allinit = function (block) {
  7465. Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
  7466. var degee = block.getFieldValue('DEGREE');
  7467. var _code = "";
  7468. if (degee == "Single Digit Recognition") {
  7469. Blockly.Python.addVariable('task_mnist', "task_mnist = kpu.load(\"/sd/preset/models/mnist.kmodel\")\n", true);
  7470. } else if (degee == "Common Object Recognition") {
  7471. var language = localStorage.getItem("handPyLanguage");
  7472. Blockly.Python.addVariable('task_objectrecognition', 'task_objectrecognition = None', true);
  7473. if (language == "en") {
  7474. _code = '' +
  7475. 'classes_objectrecognition = [\'aeroplane\', \'bicycle\', \'bird\', \'boat\', \'bottle\', \'bus\', \'car\', \'cat\', \'chair\', \'cow\', \'diningtable\', \'dog\', \'horse\', \'motorbike\', \'person\', \'pottedplant\', \'sheep\', \'sofa\', \'train\', \'tvmonitor\']\n' +
  7476. 'task_objectrecognition = kpu.load("/sd/preset/models/tinyyolo_v2_20class.kmodel")\n' +
  7477. 'object_anchor = (1.08, 1.19, 3.42, 4.41, 6.63, 11.38, 9.42, 5.11, 16.62, 10.52)\n' +
  7478. 'a = kpu.init_yolo2(task_objectrecognition, 0.5, 0.3, 5, object_anchor)\n' +
  7479. '';
  7480. }
  7481. else if (language == "zh-hans") {
  7482. _code = '' +
  7483. 'classes_objectrecognition = [\'飞机\', \'自行车\', \'鸟\', \'船\', \'瓶子\', \'公共汽车\', \'汽车\', \'猫\', \'椅子\', \'牛\', \'餐桌\', \'狗\', \'马\', \'摩托车\', \'人\', \'盆栽\', \'羊\', \'沙发\', \'火车\', \'电视监视器\']\n' +
  7484. 'task_objectrecognition = kpu.load("/sd/preset/models/tinyyolo_v2_20class.kmodel")\n' +
  7485. 'object_anchor = (1.08, 1.19, 3.42, 4.41, 6.63, 11.38, 9.42, 5.11, 16.62, 10.52)\n' +
  7486. 'a = kpu.init_yolo2(task_objectrecognition, 0.5, 0.3, 5, object_anchor)\n' +
  7487. '';
  7488. }
  7489. else {
  7490. _code = '' +
  7491. 'classes_objectrecognition = [\'飛機\', \'自行車\', \'鳥\', \'船\', \'瓶子\', \'公共汽車\', \'汽車\', \'貓\', \'椅子\', \'牛\', \'餐桌\', \'狗\', \'馬\', \'摩托車\', \'人\', \'盆栽\', \'羊\', \'沙發\', \'火車\', \'電視監視器\']\n' +
  7492. 'task_objectrecognition = kpu.load("/sd/preset/models/tinyyolo_v2_20class.kmodel")\n' +
  7493. 'object_anchor = (1.08, 1.19, 3.42, 4.41, 6.63, 11.38, 9.42, 5.11, 16.62, 10.52)\n' +
  7494. 'a = kpu.init_yolo2(task_objectrecognition, 0.5, 0.3, 5, object_anchor)\n' +
  7495. '';
  7496. }
  7497. } else {
  7498. Blockly.Python.addVariable('task_facerecognition', 'task_facerecognition = None', true);
  7499. _code = "" +
  7500. "task_facerecognition = kpu.load(\"/sd/preset/models/preset/face-recognition.kmodel\")\n" +
  7501. "anchor_face = (1.889, 2.5245, 2.9465, 3.94056, 3.99987, 5.3658, 5.155437, 6.92275, 6.718375, 9.01025)\n" +
  7502. "a = kpu.init_yolo2(task_facerecognition, 0.5, 0.3, 5, anchor_face)\n" +
  7503. "\n";
  7504. }
  7505. return _code;
  7506. }
  7507. // 边缘检测
  7508. Blockly.Blocks['ai_model_edge_init'] = {
  7509. init: function () {
  7510. // let types = getLocalStorage("isQiehuan");
  7511. // if (!types) {
  7512. // saveLocalStorage("isQiehuan", 0);
  7513. // }
  7514. this.appendDummyInput()
  7515. .appendField(Blockly.Msg.ai_models_init_title)
  7516. .appendField(Blockly.Msg.ai_models_edge_detection_model);
  7517. this.setPreviousStatement(true, null);
  7518. this.setNextStatement(true, null);
  7519. this.setColour("#ee783a");
  7520. this.setTooltip(Blockly.Msg.ai_models_init_title + Blockly.Msg.ai_models_edge_detection_model);
  7521. this.setHelpUrl('');
  7522. }
  7523. };
  7524. Blockly.Python.ai_model_edge_init = function (block) {
  7525. Blockly.Python.definitions_['v831_import_numpy_as_np'] = `import numpy as np`
  7526. Blockly.Python.definitions_.import_KPU = `
  7527. class Edge:
  7528. model = {
  7529. "param": "/root/preset/model/sobel_int8.param",
  7530. "bin": "/root/preset/model/sobel_int8.bin"
  7531. }
  7532. input_size = (224, 224, 3)
  7533. output_size = (222, 222, 3)
  7534. options = {
  7535. "model_type": "awnn",
  7536. "inputs": {
  7537. "input0": input_size
  7538. },
  7539. "outputs": {
  7540. "output0": output_size
  7541. },
  7542. "mean": [127.5, 127.5, 127.5],
  7543. "norm": [0.0078125, 0.0078125, 0.0078125],
  7544. }
  7545. def __init__(self):
  7546. from maix import nn
  7547. print("-- load model:", self.model)
  7548. self.model = nn.load(self.model, opt=self.options)
  7549. print("-- load ok")
  7550. def __del__(self):
  7551. del self.model
  7552. m = Edge()`;
  7553. // var degee = block.getFieldValue('DEGREE');
  7554. var _code = "";
  7555. return _code;
  7556. }
  7557. // 加载边缘检测模型
  7558. Blockly.Blocks['ai_model_edge_loading'] = {
  7559. init: function () {
  7560. // let types = getLocalStorage("isQiehuan");
  7561. // if (!types) {
  7562. // saveLocalStorage("isQiehuan", 0);
  7563. // }
  7564. this.appendDummyInput()
  7565. .appendField(Blockly.Msg.ai_models_load_edge_detection_model);
  7566. // this.appendDummyInput()
  7567. // .appendField(Blockly.Msg.ai_models_init_source)
  7568. // .appendField(new Blockly.FieldVariable("img_edgedetection"), "varitem");
  7569. this.setPreviousStatement(true, null);
  7570. this.setNextStatement(true, null);
  7571. this.setColour("#ee783a");
  7572. // var thisBlock = this;
  7573. this.setTooltip(Blockly.Msg.ai_models_load_edge_detection_model);
  7574. this.setHelpUrl('');
  7575. }
  7576. };
  7577. Blockly.Python.ai_model_edge_loading = function (block) {
  7578. // var degee = block.getFieldValue('varitem');
  7579. Blockly.Python.definitions_['v831_import_numpy_as_np'] = `import numpy as np`
  7580. Blockly.Python.definitions_.import_KPU = `
  7581. class Edge:
  7582. model = {
  7583. "param": "/root/preset/model/sobel_int8.param",
  7584. "bin": "/root/preset/model/sobel_int8.bin"
  7585. }
  7586. input_size = (224, 224, 3)
  7587. output_size = (222, 222, 3)
  7588. options = {
  7589. "model_type": "awnn",
  7590. "inputs": {
  7591. "input0": input_size
  7592. },
  7593. "outputs": {
  7594. "output0": output_size
  7595. },
  7596. "mean": [127.5, 127.5, 127.5],
  7597. "norm": [0.0078125, 0.0078125, 0.0078125],
  7598. }
  7599. def __init__(self):
  7600. from maix import nn
  7601. print("-- load model:", self.model)
  7602. self.model = nn.load(self.model, opt=self.options)
  7603. print("-- load ok")
  7604. def __del__(self):
  7605. del self.model
  7606. m = Edge()`;
  7607. // ${degee} = camera.capture().resize(224,224)
  7608. var _code = `canvas = canvas.resize(224, 224, padding = 0)
  7609. out = m.model.forward(canvas, quantize=True, layout="hwc")
  7610. out = out.astype(np.float32).reshape(m.output_size)
  7611. out = (np.ndarray.__abs__(out) * 255 / out.max()).astype(np.uint8)
  7612. data = out.tobytes()
  7613. canvas = canvas.load(data,(222, 222), mode="RGB")
  7614. `;
  7615. return _code;
  7616. }
  7617. // 获取边缘测试模型结果
  7618. Blockly.Blocks['ai_model_edge_result'] = {
  7619. init: function () {
  7620. this.appendDummyInput()
  7621. .appendField(Blockly.Msg.ai_models_get_edge_detection_result);
  7622. this.setOutput(true, null);
  7623. // this.setNextStatement(true, null);
  7624. this.setColour("#ee783a");
  7625. // var thisBlock = this;
  7626. this.setTooltip(Blockly.Msg.ai_models_get_edge_detection_result);
  7627. this.setHelpUrl('');
  7628. }
  7629. };
  7630. Blockly.Python.ai_model_edge_result = function (block) {
  7631. var degee = block.getFieldValue('varitem');
  7632. var _code = "edgeModel";
  7633. return [_code, Blockly.Python.ORDER_ATOMIC];
  7634. }
  7635. Blockly.Blocks['ai_model_allload'] = {
  7636. init: function () {
  7637. this.appendDummyInput()
  7638. .appendField(Blockly.Msg.ai_models_load_title)
  7639. .appendField(new Blockly.FieldDropdown([
  7640. [Blockly.Msg.ai_models_init_hand_written_model, "Single Digit Recognition"],
  7641. [Blockly.Msg.ai_models_init_object_model, "Common Object Recognition"],
  7642. [Blockly.Msg.ai_models_init_face_model, "Human Face Recognition"]
  7643. ]), "DEGREE");
  7644. // this.appendDummyInput()
  7645. // .appendField(Blockly.Msg.ai_camera_camera_fit_set1)
  7646. // .appendField(new Blockly.FieldVariable("img_mnist"), "camera_varitem");
  7647. this.appendDummyInput()
  7648. .appendField(Blockly.Msg.ai_models_init_source)
  7649. .appendField(new Blockly.FieldVariable("img_mnist"), "varitem");
  7650. this.setPreviousStatement(true, null);
  7651. this.setNextStatement(true, null);
  7652. this.setColour("#ee783a");
  7653. var thisBlock = this;
  7654. this.setTooltip(function () {
  7655. var mode = thisBlock.getFieldValue('DEGREE');
  7656. var TOOLTIPS = {
  7657. 'Single Digit Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_hand_written_model),
  7658. 'Common Object Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model),
  7659. 'Human Face Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_face_model)
  7660. };
  7661. return TOOLTIPS[mode];
  7662. });
  7663. this.setHelpUrl('');
  7664. }
  7665. };
  7666. Blockly.Python.ai_model_allload = function (block) {
  7667. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  7668. // var camera_variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('camera_varitem'), Blockly.Variables.NAME_TYPE);
  7669. Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
  7670. var degee = block.getFieldValue('DEGREE');
  7671. var _code = ""
  7672. if (degee == "Single Digit Recognition") {
  7673. // Blockly.Python.addVariable('img_mnist_resized', '', true);
  7674. _code += "img_mnist1=" + variable_name + ".to_grayscale(1)\n";
  7675. _code += "img_mnist_resized=img_mnist1.resize(28,28)\n";
  7676. _code += "a=img_mnist_resized.invert()\n";
  7677. _code += "a=img_mnist_resized.strech_char(1)\n";
  7678. _code += "a=img_mnist_resized.pix_to_ai()\n";
  7679. _code += "fmap_mnist=kpu.forward(task_mnist, img_mnist_resized)\n";
  7680. _code += "plist_mnist=fmap_mnist[:]\n";
  7681. _code += "pmax_mnist=max(plist_mnist)\n";
  7682. _code += "max_index_mnist=plist_mnist.index(pmax_mnist)\n";
  7683. } else if (degee == "Common Object Recognition") {
  7684. // Blockly.Python.addVariable('code_objectrecognition', '', true);
  7685. _code += "code_objectrecognition = kpu.run_yolo2(task_objectrecognition, " + variable_name + ")\n";
  7686. _code += variable_name + ".ai_to_pix()\n";
  7687. } else {
  7688. // Blockly.Python.addVariable('code_facerecognition', '', true);
  7689. _code += "code_facerecognition = kpu.run_yolo2(task_facerecognition, " + variable_name + ")\n";
  7690. _code += variable_name + ".ai_to_pix()\n";
  7691. }
  7692. return _code;
  7693. }
  7694. Blockly.Blocks['ai_model_index_init'] = {
  7695. init: function () {
  7696. this.appendValueInput("class_input")
  7697. .setCheck(null)
  7698. .appendField(Blockly.Msg.ai_models_init_title)
  7699. // .appendField("DEGREE");
  7700. this.setPreviousStatement(true, null);
  7701. this.setNextStatement(true, null);
  7702. this.setColour("#ee783a");
  7703. this.setTooltip(Blockly.Msg.ai_models_init_title);
  7704. this.setHelpUrl('');
  7705. }
  7706. };
  7707. Blockly.Python.ai_model_index_init = function (block) {
  7708. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  7709. Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
  7710. console.log('value_class_input', value_class_input)
  7711. var _code = value_class_input;
  7712. // Blockly.Python.addVariable('task_mnist', "task_mnist = kpu.load(\"/sd/preset/models/mnist.kmodel\")\n", true);
  7713. return _code;
  7714. }
  7715. // 手写数字识别
  7716. Blockly.Blocks['ai_model_look_written_model'] = {
  7717. init: function () {
  7718. // this.appendDummyInput()
  7719. // .appendField(Blockly.Msg.ai_models_init_title)
  7720. // .appendField(new Blockly.FieldDropdown([
  7721. // [Blockly.Msg.ai_models_init_hand_written_model, "Human Face Recognition"]
  7722. // ]), "DEGREE");
  7723. this.appendDummyInput()
  7724. .appendField(Blockly.Msg.ai_models_init_hand_written_model);
  7725. this.setOutput(true, null);
  7726. this.setColour("#ee783a");
  7727. this.setTooltip(Blockly.Msg.ai_models_init_title + Blockly.Msg.ai_models_init_hand_written_model);
  7728. this.setHelpUrl("");
  7729. }
  7730. };
  7731. Blockly.Python.ai_model_look_written_model = function (block) {
  7732. // Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
  7733. var _code = "task_mnist = kpu.load(\"/sd/preset/models/mnist.kmodel\")\n";
  7734. return [_code, Blockly.Python.ORDER_ATOMIC];
  7735. }
  7736. Blockly.Blocks['ai_model_look_written_model_old'] = {
  7737. init: function () {
  7738. this.appendDummyInput()
  7739. .appendField(Blockly.Msg.ai_models_init_title)
  7740. .appendField(new Blockly.FieldDropdown([
  7741. [Blockly.Msg.ai_models_init_hand_written_model, "Human Face Recognition"]
  7742. ]), "DEGREE");
  7743. // this.appendDummyInput()
  7744. // .appendField(Blockly.Msg.ai_models_init_hand_written_model);
  7745. this.setPreviousStatement(true, null);
  7746. this.setNextStatement(true, null);
  7747. this.setColour("#ee783a");
  7748. this.setTooltip(Blockly.Msg.ai_models_init_title + Blockly.Msg.ai_models_init_hand_written_model);
  7749. this.setHelpUrl("");
  7750. }
  7751. };
  7752. Blockly.Python.ai_model_look_written_model_old = function (block) {
  7753. Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
  7754. var _code = "task_mnist = kpu.load(\"/sd/preset/models/mnist.kmodel\")\n";
  7755. return _code;
  7756. }
  7757. Blockly.Blocks['ai_model_index_load'] = {
  7758. init: function () {
  7759. this.appendDummyInput()
  7760. .appendField(Blockly.Msg.ai_models_load_title)
  7761. .appendField(new Blockly.FieldDropdown([
  7762. [Blockly.Msg.ai_models_init_hand_written_model, "Single Digit Recognition"]
  7763. ]), "DEGREE");
  7764. this.appendDummyInput()
  7765. .appendField(Blockly.Msg.ai_models_init_source)
  7766. .appendField(new Blockly.FieldVariable("img_mnist"), "varitem");
  7767. this.setPreviousStatement(true, null);
  7768. this.setNextStatement(true, null);
  7769. this.setColour("#ee783a");
  7770. var thisBlock = this;
  7771. this.setTooltip(function () {
  7772. var mode = thisBlock.getFieldValue('DEGREE');
  7773. var TOOLTIPS = {
  7774. 'Single Digit Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_hand_written_model)
  7775. };
  7776. return TOOLTIPS[mode];
  7777. });
  7778. this.setHelpUrl('');
  7779. }
  7780. };
  7781. Blockly.Python.ai_model_index_load = function (block) {
  7782. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  7783. // var camera_variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('camera_varitem'), Blockly.Variables.NAME_TYPE);
  7784. Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
  7785. var degee = block.getFieldValue('DEGREE');
  7786. var _code = ""
  7787. if (degee == "Single Digit Recognition") {
  7788. // Blockly.Python.addVariable('img_mnist_resized', '', true);
  7789. _code += "img_mnist1=" + variable_name + ".to_grayscale(1)\n";
  7790. _code += "img_mnist_resized=img_mnist1.resize(28,28)\n";
  7791. _code += "a=img_mnist_resized.invert()\n";
  7792. _code += "a=img_mnist_resized.strech_char(1)\n";
  7793. _code += "a=img_mnist_resized.pix_to_ai()\n";
  7794. _code += "fmap_mnist=kpu.forward(task_mnist, img_mnist_resized)\n";
  7795. _code += "plist_mnist=fmap_mnist[:]\n";
  7796. _code += "pmax_mnist=max(plist_mnist)\n";
  7797. _code += "max_index_mnist=plist_mnist.index(pmax_mnist)\n";
  7798. }
  7799. return _code;
  7800. }
  7801. Blockly.Blocks['ai_model_index_mnist'] = {
  7802. init: function () {
  7803. this.appendDummyInput()
  7804. .appendField(new Blockly.FieldImage("blockly/media/digit_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  7805. this.appendDummyInput()
  7806. .appendField(Blockly.Msg.ai_models_hand_written_model_result);
  7807. this.appendDummyInput()
  7808. .appendField(new Blockly.FieldDropdown([
  7809. [Blockly.Msg.ai_models_hand_written_model_number, "c"],
  7810. [Blockly.Msg.ai_models_hand_written_model_confidence, "confidence"]
  7811. ]), "value");
  7812. this.setOutput(true, null);
  7813. this.setColour("#ee783a");
  7814. this.setTooltip(Blockly.Msg.ai_model_index_mnist_TOOLTIP);
  7815. this.setHelpUrl('');
  7816. }
  7817. };
  7818. Blockly.Python.ai_model_index_mnist = function (block) {
  7819. var value = block.getFieldValue('value');
  7820. var _code = "max_index_mnist";
  7821. if (value == "confidence") {
  7822. _code = "int(pmax_mnist*100)";
  7823. }
  7824. return [_code, Blockly.Python.ORDER_ATOMIC];
  7825. }
  7826. Blockly.Blocks['ai_model_digital_init'] = {
  7827. init: function () {
  7828. this.appendDummyInput()
  7829. .appendField(Blockly.Msg.ai_models_init_title)
  7830. .appendField(Blockly.Msg.ai_models_init_hand_written_model);
  7831. // this.appendDummyInput()
  7832. // .appendField(Blockly.Msg.ai_models_init_hand_written_model);
  7833. this.setPreviousStatement(true, null);
  7834. this.setNextStatement(true, null);
  7835. this.setColour("#ee783a");
  7836. this.setTooltip(Blockly.Msg.ai_models_init_title + Blockly.Msg.ai_models_init_hand_written_model);
  7837. this.setHelpUrl("");
  7838. }
  7839. };
  7840. Blockly.Python.ai_model_digital_init = function (block) {
  7841. // Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
  7842. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  7843. Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
  7844. var _code = `
  7845. class Number_recognition:
  7846. mdsc_path = "/root/preset/model/Number.mud"
  7847. labels = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
  7848. anchors = [1.0, 5.0, 1.35, 5.42, 0.49, 2.55, 0.86, 3.75, 0.65, 4.38]
  7849. def __init__(self):
  7850. self.model = nn.load(self.mdsc_path)
  7851. self.decoder = decoder.Yolo2(len(self.labels) , self.anchors , net_in_size = (224, 224) ,net_out_size = (7,7))
  7852. def __del__(self):
  7853. del self.model
  7854. del self.decoder
  7855. def cal_fps(self ,start , end):
  7856. one_second = 1
  7857. one_flash = end - start
  7858. fps = one_second / one_flash
  7859. return fps
  7860. number_recognition = Number_recognition()
  7861. `;
  7862. return _code;
  7863. }
  7864. Blockly.Blocks['ai_model_digital_init_loding'] = {
  7865. init: function () {
  7866. this.appendDummyInput()
  7867. .appendField(Blockly.Msg.ai_models_init_hand_written_model);
  7868. // this.appendDummyInput()
  7869. // .appendField(Blockly.Msg.ai_models_init_source)
  7870. // .appendField(new Blockly.FieldVariable("img_mnist"), "varitem");
  7871. this.setPreviousStatement(true, null);
  7872. this.setNextStatement(true, null);
  7873. this.setColour("#ee783a");
  7874. var thisBlock = this;
  7875. this.setTooltip(function () {
  7876. var mode = thisBlock.getFieldValue('DEGREE');
  7877. var TOOLTIPS = {
  7878. 'Single Digit Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_hand_written_model)
  7879. };
  7880. return TOOLTIPS[mode];
  7881. });
  7882. this.setHelpUrl('');
  7883. }
  7884. };
  7885. Blockly.Python.ai_model_digital_init_loding = function (block) {
  7886. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  7887. // var camera_variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('camera_varitem'), Blockly.Variables.NAME_TYPE);
  7888. Blockly.Python.definitions_.import_KPU = ``;
  7889. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  7890. Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
  7891. Blockly.Python.definitions_['v831_import_from_Number_recognition'] = `
  7892. class Number_recognition:
  7893. mdsc_path = "/root/preset/model/Number.mud"
  7894. labels = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
  7895. anchors = [1.0, 5.0, 1.35, 5.42, 0.49, 2.55, 0.86, 3.75, 0.65, 4.38]
  7896. def __init__(self):
  7897. self.model = nn.load(self.mdsc_path)
  7898. self.decoder = decoder.Yolo2(len(self.labels) , self.anchors , net_in_size = (224, 224) ,net_out_size = (7,7))
  7899. self.NumberRecognition = []
  7900. def __del__(self):
  7901. del self.model
  7902. del self.decoder
  7903. def cal_fps(self ,start , end):
  7904. one_second = 1
  7905. one_flash = end - start
  7906. fps = one_second / one_flash
  7907. return fps
  7908. def digitalShowCanvas(self,canvas):
  7909. out = number_recognition.model.forward(canvas, quantize=1, layout = "hwc")
  7910. BOXES, PROBS = number_recognition.decoder.run(out, nms=0.5, threshold=0.3, img_size=(224,224))
  7911. if len(BOXES):
  7912. for BOXESI, BOXOBJ in enumerate(BOXES):
  7913. canvas.draw_string(0,0, (str(number_recognition.labels[PROBS[BOXESI][0]]) + str(str(":") + str(round(PROBS[BOXESI][1][PROBS[BOXESI][0]]*100, 2)))), scale = 1, color = (255,0,0) , thickness = 1)
  7914. canvas.draw_rectangle(BOXOBJ[0],BOXOBJ[1], BOXOBJ[0]+BOXOBJ[2],BOXOBJ[1]+ BOXOBJ[3], color=(255,0,0), thickness=1)
  7915. BOXES[BOXESI].append(PROBS[BOXESI])
  7916. #self.NumberRecognition = BOXES
  7917. else:
  7918. BOXES = []
  7919. return BOXES
  7920. number_recognition = Number_recognition()
  7921. `;
  7922. var _code = `canvas = canvas.crop(48,8,224,224)
  7923. BOXES = number_recognition.digitalShowCanvas(canvas)
  7924. `
  7925. return _code;
  7926. }
  7927. // ai_model_digital_new
  7928. Blockly.Blocks['ai_model_digital_new'] = {
  7929. init: function () {
  7930. this.appendDummyInput()
  7931. .appendField(Blockly.Msg.ai_model_digital_new_text)
  7932. this.appendStatementInput("input")
  7933. .setCheck(null)
  7934. .appendField(Blockly.Msg.basic_motion_statement_exec);
  7935. this.appendStatementInput("input1")
  7936. .setCheck(null)
  7937. .appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE);
  7938. this.setColour("#ee783a");
  7939. this.setNextStatement(true, null);
  7940. this.setPreviousStatement(true, null);
  7941. this.setTooltip(Blockly.Msg.ai_model_digital_new_text);
  7942. this.setHelpUrl("");
  7943. }
  7944. };
  7945. Blockly.Python.ai_model_digital_new = function (block) {
  7946. var statements_input = Blockly.Python.statementToCode(block, 'input');
  7947. var statements_input1 = Blockly.Python.statementToCode(block, 'input1');
  7948. let allBlocks = block.workspace.getAllBlocks();
  7949. let global = ""
  7950. try {
  7951. global = allBlocks[0].workspace.variableList.toString()
  7952. }
  7953. catch (e) {
  7954. console.log(e)
  7955. }
  7956. Blockly.Python.addFunction("digitalStatements", `def digitalStatements(BOXESI):
  7957. ${global != "" ? `global ${global}` : "pass"}
  7958. ${statements_input}
  7959. `)
  7960. var code = `if (len(BOXES)):
  7961. for BOXESI in BOXES:
  7962. digitalStatements(BOXESI)
  7963. else:
  7964. ${statements_input1}
  7965. `
  7966. return code;
  7967. }
  7968. Blockly.Blocks['ai_model_digital_result'] = {
  7969. init: function () {
  7970. this.appendDummyInput()
  7971. .appendField(new Blockly.FieldImage("blockly/media/digit_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  7972. this.appendDummyInput()
  7973. // .appendField(Blockly.Msg.ai_models_from)
  7974. // .appendField(new Blockly.FieldVariable("i"), "varitem")
  7975. .appendField(Blockly.Msg.ai_models_hand_written_model_result);
  7976. this.appendDummyInput()
  7977. .appendField(new Blockly.FieldDropdown([
  7978. [Blockly.Msg.ai_models_hand_written_model_number, "c"],
  7979. [Blockly.Msg.ai_models_hand_written_model_confidence, "confidence"],
  7980. [Blockly.Msg.ai_models_object_model_x, "X"],
  7981. [Blockly.Msg.ai_models_object_model_y, "Y"],
  7982. [Blockly.Msg.ai_models_object_model_w, "W"],
  7983. [Blockly.Msg.ai_models_object_model_h, "H"],
  7984. [Blockly.Msg.ai_models_face_model_ws, "2"],
  7985. [Blockly.Msg.ai_models_face_model_hs, "3"],
  7986. [Blockly.Msg.ai_models_object_model_x_center, "CX"],
  7987. [Blockly.Msg.ai_models_object_model_y_center, "CY"]
  7988. ]), "value");
  7989. this.setOutput(true, null);
  7990. this.setColour("#ee783a");
  7991. this.setTooltip(Blockly.Msg.ai_models_hand_written_model_result);
  7992. this.setHelpUrl('');
  7993. }
  7994. };
  7995. Blockly.Python.ai_model_digital_result = function (block) {
  7996. var value = "BOXESI"
  7997. var type = block.getFieldValue('value');
  7998. // var _code = `"{}:{:.2f}%".format(number_recognition.labels[probs[${value}][0]], probs[${value}][1][probs[${value}][0]]*100)`;
  7999. if (type == "confidence") {
  8000. _code = `${value}[4][1][${value}[4][0]]*100`;
  8001. }
  8002. else if (type == "X") {
  8003. _code = `${value}[0]`;
  8004. }
  8005. else if (type == "Y") {
  8006. _code = `${value}[1]`;
  8007. }
  8008. else if (type == "W") {
  8009. _code = `int(${value}[0] + ${value}[2])`;
  8010. }
  8011. else if (type == "H") {
  8012. _code = `int(${value}[1] + ${value}[3])`;
  8013. }
  8014. else if (type == "c") {
  8015. _code = `number_recognition.labels[${value}[4][0]]`;
  8016. } else if (type == "CX") {
  8017. _code = `int((${value}[0] +${value}[0] + ${value}[2])/2)`;
  8018. } else if (type == "CY") {
  8019. _code = `int((${value}[1] + ${value}[1] + ${value}[3])/2)`;
  8020. }
  8021. else {
  8022. _code = `${value}[${type}]`;
  8023. }
  8024. return [_code, Blockly.Python.ORDER_ATOMIC];
  8025. }
  8026. Blockly.Blocks['ai_model_digital'] = {
  8027. init: function () {
  8028. this.appendDummyInput()
  8029. .appendField(Blockly.Msg.ai_model_digital);
  8030. // this.appendDummyInput()
  8031. // .appendField(new Blockly.FieldDropdown([
  8032. // [Blockly.Msg.ai_models_hand_written_model_number, "digitalResult"],
  8033. // [Blockly.Msg.ai_models_hand_written_model_confidence, "digitalConfidence"],
  8034. // ["检测框", "digitalCheckout"]
  8035. // ]), "digital");
  8036. this.setInputsInline(false);
  8037. this.setPreviousStatement(true, null);
  8038. this.setNextStatement(true, null);
  8039. this.setColour("#ee783a");
  8040. this.setTooltip();
  8041. this.setHelpUrl("");
  8042. }
  8043. };
  8044. Blockly.Python.ai_model_digital = function (block) {
  8045. Blockly.Python.addVariable("getDigitalResult", `getDigitalResult = []`)
  8046. Blockly.Python.addFunction("digitalShowCanvas", `def digitalShowCanvas():
  8047. global BOXES,getDigitalResult
  8048. getDigitalResult = []
  8049. if len(BOXES):
  8050. for BOXESI, BOXOBJ in enumerate(BOXES):
  8051. canvas.draw_string(0,0, (str(number_recognition.labels[PROBS[BOXESI][0]]) + str(str(":") + str(round(PROBS[BOXESI][1][PROBS[BOXESI][0]]*100, 2)))), scale = 1, color = (255,0,0) , thickness = 1)
  8052. canvas.draw_rectangle(BOXOBJ[0],BOXOBJ[1], BOXOBJ[0]+BOXOBJ[2],BOXOBJ[1]+ BOXOBJ[3], color=(255,0,0), thickness=1)
  8053. getDigitalResult.append({"digitalResult":number_recognition.labels[PROBS[BOXESI][0]],"digitalConfidence":round(PROBS[BOXESI][1][PROBS[BOXESI][0]]*100, 2)})
  8054. `)
  8055. var _code = "digitalShowCanvas()\n";
  8056. return _code;
  8057. }
  8058. Blockly.Blocks['ai_model_digital_attribute'] = {
  8059. init: function () {
  8060. this.appendDummyInput()
  8061. .appendField(Blockly.Msg.ai_model_digital_attribute);
  8062. this.setOutput(false, null);
  8063. this.setNextStatement(true, null);
  8064. this.setPreviousStatement(true, null);
  8065. this.setColour("#ee783a");
  8066. this.setTooltip(Blockly.Msg.ai_model_digital_attribute);
  8067. this.setHelpUrl("");
  8068. }
  8069. };
  8070. Blockly.Python['ai_model_digital_attribute'] = function (block) {
  8071. Blockly.Python.addFunction("", `def ai_model_digital_attribute():`)
  8072. var code = 'len(BOXES)';
  8073. return code;
  8074. };
  8075. Blockly.Blocks['ai_model_object_init'] = {
  8076. init: function () {
  8077. this.appendDummyInput()
  8078. .appendField(Blockly.Msg.ai_models_init_title)
  8079. .appendField(Blockly.Msg.ai_models_init_object_model);
  8080. // this.appendDummyInput().appendField(Blockly.Msg.ai_model_allinit_language).appendField(new Blockly.FieldDropdown([
  8081. // [Blockly.Msg.ai_speech_recognition_setup_set_english, "English"],
  8082. // [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "Simplified Chinese"],
  8083. // [Blockly.Msg.ai_speech_recognition_setup_set_traditional_chinese, "Traditional Chinese"]
  8084. // ]), "interface")
  8085. // this.appendValueInput("class_input")
  8086. // .setCheck(null)
  8087. // .appendField(Blockly.Msg.ai_models_customized_init_setup_name);
  8088. this.setPreviousStatement(true, null);
  8089. this.setNextStatement(true, null);
  8090. this.setColour("#ee783a");
  8091. var thisBlock = this;
  8092. this.setTooltip(function () {
  8093. var mode = thisBlock.getFieldValue('DEGREE');
  8094. var TOOLTIPS = {
  8095. 'Common Object Recognition': Blockly.Msg.ai_model_allinit_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model_title)
  8096. };
  8097. return TOOLTIPS[mode];
  8098. });
  8099. this.setHelpUrl('');
  8100. }
  8101. };
  8102. Blockly.Python.ai_model_object_init = function (block) {
  8103. var language = localStorage.getItem("handPyLanguage");
  8104. let a = ''
  8105. if (language == "en") {
  8106. a = '["aeroplane","bicycle","bird","boat","bottle","bus","car","cat","chair","cow","diningtable","dog","horse","motorbike","person","pottedplant","sheep","sofa","train","tvmonitor"]'
  8107. } else if (language == "zh-hans") {
  8108. a = '["飞机", "自行车", "鸟", "船", "瓶子", "公共汽车", "汽车", "猫", "椅子", "牛", "餐桌", "狗", "马", "摩托车", "人", "盆栽", "羊", "沙发", "火车", "电视监视器"]'
  8109. } else {
  8110. a = '["飛機", "自行車", "鳥", "船", "瓶子", "公共汽車", "汽車", "貓", "椅子", "牛", "餐桌", "狗", "馬", "摩托車", "人", "盆栽", "羊", "沙發", "火車", "電視監視器"]'
  8111. }
  8112. console.log(language)
  8113. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  8114. Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
  8115. Blockly.Python.definitions_.import_object = `
  8116. model = {
  8117. "param": "/root/preset/model/yolo2_20class_awnn.param",
  8118. "bin": "/root/preset/model/yolo2_20class_awnn.bin"
  8119. }
  8120. options = {
  8121. "model_type": "awnn",
  8122. "inputs": {
  8123. "input0": (224, 224, 3)
  8124. },
  8125. "outputs": {
  8126. "output0": (7, 7, (1+4+20)*5)
  8127. },
  8128. "mean": [127.5, 127.5, 127.5],
  8129. "norm": [0.0078125, 0.0078125, 0.0078125],
  8130. }
  8131. labels = ${a}
  8132. anchors = [5.4, 5.38, 1.65, 2.09, 0.8, 1.83, 2.45, 4.14, 0.46, 0.8]
  8133. m = nn.load(model, opt=options)
  8134. yolo2_decoder = decoder.Yolo2(len(labels), anchors, net_in_size=(options["inputs"]["input0"][0], options["inputs"]["input0"][1]), net_out_size=(7, 7))
  8135. `;
  8136. var _code = "";
  8137. return _code;
  8138. }
  8139. Blockly.Blocks['ai_model_object_load'] = {
  8140. init: function () {
  8141. this.appendDummyInput()
  8142. .appendField(Blockly.Msg.ai_models_load_title)
  8143. .appendField(Blockly.Msg.ai_models_init_object_model);
  8144. // this.appendDummyInput()
  8145. // .appendField(Blockly.Msg.ai_models_init_source)
  8146. // .appendField(new Blockly.FieldVariable("img_objectrecognition"), "varitem");
  8147. this.setPreviousStatement(true, null);
  8148. this.setNextStatement(true, null);
  8149. this.setColour("#ee783a");
  8150. var thisBlock = this;
  8151. this.setTooltip(function () {
  8152. var mode = thisBlock.getFieldValue('DEGREE');
  8153. var TOOLTIPS = {
  8154. 'Common Object Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model)
  8155. };
  8156. return TOOLTIPS[mode];
  8157. });
  8158. this.setHelpUrl('');
  8159. }
  8160. };
  8161. Blockly.Python.ai_model_object_load = function (block) {
  8162. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  8163. // var degee = block.getFieldValue('DEGREE');
  8164. var language = localStorage.getItem("handPyLanguage");
  8165. let a = ''
  8166. if (language == "en") {
  8167. a = '["aeroplane","bicycle","bird","boat","bottle","bus","car","cat","chair","cow","diningtable","dog","horse","motorbike","person","pottedplant","sheep","sofa","train","tvmonitor"]'
  8168. } else if (language == "zh-hans") {
  8169. a = '["飞机", "自行车", "鸟", "船", "瓶子", "公共汽车", "汽车", "猫", "椅子", "牛", "餐桌", "狗", "马", "摩托车", "人", "盆栽", "羊", "沙发", "火车", "电视监视器"]'
  8170. } else {
  8171. a = '["飛機", "自行車", "鳥", "船", "瓶子", "公共汽車", "汽車", "貓", "椅子", "牛", "餐桌", "狗", "馬", "摩托車", "人", "盆栽", "羊", "沙發", "火車", "電視監視器"]'
  8172. }
  8173. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  8174. Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
  8175. Blockly.Python.definitions_.import_object = `class ObjectRecognition:
  8176. def __init__(self):
  8177. model = {
  8178. "param": "/root/preset/model/yolo2_20class_awnn.param",
  8179. "bin": "/root/preset/model/yolo2_20class_awnn.bin"
  8180. }
  8181. options = {
  8182. "model_type": "awnn",
  8183. "inputs": {
  8184. "input0": (224, 224, 3)
  8185. },
  8186. "outputs": {
  8187. "output0": (7, 7, (1+4+20)*5)
  8188. },
  8189. "mean": [127.5, 127.5, 127.5],
  8190. "norm": [0.0078125, 0.0078125, 0.0078125],
  8191. }
  8192. self.labels = ${a}
  8193. anchors = [5.4, 5.38, 1.65, 2.09, 0.8, 1.83, 2.45, 4.14, 0.46, 0.8]
  8194. self.m = nn.load(model, opt=options)
  8195. self.yolo2_decoder = decoder.Yolo2(len(self.labels), anchors, net_in_size=(224,224), net_out_size=(7, 7))
  8196. self.OBJECTS = {
  8197. "OBJECT_START_X": [],
  8198. "OBJECT_START_Y": [],
  8199. "OBJECT_CONFIDENCE": [],
  8200. "OBJECT_WIDTH": [],
  8201. "OBJECT_HEIGHT": [],
  8202. "OBJECT_CENTER_X": [],
  8203. "OBJECT_CENTER_Y": [],
  8204. "OBJECT_RESULT": [],
  8205. }
  8206. def objectRecognize(self, canvas):
  8207. self.OBJECTS = {
  8208. "OBJECT_START_X": [],
  8209. "OBJECT_START_Y": [],
  8210. "OBJECT_CONFIDENCE": [],
  8211. "OBJECT_WIDTH": [],
  8212. "OBJECT_HEIGHT": [],
  8213. "OBJECT_CENTER_X": [],
  8214. "OBJECT_CENTER_Y": [],
  8215. "OBJECT_RESULT": [],
  8216. }
  8217. out = self.m.forward(canvas.tobytes(), quantize=True, layout="hwc")
  8218. BOXES, PROBS = self.yolo2_decoder.run(out, nms=0.3, threshold=0.3, img_size=(224,224))
  8219. if len(BOXES):
  8220. for BOXESI, BOXOBJ in enumerate(BOXES):
  8221. canvas.draw_string(BOXOBJ[0],(BOXOBJ[1]), ("".join([str(x) for x in [str(self.labels[PROBS[BOXESI][0]]), ",", round(PROBS[BOXESI][1][PROBS[BOXESI][0]]*100, 2)]])), scale = 1, color = (51,102,255) , thickness = 1)
  8222. canvas.draw_rectangle(BOXOBJ[0],BOXOBJ[1], BOXOBJ[0]+BOXOBJ[2],BOXOBJ[1]+ BOXOBJ[3], color=(255,0,0), thickness=1)
  8223. BOXES[BOXESI].append(PROBS[BOXESI])
  8224. else:
  8225. BOXES = []
  8226. return BOXES
  8227. ObjectRecognition = ObjectRecognition()
  8228. `;
  8229. var _code = `canvas = canvas.crop(48,8,224,224)
  8230. BOXES = ObjectRecognition.objectRecognize(canvas)
  8231. `
  8232. return _code;
  8233. }
  8234. // ai_model_look_new
  8235. Blockly.Blocks['ai_model_look_new'] = {
  8236. init: function () {
  8237. this.appendDummyInput()
  8238. .appendField(Blockly.Msg.ai_models_object_model_if)
  8239. this.appendStatementInput("input")
  8240. .setCheck(null)
  8241. .appendField(Blockly.Msg.basic_motion_statement_exec);
  8242. this.appendStatementInput("input1")
  8243. .setCheck(null)
  8244. .appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE);
  8245. this.setColour("#ee783a");
  8246. this.setNextStatement(true, null);
  8247. this.setPreviousStatement(true, null);
  8248. this.setTooltip(Blockly.Msg.ai_models_object_model_if);
  8249. this.setHelpUrl("");
  8250. }
  8251. };
  8252. Blockly.Python.ai_model_look_new = function (block) {
  8253. var statements_input = Blockly.Python.statementToCode(block, 'input');
  8254. var statements_input1 = Blockly.Python.statementToCode(block, 'input1');
  8255. let allBlocks = block.workspace.getAllBlocks();
  8256. let global = ""
  8257. try {
  8258. global = allBlocks[0].workspace.variableList.toString()
  8259. }
  8260. catch (e) {
  8261. console.log(e)
  8262. }
  8263. Blockly.Python.addFunction("modelStatements", `def modelStatements(BOXESI):
  8264. ${global != "" ? `global ${global}` : "pass"}
  8265. ${statements_input}
  8266. `)
  8267. var code = `if len(BOXES):
  8268. for BOXESI in BOXES:
  8269. modelStatements(BOXESI)
  8270. else:
  8271. ${statements_input1}
  8272. `
  8273. return code;
  8274. }
  8275. Blockly.Blocks['ai_model_get'] = {
  8276. init: function () {
  8277. this.appendDummyInput()
  8278. .appendField(new Blockly.FieldImage("blockly/media/object_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  8279. this.appendDummyInput()
  8280. .appendField(Blockly.Msg.ai_models_from)
  8281. .appendField(Blockly.Msg.ai_models_object_model_get)
  8282. .appendField(new Blockly.FieldDropdown([
  8283. [Blockly.Msg.ai_models_object_model_name, "Object"],
  8284. [Blockly.Msg.ai_models_object_model_x, "X"],
  8285. [Blockly.Msg.ai_models_object_model_y, "Y"],
  8286. // [Blockly.Msg.ai_models_object_model_w, "W"],
  8287. // [Blockly.Msg.ai_models_object_model_h, "H"],
  8288. // [Blockly.Msg.ai_models_object_model_x_center, "CX"],
  8289. // [Blockly.Msg.ai_models_object_model_y_center, "CY"],
  8290. // [Blockly.Msg.ai_models_object_model_count, "Number"],
  8291. // [Blockly.Msg.ai_models_object_model_index, "Serial"],
  8292. [Blockly.Msg.ai_models_object_model_confidence, "Confidence"],
  8293. [Blockly.Msg.ai_models_face_model_ws, "2"],
  8294. [Blockly.Msg.ai_models_face_model_hs, "3"],
  8295. [Blockly.Msg.ai_models_object_model_x_center, "CX"],
  8296. [Blockly.Msg.ai_models_object_model_y_center, "CY"]
  8297. ]), "TYPE");
  8298. this.setInputsInline(false);
  8299. this.setOutput(true, null);
  8300. this.setColour("#ee783a");
  8301. var thisBlock = this;
  8302. this.setTooltip(function () {
  8303. var mode = thisBlock.getFieldValue('TYPE');
  8304. var TOOLTIPS = {
  8305. 'Object': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_name),
  8306. 'X': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_x),
  8307. 'Y': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_y),
  8308. 'W': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_w),
  8309. 'H': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_h),
  8310. // 'CX': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_x_center),
  8311. // 'CY': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_y_center),
  8312. // 'Number': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_count),
  8313. // 'Serial': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_index),
  8314. // 'Confidence': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_confidence)
  8315. };
  8316. return TOOLTIPS[mode];
  8317. });
  8318. this.setHelpUrl("");
  8319. }
  8320. };
  8321. Blockly.Python.ai_model_get = function (block) {
  8322. var type = block.getFieldValue('TYPE');
  8323. var variable_name = "BOXESI";
  8324. var _code = "";
  8325. if (type == "Object") {
  8326. _code = `labels[${variable_name}[4][0]]`
  8327. // _code = `"{}:{:.2f}%".format(labels[probs[${variable_name}][0]], probs[${variable_name}][1][probs[${variable_name}][0]]*100)`
  8328. } else if (type == "X") {
  8329. _code = '' + variable_name + '[0]';
  8330. } else if (type == "Y") {
  8331. _code = '' + variable_name + '[1]';
  8332. } else if (type == "W") {
  8333. _code = 'int(' + variable_name + '[0]+' + '' + variable_name + '[2])';
  8334. } else if (type == "H") {
  8335. _code = 'int(' + variable_name + '[1]+' + '' + variable_name + '[3])';
  8336. } else if (type == "Confidence") {
  8337. _code = `${variable_name}[4][1][${variable_name}[4][0]]*100`;
  8338. } else if (type == "CX") {
  8339. _code = `int((${variable_name}[0] +${variable_name}[0] + ${variable_name}[2])/2)`;
  8340. } else if (type == "CY") {
  8341. _code = `int((${variable_name}[1] + ${variable_name}[1] + ${variable_name}[3])/2)`;
  8342. }
  8343. else {
  8344. _code = `${variable_name}[${type}]`;
  8345. }
  8346. return [_code, Blockly.Python.ORDER_ATOMIC];
  8347. }
  8348. Blockly.Blocks['ai_model_look'] = {
  8349. init: function () {
  8350. this.appendDummyInput()
  8351. .appendField(Blockly.Msg.ai_models_object_model_if);
  8352. this.setInputsInline(false);
  8353. this.setOutput(true, null);
  8354. this.setColour("#ee783a");
  8355. this.setTooltip(Blockly.Msg.ai_model_look_TOOLTIP);
  8356. this.setHelpUrl("");
  8357. }
  8358. };
  8359. Blockly.Python.ai_model_look = function (block) {
  8360. var _code = "len(boxes)";
  8361. return [_code, Blockly.Python.ORDER_ATOMIC];
  8362. }
  8363. Blockly.Blocks['ai_model_look_attribute'] = {
  8364. init: function () {
  8365. this.appendDummyInput()
  8366. .appendField(Blockly.Msg.ai_model_look_attribute);
  8367. this.setNextStatement(true, null);
  8368. this.setPreviousStatement(true, null);
  8369. this.setColour("#ee783a");
  8370. this.setTooltip(Blockly.Msg.ai_model_look_attribute);
  8371. this.setHelpUrl("");
  8372. }
  8373. };
  8374. Blockly.Python['ai_model_look_attribute'] = function (block) {
  8375. Blockly.Python.addFunction("objectRecognize", `def objectRecognize():
  8376. global BOXES
  8377. if len(BOXES):
  8378. for BOXESI, BOXOBJ in enumerate(BOXES):
  8379. canvas.draw_string(BOXOBJ[0],(BOXOBJ[1]), ("".join([str(x) for x in [str(labels[PROBS[BOXESI][0]]), ",", round(PROBS[BOXESI][1][PROBS[BOXESI][0]]*100, 2)]])), scale = 1, color = (51,102,255) , thickness = 1)
  8380. canvas.draw_rectangle(BOXOBJ[0],BOXOBJ[1], BOXOBJ[0]+BOXOBJ[2],BOXOBJ[1]+ BOXOBJ[3], color=(255,0,0), thickness=1)
  8381. `)
  8382. var code = 'objectRecognize()\n';
  8383. return code;
  8384. };
  8385. // 猜拳识别
  8386. Blockly.Blocks['ai_model_Guesswork_init'] = {
  8387. init: function () {
  8388. this.appendDummyInput()
  8389. .appendField(Blockly.Msg.ai_models_init_title)
  8390. .appendField(Blockly.Msg.ai_models_init_guesswork_model);
  8391. // this.appendDummyInput().appendField(Blockly.Msg.ai_model_allinit_language).appendField(new Blockly.FieldDropdown([
  8392. // [Blockly.Msg.ai_speech_recognition_setup_set_english, "English"],
  8393. // [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "Simplified Chinese"],
  8394. // [Blockly.Msg.ai_speech_recognition_setup_set_traditional_chinese, "Traditional Chinese"]
  8395. // ]), "interface")
  8396. // this.appendValueInput("class_input")
  8397. // .setCheck(null)
  8398. // .appendField(Blockly.Msg.ai_models_customized_init_setup_name);
  8399. this.setPreviousStatement(true, null);
  8400. this.setNextStatement(true, null);
  8401. this.setColour("#ee783a");
  8402. var thisBlock = this;
  8403. this.setTooltip(function () {
  8404. var mode = thisBlock.getFieldValue('DEGREE');
  8405. var TOOLTIPS = {
  8406. 'Common Object Recognition': Blockly.Msg.ai_model_allinit_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model_title)
  8407. };
  8408. return TOOLTIPS[mode];
  8409. });
  8410. this.setHelpUrl('');
  8411. }
  8412. };
  8413. Blockly.Python.ai_model_Guesswork_init = function (block) {
  8414. var language = localStorage.getItem("handPyLanguage");
  8415. console.log(language)
  8416. let a = ''
  8417. if (language == "en") {
  8418. a = '["Scissors", "Stone" ,"Paper"]'
  8419. } else if (language == "zh-hans") {
  8420. a = '["剪刀", "石头" ,"布"]'
  8421. } else {
  8422. a = '["剪刀", "石頭" ,"布"]'
  8423. }
  8424. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  8425. Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
  8426. Blockly.Python.definitions_.import_Guesswork_init = `class Mora:
  8427. mud_path = "/root/preset/model/mora_int8.mud"
  8428. labels = ${a}
  8429. anchors = [3.23, 3.25, 1.47, 1.55, 5.09, 5.33, 4.03, 4.28, 2.12, 2.56]
  8430. def __init__(self) -> None:
  8431. from maix import nn
  8432. self.model = nn.load(self.mud_path)
  8433. from maix.nn import decoder
  8434. self.decoder = decoder.Yolo2(len(self.labels) , self.anchors , net_in_size = (224, 224) ,net_out_size = (7,7))
  8435. def __del__(self):
  8436. del self.model
  8437. del self.decoder
  8438. def cal_fps(self ,start , end):
  8439. one_second = 1
  8440. one_flash = end - start
  8441. fps = one_second / one_flash
  8442. return fps
  8443. def draw_rectangle_with_title(self ,img, box, disp_str , fps ):
  8444. img.draw_rectangle(box[0], box[1], box[0] + box[2], box[1] + box[3],color=(255, 0, 0), thickness=2)
  8445. img.draw_string(box[0], box[1] ,disp_str, scale=1,color=(222, 0, 3), thickness=2)
  8446. #img.draw_string(0, 0 ,"FPS :"+str(fps), scale=2 ,color=(0, 0, 255), thickness=2)
  8447. def process(self,input):
  8448. t = time()
  8449. out = self.model.forward(input, quantize=1, layout = "hwc")
  8450. boxes, probs = self.decoder.run(out, nms=0.5, threshold=0.3, img_size=(224,224))
  8451. for i, box in enumerate(boxes):
  8452. class_id = probs[i][0]
  8453. prob = probs[i][1][class_id]
  8454. disp_str = "{}:{:.2f}%".format(self.labels[class_id], prob*100)
  8455. fps = self.cal_fps(t, time())
  8456. self.draw_rectangle_with_title(input, box, disp_str, fps)
  8457. Mora = Mora()
  8458. `;
  8459. var _code = "";
  8460. return _code;
  8461. }
  8462. Blockly.Blocks['ai_model_Guesswork_load'] = {
  8463. init: function () {
  8464. this.appendDummyInput()
  8465. .appendField(Blockly.Msg.ai_models_load_title)
  8466. .appendField(Blockly.Msg.ai_models_init_guesswork_model);
  8467. // this.appendDummyInput()
  8468. // .appendField(Blockly.Msg.ai_models_init_source)
  8469. // .appendField(new Blockly.FieldVariable("img_guessworkrecognition"), "varitem");
  8470. this.setPreviousStatement(true, null);
  8471. this.setNextStatement(true, null);
  8472. this.setColour("#ee783a");
  8473. var thisBlock = this;
  8474. this.setTooltip(function () {
  8475. var mode = thisBlock.getFieldValue('DEGREE');
  8476. var TOOLTIPS = {
  8477. 'Common Object Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model)
  8478. };
  8479. return TOOLTIPS[mode];
  8480. });
  8481. this.setHelpUrl('');
  8482. }
  8483. };
  8484. Blockly.Python.ai_model_Guesswork_load = function (block) {
  8485. var language = localStorage.getItem("handPyLanguage");
  8486. let a = ''
  8487. if (language == "en") {
  8488. a = '["Scissors", "Stone" ,"Paper"]'
  8489. } else if (language == "zh-hans") {
  8490. a = '["剪刀", "石头" ,"布"]'
  8491. } else {
  8492. a = '["剪刀", "石頭" ,"布"]'
  8493. }
  8494. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  8495. Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
  8496. Blockly.Python.definitions_.import_Guesswork_init = `class Mora:
  8497. mud_path = "/root/preset/model/mora_int8.mud"
  8498. labels = ${a}
  8499. anchors = [3.23, 3.25, 1.47, 1.55, 5.09, 5.33, 4.03, 4.28, 2.12, 2.56]
  8500. def __init__(self) -> None:
  8501. self.model = nn.load(self.mud_path)
  8502. self.decoder = decoder.Yolo2(len(self.labels) , self.anchors , net_in_size = (224, 224) ,net_out_size = (7,7))
  8503. self.MORAS = {
  8504. "MORA_START_X": [],
  8505. "MORA_START_Y": [],
  8506. "MORA_CONFIDENCE": [],
  8507. "MORA_WIDTH": [],
  8508. "MORA_HEIGHT": [],
  8509. "MORA_CENTER_X": [],
  8510. "MORA_CENTER_Y": [],
  8511. "MORA_RESULT": [],
  8512. }
  8513. def __del__(self):
  8514. del self.model
  8515. del self.decoder
  8516. def cal_fps(self ,start , end):
  8517. one_second = 1
  8518. one_flash = end - start
  8519. fps = one_second / one_flash
  8520. return fps
  8521. def draw_rectangle_with_title(self ,img, box, disp_str ):
  8522. img.draw_rectangle(box[0], box[1], box[0] + box[2], box[1] + box[3],color=(255, 0, 0), thickness=2)
  8523. img.draw_string(box[0], box[1] ,disp_str, scale=1,color=(222, 0, 3), thickness=2)
  8524. def process(self,input):
  8525. out = self.model.forward(input, quantize=1, layout = "hwc")
  8526. boxes, probs = self.decoder.run(out, nms=0.5, threshold=0.3, img_size=(224,224))
  8527. for i, box in enumerate(boxes):
  8528. class_id = probs[i][0]
  8529. prob = probs[i][1][class_id]
  8530. disp_str = "{}:{:.2f}%".format(self.labels[class_id], prob*100)
  8531. self.draw_rectangle_with_title(input, box, disp_str)
  8532. boxes[i].append(probs[i])
  8533. return boxes
  8534. Mora = Mora()
  8535. `;
  8536. var _code = `canvas = canvas.crop(48,8,224,224)
  8537. BOXES = Mora.process(canvas)
  8538. `
  8539. return _code;
  8540. }
  8541. // ai_model_Guesswork_look_new
  8542. Blockly.Blocks['ai_model_Guesswork_look_new'] = {
  8543. init: function () {
  8544. this.appendDummyInput()
  8545. .appendField(Blockly.Msg.ai_model_guesswork_look_attribute)
  8546. this.appendStatementInput("input")
  8547. .setCheck(null)
  8548. .appendField(Blockly.Msg.basic_motion_statement_exec);
  8549. this.appendStatementInput("input1")
  8550. .setCheck(null)
  8551. .appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE);
  8552. this.setColour("#ee783a");
  8553. this.setNextStatement(true, null);
  8554. this.setPreviousStatement(true, null);
  8555. this.setTooltip(Blockly.Msg.ai_model_guesswork_look_attribute);
  8556. this.setHelpUrl("");
  8557. }
  8558. };
  8559. Blockly.Python.ai_model_Guesswork_look_new = function (block) {
  8560. var statements_input = Blockly.Python.statementToCode(block, 'input');
  8561. var statements_input1 = Blockly.Python.statementToCode(block, 'input1');
  8562. let allBlocks = block.workspace.getAllBlocks();
  8563. let global = ""
  8564. try {
  8565. global = allBlocks[0].workspace.variableList.toString()
  8566. }
  8567. catch (e) {
  8568. console.log(e)
  8569. }
  8570. Blockly.Python.addFunction("GuessworkStatements", `def GuessworkStatements(BOXESI):
  8571. ${global != "" ? `global ${global}` : "pass"}
  8572. ${statements_input}
  8573. `)
  8574. var code = `if len(BOXES) > 0:
  8575. for BOXESI in BOXES:
  8576. GuessworkStatements(BOXESI)
  8577. else:
  8578. ${statements_input1}
  8579. `
  8580. return code;
  8581. }
  8582. Blockly.Blocks['ai_model_Guesswork_get'] = {
  8583. init: function () {
  8584. this.appendDummyInput()
  8585. .appendField(new Blockly.FieldImage("blockly/media/object_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  8586. this.appendDummyInput()
  8587. .appendField(Blockly.Msg.ai_models_from)
  8588. .appendField(Blockly.Msg.ai_models_guesswork_model_get)
  8589. .appendField(new Blockly.FieldDropdown([
  8590. [Blockly.Msg.ai_models_object_model_name, "Object"],
  8591. [Blockly.Msg.ai_models_object_model_x, "X"],
  8592. [Blockly.Msg.ai_models_object_model_y, "Y"],
  8593. // [Blockly.Msg.ai_models_object_model_w, "W"],
  8594. // [Blockly.Msg.ai_models_object_model_h, "H"],
  8595. // [Blockly.Msg.ai_models_object_model_x_center, "CX"],
  8596. // [Blockly.Msg.ai_models_object_model_y_center, "CY"],
  8597. // [Blockly.Msg.ai_models_object_model_count, "Number"],
  8598. // [Blockly.Msg.ai_models_object_model_index, "Serial"],
  8599. [Blockly.Msg.ai_models_object_model_confidence, "Confidence"],
  8600. [Blockly.Msg.ai_models_face_model_ws, "2"],
  8601. [Blockly.Msg.ai_models_face_model_hs, "3"],
  8602. [Blockly.Msg.ai_models_object_model_x_center, "CX"],
  8603. [Blockly.Msg.ai_models_object_model_y_center, "CY"]
  8604. ]), "TYPE");
  8605. this.setInputsInline(false);
  8606. this.setOutput(true, null);
  8607. this.setColour("#ee783a");
  8608. var thisBlock = this;
  8609. this.setTooltip(Blockly.Msg.ai_models_guesswork_model_get);
  8610. this.setHelpUrl("");
  8611. }
  8612. };
  8613. Blockly.Python.ai_model_Guesswork_get = function (block) {
  8614. var type = block.getFieldValue('TYPE');
  8615. var variable_name = "BOXESI";
  8616. var _code = "";
  8617. if (type == "Object") {
  8618. _code = `Mora.labels[${variable_name}[4][0]]`
  8619. // _code = `"{}:{:.2f}%".format(labels[probs[${variable_name}][0]], probs[${variable_name}][1][probs[${variable_name}][0]]*100)`
  8620. } else if (type == "X") {
  8621. _code = '' + variable_name + '[0]';
  8622. } else if (type == "Y") {
  8623. _code = '' + variable_name + '[1]';
  8624. } else if (type == "W") {
  8625. _code = 'int(' + variable_name + '[0]+' + '' + variable_name + '[2])';
  8626. } else if (type == "H") {
  8627. _code = 'int(' + variable_name + '[1]+' + '' + variable_name + '[3])';
  8628. } else if (type == "Confidence") {
  8629. _code = `${variable_name}[4][1][${variable_name}[4][0]]*100`;
  8630. } else if (type == "CX") {
  8631. _code = `int((${variable_name}[0] +${variable_name}[0] + ${variable_name}[2])/2)`;
  8632. } else if (type == "CY") {
  8633. _code = `int((${variable_name}[1] + ${variable_name}[1] + ${variable_name}[3])/2)`;
  8634. }
  8635. else {
  8636. _code = `${variable_name}[${type}]`;
  8637. }
  8638. return [_code, Blockly.Python.ORDER_ATOMIC];
  8639. }
  8640. Blockly.Blocks['ai_model_Guesswork_look'] = {
  8641. init: function () {
  8642. this.appendDummyInput()
  8643. .appendField(Blockly.Msg.ai_models_guesswork_model_if);
  8644. this.setInputsInline(false);
  8645. this.setNextStatement(true, null);
  8646. this.setPreviousStatement(true, null);
  8647. this.setColour("#ee783a");
  8648. this.setTooltip(Blockly.Msg.ai_models_guesswork_model_if);
  8649. this.setHelpUrl("");
  8650. }
  8651. };
  8652. Blockly.Python.ai_model_Guesswork_look = function (block) {
  8653. Blockly.Python.addFunction("guessworkShowRecognize", `def guessworkShowRecognize():
  8654. global BOXES
  8655. if len(BOXES):
  8656. for BOXESI, BOXOBJ in enumerate(BOXES):
  8657. canvas.draw_string(10,0, (str(str(Mora.labels[PROBS[BOXESI][0]])) + str(str(":") + str(round(PROBS[BOXESI][1][PROBS[BOXESI][0]]*100, 2)))), scale = 1, color = (255,0,0) , thickness = 1)
  8658. canvas.draw_rectangle(BOXOBJ[0],BOXOBJ[1], BOXOBJ[0]+BOXOBJ[2],BOXOBJ[1]+ BOXOBJ[3], color=(255,0,0), thickness=1)
  8659. `)
  8660. var _code = "guessworkShowRecognize()\n";
  8661. return _code;
  8662. }
  8663. Blockly.Blocks['ai_model_Guesswork_look_attribute'] = {
  8664. init: function () {
  8665. this.appendDummyInput()
  8666. .appendField(Blockly.Msg.ai_model_guesswork_look_attribute);
  8667. this.setOutput(true, null);
  8668. this.setColour("#ee783a");
  8669. this.setTooltip(Blockly.Msg.ai_model_guesswork_look_attribute);
  8670. this.setHelpUrl("");
  8671. }
  8672. };
  8673. Blockly.Python['ai_model_Guesswork_look_attribute'] = function (block) {
  8674. var code = 'len(BOXES)';
  8675. return [code, Blockly.Python.ORDER_NONE];
  8676. };
  8677. Blockly.Blocks['ai_model_face_recognition_load'] = {
  8678. init: function () {
  8679. this.appendDummyInput()
  8680. .appendField(Blockly.Msg.ai_models_load_title)
  8681. .appendField(Blockly.Msg.ai_models_init_face_model);
  8682. // this.appendDummyInput()
  8683. // .appendField(Blockly.Msg.ai_models_init_source)
  8684. // .appendField(new Blockly.FieldVariable("img_facedetection"), "varitem");
  8685. this.setPreviousStatement(true, null);
  8686. this.setNextStatement(true, null);
  8687. this.setColour("#ee783a");
  8688. var thisBlock = this;
  8689. this.setTooltip(function () {
  8690. var mode = thisBlock.getFieldValue('DEGREE');
  8691. var TOOLTIPS = {
  8692. 'Human Face Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_face_model)
  8693. };
  8694. return TOOLTIPS[mode];
  8695. });
  8696. this.setHelpUrl('');
  8697. }
  8698. };
  8699. Blockly.Python.ai_model_face_recognition_load = function (block) {
  8700. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  8701. Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
  8702. Blockly.Python.definitions_.import_face_recognition = `class YoloFaceRecognize:
  8703. labels = ["person"]
  8704. anchors = [1.19, 1.98, 2.79, 4.59, 4.53, 8.92, 8.06, 5.29, 10.32, 10.65]
  8705. m = {
  8706. "param": "/root/preset/model/yolo2_face_awnn.param",
  8707. "bin": "/root/preset/model/yolo2_face_awnn.bin"
  8708. }
  8709. options = {
  8710. "model_type": "awnn",
  8711. "inputs": {
  8712. "input0": (224, 224, 3)
  8713. },
  8714. "outputs": {
  8715. "output0": (7, 7, (1+4+len(labels))*5)
  8716. },
  8717. "mean": [127.5, 127.5, 127.5],
  8718. "norm": [0.0078125, 0.0078125, 0.0078125],
  8719. }
  8720. def __init__(self):
  8721. self.model = nn.load(self.m, opt=self.options)
  8722. self.decoder = decoder.Yolo2(len(self.labels), self.anchors, net_in_size=(224, 224), net_out_size=(7, 7))
  8723. self.FACES = {
  8724. "FACES_START_X": [],
  8725. "FACES_START_Y": [],
  8726. "FACENUM": 0,
  8727. "FACES_CONFIDENCE": [],
  8728. "FACES_WIDTH": [],
  8729. "FACES_HEIGHT": [],
  8730. "FACES_CENTER_X": [],
  8731. "FACES_CENTER_Y": []
  8732. }
  8733. def __del__(self):
  8734. del self.model
  8735. del self.decoder
  8736. def faceShowDetection(self,canvas):
  8737. out = YoloFaceRecognize.model.forward(canvas.tobytes(), quantize=True, layout="hwc")
  8738. BOXES, PROBS = YoloFaceRecognize.decoder.run(out, nms=0.3, threshold=0.5, img_size=(224, 224))
  8739. if len(BOXES):
  8740. for BOXESI, BOXOBJ in enumerate(BOXES):
  8741. canvas.draw_rectangle(BOXOBJ[0],BOXOBJ[1], BOXOBJ[0]+BOXOBJ[2],BOXOBJ[1]+ BOXOBJ[3], color=(255,0,0), thickness=1)
  8742. BOXES[BOXESI].append(PROBS[BOXESI])
  8743. def returnFaces(self):
  8744. return self.FACES
  8745. YoloFaceRecognize = YoloFaceRecognize()
  8746. `;
  8747. var _code = `canvas = canvas.crop(48,8,224,224)
  8748. BOXES = YoloFaceRecognize.faceShowDetection(canvas)\n`
  8749. return _code;
  8750. }
  8751. Blockly.Blocks['ai_model_xy'] = {
  8752. init: function () {
  8753. this.appendDummyInput()
  8754. .appendField(new Blockly.FieldImage("blockly/media/face_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  8755. this.appendDummyInput()
  8756. .appendField(Blockly.Msg.ai_models_from)
  8757. .appendField(Blockly.Msg.ai_models_face_model_get)
  8758. .appendField(new Blockly.FieldDropdown([
  8759. [Blockly.Msg.ai_models_object_model_name, "Object"],
  8760. [Blockly.Msg.ai_models_face_model_x, "X"],
  8761. [Blockly.Msg.ai_models_face_model_y, "Y"],
  8762. // [Blockly.Msg.ai_models_face_model_w, "W"],
  8763. // [Blockly.Msg.ai_models_face_model_h, "H"],
  8764. // [Blockly.Msg.ai_models_face_model_x_center, "CX"],
  8765. // [Blockly.Msg.ai_models_face_model_y_center, "CY"],
  8766. [Blockly.Msg.ai_models_face_model_count, "Number"],
  8767. // [Blockly.Msg.ai_models_face_model_index, "Serial"],
  8768. [Blockly.Msg.ai_models_face_model_confidence, "Confidence"],
  8769. [Blockly.Msg.ai_models_face_model_ws, "2"],
  8770. [Blockly.Msg.ai_models_face_model_hs, "3"],
  8771. [Blockly.Msg.ai_models_object_model_x_center, "CX"],
  8772. [Blockly.Msg.ai_models_object_model_y_center, "CY"]
  8773. ]), "TYPE");
  8774. this.setInputsInline(false);
  8775. this.setOutput(true, null);
  8776. this.setColour("#ee783a");
  8777. var thisBlock = this;
  8778. this.setTooltip(function () {
  8779. var mode = thisBlock.getFieldValue('TYPE');
  8780. var TOOLTIPS = {
  8781. 'X': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x),
  8782. 'Y': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y),
  8783. 'W': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_w),
  8784. 'H': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_h),
  8785. // 'CX': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x_center),
  8786. // 'CY': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y_center),
  8787. 'Number': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_count),
  8788. // 'Serial': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_index),
  8789. // 'Confidence': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_confidence)
  8790. };
  8791. return TOOLTIPS[mode];
  8792. });
  8793. this.setHelpUrl("");
  8794. }
  8795. };
  8796. Blockly.Python.ai_model_xy = function (block) {
  8797. var type = block.getFieldValue('TYPE');
  8798. var variable_name = "BOXESI";
  8799. var _code = "";
  8800. if (type == "X") {
  8801. _code = '' + variable_name + '[0]';
  8802. } else if (type == "Y") {
  8803. _code = '' + variable_name + '[1]';
  8804. } else if (type == "W") {
  8805. _code = 'int(' + variable_name + '[0]+' + '' + variable_name + '[2])';
  8806. } else if (type == "H") {
  8807. _code = 'int(' + variable_name + '[1]+' + '' + variable_name + '[3])';
  8808. } else if (type == "Confidence") {
  8809. _code = `${variable_name}[4][1][${variable_name}[4][0]]*100`;
  8810. } else if (type == "Object") {
  8811. _code = `"Face"`;
  8812. } else if (type == "CX") {
  8813. _code = `int((${variable_name}[0] +${variable_name}[0] + ${variable_name}[2])/2)`;
  8814. } else if (type == "CY") {
  8815. _code = `int((${variable_name}[1] + ${variable_name}[1] + ${variable_name}[3])/2)`;
  8816. } else if (type == "Number") {
  8817. _code = `len(boxes)`;
  8818. }
  8819. else {
  8820. _code = `${variable_name}[${type}]`;
  8821. }
  8822. return [_code, Blockly.Python.ORDER_ATOMIC];
  8823. };
  8824. Blockly.Blocks['ai_model_face_new'] = {
  8825. init: function () {
  8826. this.appendDummyInput()
  8827. .appendField(Blockly.Msg.ai_model_face_model_list)
  8828. this.appendStatementInput("input")
  8829. .setCheck(null)
  8830. .appendField(Blockly.Msg.basic_motion_statement_exec);
  8831. this.appendStatementInput("input1")
  8832. .setCheck(null)
  8833. .appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE);
  8834. this.setColour("#ee783a");
  8835. this.setNextStatement(true, null);
  8836. this.setPreviousStatement(true, null);
  8837. this.setTooltip(Blockly.Msg.ai_model_face_model_list);
  8838. this.setHelpUrl("");
  8839. }
  8840. };
  8841. Blockly.Python.ai_model_face_new = function (block) {
  8842. var statements_input = Blockly.Python.statementToCode(block, 'input');
  8843. var statements_input1 = Blockly.Python.statementToCode(block, 'input1');
  8844. let allBlocks = block.workspace.getAllBlocks();
  8845. let global = ""
  8846. try {
  8847. global = allBlocks[0].workspace.variableList.toString()
  8848. }
  8849. catch (e) {
  8850. console.log(e)
  8851. }
  8852. Blockly.Python.addFunction("GuessworkStatements", `def GuessworkStatements(BOXESI):
  8853. ${global != "" ? `global ${global}` : "pass"}
  8854. ${statements_input}
  8855. `)
  8856. var code = `if len(BOXES) > 0:
  8857. for BOXESI in BOXES:
  8858. GuessworkStatements(BOXESI)
  8859. else:
  8860. ${statements_input1}
  8861. `
  8862. return code;
  8863. }
  8864. Blockly.Blocks['ai_model_face'] = {
  8865. init: function () {
  8866. this.appendDummyInput()
  8867. .appendField(Blockly.Msg.ai_models_face_model_if);
  8868. this.setInputsInline(false);
  8869. this.setNextStatement(true, null);
  8870. this.setPreviousStatement(true, null);
  8871. this.setColour("#ee783a");
  8872. this.setTooltip(Blockly.Msg.ai_models_face_model_if);
  8873. this.setHelpUrl("");
  8874. }
  8875. };
  8876. Blockly.Python.ai_model_face = function (block) {
  8877. Blockly.Python.addFunction("faceShowDetection", `def faceShowDetection():
  8878. global BOXES
  8879. if len(BOXES):
  8880. for BOXESI, BOXOBJ in enumerate(BOXES):
  8881. canvas.draw_rectangle(BOXOBJ[0],BOXOBJ[1], BOXOBJ[0]+BOXOBJ[2],BOXOBJ[1]+ BOXOBJ[3], color=(255,0,0), thickness=1)
  8882. `)
  8883. var _code = "faceShowDetection()\n";
  8884. return _code;
  8885. }
  8886. Blockly.Blocks['ai_model_face_attribute'] = {
  8887. init: function () {
  8888. this.appendDummyInput()
  8889. .appendField(Blockly.Msg.ai_model_face_model_list);
  8890. this.setOutput(true, null);
  8891. this.setColour("#ee783a");
  8892. this.setTooltip(Blockly.Msg.ai_model_face_model_list);
  8893. this.setHelpUrl("");
  8894. }
  8895. };
  8896. Blockly.Python['ai_model_face_attribute'] = function (block) {
  8897. var code = 'boxes';
  8898. return [code, Blockly.Python.ORDER_NONE];
  8899. };
  8900. // 车牌识别
  8901. Blockly.Blocks['ai_model_card_recognition_init'] = {
  8902. init: function () {
  8903. // this.appendDummyInput()
  8904. // .appendField(new Blockly.FieldImage("blockly/media/header_customized_model.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
  8905. this.appendDummyInput()
  8906. .appendField(Blockly.Msg.ai_models_init_title)
  8907. .appendField(Blockly.Msg.ai_models_init_card_model);
  8908. this.setInputsInline(false);
  8909. this.setPreviousStatement(true, null);
  8910. this.setNextStatement(true, null);
  8911. this.setColour("#ee783a");
  8912. this.setTooltip(Blockly.Msg.ai_model_customized_init_setup_definition_TOOLTIP);
  8913. this.setHelpUrl("");
  8914. }
  8915. };
  8916. Blockly.Python['ai_model_card_recognition_init'] = function (block) {
  8917. // TODO: Assemble Python into code variable.
  8918. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  8919. Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
  8920. Blockly.Python.addVariable('CARDDATABOEX', `CARDDATABOEX = ""`, true)
  8921. Blockly.Python.definitions_['v831_card_recognition_init'] = `class LPR:
  8922. loc_model_path = "/root/preset/model/loc.mud"
  8923. reg_model_path = "/root/preset/model/reg.mud"
  8924. chars = ["皖", "沪", "津", "渝", "冀", "晋", "蒙", "辽", "吉", "黑",
  8925. "苏", "浙", "京", "闽", "赣", "鲁", "豫", "鄂", "湘", "粤",
  8926. "桂", "琼", "川", "贵", "云", "藏", "陕", "甘", "青", "宁",
  8927. "新", "警", "学", "A", "B", "C", "D", "E", "F", "G",
  8928. "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S",
  8929. "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3",
  8930. "4", "5", "6", "7", "8", "9", "-"]
  8931. variances = [0.1, 0.2]
  8932. steps = [8, 16, 32]
  8933. min_sizes = [12, 24, 48, 96, 192, 320]
  8934. card_input_img = None
  8935. def __init__(self) -> None:
  8936. from maix import nn
  8937. self.loc_model = nn.load(self.loc_model_path, opt=None)
  8938. self.reg_model = nn.load(self.reg_model_path, opt=None)
  8939. from maix.nn import decoder
  8940. self.loc_decoder = decoder.license_plate_location(
  8941. [224, 224], self.steps, self.min_sizes, self.variances)
  8942. self.reg_decoder = decoder.CTC((1, 68, 18))
  8943. def __del__(self):
  8944. del self.loc_model
  8945. del self.loc_decoder
  8946. def cal_fps(self, start, end):
  8947. one_second = 1
  8948. one_flash = end - start
  8949. fps = one_second / one_flash
  8950. return fps
  8951. def draw_fps(self, img, fps):
  8952. img.draw_string(0, 0, "FPS :"+str(fps), scale=1,
  8953. color=(255, 0, 255), thickness=1)
  8954. def draw_string(self, img, x, y, string, color):
  8955. img.draw_string(x, y, string, color=color)
  8956. def draw_paste(self, src, dst):
  8957. src.paste(dst, 0, 0)
  8958. def draw_rectangle(self, img, box):
  8959. img.draw_rectangle(box[0], box[1], box[2], box[3],
  8960. color=(230, 230, 250), thickness=2)
  8961. def draw_point(self, img, landmark):
  8962. for i in range(4):
  8963. x = landmark[2 * i]
  8964. y = landmark[2 * i + 1]
  8965. img.draw_rectangle(x-2, y-2, x+2, y+2,
  8966. color=(193, 255, 193), thickness=-1)
  8967. def process(self, input):
  8968. global CARDDATABOEX
  8969. self.card_input_img = input
  8970. # retinaface decoder only support chw layout
  8971. loc_out = self.loc_model.forward(input, quantize=1, layout="chw")
  8972. boxes, landmarks = self.loc_decoder.run(loc_out, nms=0.2, score_thresh=0.7, outputs_shape=[
  8973. [1, 4, 2058], [1, 2, 2058], [1, 8, 2058]])
  8974. if len(boxes):
  8975. # print(boxes,landmarks)
  8976. for boxesi, box in enumerate(boxes):
  8977. boxes[boxesi].append(landmarks[boxesi])
  8978. CARDDATABOEX = boxes
  8979. def get_card_data(self, landmark):
  8980. # landmark = i[4][:6]
  8981. reg_in = self.card_input_img.crop_affine(landmark, 94, 24)
  8982. reg_out = self.reg_model.forward(reg_in, quantize=1, layout="chw")
  8983. LP_number = self.reg_decoder.run(reg_out)
  8984. string_LP = ""
  8985. for id in LP_number:
  8986. string_LP += self.chars[id]
  8987. return string_LP
  8988. LPRCARD = LPR()
  8989. `;
  8990. var code = '';
  8991. return code;
  8992. };
  8993. // 车牌识别
  8994. Blockly.Blocks['ai_model_card_recognition_load'] = {
  8995. init: function () {
  8996. this.appendDummyInput()
  8997. .appendField(Blockly.Msg.ai_models_load_title)
  8998. .appendField(Blockly.Msg.ai_models_init_card_model);
  8999. // this.appendDummyInput()
  9000. // .appendField(Blockly.Msg.ai_models_customized_init_setup_source)
  9001. // .appendField(new Blockly.FieldVariable("img_card_recognition"), "varitem");
  9002. this.setInputsInline(false);
  9003. this.setPreviousStatement(true, null);
  9004. this.setNextStatement(true, null);
  9005. this.setColour("#ee783a");
  9006. this.setTooltip(Blockly.Msg.ai_model_customized_init_setup_definition_TOOLTIP);
  9007. this.setHelpUrl("");
  9008. }
  9009. };
  9010. Blockly.Python['ai_model_card_recognition_load'] = function (block) {
  9011. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  9012. Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
  9013. Blockly.Python.addVariable('CARDDATABOEX', `CARDDATABOEX = ""`, true)
  9014. Blockly.Python.definitions_['v831_card_recognition_init'] = `class LPR:
  9015. loc_model_path = "/root/preset/model/loc.mud"
  9016. reg_model_path = "/root/preset/model/reg.mud"
  9017. chars = ["皖", "沪", "津", "渝", "冀", "晋", "蒙", "辽", "吉", "黑",
  9018. "苏", "浙", "京", "闽", "赣", "鲁", "豫", "鄂", "湘", "粤",
  9019. "桂", "琼", "川", "贵", "云", "藏", "陕", "甘", "青", "宁",
  9020. "新", "警", "学", "A", "B", "C", "D", "E", "F", "G",
  9021. "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S",
  9022. "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3",
  9023. "4", "5", "6", "7", "8", "9", "-"]
  9024. variances = [0.1, 0.2]
  9025. steps = [8, 16, 32]
  9026. min_sizes = [12, 24, 48, 96, 192, 320]
  9027. card_input_img = None
  9028. def __init__(self) -> None:
  9029. self.loc_model = nn.load(self.loc_model_path, opt=None)
  9030. self.reg_model = nn.load(self.reg_model_path, opt=None)
  9031. self.loc_decoder = decoder.license_plate_location(
  9032. [224, 224], self.steps, self.min_sizes, self.variances)
  9033. self.reg_decoder = decoder.CTC((1, 68, 18))
  9034. self.LPRS = {
  9035. "LPR_START_X":[],
  9036. "LPR_START_Y":[],
  9037. "LPR_CENTER_X":[],
  9038. "LPR_CENTER_Y":[],
  9039. "LPR_WIDTH":[],
  9040. "LPR_HEIGHT":[],
  9041. "LPR_CONFIDENCE":[],
  9042. "LPR_RESULT":[],
  9043. }
  9044. def __del__(self):
  9045. del self.loc_model
  9046. del self.loc_decoder
  9047. def cal_fps(self, start, end):
  9048. one_second = 1
  9049. one_flash = end - start
  9050. fps = one_second / one_flash
  9051. return fps
  9052. def draw_fps(self, img, fps):
  9053. img.draw_string(0, 0, "FPS :"+str(fps), scale=1,
  9054. color=(255, 0, 255), thickness=1)
  9055. def draw_string(self, img, x, y, string, color):
  9056. img.draw_string(x, y, string, color=color)
  9057. def draw_paste(self, src, dst):
  9058. src.paste(dst, 0, 0)
  9059. def draw_rectangle(self, img, box):
  9060. img.draw_rectangle(box[0], box[1], box[2], box[3],
  9061. color=(230, 230, 250), thickness=2)
  9062. def draw_point(self, img, landmark):
  9063. for i in range(4):
  9064. x = landmark[2 * i]
  9065. y = landmark[2 * i + 1]
  9066. img.draw_rectangle(x-2, y-2, x+2, y+2,
  9067. color=(193, 255, 193), thickness=-1)
  9068. def process(self, input):
  9069. self.card_input_img = input
  9070. # retinaface decoder only support chw layout
  9071. loc_out = self.loc_model.forward(input, quantize=1, layout="chw")
  9072. boxes, landmarks = self.loc_decoder.run(loc_out, nms=0.2, score_thresh=0.7, outputs_shape=[[1, 4, 2058], [1, 2, 2058], [1, 8, 2058]])
  9073. self.LPRS = {
  9074. "LPR_START_X":[],
  9075. "LPR_START_Y":[],
  9076. "LPR_CENTER_X":[],
  9077. "LPR_CENTER_Y":[],
  9078. "LPR_WIDTH":[],
  9079. "LPR_HEIGHT":[],
  9080. "LPR_CONFIDENCE":[],
  9081. "LPR_RESULT":[],
  9082. }
  9083. for i,box in enumerate(boxes):
  9084. landmark = landmarks[i][:6]
  9085. reg_in = input.crop_affine(landmark , 94 , 24)
  9086. reg_out = self.reg_model.forward(reg_in , quantize=1, layout = "chw")
  9087. LP_number = self.reg_decoder.run(reg_out)
  9088. string_LP = ''
  9089. for id in LP_number:
  9090. string_LP += self.chars[id]
  9091. # string_LP += str(id)
  9092. input.draw_string(box[0]+5, box[1]+5, string_LP, color=(225,0,0))
  9093. input.draw_rectangle(box[0], box[1], box[2], box[3],color=(250,0,0), thickness=1)
  9094. boxes[i].append(landmarks[i])
  9095. return boxes
  9096. def get_card_data(self, landmark):
  9097. # landmark = i[4][:6]
  9098. reg_in = self.card_input_img.crop_affine(landmark, 94, 24)
  9099. reg_out = self.reg_model.forward(reg_in, quantize=1, layout="chw")
  9100. LP_number = self.reg_decoder.run(reg_out)
  9101. string_LP = ""
  9102. for id in LP_number:
  9103. string_LP += self.chars[id]
  9104. return string_LP
  9105. LPRCARD = LPR()
  9106. `;
  9107. // TODO: Assemble Python into code variable.
  9108. var code = `canvas = canvas.crop(48,8,224,224)
  9109. BOXES = LPRCARD.process(canvas)
  9110. `;
  9111. return code;
  9112. };
  9113. // 车牌识别
  9114. Blockly.Blocks['ai_model_card_xy_new'] = {
  9115. init: function () {
  9116. this.appendDummyInput()
  9117. .appendField(Blockly.Msg.ai_models_card_attribute)
  9118. this.appendStatementInput("input")
  9119. .setCheck(null)
  9120. .appendField(Blockly.Msg.basic_motion_statement_exec);
  9121. this.appendStatementInput("input1")
  9122. .setCheck(null)
  9123. .appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE);
  9124. this.setColour("#ee783a");
  9125. this.setNextStatement(true, null);
  9126. this.setPreviousStatement(true, null);
  9127. this.setTooltip(Blockly.Msg.ai_models_card_attribute);
  9128. this.setHelpUrl("");
  9129. }
  9130. };
  9131. Blockly.Python['ai_model_card_xy_new'] = function (block) {
  9132. var statements_input = Blockly.Python.statementToCode(block, 'input');
  9133. var statements_input1 = Blockly.Python.statementToCode(block, 'input1');
  9134. let allBlocks = block.workspace.getAllBlocks();
  9135. let global = ""
  9136. try {
  9137. global = allBlocks[0].workspace.variableList.toString()
  9138. }
  9139. catch (e) {
  9140. console.log(e)
  9141. }
  9142. Blockly.Python.addFunction("cardStatements", `def cardStatements(BOXESI):
  9143. ${global != "" ? `global ${global}` : "pass"}
  9144. ${statements_input}
  9145. `)
  9146. var code = `if len(BOXES) > 0:
  9147. for BOXESI in BOXES:
  9148. cardStatements(BOXESI)
  9149. else:
  9150. ${statements_input1}
  9151. `
  9152. return code;
  9153. };
  9154. Blockly.Blocks['ai_model_card_get'] = {
  9155. init: function () {
  9156. this.appendDummyInput()
  9157. .appendField(new Blockly.FieldImage("blockly/media/object_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  9158. this.appendDummyInput()
  9159. .appendField(Blockly.Msg.ai_models_from)
  9160. .appendField(Blockly.Msg.ai_models_card_model_get)
  9161. .appendField(new Blockly.FieldDropdown([
  9162. [Blockly.Msg.ai_models_init_card_result, "Object"],
  9163. [Blockly.Msg.ai_models_object_model_x, "X"],
  9164. [Blockly.Msg.ai_models_object_model_y, "Y"],
  9165. [Blockly.Msg.ai_models_object_model_w, "W"],
  9166. [Blockly.Msg.ai_models_object_model_h, "H"],
  9167. // [Blockly.Msg.ai_models_object_model_x_center, "CX"],
  9168. // [Blockly.Msg.ai_models_object_model_y_center, "CY"],
  9169. // [Blockly.Msg.ai_models_object_model_count, "Number"],
  9170. // [Blockly.Msg.ai_models_object_model_index, "Serial"],
  9171. [Blockly.Msg.ai_models_object_model_confidence, "Confidence"],
  9172. [Blockly.Msg.ai_models_face_model_ws, "2"],
  9173. [Blockly.Msg.ai_models_face_model_hs, "3"],
  9174. [Blockly.Msg.ai_models_object_model_x_center, "CX"],
  9175. [Blockly.Msg.ai_models_object_model_y_center, "CY"]
  9176. ]), "TYPE");
  9177. this.setInputsInline(false);
  9178. this.setOutput(true, null);
  9179. this.setColour("#ee783a");
  9180. var thisBlock = this;
  9181. this.setTooltip(Blockly.Msg.ai_models_guesswork_model_get);
  9182. this.setHelpUrl("");
  9183. }
  9184. };
  9185. Blockly.Python.ai_model_card_get = function (block) {
  9186. var type = block.getFieldValue('TYPE');
  9187. var variable_name = "BOXESI";
  9188. var _code = "";
  9189. if (type == "Object") {
  9190. _code = `LPRCARD.get_card_data(${variable_name}[4][:6])`
  9191. // _code = `"{}:{:.2f}%".format(labels[probs[${variable_name}][0]], probs[${variable_name}][1][probs[${variable_name}][0]]*100)`
  9192. } else if (type == "X") {
  9193. _code = '' + variable_name + '[0]';
  9194. } else if (type == "Y") {
  9195. _code = '' + variable_name + '[1]';
  9196. } else if (type == "W") {
  9197. _code = 'int(' + variable_name + '[2])';
  9198. } else if (type == "H") {
  9199. _code = 'int(' + variable_name + '[3])';
  9200. } else if (type == "Confidence") {
  9201. _code = `${variable_name}[4][1][${variable_name}[4][0]]*100`;
  9202. } else if (type == "CX") {
  9203. _code = `int((${variable_name}[0] + ${variable_name}[2])/2)`;
  9204. } else if (type == "CY") {
  9205. _code = `int((${variable_name}[1] + ${variable_name}[3])/2)`;
  9206. }
  9207. else {
  9208. _code = `${variable_name}[${type}]-${variable_name}[${type - 2}]`;
  9209. }
  9210. // }
  9211. return [_code, Blockly.Python.ORDER_ATOMIC];
  9212. }
  9213. //
  9214. // 车牌识别
  9215. Blockly.Blocks['ai_model_card_xy'] = {
  9216. init: function () {
  9217. this.appendDummyInput()
  9218. .appendField(Blockly.Msg.ai_models_card_if_true);
  9219. this.setInputsInline(false);
  9220. this.setNextStatement(true, null);
  9221. this.setPreviousStatement(true, null);
  9222. this.setColour("#ee783a");
  9223. this.setTooltip(Blockly.Msg.ai_models_card_if_true);
  9224. this.setHelpUrl("");
  9225. }
  9226. };
  9227. Blockly.Python['ai_model_card_xy'] = function (block) {
  9228. Blockly.Python.addFunction("cardShowRecognize", `def cardShowRecognize():
  9229. global CARDDATABOEX
  9230. if len(CARDDATABOEX):
  9231. for CARDDATABOEXI in CARDDATABOEX:
  9232. canvas.draw_rectangle(CARDDATABOEXI[0],CARDDATABOEXI[1], CARDDATABOEXI[0]+CARDDATABOEXI[2]-CARDDATABOEXI[0],CARDDATABOEXI[1]+ CARDDATABOEXI[3]-CARDDATABOEXI[1], color=(255,0,0), thickness=1)
  9233. canvas.draw_string(CARDDATABOEXI[0],CARDDATABOEXI[1], (str(LPRCARD.get_card_data(CARDDATABOEXI[4][:6]))), scale = 1, color = (255,255,255) , thickness = 1)
  9234. `)
  9235. var code = 'cardShowRecognize()\n';
  9236. return code;
  9237. };
  9238. Blockly.Blocks['ai_model_card_result'] = {
  9239. init: function () {
  9240. this.appendDummyInput()
  9241. .appendField(Blockly.Msg.ai_models_card_attribute);
  9242. this.setInputsInline(false);
  9243. this.setOutput(true, null);
  9244. this.setColour("#ee783a");
  9245. this.setTooltip(Blockly.Msg.ai_models_card_attribute);
  9246. this.setHelpUrl("");
  9247. }
  9248. };
  9249. Blockly.Python['ai_model_card_result'] = function (block) {
  9250. var code = 'CARDDATABOEX';
  9251. return [code, Blockly.Python.ORDER_ATOMIC];
  9252. };
  9253. Blockly.Blocks['ai_model_face_recognition_init_new'] = {
  9254. init: function () {
  9255. this.appendDummyInput().appendField(Blockly.Msg.ai_models_init_title)
  9256. .appendField('人脸识别模型');
  9257. this.setPreviousStatement(true, null);
  9258. this.setNextStatement(true, null);
  9259. this.setColour("#ee783a");
  9260. this.setTooltip(Blockly.Msg.ai_models_init_title + Blockly.Msg.ai_models_init_face_model);
  9261. this.setHelpUrl("");
  9262. }
  9263. };
  9264. Blockly.Python.ai_model_face_recognition_init_new = function (block) {
  9265. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  9266. Blockly.Python.definitions_['v831_import_FaceRecognize'] = `from maix.nn.app.face import FaceRecognize`
  9267. Blockly.Python.definitions_.import_face_recognition_init_new = `
  9268. class Face_recognize:
  9269. score_threshold = 70 #识别分数阈值
  9270. input_size = (224, 224, 3) #输入图片尺寸
  9271. input_size_fe = (128, 128, 3) #输入人脸数据
  9272. feature_len = 256 #人脸数据宽度
  9273. steps = [8, 16, 32] #
  9274. channel_num = 0 #通道数量
  9275. users = [] #初始化用户列表
  9276. threshold = 0.5 #人脸阈值
  9277. nms = 0.3
  9278. max_face_num = 3 #输出的画面中的人脸的最大个数
  9279. names = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] #人脸标签定义
  9280. model = {
  9281. "param": "/root/preset/model/model_int8.param",
  9282. "bin": "/root/preset/model/model_int8.bin"
  9283. }
  9284. model_fe = {
  9285. "param": "/root/preset/model/fe_res18_117.param",
  9286. "bin": "/root/preset/model/fe_res18_117.bin"
  9287. }
  9288. def __init__(self):
  9289. for i in range(len(self.steps)):
  9290. self.channel_num += self.input_size[1] / self.steps[i] * (self.input_size[0] / self.steps[i]) * 2
  9291. self.channel_num = int(self.channel_num) #统计通道数量
  9292. self.options = { #准备人脸输出参数
  9293. "model_type": "awnn",
  9294. "inputs": {
  9295. "input0": self.input_size
  9296. },
  9297. "outputs": {
  9298. "output0": (1, 4, self.channel_num) ,
  9299. "431": (1, 2, self.channel_num) ,
  9300. "output2": (1, 10, self.channel_num)
  9301. },
  9302. "mean": [127.5, 127.5, 127.5],
  9303. "norm": [0.0078125, 0.0078125, 0.0078125],
  9304. }
  9305. self.options_fe = { #准备特征提取参数
  9306. "model_type": "awnn",
  9307. "inputs": {
  9308. "inputs_blob": self.input_size_fe
  9309. },
  9310. "outputs": {
  9311. "FC_blob": (1, 1, self.feature_len)
  9312. },
  9313. "mean": [127.5, 127.5, 127.5],
  9314. "norm": [0.0078125, 0.0078125, 0.0078125],
  9315. }
  9316. print("-- load model:", self.model)
  9317. self.m = nn.load(self.model, opt=self.options)
  9318. print("-- load ok")
  9319. print("-- load model:", self.model_fe)
  9320. self.m_fe = nn.load(self.model_fe, opt=self.options_fe)
  9321. print("-- load ok")
  9322. self.face_recognizer = FaceRecognize(self.m, self.m_fe, self.feature_len, self.input_size, self.threshold, self.nms, self.max_face_num)
  9323. def map_face(self,box,points): #将224*224空间的位置转换到240*240或320*240空间内
  9324. from maix import display # print(box,points)
  9325. if display.width() == display.height():
  9326. def tran(x):
  9327. return int(x/224*display.width())
  9328. box = list(map(tran, box))
  9329. def tran_p(p):
  9330. return list(map(tran, p))
  9331. points = list(map(tran_p, points))
  9332. else:
  9333. # 168x224(320x240) > 224x224(240x240) > 320x240
  9334. s = (224*display.height()/display.width()) # 168x224
  9335. w, h, c = display.width()/224, display.height()/224, 224/s
  9336. t, d = c*h, (224 - s) // 2 # d = 224 - s // 2 == 28
  9337. box[0], box[1], box[2], box[3] = int(box[0]*w), int((box[1]-28)*t), int(box[2]*w), int((box[3])*t)
  9338. def tran_p(p):
  9339. return [int(p[0]*w), int((p[1]-d)*t)] # 224 - 168 / 2 = 28 so 168 / (old_h - 28) = 240 / new_h
  9340. points = list(map(tran_p, points))
  9341. # print(box,points)
  9342. return box,points
  9343. def recognize(self, feature): #进行人脸匹配
  9344. def _compare(user): #定义映射函数
  9345. return self.face_recognizer.compare(user, feature) #推测匹配分数 score相关分数
  9346. face_score_l = list(map(_compare,self.users)) #映射特征数据在记录中的比对分数
  9347. return max(enumerate(face_score_l), key=lambda x: x[-1]) #提取出人脸分数最大值和最大值所在的位置
  9348. def __del__(self):
  9349. del self.face_recognizer
  9350. del self.m_fe
  9351. del self.m
  9352. face_recognizer = Face_recognize()
  9353. `;
  9354. // var degee = block.getFieldValue('DEGREE');
  9355. var _code = "";
  9356. // Blockly.Python.addVariable('task_facerecognition', 'task_facerecognition = None', true);
  9357. return [_code, Blockly.Python.ORDER_ATOMIC];
  9358. }
  9359. Blockly.Blocks['ai_model_face_recognition_load_new'] = {
  9360. init: function () {
  9361. this.appendDummyInput()
  9362. .appendField(Blockly.Msg.ai_models_load_title)
  9363. .appendField(Blockly.Msg.ai_models_init_face_model);
  9364. this.appendDummyInput()
  9365. .appendField(Blockly.Msg.ai_models_init_source)
  9366. .appendField(new Blockly.FieldVariable("img_facerecognition"), "varitem");
  9367. this.setPreviousStatement(true, null);
  9368. this.setNextStatement(true, null);
  9369. this.setColour("#ee783a");
  9370. var thisBlock = this;
  9371. this.setTooltip(function () {
  9372. var mode = thisBlock.getFieldValue('DEGREE');
  9373. var TOOLTIPS = {
  9374. 'Human Face Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_face_model)
  9375. };
  9376. return TOOLTIPS[mode];
  9377. });
  9378. this.setHelpUrl('');
  9379. }
  9380. };
  9381. Blockly.Python.ai_model_face_recognition_load_new = function (block) {
  9382. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  9383. // var camera_variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('camera_varitem'), Blockly.Variables.NAME_TYPE);
  9384. // Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
  9385. // var degee = block.getFieldValue('DEGREE');
  9386. var _code = `facesRecognitionLoadNew = face_recognizer.face_recognizer.get_faces(AI_img.tobytes(),False) #提取人脸特征信息
  9387. `;
  9388. // Blockly.Python.addVariable('code_facerecognition', '', true);
  9389. // _code += "code_facerecognition = kpu.run_yolo2(task_facerecognition, " + variable_name + ")\n";
  9390. // _code += variable_name + ".ai_to_pix()\n";
  9391. return _code;
  9392. }
  9393. Blockly.Blocks['ai_model_xy_new'] = {
  9394. init: function () {
  9395. this.appendDummyInput()
  9396. .appendField(new Blockly.FieldImage("blockly/media/face_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  9397. this.appendDummyInput()
  9398. .appendField(Blockly.Msg.ai_models_from)
  9399. .appendField(new Blockly.FieldVariable("i"), "varitem")
  9400. .appendField(Blockly.Msg.ai_models_face_model_get)
  9401. .appendField(new Blockly.FieldDropdown([
  9402. [Blockly.Msg.ai_models_face_model_x, "X"],
  9403. [Blockly.Msg.ai_models_face_model_y, "Y"],
  9404. [Blockly.Msg.ai_models_face_model_w, "W"],
  9405. [Blockly.Msg.ai_models_face_model_h, "H"],
  9406. [Blockly.Msg.ai_models_face_model_x_center, "CX"],
  9407. [Blockly.Msg.ai_models_face_model_y_center, "CY"],
  9408. [Blockly.Msg.ai_models_face_model_count, "Number"],
  9409. [Blockly.Msg.ai_models_face_model_index, "Serial"],
  9410. [Blockly.Msg.ai_models_face_model_confidence, "Confidence"]
  9411. ]), "TYPE");
  9412. this.setInputsInline(false);
  9413. this.setOutput(true, null);
  9414. this.setColour("#ee783a");
  9415. var thisBlock = this;
  9416. this.setTooltip(function () {
  9417. var mode = thisBlock.getFieldValue('TYPE');
  9418. var TOOLTIPS = {
  9419. 'X': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x),
  9420. 'Y': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y),
  9421. 'W': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_w),
  9422. 'H': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_h),
  9423. 'CX': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x_center),
  9424. 'CY': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y_center),
  9425. 'Number': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_count),
  9426. 'Serial': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_index),
  9427. 'Confidence': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_confidence)
  9428. };
  9429. return TOOLTIPS[mode];
  9430. });
  9431. this.setHelpUrl("");
  9432. }
  9433. };
  9434. Blockly.Python.ai_model_xy_new = function (block) {
  9435. var type = block.getFieldValue('TYPE');
  9436. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  9437. var _code = "";
  9438. if (type == "X") {
  9439. _code = variable_name + "[0]";
  9440. } else if (type == "Y") {
  9441. _code = variable_name + "[1]";
  9442. } else if (type == "W") {
  9443. _code = variable_name + "[0] + " + variable_name + "[2]";
  9444. } else if (type == "H") {
  9445. _code = variable_name + "[1] + " + variable_name + "[3]";
  9446. }
  9447. // else if (type == "Number") {
  9448. // _code = variable_name + ".objnum()";
  9449. // } else if (type == "Serial") {
  9450. // _code = variable_name + ".index()";
  9451. // } else if (type == "Confidence") {
  9452. // _code = variable_name + ".value()";
  9453. // } else if (type == "CX") {
  9454. // _code = variable_name + ".x()+(" + variable_name + ".w()/2)";
  9455. // } else if (type == "CY") {
  9456. // _code = variable_name + ".y()+(" + variable_name + ".h()/2)";
  9457. // }
  9458. return [_code, Blockly.Python.ORDER_ATOMIC];
  9459. };
  9460. Blockly.Blocks['ai_model_face_attribute_new'] = {
  9461. init: function () {
  9462. this.appendDummyInput()
  9463. .appendField(Blockly.Msg.ai_model_face_attribute);
  9464. this.setOutput(true, null);
  9465. this.setColour("#ee783a");
  9466. this.setTooltip(Blockly.Msg.ai_model_face_attribute_TOOLTIP);
  9467. this.setHelpUrl("");
  9468. }
  9469. };
  9470. Blockly.Python['ai_model_face_attribute_new'] = function (block) {
  9471. var code = 'facesRecognitionLoadNew';
  9472. return [code, Blockly.Python.ORDER_NONE];
  9473. };
  9474. Blockly.Blocks['face_recognition_load'] = {
  9475. init: function () {
  9476. this.appendDummyInput()
  9477. .appendField(Blockly.Msg.ai_model_face_name);
  9478. this.appendDummyInput()
  9479. .appendField(Blockly.Msg.v831_face_recognition_load);
  9480. // this.appendDummyInput()
  9481. // .appendField(Blockly.Msg.ai_models_init_source)
  9482. // .appendField(new Blockly.FieldVariable("img_recognized_face"), "varitem");
  9483. this.appendValueInput("class_input")
  9484. .setCheck(null)
  9485. .appendField(Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD + ":")
  9486. // .appendField(new Blockly.FieldVariable("people_name_list"), "people_name");
  9487. this.setInputsInline(false);
  9488. this.setPreviousStatement(true, null);
  9489. this.setNextStatement(true, null);
  9490. this.setColour("#ee783a");
  9491. this.setTooltip(Blockly.Msg.v831_face_recognition_load_title);
  9492. this.setHelpUrl("");
  9493. }
  9494. };
  9495. Blockly.Python['face_recognition_load'] = function (block) {
  9496. // var face_list = Blockly.Python.variableDB_.getName(block.getFieldValue('people_name'), Blockly.Variables.NAME_TYPE);
  9497. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  9498. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  9499. Blockly.Python.definitions_['v831_import_from_maix_nn_face'] = `from maix.nn.app import face`
  9500. Blockly.Python.definitions_['v831_import_from_maix_nn_FaceRecognize'] = `from maix.nn.app.face import FaceRecognize`
  9501. Blockly.Python.addVariable('NUMBERPERSON', 'NUMBERPERSON = 0', true);
  9502. Blockly.Python.definitions_.import_Face_Recognizer = `class Face_Recognizer:
  9503. max_face_num = 4
  9504. detect_threshold = 0.5
  9505. detect_nms = 0.3
  9506. FEATURES = []
  9507. def __init__(self, threshold = 0.5, nms = 0.3, max_face_num = 1):
  9508. model = "/root/preset/model/retinaface.mud"
  9509. model_fe = "/root/preset/model/fe_resnet.mud"
  9510. self.input_size = (224, 224, 3)
  9511. input_size_fe = (128, 128, 3)
  9512. self.feature_len = 256
  9513. self.features = []
  9514. m = nn.load(model)
  9515. m_fe = nn.load(model_fe)
  9516. self.isLoadRecoredFace = False
  9517. self.CLASSNAMEFACELIST = ${value_class_input}
  9518. self.recognizer = FaceRecognize(m, m_fe, self.feature_len, self.input_size, threshold, nms, max_face_num)
  9519. self.FACERECOGNIZES = {
  9520. }
  9521. self.FACESRECOGNITONRESULT = []
  9522. def get_faces(self, img, std_img = False):
  9523. faces = self.recognizer.get_faces(img, std_img)
  9524. return faces
  9525. def __len__(self):
  9526. return len(self.features)
  9527. def add_user(self, name, feature):
  9528. self.features.append([name, feature])
  9529. return True
  9530. def remove_user(self, name_del):
  9531. rm = None
  9532. for name, feature in self.features:
  9533. if name_del == name:
  9534. rm = [name, feature]
  9535. if rm:
  9536. self.features.remove(rm)
  9537. return True
  9538. return False
  9539. def recognize(self, feature):
  9540. max_score = 0
  9541. uid = -1
  9542. for i, user in enumerate(self.features):
  9543. score = self.recognizer.compare(user[1], feature)
  9544. if score > max_score:
  9545. max_score = score
  9546. uid = i
  9547. if uid >= 0:
  9548. return self.features[uid][0], max_score
  9549. return None, 0
  9550. def get_input_size(self):
  9551. return self.input_size
  9552. def get_feature_len(self):
  9553. return self.feature_len
  9554. def darw_info(self, img, box, points, disp_str, bg_color=(255, 0, 0, 255), font_color=(255, 255, 255, 255), font_size=32):
  9555. font_wh = image.get_string_size(disp_str)
  9556. for p in points:
  9557. img.draw_rectangle(p[0] - 1, p[1] -1, p[0] + 1, p[1] + 1, color=bg_color)
  9558. img.draw_rectangle(box[0], box[1], box[0] + box[2], box[1] + box[3], color=bg_color, thickness=2)
  9559. if disp_str:
  9560. img.draw_rectangle(box[0], box[1] - font_wh[1], box[0] + font_wh[0], box[1], color=bg_color, thickness = -1)
  9561. img.draw_string(box[0], box[1] - font_wh[1], disp_str, color=font_color)
  9562. def map_face(self,box,points,IMAGEFACESHOW):
  9563. # print(box,points)
  9564. for p in points:
  9565. IMAGEFACESHOW.draw_rectangle(p[0] - 1, p[1] -1, p[0] + 1, p[1] + 1, color=(255,200,255))
  9566. #return box,points
  9567. def darw_title(self, img, dis_size ,key_l = None, key_r =None):
  9568. if key_C:
  9569. key_l = "| "+ key_l
  9570. img.draw_string( 1, 2 ,key_l , scale = 1, color = (255, 255, 255), thickness = 2)
  9571. if key_D:
  9572. key_r = key_r+" |"
  9573. w = int(dis_size[0] - 4 - image.get_string_size(key_r)[0] * 1)
  9574. img.draw_string( w, 2 ,key_r , scale = 1, color = (255, 255, 255), thickness = 2)
  9575. def recognizeShowMessage(self, canvas):
  9576. self.FACESRECOGNITONRESULT = FACERECGNIZER.get_faces(canvas)
  9577. if len(self.FACESRECOGNITONRESULT):
  9578. for FACESRECOGNITONRESULTI in self.FACESRECOGNITONRESULT:
  9579. if self.isLoadRecoredFace:
  9580. if int(FACERECGNIZER.recognize(FACESRECOGNITONRESULTI[3])[1])>85:
  9581. canvas.draw_rectangle(FACESRECOGNITONRESULTI[1][0],FACESRECOGNITONRESULTI[1][1], FACESRECOGNITONRESULTI[1][0]+FACESRECOGNITONRESULTI[1][2],FACESRECOGNITONRESULTI[1][1]+ FACESRECOGNITONRESULTI[1][3], color=(51,204,0), thickness=1)
  9582. canvas.draw_string(40,0, ("".join([str(x) for x in [FACERECGNIZER.recognize(FACESRECOGNITONRESULTI[3])[0], " : ", round(FACERECGNIZER.recognize(FACESRECOGNITONRESULTI[3])[1], 2)]])), scale = 1, color = (51,204,0) , thickness = 1)
  9583. else:
  9584. canvas.draw_rectangle(FACESRECOGNITONRESULTI[1][0],FACESRECOGNITONRESULTI[1][1], FACESRECOGNITONRESULTI[1][0]+FACESRECOGNITONRESULTI[1][2],FACESRECOGNITONRESULTI[1][1]+ FACESRECOGNITONRESULTI[1][3], color=(204,0,0), thickness=1)
  9585. canvas.draw_string(40,0, ("".join([str(x) for x in [FACERECGNIZER.recognize(FACESRECOGNITONRESULTI[3])[0], " : ", round(FACERECGNIZER.recognize(FACESRECOGNITONRESULTI[3])[1], 2)]])), scale = 1, color = (204,0,0) , thickness = 1)
  9586. else:
  9587. FACERECGNIZER.map_face(FACESRECOGNITONRESULTI[1],FACESRECOGNITONRESULTI[2],canvas)
  9588. canvas.draw_rectangle(FACESRECOGNITONRESULTI[1][0],FACESRECOGNITONRESULTI[1][1], FACESRECOGNITONRESULTI[1][0]+FACESRECOGNITONRESULTI[1][2],FACESRECOGNITONRESULTI[1][1]+ FACESRECOGNITONRESULTI[1][3], color=(255,0,0), thickness=1)
  9589. FACERECGNIZER = Face_Recognizer(0.5, 0.3, max_face_num = 4)
  9590. `
  9591. var code = `canvas = canvas.crop(48, 8,224, 224)
  9592. FACERECGNIZER.recognizeShowMessage(canvas)
  9593. `;
  9594. return code;
  9595. };
  9596. Blockly.Blocks['face_recognition_if_face_new'] = {
  9597. init: function () {
  9598. this.appendDummyInput()
  9599. .appendField(Blockly.Msg.ai_model_face_attribute_new)
  9600. this.appendStatementInput("input")
  9601. .setCheck(null)
  9602. .appendField(Blockly.Msg.basic_motion_statement_exec);
  9603. this.appendStatementInput("input1")
  9604. .setCheck(null)
  9605. .appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE);
  9606. this.setColour("#ee783a");
  9607. this.setNextStatement(true, null);
  9608. this.setPreviousStatement(true, null);
  9609. this.setTooltip(Blockly.Msg.ai_model_face_attribute_new);
  9610. this.setHelpUrl("");
  9611. }
  9612. };
  9613. Blockly.Python['face_recognition_if_face_new'] = function (block) {
  9614. var statements_input = Blockly.Python.statementToCode(block, 'input');
  9615. var statements_input1 = Blockly.Python.statementToCode(block, 'input1');
  9616. let allBlocks = block.workspace.getAllBlocks();
  9617. let global = ""
  9618. try {
  9619. global = allBlocks[0].workspace.variableList.toString()
  9620. }
  9621. catch (e) {
  9622. console.log(e)
  9623. }
  9624. Blockly.Python.addFunction("recognitionStatements", `def recognitionStatements(BOXESI):
  9625. ${global != "" ? `global ${global}` : "pass"}
  9626. ${statements_input}
  9627. `)
  9628. var code = `if len(FACERECGNIZER.FACESRECOGNITONRESULT) > 0:
  9629. for BOXESI in FACERECGNIZER.FACESRECOGNITONRESULT:
  9630. recognitionStatements(BOXESI)
  9631. else:
  9632. ${statements_input1}
  9633. `
  9634. return code;
  9635. };
  9636. Blockly.Blocks['face_recognition_if_face'] = {
  9637. init: function () {
  9638. this.appendDummyInput()
  9639. .appendField(Blockly.Msg.ai_models_face_model_if_new);
  9640. this.setInputsInline(false);
  9641. this.setNextStatement(true, null);
  9642. this.setPreviousStatement(true, null);
  9643. this.setColour("#ee783a");
  9644. this.setTooltip(Blockly.Msg.ai_models_face_model_if_new);
  9645. this.setHelpUrl("");
  9646. }
  9647. };
  9648. Blockly.Python['face_recognition_if_face'] = function (block) {
  9649. var code = ``;
  9650. return code;
  9651. };
  9652. Blockly.Blocks['face_recognition_face_result'] = {
  9653. init: function () {
  9654. this.appendDummyInput()
  9655. .appendField(Blockly.Msg.ai_model_face_attribute_new);
  9656. this.setInputsInline(false);
  9657. this.setOutput(true, null);
  9658. this.setColour("#ee783a");
  9659. this.setTooltip(Blockly.Msg.ai_model_face_attribute_new);
  9660. this.setHelpUrl("");
  9661. }
  9662. };
  9663. Blockly.Python['face_recognition_face_result'] = function (block) {
  9664. var code = `FACESRECOGNITONRESULT`;
  9665. return [code, Blockly.Python.ORDER_ATOMIC];
  9666. };
  9667. Blockly.Blocks['face_recognition_detection_rectangle'] = {
  9668. init: function () {
  9669. this.appendDummyInput()
  9670. .appendField(Blockly.Msg.ai_models_face_model_get)
  9671. .appendField(new Blockly.FieldDropdown([
  9672. // [Blockly.Msg.face_information, "rect"],
  9673. [Blockly.Msg.ai_models_face_model_x, "X"],
  9674. [Blockly.Msg.ai_models_face_model_y, "Y"],
  9675. [Blockly.Msg.ai_models_face_model_confidence_1, "Confidence"],
  9676. [Blockly.Msg.ai_models_face_model_ws, "2"],
  9677. [Blockly.Msg.ai_models_face_model_hs, "3"],
  9678. [Blockly.Msg.ai_models_object_model_x_center, "CX"],
  9679. [Blockly.Msg.ai_models_object_model_y_center, "CY"],
  9680. [Blockly.Msg.v831_model_face_name, "0"],
  9681. [Blockly.Msg.v831_models_face_model_confidence, "1"],
  9682. ]), "TYPE");
  9683. this.setInputsInline(false);
  9684. this.setOutput(true, null);
  9685. this.setColour("#ee783a");
  9686. var thisBlock = this;
  9687. this.setTooltip(function () {
  9688. var mode = thisBlock.getFieldValue('TYPE');
  9689. var TOOLTIPS = {
  9690. 'rect': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_rect),
  9691. 'X': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x),
  9692. 'Y': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y),
  9693. 'W': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_w),
  9694. 'H': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_h),
  9695. 'CX': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x_center),
  9696. 'CY': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y_center),
  9697. 'Number': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_count),
  9698. 'Serial': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_index),
  9699. 'Confidence': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_confidence)
  9700. };
  9701. return TOOLTIPS[mode];
  9702. });
  9703. this.setHelpUrl("");
  9704. }
  9705. };
  9706. Blockly.Python.face_recognition_detection_rectangle = function (block) {
  9707. var type = block.getFieldValue('TYPE');
  9708. var _code = "";
  9709. if (type == "rect") {
  9710. _code = "FACESRECOGNITONRESULTI[3]";
  9711. } else if (type == "X") {
  9712. _code = "FACESRECOGNITONRESULTI[1][0]";
  9713. } else if (type == "Y") {
  9714. _code = "FACESRECOGNITONRESULTI[1][1]";
  9715. } else if (type == "W") {
  9716. _code = `int(FACESRECOGNITONRESULTI[1][2]+FACESRECOGNITONRESULTI[1][0])`;
  9717. } else if (type == "H") {
  9718. _code = `int(FACESRECOGNITONRESULTI[1][3]+FACESRECOGNITONRESULTI[1][1])`;
  9719. } else if (type == "Number") {
  9720. _code = "FACESRECOGNITONRESULTI.objnum()";
  9721. } else if (type == "Serial") {
  9722. _code = "FACESRECOGNITONRESULTI.index()";
  9723. } else if (type == "Confidence") {
  9724. _code = "FACESRECOGNITONRESULTI[0]";
  9725. } else if (type == "CX") {
  9726. _code = `int((FACESRECOGNITONRESULTI[1][2]+FACESRECOGNITONRESULTI[1][0]+FACESRECOGNITONRESULTI[1][0])/2)`;
  9727. } else if (type == "CY") {
  9728. _code = `int((FACESRECOGNITONRESULTI[1][3]+FACESRECOGNITONRESULTI[1][1]+FACESRECOGNITONRESULTI[1][1])/2)`;
  9729. } else if (type == "0" || type == "1") {
  9730. _code = `FACERECGNIZER.recognize(FACESRECOGNITONRESULTI[3])[${type}]`
  9731. }
  9732. else {
  9733. _code = `FACESRECOGNITONRESULTI[1][${type}]`;
  9734. }
  9735. return [_code, Blockly.Python.ORDER_ATOMIC];
  9736. };
  9737. Blockly.Blocks['face_recognition_map_face'] = {
  9738. init: function () {
  9739. this.appendDummyInput()
  9740. .appendField(Blockly.Msg.face_recognition_map_face_canvas)
  9741. .appendField(new Blockly.FieldVariable("img_recognized_face"), "varitem")
  9742. .appendField(Blockly.Msg.face_recognition_map_face_show)
  9743. .appendField(Blockly.Msg.face_recognition_map_face_key_point);
  9744. // this.setInputsInline(false);
  9745. this.setPreviousStatement(true, null);
  9746. this.setNextStatement(true, null);
  9747. this.setColour("#ee783a");
  9748. this.setTooltip(Blockly.Msg.v831_setting_face_data_save_title);
  9749. this.setHelpUrl("");
  9750. }
  9751. };
  9752. Blockly.Python['face_recognition_map_face'] = function (block) {
  9753. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  9754. // var variable1 = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem1'), Blockly.Variables.NAME_TYPE);
  9755. var code = `FACERECGNIZER.map_face(FACESRECOGNITONRESULTI[1],FACESRECOGNITONRESULTI[2],${variable_name})
  9756. `;
  9757. return code;
  9758. };
  9759. Blockly.Blocks['face_recognition_add'] = {
  9760. init: function () {
  9761. this.appendDummyInput()
  9762. .appendField(Blockly.Msg.CocoRobo_EVENT_ACTION_OPT1)
  9763. .appendField(new Blockly.FieldDropdown([
  9764. ["A", "A"],
  9765. ["B", "B"],
  9766. ["C", "C"],
  9767. ["D", "D"]
  9768. ]), "button_type")
  9769. .appendField(Blockly.Msg.ai_model_face_gather_1);
  9770. this.setInputsInline(false);
  9771. this.setPreviousStatement(true, null);
  9772. this.setNextStatement(true, null);
  9773. this.setColour("#ee783a");
  9774. this.setTooltip(Blockly.Msg.v831_setting_face_data_save_title);
  9775. this.setHelpUrl("");
  9776. }
  9777. };
  9778. Blockly.Python['face_recognition_add'] = function (block) {
  9779. var _type = block.getFieldValue('button_type');
  9780. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  9781. sys.path.append("/root/")`
  9782. Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
  9783. // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
  9784. Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
  9785. key_B = BUTTON(8)
  9786. key_C = BUTTON(13)
  9787. key_D = BUTTON(7)
  9788. `
  9789. // var code = `key_${_type}.is_pressed()`
  9790. Blockly.Python.definitions_['v831_import_os'] = `import os`
  9791. Blockly.Python.definitions_['v831_import_json'] = `import json`
  9792. Blockly.Python.addVariable('ai_model_face_gather', `
  9793. def _CREATE_TEXT_FILE_WITH_CONTENT(_path, _data, _sep):
  9794. f = open(_path, "a")
  9795. f.write(_data + _sep)
  9796. f.close()
  9797. `, true);
  9798. var language = localStorage.getItem("handPyLanguage");
  9799. let saveFace = ""
  9800. if (language == "en") {
  9801. saveFace = "Save Face"
  9802. } else if (language == "zh-hant") {
  9803. saveFace = "儲存人臉"
  9804. } else {
  9805. saveFace = "保存人脸"
  9806. }
  9807. var code = `if key_${_type}.is_pressed():
  9808. while not (key_${_type}.is_pressed() == False):
  9809. time.sleep(0.1)
  9810. if NUMBERPERSON < len(FACERECGNIZER.CLASSNAMEFACELIST):
  9811. NUMBERPERSON = NUMBERPERSON + 1
  9812. FACERECGNIZER.add_user(FACERECGNIZER.CLASSNAMEFACELIST[len(FACERECGNIZER)], FACESRECOGNITONRESULTI[3])
  9813. FEATURES = FACERECGNIZER.features
  9814. try:
  9815. os.remove("/root/user/model/recorded_face_features.py")
  9816. except:
  9817. pass
  9818. try:
  9819. _CREATE_TEXT_FILE_WITH_CONTENT("/root/user/model/recorded_face_features.py", json.dumps(FACERECGNIZER.features), "\\r\\n")
  9820. except:
  9821. pass
  9822. canvas.draw_string(0,0, str("${saveFace}") + str(NUMBERPERSON), scale = 1, color = (51,204,0) , thickness = 1)
  9823. v831_display_show_canvas(canvas,_canvas_x,_canvas_y)
  9824. time.sleep(1000 / 1000)
  9825. `;
  9826. return code;
  9827. };
  9828. Blockly.Blocks['face_recognition_remove'] = {
  9829. init: function () {
  9830. this.appendDummyInput()
  9831. .appendField(Blockly.Msg.CocoRobo_EVENT_ACTION_OPT1)
  9832. .appendField(new Blockly.FieldDropdown([
  9833. ["A", "A"],
  9834. ["B", "B"],
  9835. ["C", "C"],
  9836. ["D", "D"]
  9837. ]), "button_type")
  9838. .appendField(Blockly.Msg.v831_setting_face_data_remove)
  9839. // this.appendStatementInput("input")
  9840. // .setCheck(null)
  9841. // .appendField(Blockly.Msg.basic_motion_statement_exec);
  9842. // .appendField(new Blockly.FieldVariable("save_face_data"), "varitem");
  9843. this.setInputsInline(false);
  9844. this.setPreviousStatement(true, null);
  9845. this.setNextStatement(true, null);
  9846. this.setColour("#ee783a");
  9847. this.setTooltip(Blockly.Msg.v831_setting_face_data_remove_title);
  9848. this.setHelpUrl("");
  9849. }
  9850. };
  9851. Blockly.Python['face_recognition_remove'] = function (block) {
  9852. var _type = block.getFieldValue('button_type');
  9853. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  9854. sys.path.append("/root/")`
  9855. Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
  9856. // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
  9857. Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
  9858. key_B = BUTTON(8)
  9859. key_C = BUTTON(13)
  9860. key_D = BUTTON(7)
  9861. `
  9862. let language = localStorage.getItem("handPyLanguage");
  9863. let removeFace = ""
  9864. let faceData = ""
  9865. if (language == "en") {
  9866. removeFace = "Remove Face"
  9867. faceData = "Data"
  9868. } else if (language == "zh-hant") {
  9869. removeFace = "刪除人臉"
  9870. faceData = "數據"
  9871. } else {
  9872. removeFace = "删除人脸"
  9873. faceData = "数据"
  9874. }
  9875. var code = `if key_${_type}.is_pressed() and NUMBERPERSON > 0:
  9876. while not (key_${_type}.is_pressed() == False):
  9877. time.sleep(0.1)
  9878. canvas.draw_rectangle(0,0, 0+320,0+ 20, color=(0,0,0), thickness=-1)
  9879. canvas.draw_string(40,0, ("".join([str(x) for x in ["${removeFace}", NUMBERPERSON, "${faceData}"]])), scale = 1, color = (255,255,255) , thickness = 1)
  9880. v831_display_show_canvas(canvas,_canvas_x,_canvas_y)
  9881. time.sleep(1000 / 1000)
  9882. NUMBERPERSON = NUMBERPERSON - 1
  9883. FACERECGNIZER.remove_user(FACERECGNIZER.CLASSNAMEFACELIST[len(FACERECGNIZER)-1])
  9884. FEATURES = FACERECGNIZER.features
  9885. `;
  9886. return code;
  9887. };
  9888. Blockly.Blocks['face_recognition_data_load'] = {
  9889. init: function () {
  9890. this.appendDummyInput()
  9891. .appendField(Blockly.Msg.ai_model_face_data_load);
  9892. this.setPreviousStatement(true, null);
  9893. this.setNextStatement(true, null);
  9894. this.setColour("#ee783a");
  9895. this.setTooltip(Blockly.Msg.ai_model_face_data_load);
  9896. this.setHelpUrl("");
  9897. }
  9898. };
  9899. Blockly.Python['face_recognition_data_load'] = function (block) {
  9900. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  9901. Blockly.Python.definitions_['v831_import_json'] = `import json`
  9902. Blockly.Python.definitions_['load_face_data'] = `isLoadRecoredFace = False
  9903. try:
  9904. with open("/root/user/model/recorded_face_features.py", "r") as file:
  9905. FACERECGNIZER.features = json.loads(file.read())
  9906. FACERECGNIZER.isLoadRecoredFace = True
  9907. except:
  9908. FACERECGNIZER.isLoadRecoredFace = False
  9909. `
  9910. var code = ``;
  9911. return code;
  9912. };
  9913. Blockly.Blocks['face_recognition_data_results'] = {
  9914. init: function () {
  9915. this.appendDummyInput()
  9916. .appendField(Blockly.Msg.ai_models_from)
  9917. .appendField(new Blockly.FieldVariable("img_face_Recognizer"), "varitem")
  9918. .appendField(Blockly.Msg.WIFIEASYMODE_COCOCLOUD_TYPE)
  9919. .appendField(new Blockly.FieldDropdown([
  9920. [Blockly.Msg.v831_model_face_name, "0"],
  9921. [Blockly.Msg.ai_models_face_model_confidence, "1"],
  9922. ]), "TYPE");
  9923. this.setInputsInline(false);
  9924. this.setOutput(true, null);
  9925. this.setColour("#ee783a");
  9926. this.setTooltip(Blockly.Msg.v831_face_recognition_result_title);
  9927. this.setHelpUrl("");
  9928. }
  9929. };
  9930. Blockly.Python['face_recognition_data_results'] = function (block) {
  9931. var type = block.getFieldValue('TYPE');
  9932. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  9933. var code = `FACERECGNIZER.recognize(${variable_name})[${type}]
  9934. `;
  9935. return [code, Blockly.Python.ORDER_ATOMIC];
  9936. };
  9937. // 自学习
  9938. Blockly.Blocks['ai_model_self_learning_init'] = {
  9939. init: function () {
  9940. this.appendDummyInput()
  9941. .appendField(Blockly.Msg.ai_model_self_learning_init);
  9942. this.appendValueInput("class_input")
  9943. .setCheck(null)
  9944. .appendField(Blockly.Msg.ai_models_customized_init_setup_name);
  9945. this.setInputsInline(false);
  9946. this.setPreviousStatement(true, null);
  9947. this.setNextStatement(true, null);
  9948. this.setColour("#ee783a");
  9949. this.setTooltip(Blockly.Msg.ai_model_self_learning_init);
  9950. this.setHelpUrl("");
  9951. }
  9952. };
  9953. Blockly.Python['ai_model_self_learning_init'] = function (block) {
  9954. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  9955. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  9956. Blockly.Python.definitions_.import_self_learning_init = `
  9957. CLASSNUM = ${JSON.parse(value_class_input).length}
  9958. SAMPLENUM = ${JSON.parse(value_class_input).length * 5}
  9959. CLASSNAMELIST = ${value_class_input}
  9960. `
  9961. var code = ``;
  9962. return code;
  9963. };
  9964. Blockly.Blocks['ai_model_self_learning_load'] = {
  9965. init: function () {
  9966. this.appendDummyInput()
  9967. .appendField(Blockly.Msg.ai_model_self_learning_load);
  9968. this.appendValueInput("class_input")
  9969. .setCheck(null)
  9970. .appendField(Blockly.Msg.ai_models_customized_init_setup_name);
  9971. this.setInputsInline(false);
  9972. this.setPreviousStatement(true, null);
  9973. this.setNextStatement(true, null);
  9974. this.setColour("#ee783a");
  9975. this.setTooltip(Blockly.Msg.ai_model_self_learning_load);
  9976. this.setHelpUrl("");
  9977. }
  9978. };
  9979. Blockly.Python['ai_model_self_learning_load'] = function (block) {
  9980. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  9981. Blockly.Python.definitions_['v831_import_Classifier'] = `from maix.nn.app.classifier import Classifier`
  9982. Blockly.Python.addVariable("SELFLEARNCOUNT", `SELFLEARNCOUNT = 0`, true)
  9983. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  9984. Blockly.Python.definitions_.import_self_learning_init = `
  9985. CLASSNUM = ${JSON.parse(value_class_input).length}
  9986. SAMPLENUM = ${JSON.parse(value_class_input).length * 5}
  9987. CLASSNAMELIST = ${value_class_input}
  9988. `
  9989. Blockly.Python.definitions_.self_learing_load = `class Self_learn:
  9990. model = {
  9991. "param": "/root/preset/model/resnet18_1000_awnn.param",
  9992. "bin": "/root/preset/model/resnet18_1000_awnn.bin"
  9993. }
  9994. options = {
  9995. "model_type": "awnn",
  9996. "inputs": {
  9997. "input0": (224, 224, 3)
  9998. },
  9999. "outputs": {
  10000. "190": (1, 1, 512)
  10001. },
  10002. "mean": [127.5, 127.5, 127.5],
  10003. "norm": [0.0176, 0.0176, 0.0176],
  10004. }
  10005. class_num = CLASSNUM #学习类别
  10006. sample_num = SAMPLENUM #学习类别总数量
  10007. curr_class = 0
  10008. curr_sample = 0
  10009. def __init__(self):
  10010. self.m = nn.load(self.model, opt=self.options)
  10011. self.classifier = Classifier(self.m, self.class_num, self.sample_num, 512, 224, 224)
  10012. SELFLEARN = Self_learn()
  10013. `
  10014. var code = '';
  10015. return code;
  10016. };
  10017. Blockly.Blocks['ai_model_self_learning_recognize_load'] = {
  10018. init: function () {
  10019. this.appendDummyInput()
  10020. .appendField(Blockly.Msg.ai_model_self_learning_recognize_load);
  10021. this.appendValueInput("class_input")
  10022. .setCheck(null)
  10023. .appendField(Blockly.Msg.ai_models_customized_init_setup_name);
  10024. this.setInputsInline(false);
  10025. this.setPreviousStatement(true, null);
  10026. this.setNextStatement(true, null);
  10027. this.setColour("#ee783a");
  10028. this.setTooltip(Blockly.Msg.ai_model_self_learning_recognize_load);
  10029. this.setHelpUrl("");
  10030. }
  10031. };
  10032. Blockly.Python['ai_model_self_learning_recognize_load'] = function (block) {
  10033. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  10034. Blockly.Python.definitions_['v831_import_Classifier'] = `from maix.nn.app.classifier import Classifier`
  10035. Blockly.Python.definitions_['v831_from_nn_import_load'] = `from maix.nn.app.classifier import load`
  10036. Blockly.Python.definitions_['v831_import_os'] = `import os`
  10037. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  10038. Blockly.Python.addVariable("SELFLEARNCOUNT", `SELFLEARNCOUNT = 0`, true)
  10039. Blockly.Python.definitions_.import_self_learning_init = `
  10040. CLASSNUM = ${JSON.parse(value_class_input).length}
  10041. SAMPLENUM = ${JSON.parse(value_class_input).length * 5}
  10042. CLASSNAMELIST = ${value_class_input}
  10043. `
  10044. Blockly.Python.definitions_.self_learing_load = `class Self_learn:
  10045. model = {
  10046. "param": "/root/preset/model/resnet18_1000_awnn.param",
  10047. "bin": "/root/preset/model/resnet18_1000_awnn.bin"
  10048. }
  10049. options = {
  10050. "model_type": "awnn",
  10051. "inputs": {
  10052. "input0": (224, 224, 3)
  10053. },
  10054. "outputs": {
  10055. "190": (1, 1, 512)
  10056. },
  10057. "mean": [127.5, 127.5, 127.5],
  10058. "norm": [0.0176, 0.0176, 0.0176],
  10059. }
  10060. class_num = CLASSNUM #学习类别
  10061. sample_num = SAMPLENUM #学习类别总数量
  10062. curr_class = 0
  10063. curr_sample = 0
  10064. def __init__(self):
  10065. if os.path.isfile("/root/module.bin"):
  10066. self.m = nn.load(self.model, opt=self.options)
  10067. self.classifier = load(self.m,"/root/module.bin")
  10068. else:
  10069. self.m = nn.load(self.model, opt=self.options)
  10070. self.classifier = Classifier(self.m, self.class_num, self.sample_num, 512, 224, 224)
  10071. print("not have model!")
  10072. SELFLEARN = Self_learn()
  10073. `
  10074. var code = '';
  10075. return code;
  10076. };
  10077. Blockly.Blocks['ai_model_self_learning_add_class'] = {
  10078. init: function () {
  10079. this.appendDummyInput()
  10080. .appendField(Blockly.Msg.CocoRobo_EVENT_ACTION_OPT1)
  10081. .appendField(new Blockly.FieldDropdown([
  10082. ["A", "A"],
  10083. ["B", "B"],
  10084. ["C", "C"],
  10085. ["D", "D"]
  10086. ]), "button_type")
  10087. .appendField(Blockly.Msg.ai_model_self_learning_add_class_category + Blockly.Msg.ai_model_self_learning_make_data_set);
  10088. this.setInputsInline(false);
  10089. this.setPreviousStatement(true, null);
  10090. this.setNextStatement(true, null);
  10091. this.setColour("#ee783a");
  10092. this.setTooltip(Blockly.Msg.ai_model_self_learning_add_class_category + Blockly.Msg.ai_model_self_learning_make_data_set);
  10093. this.setHelpUrl("");
  10094. }
  10095. };
  10096. Blockly.Python['ai_model_self_learning_add_class'] = function (block) {
  10097. var _type = block.getFieldValue('button_type');
  10098. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  10099. sys.path.append("/root/")`
  10100. Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
  10101. // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
  10102. Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
  10103. key_B = BUTTON(8)
  10104. key_C = BUTTON(13)
  10105. key_D = BUTTON(7)
  10106. `
  10107. var code = `canvas = canvas.crop(48, 8, 224, 224)
  10108. if key_${_type}.is_pressed() and SELFLEARNCOUNT < SELFLEARN.class_num:
  10109. while not (key_${_type}.is_pressed() == False):
  10110. time.sleep(0.1)
  10111. SELFLEARN.classifier.add_class_img(canvas)
  10112. for i in range(5):
  10113. SELFLEARN.classifier.add_sample_img(canvas)
  10114. SELFLEARNCOUNT = SELFLEARNCOUNT + 1
  10115. `;
  10116. return code;
  10117. };
  10118. Blockly.Blocks['ai_model_self_learning_make_data_set'] = {
  10119. init: function () {
  10120. this.appendDummyInput()
  10121. .appendField(Blockly.Msg.ai_model_self_learning_make_data_set);
  10122. this.setInputsInline(false);
  10123. this.setPreviousStatement(true, null);
  10124. this.setNextStatement(true, null);
  10125. this.setColour("#ee783a");
  10126. this.setTooltip(Blockly.Msg.ai_model_self_learning_make_data_set);
  10127. this.setHelpUrl("");
  10128. }
  10129. };
  10130. Blockly.Python['ai_model_self_learning_make_data_set'] = function (block) {
  10131. var code = `for i in range(5):
  10132. SELFLEARN.classifier.add_sample_img(canvas)
  10133. `;
  10134. return code;
  10135. };
  10136. Blockly.Blocks['ai_model_self_learning_picture'] = {
  10137. init: function () {
  10138. this.appendDummyInput()
  10139. .appendField(Blockly.Msg.CocoRobo_EVENT_ACTION_OPT1)
  10140. .appendField(new Blockly.FieldDropdown([
  10141. ["A", "A"],
  10142. ["B", "B"],
  10143. ["C", "C"],
  10144. ["D", "D"]
  10145. ]), "button_type")
  10146. .appendField(Blockly.Msg.ai_model_self_learning_picture + Blockly.Msg.ai_model_self_learning_save_modal);
  10147. this.setInputsInline(false);
  10148. this.setPreviousStatement(true, null);
  10149. this.setNextStatement(true, null);
  10150. this.setColour("#ee783a");
  10151. this.setTooltip(Blockly.Msg.ai_model_self_learning_picture + Blockly.Msg.ai_model_self_learning_save_modal);
  10152. this.setHelpUrl("");
  10153. }
  10154. };
  10155. Blockly.Python['ai_model_self_learning_picture'] = function (block) {
  10156. var _type = block.getFieldValue('button_type');
  10157. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  10158. sys.path.append("/root/")`
  10159. Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
  10160. // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
  10161. Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
  10162. key_B = BUTTON(8)
  10163. key_C = BUTTON(13)
  10164. key_D = BUTTON(7)
  10165. `
  10166. var code = `if key_${_type}.is_pressed() and SELFLEARNCOUNT >= SELFLEARN.class_num:
  10167. while not (key_${_type}.is_pressed() == False):
  10168. time.sleep(0.1)
  10169. SELFLEARN.classifier.train()
  10170. SELFLEARN.classifier.save("/root/module.bin")
  10171. `;
  10172. return code;
  10173. }; Blockly.Blocks['ai_model_self_learning_save_modal'] = {
  10174. init: function () {
  10175. this.appendDummyInput()
  10176. .appendField(Blockly.Msg.ai_model_self_learning_save_modal);
  10177. this.setInputsInline(false);
  10178. this.setPreviousStatement(true, null);
  10179. this.setNextStatement(true, null);
  10180. this.setColour("#ee783a");
  10181. this.setTooltip(Blockly.Msg.ai_model_self_learning_save_modal);
  10182. this.setHelpUrl("");
  10183. }
  10184. };
  10185. Blockly.Python['ai_model_self_learning_save_modal'] = function (block) {
  10186. var code = `SELFLEARN.classifier.save("/root/module.bin")
  10187. `;
  10188. return code;
  10189. };
  10190. Blockly.Blocks['ai_model_self_learning_class_verification'] = {
  10191. init: function () {
  10192. this.appendDummyInput()
  10193. .appendField(Blockly.Msg.ai_model_self_learning_class_verification);
  10194. this.setInputsInline(false);
  10195. this.setPreviousStatement(true, null);
  10196. this.setNextStatement(true, null);
  10197. this.setColour("#ee783a");
  10198. this.setTooltip(Blockly.Msg.ai_model_self_learning_class_verification);
  10199. this.setHelpUrl("");
  10200. }
  10201. };
  10202. Blockly.Python['ai_model_self_learning_class_verification'] = function (block) {
  10203. var code = `canvas = canvas.crop(48, 8, 224, 224)
  10204. SELFLEARNidx, SELFLEARNdistance = SELFLEARN.classifier.predict(canvas)
  10205. `;
  10206. return code;
  10207. };
  10208. Blockly.Blocks['ai_model_self_learning_result'] = {
  10209. init: function () {
  10210. this.appendDummyInput()
  10211. .appendField(Blockly.Msg.ai_model_self_learning_result)
  10212. .appendField(new Blockly.FieldDropdown([
  10213. [Blockly.Msg.ai_model_self_learning_result_name, "X"],
  10214. [Blockly.Msg.ai_models_object_model_confidence, "Y"]
  10215. ]), "TYPE");;
  10216. this.setOutput(true, null);
  10217. this.setColour("#ee783a");
  10218. this.setTooltip(Blockly.Msg.ai_model_self_learning_result);
  10219. this.setHelpUrl("");
  10220. }
  10221. };
  10222. Blockly.Python['ai_model_self_learning_result'] = function (block) {
  10223. var type = block.getFieldValue('TYPE');
  10224. var code = '';
  10225. if (type == 'X') {
  10226. code = `CLASSNAMELIST[SELFLEARNidx]`
  10227. } else {
  10228. code = `100-SELFLEARNdistance`
  10229. }
  10230. return [code, Blockly.Python.ORDER_ATOMIC];
  10231. };
  10232. Blockly.Blocks['ai_model_customized_init_setup_definition'] = {
  10233. init: function () {
  10234. this.appendDummyInput()
  10235. .appendField(new Blockly.FieldImage("blockly/media/header_customized_model.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
  10236. this.appendDummyInput()
  10237. .appendField(Blockly.Msg.ai_model_customized_init_setup_definition);
  10238. this.setInputsInline(false);
  10239. this.setPreviousStatement(true, null);
  10240. this.setNextStatement(true, null);
  10241. this.setColour("#ee783a");
  10242. this.setTooltip(Blockly.Msg.ai_model_customized_init_setup_definition_TOOLTIP);
  10243. this.setHelpUrl("");
  10244. }
  10245. };
  10246. Blockly.Python['ai_model_customized_init_setup_definition'] = function (block) {
  10247. // TODO: Assemble Python into code variable.
  10248. Blockly.Python.includes_.import_amxisd = '' +
  10249. 'print("Clearing Cached Variables...", end="")\n' +
  10250. 'for name in dir(): \n' +
  10251. ' if not name.startswith(\'_\'): \n' +
  10252. ' del globals()[name]\n' +
  10253. 'print(" Done")\n' +
  10254. 'import KPU as kpu\n' +
  10255. 'kpu.memtest()\n' +
  10256. 'from Maix import utils\n' +
  10257. 'import gc\n' +
  10258. 'gc.enable()\n' +
  10259. 'utils.gc_heap_size()\n' +
  10260. '\n' +
  10261. '################# Done Init #################\n' +
  10262. '';
  10263. var code = '';
  10264. return code;
  10265. };
  10266. // 初始化serialcomm_read_setup_title_text_1
  10267. Blockly.Blocks['ai_model_index_custom_initialization_init_1'] = {
  10268. init: function () {
  10269. this.appendValueInput("class_input")
  10270. .setCheck(null)
  10271. .appendField(Blockly.Msg.serialcomm_read_setup_title_text_1)
  10272. // .appendField("DEGREE");
  10273. this.setPreviousStatement(true, null);
  10274. this.setNextStatement(true, null);
  10275. this.setColour("#ee783a");
  10276. this.setTooltip(Blockly.Msg.serialcomm_read_setup_title_text_1);
  10277. this.setHelpUrl('');
  10278. }
  10279. };
  10280. Blockly.Python.ai_model_index_custom_initialization_init_1 = function (block) {
  10281. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  10282. Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
  10283. var _code = value_class_input;
  10284. return _code;
  10285. }
  10286. // 自定义人脸识别
  10287. Blockly.Blocks['ai_model_face_model'] = {
  10288. init: function () {
  10289. this.appendDummyInput()
  10290. .appendField(Blockly.Msg.ai_model_face_setup);
  10291. this.setInputsInline(false);
  10292. this.setOutput(true, null);
  10293. this.setColour("#ee783a");
  10294. this.setTooltip(Blockly.Msg.ai_model_face_setup);
  10295. this.setHelpUrl("");
  10296. }
  10297. };
  10298. Blockly.Python.ai_model_face_model = function (block) {
  10299. Blockly.Python.definitions_['v831_import_time'] = `import time`
  10300. Blockly.Python.definitions_['v831_import_gc'] = `import gc`
  10301. Blockly.Python.includes_.import_amxisd = '' +
  10302. 'for name in dir(): \n' +
  10303. ' if not name.startswith(\'_\'): \n' +
  10304. ' del globals()[name]\n' +
  10305. 'gc.enable()\n' +
  10306. '\n' +
  10307. 'try:\n' +
  10308. ' from cocorobo import firmware_info\n' +
  10309. 'except BaseException as e:\n' +
  10310. ' print(str(e))\n' +
  10311. ' pass\n' +
  10312. '\n' +
  10313. 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
  10314. ' from Maix import utils\n' +
  10315. ' utils.gc_heap_size(0xAF000)\n' +
  10316. 'else:\n' +
  10317. ' import utime\n' +
  10318. ' clock = None\n' +
  10319. ' ACCURACY = 85\n' +
  10320. '\n' +
  10321. 'task_fd = None\n' +
  10322. 'task_ld = None\n' +
  10323. 'task_fe = None\n' +
  10324. '\n' +
  10325. '';
  10326. var code = `
  10327. from fpioa_manager import *
  10328. from Maix import FPIOA, GPIO
  10329. _gp_side_buttons = [9, 10, 11]
  10330. FPIOA().set_function(_gp_side_buttons[0],FPIOA.GPIO0)
  10331. FPIOA().set_function(_gp_side_buttons[1],FPIOA.GPIO1)
  10332. FPIOA().set_function(_gp_side_buttons[2],FPIOA.GPIO2)
  10333. _gp_side_a = GPIO(GPIO.GPIO0,GPIO.IN,GPIO.PULL_UP)
  10334. _gp_side_b = GPIO(GPIO.GPIO1,GPIO.IN,GPIO.PULL_UP)
  10335. _gp_side_c = GPIO(GPIO.GPIO2,GPIO.IN,GPIO.PULL_UP)
  10336. side_button_state = False
  10337. def run_face_compare(record_ftrs, feature):
  10338. scores = []
  10339. for j in range(len(record_ftrs)):
  10340. score = kpu.face_compare(record_ftrs[j], feature)
  10341. scores.append(score)
  10342. max_score = 0
  10343. # if int(str(firmware_info.ai()).split("-")[0]) < 2021:
  10344. # index = -1
  10345. # else:
  10346. # index = 0
  10347. index = -1
  10348. for k in range(len(scores)):
  10349. if max_score < scores[k]:
  10350. max_score = scores[k]
  10351. index = k
  10352. return [scores, max_score, index]
  10353. # print(scores)
  10354. `;
  10355. // var code = '';
  10356. return [code, Blockly.Python.ORDER_ATOMIC];
  10357. }
  10358. // 设置人脸识别名称
  10359. Blockly.Blocks['ai_model_face_setup'] = {
  10360. init: function () {
  10361. // this.appendDummyInput()
  10362. // .appendField(Blockly.Msg.ai_model_face_setup);
  10363. this.appendValueInput("class_input")
  10364. .setCheck(null)
  10365. .appendField(Blockly.Msg.ai_model_face_name);
  10366. this.setPreviousStatement(true, null);
  10367. this.setNextStatement(true, null);
  10368. this.setColour("#ee783a");
  10369. this.setTooltip(Blockly.Msg.ai_model_face_name.replace(":", ""));
  10370. this.setHelpUrl("");
  10371. }
  10372. };
  10373. Blockly.Python['ai_model_face_setup'] = function (block) {
  10374. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  10375. var code = `
  10376. img_lcd = image.Image()
  10377. # img_face = image.Image(size=(128, 128))
  10378. collectNum = 0
  10379. record_ftrs = []
  10380. result = []
  10381. res_index = -1
  10382. # a = img_face.pix_to_ai()
  10383. names = ` + value_class_input + `
  10384. `;
  10385. return code;
  10386. };
  10387. Blockly.Blocks['ai_face_detection_model'] = {
  10388. init: function () {
  10389. this.appendDummyInput()
  10390. .appendField(Blockly.Msg.ai_face_detection_model);
  10391. this.setPreviousStatement(true, null);
  10392. this.setNextStatement(true, null);
  10393. this.setColour("#ee783a");
  10394. this.setTooltip(Blockly.Msg.ai_face_detection_model_TOOLTIP);
  10395. this.setHelpUrl("");
  10396. }
  10397. };
  10398. Blockly.Python['ai_face_detection_model'] = function (block) {
  10399. var code = '\n' +
  10400. 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
  10401. ' task_fd = kpu.load("/sd/preset/models/face_reocgnition/FD.emodel") # 人脸检测模型\n' +
  10402. 'else:\n' +
  10403. ' task_fd = kpu.load("/sd/preset/models/face/v2/FaceDetection.emodel") # 0x300000)\n' +
  10404. 'anchor = (1.889, 2.5245, 2.9465, 3.94056, 3.99987, 5.3658, 5.155437, 6.92275, 6.718375, 9.01025)\n' +
  10405. 'a = kpu.init_yolo2(task_fd, 0.5, 0.3, 5, anchor)\n' +
  10406. '\n' +
  10407. '';
  10408. return code;
  10409. };
  10410. Blockly.Blocks['ai_face_point_detection_model'] = {
  10411. init: function () {
  10412. this.appendDummyInput()
  10413. .appendField(Blockly.Msg.ai_face_point_detection_model);
  10414. this.setPreviousStatement(true, null);
  10415. this.setNextStatement(true, null);
  10416. this.setColour("#ee783a");
  10417. this.setTooltip(Blockly.Msg.ai_face_point_detection_model_TOOLTIP);
  10418. this.setHelpUrl("");
  10419. }
  10420. };
  10421. Blockly.Python['ai_face_point_detection_model'] = function (block) {
  10422. Blockly.Python.definitions_.import_ai_face_point_detection_model = `
  10423. def run_five_points_inference(canvas, canvas_face, detected_face_rect):
  10424. a = canvas.draw_rectangle(detected_face_rect)
  10425. # Create face image from detection
  10426. face_cut = canvas.cut(detected_face_rect[0], detected_face_rect[1], detected_face_rect[2], detected_face_rect[3])
  10427. # Convert created face image to a dimension of 128x128
  10428. face_cut_128 = face_cut.resize(128, 128)
  10429. # 将正脸图像转为kpu格式, 便于后面的关键点模型的使用
  10430. a = face_cut_128.pix_to_ai()
  10431. # Get landmark for 5 points of the detected face
  10432. # 运行人脸5点关键点检测模型, 获取当前识别人脸的关键点数据
  10433. fmap = kpu.forward(task_ld, face_cut_128)
  10434. # print("fmap", fmap)
  10435. # 获取关键点预测结果
  10436. plist = fmap[:]
  10437. # print("plist", plist)
  10438. # Get position of left eye, then draw it on the canvas.
  10439. le = (i.x()+int(plist[0]*i.w() - 10), i.y()+int(plist[1]*i.h()))
  10440. a = canvas.draw_circle(le[0], le[1], 4)
  10441. # Get position of Right eye, then draw it on the canvas.
  10442. re = (i.x()+int(plist[2]*i.w()), i.y()+int(plist[3]*i.h()))
  10443. a = canvas.draw_circle(re[0], re[1], 4)
  10444. # Get position of Nose, then draw it on the canvas.
  10445. nose = (i.x()+int(plist[4]*i.w()), i.y()+int(plist[5]*i.h()))
  10446. a = canvas.draw_circle(nose[0], nose[1], 4)
  10447. # Get position of Left cheek, then draw it on the canvas.
  10448. lm = (i.x()+int(plist[6]*i.w()), i.y()+int(plist[7]*i.h()))
  10449. a = canvas.draw_circle(lm[0], lm[1], 4)
  10450. # Get position of Right cheek, then draw it on the canvas.
  10451. rm = (i.x()+int(plist[8]*i.w()), i.y()+int(plist[9]*i.h()))
  10452. a = canvas.draw_circle(rm[0], rm[1], 4)
  10453. # Align face to standard position
  10454. src_point = [le, re, nose, lm, rm]
  10455. '''
  10456. get_affine_transform() 函数, 根据获得的5点坐标与标准正脸坐标获取仿射变换矩阵
  10457. - 计算3个二维点对之间的仿射变换矩阵H(2行x3列),自由度为6。
  10458. - 仿射变换的原理就是根据源图像中一个三角形的顶点坐标和应用仿射变换之后的
  10459. - 目标图像中一个三角形的顶点坐标计算出一个变换矩阵,然后将这个矩阵应用到整个源图像。
  10460. src_point 为输入源图像中的三角形顶点坐标
  10461. dst_point 为输出目标图像中的三角形顶点坐标
  10462. Ref: https://zhuanlan.zhihu.com/p/142260846
  10463. '''
  10464. T = image.get_affine_transform(src_point, dst_point)
  10465. '''
  10466. warp_affine_ai() 函数, 对原始图片人脸图片进行仿射变换,变换为正脸图像
  10467. '''
  10468. a = image.warp_affine_ai(canvas, canvas_face, T)
  10469. '''
  10470. 将正脸图像转为kpu格式
  10471. '''
  10472. a = canvas_face.ai_to_pix()
  10473. # Recycle face_cut_128 in order to reduce memory usage
  10474. del(face_cut_128)
  10475. `;
  10476. var code = '\n' +
  10477. 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
  10478. ' task_ld = kpu.load("/sd/preset/models/face_reocgnition/KP_chwise.emodel") # 人脸5点关键点检测模型\n' +
  10479. 'else:\n' +
  10480. ' task_ld = kpu.load("/sd/preset/models/face/v2/FaceLandmarkDetection.emodel")# 0x400000)\n' +
  10481. 'dst_point = [(44, 59), (84, 59), (64, 82), (47, 105),(81, 105)]\n' +
  10482. '\n' +
  10483. '';
  10484. return code;
  10485. };
  10486. Blockly.Blocks['ai_face_Vitter_eigenvalue_model'] = {
  10487. init: function () {
  10488. this.appendDummyInput()
  10489. .appendField(Blockly.Msg.ai_face_Vitter_eigenvalue_model);
  10490. this.setPreviousStatement(true, null);
  10491. this.setNextStatement(true, null);
  10492. this.setColour("#ee783a");
  10493. this.setTooltip(Blockly.Msg.ai_face_Vitter_eigenvalue_model_TOOLTIP);
  10494. this.setHelpUrl("");
  10495. }
  10496. };
  10497. Blockly.Python['ai_face_Vitter_eigenvalue_model'] = function (block) {
  10498. Blockly.Python.definitions_.import_ai_face_Vitter_eigenvalue_model = `
  10499. def run_fmap_calculation(canvas_face):
  10500. global fmap
  10501. # Calculate face feature vector from 'img_face', 计算正脸图片的196维特征值
  10502. fmap = kpu.forward(task_fe, canvas_face)
  10503. # 获取计算结果
  10504. feature = kpu.face_encode(fmap[:])
  10505. return feature
  10506. `;
  10507. var code = '\n' +
  10508. 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
  10509. ' task_fe = kpu.load("/sd/preset/models/face_reocgnition/face_recognition_v4_2020_09_07.emodel") # 人脸196维特征值模型\n' +
  10510. ' kpu.set_outputs(task_fe, 0,1,1, 512)\n' +
  10511. 'else:\n' +
  10512. ' task_fe = kpu.load("/sd/preset/models/face/v2/FeatureExtraction.emodel")# 0x500000)\n' +
  10513. ' clock = time.clock()\n' +
  10514. '\n' +
  10515. '';
  10516. return code;
  10517. };
  10518. // 加载人脸检测模型,设置识别图像源
  10519. Blockly.Blocks['ai_model_face_start_recognition'] = {
  10520. init: function () {
  10521. this.appendDummyInput()
  10522. .appendField(Blockly.Msg.ai_model_face_start_recognition + Blockly.Msg.ai_models_customized_init_setup_source)
  10523. .appendField(new Blockly.FieldVariable("img"), "varitem");
  10524. // this.appendDummyInput()
  10525. // .appendField(Blockly.Msg.ai_models_customized_init_type_set)
  10526. // .appendField(new Blockly.FieldDropdown([
  10527. // [Blockly.Msg.ai_models_customized_init_type_set_fast, "fast"],
  10528. // [Blockly.Msg.ai_models_customized_init_type_set_slow, "slow"]
  10529. // ]), "detect_type");
  10530. // this.appendStatementInput("NAME")
  10531. // .setCheck(null)
  10532. // .appendField(Blockly.Msg.ai_speech_recognition_any_result_text_do);
  10533. this.setInputsInline(false);
  10534. this.setPreviousStatement(true, null);
  10535. this.setNextStatement(true, null);
  10536. this.setColour("#ee783a");
  10537. this.setTooltip(Blockly.Msg.ai_model_face_start_recognition_TOOLTIP);
  10538. this.setHelpUrl("");
  10539. }
  10540. }
  10541. Blockly.Python['ai_model_face_start_recognition'] = function (block) {
  10542. // var statements_name = Blockly.Python.statementToCode(block, 'NAME');
  10543. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  10544. // var dropdown_detect_type = block.getFieldValue('detect_type');
  10545. localStorage.setItem("ai_model_face_variable_name", variable_name);
  10546. var code = '' +
  10547. 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
  10548. ' index = -1\n' +
  10549. 'else:\n' +
  10550. ' clock.tick()\n' +
  10551. 'a = img_face.pix_to_ai()\n' +
  10552. 'code = kpu.run_yolo2(task_fd, ' + variable_name + ')\n';
  10553. return code;
  10554. }
  10555. Blockly.Blocks['ai_models_customized_init_type_set'] = {
  10556. init: function () {
  10557. // this.appendDummyInput()
  10558. // .appendField(Blockly.Msg.ai_model_face_start_recognition + Blockly.Msg.ai_models_customized_init_setup_source)
  10559. // .appendField(new Blockly.FieldVariable("img"), "varitem");
  10560. this.appendDummyInput()
  10561. .appendField(Blockly.Msg.ai_models_customized_init_type_set)
  10562. .appendField(new Blockly.FieldDropdown([
  10563. [Blockly.Msg.ai_models_customized_init_type_set_fast, "fast"],
  10564. [Blockly.Msg.ai_models_customized_init_type_set_slow, "slow"]
  10565. ]), "detect_type");
  10566. // this.appendStatementInput("NAME")
  10567. // .setCheck(null)
  10568. // .appendField(Blockly.Msg.ai_speech_recognition_any_result_text_do);
  10569. this.setInputsInline(false);
  10570. this.setPreviousStatement(true, null);
  10571. this.setNextStatement(true, null);
  10572. this.setColour("#ee783a");
  10573. this.setTooltip(Blockly.Msg.ai_models_customized_init_type_set.replace(":", ""));
  10574. this.setHelpUrl("");
  10575. }
  10576. }
  10577. Blockly.Python['ai_models_customized_init_type_set'] = function (block) {
  10578. // var statements_name = Blockly.Python.statementToCode(block, 'NAME');
  10579. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  10580. var dropdown_detect_type = block.getFieldValue('detect_type');
  10581. // localStorage.setItem("ai_model_face_variable_name", variable_name);
  10582. if (dropdown_detect_type == "fast") {
  10583. // var break_string = " break\n";
  10584. var break_string = "break_string = True\n";
  10585. } else if (dropdown_detect_type == "slow") {
  10586. // var break_string = " # break\n";
  10587. var break_string = "break_string = False\n";
  10588. }
  10589. var code = '' +
  10590. break_string +
  10591. '\n';
  10592. return code;
  10593. }
  10594. Blockly.Blocks['ai_model_face_model_load_finish'] = {
  10595. init: function () {
  10596. this.appendDummyInput()
  10597. .appendField(Blockly.Msg.ai_model_face_model_load_finish);
  10598. this.setOutput(true, null);
  10599. this.setColour("#ee783a");
  10600. this.setTooltip(Blockly.Msg.ai_model_face_model_load_finish_TOOLTIP);
  10601. this.setHelpUrl("");
  10602. }
  10603. };
  10604. Blockly.Python['ai_model_face_model_load_finish'] = function (block) {
  10605. var code = 'code is not None';
  10606. return [code, Blockly.Python.ORDER_NONE];
  10607. };
  10608. Blockly.Blocks['ai_model_face_model_list'] = {
  10609. init: function () {
  10610. this.appendDummyInput()
  10611. .appendField(Blockly.Msg.ai_model_face_model_list);
  10612. this.setOutput(true, null);
  10613. this.setColour("#ee783a");
  10614. this.setTooltip(Blockly.Msg.ai_model_face_model_list_TOOLTIP);
  10615. this.setHelpUrl("");
  10616. }
  10617. };
  10618. Blockly.Python['ai_model_face_model_list'] = function (block) {
  10619. var code = 'code';
  10620. return [code, Blockly.Python.ORDER_NONE];
  10621. };
  10622. Blockly.Blocks['ai_model_face_detection_rectangle'] = {
  10623. init: function () {
  10624. this.appendDummyInput()
  10625. .appendField(new Blockly.FieldImage("blockly/media/face_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  10626. this.appendDummyInput()
  10627. .appendField(Blockly.Msg.ai_models_from)
  10628. .appendField(new Blockly.FieldVariable("i"), "varitem")
  10629. .appendField(Blockly.Msg.ai_models_face_model_get)
  10630. .appendField(new Blockly.FieldDropdown([
  10631. [Blockly.Msg.ai_models_face_model_rect, "rect"],
  10632. [Blockly.Msg.ai_models_face_model_x, "X"],
  10633. [Blockly.Msg.ai_models_face_model_y, "Y"],
  10634. [Blockly.Msg.ai_models_face_model_w, "W"],
  10635. [Blockly.Msg.ai_models_face_model_h, "H"],
  10636. [Blockly.Msg.ai_models_face_model_x_center, "CX"],
  10637. [Blockly.Msg.ai_models_face_model_y_center, "CY"],
  10638. [Blockly.Msg.ai_models_face_model_count, "Number"],
  10639. [Blockly.Msg.ai_models_face_model_index, "Serial"],
  10640. [Blockly.Msg.ai_models_face_model_confidence, "Confidence"]
  10641. ]), "TYPE");
  10642. this.setInputsInline(false);
  10643. this.setOutput(true, null);
  10644. this.setColour("#ee783a");
  10645. var thisBlock = this;
  10646. this.setTooltip(function () {
  10647. var mode = thisBlock.getFieldValue('TYPE');
  10648. var TOOLTIPS = {
  10649. 'rect': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_rect),
  10650. 'X': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x),
  10651. 'Y': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y),
  10652. 'W': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_w),
  10653. 'H': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_h),
  10654. 'CX': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x_center),
  10655. 'CY': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y_center),
  10656. 'Number': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_count),
  10657. 'Serial': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_index),
  10658. 'Confidence': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_confidence)
  10659. };
  10660. return TOOLTIPS[mode];
  10661. });
  10662. this.setHelpUrl("");
  10663. }
  10664. };
  10665. Blockly.Python.ai_model_face_detection_rectangle = function (block) {
  10666. var type = block.getFieldValue('TYPE');
  10667. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  10668. var _code = "";
  10669. if (type == "rect") {
  10670. _code = variable_name + ".rect()";
  10671. } else if (type == "X") {
  10672. _code = variable_name + ".x()";
  10673. } else if (type == "Y") {
  10674. _code = variable_name + ".y()";
  10675. } else if (type == "W") {
  10676. _code = variable_name + ".w()";
  10677. } else if (type == "H") {
  10678. _code = variable_name + ".h()";
  10679. } else if (type == "Number") {
  10680. _code = variable_name + ".objnum()";
  10681. } else if (type == "Serial") {
  10682. _code = variable_name + ".index()";
  10683. } else if (type == "Confidence") {
  10684. _code = variable_name + ".value()";
  10685. } else if (type == "CX") {
  10686. _code = variable_name + ".x()+(" + variable_name + ".w()/2)";
  10687. } else if (type == "CY") {
  10688. _code = variable_name + ".y()+(" + variable_name + ".h()/2)";
  10689. }
  10690. return [_code, Blockly.Python.ORDER_ATOMIC];
  10691. };
  10692. Blockly.Blocks['ai_model_face_load_point_detection_model'] = {
  10693. init: function () {
  10694. this.appendDummyInput()
  10695. .appendField(Blockly.Msg.ai_model_face_load_point_detection_model + Blockly.Msg.ai_models_customized_init_setup_source)
  10696. .appendField(new Blockly.FieldVariable("img"), "varitem");
  10697. this.appendDummyInput()
  10698. .appendField(Blockly.Msg.ai_model_face_load_point_detection_model_1)
  10699. .appendField(new Blockly.FieldVariable("img_face"), "varitem1");
  10700. this.appendValueInput("class_input")
  10701. .setCheck(null)
  10702. .appendField(Blockly.Msg.ai_model_face_load_point_detection_model_2);
  10703. this.setInputsInline(false);
  10704. this.setPreviousStatement(true, null);
  10705. this.setNextStatement(true, null);
  10706. this.setColour("#ee783a");
  10707. this.setTooltip(Blockly.Msg.ai_model_face_load_point_detection_model_TOOLTIP);
  10708. this.setHelpUrl("");
  10709. }
  10710. }
  10711. Blockly.Python.ai_model_face_load_point_detection_model = function (block) {
  10712. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  10713. var variable_name_1 = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem1'), Blockly.Variables.NAME_TYPE);
  10714. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  10715. var _code = "run_five_points_inference(" + variable_name + ", " + variable_name_1 + ", " + value_class_input + ")\n";
  10716. return _code;
  10717. };
  10718. Blockly.Blocks['ai_model_face_gather'] = {
  10719. init: function () {
  10720. this.appendDummyInput()
  10721. .appendField(Blockly.Msg.ai_model_face_gather);
  10722. this.appendValueInput("class_input")
  10723. .setCheck(null)
  10724. .appendField(Blockly.Msg.ai_model_face_gather_1);
  10725. this.setPreviousStatement(true, null);
  10726. this.setNextStatement(true, null);
  10727. this.setColour("#ee783a");
  10728. this.setTooltip(Blockly.Msg.ai_model_face_gather_TOOLTIP);
  10729. this.setHelpUrl("");
  10730. }
  10731. };
  10732. Blockly.Python['ai_model_face_gather'] = function (block) {
  10733. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC).replace('\"', '').replace('\"', '');
  10734. Blockly.Python.definitions_['v831_import_os'] = `import os`
  10735. Blockly.Python.addVariable('ai_model_face_gather', `
  10736. def _CREATE_TEXT_FILE_WITH_CONTENT(_path, _data, _sep):
  10737. f = open(_path, 'a')
  10738. f.write(_data + _sep)
  10739. f.close()
  10740. `, true);
  10741. var code = '' +
  10742. '# start to gather faces\n' +
  10743. 'result = run_face_compare(record_ftrs, feature)\n' +
  10744. 'if int(str(firmware_info.ai()).split("-")[0]) < 2021 and collectNum < len(names):\n' +
  10745. ' if(len(names) > result[2]):\n' +
  10746. ' if result[1] <= 80:\n' +
  10747. ' a = lcd_draw_string(' + localStorage.getItem("ai_model_face_variable_name") + ', i.x(), i.y(), ("X :%2.1f" % (result[1])), color=(102, 204, 153), scale=1, mono_space=False)\n' +
  10748. ' if _gp_side_b.value() == True and side_button_state == False:\n' +
  10749. ' record_ftrs.append(feature)\n' +
  10750. ' collectNum = collectNum + 1\n' +
  10751. ' side_button_state = True\n' +
  10752. ' elif _gp_side_b.value() == False and side_button_state == True:\n' +
  10753. ' side_button_state = False\n' +
  10754. 'elif int(str(firmware_info.ai()).split("-")[0]) >= 2021 and collectNum < len(names):\n' +
  10755. ' if(len(names) > result[2]):\n' +
  10756. ' if result[1] <= ACCURACY:\n' +
  10757. ' a = lcd_draw_string(' + localStorage.getItem("ai_model_face_variable_name") + ', i.x(), i.y(), " " , color=(102, 204, 153), scale=1, mono_space=False)\n' +
  10758. ' if _gp_side_b.value() == True and side_button_state == False:\n' +
  10759. ' record_ftrs.append(feature)\n' +
  10760. ' collectNum = collectNum + 1\n' +
  10761. ' side_button_state = True\n' +
  10762. ' elif _gp_side_b.value() == False and side_button_state == True:\n' +
  10763. ' side_button_state = False\n' +
  10764. 'if collectNum >= len(names):\n' +
  10765. ' try:\n' +
  10766. ' os.remove("/sd/user/' + value_class_input + '.py")\n' +
  10767. ' except:\n' +
  10768. ' pass\n' +
  10769. ' all = {}\n' +
  10770. ' try:\n' +
  10771. ' for j in range(len(names)):\n' +
  10772. ' all[names[j]] = record_ftrs[j]\n' +
  10773. ' _CREATE_TEXT_FILE_WITH_CONTENT("/sd/user/' + value_class_input + '.py", "all =" + str(all), "\\r\\n")\n' +
  10774. '\n' +
  10775. ' except:\n' +
  10776. ' pass\n' +
  10777. // 'if break_string == True:\n' +
  10778. // ' break\n' +
  10779. '\n';
  10780. return code;
  10781. };
  10782. Blockly.Blocks['ai_model_face_gather_num_judge'] = {
  10783. init: function () {
  10784. this.appendDummyInput()
  10785. .appendField(Blockly.Msg.ai_model_face_gather_num_judge);
  10786. this.setOutput(true, null);
  10787. this.setColour("#ee783a");
  10788. this.setTooltip(Blockly.Msg.ai_model_face_gather_num_judge_TOOLTIP);
  10789. this.setHelpUrl("");
  10790. }
  10791. };
  10792. Blockly.Python['ai_model_face_gather_num_judge'] = function (block) {
  10793. var code = 'collectNum >= len(names)';
  10794. return [code, Blockly.Python.ORDER_NONE];
  10795. };
  10796. Blockly.Blocks['ai_model_face_data_load'] = {
  10797. init: function () {
  10798. this.appendDummyInput()
  10799. .appendField(Blockly.Msg.ai_model_face_data_load);
  10800. this.appendValueInput("class_input")
  10801. .setCheck(null)
  10802. .appendField(Blockly.Msg.ai_model_face_data_load_1);
  10803. this.setPreviousStatement(true, null);
  10804. this.setNextStatement(true, null);
  10805. this.setColour("#ee783a");
  10806. this.setTooltip(Blockly.Msg.ai_model_face_data_load_TOOLTIP);
  10807. this.setHelpUrl("");
  10808. }
  10809. };
  10810. Blockly.Python['ai_model_face_data_load'] = function (block) {
  10811. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC).replace('\"', '').replace('\"', '');
  10812. Blockly.Python.addVariable('ai_model_face_data_load', `
  10813. try:
  10814. import user.${value_class_input} as recorded_face_features
  10815. except:
  10816. pass
  10817. `, true);
  10818. var code = '' +
  10819. '# load faces data\n' +
  10820. 'all = {}\n' +
  10821. 'record_ftrs = []\n' +
  10822. 'collectNum = len(names)\n' +
  10823. 'try:\n' +
  10824. ' all = recorded_face_features.all\n' +
  10825. ' for j in range(len(names)):\n' +
  10826. ' record_ftrs.append(all[names[j]])\n' +
  10827. '\n' +
  10828. 'except:\n' +
  10829. ' pass\n' +
  10830. '\n';
  10831. // 'all = recorded_face_features.all\n' +
  10832. return code;
  10833. };
  10834. Blockly.Blocks['ai_model_face_recognition'] = {
  10835. init: function () {
  10836. this.appendDummyInput()
  10837. .appendField(Blockly.Msg.ai_model_face_recognition);
  10838. this.setPreviousStatement(true, null);
  10839. this.setNextStatement(true, null);
  10840. this.setColour("#ee783a");
  10841. this.setTooltip(Blockly.Msg.ai_model_face_recognition_TOOLTIP);
  10842. this.setHelpUrl("");
  10843. }
  10844. };
  10845. Blockly.Python['ai_model_face_recognition'] = function (block) {
  10846. var code = '' +
  10847. 'if collectNum >= len(names):\n' +
  10848. ' result = run_face_compare(record_ftrs, feature)\n' +
  10849. ' if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
  10850. ' if(len(names) > result[2]):\n' +
  10851. ' if result[1] > 80:\n' +
  10852. ' a = lcd_draw_string(' + localStorage.getItem("ai_model_face_variable_name") + ', i.x(), i.y(), ("%s :%2.1f" % (names[result[2]], result[1])), color=(0, 255, 0), scale=1, mono_space=False)\n' +
  10853. ' else:\n' +
  10854. ' if(len(names) > result[2]):\n' +
  10855. ' if result[1] > ACCURACY:\n' +
  10856. ' a = lcd_draw_string(' + localStorage.getItem("ai_model_face_variable_name") + ', i.x(), i.y(), ("%s :%2.1f" % (names[result[2]], result[1])), color=(0, 255, 0), scale=1, mono_space=False)\n' +
  10857. ' res_index = result[2]\n' +
  10858. '\n' +
  10859. 'if break_string == True:\n' +
  10860. ' break\n' +
  10861. '\n' +
  10862. '';
  10863. return code;
  10864. };
  10865. Blockly.Blocks['ai_model_face_recognition_get_result'] = {
  10866. init: function () {
  10867. this.appendDummyInput()
  10868. .appendField(Blockly.Msg.ai_model_face_recognition_get_result);
  10869. // this.appendStatementInput("NAME")
  10870. // .setCheck(null)
  10871. // .appendField(Blockly.Msg.ai_speech_recognition_any_result_text_do);
  10872. this.setOutput(true);
  10873. this.setColour("#ee783a");
  10874. this.setTooltip(Blockly.Msg.ai_model_face_recognition_get_result_TOOLTIP);
  10875. this.setHelpUrl("");
  10876. }
  10877. };
  10878. Blockly.Python['ai_model_face_recognition_get_result'] = function (block) {
  10879. // var statements_name = Blockly.Python.statementToCode(block, 'NAME');
  10880. var code = '(len(names) > result[2] and collectNum >= len(names))';
  10881. // statements_name +
  10882. // 'if break_string == True:\n' +
  10883. // ' break\n' +
  10884. // 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
  10885. // ' ' + localStorage.getItem("ai_model_face_variable_name") + ' = ' + localStorage.getItem("ai_model_face_variable_name") + '.cut(40,0,240,240)\n' +
  10886. // ' a = lcd.display(' + localStorage.getItem("ai_model_face_variable_name") + ', oft=(0,0))\n' +
  10887. // ' gc.collect()\n' +
  10888. // ' # kpu.memtest()\n' +
  10889. // 'else:\n' +
  10890. // ' fps = clock.fps()\n' +
  10891. // ' a = lcd.display(' + localStorage.getItem("ai_model_face_variable_name") + ')\n' +
  10892. // ' gc.collect()\n' +
  10893. // ' # kpu.memtest()\n' +
  10894. // '\n' +
  10895. // '';
  10896. return [code, Blockly.Python.ORDER_NONE];
  10897. };
  10898. Blockly.Blocks['ai_model_getfaceresult'] = {
  10899. init: function () {
  10900. this.appendDummyInput()
  10901. .appendField(Blockly.Msg.ai_model_getface);
  10902. this.setOutput(true, null);
  10903. this.setColour("#ee783a");
  10904. this.setTooltip(Blockly.Msg.ai_model_getface_TOOLTIP);
  10905. this.setHelpUrl("");
  10906. }
  10907. };
  10908. Blockly.Python['ai_model_getfaceresult'] = function (block) {
  10909. // TODO: Assemble Python into code variable.
  10910. var code = 'names[res_index] if (res_index != -1 and len(names) > res_index and collectNum >= len(names)) else ""';
  10911. // TODO: Change ORDER_NONE to the correct strength.
  10912. return [code, Blockly.Python.ORDER_NONE];
  10913. };
  10914. Blockly.Blocks['ai_model_show_face'] = {
  10915. init: function () {
  10916. this.appendDummyInput()
  10917. .appendField(Blockly.Msg.ai_model_show_face);
  10918. this.setPreviousStatement(true, null);
  10919. this.setNextStatement(true, null);
  10920. this.setColour("#ee783a");
  10921. this.setTooltip(Blockly.Msg.ai_model_show_face_TOOLTIP);
  10922. this.setHelpUrl("");
  10923. }
  10924. };
  10925. Blockly.Python['ai_model_show_face'] = function (block) {
  10926. var code = '' +
  10927. // ' if break_string == True:\n' +
  10928. // ' break\n' +
  10929. 'lcd_draw_string(img, 240, 0, (str(num)), color = (255, 102, 0), scale = 2, mono_space = False)\n' +
  10930. 'if isCollect == 0:\n' +
  10931. ' lcd_draw_string(img, 40, 0, "按A识别上次样本", color = (255, 0, 0), scale = 1, mono_space = False)\n' +
  10932. ' lcd_draw_string(img, 40, 16, "按C重新拍摄", color = (255, 0, 0), scale = 1, mono_space = False)\n' +
  10933. 'elif isCollect == 1:\n' +
  10934. ' lcd_draw_string(img, 40, 0, "开始识别", color = (255, 0, 0), scale = 1, mono_space = False)\n' +
  10935. 'elif isCollect == 2:\n' +
  10936. ' lcd_draw_string(img, 40, 0, "开始采集人脸模板数据", color = (255, 0, 0), scale = 1, mono_space = False)\n' +
  10937. 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
  10938. ' ' + localStorage.getItem("ai_model_face_variable_name") + ' = ' + localStorage.getItem("ai_model_face_variable_name") + '.cut(40,0,240,240)\n' +
  10939. ' lcd.display(' + localStorage.getItem("ai_model_face_variable_name") + ', oft=(0,0))\n' +
  10940. ' gc.collect()\n' +
  10941. 'else:\n' +
  10942. ' fps = clock.fps()\n' +
  10943. ' a = lcd.display(' + localStorage.getItem("ai_model_face_variable_name") + ')\n' +
  10944. ' gc.collect()\n' +
  10945. '';
  10946. return code;
  10947. };
  10948. Blockly.Blocks['ai_model_class_setup'] = {
  10949. init: function () {
  10950. // this.appendDummyInput()
  10951. // .appendField(Blockly.Msg.ai_model_class_setup);
  10952. this.appendValueInput("class_input")
  10953. .setCheck(null)
  10954. .appendField(Blockly.Msg.ai_model_class_name);
  10955. this.setPreviousStatement(true, null);
  10956. this.setNextStatement(true, null);
  10957. this.setColour("#ee783a");
  10958. this.setTooltip(Blockly.Msg.ai_model_class_name.replace(":", ""));
  10959. this.setHelpUrl("");
  10960. }
  10961. };
  10962. Blockly.Python['ai_model_class_setup'] = function (block) {
  10963. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  10964. var code = `
  10965. ############### config #################
  10966. class_names = ` + value_class_input + `
  10967. class_num = len(class_names)
  10968. sample_num = len(class_names) * 5
  10969. THRESHOLD = 11
  10970. board_cube = 0
  10971. button_state = False
  10972. FPIOA().set_function(10, FPIOA.GPIO1)
  10973. key1 = GPIO(GPIO.GPIO1, GPIO.IN, GPIO.PULL_UP)
  10974. `;
  10975. return code;
  10976. };
  10977. Blockly.Blocks['ai_class_model'] = {
  10978. init: function () {
  10979. this.appendDummyInput()
  10980. .appendField(Blockly.Msg.ai_class_model);
  10981. this.setPreviousStatement(true, null);
  10982. this.setNextStatement(true, null);
  10983. this.setColour("#ee783a");
  10984. this.setTooltip(Blockly.Msg.ai_class_model_TOOLTIP);
  10985. this.setHelpUrl("");
  10986. }
  10987. };
  10988. Blockly.Python['ai_class_model'] = function (block) {
  10989. Blockly.Python.addVariable('ai_class_model', `
  10990. try:
  10991. del model
  10992. except Exception:
  10993. pass
  10994. try:
  10995. del classifier
  10996. except Exception:
  10997. pass
  10998. gc.collect()
  10999. cap_num = 0
  11000. train_status = 0
  11001. last_cap_time = 0
  11002. last_btn_status = 0
  11003. res_index = -1
  11004. is_save = 0
  11005. `)
  11006. var code = 'model = kpu.load("/sd/preset/models/object_classifier.emodel")\n';
  11007. return code;
  11008. };
  11009. Blockly.Blocks['ai_class_model_cluster'] = {
  11010. init: function () {
  11011. this.appendDummyInput()
  11012. .appendField(Blockly.Msg.ai_class_model_cluster);
  11013. this.setPreviousStatement(true, null);
  11014. this.setNextStatement(true, null);
  11015. this.setColour("#ee783a");
  11016. this.setTooltip(Blockly.Msg.ai_class_model_cluster_TOOLTIP);
  11017. this.setHelpUrl("");
  11018. }
  11019. };
  11020. Blockly.Python['ai_class_model_cluster'] = function (block) {
  11021. // Blockly.Python.addVariable('ai_class_model_cluster', `
  11022. // `)
  11023. var code = 'classifier = kpu.classifier(model, class_num, sample_num)\n';
  11024. return code;
  11025. };
  11026. Blockly.Blocks['ai_model_class_start_load'] = {
  11027. init: function () {
  11028. this.appendDummyInput()
  11029. .appendField(Blockly.Msg.ai_models_customized_init_setup_source)
  11030. .appendField(new Blockly.FieldVariable("img"), "varitem");
  11031. this.appendDummyInput()
  11032. .appendField(Blockly.Msg.ai_model_class_start_load);
  11033. // this.appendStatementInput("NAME")
  11034. // .setCheck(null)
  11035. // .appendField(Blockly.Msg.ai_speech_recognition_any_result_text_do);
  11036. this.setInputsInline(false);
  11037. this.setPreviousStatement(true, null);
  11038. this.setNextStatement(true, null);
  11039. this.setColour("#ee783a");
  11040. this.setTooltip(Blockly.Msg.ai_model_class_start_load_TOOLTIP);
  11041. this.setHelpUrl("");
  11042. }
  11043. }
  11044. Blockly.Python['ai_model_class_start_load'] = function (block) {
  11045. // var statements_name = Blockly.Python.statementToCode(block, 'NAME');
  11046. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  11047. localStorage.setItem("ai_model_class_start_load", variable_name);
  11048. var code = '' +
  11049. 'if board_cube:\n' +
  11050. ' ' + variable_name + ' = ' + variable_name + '.rotation_corr(z_rotation=90)\n' +
  11051. ' ' + variable_name + '.pix_to_ai()\n' +
  11052. '\n';
  11053. return code;
  11054. }
  11055. Blockly.Blocks['ai_model_class_data_load'] = {
  11056. init: function () {
  11057. this.appendDummyInput()
  11058. .appendField(Blockly.Msg.ai_model_class_data_load);
  11059. this.appendValueInput("class_input")
  11060. .setCheck(null)
  11061. .appendField(Blockly.Msg.ai_model_class_data_load_1);
  11062. this.setPreviousStatement(true, null);
  11063. this.setNextStatement(true, null);
  11064. this.setColour("#ee783a");
  11065. this.setTooltip(Blockly.Msg.ai_model_class_data_load_TOOLTIP);
  11066. this.setHelpUrl("");
  11067. }
  11068. };
  11069. Blockly.Python['ai_model_class_data_load'] = function (block) {
  11070. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC).replace('\"', '').replace('\"', '');
  11071. var code = '' +
  11072. 'try:\n' +
  11073. ' saved_path = "/sd/user/' + value_class_input + '.classifier"\n' +
  11074. ' f=open(saved_path,"r")\n' +
  11075. ' classifier, class_num, sample_num = kpu.classifier.load(model, saved_path)\n' +
  11076. ' train_status = 1\n' +
  11077. 'except:\n' +
  11078. ' ' + localStorage.getItem("ai_model_class_start_load") + '.draw_rectangle(0, 0, 240,20, fill=True, color=(0,0,0))\n' +
  11079. ' lcd_draw_string(' + localStorage.getItem("ai_model_class_start_load") + ', 0, 0, "Not found last sample", color=lcd.WHITE,scale=1,mono_space=False)\n' +
  11080. '\n';
  11081. return code;
  11082. };
  11083. Blockly.Blocks['ai_model_class_gather_load_finish'] = {
  11084. init: function () {
  11085. this.appendDummyInput()
  11086. .appendField(Blockly.Msg.ai_model_class_gather_load_finish);
  11087. this.setOutput(true, null);
  11088. this.setColour("#ee783a");
  11089. this.setTooltip(Blockly.Msg.ai_model_class_gather_load_finish_TOOLTIP);
  11090. this.setHelpUrl("");
  11091. }
  11092. };
  11093. Blockly.Python['ai_model_class_gather_load_finish'] = function (block) {
  11094. var code = 'train_status == 0';
  11095. return [code, Blockly.Python.ORDER_NONE];
  11096. };
  11097. Blockly.Blocks['ai_model_class_cluster_train'] = {
  11098. init: function () {
  11099. this.appendDummyInput()
  11100. .appendField(Blockly.Msg.ai_model_class_cluster_train);
  11101. this.appendValueInput("class_input")
  11102. .setCheck(null)
  11103. .appendField(Blockly.Msg.ai_model_class_cluster_train_1);
  11104. this.setPreviousStatement(true, null);
  11105. this.setNextStatement(true, null);
  11106. this.setColour("#ee783a");
  11107. this.setTooltip(Blockly.Msg.ai_model_class_cluster_train_TOOLTIP);
  11108. this.setHelpUrl("");
  11109. }
  11110. };
  11111. Blockly.Python['ai_model_class_cluster_train'] = function (block) {
  11112. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC).replace('\"', '').replace('\"', '');
  11113. var code = '' +
  11114. 'if cap_num >= class_num + sample_num and train_status == 0:\n' +
  11115. ' ' + localStorage.getItem("ai_model_class_start_load") + '.draw_rectangle(58,98, len("training...")*10+8 , 24, fill=True, color=lcd.RED)\n' +
  11116. ' ' + localStorage.getItem("ai_model_class_start_load") + ' = lcd_draw_string(' + localStorage.getItem("ai_model_class_start_load") + ', 60, 100, "training...", color=lcd.WHITE,scale=1,mono_space=False)\n' +
  11117. ' lcd.display(' + localStorage.getItem("ai_model_class_start_load") + ')\n' +
  11118. ' try:\n' +
  11119. ' classifier.train()\n' +
  11120. ' saved_path = "/sd/user/' + value_class_input + '.classifier"\n' +
  11121. ' f=open(saved_path,"r")\n' +
  11122. ' os.remove("/sd/user/' + value_class_input + '.classifier")\n' +
  11123. ' classifier.save("/sd/user/' + value_class_input + '.classifier")\n' +
  11124. ' except:\n' +
  11125. ' classifier.save("/sd/user/' + value_class_input + '.classifier")\n' +
  11126. ' time.sleep(2)\n' +
  11127. ' train_status = 1\n' +
  11128. '\n';
  11129. return code;
  11130. };
  11131. Blockly.Blocks['ai_model_class_recognition'] = {
  11132. init: function () {
  11133. this.appendDummyInput()
  11134. .appendField(Blockly.Msg.ai_model_class_recognition);
  11135. this.setPreviousStatement(true, null);
  11136. this.setNextStatement(true, null);
  11137. this.setColour("#ee783a");
  11138. this.setTooltip(Blockly.Msg.ai_model_class_recognition_TOOLTIP);
  11139. this.setHelpUrl("");
  11140. }
  11141. };
  11142. Blockly.Python['ai_model_class_recognition'] = function (block) {
  11143. var code = '' +
  11144. '# predict\n' +
  11145. 'if train_status == 1:\n' +
  11146. ' res_index = -1\n' +
  11147. ' try:\n' +
  11148. ' res_index, min_dist = classifier.predict(' + localStorage.getItem("ai_model_class_start_load") + ')\n' +
  11149. ' except Exception as e:\n' +
  11150. ' print("predict err:", e)\n' +
  11151. ' if res_index >= 0 and min_dist < THRESHOLD :\n' +
  11152. ' ' + localStorage.getItem("ai_model_class_start_load") + '.draw_rectangle(0,0, len(class_names[res_index])*10+8 , 24, fill=True, color=lcd.RED)\n' +
  11153. ' ' + localStorage.getItem("ai_model_class_start_load") + ' = lcd_draw_string(' + localStorage.getItem("ai_model_class_start_load") + ', 2, 2, class_names[res_index], color=lcd.WHITE,scale=1,mono_space=False)\n' +
  11154. ' else:\n' +
  11155. ' ' + localStorage.getItem("ai_model_class_start_load") + '.draw_rectangle(0,0, len("maybe {}".format(class_names[res_index]))*10+8 , 24, fill=True, color=lcd.RED)\n' +
  11156. ' ' + localStorage.getItem("ai_model_class_start_load") + ' = lcd_draw_string(' + localStorage.getItem("ai_model_class_start_load") + ', 2, 2, "maybe {}".format(class_names[res_index]), color=lcd.WHITE,scale=1,mono_space=False)\n' +
  11157. '\n';
  11158. return code;
  11159. };
  11160. Blockly.Blocks['ai_model_show_class'] = {
  11161. init: function () {
  11162. this.appendDummyInput()
  11163. .appendField(Blockly.Msg.ai_model_show_face);
  11164. this.setPreviousStatement(true, null);
  11165. this.setNextStatement(true, null);
  11166. this.setColour("#ee783a");
  11167. this.setTooltip(Blockly.Msg.ai_model_show_face_TOOLTIP);
  11168. this.setHelpUrl("");
  11169. }
  11170. };
  11171. Blockly.Python['ai_model_show_class'] = function (block) {
  11172. var code = '' +
  11173. '' + localStorage.getItem("ai_model_class_start_load") + ' = ' + localStorage.getItem("ai_model_class_start_load") + '.cut(0,0,240,240)\n' +
  11174. 'lcd.display(' + localStorage.getItem("ai_model_class_start_load") + ', oft=(0,0))\n' +
  11175. '';
  11176. return code;
  11177. };
  11178. Blockly.Blocks['ai_model_customized_init_setup'] = {
  11179. init: function () {
  11180. this.appendDummyInput()
  11181. .appendField(Blockly.Msg.ai_models_customized_init_setup_title);
  11182. this.appendDummyInput()
  11183. .appendField(Blockly.Msg.ai_models_customized_init_setup_path)
  11184. .appendField(new Blockly.FieldTextInput("yolov2_int8"), "model_path");
  11185. this.appendValueInput("class_input")
  11186. .setCheck(null)
  11187. .appendField(Blockly.Msg.ai_models_customized_init_setup_name);
  11188. this.setPreviousStatement(true, null);
  11189. this.setNextStatement(true, null);
  11190. this.setColour("#ee783a");
  11191. this.setTooltip(Blockly.Msg.ai_model_customized_init_setup_TOOLTIP);
  11192. this.setHelpUrl("");
  11193. }
  11194. };
  11195. Blockly.Python['ai_model_customized_init_setup'] = function (block) {
  11196. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  11197. var text_model_path = block.getFieldValue('model_path');
  11198. Blockly.Python.definitions_['v831_import_from_maix_nn'] = "from maix import nn";
  11199. Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
  11200. let path = `/root/user/model/${text_model_path}`
  11201. if (text_model_path == "autologistics") {
  11202. path = `/root/preset/model/${text_model_path}`
  11203. }
  11204. let code = `class Yolo:
  11205. labels = ${value_class_input}
  11206. anchors = [1.19, 1.98, 2.79, 4.59, 4.53, 8.92, 8.06, 5.29, 10.32, 10.65]
  11207. m = {
  11208. "param": "${path}.param",
  11209. "bin": "${path}.bin"
  11210. }
  11211. options = {
  11212. "model_type": "awnn",
  11213. "inputs": {
  11214. "input0": (224, 224, 3)
  11215. },
  11216. "outputs": {
  11217. "output0": (7, 7, (1+4+len(labels))*5)
  11218. },
  11219. "mean": [127.5, 127.5, 127.5],
  11220. "norm": [0.0078125, 0.0078125, 0.0078125],
  11221. }
  11222. def __init__(self):
  11223. from maix import nn
  11224. from maix.nn import decoder
  11225. self.model = nn.load(self.m, opt=self.options)
  11226. self.decoder = decoder.Yolo2(len(self.labels), self.anchors, net_in_size=(224, 224), net_out_size=(7, 7))
  11227. def __del__(self):
  11228. del self.model
  11229. del self.decoder
  11230. Yolo = Yolo()
  11231. `;
  11232. return code;
  11233. };
  11234. Blockly.Blocks['ai_model_customized_load_setup'] = {
  11235. init: function () {
  11236. this.appendDummyInput()
  11237. .appendField(Blockly.Msg.ai_model_customized_load_setup_title);
  11238. this.appendDummyInput()
  11239. .appendField(Blockly.Msg.ai_models_customized_init_setup_path)
  11240. .appendField(new Blockly.FieldTextInput("yolov2_int8"), "model_path");
  11241. // this.appendDummyInput()
  11242. // .appendField(Blockly.Msg.ai_models_customized_init_setup_source)
  11243. // .appendField(new Blockly.FieldVariable("img_modelrecognition"), "varitem");
  11244. this.appendValueInput("class_input")
  11245. .setCheck(null)
  11246. .appendField(Blockly.Msg.ai_models_customized_init_setup_name);
  11247. this.setPreviousStatement(true, null);
  11248. this.setNextStatement(true, null);
  11249. this.setColour("#ee783a");
  11250. this.setTooltip(Blockly.Msg.ai_model_customized_load_setup_TOOLTIP);
  11251. this.setHelpUrl("");
  11252. }
  11253. };
  11254. Blockly.Python['ai_model_customized_load_setup'] = function (block) {
  11255. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  11256. var text_model_path = block.getFieldValue('model_path');
  11257. Blockly.Python.definitions_['v831_import_from_maix_nn'] = "from maix import nn";
  11258. Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
  11259. let path = `/root/user/model/${text_model_path}`
  11260. if (text_model_path == "autologistics") {
  11261. path = `/root/preset/model/${text_model_path}`
  11262. }
  11263. Blockly.Python.definitions_['CLASSYOLO'] = `class Yolo:
  11264. labels = ${value_class_input}
  11265. anchors = [1.19, 1.98, 2.79, 4.59, 4.53, 8.92, 8.06, 5.29, 10.32, 10.65]
  11266. m = {
  11267. "param": "${path}.param",
  11268. "bin": "${path}.bin"
  11269. }
  11270. options = {
  11271. "model_type": "awnn",
  11272. "inputs": {
  11273. "input0": (224, 224, 3)
  11274. },
  11275. "outputs": {
  11276. "output0": (7, 7, (1+4+len(labels))*5)
  11277. },
  11278. "mean": [127.5, 127.5, 127.5],
  11279. "norm": [0.0078125, 0.0078125, 0.0078125],
  11280. }
  11281. def __init__(self):
  11282. self.model = nn.load(self.m, opt=self.options)
  11283. self.decoder = decoder.Yolo2(len(self.labels), self.anchors, net_in_size=(224, 224), net_out_size=(7, 7))
  11284. self.FACESYOLOS = {
  11285. "FACE_START_X": [],
  11286. "FACE_START_Y": [],
  11287. "FACE_CENTET_X": [],
  11288. "FACE_CENTET_Y": [],
  11289. "FACE_WIDTH": [],
  11290. "FACE_HEIGHT": [],
  11291. "FACE_RESULT": [],
  11292. "FACE_CONFIDENCE": [],
  11293. }
  11294. def __del__(self):
  11295. del self.model
  11296. del self.decoder
  11297. def faceRecognizeShowResult(self,canvas):
  11298. out = self.model.forward(canvas, quantize=True, layout="hwc")
  11299. BOXES, PROBS = self.decoder.run(out, nms=0.3, threshold=0.3, img_size=(224, 224))
  11300. if len(BOXES):
  11301. for BOXESI, BOXOBJ in enumerate(BOXES):
  11302. canvas.draw_string((BOXOBJ[0]),(BOXOBJ[1]), ("".join([str(x) for x in [self.labels[PROBS[BOXESI][0]], ";", str(round((PROBS[BOXESI][1][PROBS[BOXESI][0]]*100), 2)) + str("%")]])), scale = 1, color = (255,0,0) , thickness = 1)
  11303. canvas.draw_rectangle((BOXOBJ[0]),(BOXOBJ[1]), (BOXOBJ[0])+(BOXOBJ[2]),(BOXOBJ[1])+ (BOXOBJ[3]), color=(255,0,0), thickness=1)
  11304. BOXES[BOXESI].append(PROBS[BOXESI])
  11305. return BOXES
  11306. FaceYolo = Yolo()
  11307. `;
  11308. var code = `canvas = canvas.crop(48,8,224,224)
  11309. BOXES = FaceYolo.faceRecognizeShowResult(canvas)
  11310. `;
  11311. return code;
  11312. };
  11313. Blockly.Blocks['ai_model_customized_get_result'] = {
  11314. init: function () {
  11315. this.appendDummyInput()
  11316. .appendField(Blockly.Msg.ai_models_from)
  11317. .appendField(Blockly.Msg.ai_models_customized_get_result_any)
  11318. .appendField(new Blockly.FieldDropdown([
  11319. [Blockly.Msg.ai_models_customized_get_result_name, "classid"],
  11320. [Blockly.Msg.ai_models_customized_get_result_x, "x"],
  11321. [Blockly.Msg.ai_models_customized_get_result_y, "y"],
  11322. // [Blockly.Msg.ai_models_customized_get_result_w, "w"],
  11323. // [Blockly.Msg.ai_models_customized_get_result_h, "h"],
  11324. // [Blockly.Msg.ai_models_customized_get_result_x_center, "cx"],
  11325. // [Blockly.Msg.ai_models_customized_get_result_y_center, "cy"],
  11326. // [Blockly.Msg.ai_models_customized_get_result_count, "objnum"],
  11327. // [Blockly.Msg.ai_models_customized_get_result_index, "index"],
  11328. [Blockly.Msg.ai_models_customized_get_result_confidence, "value"],
  11329. [Blockly.Msg.ai_models_face_model_ws, "2"],
  11330. [Blockly.Msg.ai_models_face_model_hs, "3"],
  11331. [Blockly.Msg.ai_models_object_model_x_center, "CX"],
  11332. [Blockly.Msg.ai_models_object_model_y_center, "CY"]
  11333. ]), "get_results");
  11334. this.setOutput(true, null);
  11335. this.setColour("#ee783a");
  11336. var thisBlock = this;
  11337. this.setTooltip(function () {
  11338. var mode = thisBlock.getFieldValue('get_results');
  11339. var TOOLTIPS = {
  11340. 'classid': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_name),
  11341. 'x': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_x),
  11342. 'y': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_y),
  11343. 'w': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_w),
  11344. 'h': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_h),
  11345. 'cx': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_x_center),
  11346. 'cy': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_y_center),
  11347. 'objnum': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_count),
  11348. 'index': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_index),
  11349. 'value': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_confidence)
  11350. };
  11351. return TOOLTIPS[mode];
  11352. });
  11353. this.setHelpUrl("");
  11354. }
  11355. };
  11356. Blockly.Python['ai_model_customized_get_result'] = function (block) {
  11357. var variable_name = "BOXESI";
  11358. var dropdown_get_results = block.getFieldValue('get_results');
  11359. // TODO: Assemble Python into code variable.
  11360. var code = '';
  11361. if (dropdown_get_results == "classid") {
  11362. code = 'Yolo.labels[' + variable_name + '[4][0]]';
  11363. } else if (dropdown_get_results == 'x') {
  11364. code = variable_name + '[0]';
  11365. } else if (dropdown_get_results == "y") {
  11366. code = variable_name + "[1]";
  11367. } else if (dropdown_get_results == "w") {
  11368. code = `${variable_name}[0]+${variable_name}[2]`;
  11369. } else if (dropdown_get_results == "h") {
  11370. code = `${variable_name}[1]+${variable_name}[3]`;
  11371. } else if (dropdown_get_results == "value") {
  11372. code = `${variable_name}[4][1][${variable_name}[4][0]]`;
  11373. } else if (dropdown_get_results == "CX") {
  11374. code = `int((${variable_name}[0] + ${variable_name}[2])/2)`;
  11375. } else if (dropdown_get_results == "CY") {
  11376. code = `int((${variable_name}[1] + ${variable_name}[3])/2)`;
  11377. }
  11378. else {
  11379. code = `${variable_name}[${dropdown_get_results}]`;
  11380. }
  11381. // TODO: Change ORDER_NONE to the correct strength.
  11382. return [code, Blockly.Python.ORDER_NONE];
  11383. };
  11384. Blockly.Blocks['ai_model_customized_if_got_new'] = {
  11385. init: function () {
  11386. this.appendDummyInput()
  11387. .appendField(Blockly.Msg.ai_model_customized_attribute)
  11388. this.appendStatementInput("input")
  11389. .setCheck(null)
  11390. .appendField(Blockly.Msg.basic_motion_statement_exec);
  11391. this.appendStatementInput("input1")
  11392. .setCheck(null)
  11393. .appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE);
  11394. this.setColour("#ee783a");
  11395. this.setNextStatement(true, null);
  11396. this.setPreviousStatement(true, null);
  11397. this.setTooltip(Blockly.Msg.ai_model_customized_attribute);
  11398. this.setHelpUrl("");
  11399. }
  11400. };
  11401. Blockly.Python['ai_model_customized_if_got_new'] = function (block) {
  11402. var statements_input = Blockly.Python.statementToCode(block, 'input');
  11403. var statements_input1 = Blockly.Python.statementToCode(block, 'input1');
  11404. let allBlocks = block.workspace.getAllBlocks();
  11405. let global = ""
  11406. try {
  11407. global = allBlocks[0].workspace.variableList.toString()
  11408. }
  11409. catch (e) {
  11410. console.log(e)
  11411. }
  11412. Blockly.Python.addFunction("cardStatements", `def cardStatements(BOXESI):
  11413. ${global != "" ? `global ${global}` : "pass"}
  11414. ${statements_input}
  11415. `)
  11416. var code = `if len(BOXES) > 0:
  11417. for BOXESI in BOXES:
  11418. cardStatements(BOXESI)
  11419. else:
  11420. ${statements_input1}
  11421. `
  11422. return code;
  11423. };
  11424. Blockly.Blocks['ai_model_customized_if_got'] = {
  11425. init: function () {
  11426. this.appendDummyInput()
  11427. .appendField(Blockly.Msg.ai_models_customized_if_got);
  11428. this.setNextStatement(true, null);
  11429. this.setPreviousStatement(true, null);
  11430. this.setColour("#ee783a");
  11431. this.setTooltip(Blockly.Msg.ai_models_customized_if_got);
  11432. this.setHelpUrl("");
  11433. }
  11434. };
  11435. Blockly.Python['ai_model_customized_if_got'] = function (block) {
  11436. Blockly.Python.addFunction("faceRecognizeShowResult", `def faceRecognizeShowResult():
  11437. global BOXES
  11438. if len(BOXES):
  11439. for BOXESI, BOXOBJ in enumerate(BOXES):
  11440. canvas.draw_string((BOXOBJ[0]),(BOXOBJ[1]), ("".join([str(x) for x in [Yolo.labels[PROBS[BOXESI][0]], ";", str(round((PROBS[BOXESI][1][PROBS[BOXESI][0]]*100), 2)) + str("%")]])), scale = 1, color = (255,0,0) , thickness = 1)
  11441. canvas.draw_rectangle((BOXOBJ[0]),(BOXOBJ[1]), (BOXOBJ[0])+(BOXOBJ[2]),(BOXOBJ[1])+ (BOXOBJ[3]), color=(255,0,0), thickness=1)
  11442. `)
  11443. var code = 'faceRecognizeShowResult()\n';
  11444. return code;
  11445. };
  11446. Blockly.Blocks['ai_model_customized_attribute'] = {
  11447. init: function () {
  11448. this.appendDummyInput()
  11449. .appendField(Blockly.Msg.ai_model_customized_attribute);
  11450. this.setOutput(true, null);
  11451. this.setColour("#ee783a");
  11452. this.setTooltip(Blockly.Msg.ai_model_customized_attribute_TOOLTIP);
  11453. this.setHelpUrl("");
  11454. }
  11455. };
  11456. Blockly.Python['ai_model_customized_attribute'] = function (block) {
  11457. var code = 'len(BOXES)';
  11458. return [code, Blockly.Python.ORDER_NONE];
  11459. };
  11460. /*
  11461. _ ___ ____ _
  11462. / \ |_ _| / ___| _ _ ___| |_ ___ _ __ ___
  11463. / _ \ | | \___ \| | | / __| __/ _ \ '_ ` _ \
  11464. / ___ \ | | ___) | |_| \__ \ || __/ | | | | |
  11465. /_/ \_\___| |____/ \__, |___/\__\___|_| |_| |_|
  11466. |___/
  11467. */
  11468. Blockly.Blocks['ai_system_off'] = {
  11469. init: function () {
  11470. this.appendDummyInput()
  11471. .appendField(Blockly.Msg.ai_system_off);
  11472. this.setPreviousStatement(true);
  11473. this.setNextStatement(true);
  11474. this.setColour("#22398e");
  11475. this.setTooltip(Blockly.Msg.ai_system_restart_TOOLTIP);
  11476. this.setHelpUrl("");
  11477. }
  11478. };
  11479. Blockly.Python.ai_system_off = function (block) {
  11480. Blockly.Python.definitions_['v831_import_os'] = `import os`
  11481. var _code = `os.system("poweroff")
  11482. `
  11483. return _code;
  11484. }
  11485. Blockly.Blocks['ai_system_restart'] = {
  11486. init: function () {
  11487. this.appendDummyInput()
  11488. .appendField(Blockly.Msg.ai_system_restart);
  11489. this.setPreviousStatement(true);
  11490. this.setNextStatement(true);
  11491. this.setColour("#22398e");
  11492. this.setTooltip(Blockly.Msg.ai_system_off_TOOLTIP);
  11493. this.setHelpUrl("");
  11494. }
  11495. };
  11496. Blockly.Python.ai_system_restart = function (block) {
  11497. Blockly.Python.definitions_['v831_import_os'] = `import os`
  11498. var _code = `os.system("reboot")
  11499. `
  11500. return _code;
  11501. }
  11502. Blockly.Blocks['ai_system_refresh'] = {
  11503. init: function () {
  11504. this.appendDummyInput()
  11505. .appendField(Blockly.Msg.ai_system_refresh);
  11506. this.setPreviousStatement(true);
  11507. this.setNextStatement(true);
  11508. this.setColour("#22398e");
  11509. this.setTooltip(Blockly.Msg.ai_system_refresh_TOOLTIP);
  11510. this.setHelpUrl("");
  11511. }
  11512. };
  11513. Blockly.Python.ai_system_refresh = function (block) {
  11514. Blockly.Python.definitions_['v831_import_os'] = `import os`
  11515. var _code = `os.system("sync")
  11516. `
  11517. return _code;
  11518. }
  11519. Blockly.Blocks['ai_system_volume'] = {
  11520. init: function () {
  11521. this.appendDummyInput()
  11522. .appendField(Blockly.Msg.system_voice)
  11523. .appendField(new Blockly.FieldNumber(25, 0, 100), "play_vol");
  11524. this.setPreviousStatement(true);
  11525. this.setNextStatement(true);
  11526. this.setColour("#22398e");
  11527. }
  11528. }
  11529. Blockly.Python.ai_system_volume = function (block) {
  11530. var number_play_vol = block.getFieldValue('play_vol');
  11531. Blockly.Python.definitions_['v831_import_os'] = `import os`
  11532. Blockly.Python.definitions_['systemVoice_numberMap'] = `def voice_numberMap(value):
  11533. valueScaled = float(value - 0) / float(100)
  11534. return int(valueScaled * 31)
  11535. `
  11536. var _code = `VOICENUMP = str(voice_numberMap(${number_play_vol}))
  11537. time.sleep(0.01)
  11538. SYSTEMVOICE = "amixer cset numid=8,iface=MIXER,name=\\"LINEOUT volume\\" "+ VOICENUMP+""
  11539. os.system(SYSTEMVOICE)
  11540. `
  11541. return _code;
  11542. }
  11543. Blockly.Blocks['ai_system_thread'] = {
  11544. init: function () {
  11545. this.appendDummyInput()
  11546. .appendField(Blockly.Msg.ai_system_thread_setting)
  11547. .appendField(new Blockly.FieldNumber(1, 1, 5), "thread")
  11548. this.appendStatementInput("input")
  11549. .setCheck(null)
  11550. .appendField(Blockly.Msg.basic_motion_statement_exec);
  11551. this.setColour("#22398e");
  11552. this.setTooltip(Blockly.Msg.ai_system_thread_setting);
  11553. this.setHelpUrl("");
  11554. }
  11555. };
  11556. Blockly.Python['ai_system_thread'] = function (block) {
  11557. var threadNum = block.getFieldValue('thread');
  11558. var statements_input = Blockly.Python.statementToCode(block, 'input');
  11559. Blockly.Python.definitions_['v831_import_threading'] = `import threading`
  11560. let allBlocks = block.workspace.getAllBlocks();
  11561. let global = ""
  11562. try {
  11563. global = allBlocks[0].workspace.variableList.toString()
  11564. }
  11565. catch (e) {
  11566. console.log(e)
  11567. }
  11568. Blockly.Python.definitions_['v831_import_thread_calsss_fun' + threadNum] = `def thread_calsss_fun${threadNum}():
  11569. ${global != "" ? global : ""}
  11570. ${statements_input}
  11571. CocoPiThread${threadNum} = threading.Thread(target=thread_calsss_fun${threadNum})
  11572. `
  11573. var code = ``;
  11574. return code;
  11575. };
  11576. Blockly.Blocks['ai_system_thread_create_with_container'] = {
  11577. init: function () {
  11578. this.setColour("#22398e");
  11579. this.appendDummyInput()
  11580. .appendField(Blockly.Msg.serialcomm_write_item);
  11581. this.appendStatementInput('STACK');
  11582. this.setTooltip('');
  11583. this.contextMenu = false;
  11584. }
  11585. };
  11586. Blockly.Blocks['ai_system_thread_data_create_with_item'] = {
  11587. init: function () {
  11588. this.setColour("#22398e");
  11589. this.appendDummyInput()
  11590. .appendField(Blockly.Msg.ai_systen_thread_val);
  11591. this.setPreviousStatement(true);
  11592. this.setNextStatement(true);
  11593. this.setTooltip('');
  11594. this.contextMenu = false;
  11595. }
  11596. };
  11597. Blockly.Blocks['ai_system_thread_set_setDaemon'] = {
  11598. init: function () {
  11599. this.appendDummyInput()
  11600. .appendField(Blockly.Msg.ai_system_thread_setting).appendField(new Blockly.FieldNumber(1, 1, 5), "thread")
  11601. .appendField(Blockly.Msg.digital_set_as).appendField(new Blockly.FieldDropdown([
  11602. [Blockly.Msg.ai_system_thread_setDaemon, "True"],
  11603. [Blockly.Msg.ai_system_thread_not_setDaemon, "False"]
  11604. ]), "setDaemon");
  11605. this.setPreviousStatement(true, null);
  11606. this.setNextStatement(true, null)
  11607. this.setColour("#22398e");
  11608. this.setTooltip(Blockly.Msg.ai_system_thread_TOOLTIP);
  11609. this.setHelpUrl("");
  11610. }
  11611. };
  11612. Blockly.Python['ai_system_thread_set_setDaemon'] = function (block) {
  11613. var threadNum = block.getFieldValue('thread');
  11614. var queue_value = block.getFieldValue('setDaemon');
  11615. var code = `CocoPiThread${threadNum}.setDaemon(${queue_value})
  11616. `;
  11617. return code;
  11618. };
  11619. Blockly.Blocks['ai_system_thread_set_join'] = {
  11620. init: function () {
  11621. this.appendDummyInput()
  11622. .appendField(Blockly.Msg.ai_system_thread_setting)
  11623. .appendField(new Blockly.FieldNumber(1, 1, 5), "thread")
  11624. .appendField(Blockly.Msg.ai_system_thread_set_join)
  11625. this.setPreviousStatement(true, null);
  11626. this.setNextStatement(true, null)
  11627. this.setColour("#22398e");
  11628. this.setTooltip(Blockly.Msg.ai_system_thread_TOOLTIP);
  11629. this.setHelpUrl("");
  11630. }
  11631. };
  11632. Blockly.Python['ai_system_thread_set_join'] = function (block) {
  11633. var threadNum = block.getFieldValue('thread');
  11634. var code = `CocoPiThread${threadNum}.join()
  11635. `;
  11636. return code;
  11637. };
  11638. Blockly.Blocks['ai_system_thread_start'] = {
  11639. init: function () {
  11640. this.appendDummyInput()
  11641. .appendField(Blockly.Msg.ai_system_thread).appendField(new Blockly.FieldNumber(1, 1, 5), "thread");
  11642. // this.appendStatementInput("input")
  11643. // .setCheck(null)
  11644. // .appendField(Blockly.Msg.basic_motion_statement_exec);
  11645. this.setPreviousStatement(true, null);
  11646. this.setNextStatement(true, null)
  11647. this.setColour("#22398e");
  11648. this.setTooltip(Blockly.Msg.ai_system_thread_TOOLTIP);
  11649. this.setHelpUrl("");
  11650. }
  11651. };
  11652. Blockly.Python['ai_system_thread_start'] = function (block) {
  11653. var threadNum = block.getFieldValue('thread');
  11654. // var statements_input = Blockly.Python.statementToCode(block, 'input');
  11655. var code = `CocoPiThread${threadNum}.start()
  11656. `;
  11657. return code;
  11658. };
  11659. Blockly.Blocks["ai_system_set_queue"] = {
  11660. init: function () {
  11661. this.appendDummyInput()
  11662. .appendField(Blockly.Msg.ai_systen_queue_aritem)
  11663. this.appendValueInput("queueVaritem")
  11664. .setCheck(null);
  11665. this.appendDummyInput().appendField(Blockly.Msg.ai_systen_queue_put)
  11666. .appendField(new Blockly.FieldDropdown([
  11667. ["1", "1"],
  11668. ["2", "2"],
  11669. ["3", "3"],
  11670. ["4", "4"],
  11671. ["5", "5"]
  11672. ]), "queue_value");
  11673. this.setPreviousStatement(true, null);
  11674. this.setNextStatement(true, null);
  11675. this.setColour("#22398e");
  11676. this.setTooltip("");
  11677. }
  11678. }
  11679. Blockly.Python['ai_system_set_queue'] = function (block) {
  11680. var variable_name = Blockly.Python.valueToCode(block, 'queueVaritem', Blockly.Python.ORDER_ATOMIC);
  11681. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  11682. var queue_value = block.getFieldValue('queue_value');
  11683. Blockly.Python.definitions_["v831_import_queue"] = `import queue`
  11684. Blockly.Python.definitions_["v831_import_queue_init" + queue_value] = `queue${queue_value} = queue.Queue()`
  11685. var code = `queue${queue_value}.put(${variable_name})
  11686. `;
  11687. return code;
  11688. }
  11689. Blockly.Blocks["ai_system_get_queue"] = {
  11690. init: function () {
  11691. this.appendDummyInput()
  11692. .appendField(Blockly.Msg.ai_systen_queue_get)
  11693. .appendField(new Blockly.FieldDropdown([
  11694. ["1", "1"],
  11695. ["2", "2"],
  11696. ["3", "3"],
  11697. ["4", "4"],
  11698. ["5", "5"]
  11699. ]), "queue_value")
  11700. .appendField(Blockly.Msg.ai_systen_queue_value);
  11701. this.setOutput(true, null);
  11702. this.setColour("#22398e");
  11703. this.setTooltip("");
  11704. }
  11705. }
  11706. Blockly.Python['ai_system_get_queue'] = function (block) {
  11707. var queue_value = block.getFieldValue('queue_value');
  11708. var code = `queue${queue_value}.get()`;
  11709. return [code, Blockly.Python.ORDER_NONE];
  11710. }
  11711. // 拼音识别
  11712. Blockly.Blocks['speech_recognition_phonetic_to_pinyin_setup'] = {
  11713. init: function () {
  11714. this.appendDummyInput()
  11715. .appendField(new Blockly.FieldImage("blockly/media/speech_recognition_header_recognition_new.png", 130, 60, { alt: "*", flipRtl: "FALSE" }));
  11716. this.appendDummyInput()
  11717. .appendField(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_setup);
  11718. this.setPreviousStatement(true, null);
  11719. this.setNextStatement(true, null);
  11720. this.setColour("#ee783a");
  11721. this.setTooltip(Blockly.Msg.speech_recognition_phonetic_to_pinyin_setup_TOOLTIP);
  11722. this.setHelpUrl("");
  11723. }
  11724. };
  11725. Blockly.Python['speech_recognition_phonetic_to_pinyin_setup'] = function (block) {
  11726. Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
  11727. Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
  11728. Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
  11729. Blockly.Python.definitions_["v831_import_maix_speech"] = `import _maix_speech`
  11730. Blockly.Python.definitions_.speech_recognition_phonetic_to_pinyin_setup_def = `asr = _maix_speech.Asr()
  11731. asr.open("hw:0,0", "/root/preset/drivers/ASR/CocoPi_Asr_Model/CocoPi_Asr_Model_V2.1")
  11732. asr.clear()
  11733. asr_kws_result=[0,0] #获取识别结果及识别概率
  11734. similars = [
  11735. ["pai3", "ai4"],
  11736. ["le4", "luo4"],
  11737. ]
  11738. def asr_kws(keys):
  11739. global asr_kws_result
  11740. tmp = max(keys)
  11741. asr_kws_result[0] = keys.index(tmp)
  11742. asr_kws_result[1] = round(tmp,2)
  11743. `
  11744. var code = "";
  11745. return code;
  11746. };
  11747. Blockly.Blocks.set_pinyin_dict_create_with_items_insert = {
  11748. init: function () {
  11749. this.setColour("#ee783a");
  11750. this.appendDummyInput("").appendField(new Blockly.FieldLabel(Blockly.Msg.ai_speech_recognition_setup_pinyin), "TIP");
  11751. this.itemCount_ = 3;
  11752. this.updateShape_();
  11753. this.setOutput(!0);
  11754. this.setMutator(new Blockly.Mutator(["set_pinyin_dict_create_with_item"]));
  11755. this.setTooltip(Blockly.Msg.ai_speech_recognition_setup_pinyin_and_tone)
  11756. },
  11757. mutationToDom: function () {
  11758. var a = document.createElement("mutation");
  11759. a.setAttribute("items", this.itemCount_);
  11760. return a
  11761. },
  11762. domToMutation: function (a) {
  11763. this.itemCount_ = parseInt(a.getAttribute("items"), 10);
  11764. this.updateShape_()
  11765. },
  11766. decompose: function (a) {
  11767. var b = a.newBlock("set_pinyin_dict_create_with_container");
  11768. b.initSvg();
  11769. for (var c = b.getInput("STACK").connection, e = 0; e < this.itemCount_; e++) {
  11770. var d = a.newBlock("set_pinyin_dict_create_with_item");
  11771. d.initSvg();
  11772. c.connect(d.previousConnection);
  11773. c = d.nextConnection
  11774. }
  11775. return b
  11776. },
  11777. compose: function (a) {
  11778. a = a.getInputTargetBlock("STACK");
  11779. for (var b = [], c = 0; a;)
  11780. b[c] = a.valueConnection_,
  11781. a = a.nextConnection && a.nextConnection.targetBlock(),
  11782. c++;
  11783. this.itemCount_ = c;
  11784. this.updateShape_();
  11785. for (c = 0; c < this.itemCount_; c++)
  11786. b[c] && this.getInput("ADD" + c).connection.connect(b[c])
  11787. },
  11788. saveConnections: function (a) {
  11789. a = a.getInputTargetBlock("STACK");
  11790. for (var b = 0; a;) {
  11791. var c = this.getInput("ADD" + b);
  11792. a.valueConnection_ = c && c.connection;
  11793. b++;
  11794. a = a.nextConnection && a.nextConnection.targetBlock()
  11795. }
  11796. },
  11797. updateShape_: function () {
  11798. this.getInput("EMPTY") && this.removeInput("EMPTY");
  11799. for (var a = [], b = 0; this.getInput("ADD" + b); b++)
  11800. a.push(this.getFieldValue("KEY" + b)),
  11801. this.removeInput("ADD" + b);
  11802. if (0 == this.itemCount_)
  11803. this.getField("TIP").setText(Blockly.Msg.ai_speech_recognition_setup_pinyin);
  11804. else
  11805. for (this.getField("TIP").setText(Blockly.Msg.ai_speech_recognition_setup_pinyin),
  11806. b = 0; b < this.itemCount_; b++)
  11807. this.appendInput_(Blockly.DUMMY_INPUT, "ADD" + b).appendField(new Blockly.FieldTextInput(a.length > b ? a[b] : 0 == b ? "key_0" : "key_" + b), "KEY" + b).appendField(":")
  11808. .appendField(Blockly.Msg.ai_speech_recognition_setup_tone).appendField(new Blockly.FieldDropdown([
  11809. ["1", "1"],
  11810. ["2", "2"],
  11811. ["3", "3"],
  11812. ["4", "4"],
  11813. ]), "toneADD" + b + b)
  11814. },
  11815. getVars: function () {
  11816. return [this.getFieldValue("VAR")]
  11817. },
  11818. renameVar: function (a, b) {
  11819. Blockly.Names.equals(a, this.getFieldValue("VAR")) && this.setTitleValue(b, "VAR")
  11820. }
  11821. };
  11822. Blockly.Blocks.set_pinyin_dict_create_with_item = {
  11823. init: function () {
  11824. this.setColour("#ee783a");
  11825. this.appendDummyInput().appendField(Blockly.Msg.ai_speech_recognition_setup_pinyin);
  11826. this.setPreviousStatement(!0);
  11827. this.setNextStatement(!0);
  11828. this.setTooltip(Blockly.Msg.ai_speech_recognition_setup_pinyin);
  11829. this.contextMenu = !1
  11830. }
  11831. };
  11832. Blockly.Blocks.set_pinyin_dict_create_with_container = {
  11833. init: function () {
  11834. this.setColour("#ee783a");
  11835. this.appendDummyInput().appendField(Blockly.Msg.robot_dog_servo_execution);
  11836. this.appendStatementInput("STACK");
  11837. this.setTooltip(Blockly.Msg.robot_dog_servo_execution);
  11838. this.contextMenu = !1
  11839. }
  11840. };
  11841. Blockly.Python.set_pinyin_dict_create_with_items_insert = function (block) {
  11842. for (var a = Array(this.itemCount_), b = 0; b < this.itemCount_; b++) {
  11843. var c = this.getFieldValue("KEY" + b);
  11844. a[b] = c + block.getFieldValue("toneADD" + b + b);
  11845. }
  11846. a = "{" + a.join(", ") + "}";
  11847. return [a, Blockly.Python.ORDER_ATOMIC]
  11848. };
  11849. Blockly.Blocks['speech_recognition_phonetic_to_pinyin_set_param'] = {
  11850. init: function () {
  11851. this.appendDummyInput()
  11852. .appendField(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_set_param);
  11853. // this.appendValueInput("data")
  11854. // .setCheck(null)
  11855. // .appendField(Blockly.Msg.ai_speech_recognition_setup_pinyin);
  11856. this.setPreviousStatement(true, null);
  11857. this.setNextStatement(true, null);
  11858. this.setInputsInline(false);
  11859. this.setColour("#ee783a");
  11860. this.pinyinitemCount_ = 1
  11861. this.updateShape_();
  11862. this.setMutator(new Blockly.Mutator(["v831_to_pinyin_set_param"]));
  11863. this.setTooltip(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_set_param_TOOLTIP);
  11864. this.setHelpUrl("");
  11865. },
  11866. mutationToDom: function () {
  11867. var a = document.createElement("mutation");
  11868. a.setAttribute("items", this.pinyinitemCount_);
  11869. return a
  11870. },
  11871. domToMutation: function (a) {
  11872. this.pinyinitemCount_ = parseInt(a.getAttribute("items"), 10);
  11873. this.updateShape_()
  11874. },
  11875. decompose: function (a) {
  11876. var b = a.newBlock("v831_to_pinyin_set_param_container");
  11877. b.initSvg();
  11878. for (var c = b.getInput("STACK").connection, e = 0; e < this.pinyinitemCount_; e++) {
  11879. var d = a.newBlock("v831_to_pinyin_set_param");
  11880. d.initSvg();
  11881. c.connect(d.previousConnection);
  11882. c = d.nextConnection
  11883. }
  11884. return b
  11885. },
  11886. compose: function (a) {
  11887. var b = a.getInputTargetBlock("STACK");
  11888. for (a = []; b;)
  11889. a.push(b.valueConnection_),
  11890. b = b.nextConnection && b.nextConnection.targetBlock();
  11891. for (b = 0; b < this.pinyinitemCount_; b++) {
  11892. var c = this.getInput("PINYIN" + b).connection.targetConnection;
  11893. c && -1 == a.indexOf(c) && c.disconnect()
  11894. }
  11895. this.pinyinitemCount_ = a.length;
  11896. this.updateShape_();
  11897. for (b = 0; b < this.pinyinitemCount_; b++)
  11898. Blockly.Mutator.reconnect(a[b], this, "PINYIN" + b)
  11899. },
  11900. saveConnections: function (a) {
  11901. a = a.getInputTargetBlock("STACK");
  11902. for (var b = 0; a;) {
  11903. var c = this.getInput("PINYIN" + b);
  11904. a.valueConnection_ = c && c.connection.targetConnection;
  11905. b++;
  11906. a = a.nextConnection && a.nextConnection.targetBlock()
  11907. }
  11908. },
  11909. updateShape_: function () {
  11910. // this.itemCount_ && this.getInput("EMPTY") ? this.removeInput("EMPTY") : this.itemCount_ || this.getInput("EMPTY") || this.appendDummyInput("EMPTY").appendField(Blockly.Msg.TUPLE_CREATE_EMPTY_TITLE);
  11911. for (var a = 0; a < this.pinyinitemCount_; a++)
  11912. if (!this.getInput("PINYIN" + a)) {
  11913. var b = this.appendValueInput("PINYIN" + a);
  11914. 0 == a && b.appendField(Blockly.Msg.ai_speech_recognition_setup_pinyin_and_tone)
  11915. }
  11916. for (; this.getInput("PINYIN" + a);)
  11917. this.removeInput("PINYIN" + a),
  11918. a++
  11919. }
  11920. };
  11921. Blockly.Blocks['v831_to_pinyin_set_param'] = {
  11922. init: function () {
  11923. this.appendDummyInput()
  11924. .appendField(Blockly.Msg.ai_speech_recognition_setup_pinyin_and_tone);
  11925. this.setPreviousStatement(true);
  11926. this.setNextStatement(true);
  11927. this.setColour("#ee783a")
  11928. this.setTooltip('');
  11929. this.contextMenu = false;
  11930. }
  11931. };
  11932. Blockly.Blocks['v831_to_pinyin_set_param_container'] = {
  11933. init: function () {
  11934. this.setColour("#ee783a");
  11935. this.appendDummyInput()
  11936. .appendField(Blockly.Msg.ARD_SERIAL_SETUP);
  11937. this.appendStatementInput('STACK');
  11938. this.setTooltip('');
  11939. this.contextMenu = false;
  11940. }
  11941. };
  11942. Blockly.Python['speech_recognition_phonetic_to_pinyin_set_param'] = function (block) {
  11943. // var data = Blockly.Python.valueToCode(block, 'data', Blockly.Python.ORDER_ATOMIC);
  11944. Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
  11945. Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
  11946. Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
  11947. Blockly.Python.definitions_["v831_import_maix_speech"] = `import _maix_speech`
  11948. var a = Array(this.pinyinitemCount_)
  11949. for (let b = 0; b < this.pinyinitemCount_; b++) {
  11950. var c = Blockly.Python.valueToCode(this, "PINYIN" + b, Blockly.Python.ORDER_NONE)
  11951. a[b] = c.slice(1, -1).replaceAll(",", "")
  11952. }
  11953. a = a.map(r => [r, 0.1])
  11954. Blockly.Python.definitions_.speech_recognition_phonetic_to_pinyin_setup_def = `asr = _maix_speech.Asr()
  11955. asr.open("hw:0,0", "/home/ASR/CocoPi_Asr_Model/CocoPi_Asr_Model_V2.1")
  11956. asr.clear()
  11957. asr_kws_result=[0,0] #获取识别结果及识别概率
  11958. similars = [
  11959. ["pai3", "ai4"],
  11960. ["le4", "luo4"],
  11961. ]
  11962. def asr_kws(keys):
  11963. global asr_kws_result
  11964. tmp = max(keys)
  11965. asr_kws_result[0] = keys.index(tmp)
  11966. asr_kws_result[1] = round(tmp,2)
  11967. `
  11968. // Blockly.Python.definitions_["set_keywords_function"] = `def SetKeywords(data):
  11969. // dataList = []
  11970. // for obj in data:
  11971. // dataList.append([obj,0.1])
  11972. // print(dataList)
  11973. // return dataList
  11974. // `
  11975. var code = `keywords = ${JSON.stringify(a)}
  11976. asr.set_kws(keywords, similars, asr_kws)
  11977. `;
  11978. return code;
  11979. };
  11980. Blockly.Blocks['speech_recognition_set_pinyin_tone'] = {
  11981. init: function () {
  11982. this.appendDummyInput()
  11983. .appendField("声调").appendField(new Blockly.FieldDropdown([
  11984. ["1", "1"],
  11985. ["2", "2"],
  11986. ["3", "3"],
  11987. ["4", "4"],
  11988. ]), "tone");
  11989. this.setOutput(true, null);
  11990. this.setColour("#ee783a");
  11991. this.setTooltip(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_get_result_TOOLTIP);
  11992. this.setHelpUrl("");
  11993. }
  11994. };
  11995. Blockly.Python['speech_recognition_set_pinyin_tone'] = function (block) {
  11996. let tone = block.getFieldValue('tone');
  11997. console.log(tone)
  11998. Blockly.Python.definitions_.speech_recognition_phonetic_to_pinyin_start_recognition_def = `def getAsrResult():
  11999. global asr_kws_result,keywords
  12000. if(asr_kws_result[1]!=0):
  12001. asr_kws_result_list = keywords[asr_kws_result[0]][0]
  12002. return asr_kws_result_list
  12003. `
  12004. var code = tone;
  12005. return [code, Blockly.Python.ORDER_NONE];
  12006. };
  12007. Blockly.Blocks['speech_recognition_phonetic_to_pinyin_start_recognition'] = {
  12008. init: function () {
  12009. this.appendDummyInput()
  12010. .appendField(Blockly.Msg.speech_recognition_phonetic_to_pinyin_start_recognition);
  12011. this.setPreviousStatement(true, null);
  12012. this.setNextStatement(true, null);
  12013. this.setColour("#ee783a");
  12014. this.setTooltip(Blockly.Msg.speech_recognition_phonetic_to_pinyin_start_recognition_TOOLTIP);
  12015. this.setHelpUrl("");
  12016. }
  12017. };
  12018. Blockly.Python['speech_recognition_phonetic_to_pinyin_start_recognition'] = function (block) {
  12019. var code = "asr.run(1)\n";
  12020. return code;
  12021. };
  12022. Blockly.Blocks['speech_recognition_phonetic_to_pinyin_stop_recognition'] = {
  12023. init: function () {
  12024. this.appendDummyInput()
  12025. .appendField(Blockly.Msg.speech_recognition_phonetic_to_pinyin_stop_recognition);
  12026. this.setPreviousStatement(true, null);
  12027. this.setNextStatement(true, null);
  12028. this.setColour("#ee783a");
  12029. this.setTooltip(Blockly.Msg.speech_recognition_phonetic_to_pinyin_stop_recognition_TOOLTIP);
  12030. this.setHelpUrl("");
  12031. }
  12032. };
  12033. Blockly.Python['speech_recognition_phonetic_to_pinyin_stop_recognition'] = function (block) {
  12034. var code = "asr.exit()\n";
  12035. return code;
  12036. };
  12037. Blockly.Blocks['speech_recognition_phonetic_to_pinyin_pause_recognition'] = {
  12038. init: function () {
  12039. this.appendDummyInput()
  12040. .appendField(Blockly.Msg.speech_recognition_phonetic_to_pinyin_pause_recognition);
  12041. this.setPreviousStatement(true, null);
  12042. this.setNextStatement(true, null);
  12043. this.setColour("#ee783a");
  12044. this.setTooltip(Blockly.Msg.speech_recognition_phonetic_to_pinyin_pause_recognition_TOOLTIP);
  12045. this.setHelpUrl("");
  12046. }
  12047. };
  12048. Blockly.Python['speech_recognition_phonetic_to_pinyin_pause_recognition'] = function (block) {
  12049. var code = "asr.clear()\n";
  12050. return code;
  12051. };
  12052. Blockly.Blocks['speech_recognition_phonetic_to_pinyin_get_result'] = {
  12053. init: function () {
  12054. this.appendDummyInput()
  12055. .appendField(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_get_result);
  12056. this.setOutput(true, null);
  12057. this.setColour("#ee783a");
  12058. this.setTooltip(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_get_result_TOOLTIP);
  12059. this.setHelpUrl("");
  12060. }
  12061. };
  12062. Blockly.Python['speech_recognition_phonetic_to_pinyin_get_result'] = function (block) {
  12063. Blockly.Python.definitions_.speech_recognition_phonetic_to_pinyin_start_recognition_def = `def getAsrResult():
  12064. global asr_kws_result,keywords
  12065. if(asr_kws_result[1]!=0):
  12066. asr_kws_result_list = keywords[asr_kws_result[0]][0]
  12067. return asr_kws_result_list
  12068. `
  12069. var code = 'getAsrResult()';
  12070. return [code, Blockly.Python.ORDER_NONE];
  12071. };
  12072. // numpy + mnist
  12073. Blockly.Blocks['Numpy_Neural_Network_init'] = {
  12074. init: function () {
  12075. this.appendDummyInput()
  12076. .appendField(Blockly.Msg.numpy_mnist_model_init);
  12077. this.setPreviousStatement(true, null);
  12078. this.setNextStatement(true, null);
  12079. this.setColour("#ee783a");
  12080. this.setTooltip(Blockly.Msg.numpy_mnist_model_init);
  12081. this.setHelpUrl("");
  12082. }
  12083. };
  12084. Blockly.Python['Numpy_Neural_Network_init'] = function (block) {
  12085. Blockly.Python.definitions_['v831_import_numpy_as_np'] = `import numpy as np`;
  12086. Blockly.Python.definitions_["v831_import_pickle"] = `import pickle`
  12087. Blockly.Python.definitions_["v831_NeuralNetwork_init"] = `def sigmoid(x):
  12088. return 1/(1+np.exp(-x))
  12089. def grad(x):
  12090. return x*(1-x)
  12091. class NeuralNetwork:
  12092. """
  12093. 三层全连接前馈神经网络
  12094. """
  12095. def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate, active_function=sigmoid, gradient=grad, lambda_=0.1):
  12096. """
  12097. :param inputnodes: 输入层结点数
  12098. :param hiddennodes: 隐藏层节点数
  12099. :param outputnodes: 输出层节点数
  12100. :param learningrate: 学习率
  12101. :param active_function: 激活函数
  12102. :param gradient: 激活函数的导数
  12103. :param lambda_: L2正则化系数
  12104. """
  12105. self.inputnodes = inputnodes
  12106. self.hiddennodes = hiddennodes
  12107. self.outputnodes = outputnodes
  12108. self.learningrate = learningrate
  12109. self.active_function = active_function
  12110. self.gradient = gradient
  12111. self.lambda_ = lambda_
  12112. # 权值矩阵
  12113. self.weights_i_h = np.random.rand(
  12114. self.hiddennodes, self.inputnodes) - 0.5
  12115. self.weights_h_o = np.random.rand(
  12116. self.outputnodes, self.hiddennodes) - 0.5
  12117. def train_sgd(self, x, y):
  12118. """梯度下降训练"""
  12119. TRAINX = np.array(x).reshape(-1, 1)
  12120. target = np.zeros((self.outputnodes, 1)) + 0.01
  12121. target[y, 0] = 0.99
  12122. hiddeninputs = np.dot(self.weights_i_h, TRAINX)
  12123. hiddenoutputs = self.active_function(hiddeninputs)
  12124. outputinputs = np.dot(self.weights_h_o, hiddenoutputs)
  12125. final_outputs = self.active_function(outputinputs)
  12126. error = target - final_outputs
  12127. hidden_error = np.dot(self.weights_h_o.transpose(), error)
  12128. self.weights_h_o += self.learningrate * error * \
  12129. np.dot(self.gradient(final_outputs), hiddenoutputs.transpose())
  12130. self.weights_i_h += self.learningrate * hidden_error * \
  12131. np.dot(self.gradient(hiddenoutputs), TRAINX.transpose())
  12132. def fit(self, TRAINX, targets):
  12133. TRAINX = np.array(TRAINX)
  12134. for i in range(TRAINX.shape[0]):
  12135. self.train_sgd(TRAINX[i], targets[i])
  12136. def query(self, inputs, debug=False):
  12137. """单个值预测"""
  12138. inputs = np.array(inputs).reshape(-1, 1)
  12139. hidden_input = np.dot(self.weights_i_h, inputs)
  12140. hidden_output = self.active_function(hidden_input)
  12141. output_input = np.dot(self.weights_h_o, hidden_output)
  12142. final_output = self.active_function(output_input)
  12143. if debug:
  12144. print("predict: ", final_output)
  12145. return np.argmax(final_output)
  12146. def predict(self, inputs):
  12147. """批量预测"""
  12148. res = []
  12149. for x in inputs:
  12150. res.append(self.query(x))
  12151. return res
  12152. def __str__(self):
  12153. return "NeuralNetwork: \\ninput_nodes = {0}, hidden_nodes = {1}, \\noutputnodes = {2}, learningrate = {3}".format(self.inputnodes, self.hiddennodes, self.outputnodes, self.learningrate)
  12154. # 用测试数据测试
  12155. def accuracy(y_true, y_pred):
  12156. """准确度"""
  12157. y_true = np.array(y_true)
  12158. y_pred = np.array(y_pred)
  12159. return sum(y_true == y_pred)/y_true.shape[0]
  12160. # 用全部数据进行训练
  12161. def get_data():
  12162. # train_df = np.loadtxt("mnist_train.csv", delimiter=",", dtype=str)
  12163. # test_df = np.loadtxt("mnist_test.csv", delimiter=",", dtype=str)
  12164. global train_df, test_df
  12165. print(train_df.shape)
  12166. print(test_df.shape)
  12167. train_data = train_df.astype("int")
  12168. TRAINX = train_data[:, 1:]
  12169. TRAINY = train_data[:, 0]
  12170. TRAINX = TRAINX / 255 * 0.99 + 0.01
  12171. test_data = test_df.astype("int")
  12172. TESTX = test_data[:, 1:]
  12173. TESTY = test_data[:, 0]
  12174. TESTX = TESTX / 255 * 0.99 + 0.01
  12175. return TRAINX, TRAINY, TESTX, TESTY
  12176. `
  12177. var code = '';
  12178. return code;
  12179. };
  12180. Blockly.Blocks['Numpy_Neural_Network_load'] = {
  12181. init: function () {
  12182. this.appendDummyInput()
  12183. .appendField("numpy + mnist 训练模型加载");
  12184. this.setPreviousStatement(true, null);
  12185. this.setNextStatement(true, null);
  12186. this.setColour("#ee783a");
  12187. this.setTooltip("numpy + mnist 训练模型加载");
  12188. this.setHelpUrl("");
  12189. }
  12190. };
  12191. Blockly.Python['Numpy_Neural_Network_load'] = function (block) {
  12192. Blockly.Python.definitions_['v831_import_numpy_as_np'] = `import numpy as np`;
  12193. Blockly.Python.definitions_["v831_import_pickle"] = `import pickle`
  12194. Blockly.Python.definitions_["v831_NeuralNetwork_init"] = `def sigmoid(x):
  12195. return 1/(1+np.exp(-x))
  12196. def grad(x):
  12197. return x*(1-x)
  12198. class NeuralNetwork:
  12199. """
  12200. 三层全连接前馈神经网络
  12201. """
  12202. def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate, active_function=sigmoid, gradient=grad, lambda_=0.1):
  12203. """
  12204. :param inputnodes: 输入层结点数
  12205. :param hiddennodes: 隐藏层节点数
  12206. :param outputnodes: 输出层节点数
  12207. :param learningrate: 学习率
  12208. :param active_function: 激活函数
  12209. :param gradient: 激活函数的导数
  12210. :param lambda_: L2正则化系数
  12211. """
  12212. self.inputnodes = inputnodes
  12213. self.hiddennodes = hiddennodes
  12214. self.outputnodes = outputnodes
  12215. self.learningrate = learningrate
  12216. self.active_function = active_function
  12217. self.gradient = gradient
  12218. self.lambda_ = lambda_
  12219. # 权值矩阵
  12220. self.weights_i_h = np.random.rand(
  12221. self.hiddennodes, self.inputnodes) - 0.5
  12222. self.weights_h_o = np.random.rand(
  12223. self.outputnodes, self.hiddennodes) - 0.5
  12224. def train_sgd(self, x, y):
  12225. """梯度下降训练"""
  12226. TRAINX = np.array(x).reshape(-1, 1)
  12227. target = np.zeros((self.outputnodes, 1)) + 0.01
  12228. target[y, 0] = 0.99
  12229. hiddeninputs = np.dot(self.weights_i_h, TRAINX)
  12230. hiddenoutputs = self.active_function(hiddeninputs)
  12231. outputinputs = np.dot(self.weights_h_o, hiddenoutputs)
  12232. final_outputs = self.active_function(outputinputs)
  12233. error = target - final_outputs
  12234. hidden_error = np.dot(self.weights_h_o.transpose(), error)
  12235. self.weights_h_o += self.learningrate * error * \
  12236. np.dot(self.gradient(final_outputs), hiddenoutputs.transpose())
  12237. self.weights_i_h += self.learningrate * hidden_error * \
  12238. np.dot(self.gradient(hiddenoutputs), TRAINX.transpose())
  12239. def fit(self, TRAINX, targets):
  12240. TRAINX = np.array(TRAINX)
  12241. for i in range(TRAINX.shape[0]):
  12242. self.train_sgd(TRAINX[i], targets[i])
  12243. def query(self, inputs, debug=False):
  12244. """单个值预测"""
  12245. inputs = np.array(inputs).reshape(-1, 1)
  12246. hidden_input = np.dot(self.weights_i_h, inputs)
  12247. hidden_output = self.active_function(hidden_input)
  12248. output_input = np.dot(self.weights_h_o, hidden_output)
  12249. final_output = self.active_function(output_input)
  12250. if debug:
  12251. print("predict: ", final_output)
  12252. return np.argmax(final_output)
  12253. def predict(self, inputs):
  12254. """批量预测"""
  12255. res = []
  12256. for x in inputs:
  12257. res.append(self.query(x))
  12258. return res
  12259. def __str__(self):
  12260. return "NeuralNetwork: \\ninput_nodes = {0}, hidden_nodes = {1}, \\noutputnodes = {2}, learningrate = {3}".format(self.inputnodes, self.hiddennodes, self.outputnodes, self.learningrate)
  12261. # 用测试数据测试
  12262. def accuracy(y_true, y_pred):
  12263. """准确度"""
  12264. y_true = np.array(y_true)
  12265. y_pred = np.array(y_pred)
  12266. return sum(y_true == y_pred)/y_true.shape[0]
  12267. # 用全部数据进行训练
  12268. def get_data():
  12269. # train_df = np.loadtxt("mnist_train.csv", delimiter=",", dtype=str)
  12270. # test_df = np.loadtxt("mnist_test.csv", delimiter=",", dtype=str)
  12271. global train_df, test_df
  12272. print(train_df.shape)
  12273. print(test_df.shape)
  12274. train_data = train_df.astype("int")
  12275. TRAINX = train_data[:, 1:]
  12276. TRAINY = train_data[:, 0]
  12277. TRAINX = TRAINX / 255 * 0.99 + 0.01
  12278. test_data = test_df.astype("int")
  12279. TESTX = test_data[:, 1:]
  12280. TESTY = test_data[:, 0]
  12281. TESTX = TESTX / 255 * 0.99 + 0.01
  12282. return TRAINX, TRAINY, TESTX, TESTY
  12283. `
  12284. var code = `#构建神经网络训练服务
  12285. TRAINX, TRAINY, TESTX, TESTY = get_data()
  12286. NN = NeuralNetwork(784, 100, 10, 0.3)
  12287. NN.fit(TRAINX, TRAINY)
  12288. y_pred = NN.predict(TESTX)
  12289. `;
  12290. return code;
  12291. };
  12292. Blockly.Blocks['Numpy_Neural_Network_LOading_test_train'] = {
  12293. init: function () {
  12294. this.appendDummyInput()
  12295. .appendField(Blockly.Msg.numpy_mnist_loading_train_and_test_set);
  12296. this.appendValueInput("class_input")
  12297. .setCheck(null)
  12298. .appendField(Blockly.Msg.numpy_mnist_train_set_url);
  12299. this.appendValueInput("class_input1")
  12300. .setCheck(null)
  12301. .appendField(Blockly.Msg.numpy_mnist_test_set_url);
  12302. this.setPreviousStatement(true, null);
  12303. this.setNextStatement(true, null);
  12304. this.setColour("#ee783a");
  12305. this.setTooltip(Blockly.Msg.numpy_mnist_loading_train_and_test_set);
  12306. this.setHelpUrl("");
  12307. }
  12308. };
  12309. Blockly.Python['Numpy_Neural_Network_LOading_test_train'] = function (block) {
  12310. var trainUrl = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  12311. var testUrl = Blockly.Python.valueToCode(block, 'class_input1', Blockly.Python.ORDER_ATOMIC);
  12312. // TODO: Assemble Python into code variable.
  12313. var code = `test_df = np.loadtxt(${testUrl}, delimiter=",", dtype=str)
  12314. train_df = np.loadtxt(${trainUrl}, delimiter=",", dtype=str)
  12315. `;
  12316. // TODO: Change ORDER_NONE to the correct strength.
  12317. return code;
  12318. };
  12319. Blockly.Blocks['Numpy_Neural_Network_numpy_isStart'] = {
  12320. init: function () {
  12321. this.appendDummyInput()
  12322. .appendField(Blockly.Msg.numpy_mnist_is_training_start);
  12323. this.setOutput(true, null);
  12324. this.setColour("#ee783a");
  12325. this.setTooltip(Blockly.Msg.numpy_mnist_is_training_start);
  12326. this.setHelpUrl("");
  12327. }
  12328. };
  12329. Blockly.Python['Numpy_Neural_Network_numpy_isStart'] = function (block) {
  12330. // TODO: Assemble Python into code variable.
  12331. var code = `not os.path.exists("/usr/lib/python3.8/site-packages/numpy/random/__init__.py")`;
  12332. // TODO: Change ORDER_NONE to the correct strength.
  12333. return [code, Blockly.Python.ORDER_NONE];
  12334. };
  12335. Blockly.Blocks['Numpy_Neural_Network_setting_training_argument'] = {
  12336. init: function () {
  12337. this.appendDummyInput()
  12338. .appendField(Blockly.Msg.numpy_mnist_setting_training_argument);
  12339. this.appendValueInput("class_input")
  12340. .setCheck(null)
  12341. .appendField(Blockly.Msg.numpy_mnist_input_trait_dimensionality);
  12342. this.appendValueInput("class_input1")
  12343. .setCheck(null)
  12344. .appendField(Blockly.Msg.numpy_mnist_setting_training_argument_number_node);
  12345. this.appendValueInput("class_input2")
  12346. .setCheck(null)
  12347. .appendField(Blockly.Msg.numpy_mnist_output_dimensionality);
  12348. this.appendValueInput("class_input3")
  12349. .setCheck(null)
  12350. .appendField(Blockly.Msg.numpy_mnist_setting_training_argument_learning_rate);
  12351. this.appendValueInput("class_input4")
  12352. .setCheck(null)
  12353. .appendField(Blockly.Msg.numpy_mnist_setting_training_argument_frequency);
  12354. this.appendValueInput("class_input5")
  12355. .setCheck(null)
  12356. .appendField(Blockly.Msg.VIDEO_S_S);
  12357. this.setPreviousStatement(true, null);
  12358. this.setNextStatement(true, null);
  12359. this.setColour("#ee783a");
  12360. this.setTooltip(Blockly.Msg.numpy_mnist_setting_training_argument);
  12361. this.setHelpUrl("");
  12362. }
  12363. };
  12364. Blockly.Python['Numpy_Neural_Network_setting_training_argument'] = function (block) {
  12365. var class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  12366. var class_input1 = Blockly.Python.valueToCode(block, 'class_input1', Blockly.Python.ORDER_ATOMIC);
  12367. var class_input2 = Blockly.Python.valueToCode(block, 'class_input2', Blockly.Python.ORDER_ATOMIC);
  12368. var class_input3 = Blockly.Python.valueToCode(block, 'class_input3', Blockly.Python.ORDER_ATOMIC);
  12369. var class_input4 = Blockly.Python.valueToCode(block, 'class_input4', Blockly.Python.ORDER_ATOMIC);
  12370. var class_input5 = Blockly.Python.valueToCode(block, 'class_input5', Blockly.Python.ORDER_ATOMIC);
  12371. // TODO: Assemble Python into code variable.
  12372. console.log(Number(class_input.slice(1, -1)), class_input1, class_input2, class_input3)
  12373. var code = `TRAINX, TRAINY, TESTX, TESTY = get_data()
  12374. NN = NeuralNetwork(${Number(class_input.slice(1, -1))}, ${Number(class_input1.slice(1, -1))}, ${Number(class_input2.slice(1, -1))}, ${Number(class_input3.slice(1, -1))})
  12375. #开启神经网络训练,记录时长
  12376. AccuracyRATE = 0
  12377. # 训练10次,每3次训练下降一次学习率
  12378. for e in range(1, ${Number(class_input4.slice(1, -1)) + 1}):
  12379. if e % 3 == 0:
  12380. NN.learningrate /= 2
  12381. NN.fit(TRAINX, TRAINY)
  12382. y_pred = NN.predict(TESTX)
  12383. CURRENTACCURACY = accuracy(TESTY, y_pred)
  12384. if CURRENTACCURACY > AccuracyRATE:
  12385. AccuracyRATE = CURRENTACCURACY
  12386. #文件已保存至
  12387. with open(${class_input5}, "wb") as f: # 保存模型
  12388. pickle.dump(pickle.dumps(NN), f)
  12389. os.system("touch /usr/lib/python3.8/site-packages/numpy/random/__init__.py")
  12390. `;
  12391. // TODO: Change ORDER_NONE to the correct strength.
  12392. return code;
  12393. };
  12394. //
  12395. Blockly.Blocks['Numpy_Neural_Network_numpy_loading_model'] = {
  12396. init: function () {
  12397. this.appendDummyInput()
  12398. .appendField(Blockly.Msg.numpy_mnist_loading_model);
  12399. this.appendValueInput("class_input")
  12400. .setCheck(null)
  12401. .appendField(Blockly.Msg.AUDIO_S_PF);
  12402. this.setPreviousStatement(true, null);
  12403. this.setNextStatement(true, null);
  12404. this.setColour("#ee783a");
  12405. this.setTooltip(Blockly.Msg.numpy_mnist_loading_model);
  12406. this.setHelpUrl("");
  12407. }
  12408. };
  12409. Blockly.Python['Numpy_Neural_Network_numpy_loading_model'] = function (block) {
  12410. var trainUrl = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  12411. // TODO: Assemble Python into code variable.
  12412. var code = `try:
  12413. with open(${trainUrl},"rb") as f:
  12414. b_data = pickle.load(f)
  12415. net_model = pickle.loads(b_data)
  12416. except:
  12417. pass
  12418. `;
  12419. // TODO: Change ORDER_NONE to the correct strength.
  12420. return code;
  12421. };
  12422. Blockly.Python['Numpy_Neural_Network_LOading_test_train'] = function (block) {
  12423. var trainUrl = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  12424. var testUrl = Blockly.Python.valueToCode(block, 'class_input1', Blockly.Python.ORDER_ATOMIC);
  12425. // TODO: Assemble Python into code variable.
  12426. var code = `test_df = np.loadtxt(${testUrl}, delimiter=",", dtype=str)
  12427. train_df = np.loadtxt(${trainUrl}, delimiter=",", dtype=str)
  12428. `;
  12429. // TODO: Change ORDER_NONE to the correct strength.
  12430. return code;
  12431. };
  12432. Blockly.Blocks['Numpy_Neural_Network_numpy_loading_model_fun'] = {
  12433. init: function () {
  12434. // this.appendDummyInput()
  12435. // .appendField("获取检测结果");
  12436. this.appendDummyInput()
  12437. .appendField("在屏幕中显示numpy的检测结果")
  12438. this.setPreviousStatement(true, null);
  12439. this.setNextStatement(true, null);
  12440. this.setColour("#ee783a");
  12441. this.setTooltip(Blockly.Msg.ai_model_getclass_TOOLTIP);
  12442. this.setHelpUrl("");
  12443. }
  12444. };
  12445. Blockly.Python['Numpy_Neural_Network_numpy_loading_model_fun'] = function (block) {
  12446. Blockly.Python.definitions_["v831_import_PIL_image"] = `from PIL import Image`
  12447. Blockly.Python.definitions_["v831_function_numpy_result"] = `def numpyResult(img):
  12448. img_path="/root/user/image_1.png"
  12449. img_gray_path="/root/user/image_gray.png"
  12450. mk = img.crop(0, 0, 240, 240) #裁剪图像为320*240
  12451. mk1=img.crop(0, 0, 240, 240).resize(224,224) #继续裁剪图像为224*224
  12452. numpyResultcanvas= image.new(size = (320, 240), color = (0,255,0), mode = 'RGB') #创建背景图
  12453. numpyResultcanvas.draw_image(mk1.rotate(90,adjust=1),58,8) #贴224*224的图片
  12454. mk2=mk1.resize(28,28) #裁剪图片为28*28
  12455. numpyResultcanvas.draw_image(mk2,8,8) #贴28*28的图
  12456. mk2.save(img_path)
  12457. origin=Image.open(img_path).convert('L') #转为8位分辨率灰度图(0~255)
  12458. origin.save(img_gray_path)
  12459. origin_gray=image.open(img_gray_path)
  12460. numpyResultcanvas.draw_image(origin_gray,8,48)
  12461. numpyResultImg = np.array(origin).reshape(1, 784).astype('int')
  12462. numpyResultImg = numpyResultImg / 255 * 0.99 + 0.01
  12463. print(numpyResultImg.shape)
  12464. result = net_model.query(numpyResultImg)
  12465. return result
  12466. `
  12467. // TODO: Assemble Python into code variable.
  12468. var code = `canvas = canvas.crop(48,8,224,224)
  12469. GETNUMPYRESULT = numpyResult(canvas)
  12470. if GETNUMPYRESULT != "":
  12471. canvas.draw_string(0,0, (str(GETNUMPYRESULT)), scale = 3, color = (204,204,204) , thickness = 1)
  12472. else:
  12473. canvas.draw_string(0,0, ("None"), scale = 3, color = (204,204,204) , thickness = 1)
  12474. `;
  12475. // TODO: Change ORDER_NONE to the correct strength.
  12476. return code;
  12477. };
  12478. Blockly.Blocks['Numpy_Neural_Network_numpy_loading_model_result'] = {
  12479. init: function () {
  12480. this.appendDummyInput()
  12481. .appendField(Blockly.Msg.numpy_mnist_get_result);
  12482. this.setOutput(true, null);
  12483. this.setColour("#ee783a");
  12484. this.setTooltip(Blockly.Msg.numpy_mnist_get_result);
  12485. this.setHelpUrl("");
  12486. }
  12487. };
  12488. Blockly.Python['Numpy_Neural_Network_numpy_loading_model_result'] = function (block) {
  12489. var code = `GETNUMPYRESULT`;
  12490. // TODO: Change ORDER_NONE to the correct strength.
  12491. return [code, Blockly.Python.ORDER_NONE];
  12492. };
  12493. //
  12494. Blockly.Blocks['Numpy_Neural_Network_numpy_clear'] = {
  12495. init: function () {
  12496. this.appendDummyInput()
  12497. .appendField(Blockly.Msg.numpy_mnist_clear);
  12498. this.setPreviousStatement(true, null);
  12499. this.setNextStatement(true, null);
  12500. this.setColour("#ee783a");
  12501. this.setTooltip(Blockly.Msg.numpy_mnist_clear);
  12502. this.setHelpUrl("");
  12503. }
  12504. };
  12505. Blockly.Python['Numpy_Neural_Network_numpy_clear'] = function (block) {
  12506. var code = `os.system('rm -rf /usr/lib/python3.8/site-packages/numpy/random/__init__.py')
  12507. `;
  12508. // TODO: Change ORDER_NONE to the correct strength.
  12509. return code;
  12510. };
  12511. Blockly.Blocks["cocopi_chatGpt_init"] = {
  12512. init: function () {
  12513. this.appendDummyInput()
  12514. .appendField(Blockly.Msg.ChatGpt_init); //
  12515. this.setPreviousStatement(true, null);
  12516. this.setNextStatement(true, null);
  12517. this.setColour("#7e3cca");
  12518. this.setTooltip(Blockly.Msg.ChatGpt_init);
  12519. this.setHelpUrl("");
  12520. }
  12521. };
  12522. Blockly.Python['cocopi_chatGpt_init'] = function (block) {
  12523. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  12524. sys.path.append("/root/")`
  12525. Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try:
  12526. from CocoPi import GPTrequest
  12527. except:
  12528. import sys
  12529. sys.path.append("/home/drivers/pylib/")
  12530. from GPTrequest import GPTrequest`
  12531. Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()`
  12532. var code = ``;
  12533. // TODO: Change ORDER_NONE to the correct strength.
  12534. return code;
  12535. };
  12536. Blockly.Blocks["cocopi_chatGpt_text_to_img_loading"] = {
  12537. init: function () {
  12538. this.appendValueInput("NAME")
  12539. .setCheck(null)
  12540. .appendField(Blockly.Msg.ChatGpt_set_img_des);
  12541. this.appendDummyInput()
  12542. .appendField(Blockly.Msg.ChatGpt_get_img_path_result);
  12543. this.setOutput(true, null);
  12544. this.setColour("#7e3cca");
  12545. this.setTooltip(Blockly.Msg.ChatGpt_set_img_des);
  12546. this.setInputsInline(false)
  12547. this.setHelpUrl("");
  12548. }
  12549. };
  12550. Blockly.Python['cocopi_chatGpt_text_to_img_loading'] = function (block) {
  12551. var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
  12552. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  12553. sys.path.append("/root/")`
  12554. Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try:
  12555. from CocoPi import GPTrequest
  12556. except:
  12557. import sys
  12558. sys.path.append("/home/drivers/pylib/")
  12559. from GPTrequest import GPTrequest`
  12560. Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()`
  12561. // Blockly.Python.addVariable("TextContent", `TextContent = ""`, true)
  12562. var code = `gptInit.get_text_to_img(${text})`;
  12563. // TODO: Change ORDER_NONE to the correct strength.
  12564. return [code, Blockly.Python.ORDER_ATOMIC];
  12565. };
  12566. Blockly.Blocks["cocopi_chatGpt_image_to_text_loading"] = {
  12567. init: function () {
  12568. this.appendValueInput("NAME")
  12569. .setCheck(null)
  12570. .appendField(Blockly.Msg.ChatGpt_set_text_path);
  12571. this.appendValueInput("NAME1")
  12572. .setCheck(null)
  12573. .appendField(Blockly.Msg.ChatGpt_set_text_text_content);
  12574. this.appendDummyInput()
  12575. .appendField(Blockly.Msg.ChatGpt_get_text_content_result);
  12576. this.setOutput(true, null);
  12577. this.setInputsInline(false);
  12578. this.setColour("#7e3cca");
  12579. this.setTooltip(Blockly.Msg.ChatGpt_set_text_path);
  12580. this.setHelpUrl("");
  12581. }
  12582. };
  12583. Blockly.Python['cocopi_chatGpt_image_to_text_loading'] = function (block) {
  12584. var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
  12585. var content = Blockly.Python.valueToCode(block, 'NAME1', Blockly.Python.ORDER_ATOMIC);
  12586. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  12587. sys.path.append("/root/")`
  12588. Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try:
  12589. from CocoPi import GPTrequest
  12590. except:
  12591. import sys
  12592. sys.path.append("/home/drivers/pylib/")
  12593. from GPTrequest import GPTrequest`
  12594. Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()`
  12595. var code = `gptInit.get_image_to_text(${text},${content})`;
  12596. // TODO: Change ORDER_NONE to the correct strength.
  12597. return [code, Blockly.Python.ORDER_ATOMIC];
  12598. };
  12599. Blockly.Blocks["cocopi_chatGpt_text_to_voice_loading"] = {
  12600. init: function () {
  12601. this.appendValueInput("NAME")
  12602. .setCheck(null)
  12603. .appendField(Blockly.Msg.ChatGpt_set_text_content);
  12604. this.appendDummyInput()
  12605. .appendField(Blockly.Msg.ChatGpt_get_voice_path_result);
  12606. this.setOutput(true, null);
  12607. this.setInputsInline(false);
  12608. this.setColour("#7e3cca");
  12609. this.setTooltip(Blockly.Msg.ChatGpt_get_voice_path_result);
  12610. this.setHelpUrl("");
  12611. }
  12612. };
  12613. Blockly.Python['cocopi_chatGpt_text_to_voice_loading'] = function (block) {
  12614. var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
  12615. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  12616. sys.path.append("/root/")`
  12617. Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try:
  12618. from CocoPi import GPTrequest
  12619. except:
  12620. import sys
  12621. sys.path.append("/home/drivers/pylib/")
  12622. from GPTrequest import GPTrequest`
  12623. Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()`
  12624. var code = `gptInit.get_text_to_voice(${text})`;
  12625. // TODO: Change ORDER_NONE to the correct strength.
  12626. return [code, Blockly.Python.ORDER_ATOMIC];
  12627. };
  12628. Blockly.Blocks["cocopi_chatGpt_text_to_voice_result"] = {
  12629. init: function () {
  12630. this.appendDummyInput()
  12631. .appendField(Blockly.Msg.ChatGpt_get_voice_path_result);
  12632. this.setOutput(true, null);
  12633. this.setColour("#7e3cca");
  12634. this.setTooltip(Blockly.Msg.ChatGpt_get_voice_path_result);
  12635. this.setHelpUrl("");
  12636. }
  12637. };
  12638. Blockly.Python['cocopi_chatGpt_text_to_voice_result'] = function (block) {
  12639. var code = `gptInit.get_text_to_voice(VOICECONTENT)`;
  12640. return [code, Blockly.Python.ORDER_ATOMIC];
  12641. };
  12642. Blockly.Blocks["cocopi_chatGpt_voice_to_text_loading"] = {
  12643. init: function () {
  12644. this.appendValueInput("NAME")
  12645. .setCheck(null)
  12646. .appendField(Blockly.Msg.ChatGpt_set_voice_path);
  12647. this.appendDummyInput()
  12648. .appendField(Blockly.Msg.ChatGpt_get_voice_text_content_result);
  12649. this.setOutput(true, null);
  12650. this.setInputsInline(false)
  12651. this.setColour("#7e3cca");
  12652. this.setTooltip(Blockly.Msg.ChatGpt_set_voice_path);
  12653. this.setHelpUrl("");
  12654. }
  12655. };
  12656. Blockly.Python['cocopi_chatGpt_voice_to_text_loading'] = function (block) {
  12657. var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
  12658. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  12659. sys.path.append("/root/")`
  12660. Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try:
  12661. from CocoPi import GPTrequest
  12662. except:
  12663. import sys
  12664. sys.path.append("/home/drivers/pylib/")
  12665. from GPTrequest import GPTrequest`
  12666. Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()`
  12667. var code = `gptInit.get_voice_to_text(${text})`;
  12668. // TODO: Change ORDER_NONE to the correct strength.
  12669. return [code, Blockly.Python.ORDER_ATOMIC];
  12670. };
  12671. Blockly.Blocks["cocopi_chatGpt_post_chatgpt_loading"] = {
  12672. init: function () {
  12673. this.appendValueInput("NAME")
  12674. .setCheck(null)
  12675. .appendField(Blockly.Msg.ChatGpt_set_problem_content);
  12676. this.appendDummyInput()
  12677. .appendField(Blockly.Msg.ChatGpt_get_problem_result);
  12678. this.setOutput(true, null);
  12679. this.setInputsInline(false)
  12680. this.setColour("#7e3cca");
  12681. this.setTooltip(Blockly.Msg.ChatGpt_set_problem_content);
  12682. this.setHelpUrl("");
  12683. }
  12684. };
  12685. Blockly.Python['cocopi_chatGpt_post_chatgpt_loading'] = function (block) {
  12686. var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
  12687. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  12688. sys.path.append("/root/")`
  12689. Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try:
  12690. from CocoPi import GPTrequest
  12691. except:
  12692. import sys
  12693. sys.path.append("/home/drivers/pylib/")
  12694. from GPTrequest import GPTrequest`
  12695. Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()`
  12696. var code = `gptInit.get_post_chatgpt(${text})`;
  12697. // TODO: Change ORDER_NONE to the correct strength.
  12698. return [code, Blockly.Python.ORDER_ATOMIC];
  12699. };
  12700. Blockly.Blocks["cocopi_chatGpt_post_chatgpt_result"] = {
  12701. init: function () {
  12702. this.appendDummyInput()
  12703. .appendField(Blockly.Msg.ChatGpt_get_problem_result);
  12704. this.setOutput(true, null);
  12705. this.setColour("#7e3cca");
  12706. this.setTooltip(Blockly.Msg.ChatGpt_get_problem_result);
  12707. this.setHelpUrl("");
  12708. }
  12709. };
  12710. Blockly.Python['cocopi_chatGpt_post_chatgpt_result'] = function (block) {
  12711. var code = `gptInit.get_post_chatgpt(CHATGPTPROBLEM)`;
  12712. return [code, Blockly.Python.ORDER_ATOMIC];;
  12713. };
  12714. //
  12715. Blockly.Blocks["cocopi_chatGpt_result"] = {
  12716. init: function () {
  12717. this.appendDummyInput()
  12718. // .appendField(Blockly.Msg.ChatGpt_get_problem_result)
  12719. .appendField(new Blockly.FieldDropdown([
  12720. [Blockly.Msg.ChatGpt_get_img_path_result, "1"],
  12721. [Blockly.Msg.ChatGpt_get_text_content_result, "2"],
  12722. [Blockly.Msg.ChatGpt_get_voice_path_result, "3"],
  12723. [Blockly.Msg.ChatGpt_get_voice_text_content_result, "4"],
  12724. [Blockly.Msg.ChatGpt_get_problem_result, "5"],
  12725. [Blockly.Msg.ChatGpt_ai_agent_chat_result, "6"]
  12726. ]), "gpt_return");
  12727. this.setOutput(true, null);
  12728. this.setColour("#7e3cca");
  12729. this.setTooltip(Blockly.Msg.ChatGpt_get_problem_result);
  12730. this.setHelpUrl("");
  12731. }
  12732. };
  12733. Blockly.Python['cocopi_chatGpt_result'] = function (block) {
  12734. var queue_value = block.getFieldValue('gpt_return');
  12735. Blockly.Python.addVariable("CocoPiGPTRESULT", `CocoPiGPTRESULT = None`, true)
  12736. var res = ``;
  12737. if (queue_value == 5) {
  12738. res = `gptInit.get_post_chatgpt(CHATGPTPROBLEM)`
  12739. } else if (queue_value == 4) {
  12740. res = `gptInit.get_voice_to_text(VOICEPATH)`
  12741. } else if (queue_value == 3) {
  12742. res = `gptInit.get_text_to_voice(VOICECONTENT)`
  12743. } else if (queue_value == 2) {
  12744. res = `gptInit.get_image_to_text(IMAGEPATH,IMAGECONTENT)`
  12745. } else if (queue_value == 1) {
  12746. res = `gptInit.get_text_to_img(TextContent)`
  12747. }
  12748. else if (queue_value == 6) {
  12749. res = `gptInit.get_post_AI_Intelligence(AIAGENTCHATID,AIAGENTCHATMESSAGE)`
  12750. }
  12751. Blockly.Python.definitions_["CocoPiGPTRESULTFUNC"] = `def CocoPiGPTRESULTFUNC(res):
  12752. global CocoPiGPTRESULT
  12753. try:
  12754. CocoPiGPTRESULT = res
  12755. except:
  12756. CocoPiGPTRESULT = ""
  12757. return CocoPiGPTRESULT
  12758. `
  12759. var code = `CocoPiGPTRESULTFUNC(${res})`;
  12760. return [code, Blockly.Python.ORDER_ATOMIC];;
  12761. };
  12762. Blockly.Blocks["cocopi_chatGpt_AI_loading"] = {
  12763. init: function () {
  12764. this.appendValueInput("NAME")
  12765. .setCheck(null)
  12766. .appendField(Blockly.Msg.ChatGpt_ai_agent_chat_set_appID);
  12767. this.appendValueInput("NAME1")
  12768. .setCheck(null)
  12769. .appendField(Blockly.Msg.ChatGpt_set_problem_content);
  12770. this.appendDummyInput().appendField(Blockly.Msg.ChatGpt_ai_agent_chat_result)
  12771. this.setOutput(true, null);
  12772. this.setInputsInline(false);
  12773. this.setColour("#7e3cca");
  12774. this.setTooltip(Blockly.Msg.ChatGpt_set_text_path);
  12775. this.setHelpUrl("");
  12776. }
  12777. };
  12778. Blockly.Python['cocopi_chatGpt_AI_loading'] = function (block) {
  12779. var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
  12780. var content = Blockly.Python.valueToCode(block, 'NAME1', Blockly.Python.ORDER_ATOMIC);
  12781. var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
  12782. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  12783. sys.path.append("/root/")`
  12784. Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try:
  12785. from CocoPi import GPTrequest
  12786. except:
  12787. import sys
  12788. sys.path.append("/home/drivers/pylib/")
  12789. from GPTrequest import GPTrequest`
  12790. Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()`
  12791. var code = `gptInit.get_post_AI_Intelligence(${text},${content})`
  12792. return [code, Blockly.Python.ORDER_ATOMIC];
  12793. };
  12794. //
  12795. Blockly.Blocks["cocopi_chatGpt_AI_loading_more"] = {
  12796. init: function () {
  12797. this.appendValueInput("NAME")
  12798. .setCheck(null)
  12799. .appendField(Blockly.Msg.ChatGpt_ai_agent_chat_set_appID_more);
  12800. this.appendValueInput("NAME1")
  12801. .setCheck(null)
  12802. .appendField(Blockly.Msg.ChatGpt_set_problem_content);
  12803. this.appendDummyInput().appendField(Blockly.Msg.ChatGpt_ai_agent_chat_result_more)
  12804. this.setOutput(true, null);
  12805. this.setInputsInline(false);
  12806. this.setColour("#7e3cca");
  12807. this.setTooltip(Blockly.Msg.ChatGpt_set_text_path);
  12808. this.setHelpUrl("");
  12809. }
  12810. };
  12811. Blockly.Python['cocopi_chatGpt_AI_loading_more'] = function (block) {
  12812. var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
  12813. var content = Blockly.Python.valueToCode(block, 'NAME1', Blockly.Python.ORDER_ATOMIC);
  12814. var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
  12815. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  12816. sys.path.append("/root/")`
  12817. Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try:
  12818. from CocoPi import GPTrequest
  12819. except:
  12820. import sys
  12821. sys.path.append("/home/drivers/pylib/")
  12822. from GPTrequest import GPTrequest`
  12823. Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()`
  12824. var code = `gptInit.cocopi_chatGpt_AI_loading_more(${text},${content})`
  12825. // Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  12826. // Blockly.Python.definitions_['v831_import_json'] = `import json`
  12827. // Blockly.Python.definitions_['v831_import_os'] = `import os`
  12828. // Blockly.Python.definitions_['v831_import_time'] = `import time`
  12829. // Blockly.Python.addFunction("cocopi_chatGpt_AI_loading_more", `def cocopi_chatGpt_AI_loading_more(appID,content):
  12830. // url = "https://gpt4.cocorobo.cn/handle_muti_agent"
  12831. // headers={
  12832. // "Content-Type":"application/json",
  12833. // }
  12834. // cmd="cat /sys/class/sunxi_info/sys_info"
  12835. // rec=os.popen(cmd).read()
  12836. // hwMac=rec[rec.find("sunxi_serial : ")+20:rec.find("sunxi_serial : ")+52]
  12837. // params = {
  12838. // "muti_agent_id":appID,
  12839. // "message":content,
  12840. // "userId":"602def61-005d-11ee-91d8-005056b86db5",
  12841. // "session_name":"0606"
  12842. // }
  12843. // textContent = ""
  12844. // res = requests.post(url, headers=headers, data=json.dumps(params))
  12845. // try:
  12846. // textContent = json.loads(res.text)["FunctionResponse"]["response"]
  12847. // except:
  12848. // textContent = ""
  12849. // return textContent
  12850. // `, true)
  12851. return [code, Blockly.Python.ORDER_ATOMIC];
  12852. };
  12853. Blockly.Blocks.tuple_create_with_items_inserts = {
  12854. init: function () {
  12855. this.setHelpUrl(Blockly.Msg.TUPLE_CREATE_WITH_ITEMS_INSERT_HELPURL);
  12856. this.setColour("#ee783a");
  12857. this.itemCount_ = 3;
  12858. this.updateShape_();
  12859. this.setOutput(!0);
  12860. this.setMutator(new Blockly.Mutator(["tuple_create_with_items"]));
  12861. this.setTooltip(Blockly.Msg.TUPLE_CREATE_WITH_ITEMS_INSERT_TOOLTIP)
  12862. },
  12863. mutationToDom: function () {
  12864. var a = document.createElement("mutation");
  12865. a.setAttribute("items", this.itemCount_);
  12866. return a
  12867. },
  12868. domToMutation: function (a) {
  12869. this.itemCount_ = parseInt(a.getAttribute("items"), 10);
  12870. this.updateShape_()
  12871. },
  12872. decompose: function (a) {
  12873. var b = a.newBlock("tuple_create_with_containers");
  12874. b.initSvg();
  12875. for (var c = b.getInput("STACK").connection, e = 0; e < this.itemCount_; e++) {
  12876. var d = a.newBlock("tuple_create_with_items");
  12877. d.initSvg();
  12878. c.connect(d.previousConnection);
  12879. c = d.nextConnection
  12880. }
  12881. return b
  12882. },
  12883. compose: function (a) {
  12884. var b = a.getInputTargetBlock("STACK");
  12885. for (a = []; b;)
  12886. a.push(b.valueConnection_),
  12887. b = b.nextConnection && b.nextConnection.targetBlock();
  12888. for (b = 0; b < this.itemCount_; b++) {
  12889. var c = this.getInput("ADD" + b).connection.targetConnection;
  12890. c && -1 == a.indexOf(c) && c.disconnect()
  12891. }
  12892. this.itemCount_ = a.length;
  12893. this.updateShape_();
  12894. for (b = 0; b < this.itemCount_; b++)
  12895. Blockly.Mutator.reconnect(a[b], this, "ADD" + b)
  12896. },
  12897. saveConnections: function (a) {
  12898. a = a.getInputTargetBlock("STACK");
  12899. for (var b = 0; a;) {
  12900. var c = this.getInput("ADD" + b);
  12901. a.valueConnection_ = c && c.connection.targetConnection;
  12902. b++;
  12903. a = a.nextConnection && a.nextConnection.targetBlock()
  12904. }
  12905. },
  12906. updateShape_: function () {
  12907. this.itemCount_ && this.getInput("EMPTY") ? this.removeInput("EMPTY") : this.itemCount_ || this.getInput("EMPTY") || this.appendDummyInput("EMPTY").appendField(Blockly.Msg.TUPLE_CREATE_EMPTY_TITLE);
  12908. for (var a = 0; a < this.itemCount_; a++)
  12909. if (!this.getInput("ADD" + a)) {
  12910. var b = this.appendValueInput("ADD" + a);
  12911. 0 == a && b.appendField(Blockly.Msg.TUPLE_CREATE_WITH_INPUT_WITH)
  12912. }
  12913. for (; this.getInput("ADD" + a);)
  12914. this.removeInput("ADD" + a),
  12915. a++
  12916. }
  12917. };
  12918. Blockly.Blocks.tuple_create_with_items = {
  12919. init: function () {
  12920. this.setColour("#ee783a");
  12921. this.appendDummyInput().appendField(Blockly.Msg.TUPLE_CREATE_WITH_ITEM_TITLE);
  12922. this.setPreviousStatement(!0);
  12923. this.setNextStatement(!0);
  12924. this.setTooltip(Blockly.Msg.TUPLE_CREATE_WITH_ITEM_TOOLTIP);
  12925. this.contextMenu = !1
  12926. }
  12927. };
  12928. Blockly.Blocks.tuple_create_with_containers = {
  12929. init: function () {
  12930. this.setColour("#ee783a");
  12931. this.appendDummyInput().appendField(Blockly.Msg.TUPLE_CREATE_WITH_CONTAINER_TITLE_ADD);
  12932. this.appendStatementInput("STACK");
  12933. this.setTooltip(Blockly.Msg.TUPLE_CREATE_WITH_CONTAINER_TOOLTIP);
  12934. this.contextMenu = !1
  12935. }
  12936. };
  12937. Blockly.Python.tuple_create_with_items_inserts = function (a) {
  12938. for (var b = Array(a.itemCount_), c = 0; c < a.itemCount_; c++)
  12939. b[c] = Blockly.Python.valueToCode(a, "ADD" + c, Blockly.Python.ORDER_NONE) || "None";
  12940. return [1 == a.itemCount_ ? "(" + b[0] + ",)" : "(" + b.join(", ") + ")", Blockly.Python.ORDER_ATOMIC]
  12941. };