12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167 |
- /*
- _ ___ ____ _
- / \ |_ _| | __ ) __ _ ___(_) ___
- / _ \ | | | _ \ / _` / __| |/ __|
- / ___ \ | | | |_) | (_| \__ \ | (__
- /_/ \_\___| |____/ \__,_|___/_|\___|
- */
- Blockly.Blocks['ai_v831_button_read_pressed_canvas'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_basic_button_when)
- .appendField(new Blockly.FieldDropdown([
- ["A", "A"],
- ["B", "B"],
- ["C", "C"],
- ["D", "D"]
- ]), "button_type")
- .appendField(Blockly.Msg.ai_basic_pressed)
- this.setOutput(true, null);
- this.setColour("#d42b03");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('button_type');
- var TOOLTIPS = {
- '0': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "A"),
- '1': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "B"),
- '2': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "C"),
- '3': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "D"),
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_v831_button_read_pressed_canvas'] = function (block) {
- var _type = block.getFieldValue('button_type');
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
- // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
- Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
- key_B = BUTTON(8)
- key_C = BUTTON(13)
- key_D = BUTTON(7)
- `
- var code = `key_${_type}.is_pressed()`
- return [code, Blockly.Python.ORDER_CONDITIONAL];
- };
- Blockly.Blocks['ai_v831_button_read_pressed'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.TOUCH_CASE)
- .appendField(new Blockly.FieldDropdown([
- ["A", "A"],
- ["B", "B"],
- ["C", "C"],
- ["D", "D"]
- ]), "button_type")
- .appendField(Blockly.Msg.ai_basic_pressed)
- this.appendStatementInput("input")
- .setCheck(null)
- .appendField(Blockly.Msg.basic_motion_statement_exec);
- // this.setOutput(true, null);
- this.setNextStatement(true);
- this.setPreviousStatement(true);
- this.setColour("#d42b03");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('button_type');
- var TOOLTIPS = {
- '0': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "A"),
- '1': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "B"),
- '2': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "C"),
- '3': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "D"),
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_v831_button_read_pressed'] = function (block) {
- var _type = block.getFieldValue('button_type');
- var statements_input = Blockly.Python.statementToCode(block, 'input');
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
- // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
- Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
- key_B = BUTTON(8)
- key_C = BUTTON(13)
- key_D = BUTTON(7)
- `
- let allBlocks = block.workspace.getAllBlocks();
- let global = ""
- try {
- global = allBlocks[0].workspace.variableList.toString()
- }
- catch (e) {
- console.log(e)
- }
- Blockly.Python.addFunction("BUTTON" + _type, `def BUTTON${_type}():
- ${global ? 'global ' + global : ""}
- ${statements_input || " pass"}\n`, true)
- var code = `if key_${_type}.is_pressed():
- BUTTON${_type}()
- `
- return code;
- };
- Blockly.Blocks['ai_v831_button_read_released'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.TOUCH_CASE)
- .appendField(new Blockly.FieldDropdown([
- ["A", "A"],
- ["B", "B"],
- ["C", "C"],
- ["D", "D"]
- ]), "button_type")
- .appendField(Blockly.Msg.ai_basic_pressed_one)
- this.appendStatementInput("input")
- .setCheck(null)
- .appendField(Blockly.Msg.basic_motion_statement_exec);
- // this.setOutput(true, null);
- this.setNextStatement(true);
- this.setPreviousStatement(true);
- this.setColour("#d42b03");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('button_type');
- var TOOLTIPS = {
- '0': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "A"),
- '1': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "B"),
- '2': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "C"),
- '3': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "D"),
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_v831_button_read_released'] = function (block) {
- var _type = block.getFieldValue('button_type');
- var statements_input = Blockly.Python.statementToCode(block, 'input');
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
- // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
- Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
- key_B = BUTTON(8)
- key_C = BUTTON(13)
- key_D = BUTTON(7)
- `
- let allBlocks = block.workspace.getAllBlocks();
- let global = ""
- try {
- global = allBlocks[0].workspace.variableList.toString()
- }
- catch (e) {
- console.log(e)
- }
- Blockly.Python.addFunction("BUTTONisPressed" + _type, `def BUTTONisPressed${_type}():
- ${global ? 'global ' + global : ""}
- ${statements_input || " pass"}\n`, true)
- var code = `if key_${_type}.is_pressed():
- while not (key_${_type}.is_pressed() == False):
- time.sleep(0.1)
- BUTTONisPressed${_type}()
- `
- return code;
- };
- Blockly.Blocks['ai_v831_button_loosen'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.TOUCH_CASE)
- .appendField(new Blockly.FieldDropdown([
- ["A", "A"],
- ["B", "B"],
- ["C", "C"],
- ["D", "D"]
- ]), "button_type")
- .appendField(Blockly.Msg.ESP32RELEASED)
- this.appendStatementInput("input")
- .setCheck(null)
- .appendField(Blockly.Msg.basic_motion_statement_exec);
- // this.setOutput(true, null);
- this.setNextStatement(true);
- this.setPreviousStatement(true);
- this.setColour("#d42b03");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('button_type');
- var TOOLTIPS = {
- '0': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "A"),
- '1': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "B"),
- '2': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "C"),
- '3': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "D"),
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_v831_button_loosen'] = function (block) {
- var _type = block.getFieldValue('button_type');
- var statements_input = Blockly.Python.statementToCode(block, 'input');
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
- // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
- Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
- key_B = BUTTON(8)
- key_C = BUTTON(13)
- key_D = BUTTON(7)
- `
- let allBlocks = block.workspace.getAllBlocks();
- let global = ""
- try {
- global = allBlocks[0].workspace.variableList.toString()
- }
- catch (e) {
- console.log(e)
- }
- Blockly.Python.addFunction("NOBUTTONisPressed" + _type, `def NOBUTTONisPressed${_type}():
- ${global ? 'global ' + global : ""}
- ${statements_input || " pass"}\n`, true)
- var code = `if key_${_type}.is_pressed() == False:
- NOBUTTONisPressed${_type}()
- `
- return code;
- };
- Blockly.Blocks['ai_v831_button_del'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_basic_button_when)
- .appendField(new Blockly.FieldDropdown([
- ["A", "A"],
- ["B", "B"],
- ["C", "C"],
- ["D", "D"]
- ]), "button_type_released")
- .appendField(Blockly.Msg.ai_basic_released)
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#d42b03");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('button_type_released');
- var TOOLTIPS = {
- '0': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "A"),
- '1': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "B"),
- '2': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "C"),
- '3': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "D"),
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_v831_button_del'] = function (block) {
- var _type = block.getFieldValue('button_type_released');
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
- // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
- Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
- key_B = BUTTON(8)
- key_C = BUTTON(13)
- key_D = BUTTON(7)
- `
- var code = `key_${_type}.button.release()
- del key_${_type}
- `
- return code;
- };
- Blockly.Blocks['ai_v831_led_light_up'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_basic_led_set)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_basic_led_blue, "blue"],
- // [Blockly.Msg.ai_basic_led_red, "red"]
- ]), "type")
- .appendField(Blockly.Msg.ai_basic_led_on);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#d42b03");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('type');
- var TOOLTIPS = {
- 'blue': Blockly.Msg.ai_k210_led_light_up_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_blue),
- 'red': Blockly.Msg.ai_k210_led_light_up_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_red)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_v831_led_light_up'] = function (block) {
- var dropdown_type = block.getFieldValue('type');
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.definitions_['v831_import_smbus2'] = `import smbus2`
- Blockly.Python.definitions_['v831_import_time'] = `import time`
- Blockly.Python.definitions_['v831_import_CocoPi_LED'] = `from CocoPi import LED
- LED = LED()
- `
- // TODO: Assemble Python into code variable.
- var code = `LED.out(1)
- `;
- return code;
- };
- Blockly.Blocks['ai_v831_led_light_off'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_basic_led_set)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_basic_led_blue, "blue"],
- // [Blockly.Msg.ai_basic_led_red, "red"]
- ]), "type")
- .appendField(Blockly.Msg.ai_basic_led_off);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#d42b03");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('type');
- var TOOLTIPS = {
- 'blue': Blockly.Msg.ai_k210_led_light_off_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_blue),
- 'red': Blockly.Msg.ai_k210_led_light_off_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_red)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_v831_led_light_off'] = function (block) {
- var dropdown_type = block.getFieldValue('type');
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.definitions_['v831_import_smbus2'] = `import smbus2`
- Blockly.Python.definitions_['v831_import_time'] = `import time`
- Blockly.Python.definitions_['v831_import_CocoPi_LED'] = `from CocoPi import LED
- LED = LED()
- `
- // TODO: Assemble Python into code variable.
- var code = `LED.out(0)
- `;
- return code;
- };
- Blockly.Blocks['ai_v831_rgb_light_up'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_basic_rgb_set_on)
- this.appendValueInput("rgb_value")
- .setCheck(null)
- .appendField("");
- this.appendDummyInput()
- .appendField(Blockly.Msg.LED_BRTN).appendField(new Blockly.FieldNumber(50, 0, 255), "uart_bps");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#d42b03");
- this.setTooltip(Blockly.Msg.ai_basic_rgb_set_on);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_v831_rgb_light_up'] = function (block) {
- var value_name = Blockly.Python.valueToCode(block, 'rgb_value', Blockly.Python.ORDER_ATOMIC);
- var content = block.getFieldValue('uart_bps');
- console.log(value_name.slice(1, -1))
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.definitions_['v831_import_smbus2'] = `import smbus2`
- Blockly.Python.definitions_['v831_import_time'] = `import time`
- Blockly.Python.definitions_['v831_import_CocoPi_RGB'] = `from CocoPi import singleRgb
- singleRgb=singleRgb()`;
- var code = `singleRgb.setBrightness(${content})
- singleRgb.setColor(${value_name.slice(1, -1)})
- time.sleep(0.05)
- singleRgb.show()
- `;
- return code;
- };
- Blockly.Blocks['ai_v831_rgb_light_off'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_basic_rgb_set_off)
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#d42b03");
- this.setTooltip(Blockly.Msg.ai_basic_rgb_set_off);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_v831_rgb_light_off'] = function (block) {
- var dropdown_type = block.getFieldValue('type');
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.definitions_['v831_import_smbus2'] = `import smbus2`
- Blockly.Python.definitions_['v831_import_time'] = `import time`
- Blockly.Python.definitions_['v831_import_CocoPi_RGB'] = `from CocoPi import singleRgb
- singleRgb=singleRgb()`;
- // TODO: Assemble Python into code variable.
- var code = `singleRgb.setColor(0,0,0)
- time.sleep(0.05)
- singleRgb.show()
- `;
- return code;
- };
- Blockly.Blocks['ai_basic_light_up_led_analog'] = {
- init: function () {
- this.appendValueInput("brightness")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_basic_led_analog_set)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_basic_led_analog_led1, "1"],
- [Blockly.Msg.ai_basic_led_analog_led2, "2"]
- ]), "type")
- .appendField(Blockly.Msg.ai_basic_led_analog_brightness_text);
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_basic_led_analog_range_text);
- this.setInputsInline(true);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#d42b03");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('type');
- var TOOLTIPS = {
- '1': Blockly.Msg.ai_basic_light_up_led_analog_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_analog_led1),
- '2': Blockly.Msg.ai_basic_light_up_led_analog_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_analog_led2)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_basic_light_up_led_analog'] = function (block) {
- var dropdown_type = block.getFieldValue('type');
- var value_brightness = Blockly.Python.valueToCode(block, 'brightness', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_['v831_import_time'] = `import time`
- Blockly.Python.definitions_['ai_basic_light_up_led_analog_def'] = '' +
- 'from machine import Timer,PWM\n' +
- '\n' +
- 'led_left_tim = Timer(Timer.TIMER2, Timer.CHANNEL0, mode=Timer.MODE_PWM)\n' +
- 'led_right_tim = Timer(Timer.TIMER2, Timer.CHANNEL1, mode=Timer.MODE_PWM)\n' +
- 'led_left_ctrl = PWM(led_left_tim, freq=500000, duty=50, pin=31)\n' +
- 'led_right_ctrl = PWM(led_right_tim, freq=500000, duty=50, pin=32)\n' +
- '\n' +
- 'def analog_light(which, brightness):\n' +
- ' if which == 1:\n' +
- ' led_left_ctrl.duty(brightness)\n' +
- ' if which == 2:\n' +
- ' led_right_ctrl.duty(brightness)\n' +
- '';
- // TODO: Assemble Python into code variable.
- var code = 'analog_light(' + dropdown_type + ',' + value_brightness + ')\n';
- return code;
- };
- /*
- _ ___ ___ ____
- / \ |_ _| |_ _|_ __ ___ __ _ __ _ ___ | _ \ _ __ ___ ___ ___ ___ ___
- / _ \ | | | || '_ ` _ \ / _` |/ _` |/ _ \ | |_) | '__/ _ \ / __/ _ \/ __/ __|
- / ___ \ | | | || | | | | | (_| | (_| | __/ | __/| | | (_) | (_| __/\__ \__ \
- /_/ \_\___| |___|_| |_| |_|\__,_|\__, |\___| |_| |_| \___/ \___\___||___/___/
- |___/
- */
- Blockly.Blocks["ai_lcd_screeninit"] = {
- init: function () {
- // this.appendDummyInput()
- // .appendField(new Blockly.FieldImage("blockly/media/screen_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.image_process_lcd_init);
- this.appendDummyInput().appendField(Blockly.Msg.image_process_lcd_direction)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.image_process_lcd_landscape_screen, "False"],
- [Blockly.Msg.image_process_lcd_vertical_screen, "True"]
- ]), "isScreen")
- this.setInputsInline(false);
- this.setPreviousStatement(true);
- this.setNextStatement(true);
- this.setColour("#5cb2d6");
- this.setTooltip(Blockly.Msg.ai_lcd_screeninit_TOOLTIP);
- this.setHelpUrl('');
- }
- }
- Blockly.Python.ai_lcd_screeninit = function (block) {
- var isScreen = block.getFieldValue('isScreen');
- Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
- Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
- Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- // Blockly.Python.addVariable("ScreenOrientation", `ScreenOrientation = ${isScreen}`, false)
- Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
- def CAMERATYPE():
- global cameraSize
- try:
- if os.path.exists("/etc/cameraSize.cfg"):
- cameraSize = True
- else:
- cameraSize = False
- except:
- cameraSize = False
- CAMERATYPE()
- `
- Blockly.Python.definitions_['v831_camera_set_ScreenOrientation'] = `ScreenOrientation = ${isScreen}`
- var _code = ``;
- return _code;;
- }
- Blockly.Blocks['ai_lcd_rotation'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.LCD_CANVAS + Blockly.Msg.image_process_set_lcd_rotation)
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- // .appendField()
- .appendField(new Blockly.FieldDropdown([
- ["0°", "0"],
- ["90°", "90"],
- ["180°", "180"],
- ["270°", "270"]
- ]), "DEGREE")
- .appendField(Blockly.Msg.CATEGORY_SHOW)
- this.setInputsInline(true);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#5bb2d6");
- this.setTooltip(Blockly.Msg.ai_lcd_rotation_TOOLTIP);
- this.setHelpUrl('');
- }
- }
- Blockly.Python.ai_lcd_rotation = function (block) {
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var dropdown_name = block.getFieldValue('DEGREE');
- Blockly.Python.addFunction('v831_rotation_fun', `def screenShow(inputImg,rotationAngle):
- if rotationAngle==90 or rotationAngle == 270:
- screenCapture=inputImg.crop(0,0,240,320)
- else:
- screenCapture=inputImg.crop(0,0,320,240)
- canvas_screenShow = screenCapture.rotate(-rotationAngle,adjust=1)
- display.show(canvas_screenShow)
- `)
- let w = ''
- let h = ''
- if (dropdown_name == 90 || dropdown_name == 270) {
- w = 240
- h = 320
- } else {
- w = 320
- h = 240
- }
- var _code = `screenShow(canvas,${dropdown_name})
- `;
- return _code;;
- }
- Blockly.Blocks['ai_lcd_font'] = {
- init: function () {
- this.appendDummyInput().appendField(Blockly.Msg.image_lcd_set_font)
- this.appendValueInput("save_path")
- .setCheck(null)
- this.setInputsInline(true);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#5bb2d6");
- this.setTooltip(Blockly.Msg.image_lcd_set_font);
- this.setHelpUrl('');
- }
- }
- Blockly.Python.ai_lcd_font = function (block) {
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var font_path = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC);
- var _code = `image.load_freetype(${font_path})\n`;
- return _code;;
- }
- Blockly.Blocks['ai_lcd_filp'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_set_lcd_mirror_flip)
- .appendField(new Blockly.FieldCheckbox('TRUE'), 'TextCheckBox');
- this.setInputsInline(true);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#5bb2d6");
- this.setTooltip(Blockly.Msg.ai_lcd_filp_TOOLTIP);
- this.setHelpUrl('');
- }
- }
- Blockly.Python.ai_lcd_filp = function (block) {
- var _tf = block.getFieldValue('TextCheckBox') == 'TRUE' ? "True" : "False";
- var _code = "lcd.mirror(" + _tf + ")\n";
- return _code;
- }
- Blockly.Blocks['ai_lcd_screen'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_set_filled_screen_color)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.image_process_set_filled_screen_color_red, "RED"],
- [Blockly.Msg.image_process_set_filled_screen_color_green, "GREEN"],
- [Blockly.Msg.image_process_set_filled_screen_color_blue, "BLUE"],
- [Blockly.Msg.image_process_set_filled_screen_color_purple, "PURPLE"],
- [Blockly.Msg.image_process_set_filled_screen_color_cyan, "CYAN"],
- [Blockly.Msg.image_process_set_filled_screen_color_orange, "ORANGE"],
- [Blockly.Msg.image_process_set_filled_screen_color_yellow, "YELLOW"],
- [Blockly.Msg.image_process_set_filled_screen_color_black, "BLACK"],
- [Blockly.Msg.image_process_set_filled_screen_color_white, "WHITE"]
- ]), "COLOR");
- this.setInputsInline(true);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#5bb2d6");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('COLOR');
- var TOOLTIPS = {
- 'RED': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_red),
- 'GREEN': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_green),
- 'BLUE': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_blue),
- 'PURPLE': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_purple),
- 'CYAN': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_cyan),
- 'ORANGE': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_orange),
- 'YELLOW': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_yellow),
- 'BLACK': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_black),
- 'WHITE': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_white)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_lcd_screen = function (block) {
- var colour_name = block.getFieldValue('COLOR');
- var _code = "lcd.clear(lcd." + colour_name + ")\n";
- return _code;
- }
- Blockly.Blocks['ai_lcd_fill_screen_with_rgb'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_text_let_canvas)
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- .appendField(Blockly.Msg.image_process_text_let_canvas_filled_with_color);
- this.appendValueInput("rgb_value")
- .setCheck(null)
- .appendField("");
- this.setInputsInline(true);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#5bb2d6");
- this.setTooltip(Blockly.Msg.ai_lcd_fill_screen_with_rgb_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_lcd_fill_screen_with_rgb'] = function (block) {
- var value_name = Blockly.Python.valueToCode(block, 'rgb_value', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- if (value_name.charAt(0) == '#') {
- var d = 0,
- e = 0,
- f = 0;
- try {
- 7 == value_name.length && (d = parseInt(value_name.substring(1, 3), 16),
- e = parseInt(value_name.substring(3, 5), 16),
- f = parseInt(value_name.substring(5, 7), 16))
- } catch (g) { }
- // TODO: Assemble Python into code variable.
- value_name = "(" + d + "," + e + "," + f + ")";
- }
- var code = `try:
- if ScreenOrientation:
- canvas = image.new(size = (240, 320), color = ${value_name}, mode = "RGB")
- else:
- canvas = image.new(size = (320, 240), color = ${value_name}, mode = "RGB")
- except:
- canvas = image.new(size = (320, 240), color = ${value_name}, mode = "RGB")
- `;
- return code;
- };
- Blockly.Blocks['ai_lcd_clear'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_clear_lcd);
- this.setInputsInline(true);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#5bb2d6");
- this.setTooltip(Blockly.Msg.ai_lcd_clear_TOOLTIP);
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_lcd_clear = function (block) {
- var _code = "lcd.clear(lcd.BLACK)\n";
- return _code;
- }
- Blockly.Blocks['ai_lcd_rgb_value_input'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_rgb_r);
- this.appendValueInput("rgb_value_r")
- .setCheck(null)
- .appendField("");
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_rgb_g);
- this.appendValueInput("rgb_value_g")
- .setCheck(null)
- .appendField("");
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_rgb_b);
- this.appendValueInput("rgb_value_b")
- .setCheck(null)
- .appendField("");
- this.setInputsInline(true);
- this.setOutput(true, null);
- this.setColour("#5bb2d6");
- this.setTooltip(Blockly.Msg.ai_lcd_rgb_value_input_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_lcd_rgb_value_input'] = function (block) {
- var value_rgb_value_r = Blockly.Python.valueToCode(block, 'rgb_value_r', Blockly.Python.ORDER_ATOMIC);
- var value_rgb_value_g = Blockly.Python.valueToCode(block, 'rgb_value_g', Blockly.Python.ORDER_ATOMIC);
- var value_rgb_value_b = Blockly.Python.valueToCode(block, 'rgb_value_b', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- var code = '' + value_rgb_value_r + ',' + value_rgb_value_g + ',' + value_rgb_value_b + '';
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks.ai_lcd_XY = {
- init: function () {
- var _input = this.appendDummyInput();
- this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL);
- this.setTooltip(Blockly.Msg.ai_lcd_XY_TOOLTIP);
- this.setColour("#5bb2d6");
- this.setOutput(!0, "Boolean");
- _input.appendField(Blockly.Msg.image_process_xy_x);
- this.appendValueInput("A").setCheck("Number");
- _input = this.appendDummyInput();
- _input.appendField(Blockly.Msg.image_process_xy_y)
- this.appendValueInput("B").setCheck("Number");
- this.setInputsInline(!0);
- }
- };
- Blockly.Python.ai_lcd_XY = function (block) {
- var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
- var _y = Blockly.Python.valueToCode(block, "B", Blockly.Python.ORDER_ATOMIC);
- var code = "" + _x + ", " + _y + "";
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks.ai_lcd_WH = {
- init: function () {
- var _input = this.appendDummyInput();
- this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL);
- this.setTooltip(Blockly.Msg.ai_lcd_WH_TOOLTIP);
- this.setColour("#5bb2d6");
- this.setOutput(!0, "Boolean");
- _input.appendField(Blockly.Msg.image_process_wh_width);
- this.appendValueInput("A").setCheck("Number");
- _input = this.appendDummyInput();
- _input.appendField(Blockly.Msg.image_process_wh_height)
- this.appendValueInput("B").setCheck("Number");
- this.setInputsInline(!0);
- }
- };
- Blockly.Python.ai_lcd_WH = function (block) {
- var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
- var _y = Blockly.Python.valueToCode(block, "B", Blockly.Python.ORDER_ATOMIC);
- var code = "" + _x + ", " + _y + "";
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks['ai_lcd_colortext'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_text.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_lcd_show_text);
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_lcd_show_text_color)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.image_process_lcd_show_text_color_white, "WHITE"],
- [Blockly.Msg.image_process_lcd_show_text_color_black, "BLACK"],
- [Blockly.Msg.image_process_lcd_show_text_color_red, "RED"],
- [Blockly.Msg.image_process_lcd_show_text_color_green, "GREEN"],
- [Blockly.Msg.image_process_lcd_show_text_color_blue, "BLUE"],
- [Blockly.Msg.image_process_lcd_show_text_color_purple, "PURPLE"],
- [Blockly.Msg.image_process_lcd_show_text_color_cyan, "CYAN"],
- [Blockly.Msg.image_process_lcd_show_text_color_orange, "ORANGE"],
- [Blockly.Msg.image_process_lcd_show_text_color_yellow, "YELLOW"]
- ]), "COLOR");
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_lcd_show_text_bg_color)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.image_process_lcd_show_text_color_black, "BLACK"],
- [Blockly.Msg.image_process_lcd_show_text_color_white, "WHITE"],
- [Blockly.Msg.image_process_lcd_show_text_color_red, "RED"],
- [Blockly.Msg.image_process_lcd_show_text_color_green, "GREEN"],
- [Blockly.Msg.image_process_lcd_show_text_color_blue, "BLUE"],
- [Blockly.Msg.image_process_lcd_show_text_color_purple, "PURPLE"],
- [Blockly.Msg.image_process_lcd_show_text_color_cyan, "CYAN"],
- [Blockly.Msg.image_process_lcd_show_text_color_orange, "ORANGE"],
- [Blockly.Msg.image_process_lcd_show_text_color_yellow, "YELLOW"]
- ]), "BCOLOR");
- this.appendValueInput("CONTENT")
- .setCheck("String")
- .appendField(Blockly.Msg.image_process_text_content);
- /* this.appendDummyInput()
- .appendField(Blockly.Msg.LCDDT); */
- this.appendValueInput("POSA")
- .setCheck("String")
- .appendField(Blockly.Msg.image_process_text_start_coord);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#5bb2d6");
- this.setTooltip('');
- this.setHelpUrl('');
- }
- };
- Blockly.Python['ai_lcd_colortext'] = function (block) {
- var color = block.getFieldValue("COLOR");
- var bcolor = block.getFieldValue("BCOLOR");
- var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
- var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
- //var size = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
- var _code = "lcd_draw_string(lcd," + xy + ", " + content + ", color=" + color + ")\n"; //, scale=" + size + "
- // return [_code, Blockly.Python.ORDER_ATOMIC]
- return _code;
- };
- Blockly.Blocks["ai_lcd_createnonecarvas"] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_create_blank_canvas)
- .appendField(new Blockly.FieldVariable("canvas"), "varitem");
- this.appendValueInput("wh")
- .setCheck(null)
- .appendField(Blockly.Msg.image_process_text_size);
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.LCDDCC_F)
- // .appendField(new Blockly.FieldCheckbox("TRUE"), "check")
- // .appendField(Blockly.Msg.LCDDCC_I)
- // .appendField(new Blockly.FieldTextInput(""), "text");
- this.setInputsInline(true);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#5cb2d6");
- this.setTooltip(Blockly.Msg.ai_lcd_createnonecarvas_TOOLTIP);
- this.setHelpUrl('');
- }
- }
- Blockly.Python.ai_lcd_createnonecarvas = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var value_wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
- var _code = variable_name + " = image.new(size = (" + value_wh + "))\n";
- return _code;
- }
- Blockly.Blocks["ai_lcd_fillcanvas"] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_text_let_canvas)
- .appendField(new Blockly.FieldVariable("canvas"), "varitem");
- this.appendValueInput("color")
- .setCheck(null)
- .appendField(Blockly.Msg.image_process_text_let_canvas_filled_with_color);
- this.setInputsInline(true);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#5cb2d6");
- this.setTooltip(Blockly.Msg.ai_lcd_fillcanvas_TOOLTIP);
- this.setHelpUrl('');
- }
- }
- Blockly.Python.ai_lcd_fillcanvas = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var value_color = Blockly.Python.valueToCode(block, 'color', Blockly.Python.ORDER_ATOMIC);
- var _code = variable_name + '.draw_rectangle(0,0, ' + variable_name + '.width(),' + variable_name + '.height(), color=' + value_color + ', thickness=1, fill=True)\n';
- return _code;
- }
- Blockly.Blocks["ai_lcd_createcarvas"] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_create_image_canvas)
- .appendField(new Blockly.FieldVariable("canvas"), "varitem");
- this.appendValueInput("path").setCheck(null).appendField(Blockly.Msg.image_process_create_image_canvas_path);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- // this.setInputsInline(true);
- this.setColour("#5cb2d6");
- this.setTooltip(Blockly.Msg.ai_lcd_createcarvas_TOOLTIP);
- this.setHelpUrl('');
- }
- }
- Blockly.Python.ai_lcd_createcarvas = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- // var checkbox_name = block.getFieldValue('check') == 'TRUE' ? "True" : "False";
- var text_name = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
- var _code = variable_name + " = image.open(" + text_name + ")\n";
- return _code;
- }
- Blockly.Blocks['ai_lcd_showcarvas_set_cord'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_text_set_canvas_setup)
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem");
- this.appendValueInput("xy")
- .setCheck(null)
- .appendField(Blockly.Msg.image_process_text_start_coord_as);
- this.setInputsInline(true);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#5cb2d6");
- this.setTooltip(Blockly.Msg.ai_lcd_showcarvas_set_cord_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_lcd_showcarvas_set_cord = function (block) {
- var value_name = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- var code = "_canvas_x, _canvas_y = " + value_name + "\n";
- return code;
- };
- Blockly.Blocks['ai_lcd_showcarvas_set_display'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_show_canvas)
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem");
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#5cb2d6");
- this.setTooltip(Blockly.Msg.ai_lcd_showcarvas_set_display_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_lcd_showcarvas_set_display = function (block) {
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- Blockly.Python.definitions_['v831_import_mjpg'] = `from maix import mjpg`
- Blockly.Python.definitions_['v831_import_utils'] = `from maix import utils`
- Blockly.Python.definitions_['v831_import_base64'] = `import base64`
- Blockly.Python.definitions_['v831_import_time'] = `import time`
- Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
- Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
- Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
- Blockly.Python.addVariable(`_canvas_x`, `_canvas_x = 0`, true)
- Blockly.Python.addVariable(`_canvas_y`, `_canvas_y = 0`, true)
- Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
- def CAMERATYPE():
- global cameraSize
- try:
- if os.path.exists("/etc/cameraSize.cfg"):
- cameraSize = True
- else:
- cameraSize = False
- except:
- cameraSize = False
- CAMERATYPE()
- `
- Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf")
- if cameraSize==True:
- camera.camera.config(size=(320,240))
- else:
- camera.camera.config(size=(240,320))
- try:
- if ScreenOrientation==True:
- canvas = image.new(size = (240, 320))
- else:
- canvas = image.new(size = (320, 240))
- except:
- canvas = image.new(size = (320, 240))
- ScreenOrientation = False
- `
- Blockly.Python.definitions_[`v831_display_show_canvas`] = `def v831_display_show_canvas(displayShow,_canvas_x,_canvas_y):
- global ScreenOrientation,cameraSize
- try:
- if ScreenOrientation:
- displayShowCanvas = image.new(size = (240, 320))
- displayShowCanvas.draw_rectangle(0,0,240,320, color=(0,0,0), thickness=-1)
- displayShowCanvas.draw_image(displayShow,_canvas_x,_canvas_y,alpha=1)
- displayShowVER = displayShowCanvas.crop(0,0,240,320)
- displayShowVER = displayShowVER.rotate(-90, adjust=1)
- display.show(displayShowVER)
- else:
- displayShowCanvas = image.new(size = (320, 240))
- displayShowCanvas.draw_rectangle(0,0,320,240, color=(0,0,0), thickness=-1)
- displayShowCanvas.draw_image(displayShow,_canvas_x,_canvas_y,alpha=1)
- display.show(displayShowCanvas)
- except:
- displayShowCanvas = image.new(size = (320, 240))
- displayShowCanvas.draw_rectangle(0,0,320,240, color=(0,0,0), thickness=-1)
- displayShowCanvas.draw_image(displayShow,_canvas_x,_canvas_y,alpha=1)
- display.show(displayShowCanvas)
-
- `
- var code = `v831_display_show_canvas(canvas,_canvas_x,_canvas_y)
- `;
- return code;
- };
- Blockly.Blocks['ai_lcd_showcarvas'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_show_canvas)
- .appendField(new Blockly.FieldVariable("canvas"), "varitem");
- this.appendValueInput("xy")
- .setCheck(null)
- .appendField(Blockly.Msg.image_process_text_start_coord);
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#5cb2d6");
- this.setTooltip("");
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_lcd_showcarvas = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var value_name = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- var code = "lcd.display(" + variable_name + ", oft=(" + value_name + "))\n";
- return code;
- };
- Blockly.Blocks['ai_lcd_clearcanvas'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_clear_canvas_1 + Blockly.Msg.image_process_clear_canvas_2)
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#5bb2d6");
- this.setTooltip(Blockly.Msg.ai_lcd_clearcanvas_TOOLTIP);
- this.setHelpUrl('');
- }
- }
- Blockly.Python.ai_lcd_clearcanvas = function (block) {
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var _code = "canvas.clear()\n";
- return _code;;
- }
- Blockly.Blocks['lcd_set_position'] = {
- init: function () {
- this.appendValueInput("POSX")
- .setCheck("Number")
- .appendField("X:");
- this.appendValueInput("POSY")
- .setCheck("Number")
- .appendField("Y:");
- this.setOutput(true, "String");
- this.setInputsInline(true);
- this.setColour("#5bb2d6");
- this.setTooltip("");
- this.setHelpUrl("");
- }
- };
- Blockly.Python['lcd_set_position'] = function (block) {
- // var reg = /^?[0-9]\d*$/
- var pos_x = Blockly.Python.valueToCode(block, 'POSX', Blockly.Python.ORDER_ATOMIC);
- var pos_y = Blockly.Python.valueToCode(block, 'POSY', Blockly.Python.ORDER_ATOMIC);
- //var code = posConvert(pos_x, pos_y);
- var code = pos_x + "," + pos_y;
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks['lcd_set_color'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.COLOR)
- .appendField(new Blockly.FieldColour("#ff0000"), "COLOR");
- this.setOutput(true, "String");
- this.setColour("#5bb2d6");
- this.setTooltip("");
- this.setHelpUrl("");
- }
- };
- Blockly.Python['lcd_set_color'] = function (block) {
- var code = block.getFieldValue('COLOR');
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks['lcd_set_width_height'] = {
- init: function () {
- this.appendValueInput("WIDTH")
- .setCheck("Number")
- .appendField(Blockly.Msg.OLCD_WIDTH);
- this.appendValueInput("HEIGHT")
- .setCheck("Number")
- .appendField(Blockly.Msg.OLCD_HEIGHT);
- this.setOutput(true, "String");
- this.setInputsInline(true);
- this.setColour("#5bb2d6");
- this.setTooltip("");
- this.setHelpUrl("");
- }
- };
- Blockly.Python['lcd_set_width_height'] = function (block) {
- var width = Blockly.Python.valueToCode(block, 'WIDTH', Blockly.Python.ORDER_ATOMIC);
- var height = Blockly.Python.valueToCode(block, 'HEIGHT', Blockly.Python.ORDER_ATOMIC);
- var code = width + ', ' + height;
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- // ai_lcd_textcarvas_new_line
- Blockly.Blocks['ai_lcd_textcarvas_new_line'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_text.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_text_on_canvas + Blockly.Msg.image_process_text_on_draw + Blockly.Msg.image_process_draw_text)
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- // .appendField();
- this.appendValueInput("POSA")
- .setCheck("String")
- .appendField(Blockly.Msg.image_process_text_start_coord);
- this.appendValueInput("CONTENT")
- .setCheck("String")
- .appendField(Blockly.Msg.image_process_text_content);
- this.appendValueInput("dispalyStr")
- .setCheck("Number")
- .appendField(Blockly.Msg.image_process_text_dispalyStr);
- this.appendValueInput("buttonUp")
- .setCheck("String")
- .appendField(Blockly.Msg.image_process_text_buttonDown);
- this.appendValueInput("buttonDown")
- .setCheck("String")
- .appendField(Blockly.Msg.image_process_text_buttonUp);
- this.appendValueInput("COLOR")
- .setCheck("String")
- .appendField(Blockly.Msg.image_process_text_color);
- this.appendValueInput("Scale")
- .setCheck("Number")
- .appendField(Blockly.Msg.image_process_draw_text_font_size);
- this.appendValueInput("LineNum")
- .setCheck("Number")
- .appendField(Blockly.Msg.image_process_text_line_heigit);
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.image_process_draw_text_if_monospace)
- // .appendField(new Blockly.FieldCheckbox("FALSE"), "bool");
- this.setInputsInline(false);
- this.setPreviousStatement(true);
- this.setNextStatement(true);
- this.setColour("#5bb2d6");
- this.setTooltip(Blockly.Msg.ai_lcd_textcarvas_TOOLTIP);
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_lcd_textcarvas_new_line = function (block) {
- var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
- var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
- var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
- var scale = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
- var LineNum = Blockly.Python.valueToCode(block, 'LineNum', Blockly.Python.ORDER_ATOMIC);
- var dispalyStr = Blockly.Python.valueToCode(block, 'dispalyStr', Blockly.Python.ORDER_ATOMIC);
- var buttonUp = Blockly.Python.valueToCode(block, 'buttonUp', Blockly.Python.ORDER_ATOMIC);
- var buttonDown = Blockly.Python.valueToCode(block, 'buttonDown', Blockly.Python.ORDER_ATOMIC);
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
- Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
- Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
- def CAMERATYPE():
- global cameraSize
- try:
- if os.path.exists("/etc/cameraSize.cfg"):
- cameraSize = True
- else:
- cameraSize = False
- except:
- cameraSize = False
- CAMERATYPE()
- `
- Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf")
- if cameraSize==True:
- camera.camera.config(size=(320,240))
- else:
- camera.camera.config(size=(240,320))
- try:
- if ScreenOrientation==True:
- canvas = image.new(size = (240, 320))
- else:
- canvas = image.new(size = (320, 240))
- except:
- canvas = image.new(size = (320, 240))
- ScreenOrientation = False
- `
- var _code = ""
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
- // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
- Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
- key_B = BUTTON(8)
- key_C = BUTTON(13)
- key_D = BUTTON(7)`
- Blockly.Python.definitions_["ai_lcd_textcarvas_new_line"] = `BUTTONNUMBER = 0
- def textCanvasNewLine(canvasName,posax,posay,text,Num,buttonUp,buttonDown,Scale,Color,LineNum):
- global BUTTONNUMBER,ScreenOrientation
- numText = len(text)//Num + 1
- lineHeight = 240
- if ScreenOrientation:
- lineHeight = 320
- if numText>(lineHeight//LineNum):
- if buttonUp:
- time.sleep(0.1)
- if BUTTONNUMBER<int(numText-(lineHeight//LineNum))+ int(posay/LineNum):
- BUTTONNUMBER = BUTTONNUMBER + 1
- elif buttonDown:
- time.sleep(0.1)
- if BUTTONNUMBER>0:
- BUTTONNUMBER = BUTTONNUMBER - 1
- #BUTTONNUMBER = BUTTONNUMBER + (posay/LineNum)
- for i in range(numText):
- canvasName.draw_string(posax,posay+int(i*LineNum),text[int((i+BUTTONNUMBER)*Num):int((i+1+BUTTONNUMBER)*Num)], scale = Scale, color = Color, thickness = 1)
-
- # canvasName.draw_string(posax,posay,str(text), scale = Scale, color = Color, thickness = 1)
- `
- if (color.charAt(0) == '#') {
- var d = 0,
- e = 0,
- f = 0;
- try {
- 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
- e = parseInt(color.substring(3, 5), 16),
- f = parseInt(color.substring(5, 7), 16))
- } catch (g) { }
- var bool = "False";
- // var bool = block.getFieldValue('bool') == "TRUE" ? "True" : "False";
- // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False";
- // color=(" + d + "," + e + "," + f + ")" + ", font_size=" + size + ")\n"
- _code = `textCanvasNewLine(canvas,${xy},${content},${dispalyStr},${buttonUp},${buttonDown},${scale},(${d} ,${e}, ${f}),${LineNum})\n`
- // _code = variable_name + '.draw_string(' + xy + ', ' + content + ', scale = ' + scale + ', color = (' + d + ',' + e + ',' + f + ') , thickness = 1)\n'; // #在红色画布上写下hello world
- } else if (color.charAt(0) != '#') {
- var d = 0,
- e = 0,
- f = 0;
- try {
- 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
- e = parseInt(color.substring(3, 5), 16),
- f = parseInt(color.substring(5, 7), 16))
- } catch (g) { }
- _code = `textCanvasNewLine(canvas,${xy},${content},${dispalyStr},${buttonUp},${buttonDown},${scale},${color},${LineNum})\n`
- // _code = variable_name + '.draw_string(' + xy + ', ' + content + ', scale = ' + scale + ', color = ' + color + ', thickness = 1)\n' + // #在红色画布上写下hello world
- // '';
- }
- return _code;
- }
- Blockly.Blocks['ai_lcd_textcarvas'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_text.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_text_on_canvas + Blockly.Msg.image_process_text_on_draw + Blockly.Msg.image_process_draw_text)
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- this.appendValueInput("POSA")
- .setCheck("String")
- .appendField(Blockly.Msg.image_process_text_start_coord);
- this.appendValueInput("CONTENT")
- .setCheck("String")
- .appendField(Blockly.Msg.image_process_text_content);
- this.appendValueInput("COLOR")
- .setCheck("String")
- .appendField(Blockly.Msg.image_process_text_color);
- this.appendValueInput("Scale")
- .setCheck("Number")
- .appendField(Blockly.Msg.image_process_draw_text_font_size);
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.image_process_draw_text_if_monospace)
- // .appendField(new Blockly.FieldCheckbox("FALSE"), "bool");
- this.setInputsInline(false);
- this.setPreviousStatement(true);
- this.setNextStatement(true);
- this.setColour("#5bb2d6");
- this.setTooltip(Blockly.Msg.ai_lcd_textcarvas_TOOLTIP);
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_lcd_textcarvas = function (block) {
- var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
- Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
- Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
- def CAMERATYPE():
- global cameraSize
- try:
- if os.path.exists("/etc/cameraSize.cfg"):
- cameraSize = True
- else:
- cameraSize = False
- except:
- cameraSize = False
- CAMERATYPE()
- `
- Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf")
- if cameraSize==True:
- camera.camera.config(size=(320,240))
- else:
- camera.camera.config(size=(240,320))
- try:
- if ScreenOrientation==True:
- canvas = image.new(size = (240, 320))
- else:
- canvas = image.new(size = (320, 240))
- except:
- canvas = image.new(size = (320, 240))
- ScreenOrientation = False
- `
- var _code = ""
- if (color.charAt(0) == '#') {
- var d = 0,
- e = 0,
- f = 0;
- try {
- 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
- e = parseInt(color.substring(3, 5), 16),
- f = parseInt(color.substring(5, 7), 16))
- } catch (g) { }
- var bool = "False";
- // var bool = block.getFieldValue('bool') == "TRUE" ? "True" : "False";
- // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False";
- var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
- var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
- var scale = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
- // color=(" + d + "," + e + "," + f + ")" + ", font_size=" + size + ")\n"
- _code = 'canvas.draw_string(' + xy + ', ' + content + ', scale = ' + scale + ', color = (' + d + ',' + e + ',' + f + ') , thickness = 1)\n'; // #在红色画布上写下hello world
- } else if (color.charAt(0) != '#') {
- var d = 0,
- e = 0,
- f = 0;
- try {
- 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
- e = parseInt(color.substring(3, 5), 16),
- f = parseInt(color.substring(5, 7), 16))
- } catch (g) { }
- var bool = "False";
- // var bool = block.getFieldValue('bool') == "TRUE" ? "True" : "False";
- // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False";
- var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
- var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
- var scale = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
- _code = 'canvas.draw_string(' + xy + ', ' + content + ', scale = ' + scale + ', color = ' + color + ', thickness = 1)\n' + // #在红色画布上写下hello world
- '';
- }
- return _code;
- }
- Blockly.Blocks['ai_lcd_characterscarvas'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_hanzi_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_text_on_canvas)
- .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- .appendField(Blockly.Msg.image_process_text_on_draw + Blockly.Msg.image_process_draw_characters);
- this.appendValueInput("POSA")
- .setCheck("String")
- .appendField(Blockly.Msg.image_process_text_start_coord);
- this.appendValueInput("CONTENT")
- .setCheck("String")
- .appendField(Blockly.Msg.image_process_text_content);
- this.appendValueInput("COLOR")
- .setCheck("String")
- .appendField(Blockly.Msg.image_process_text_color);
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_draw_text_font_size + ":")
- // .setCheck(null)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.SMALL, "1"],
- [Blockly.Msg.MIDDLE, "2"],
- [Blockly.Msg.LARGE, "3"]
- ]), "fonts");
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.Set_Auto_Wrap + ":")
- // // .setCheck(null)
- // .appendField(new Blockly.FieldDropdown([
- // [Blockly.Msg.LED_SCROLL_YES, "True"],
- // [Blockly.Msg.LED_SCROLL_NO, "False"]
- // ]), "wraps");
- this.setInputsInline(false);
- this.setPreviousStatement(true);
- this.setNextStatement(true);
- this.setColour("#5bb2d6");
- this.setTooltip(Blockly.Msg.ai_lcd_characterscarvas_TOOLTIP);
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_lcd_characterscarvas = function (block) {
- var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
- var _code = ''
- if (color.charAt(0) == '#') {
- var d = 0,
- e = 0,
- f = 0;
- try {
- 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
- e = parseInt(color.substring(3, 5), 16),
- f = parseInt(color.substring(5, 7), 16))
- } catch (g) { }
- // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False";
- var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
- var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
- var size = block.getFieldValue('fonts');;
- // var wraps = block.getFieldValue('wraps');
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- _code = "lcd_draw_string(" + variable_name + ", " + xy + ", " + content + ", color=(" + d + "," + e + "," + f + ")" + ", font_size=" + size + ")\n";
- } else if (color.charAt(0) != '#') {
- var d = 0,
- e = 0,
- f = 0;
- try {
- 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
- e = parseInt(color.substring(3, 5), 16),
- f = parseInt(color.substring(5, 7), 16))
- } catch (g) { }
- // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False";
- var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
- var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
- var size = block.getFieldValue('fonts');;
- // var wraps = block.getFieldValue('wraps');
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- _code = "lcd_draw_string(" + variable_name + ", " + xy + ", " + content + ", color=" + color + ", font_size=" + size + ")\n";
- }
- return _code;
- }
- Blockly.Blocks['ai_lcd_linecarvas'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_line.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_text_on_canvas + Blockly.Msg.image_process_text_on_draw + Blockly.Msg.image_process_draw_line)
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- // .appendField();
- this.appendValueInput("POSA")
- .setCheck("String")
- .appendField(Blockly.Msg.image_process_text_start_coord);
- this.appendValueInput("POSB")
- .setCheck("String")
- .appendField(Blockly.Msg.image_process_text_end_coord);
- this.appendValueInput("COLOR")
- .setCheck("String")
- .appendField(Blockly.Msg.image_process_text_color);
- this.appendValueInput("Scale")
- .setCheck("Number")
- .appendField(Blockly.Msg.image_process_text_thick);
- this.setInputsInline(false);
- this.setPreviousStatement(true);
- this.setNextStatement(true);
- this.setColour("#5bb2d6");
- this.setTooltip(Blockly.Msg.ai_lcd_linecarvas_TOOLTIP);
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_lcd_linecarvas = function (block) {
- var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
- Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
- Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
- def CAMERATYPE():
- global cameraSize
- try:
- if os.path.exists("/etc/cameraSize.cfg"):
- cameraSize = True
- else:
- cameraSize = False
- except:
- cameraSize = False
- CAMERATYPE()
- `
- Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf")
- if cameraSize==True:
- camera.camera.config(size=(320,240))
- else:
- camera.camera.config(size=(240,320))
- try:
- if ScreenOrientation==True:
- canvas = image.new(size = (240, 320))
- else:
- canvas = image.new(size = (320, 240))
- except:
- canvas = image.new(size = (320, 240))
- ScreenOrientation = False
- `
- if (color.charAt(0) == '#') {
- var d = 0,
- e = 0,
- f = 0;
- try {
- 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
- e = parseInt(color.substring(3, 5), 16),
- f = parseInt(color.substring(5, 7), 16))
- } catch (g) { }
- var size = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
- var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
- var xy2 = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
- var _code = "canvas.draw_line(" + xy + ", " + xy2 + ", color=(" + d + "," + e + "," + f + "), thickness=" + size + ")\n";
- } else if (color.charAt(0) != '#') {
- var d = 0,
- e = 0,
- f = 0;
- try {
- 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
- e = parseInt(color.substring(3, 5), 16),
- f = parseInt(color.substring(5, 7), 16))
- } catch (g) { }
- var size = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
- var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
- var xy2 = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
- var _code = "canvas.draw_line(" + xy + ", " + xy2 + ", color=" + color + ", thickness=" + size + ")\n";
- }
- return _code;
- }
- Blockly.Blocks['ai_lcd_draw_rectangle'] = {
- init: function () {
- // this.appendDummyInput()
- // .appendField(
- // new Blockly.FieldImage("./../blockly/media/line.png", 25, 25, "15"));
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_rectangle.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_text_on_canvas + Blockly.Msg.image_process_text_on_draw)
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- // .appendField()
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.image_process_text_filled, "fillrect"],
- [Blockly.Msg.image_process_text_stroked, "rect"]
- ]), "rect_type")
- .appendField(Blockly.Msg.image_process_draw_rectangle_text);
- this.appendValueInput("POSA")
- .setCheck("String")
- .appendField(Blockly.Msg.image_process_text_start_coord);
- this.appendValueInput("POSB")
- .setCheck("String")
- .appendField(Blockly.Msg.image_process_text_size);
- this.appendValueInput("COLOR")
- .setCheck("String")
- .appendField(Blockly.Msg.image_process_text_color);
- // this.appendValueInput("Scale")
- // .setCheck("Number")
- // .appendField(Blockly.Msg.image_process_text_thick);
- this.setInputsInline(false);
- this.setPreviousStatement(true);
- this.setNextStatement(true);
- this.setColour("#5bb2d6");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('rect_type');
- var TOOLTIPS = {
- 'fillrect': Blockly.Msg.ai_lcd_ractanglecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_filled),
- 'rect': Blockly.Msg.ai_lcd_ractanglecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_stroked)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_lcd_draw_rectangle = function (block) {
- var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var type = block.getFieldValue('rect_type') == "fillrect" ? "-1" : "1";
- var th = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
- var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
- var size = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
- Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
- Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
- def CAMERATYPE():
- global cameraSize
- try:
- if os.path.exists("/etc/cameraSize.cfg"):
- cameraSize = True
- else:
- cameraSize = False
- except:
- cameraSize = False
- CAMERATYPE()
- `
- Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf")
- if cameraSize==True:
- camera.camera.config(size=(320,240))
- else:
- camera.camera.config(size=(240,320))
-
- try:
- if ScreenOrientation==True:
- canvas = image.new(size = (240, 320))
- else:
- canvas = image.new(size = (320, 240))
- except:
- canvas = image.new(size = (320, 240))
- ScreenOrientation = False
- `
- // console.log(xy.split(','),size.split(','))
- let a = xy.split(',')
- let b = size.split(',')
- // let w = Number(a[0])+Number(b[0])
- // let h = Number(a[1])+Number(b[1])
- // let wh = `${w},${h}`
- // let ai_lcd_fill_screen_with_rgb = text.includes('ai_lcd_fill_screen_with_rgb')
- var _code = ''
- if (color.charAt(0) == '#') {
- var d = 0,
- e = 0,
- f = 0;
- try {
- 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
- e = parseInt(color.substring(3, 5), 16),
- f = parseInt(color.substring(5, 7), 16))
- } catch (g) { }
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- // var type = block.getFieldValue('rect_type') == "fillrect" ? "-1" : "1";
- // var th = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
- // var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
- // var size = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
- _code = `canvas.draw_rectangle(${xy}, ${a[0]}+${b[0]},${a[1]}+${b[1]}, color=(${d},${e},${f}), thickness=${type})
- `
- } else if (color.charAt(0) != '#') {
- _code = `canvas.draw_rectangle(${xy}, ${a[0]}+${b[0]},${a[1]}+${b[1]}, color=${color}, thickness=${type})
- `
- }
- return _code;
- }
- Blockly.Blocks['ai_lcd_drawcirclecarvas'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_circle.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_text_on_canvas + Blockly.Msg.image_process_text_on_draw)
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- // .appendField()
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.image_process_text_filled, "fillrect"],
- [Blockly.Msg.image_process_text_stroked, "rect"]
- ]), "rect_type")
- .appendField(Blockly.Msg.image_process_draw_circle_text);
- this.appendValueInput("POSA")
- .setCheck("String")
- .appendField(Blockly.Msg.image_process_draw_circle_text_start);
- this.appendValueInput("Scale")
- .setCheck("Number")
- .appendField(Blockly.Msg.image_process_text_radius);
- this.appendValueInput("COLOR")
- .setCheck("String")
- .appendField(Blockly.Msg.image_process_text_color);
- // this.appendValueInput("Scale_0")
- // .setCheck("Number")
- // .appendField(Blockly.Msg.image_process_text_thick);
- this.setInputsInline(false);
- this.setPreviousStatement(true);
- this.setNextStatement(true);
- this.setColour("#5bb2d6");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('rect_type');
- var TOOLTIPS = {
- 'fillrect': Blockly.Msg.ai_lcd_drawcirclecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_filled),
- 'rect': Blockly.Msg.ai_lcd_drawcirclecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_stroked)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_lcd_drawcirclecarvas = function (block) {
- var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
- Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
- Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
- def CAMERATYPE():
- global cameraSize
- try:
- if os.path.exists("/etc/cameraSize.cfg"):
- cameraSize = True
- else:
- cameraSize = False
- except:
- cameraSize = False
- CAMERATYPE()
- `
- Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf")
- if cameraSize==True:
- camera.camera.config(size=(320,240))
- else:
- camera.camera.config(size=(240,320))
- try:
- if ScreenOrientation==True:
- canvas = image.new(size = (240, 320))
- else:
- canvas = image.new(size = (320, 240))
- except:
- canvas = image.new(size = (320, 240))
- ScreenOrientation = False
- `
- if (color.charAt(0) == '#') {
- var d = 0,
- e = 0,
- f = 0;
- try {
- 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
- e = parseInt(color.substring(3, 5), 16),
- f = parseInt(color.substring(5, 7), 16))
- } catch (g) { }
- var type = block.getFieldValue('rect_type') == "fillrect" ? "-1" : "1";
- var th = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
- var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
- var th0 = Blockly.Python.valueToCode(block, 'Scale_0', Blockly.Python.ORDER_ATOMIC);
- var _code = "canvas.draw_circle(" + xy + ", " + th + ", color=(" + d + ", " + e + ", " + f + "), thickness=" + type + ")\n";
- } else if (color.charAt(0) != '#') {
- var d = 0,
- e = 0,
- f = 0;
- try {
- 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
- e = parseInt(color.substring(3, 5), 16),
- f = parseInt(color.substring(5, 7), 16))
- } catch (g) { }
- var type = block.getFieldValue('rect_type') == "fillrect" ? "-1" : "1";
- var th = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
- var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
- var th0 = Blockly.Python.valueToCode(block, 'Scale_0', Blockly.Python.ORDER_ATOMIC);
- var _code = "canvas.draw_circle(" + xy + ", " + th + ", color=" + color + ", thickness=" + type + ")\n";
- }
- return _code;
- }
- Blockly.Blocks['ai_lcd_draw_image_on_canvas'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_image.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_text_on_canvas + Blockly.Msg.image_process_draw_image_title);
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- // .appendField();
- this.appendValueInput("image_path")
- .setCheck(null)
- .appendField(Blockly.Msg.image_process_draw_sensor_image_path);
- this.appendValueInput("scale_y")
- .setCheck(null)
- .appendField(Blockly.Msg.OLCD_COORDINATE);
- this.appendValueInput("alpha")
- .setCheck(null)
- .appendField(Blockly.Msg.image_process_draw_image_alpha);
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#5bb2d6");
- this.setTooltip(Blockly.Msg.ai_lcd_draw_image_on_canvas_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_lcd_draw_image_on_canvas'] = function (block) {
- var value_image_path = Blockly.Python.valueToCode(block, 'image_path', Blockly.Python.ORDER_ATOMIC);
- var value_scale_y = Blockly.Python.valueToCode(block, 'scale_y', Blockly.Python.ORDER_ATOMIC);
- var alpha = Blockly.Python.valueToCode(block, 'alpha', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
- Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
- Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
- def CAMERATYPE():
- global cameraSize
- try:
- if os.path.exists("/etc/cameraSize.cfg"):
- cameraSize = True
- else:
- cameraSize = False
- except:
- cameraSize = False
- CAMERATYPE()
- `
- Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf")
- if cameraSize==True:
- camera.camera.config(size=(320,240))
- else:
- camera.camera.config(size=(240,320))
- try:
- if ScreenOrientation==True:
- canvas = image.new(size = (240, 320))
- else:
- canvas = image.new(size = (320, 240))
- except:
- canvas = image.new(size = (320, 240))
- ScreenOrientation = False
- `
- // let alpha = Blockly.Python.valueToCode(block, 'alpha', Blockly.Python.ORDER_ATOMIC)
- // TODO: Assemble Python into code variable.
- var code = 'canvas.draw_image(' + value_image_path + ',' + value_scale_y + ',alpha=' + alpha + ')\n';
- return code;
- };
- Blockly.Blocks['v831_img_save'] = {
- init: function () {
- this.appendValueInput("save_path")
- .setCheck(null)
- .appendField(Blockly.Msg.image_process_text_let_canvas)
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- .appendField(Blockly.Msg.image_process_img_save)
- // .appendField(new Blockly.FieldDropdown([
- // [Blockly.Msg.display_draw_vertical, "0", "img"],
- // [Blockly.Msg.display_draw_horizontal, "1", "img1"]
- // ]), "invert");
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_img_save_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['v831_img_save'] = function (block) {
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var save_path_location = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC);
- // let invert = block.getFieldValue('invert');
- // console.log(document.getElementById("img").value, invert)
- var code = 'canvas.save("/root/user/img/' + save_path_location.slice(1, -1) + '.jpg")\n';
- if (save_path_location[0] != '"') {
- code = 'canvas.save(' + save_path_location + ')\n';
- }
- return code;
- };
- Blockly.Blocks.v831_img_text = {
- init: function () {
- this.appendValueInput("save_path")
- .setCheck(null)
- .appendField(Blockly.Msg.read_img_path_to)
- this.setOutput(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.read_img_path_to);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.v831_img_text = function (block) {
- var save_path_location = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC);
- var code = 'image.open(' + save_path_location + ')';
- return [code,Blockly.Python.ORDER_NONE];
- }
- Blockly.Blocks['v831_img_open'] = {
- init: function () {
- this.appendValueInput("save_path")
- .setCheck(null)
- .appendField(Blockly.Msg.read_img_path_to)
- // .appendField(Blockly.Msg.image_process_img_save);
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.image_process_img_save_quality)
- // .appendField(new Blockly.FieldNumber(90, 0, 100), "compression")
- // .appendField("%");
- // this.setInputsInline(false);
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.read_img_path_to);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['v831_img_open'] = function (block) {
- var save_path_location = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC);
- var code = 'canvas = image.open(' + save_path_location + ')\n';
- return code;
- };
- // 翻转
- Blockly.Blocks['v831_lcd_invert'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_text_let_canvas + Blockly.Msg.image_process_text_image_canvas)
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- // .appendField()
- .appendField(Blockly.Msg.image_process_pixtovec_text_first)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.display_draw_vertical, "0"],
- [Blockly.Msg.display_draw_horizontal, "1"]
- ]), "invert")
- .appendField(Blockly.Msg.MAIXDUINO_DISPLAY_ORIENTATION_ROTATE);
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null);
- this.setColour("#f0983e");
- // this.setTooltip(Blockly.Msg.ai_lcd_invert_color_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['v831_lcd_invert'] = function (block) {
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- let invert = block.getFieldValue('invert');
- // TODO: Assemble Python into code variable.
- var code = `canvas = canvas.flip(${invert})\n`
- // TODO: Change ORDER_NONE to the correct strength.
- return code;
- };
- // 旋转
- Blockly.Blocks['v831_lcd_rotating'] = {
- init: function () {
- this.appendValueInput('spend')
- .setCheck(null)
- .appendField(Blockly.Msg.image_process_text_let_canvas + Blockly.Msg.image_process_text_image_canvas)
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- // .appendField()
- .appendField(Blockly.Msg.image_process_pixtovec_text_first)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.x_motor_cw_ai, "0"],
- [Blockly.Msg.x_motor_acw_ai, "1"]
- ]), "rotating")
- .appendField(Blockly.Msg.x_motor_set_motor_turns_ai);
- this.appendDummyInput().appendField(Blockly.Msg.robot_dog_ag);
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_lcd_invert_color_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['v831_lcd_rotating'] = function (block) {
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- let rotating = block.getFieldValue('rotating');
- let spend = (rotating != 0 ? '+' : '-') + Blockly.Python.valueToCode(block, 'spend', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- // Blockly.Python.definitions_['lcd_invert_init'] = `def lcdRotation(inputImg,rotationAngle):
- // from maix import image
- // imgRotationAim = image.new(size = (320, 240),color=(0,0,0))
- // imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
- // return imgRotationAim.draw_image(imageRotationBuffer.rotate(rotationAngle, adjust=1),0,0,alpha=1)
- // `
- // console.log(rotating,spend)
- var code = `canvas = canvas.rotate(${spend}, adjust=1)\n`
- // variable_name+'.rotate('+ spend +', adjust=1)';
- // TODO: Change ORDER_NONE to the correct strength.
- return code;
- };
- Blockly.Blocks['ai_lcd_invert_color'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_text_let_canvas + Blockly.Msg.image_process_color_invert)
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- // .appendField();
- this.setOutput(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_lcd_invert_color_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_lcd_invert_color'] = function (block) {
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- // TODO: Assemble Python into code variable.
- var code = 'canvas.invert()';
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['v831_lcd_resizecanvas'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_text_let_canvas + Blockly.Msg.image_process_text_image_canvas)
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- // .appendField()
- .appendField(Blockly.Msg.image_process_resize_to);
- this.appendValueInput("wh")
- .setCheck(null);
- this.setInputsInline(true);
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_lcd_resizecanvas_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['v831_lcd_resizecanvas'] = function (block) {
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- // Blockly.Python.definitions_['lcd_invert_init'] = `CANVASINVERT = image.new(size = (240, 320), color = (0,0,0), mode = 'RGB')
- // `
- // var code = `CANVASINVERT.draw_image(${variable_name}.crop(0, 0, 240, 320).resize(${wh}),0,0,alpha=1)`
- // variable_name + '.resize(' + wh + ')';
- // TODO: Change ORDER_NONE to the correct strength.
- var code = `canvas = canvas.resize(${wh}, padding = 0)\n`
- return code;
- };
- Blockly.Blocks['ai_lcd_color_scheme'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_text_let_canvas)
- .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- .appendField(Blockly.Msg.image_process_color_scheme_convert)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.image_process_color_scheme_bw, "to_grayscale(1)"],
- [Blockly.Msg.image_process_color_scheme_rgb, "to_rgb565(1)"]
- ]), "color_scheme");
- this.setOutput(true, null);
- this.setColour("#f0983e");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('color_scheme');
- var TOOLTIPS = {
- 'to_grayscale(1)': Blockly.Msg.ai_lcd_color_scheme_TOOLTIP.replace('%1', Blockly.Msg.image_process_color_scheme_bw),
- 'to_rgb565(1)': Blockly.Msg.ai_lcd_color_scheme_TOOLTIP.replace('%1', Blockly.Msg.image_process_color_scheme_rgb)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_lcd_color_scheme'] = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var dropdown_vari = block.getFieldValue('color_scheme');
- // TODO: Assemble Python into code variable.
- var code = variable_name + '.' + dropdown_vari;
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_lcd_ai_pix'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_text_let_canvas)
- .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- .appendField(Blockly.Msg.image_process_pixtovec_text_first)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.image_process_pixtovec_v2p, ".ai_to_pix()"],
- [Blockly.Msg.image_process_pixtovec_p2v, ".pix_to_ai()"]
- ]), "ai_pix_type")
- .appendField(Blockly.Msg.image_process_pixtovec_conversion);
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#f0983e");
- this.setTooltip("");
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_lcd_ai_pix'] = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var dropdown_vari = block.getFieldValue('ai_pix_type');
- // TODO: Assemble Python into code variable.
- var code = 'a = ' + variable_name + dropdown_vari + '\n';
- // TODO: Change ORDER_NONE to the correct strength.
- return code;
- };
- Blockly.Blocks['v831_lcd_img_cut'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_text_let_canvas + Blockly.Msg.image_process_text_image_canvas + Blockly.Msg.image_process_imgcut_cutting)
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- // .appendField()
- // .appendField();
- this.appendValueInput("xy")
- .setCheck(null)
- .appendField(Blockly.Msg.image_process_imgcut_start_coord);
- this.appendValueInput("wh")
- .setCheck(null)
- .appendField(Blockly.Msg.image_process_imgcut_size);
- this.setInputsInline(false);
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null)
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_lcd_img_cut_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['v831_lcd_img_cut'] = function (block) {
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
- var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- // TODO: Change ORDER_NONE to the correct strength.
- var code = `canvas = canvas.crop(${xy},${wh})\n`;
- return code;
- };
- Blockly.Blocks['ai_vision_get_statistics'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_get_statistics_to_canvas)
- .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- .appendField(Blockly.Msg.image_process_get_statistics_get_analysis);
- this.appendValueInput("xy")
- .setCheck(null)
- .appendField(Blockly.Msg.image_process_get_statistics_start_coord);
- this.appendValueInput("wh")
- .setCheck(null)
- .appendField(Blockly.Msg.image_process_get_statistics_size);
- this.appendValueInput("bins")
- .setCheck(null)
- .appendField(Blockly.Msg.image_process_get_statistics_boxes);
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_vision_get_statistics_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_vision_get_statistics'] = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
- var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
- var bins = Blockly.Python.valueToCode(block, 'bins', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- var code = variable_name + '.get_statistics(bins=' + bins + ',roi=(' + xy + ',' + wh + '))';
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_vision_get_histogram'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_get_histogram_get)
- .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- .appendField(Blockly.Msg.ai_vision_get_histogram_compute);
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_get_histogram_region);
- this.appendValueInput("xy")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_get_histogram_region_xy);
- this.appendValueInput("wh")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_get_histogram_region_wh);
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_vision_get_histogram_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_vision_get_histogram'] = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var value_xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
- var value_wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- var code = variable_name + '.get_histogram(roi=(' + value_xy + ',' + value_wh + '))';
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_vision_get_histogram_percentile'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_get_histogram_details_1)
- .appendField(new Blockly.FieldVariable("hist"), "varitem")
- .appendField(Blockly.Msg.ai_vision_get_histogram_details_get);
- this.appendValueInput("perc")
- .setCheck(null);
- this.setInputsInline(true);
- this.setOutput(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_vision_get_histogram_percentile_TOOLTIP);
- this.setHelpUrl("https://docs.openmv.io/library/omv.image.html#id3");
- }
- };
- Blockly.Python['ai_vision_get_histogram_percentile'] = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var value_perc = Blockly.Python.valueToCode(block, 'perc', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- var code = variable_name + '.get_percentile(' + value_perc + ')';
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_vision_get_histogram_percentile_detail'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_get_histogram_percentile_1)
- .appendField(new Blockly.FieldVariable("percentile"), "varitem");
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_get_histogram_percentile_2)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_vision_get_histogram_percentile_3, "value()"],
- [Blockly.Msg.ai_vision_get_histogram_percentile_4, "l_value()"],
- [Blockly.Msg.ai_vision_get_histogram_percentile_5, "a_value()"],
- [Blockly.Msg.ai_vision_get_histogram_percentile_6, "b_value()"]
- ]), "option");
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#f0983e");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('option');
- var TOOLTIPS = {
- 'value()': Blockly.Msg.ai_vision_get_histogram_percentile_detail_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_get_histogram_percentile_3),
- 'l_value()': Blockly.Msg.ai_vision_get_histogram_percentile_detail_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_get_histogram_percentile_4),
- 'a_value()': Blockly.Msg.ai_vision_get_histogram_percentile_detail_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_get_histogram_percentile_5),
- 'b_value()': Blockly.Msg.ai_vision_get_histogram_percentile_detail_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_get_histogram_percentile_6)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl("https://docs.openmv.io/library/omv.image.html#id3");
- }
- };
- Blockly.Python['ai_vision_get_histogram_percentile_detail'] = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var dropdown_option = block.getFieldValue('option');
- var code = variable_name + '.' + dropdown_option;
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_vision_lab_rgb_conversion'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_lab_rgb_conversion_exec)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.image_process_lab_rgb_conversion_torgb, "lab_to_rgb"],
- [Blockly.Msg.image_process_lab_rgb_conversion_tolab, "rgb_to_lab"]
- ]), "rgblab");
- this.appendValueInput("color_tuple")
- .setCheck(null)
- .appendField(Blockly.Msg.image_process_lab_rgb_conversion_tuple);
- this.setOutput(true, null);
- this.setColour("#f0983e");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('rgblab');
- var TOOLTIPS = {
- 'lab_to_rgb': Blockly.Msg.ai_vision_lab_rgb_conversion_TOOLTIP.replace('%1', Blockly.Msg.image_process_lab_rgb_conversion_torgb),
- 'rgb_to_lab': Blockly.Msg.ai_vision_lab_rgb_conversion_TOOLTIP.replace('%1', Blockly.Msg.image_process_lab_rgb_conversion_tolab)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_vision_lab_rgb_conversion'] = function (block) {
- var type = block.getFieldValue('rgblab');
- var tuple = Blockly.Python.valueToCode(block, 'color_tuple', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- var code = 'image.' + type + '(' + tuple + ')';
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_vision_rgb_grayscale_conversion'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_rgb_grayscale_conversion_exec)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.image_process_rgb_grayscale_conversion_torgb, "grayscale_to_rgb"],
- [Blockly.Msg.image_process_rgb_grayscale_conversion_togray, "rgb_to_grayscale"]
- ]), "rgb_g");
- this.appendValueInput("color_tuple")
- .setCheck(null)
- .appendField(Blockly.Msg.image_process_rgb_grayscale_conversion_set);
- this.setOutput(true, null);
- this.setColour("#f0983e");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('rgb_g');
- var TOOLTIPS = {
- 'grayscale_to_rgb': Blockly.Msg.ai_vision_rgb_grayscale_conversion_TOOLTIP.replace('%1', Blockly.Msg.image_process_rgb_grayscale_conversion_torgb),
- 'rgb_to_grayscale': Blockly.Msg.ai_vision_rgb_grayscale_conversion_TOOLTIP.replace('%1', Blockly.Msg.image_process_rgb_grayscale_conversion_togray)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_vision_rgb_grayscale_conversion'] = function (block) {
- var type = block.getFieldValue('rgb_g');
- var tuple = Blockly.Python.valueToCode(block, 'color_tuple', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.addVariable('rgb_tuple', "rgb_tuple = None", true);
- // TODO: Assemble Python into code variable.
- var code = 'image.' + type + '(' + tuple + ')';
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- /*
- _ ___ ____
- / \ |_ _| / ___|__ _ _ __ ___ ___ _ __ __ _
- / _ \ | | | | / _` | '_ ` _ \ / _ \ '__/ _` |
- / ___ \ | | | |__| (_| | | | | | | __/ | | (_| |
- /_/ \_\___| \____\__,_|_| |_| |_|\___|_| \__,_|
- */
- Blockly.Blocks.ai_camera_wh = {
- init: function () {
- var _input = this.appendDummyInput();
- this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL);
- this.setColour("#60c1bb");
- this.setOutput(!0, "Boolean");
- _input.appendField(Blockly.Msg.W);
- this.appendValueInput("A").setCheck("Number");
- _input = this.appendDummyInput();
- _input.appendField(Blockly.Msg.H)
- this.appendValueInput("B").setCheck("Number");
- this.setInputsInline(!0);
- }
- };
- Blockly.Python.ai_camera_wh = function (block) {
- var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
- var _y = Blockly.Python.valueToCode(block, "B", Blockly.Python.ORDER_ATOMIC);
- var code = "" + _x + ", " + _y + "";
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks['ai_camera_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/camera_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_camera_camera_init);
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_camera_camera_set_size)
- // .appendField(new Blockly.FieldDropdown([
- // ["QVGA (320*240)", "QVGA"],
- // ["QQVGA (160*120)", "QQVGA"]
- // ]), "DEGREE");
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_camera_camera_color_mode)
- // .appendField(new Blockly.FieldDropdown([
- // [Blockly.Msg.ai_camera_camera_color_mode_rgb, "RGB565"],
- // [Blockly.Msg.ai_camera_camera_color_mode_bw, "GRAYSCALE"]
- // ]), "DEGREE1");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#60c1bb");
- this.setTooltip(Blockly.Msg.ai_camera_init_TOOLTIP);
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_camera_init = function (block) {
- Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
- def CAMERATYPE():
- global cameraSize
- try:
- if os.path.exists("/etc/cameraSize.cfg"):
- cameraSize = True
- else:
- cameraSize = False
- except:
- cameraSize = False
- CAMERATYPE()
- `
- Blockly.Python.addVariable("SETVFLIP", "SETVFLIP = False", true)
- Blockly.Python.addVariable("SETHMIRROT", "SETHMIRROT = False", true)
- var _code = ``;
- return _code;
- }
- Blockly.Blocks['ai_camera_windows'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_camera_windowing_resize);
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_camera_windowing_w)
- .appendField(new Blockly.FieldNumber(240), "window_w")
- .appendField(Blockly.Msg.ai_camera_windowing_h)
- .appendField(new Blockly.FieldNumber(320), "window_h")
- // .appendField(Blockly.Msg.ai_camera_windowing_unit);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#60c1bb");
- this.setTooltip(Blockly.Msg.ai_camera_windows_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_camera_windows'] = function (block) {
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var w = block.getFieldValue('window_w');
- var h = block.getFieldValue('window_h');
- // var code = 'sensor.set_windowing((' + w + ',' + h + '))\n';
- var code = 'camera.camera.config(size=(' + w + ',' + h + '))\n';
- return code;
- };
- Blockly.Blocks['ai_camera_fit_to_screen_size'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_camera_camera_fit_set + Blockly.Msg.ai_camera_camera_fit_to)
- .appendField(new Blockly.FieldDropdown([
- ["320*240", "320"],
- ["224*224", "224"]
- ]), "size");
- this.setInputsInline(true);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#60c1bb");
- this.setTooltip(Blockly.Msg.ai_camera_fit_to_screen_size_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_camera_fit_to_screen_size'] = function (block) {
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var dropdown_size = block.getFieldValue('size');
- Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
- Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
- def CAMERATYPE():
- global cameraSize
- try:
- if os.path.exists("/etc/cameraSize.cfg"):
- cameraSize = True
- else:
- cameraSize = False
- except:
- cameraSize = False
- CAMERATYPE()
- `
- Blockly.Python.definitions_['lcd_invert_init'] = `def lcdRotation(inputImg):
- global SETVFLIP,SETHMIRROT,cameraSize,ScreenOrientation
- imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
- try:
- if ScreenOrientation:
- imgRotationAim = image.new(size = (240, 320))
- rotationAngle = 180
- else:
- imgRotationAim = image.new(size = (320, 240))
- rotationAngle = 90
- except:
- imgRotationAim = image.new(size = (320, 240))
- rotationAngle = 90
- GETROTATION = imageRotationBuffer.rotate(+rotationAngle, adjust=1)
- GETROTATION = imgRotationAim.draw_image(GETROTATION,0,0,alpha=1)
- return GETROTATION
- `
- Blockly.Python.definitions_['lcd_invert_init_new'] = `def lcdRotationNew(inputImg):
- global SETVFLIP,SETHMIRROT,cameraSize,ScreenOrientation
- imageRotationBuffer = inputImg.crop(0, 0, 320, 240)
- try:
- if ScreenOrientation:
- imgRotationAim = image.new(size = (240, 320))
- rotationAngle = 90
- GETROTATION = imageRotationBuffer.rotate(+rotationAngle, adjust=1)
- else:
- imgRotationAim = image.new(size = (320, 240))
- GETROTATION = imageRotationBuffer
- except:
- imgRotationAim = image.new(size = (320, 240))
- GETROTATION = imageRotationBuffer
-
- GETROTATION = imgRotationAim.draw_image(GETROTATION,0,0,alpha=1)
- return GETROTATION
- `
- Blockly.Python.definitions_['lcd_invert_rotate_camera'] = `def getLcdRotation(cameraCapture):
- global cameraSize
- if cameraSize:
- return lcdRotationNew(cameraCapture)
- else:
- return lcdRotation(cameraCapture)
- `
- // #从摄像头中获取一张图像
- var code = `canvas = getLcdRotation(camera.capture())\n`;
- // TODO: Assemble Python into code variable.
- if (dropdown_size == "224") {
- code = `canvas = getLcdRotation(camera.capture()).crop(0,0,224,224)\n`
- }
- return code;
- };
- Blockly.Blocks['ai_camera_snapshot'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_camera_snapshot);
- this.setOutput(false, null);
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null);
- this.setColour("#60c1bb");
- this.setTooltip(Blockly.Msg.ai_camera_snapshot_TOOLTIP);
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_camera_snapshot = function (block) {
- Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
- Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
- def CAMERATYPE():
- global cameraSize
- try:
- if os.path.exists("/etc/cameraSize.cfg"):
- cameraSize = True
- else:
- cameraSize = False
- except:
- cameraSize = False
- CAMERATYPE()
- `
- Blockly.Python.definitions_['lcd_invert_init_new'] = `def lcdRotationNew(inputImg):
- global SETVFLIP,SETHMIRROT,cameraSize,ScreenOrientation
- imageRotationBuffer = inputImg.crop(0, 0, 320, 240)
- if ScreenOrientation:
- imgRotationAim = image.new(size = (240, 320))
- rotationAngle = 90
- GETROTATION = imageRotationBuffer.rotate(+rotationAngle, adjust=1)
- else:
- imgRotationAim = image.new(size = (320, 240))
- GETROTATION = imageRotationBuffer
-
- GETROTATION = imgRotationAim.draw_image(GETROTATION,0,0,alpha=1)
- return GETROTATION
- `
- Blockly.Python.addVariable("ScreenOrientation", `ScreenOrientation = False`, true)
- // #从摄像头中获取一张图像
- var _code = `canvas = lcdRotationNew(camera.capture())\n`;
- return _code;
- }
- // 图传
- Blockly.Blocks['v831_camera_graph_transmission'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.v831_transmission_setup_show);
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.v831_transmission_init_setup_source)
- // .appendField(new Blockly.FieldVariable("img_graphTransmission"), "varitem");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#60c1bb");
- this.setTooltip(Blockly.Msg.v831_transmission_setup_show);
- this.setHelpUrl('');
- }
- };
- Blockly.Python.v831_camera_graph_transmission = function (block) {
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- Blockly.Python.definitions_['v831_import_mjpg'] = `from maix import mjpg`
- Blockly.Python.definitions_['v831_import_utils'] = `from maix import utils`
- Blockly.Python.definitions_['v831_import_base64'] = `import base64`
- Blockly.Python.definitions_['v831_import_time'] = `import time`
- // #从摄像头中获取一张图像
- var _code = `jpg = utils.rgb2jpg(canvas.convert("RGB").tobytes(), canvas.width, canvas.height)
- img_base64 = base64.b64encode(jpg)
- img_base64_str = "data:image/jpg;base64," + str(img_base64)[2:-1]
- time.sleep(0.1)
- try:
- print(img_base64_str)
- pass
- except Exception as e:
- print(str(e))
- pass
- `;
- return _code
- }
- Blockly.Blocks['v831_camera_internet_transmission'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.v831_internet_transmission_setup_show);
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.v831_transmission_init_setup_source)
- // .appendField(new Blockly.FieldVariable("img_graphTransmission"), "varitem");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#60c1bb");
- this.setTooltip(Blockly.Msg.v831_transmission_setup_show);
- this.setHelpUrl('');
- }
- };
- Blockly.Python.v831_camera_internet_transmission = function (block) {
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- Blockly.Python.definitions_['v831_import_mjpg'] = `from maix import mjpg`
- Blockly.Python.definitions_['v831_import_utils'] = `from maix import utils`
- Blockly.Python.definitions_['v831_import_queue'] = `queue = mjpg.Queue(maxsize=8)
- mjpg.MjpgServerThread("0.0.0.0", 18811, mjpg.BytesImageHandlerFactory(q=queue)).start()`
- // #从摄像头中获取一张图像
- var _code = `jpg = utils.rgb2jpg(canvas.convert("RGB").tobytes(), 320, 240)
- queue.put(mjpg.BytesImage(jpg))
- `;
- return _code
- }
- Blockly.Blocks['ai_camera_lens_corr'] = {
- init: function () {
- this.appendValueInput("lens_corr")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_camera_set_lens_corr);
- this.setInputsInline(true);
- this.setOutput(true, null);
- this.setColour("#60c1bb");
- this.setTooltip(Blockly.Msg.ai_camera_lens_corr_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_camera_lens_corr'] = function (block) {
- var value_lens_corr = Blockly.Python.valueToCode(block, 'lens_corr', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- var code = value_lens_corr + '.lens_corr(strength = 1.8, zoom = 1.0)';
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_camera_image_property_change'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_camera_bcs_set_text_2)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_camera_bcs_vflip, "set_vflip"],
- [Blockly.Msg.ai_camera_bcs_hmirror, "set_hmirror"],
- // [Blockly.Msg.ai_camera_bcs_wb, "set_auto_whitebal"],
- // [Blockly.Msg.ai_camera_bcs_g, "set_auto_gain"],
- // [Blockly.Msg.ai_camera_bcs_e, "set_auto_exposure"]
- ]), "image_property")
- .appendField(Blockly.Msg.ai_camera_bcs_as_2)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_camera_enable + Blockly.Msg.ai_camera_bcs_status, "True"],
- [Blockly.Msg.ai_camera_disable + Blockly.Msg.ai_camera_bcs_status, "False"]
- ]), "DEGREE");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#60c1bb");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('image_property');
- var TOOLTIPS = {
- 'set_vflip': Blockly.Msg.ai_camera_image_property_change_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_vflip),
- 'set_hmirror': Blockly.Msg.ai_camera_image_property_change_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_hmirror),
- 'set_auto_whitebal': Blockly.Msg.ai_camera_image_property_change_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_wb),
- 'set_auto_gain': Blockly.Msg.ai_camera_image_property_change_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_g),
- 'set_auto_exposure': Blockly.Msg.ai_camera_image_property_change_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_e)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_camera_image_property_change = function (block) {
- var degee = block.getFieldValue('DEGREE');
- var dropdown_image_property = block.getFieldValue('image_property');
- var _code = ``;
- if (dropdown_image_property == "set_vflip") {
- _code = `SETVFLIP = ${degee}
- `
- } else if (dropdown_image_property == "set_hmirror") {
- _code = `SETHMIRROT = ${degee}
- `
- }
- return _code;
- }
- Blockly.Blocks['ai_camera_vflip'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_camera_set_vflip)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_camera_enable, "True"],
- [Blockly.Msg.ai_camera_disable, "False"]
- ]), "DEGREE")
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#60c1bb");
- this.setTooltip('');
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_camera_vflip = function (block) {
- var degee = block.getFieldValue('DEGREE');
- var _code = "sensor.set_vflip(" + degee + ")\n";
- return _code;
- }
- Blockly.Blocks['ai_camera_hmirror'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_camera_set_hmirror)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_camera_enable, "True"],
- [Blockly.Msg.ai_camera_disable, "False"]
- ]), "DEGREE")
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#60c1bb");
- this.setTooltip('');
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_camera_hmirror = function (block) {
- var degee = block.getFieldValue('DEGREE');
- var _code = "sensor.set_hmirror(" + degee + ")\n"
- return _code;
- }
- Blockly.Blocks['ai_camera_auto_whitebal'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_camera_set_auto_whitebal)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_camera_enable, "True"],
- [Blockly.Msg.ai_camera_disable, "False"]
- ]), "DEGREE")
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#60c1bb");
- this.setTooltip('');
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_camera_auto_whitebal = function (block) {
- var degee = block.getFieldValue('DEGREE');
- var _code = "sensor.set_auto_whitebal(" + degee + ")\n"
- return _code;
- }
- Blockly.Blocks['ai_camera_auto_gain'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_camera_set_auto_gain)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_camera_enable, "True"],
- [Blockly.Msg.ai_camera_disable, "False"]
- ]), "DEGREE")
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#60c1bb");
- this.setTooltip('');
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_camera_auto_gain = function (block) {
- var degee = block.getFieldValue('DEGREE');
- var _code = "sensor.set_auto_gain(" + degee + ")\n"
- return _code;
- }
- Blockly.Blocks['ai_camera_auto_exposure'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_camera_set_auto_exposure)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_camera_enable, "True"],
- [Blockly.Msg.ai_camera_disable, "False"]
- ]), "DEGREE")
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#60c1bb");
- this.setTooltip('');
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_camera_auto_exposure = function (block) {
- var degee = block.getFieldValue('DEGREE');
- var _code = "sensor.set_auto_exposure(" + degee + ")\n"
- return _code;
- }
- Blockly.Blocks['ai_camera_bcs_operation'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_camera_bcs_set_text)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_camera_bcs_contrast, "contrast"],
- [Blockly.Msg.ai_camera_bcs_brightness, "brightness"],
- [Blockly.Msg.ai_camera_bcs_saturation, "saturation"]
- ]), "image_property")
- .appendField(Blockly.Msg.ai_camera_bcs_as);
- this.appendValueInput("A").setCheck("Number");
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_camera_set_range);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setInputsInline(!0);
- this.setColour("#60c1bb");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('image_property');
- var TOOLTIPS = {
- 'contrast': Blockly.Msg.ai_camera_bcs_operation_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_contrast),
- 'brightness': Blockly.Msg.ai_camera_bcs_operation_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_brightness),
- 'saturation': Blockly.Msg.ai_camera_bcs_operation_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_saturation)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_camera_bcs_operation = function (block) {
- var dropdown_image_property = block.getFieldValue('image_property');
- var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
- var _code = "sensor.set_" + dropdown_image_property + "(" + _x + ")\n"
- return _code;
- }
- Blockly.Blocks['ai_camera_contrast'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_camera_set_contrast_to_value);
- this.appendValueInput("A").setCheck("Number");
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_camera_set_range);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setInputsInline(!0);
- this.setColour("#60c1bb");
- this.setTooltip('');
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_camera_contrast = function (block) {
- var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
- var _code = "sensor.set_contrast(" + _x + ")\n"
- return _code;
- }
- Blockly.Blocks['ai_camera_brightness'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_camera_set_brightness_to_value);
- this.appendValueInput("A").setCheck("Number");
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_camera_set_range);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setInputsInline(!0);
- this.setColour("#60c1bb");
- this.setTooltip('');
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_camera_brightness = function (block) {
- var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
- var _code = "sensor.set_brightness(" + _x + ")\n"
- return _code;
- }
- Blockly.Blocks['ai_camera_saturation'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_camera_set_saturation_value);
- this.appendValueInput("A").setCheck("Number");
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_camera_set_range);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setInputsInline(!0);
- this.setColour("#60c1bb");
- this.setTooltip('');
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_camera_saturation = function (block) {
- var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
- var _code = "sensor.set_saturation(" + _x + ")\n"
- return _code;
- }
- /*
- _ ___ __ ___ _
- / \ |_ _| \ \ / (_)___(_) ___ _ __
- / _ \ | | \ \ / /| / __| |/ _ \| '_ \
- / ___ \ | | \ V / | \__ \ | (_) | | | |
- /_/ \_\___| \_/ |_|___/_|\___/|_| |_|
-
- */
- Blockly.Blocks.ai_lcd_XY_vision = {
- init: function () {
- var _input = this.appendDummyInput();
- this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL);
- this.setColour("#f0983e");
- this.setOutput(!0, "Boolean");
- _input.appendField(Blockly.Msg.X);
- this.appendValueInput("A").setCheck("Number");
- _input = this.appendDummyInput();
- _input.appendField(Blockly.Msg.Y)
- this.appendValueInput("B").setCheck("Number");
- this.setInputsInline(!0);
- }
- };
- Blockly.Python.ai_lcd_XY_vision = function (block) {
- var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
- var _y = Blockly.Python.valueToCode(block, "B", Blockly.Python.ORDER_ATOMIC);
- var code = "" + _x + ", " + _y + "";
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks.ai_lcd_WH_vision = {
- init: function () {
- var _input = this.appendDummyInput();
- this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL);
- this.setColour("#f0983e");
- this.setOutput(!0, "Boolean");
- _input.appendField(Blockly.Msg.W);
- this.appendValueInput("A").setCheck("Number");
- _input = this.appendDummyInput();
- _input.appendField(Blockly.Msg.H)
- this.appendValueInput("B").setCheck("Number");
- this.setInputsInline(!0);
- }
- };
- Blockly.Python.ai_lcd_WH_vision = function (block) {
- var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
- var _y = Blockly.Python.valueToCode(block, "B", Blockly.Python.ORDER_ATOMIC);
- var code = "" + _x + ", " + _y + "";
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks['ai_canvas_area_tuple'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_canvas_area_tuple);
- this.appendValueInput("xy")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_canvas_area_tuple_xy);
- this.appendValueInput("wh")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_canvas_area_tuple_wh);
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_vision_canvas_area_tuple_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_canvas_area_tuple'] = function (block) {
- var value_coordinate = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
- var value_size = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- var code = value_coordinate + ',' + value_size;
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_lane_tracking_run'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/lane_tracking_header.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_from_canvas + Blockly.Msg.ai_vision_lane_tracking_run)
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- // .appendField();
- this.appendValueInput("rgb_value")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_threshold);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_vision_lane_tracking_setup_threshold);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_lane_tracking_run'] = function (block) {
- var value_color = Blockly.Python.valueToCode(block, 'rgb_value', Blockly.Python.ORDER_ATOMIC)
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var code = '' +
- 'line = canvas.find_line()\n' +
- 'canvas.draw_line(line["rect"][0], line["rect"][1], line["rect"][2],line["rect"][3], color=' + value_color + ', thickness=1)\n' +
- 'canvas.draw_line(line["rect"][2], line["rect"][3], line["rect"][4],line["rect"][5], color=' + value_color + ', thickness=1)\n' +
- 'canvas.draw_line(line["rect"][4], line["rect"][5], line["rect"][6],line["rect"][7], color=' + value_color + ', thickness=1)\n' +
- 'canvas.draw_line(line["rect"][6], line["rect"][7], line["rect"][0],line["rect"][1], color=' + value_color + ', thickness=1)\n' +
- 'canvas.draw_circle(line["cx"], line["cy"], 4,color=' + value_color + ', thickness=1)\n';
- return code;
- };
- Blockly.Blocks['ai_vision_find_lines'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/ai_vision_find_line.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_from_canvas)
- .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- .appendField(Blockly.Msg.ai_vision_find_line);
- this.appendValueInput("xy")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_find_line_start_coord);
- this.appendValueInput("wh")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_find_line_size);
- /*this.appendValueInput("threshold")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_find_line_hoffman_threshold);
- this.appendValueInput("theta_margin")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_find_line_merge_theta);
- this.appendValueInput("rho_margin")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_find_line_merge_rho);*/
- this.setOutput(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_vision_find_lines_TOOLTIP);
- this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
- }
- };
- Blockly.Python['ai_vision_find_lines'] = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- //var threshold = Blockly.Python.valueToCode(block, 'threshold', Blockly.Python.ORDER_ATOMIC);
- //var theta_margin = Blockly.Python.valueToCode(block, 'theta_margin', Blockly.Python.ORDER_ATOMIC);
- //var rho_margin = Blockly.Python.valueToCode(block, 'rho_margin', Blockly.Python.ORDER_ATOMIC);
- var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
- var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- var code = variable_name + '.find_lines(roi=(' + xy + ',' + wh + '), threshold = 1000, theta_margin = 25, rho_margin = 25)';
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_vision_find_rects'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/ai_vision_find_rect.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_from_canvas)
- .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- .appendField(Blockly.Msg.ai_vision_find_rect);
- this.appendValueInput("xy")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_find_rect_start_coord);
- this.appendValueInput("wh")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_find_rect_region_size);
- /*this.appendValueInput("threshold")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_find_rect_bounding_threshold);*/
- this.setOutput(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_vision_find_rects_TOOLTIP);
- this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
- }
- };
- Blockly.Python['ai_vision_find_rects'] = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
- var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
- // var threshold = Blockly.Python.valueToCode(block, 'threshold', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- var code = variable_name + '.find_rects(roi=(' + xy + ',' + wh + '), threshold = 10000)';
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_vision_find_lines'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/ai_vision_find_color.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_from_canvas + Blockly.Msg.ai_vision_find_blobs_color_region)
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- // .appendField();
- this.appendValueInput("color")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_threshold);
- this.appendValueInput("xy")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_find_blobs_start_coord);
- this.appendValueInput("wh")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_find_blobs_size);
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_vision_find_blobs_TOOLTIP);
- this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
- }
- };
- Blockly.Python['ai_vision_find_lines'] = function (block) {
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var value_color = Blockly.Python.valueToCode(block, 'color', Blockly.Python.ORDER_ATOMIC);
- var value_xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
- var value_wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_[''] = `
- def v831_find_blob_fun(lane_trackingimg,region1,COLOR):
- IMGBLOB = lane_trackingimg.crop(region1[0],region1[1],region1[2],region1[3])
- blobsCANVAS = IMGBLOB.find_blobs(COLOR, merge=True)
- return blobsCANVAS
- `;
- var code = `v831_find_blob_fun(canvas,(${value_xy},${value_wh}),${value_color})
- `;
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_vision_find_blobs'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/ai_vision_find_color.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_from_canvas + Blockly.Msg.ai_vision_find_lines_color_region)
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- // .appendField();
- this.appendValueInput("color")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_threshold);
- this.appendValueInput("xy")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_find_blobs_start_coord);
- this.appendValueInput("wh")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_find_blobs_size);
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_vision_find_blobs_TOOLTIP);
- this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
- }
- };
- Blockly.Python['ai_vision_find_blobs'] = function (block) {
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var value_color = Blockly.Python.valueToCode(block, 'color', Blockly.Python.ORDER_ATOMIC);
- var value_xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
- var value_wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.addVariable('lane_trackingline', "lane_trackingline1 = {}", true);
- Blockly.Python.definitions_['ai_vision_find_blobs_color'] = `_ld_color_detection_threshold = ${value_color}
- def v831_lane_tracking_setup_one(lane_trackingimg,region1):
- global lane_trackingline
- lane_trackingcanvas = lane_trackingimg.crop(region1[0],region1[1],region1[2],region1[3])
- lane_trackingline = lane_trackingcanvas.find_line()
- lane_trackingcanvas.draw_circle(lane_trackingline["cx"], lane_trackingline["cy"], 2,color=(0,255,0), thickness=1)
- lane_trackingimg.draw_image(lane_trackingcanvas,region1[0],region1[1])
- lane_trackingimg.draw_rectangle(region1[0],region1[1],region1[0]+region1[2],region1[1]+region1[3], color=(255,0,0), thickness=1)
- lane_trackingline["cx"] = lane_trackingline["cx"] + region1[0]
- lane_trackingline["cy"] = lane_trackingline["cy"] + region1[1]
- return lane_trackingline
- `;
- var code = `v831_lane_tracking_setup_one(canvas,(${value_xy},${value_wh}))
- `;
- return [code, Blockly.Python.ORDER_NONE];
- };
- //
- Blockly.Blocks['ai_vision_find_blobs_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.OLCD_LINE_START)
- .appendField(new Blockly.FieldVariable("i"), "varitem")
- .appendField(Blockly.Msg.ai_vision_find_lines_color_region_result)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_models_object_model_x_center, "cx"],
- [Blockly.Msg.ai_models_object_model_y_center, "cy"]
- ]), "value");
- // this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_vision_find_lines_color_region_result);
- }
- };
- Blockly.Python['ai_vision_find_blobs_result'] = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var property = block.getFieldValue('value');
- var code = `${variable_name}.get("${property}")`;
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks['ai_lane_tracking_setup'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/lane_tracking_header.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput().appendField(Blockly.Msg.ai_vision_from_canvas + Blockly.Msg.ai_vision_lane_tracking_setup)
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- // .appendField();
- this.appendValueInput("color")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_threshold);
- this.appendValueInput("lsize")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_l);
- this.appendValueInput("rsize")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_r);
- // this.appendValueInput("axis")
- // .setCheck(null)
- // .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_axis);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_vision_lane_tracking_setup_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_lane_tracking_setup'] = function (block) {
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var value_color = Blockly.Python.valueToCode(block, 'color', Blockly.Python.ORDER_ATOMIC);
- var value_lsize = Blockly.Python.valueToCode(block, 'lsize', Blockly.Python.ORDER_ATOMIC);
- var value_rsize = Blockly.Python.valueToCode(block, 'rsize', Blockly.Python.ORDER_ATOMIC);
- var value_axis = Blockly.Python.valueToCode(block, 'axis', Blockly.Python.ORDER_ATOMIC);
- console.log(value_lsize[0])
- Blockly.Python.addVariable('lane_trackingline1', "lane_trackingline1 = {}", true);
- Blockly.Python.addVariable('lane_trackingline2', "lane_trackingline2 = {}", true);
- Blockly.Python.definitions_['ai_lane_tracking_setup'] = `_ld_color_detection_threshold = ${value_color}
- def v831_lane_tracking_setup(lane_trackingimg,region1,region2):
- global lane_trackingline1,lane_trackingline2
- lane_trackingcanvas1 = lane_trackingimg.crop(region1[0],region1[1],region1[2],region1[3])
- lane_trackingcanvas2 = lane_trackingimg.crop(region2[0],region2[1],region2[2],region2[3])
- lane_trackingline1 = lane_trackingcanvas1.find_line()
- lane_trackingline2 = lane_trackingcanvas2.find_line()
- lane_trackingcanvas1.draw_circle(lane_trackingline1["cx"], lane_trackingline1["cy"], 2,color=(0,255,0), thickness=1)
- lane_trackingcanvas2.draw_circle(lane_trackingline2["cx"], lane_trackingline2["cy"], 2,color=(0,255,0), thickness=1)
- lane_trackingimg.draw_image(lane_trackingcanvas1,region1[0],region1[1])
- lane_trackingimg.draw_image(lane_trackingcanvas2,region2[0],region2[1])
- lane_trackingimg.draw_rectangle(region1[0],region1[1],region1[0]+region1[2],region1[1]+region1[3], color=(255,0,0), thickness=1)
- lane_trackingimg.draw_rectangle(region2[0],region2[1],region2[0]+region2[2],region2[1]+region2[3], color=(255,0,0), thickness=1)
- `
- let code = `v831_lane_tracking_setup(canvas,${value_lsize},${value_rsize})
- `
- return code
- }
- Blockly.Blocks['ai_lane_tracking_get'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_lane_tracking_run_get)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_vision_lane_tracking_run_ld, "left_check"],
- [Blockly.Msg.ai_vision_lane_tracking_run_lv, "left_value"],
- [Blockly.Msg.ai_vision_lane_tracking_run_rd, "right_check"],
- [Blockly.Msg.ai_vision_lane_tracking_run_rv, "right_value"]
- ]), "return");
- this.setOutput(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_vision_lane_tracking_run_get_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_lane_tracking_get'] = function (block) {
- var dropdown_return = block.getFieldValue('return');
- // TODO: Assemble Python into code variable.
- var code = '_ld_return["' + dropdown_return + '"]';
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_vision_color_analyze'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/ai_vision_analyze_color.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_get_canvas + Blockly.Msg.ai_vision_color_analyze_get_result)
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- // .appendField();
- this.appendValueInput("xy")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_color_analyze_start_coord);
- this.appendValueInput("wh")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_vision_color_analyze_size);
- this.setOutput(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_vision_color_analyze_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_vision_color_analyze'] = function (block) {
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
- var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- var code = 'canvas.get_blob_color((' + xy + ', ' + wh + '), 0, 0)';
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_vision_get_blobs'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_from)
- .appendField(new Blockly.FieldVariable("i"), "varitem")
- .appendField(Blockly.Msg.ai_vision_get_blobs_result)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_vision_detection_box_x, "x"],
- [Blockly.Msg.ai_vision_detection_box_y, "y"],
- [Blockly.Msg.ai_models_face_model_ws, "w"],
- [Blockly.Msg.ai_models_face_model_hs, "h"],
- // [Blockly.Msg.ai_vision_detection_box_pixels, "pixels()"],
- [Blockly.Msg.ai_vision_detection_box_cx, "cx"],
- [Blockly.Msg.ai_vision_detection_box_cy, "cy"]
- // [Blockly.Msg.ai_vision_detection_box_degree, "rotation()"],
- // [Blockly.Msg.ai_vision_detection_box_total, "count()"]
- ]), "blob_type");
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_vision_get_blobs_TOOLTIP);
- this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
- }
- };
- Blockly.Python['ai_vision_get_blobs'] = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var type = block.getFieldValue('blob_type');
- // TODO: Assemble Python into code variable.
- var code = `${variable_name}["${type}"]`;
- if (type == "cx") {
- code = `int((${variable_name}["w"] + ${variable_name}["x"] + ${variable_name}["x"])/2)`
- } else if (type == "cy") {
- code = `int((${variable_name}["h"] + ${variable_name}["y"] + ${variable_name}["y"])/2)`
- }
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_vision_get_threshold_default'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_detection_color_threshold_set)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_vision_detection_color_threshold_set_black, "black"],
- [Blockly.Msg.ai_vision_detection_color_threshold_set_white, "white"],
- [Blockly.Msg.ai_vision_detection_color_threshold_set_red, "red"],
- [Blockly.Msg.ai_vision_detection_color_threshold_set_green, "green"],
- [Blockly.Msg.ai_vision_detection_color_threshold_set_blue, "blue"],
- [Blockly.Msg.ai_vision_detection_color_threshold_set_orange, "orange"]
- ]), "color");
- this.setOutput(true, null);
- this.setColour("#f0983e");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('color');
- var TOOLTIPS = {
- 'black': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_black),
- 'white': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_white),
- 'red': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_red),
- 'green': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_green),
- 'blue': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_blue),
- 'orange': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_orange)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_vision_get_threshold_default'] = function (block) {
- var dropdown_color = block.getFieldValue('color');
- // TODO: Assemble Python into code variable.
- if (dropdown_color == "black") {
- var code = '[(0,40)]';
- } else if (dropdown_color == "white") {
- var code = '[(64,100)]';
- } else if (dropdown_color == "red") {
- var code = '[(45, 65, 40, 80, 40, 60)]';
- } else if (dropdown_color == "green") {
- var code = '[(45, 65, -50, -30, 0, 40)]';
- } else if (dropdown_color == "blue") {
- var code = '[(45, 65, -20, 30, -60, -20)]';
- } else if (dropdown_color == "orange") {
- var code = '[(77, 55, 19, 61, 14, 108)]';
- }
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_vision_find_qrcode'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/ai_vision_qrcode_.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField("开始识别二维码")
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- // .appendField();
- this.setOutput(false, null);
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_vision_find_qrcode_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_vision_find_qrcode'] = function (block) {
- // TODO: Assemble Python into code variable.
- var code = 'findQrcode = canvas.find_qrcodes() \n';
- // TODO: Change ORDER_NONE to the correct strength.
- return code;
- };
- Blockly.Blocks['ai_vision_find_qrcode_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField("屏幕显示二维码").
- appendField(new Blockly.FieldDropdown([
- ["源文本", "SourceText"],
- ["检测框", "CheckBox"],
- ]), "qrcode_result")
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- // .appendField();
- this.setOutput(false, null);
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_vision_find_qrcode_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_vision_find_qrcode_result'] = function (block) {
- let qrcode_result = block.getFieldValue('qrcode_result');
- let qrcodeResultAllBlock = getBlocksByTypeName("ai_vision_find_qrcode_result")
- // console.log("qrcode_result",qrcodeResultAllBlock[0].innerText)
- let findQrcodeStr = qrcodeResultAllBlock[0].innerText
- let Source = findQrcodeStr.indexOf("Source") != -1 ? "True" : "False"
- let CheckBox = findQrcodeStr.indexOf("CheckBox") != -1 ? "True" : "False"
- Blockly.Python.addFunction("showQRcodeResult", `def showQRcodeResult(Source,CheckBox):
- global findQrcode
- for i in findQrcode:
- if Source:
- canvas.draw_string((i["x"]),(i["y"]), (i["payload"]), scale = 1, color = (255,0,0) , thickness = 1)
- if CheckBox:
- canvas.draw_rectangle((i["x"]),(i["y"]), (i["x"])+(i["w"]),(i["y"])+ (i["h"]), color=(255,0,0), thickness=1)
- `)
- // TODO: Assemble Python into code variable.
- let code = ""
- if (qrcodeResultAllBlock[0].id == block.id) {
- code = `showQRcodeResult(${Source},${CheckBox})
- `
- }
- // TODO: Change ORDER_NONE to the correct strength.
- return code;
- };
- Blockly.Blocks['ai_vision_qrcode_get_info'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_qrcode_get_result + Blockly.Msg.ai_vision_pattern_detection_content)
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_vision_qrcode_get_result + Blockly.Msg.ai_vision_pattern_detection_content);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_vision_qrcode_get_info'] = function (block) {
- Blockly.Python.addFunction("getQRcodeResult", `def getQRcodeResult():
- global findQrcode
- qrCodeList = []
- for i in findQrcode:
- qrCodeList.append({i["payload"]})
- return qrCodeList
- `)
- let code = "getQRcodeResult()"
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_vision_find_apriltag'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/ai_vision_apriltag_.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_get_canvas + Blockly.Msg.ai_vision_apriltag_detected_result)
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- // .appendField();
- // this.setOutput(true, null);
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_vision_find_apriltag_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_vision_find_apriltag'] = function (block) {
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- // TODO: Assemble Python into code variable.
- var code = 'findApriltags = canvas.find_apriltags(families = 16,fx = (6/5.76)*320,fy = (6/3.24)*240,cx = 160,cy = 120)';
- // TODO: Change ORDER_NONE to the correct strength.
- return code;
- };
- Blockly.Blocks['ai_vision_apriltag_get_info'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_apriltag_get_result)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_vision_pattern_detection_content, "ApriltagId"],
- // [Blockly.Msg.ai_vision_pattern_detection_type_id, "id"],
- [Blockly.Msg.ai_vision_pattern_detection_type_family, "ApriltagCheckout"]
- ]), "get_info");
- this.setInputsInline(false);
- // this.setOutput(true, null);
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null);
- this.setColour("#f0983e");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('get_info');
- var TOOLTIPS = {
- 'payload': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_content),
- 'id': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_content),
- 'family': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_type_family),
- 'x': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_x),
- 'y': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_y),
- 'w': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_w),
- 'h': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_h)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_vision_apriltag_get_info'] = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var dropdown_name = block.getFieldValue('get_info');
- let apriltagAllBlock = getBlocksByTypeName("ai_vision_apriltag_get_info")
- let findQrcodeStr = apriltagAllBlock[0].innerText
- let ApriltagId = findQrcodeStr.indexOf("ApriltagId") != -1 ? "True" : "False"
- let ApriltagCheckout = findQrcodeStr.indexOf("ApriltagCheckout") != -1 ? "True" : "False"
- Blockly.Python.addFunction("getApriltagCanvasResult", `def getApriltagCanvasResult(ApriltagId,ApriltagCheckout):
- global findApriltags
- for i in findApriltags:
- if apriltagId:
- canvas.draw_string((i["x"]),(i["y"]), (i["id"]), scale = 1, color = (255,0,0) , thickness = 1)
- if ApriltagCheckout:
- canvas.draw_rectangle((i["x"]),(i["y"]), (i["x"])+(i["w"]),(i["y"])+ (i["h"]), color=(255,0,0), thickness=1)
- )`)
- // TODO: Assemble Python into code variable.
- var code = `getApriltagCanvasResult(${ApriltagId},${ApriltagCheckout})`;
- // TODO: Change ORDER_NONE to the correct strength.
- return code;
- };
- Blockly.Blocks['ai_vision_find_datamatrices'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_get_canvas + Blockly.Msg.ai_vision_apriltag_detected_result);
- this.setOutput(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_vision_find_datamatrices_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_vision_find_datamatrices'] = function (block) {
- Blockly.Python.addFunction("getApriltagResult", `def getApriltagResult():
- global findApriltags
- if len(findApriltags):
- return findApriltags[0]["id"]
- else:
- return ""
- )`)
- var code = `getApriltagResult()`;
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_vision_datamatrices_get_info'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_from)
- .appendField(new Blockly.FieldVariable("i"), "varitem")
- .appendField(Blockly.Msg.ai_vision_data_matrices_get_result)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_vision_pattern_detection_content, "payload"],
- [Blockly.Msg.ai_vision_pattern_detection_rows, "rows"],
- [Blockly.Msg.ai_vision_pattern_detection_cols, "columns"],
- [Blockly.Msg.ai_vision_pattern_detection_can_tolerate_count, "capacity"],
- [Blockly.Msg.ai_vision_pattern_detection_can_not_tolerate_count, "padding"],
- [Blockly.Msg.ai_vision_pattern_detection_x, "x"],
- [Blockly.Msg.ai_vision_pattern_detection_y, "y"],
- [Blockly.Msg.ai_vision_pattern_detection_w, "w"],
- [Blockly.Msg.ai_vision_pattern_detection_h, "h"]
- ]), "get_info");
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#f0983e");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('get_info');
- var TOOLTIPS = {
- 'payload': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_content),
- 'rows': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_rows),
- 'columns': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_cols),
- 'capacity': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_can_tolerate_count),
- 'padding': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_can_not_tolerate_count),
- 'x': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_x),
- 'y': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_y),
- 'w': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_w),
- 'h': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_h)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_vision_datamatrices_get_info'] = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var dropdown_name = block.getFieldValue('get_info');
- // TODO: Assemble Python into code variable.
- var code = variable_name + '.' + dropdown_name + '()';
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_vision_find_barcodes'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/ai_vision_barcode_.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_get_canvas + Blockly.Msg.ai_vision_barcode_detected_result)
- // .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- // .appendField();
- this.setNextStatement(true);
- this.setPreviousStatement(true);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_vision_find_barcodes_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_vision_find_barcodes'] = function (block) {
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- // TODO: Assemble Python into code variable.
- var code = 'findBarcodes = canvas.find_barcodes() \n';
- // TODO: Change ORDER_NONE to the correct strength.
- return code;
- };
- Blockly.Blocks['ai_vision_barcodes_get_info'] = {
- init: function () {
- this.appendDummyInput()
- .appendField("屏幕显示条形码")
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_vision_pattern_detection_content, "barcodesPayload"],
- [Blockly.Msg.ai_models_face_model_rect, "barcodesCorners"]
- ]), "get_info");
- this.setInputsInline(false);
- this.setOutput(false, null);
- this.setNextStatement(true);
- this.setPreviousStatement(true);
- this.setColour("#f0983e");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('get_info');
- var TOOLTIPS = {
- 'payload': Blockly.Msg.ai_vision_barcodes_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_content),
- 'corners': Blockly.Msg.ai_models_face_model_rect.replace('%1', Blockly.Msg.ai_models_face_model_rect),
- 'x': Blockly.Msg.ai_vision_barcodes_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_x),
- 'y': Blockly.Msg.ai_vision_barcodes_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_y),
- 'w': Blockly.Msg.ai_vision_barcodes_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_w),
- 'h': Blockly.Msg.ai_vision_barcodes_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_h)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_vision_barcodes_get_info'] = function (block) {
- var dropdown_name = block.getFieldValue('get_info');
- let qrcodeResultAllBlock = getBlocksByTypeName("ai_vision_barcodes_get_info")
- // console.log("qrcode_result",qrcodeResultAllBlock[0].innerText)
- let findQrcodeStr = qrcodeResultAllBlock[0].innerText
- let barcodesPayload = findQrcodeStr.indexOf("barcodesPayload") != -1 ? "True" : "False"
- let barcodesCorners = findQrcodeStr.indexOf("barcodesCorners") != -1 ? "True" : "False"
- Blockly.Python.addFunction("showBarcodesResult", `def showBarcodesResult(type1,type2):
- global findBarcodes
- for i in findBarcodes:
- if type1:
- canvas.draw_string((i["corners"][0][0]),(i["corners"][0][1]), (i["payload"]), scale = 1, color = (255,0,0) , thickness = 1)
- if type2:
- x1,y1 = i['corners'][0] #访问字典的列表
- x2,y2 = i['corners'][1]
- x3,y3 = i['corners'][2]
- x4,y4 = i['corners'][3]
- canvas.draw_line(x1, y1, x2, y2, color = (0, 255, 0), thickness = 3)
- canvas.draw_line(x2, y2, x3, y3, color = (0, 255, 0), thickness = 3)
- canvas.draw_line(x3, y3, x4, y4, color = (0, 255, 0), thickness = 3)
- canvas.draw_line(x4, y4, x1, y1, color = (0, 255, 0), thickness = 3)
- `)
- // TODO: Assemble Python into code variable.
- let code = ""
- if (qrcodeResultAllBlock[0].id == block.id) {
- code = `showBarcodesResult(${barcodesPayload},${barcodesCorners})
- `
- }
- return code
- };
- Blockly.Blocks['ai_vision_barcodes_get_info_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.uav_bar_code)
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.uav_bar_code);
- }
- };
- Blockly.Python['ai_vision_barcodes_get_info_result'] = function (block) {
- Blockly.Python.addFunction("getBarcodesResult", `def getBarcodesResult():
- global findBarcodes
- if len(findBarcodes)>0:
- return findBarcodes[0]["payload"]
- else:
- return ""
- `)
- var code = `getBarcodesResult()`;
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_vision_get_circles'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_from)
- .appendField(new Blockly.FieldVariable("i"), "varitem")
- .appendField(Blockly.Msg.ai_vision_find_circle_detected_result)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_vision_find_circle_detected_x, "x()"],
- [Blockly.Msg.ai_vision_find_circle_detected_y, "y()"],
- [Blockly.Msg.ai_vision_find_circle_detected_radius, "r()"]
- ]), "blob_type");
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_vision_get_circles_TOOLTIP);
- this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
- }
- };
- Blockly.Python['ai_vision_get_circles'] = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var type = block.getFieldValue('blob_type');
- var code = variable_name + '.' + type;
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_vision_get_rects'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_from)
- .appendField(new Blockly.FieldVariable("i"), "varitem")
- .appendField(Blockly.Msg.ai_vision_find_rect_detected_result)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_vision_find_rect_detected_x, "x()"],
- [Blockly.Msg.ai_vision_find_rect_detected_y, "y()"],
- [Blockly.Msg.ai_vision_find_rect_detected_w, "w()"],
- [Blockly.Msg.ai_vision_find_rect_detected_h, "h()"],
- [Blockly.Msg.ai_vision_find_rect_detected_tuple, "rect()"],
- [Blockly.Msg.ai_vision_find_rect_detected_corners, "corners()"]
- ]), "blob_type");
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_vision_get_rects_TOOLTIP);
- this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
- }
- };
- Blockly.Python['ai_vision_get_rects'] = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var type = block.getFieldValue('blob_type');
- // TODO: Assemble Python into code variable.
- var code = variable_name + '.' + type;
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_vision_get_lines'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_vision_from)
- .appendField(new Blockly.FieldVariable("i"), "varitem")
- .appendField(Blockly.Msg.ai_vision_find_line_detected_result)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_vision_find_line_detected_start_x, "x1()"],
- [Blockly.Msg.ai_vision_find_line_detected_start_y, "y1()"],
- [Blockly.Msg.ai_vision_find_line_detected_end_x, "x2()"],
- [Blockly.Msg.ai_vision_find_line_detected_end_y, "y2()"],
- [Blockly.Msg.ai_vision_find_line_detected_length, "length()"],
- [Blockly.Msg.ai_vision_find_line_detected_angle, "theta()"]
- ]), "blob_type");
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#f0983e");
- this.setTooltip(Blockly.Msg.ai_vision_get_lines_TOOLTIP);
- this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
- }
- };
- Blockly.Python['ai_vision_get_lines'] = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var type = block.getFieldValue('blob_type');
- // TODO: Assemble Python into code variable.
- var code = variable_name + '.' + type;
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- /*
- _ ___ __ __ _ _
- / \ |_ _| | \/ (_) ___ _ __ ___ _ __ | |__ ___ _ __ ___
- / _ \ | | | |\/| | |/ __| '__/ _ \| '_ \| '_ \ / _ \| '_ \ / _ \
- / ___ \ | | | | | | | (__| | | (_) | |_) | | | | (_) | | | | __/
- /_/ \_\___| |_| |_|_|\___|_| \___/| .__/|_| |_|\___/|_| |_|\___|
- |_|
- */
- Blockly.Blocks['ai_mphone_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/microphone_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_microphone_init);
- this.setPreviousStatement(true);
- this.setNextStatement(true);
- this.setColour("#5fcd8e");
- this.setTooltip(Blockly.Msg.ai_mphone_init_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_mphone_init = function (block) {
- Blockly.Python.definitions_.import_all_mphone = "" +
- "from Maix import GPIO, I2S, FFT\n" +
- "from board import board_info\n" +
- "from fpioa_manager import fm\n" +
- "\n" +
- "sample_rate = 38640\n" +
- "sample_points = 1024\n" +
- "fft_points = 512\n" +
- "hist_x_num = 50\n" +
- "\n" +
- "fm.register(20,fm.fpioa.I2S0_IN_D0, force=True)\n" +
- "fm.register(19,fm.fpioa.I2S0_WS, force=True)\n" +
- "fm.register(18,fm.fpioa.I2S0_SCLK, force=True)\n" +
- "\n" +
- "_recorder_rx = I2S(I2S.DEVICE_0)\n" +
- "_recorder_rx.channel_config(_recorder_rx.CHANNEL_0, _recorder_rx.RECEIVER, align_mode = I2S.STANDARD_MODE)\n" +
- "_recorder_rx.set_sample_rate(sample_rate)\n" +
- "def _microphone_read_average(lst): \n" +
- " return int((sum(lst)/len(lst))*100)\n" +
- "";
- // Blockly.Python.addVariable('sample_rate', "sample_rate = 38640", true);
- // Blockly.Python.addVariable('sample_points', "sample_points = 1024", true);
- // Blockly.Python.addVariable('fft_points', "fft_points = 512", true);
- // Blockly.Python.addVariable('hist_x_num', "hist_x_num = 50", true);
- // Blockly.Python.addVariable('_recorder_rx', "_recorder_rx = None", true);
- // Blockly.Python.addVariable('fft_res', "fft_res = None", true);
- // Blockly.Python.addVariable('fft_amp', "fft_amp = None", true);
- Blockly.Python.addVariable('read_all_channel', "read_all_channel = [0, 0, 0, 0, 0, 0, 0, 0]", true);
- // Blockly.Python.addVariable('_recorder_rx', "", true);
- var _code = "" +
- "";
- return _code;
- }
- Blockly.Blocks['mphone_audio_spectrum_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/ai_audio_spectrum.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_microphone_start_spectrum_analyze);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#5fcd8e");
- this.setTooltip(Blockly.Msg.mphone_audio_spectrum_init_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['mphone_audio_spectrum_init'] = function (block) {
- // TODO: Assemble Python into code variable.
- Blockly.Python.definitions_['v831_import_time'] = `import time`
- var code = "" +
- "time.sleep_ms(10)\n" +
- "_audio = _recorder_rx.record(sample_points)\n" +
- "fft_res = FFT.run(_audio.to_bytes(),fft_points)\n" +
- "fft_amp = FFT.amplitude(fft_res)\n\n" +
- "read_all_channel[0] = int(_microphone_read_average(fft_amp[0:63]))\n" +
- "read_all_channel[1] = int(_microphone_read_average(fft_amp[64:127]))\n" +
- "read_all_channel[2] = int(_microphone_read_average(fft_amp[127:191]))\n" +
- "read_all_channel[3] = int(_microphone_read_average(fft_amp[192:255]))\n" +
- "read_all_channel[4] = int(_microphone_read_average(fft_amp[256:319]))\n" +
- "read_all_channel[5] = int(_microphone_read_average(fft_amp[320:383]))\n" +
- "read_all_channel[6] = int(_microphone_read_average(fft_amp[384:447]))\n" +
- "read_all_channel[7] = int(_microphone_read_average(fft_amp[448:514]))\n" +
- "";
- return code;
- };
- Blockly.Blocks['ai_mphone_read_sound_sensitivity'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_microphone_get_spectrum_analyze_result)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_1, "0"],
- [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_2, "1"],
- [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_3, "2"],
- [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_4, "3"],
- [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_5, "4"],
- [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_6, "5"],
- [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_7, "6"],
- [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_8, "7"]
- ]), "level");
- this.setOutput(true, null);
- this.setColour("#5fcd8e");
- this.setTooltip(Blockly.Msg.ai_mphone_read_sound_sensitivity_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_mphone_read_sound_sensitivity'] = function (block) {
- var dropdown_level = block.getFieldValue('level');
- // TODO: Assemble Python into code variable.
- var code = 'read_all_channel[' + dropdown_level + ']';
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_mphone_Record_audio_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/microphone_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_mphone_Record_audio_init);
- this.setPreviousStatement(true);
- this.setNextStatement(true);
- this.setColour("#5fcd8e");
- this.setTooltip(Blockly.Msg.ai_mphone_Record_audio_init_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_mphone_Record_audio_init = function (block) {
- Blockly.Python.definitions_.import_ai_mphone_Record_audio_init = "" +
- "from Maix import GPIO, I2S\n" +
- "from fpioa_manager import fm\n" +
- 'import audio\n' +
- "\n" +
- '# user setting\n' +
- "sample_rate = 16000\n" +
- "# default seting\n" +
- "sample_points = 2048\n" +
- "wav_ch = 2\n" +
- "\n" +
- 'fm.register(8, fm.fpioa.GPIO0, force=True)\n' +
- 'wifi_en = GPIO(GPIO.GPIO0, GPIO.OUT)\n' +
- 'wifi_en.value(0)\n' +
- "\n" +
- "fm.register(20,fm.fpioa.I2S0_IN_D0, force=True)\n" +
- "fm.register(19,fm.fpioa.I2S0_WS, force=True)\n" +
- "fm.register(18,fm.fpioa.I2S0_SCLK, force=True)\n" +
- "\n" +
- "rx = I2S(I2S.DEVICE_0)\n" +
- "rx.channel_config(rx.CHANNEL_0, rx.RECEIVER, align_mode=I2S.STANDARD_MODE)\n" +
- "rx.set_sample_rate(sample_rate)\n" +
- "print(rx)\n" +
- "";
- var _code = "" +
- "";
- return _code;
- }
- Blockly.Blocks['ai_mphone_record_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_microphone_init);
- this.setPreviousStatement(true);
- this.setNextStatement(true, null);
- this.setColour("#5fcd8e");
- this.setTooltip(Blockly.Msg.ai_microphone_init);
- this.setHelpUrl("");
- }
- }
- Blockly.Python['ai_mphone_record_init'] = function (block) {
- Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio`
- Blockly.Python.definitions_['v831_import_wave'] = `import wave`
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- let code = ''
- return code;
- }
- Blockly.Blocks['ai_mphone_record_setting'] = {
- init: function () {
- this.appendValueInput("record_time").setCheck(null)
- .appendField(Blockly.Msg.ai_mphone_Record_audio_start_time)
- this.appendValueInput("path")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_mphone_Record_audio_start_path);
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_mphone_Record_audio_start);
- this.setPreviousStatement(true);
- this.setNextStatement(true, null);
- this.setInputsInline(false);
- this.setColour("#5fcd8e");
- this.setTooltip(Blockly.Msg.ai_mphone_Record_audio_start);
- this.setHelpUrl("");
- }
- }
- Blockly.Python['ai_mphone_record_setting'] = function (block) {
- var value_path = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
- var record_time = Blockly.Python.valueToCode(block, 'record_time', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio`
- Blockly.Python.definitions_['v831_import_wave'] = `import wave`
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- let code = `if(os.path.exists(${value_path})):
- os.system("rm ${value_path.slice(1, value_path.length - 1)}")
- CHUNK = 1024
- FORMAT = pyaudio.paInt16
- CHANNELS = 1
- RATE = 16000
- RECORD_SECONDS = ${Number(record_time) + 1}
- WAVE_OUTPUT_FILENAME = ${value_path}
- p = pyaudio.PyAudio()
- stream = p.open(format=FORMAT,channels=CHANNELS,rate=RATE,input=True,frames_per_buffer=CHUNK)
- print("* recording")
-
- frames = []
-
- for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
- data = stream.read(CHUNK,exception_on_overflow = False)
- frames.append(data)
-
- print("* done recording")
-
- stream.stop_stream()
- stream.close()
- p.terminate()
-
- wf = wave.open(WAVE_OUTPUT_FILENAME, "wb")
- wf.setnchannels(CHANNELS)
- wf.setsampwidth(p.get_sample_size(FORMAT))
- wf.setframerate(RATE)
- wf.writeframes(b"".join(frames))
- wf.close()
- `
- return code;
- }
- Blockly.Blocks['ai_mphone_Record_audio_start'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_mphone_Record_audio_start);
- this.setPreviousStatement(true);
- this.setNextStatement(true, null);
- this.setColour("#5fcd8e");
- this.setTooltip(Blockly.Msg.ai_mphone_Record_audio_start_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_mphone_Record_audio_start'] = function (block) {
- var code = `
- print("* recording")
-
- frames = []
-
- for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
- data = stream.read(CHUNK,exception_on_overflow = False)
- frames.append(data)
-
- print("* done recording")
-
- stream.stop_stream()
- stream.close()
- p.terminate()
-
- wf = wave.open(WAVE_OUTPUT_FILENAME, "wb")
- wf.setnchannels(CHANNELS)
- wf.setsampwidth(p.get_sample_size(FORMAT))
- wf.setframerate(RATE)
- wf.writeframes(b"".join(frames))
- wf.close()
- `;
- return code;
- };
- Blockly.Blocks['ai_audio_start_recording'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_audio_play_music_file);
- this.appendValueInput("path")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_audio_play_music_file_set_file_path);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#5fcd8e");
- this.setTooltip(Blockly.Msg.ai_audio_stop_recording_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_audio_start_recording'] = function (block) {
- // TODO: Assemble Python into code variable.
- Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio`
- Blockly.Python.definitions_['v831_import_wave'] = `import wave`
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- var code = `
- CHUNK = 1024
- wf = wave.open(r"test.wav", "rb")#(sys.argv[1], "rb"
- p = pyaudio.PyAudio()
-
- stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
- channels=wf.getnchannels(),
- rate=wf.getframerate(),
- output=True)
-
- data = wf.readframes(CHUNK)
-
- while len(data) > 0:
- stream.write(data)
- data = wf.readframes(CHUNK)
-
- stream.stop_stream()
- stream.close()
-
- p.terminate()
- `;
- return code;
- };
- /*
- _ ___ _ _ _
- / \ |_ _| / \ _ _ __| (_) ___
- / _ \ | | / _ \| | | |/ _` | |/ _ \
- / ___ \ | | / ___ \ |_| | (_| | | (_) |
- /_/ \_\___| /_/ \_\__,_|\__,_|_|\___/
- */
- Blockly.Blocks['ai_audio_play_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.AUDIO_S);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#603ea0");
- this.setTooltip("");
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_audio_play_init'] = function (block) {
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio`
- Blockly.Python.definitions_['v831_import_wave'] = `import wave`
- Blockly.Python.definitions_['v831_import_time'] = `import time`
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.addVariable("VOICESTATE", "VOICESTATE = 0", true)
- Blockly.Python.addVariable("VOICEDATA", "", true)
- Blockly.Python.addVariable("VOICESTREAM", 'VOICESTREAM = ""', true)
- Blockly.Python.addVariable("VOICEPYAUDIO", "VOICEPYAUDIO = pyaudio.PyAudio()", true)
- Blockly.Python.addVariable("CHUNK", "CHUNK = 1024", true)
- Blockly.Python.addVariable("VOICEPPATH", "", true)
- Blockly.Python.addVariable("VOICEPLAYSTATE", 'VOICEPLAYSTATE = True', true)
- Blockly.Python.addVariable("VOICEWF", 'VOICEWF = ""', true)
- var _code = ``;
- return _code;
- };
- Blockly.Blocks['ai_audio_play_volume'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol)
- .appendField(new Blockly.FieldNumber(25, 0, 100), "play_vol")
- .appendField("(0~100)");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#603ea0");
- this.setTooltip("");
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_audio_play_volume'] = function (block) {
- var number_play_vol = block.getFieldValue('play_vol');
- Blockly.Python.definitions_['systemVoice_numberMap'] = `def voice_numberMap(value):
- valueScaled = float(value - 0) / float(100)
- return int(valueScaled * 31)
- `
- var _code = `VOICENUMP = str(voice_numberMap(${number_play_vol}))
- time.sleep(0.01)
- SYSTEMVOICE = "amixer cset numid=8,iface=MIXER,name=\\"LINEOUT volume\\" "+ VOICENUMP+""
- `;
- return _code;
- };
- Blockly.Blocks['ai_audio_play_song'] = {
- init: function () {
- this.appendValueInput("path")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_audio_play_music_file_set_file_path)
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol)
- .appendField(new Blockly.FieldNumber(25, 0, 100), "play_vol")
- .appendField("(0~100)");
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_audio_start_play);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#603ea0");
- this.setTooltip(Blockly.Msg.ai_audio_start_play);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_audio_play_song'] = function (block) {
- var path_to_video = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
- var number_play_vol = block.getFieldValue('play_vol');
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio`
- Blockly.Python.definitions_['v831_import_wave'] = `import wave`
- Blockly.Python.definitions_['v831_import_time'] = `import time`
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.addVariable("CHUNK", "CHUNK = 1024", true)
- Blockly.Python.definitions_['systemVoice_numberMap'] = `def voice_numberMap(value):
- valueScaled = float(value - 0) / float(100)
- return int(valueScaled * 31)
- VOICENUMP = str(voice_numberMap(${number_play_vol}))
- time.sleep(0.01)
- SYSTEMVOICE = "amixer cset numid=8,iface=MIXER,name=\\"LINEOUT volume\\" "+ VOICENUMP+""
- os.system(SYSTEMVOICE)
- `
- // Blockly.Python.addVariable("VOICEPPATH","",false)
- var _code = `
- wf = wave.open(${path_to_video}, "rb")#(sys.argv[1], "rb"
- p = pyaudio.PyAudio()
-
- stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),channels=wf.getnchannels(),rate=wf.getframerate(),output=True)
-
- data = wf.readframes(CHUNK)
- while len(data) > 0:
- stream.write(data)
- data = wf.readframes(CHUNK)
-
- stream.stop_stream()
- stream.close()
-
- p.terminate()
- `;
- return _code;
- };
- Blockly.Blocks['ai_audio_play_start'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_audio_start_play);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#603ea0");
- this.setTooltip(Blockly.Msg.ai_audio_start_play);
- this.setHelpUrl("");
- }
- }
- Blockly.Python['ai_audio_play_start'] = function (block) {
- Blockly.Python.definitions_["VoicePlayState"] = `def VoicePlayState():
- global VOICESTATE,VOICEDATA,CHUNK,VOICESTREAM,VOICEPYAUDIO,VOICEWF,VOICEPPATH
- if VOICESTATE == 0:
- VOICEWF = wave.open(VOICEPPATH, "rb")#(sys.argv[1], "rb"
- VOICEPYAUDIO = pyaudio.PyAudio()
- VOICESTREAM = VOICEPYAUDIO.open(format=VOICEPYAUDIO.get_format_from_width(VOICEWF.getsampwidth()),channels=VOICEWF.getnchannels(),rate=VOICEWF.getframerate(),output=True)
- VOICEDATA = VOICEWF.readframes(CHUNK)
- VOICESTATE = 1
- return True
- else:
- if len(VOICEDATA) > 0:
- try:
- VOICESTREAM.write(VOICEDATA)
- VOICEDATA = VOICEWF.readframes(CHUNK)
- return True
- except:
- VOICESTATE = 0
- else:
- VOICESTREAM.stop_stream()
- VOICESTREAM.close()
- VOICEPYAUDIO.terminate()
- VOICESTATE = 0
- return False
- `
- let code = `VOICEPLAYSTATE = VoicePlayState()
- `
- return code;
- }
- Blockly.Blocks['ai_audio_play_finish'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_audio_end_play);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#603ea0");
- this.setTooltip("");
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_audio_play_finish'] = function (block) {
- // TODO: Assemble Python into code variable.
- var code = `try:
- VOICESTREAM.stop_stream()
- VOICESTREAM.close()
- VOICEPYAUDIO.terminate()
- VOICESTATE = 0
- except:
- pass
- `;
- return code;
- };
- Blockly.Blocks['ai_audio_get_play_status'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_audio_get_play_status);
- this.setOutput(true, null);
- this.setColour("#603ea0");
- this.setTooltip(Blockly.Msg.ai_audio_play_state_speaker_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_audio_get_play_status'] = function (block) {
- // TODO: Assemble Python into code variable.
- var code = 'VOICEPLAYSTATE';
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- // 在线语音识别
- Blockly.Blocks['ai_online_voice_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.online_voice_init); //
- this.appendValueInput("A").setCheck(null).appendField('APP ID');
- this.appendValueInput("B").setCheck(null).appendField('API Secret');
- this.appendValueInput("C").setCheck(null).appendField('API Key'); //Blockly.Msg.online_voice_init_path
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.online_voice_init);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_online_voice_init'] = function (block) {
- var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
- var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
- var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- Blockly.Python.definitions_['v831_import_time'] = `import time`
- Blockly.Python.definitions_['v831_import_websocket'] = `import websocket`
- Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
- Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
- Blockly.Python.definitions_['v831_import_base64'] = `import base64`
- Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
- Blockly.Python.definitions_['v831_import_json'] = `import json`
- Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode`
- Blockly.Python.definitions_['v831_import_ssl'] = `import ssl`
- Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time`
- Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime`
- Blockly.Python.definitions_['v831_import_thread_as_thread'] = `import _thread as thread`
- Blockly.Python.definitions_.ai_online_voice_init = `
- STATUS_FIRST_FRAME = 0 # 第一帧的标识
- STATUS_CONTINUE_FRAME = 1 # 中间帧标识
- STATUS_LAST_FRAME = 2 # 最后一帧的标识
- class Ws_Param_voice(object):
- # 初始化
- def __init__(self, APPID, APIKey, APISecret, AudioFile):
- self.APPID_voice = APPID
- self.APIKey_voice = APIKey
- self.APISecret_voice = APISecret
- self.AudioFile_voice = AudioFile
-
- # 公共参数(common)
- self.CommonArgs = {"app_id": self.APPID_voice}
- # 业务参数(business),更多个性化参数可在官网查看
- self.BusinessArgs = {"domain": "iat", "language": "zh_cn", "accent": "mandarin", "vinfo":1,"vad_eos":10000}
-
- # 生成url
- def create_url_voice(self):
- url = "wss://ws-api.xfyun.cn/v2/iat"
- # 生成RFC1123格式的时间戳
- now = datetime.now()
- date = format_date_time(mktime(now.timetuple()))
-
- # 拼接字符串
- signature_origin = "host: " + "ws-api.xfyun.cn" + "\\n"
- signature_origin += "date: " + date + "\\n"
- signature_origin += "GET " + "/v2/iat " + "HTTP/1.1"
- # 进行hmac-sha256进行加密
- signature_sha = hmac.new(self.APISecret_voice .encode("utf-8"), signature_origin.encode("utf-8"),
- digestmod=hashlib.sha256).digest()
- signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
-
- authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (self.APIKey_voice , "hmac-sha256", "host date request-line", signature_sha)
- authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8")
- # 将请求的鉴权参数组合为字典
- v = {
- "authorization": authorization,
- "date": date,
- "host": "ws-api.xfyun.cn"
- }
- # 拼接鉴权参数,生成url
- url = url + "?" + urlencode(v)
- # print("date: ",date)
- # print("v: ",v)
- # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致
- # print('websocket url :', url)
- return url
-
-
- # 收到websocket消息的处理
- def on_message_voice(ws, message):
- global asr_result,txt_result
- try:
- code = json.loads(message)["code"]
- sid = json.loads(message)["sid"]
- if code != 0:
- errMsg = json.loads(message)["message"]
- print("sid:%s call error:%s code is:%s" % (sid, errMsg, code))
-
- else:
- data = json.loads(message)["data"]["result"]["ws"]
- # print(json.loads(message))
- result = ""
- for i in data:
- for w in i["cw"]:
- result += w["w"]
- print("sid:%s call success!,data is:%s" % (sid, json.dumps(data, ensure_ascii=False)))
- print("json.dumps(data, ensure_ascii=False)",eval(json.dumps(data, ensure_ascii=False)))
- asr_result.append(eval(json.dumps(data, ensure_ascii=False)))
- txt_result.append(eval(json.dumps(data, ensure_ascii=False)[1]))
- except Exception as e:
- print("receive msg,but parse exception:", e)
-
-
-
- # 收到websocket错误的处理
- def on_error_voice(ws, error):
- print("### error:", error)
-
-
- # 收到websocket关闭的处理
- def on_close_voice(ws):
- print("### closed ###")
-
-
- # 收到websocket连接建立的处理
- def on_open_voice(ws):
- def run_voice(*args):
- global wsParam_voice
- frameSize = 8000 # 每一帧的音频大小
- intervel = 0.04 # 发送音频间隔(单位:s)
- status = STATUS_FIRST_FRAME # 音频的状态信息,标识音频是第一帧,还是中间帧、最后一帧
-
- with open(wsParam_voice.AudioFile_voice, "rb") as fp:
- while True:
- buf = fp.read(frameSize)
- # 文件结束
- if not buf:
- status = STATUS_LAST_FRAME
- # 第一帧处理
- # 发送第一帧音频,带business 参数
- # appid 必须带上,只需第一帧发送
- if status == STATUS_FIRST_FRAME:
-
- d = {"common": wsParam_voice.CommonArgs,
- "business": wsParam_voice.BusinessArgs,
- "data": {"status": 0, "format": "audio/L16;rate=16000",
- "audio": str(base64.b64encode(buf), "utf-8"),
- "encoding": "raw"}}
- d = json.dumps(d)
- ws.send(d)
- status = STATUS_CONTINUE_FRAME
- # 中间帧处理
- elif status == STATUS_CONTINUE_FRAME:
- d = {"data": {"status": 1, "format": "audio/L16;rate=16000",
- "audio": str(base64.b64encode(buf), "utf-8"),
- "encoding": "raw"}}
- ws.send(json.dumps(d))
- # 最后一帧处理
- elif status == STATUS_LAST_FRAME:
- d = {"data": {"status": 2, "format": "audio/L16;rate=16000",
- "audio": str(base64.b64encode(buf), "utf-8"),
- "encoding": "raw"}}
- ws.send(json.dumps(d))
- time.sleep(1)
- break
- # 模拟音频采样间隔
- time.sleep(intervel)
- ws.close()
-
- thread.start_new_thread(run_voice, ())
-
- asr_result=[]
- txt_result=[]
- APPId_voice = ${APPId}
- APISecret_voice = ${APISecret}
- APIKey_voice = ${APIKey}
- `
- var code = '';
- return code;
- };
- // 在线语音识别加载
- Blockly.Blocks['ai_online_voice_loading'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.online_voice_loading); //
- this.appendValueInput("A").setCheck(null).appendField('APP ID');
- this.appendValueInput("B").setCheck(null).appendField('API Secret');
- this.appendValueInput("C").setCheck(null).appendField('API Key');
- this.appendValueInput("path").setCheck(null).appendField(Blockly.Msg.online_voice_init_path);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.online_voice_loading);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_online_voice_loading'] = function (block) {
- var AudioFile = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
- var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
- var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
- var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- Blockly.Python.definitions_['v831_import_time'] = `import time`
- Blockly.Python.definitions_['v831_import_websocket'] = `import websocket`
- Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
- Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
- Blockly.Python.definitions_['v831_import_base64'] = `import base64`
- Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
- Blockly.Python.definitions_['v831_import_json'] = `import json`
- Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode`
- Blockly.Python.definitions_['v831_import_ssl'] = `import ssl`
- Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time`
- Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime`
- Blockly.Python.definitions_['v831_import_thread_as_thread'] = `import _thread as thread`
- Blockly.Python.definitions_.ai_online_voice_init = `
- STATUS_FIRST_FRAME = 0 # 第一帧的标识
- STATUS_CONTINUE_FRAME = 1 # 中间帧标识
- STATUS_LAST_FRAME = 2 # 最后一帧的标识
- class Ws_Param_voice(object):
- # 初始化
- def __init__(self, APPID, APIKey, APISecret, AudioFile):
- self.APPID_voice = APPID
- self.APIKey_voice = APIKey
- self.APISecret_voice = APISecret
- self.AudioFile_voice = AudioFile
-
- # 公共参数(common)
- self.CommonArgs = {"app_id": self.APPID_voice}
- # 业务参数(business),更多个性化参数可在官网查看
- self.BusinessArgs = {"domain": "iat", "language": "zh_cn", "accent": "mandarin", "vinfo":1,"vad_eos":10000}
-
- # 生成url
- def create_url_voice(self):
- url = "wss://ws-api.xfyun.cn/v2/iat"
- # 生成RFC1123格式的时间戳
- now = datetime.now()
- date = format_date_time(mktime(now.timetuple()))
-
- # 拼接字符串
- signature_origin = "host: " + "ws-api.xfyun.cn" + "\\n"
- signature_origin += "date: " + date + "\\n"
- signature_origin += "GET " + "/v2/iat " + "HTTP/1.1"
- # 进行hmac-sha256进行加密
- signature_sha = hmac.new(self.APISecret_voice .encode("utf-8"), signature_origin.encode("utf-8"),
- digestmod=hashlib.sha256).digest()
- signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
-
- authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (self.APIKey_voice , "hmac-sha256", "host date request-line", signature_sha)
- authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8")
- # 将请求的鉴权参数组合为字典
- v = {
- "authorization": authorization,
- "date": date,
- "host": "ws-api.xfyun.cn"
- }
- # 拼接鉴权参数,生成url
- url = url + "?" + urlencode(v)
- # print("date: ",date)
- # print("v: ",v)
- # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致
- # print('websocket url :', url)
- return url
-
-
- # 收到websocket消息的处理
- def on_message_voice(ws, message):
- global asr_result,txt_result
- try:
- code = json.loads(message)["code"]
- sid = json.loads(message)["sid"]
- if code != 0:
- errMsg = json.loads(message)["message"]
- print("sid:%s call error:%s code is:%s" % (sid, errMsg, code))
-
- else:
- data = json.loads(message)["data"]["result"]["ws"]
- # print(json.loads(message))
- result = ""
- for i in data:
- for w in i["cw"]:
- result += w["w"]
- print("sid:%s call success!,data is:%s" % (sid, json.dumps(data, ensure_ascii=False)))
- print("json.dumps(data, ensure_ascii=False)",eval(json.dumps(data, ensure_ascii=False)))
- asr_result.append(eval(json.dumps(data, ensure_ascii=False)))
- txt_result.append(eval(json.dumps(data, ensure_ascii=False)[1]))
- except Exception as e:
- print("receive msg,but parse exception:", e)
-
-
-
- # 收到websocket错误的处理
- def on_error_voice(ws, error):
- print("### error:", error)
-
-
- # 收到websocket关闭的处理
- def on_close_voice(ws):
- print("### closed ###")
-
-
- # 收到websocket连接建立的处理
- def on_open_voice(ws):
- def run_voice(*args):
- global wsParam_voice
- frameSize = 8000 # 每一帧的音频大小
- intervel = 0.04 # 发送音频间隔(单位:s)
- status = STATUS_FIRST_FRAME # 音频的状态信息,标识音频是第一帧,还是中间帧、最后一帧
-
- with open(wsParam_voice.AudioFile_voice, "rb") as fp:
- while True:
- buf = fp.read(frameSize)
- # 文件结束
- if not buf:
- status = STATUS_LAST_FRAME
- # 第一帧处理
- # 发送第一帧音频,带business 参数
- # appid 必须带上,只需第一帧发送
- if status == STATUS_FIRST_FRAME:
-
- d = {"common": wsParam_voice.CommonArgs,
- "business": wsParam_voice.BusinessArgs,
- "data": {"status": 0, "format": "audio/L16;rate=16000",
- "audio": str(base64.b64encode(buf), "utf-8"),
- "encoding": "raw"}}
- d = json.dumps(d)
- ws.send(d)
- status = STATUS_CONTINUE_FRAME
- # 中间帧处理
- elif status == STATUS_CONTINUE_FRAME:
- d = {"data": {"status": 1, "format": "audio/L16;rate=16000",
- "audio": str(base64.b64encode(buf), "utf-8"),
- "encoding": "raw"}}
- ws.send(json.dumps(d))
- # 最后一帧处理
- elif status == STATUS_LAST_FRAME:
- d = {"data": {"status": 2, "format": "audio/L16;rate=16000",
- "audio": str(base64.b64encode(buf), "utf-8"),
- "encoding": "raw"}}
- ws.send(json.dumps(d))
- time.sleep(1)
- break
- # 模拟音频采样间隔
- time.sleep(intervel)
- ws.close()
-
- thread.start_new_thread(run_voice, ())
-
- asr_result=[]
- txt_result=[]
- APPId_voice = ${APPId}
- APISecret_voice = ${APISecret}
- APIKey_voice = ${APIKey}
- `
- Blockly.Python.definitions_['get_online_voice_data'] = `asr_string=""
- def getVoiceData():
- global wsParam_voice,asr_string,txt_result,asr_result
- # 测试时候在此处正确填写相关信息即可运行
- asr_string = ""
- txt_result = []
- asr_result = []
- time1 = datetime.now()
- wsParam_voice = Ws_Param_voice(APPID=APPId_voice, APISecret=APISecret_voice,
- APIKey=APIKey_voice,
- AudioFile=${AudioFile})
- websocket.enableTrace(False)
- wsUrl = wsParam_voice.create_url_voice()
- ws = websocket.WebSocketApp(wsUrl, on_message=on_message_voice, on_error=on_error_voice)
- ws.on_open = on_open_voice
- ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
- time2 = datetime.now()
- for i in range(len(asr_result)):
- for j in range(len(asr_result[i])):
- txt_result.append(asr_result[i][j]["cw"][0]["w"])
- print("txt_result:", txt_result)
- for i in range(len(txt_result)):
- asr_string=asr_string+txt_result[i]
- print("asr_string:", asr_string)
- return asr_string
- `
- let code = `VoiceResult = getVoiceData()
- `;
- return code;
- };
- Blockly.Blocks['ai_online_voice_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.online_voice_result); //
- this.setOutput(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.online_voice_result);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_online_voice_result'] = function (block) {
- let code = `VoiceResult`;
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- // 在线人脸识别
- Blockly.Blocks['ai_online_ident_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.online_face_init); //
- this.appendValueInput("A").setCheck(null).appendField('APP ID');
- this.appendValueInput("B").setCheck(null).appendField('API Secret');
- this.appendValueInput("C").setCheck(null).appendField('API Key');
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.online_face_init);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_online_ident_init'] = function (block) {
- var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
- var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
- var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
- Blockly.Python.definitions_['v831_import_base64'] = `import base64`
- Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
- Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime`
- Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
- Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time`
- Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode`
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- Blockly.Python.definitions_['v831_import_traceback'] = `import traceback`
- Blockly.Python.definitions_['v831_import_json'] = `import json`
- Blockly.Python.definitions_['v831_import_requests'] = `import requests`
- Blockly.Python.definitions_.ai_online_ident_init = `
- class AssembleHeaderException(Exception):
- def __init__(self, msg):
- self.message = msg
- class Url:
- def __init__(this, host, path, schema):
- this.host = host
- this.path = path
- this.schema = schema
- pass
- # 进行sha256加密和base64编码
- def sha256base64(data):
- sha256 = hashlib.sha256()
- sha256.update(data)
- digest = base64.b64encode(sha256.digest()).decode(encoding="utf-8")
- return digest
- def parse_url_face(requset_url):
- stidx = requset_url.index("://")
- host = requset_url[stidx + 3:]
- schema = requset_url[:stidx + 3]
- edidx = host.index("/")
- if edidx <= 0:
- raise AssembleHeaderException("invalid request url:" + requset_url)
- path = host[edidx:]
- host = host[:edidx]
- u = Url(host, path, schema)
- return u
- def assemble_ws_auth_url_face(requset_url, method="GET", api_key="", api_secret=""):
- u = parse_url_face(requset_url)
- host = u.host
- path = u.path
- now = datetime.now()
- date = format_date_time(mktime(now.timetuple()))
- print(date)
- # date = "Thu, 12 Dec 2019 01:57:27 GMT"
- signature_origin = "host: {}\\ndate: {}\\n{} {} HTTP/1.1".format(host, date, method, path)
- print(signature_origin)
- signature_sha = hmac.new(api_secret.encode("utf-8"), signature_origin.encode("utf-8"),
- digestmod=hashlib.sha256).digest()
- signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
- authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (
- api_key, "hmac-sha256", "host date request-line", signature_sha)
- authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8")
- print(authorization_origin)
- values = {
- "host": host,
- "date": date,
- "authorization": authorization
- }
- return requset_url + "?" + urlencode(values)
- def gen_body_face(appid, img_path, server_id):
- with open(img_path, "rb") as f:
- img_data = f.read()
- body = {
- "header": {
- "app_id": appid,
- "status": 3
- },
- "parameter": {
- server_id: {
- "service_kind": "face_detect",
- #"detect_points": "1", #检测特征点
- #"detect_property": "1", #检测人脸属性
- "face_detect_result": {
- "encoding": "utf8",
- "compress": "raw",
- "format": "json"
- }
- }
- },
- "payload": {
- "input1": {
- "encoding": "jpg",
- "status": 3,
- "image": str(base64.b64encode(img_data), "utf-8")
- }
- }
- }
- return json.dumps(body)
- APPId_face = ${APPId}
- APISecret_face = ${APISecret}
- APIKey_face = ${APIKey}
- `;
- let code = ''
- return code;
- };
- // 在线人脸识别加载
- Blockly.Blocks['ai_online_ident_loading'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.online_face_loading); //
- this.appendValueInput("A").setCheck(null).appendField('APP ID');
- this.appendValueInput("B").setCheck(null).appendField('API Secret');
- this.appendValueInput("C").setCheck(null).appendField('API Key');
- this.appendValueInput("path")
- .setCheck(null)
- .appendField(Blockly.Msg.online_face_init_path); //
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.online_face_loading);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_online_ident_loading'] = function (block) {
- var path = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
- var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
- var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
- var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
- Blockly.Python.definitions_['v831_import_base64'] = `import base64`
- Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
- Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime`
- Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
- Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time`
- Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode`
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- Blockly.Python.definitions_['v831_import_traceback'] = `import traceback`
- Blockly.Python.definitions_['v831_import_json'] = `import json`
- Blockly.Python.definitions_['v831_import_requests'] = `import requests`
- Blockly.Python.definitions_.ai_online_ident_init = `
- class AssembleHeaderException(Exception):
- def __init__(self, msg):
- self.message = msg
- class Url:
- def __init__(this, host, path, schema):
- this.host = host
- this.path = path
- this.schema = schema
- pass
- # 进行sha256加密和base64编码
- def sha256base64(data):
- sha256 = hashlib.sha256()
- sha256.update(data)
- digest = base64.b64encode(sha256.digest()).decode(encoding="utf-8")
- return digest
- def parse_url_face(requset_url):
- stidx = requset_url.index("://")
- host = requset_url[stidx + 3:]
- schema = requset_url[:stidx + 3]
- edidx = host.index("/")
- if edidx <= 0:
- raise AssembleHeaderException("invalid request url:" + requset_url)
- path = host[edidx:]
- host = host[:edidx]
- u = Url(host, path, schema)
- return u
- def assemble_ws_auth_url_face(requset_url, method="GET", api_key="", api_secret=""):
- u = parse_url_face(requset_url)
- host = u.host
- path = u.path
- now = datetime.now()
- date = format_date_time(mktime(now.timetuple()))
- print(date)
- # date = "Thu, 12 Dec 2019 01:57:27 GMT"
- signature_origin = "host: {}\\ndate: {}\\n{} {} HTTP/1.1".format(host, date, method, path)
- print(signature_origin)
- signature_sha = hmac.new(api_secret.encode("utf-8"), signature_origin.encode("utf-8"),
- digestmod=hashlib.sha256).digest()
- signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
- authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (
- api_key, "hmac-sha256", "host date request-line", signature_sha)
- authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8")
- print(authorization_origin)
- values = {
- "host": host,
- "date": date,
- "authorization": authorization
- }
- return requset_url + "?" + urlencode(values)
- def gen_body_face(appid, img_path, server_id):
- with open(img_path, "rb") as f:
- img_data = f.read()
- body = {
- "header": {
- "app_id": appid,
- "status": 3
- },
- "parameter": {
- server_id: {
- "service_kind": "face_detect",
- #"detect_points": "1", #检测特征点
- #"detect_property": "1", #检测人脸属性
- "face_detect_result": {
- "encoding": "utf8",
- "compress": "raw",
- "format": "json"
- }
- }
- },
- "payload": {
- "input1": {
- "encoding": "jpg",
- "status": 3,
- "image": str(base64.b64encode(img_data), "utf-8")
- }
- }
- }
- return json.dumps(body)
- APPId_face = ${APPId}
- APISecret_face = ${APISecret}
- APIKey_face = ${APIKey}
- `;
- Blockly.Python.definitions_.online_ident = `
- ONLINE_IDENT_DATA = ""
- def run_face(appid, apikey, apisecret, img_path, server_id="s67c9c78c"):
- url = "http://api.xf-yun.com/v1/private/{}".format(server_id)
- request_url = assemble_ws_auth_url_face(url, "POST", apikey, apisecret)
- headers = {"content-type": "application/json", "host": "api.xf-yun.com", "app_id": appid}
- print(request_url)
- response = requests.post(request_url, data=gen_body_face(appid, img_path, server_id), headers=headers)
- resp_data = json.loads(response.content.decode("utf-8"))
- print(resp_data)
- picRes=base64.b64decode(resp_data["payload"]["face_detect_result"]["text"]).decode()
- print(picRes)
- with open("/root/pic0.txt","w") as f:
- f.write(picRes)
- return eval(picRes)
- `
- let code = `
- if __name__ == "__main__":
- img_path_face = ${path}
- ONLINE_IDENT_DATA = run_face(appid=APPId_face,apisecret=APISecret_face,apikey=APIKey_face,img_path=img_path_face,)
- `;
- return code;
- };
- // 在线人脸识别结果
- Blockly.Blocks['ai_online_ident_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.online_face_result); //
- this.setOutput(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.online_face_result);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_online_ident_result'] = function (block) {
- let code = `ONLINE_IDENT_DATA["face_num"]`;
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks['ai_online_ident_result_people'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.serialcomm_write_item_first)
- .appendField(new Blockly.FieldVariable("i"), "varitem")
- .appendField(Blockly.Msg.face_information)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_models_object_model_x, "x"],
- [Blockly.Msg.ai_models_object_model_y, "y"],
- [Blockly.Msg.ai_models_object_model_w, "w"],
- [Blockly.Msg.ai_models_object_model_h, "h"],
- // ['人脸属性信息', "property"],
- [Blockly.Msg.ai_models_object_model_confidence, "score"]
- ]), "TYPE");
- this.setOutput(true, null);
- this.setColour("#0000ff");
- this.setTooltip('');
- this.setHelpUrl("");
- }
- }
- Blockly.Python['ai_online_ident_result_people'] = function (block) {
- var type = block.getFieldValue('TYPE');
- var i = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- let code = '';
- if (type == "w") {
- code = `ONLINE_IDENT_DATA.get('face_'+str(${i})).get('${type}') + ONLINE_IDENT_DATA.get('face_'+str(${i})).get('x')`
- } else if (type == "h") {
- code = `ONLINE_IDENT_DATA.get('face_'+str(${i})).get('${type}') + ONLINE_IDENT_DATA.get('face_'+str(${i})).get('y')`
- } else {
- code = `ONLINE_IDENT_DATA.get('face_'+str(${i})).get('${type}')`
- }
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks['ai_audio_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/speaker_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.Text_to_speech_initialization); //
- this.appendValueInput("A")
- .setCheck(null)
- .appendField('APP ID');
- this.appendValueInput("B")
- .setCheck(null)
- .appendField('API Secret');
- this.appendValueInput("C")
- .setCheck(null)
- .appendField('API Key');
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.Text_to_speech_initialization);
- this.setHelpUrl("");
- }
- };
- // 在线文本转语音初始化
- Blockly.Python.ai_audio_init = function (block) {
- var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
- var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
- var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_['v831_import_time'] = `import time`
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- Blockly.Python.definitions_['v831_import_json'] = `import json`
- Blockly.Python.definitions_['v831_import_wave'] = `import wave`
- Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode`
- Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time`
- Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime`
- Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
- // Blockly.Python.definitions_['v831_import_datetime'] = `import datetime`
- Blockly.Python.definitions_['v831_import_websocket'] = `import websocket`
- Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
- Blockly.Python.definitions_['v831_import_base64'] = `import base64`
- Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
- Blockly.Python.definitions_['v831_import_ssl'] = `import ssl`
- Blockly.Python.definitions_['v831_import_thread_as_thread'] = `import _thread as thread`
- Blockly.Python.definitions_.ai_audio_init_function = `
- STATUS_FIRST_FRAME = 0 # 第一帧的标识
- STATUS_CONTINUE_FRAME = 1 # 中间帧标识
- STATUS_LAST_FRAME = 2 # 最后一帧的标识
- class Ws_Param_Audio(object):
- # 初始化
- def __init__(self, APPID, APIKey, APISecret, Text):
- self.APPID = APPID
- self.APIKey = APIKey
- self.APISecret = APISecret
- self.Text = Text
-
- # 公共参数(common)
- self.CommonArgs = {"app_id": self.APPID}
- # 业务参数(business),更多个性化参数可在官网查看
- self.BusinessArgs = {"aue": "raw", "auf": "audio/L16;rate=16000", "vcn": "xiaoyan", "tte": "utf8"}
- self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode("utf-8")), "UTF8")}
- #使用小语种须使用以下方式,此处的unicode指的是 utf16小端的编码方式,即"UTF-16LE"”
- #self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode('utf-16')), "UTF8")}
-
- # 生成url
- def create_url(self):
- url = "wss://tts-api.xfyun.cn/v2/tts"
- # 生成RFC1123格式的时间戳
- now = datetime.now()
- date = format_date_time(mktime(now.timetuple()))
-
- # 拼接字符串
- signature_origin = "host: " + "ws-api.xfyun.cn" + "\\n"
- signature_origin += "date: " + date + "\\n"
- signature_origin += "GET " + "/v2/tts " + "HTTP/1.1"
- # 进行hmac-sha256进行加密
- signature_sha = hmac.new(self.APISecret.encode("utf-8"), signature_origin.encode("utf-8"),digestmod=hashlib.sha256).digest()
- signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
-
- authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (self.APIKey, "hmac-sha256", "host date request-line", signature_sha)
- authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8")
- # 将请求的鉴权参数组合为字典
- v = {
- "authorization": authorization,
- "date": date,
- "host": "ws-api.xfyun.cn"
- }
- # 拼接鉴权参数,生成url
- url = url + "?" + urlencode(v)
- # print("date: ",date)
- # print("v: ",v)
- # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致
- # print('websocket url :', url)
- return url
- APPId_Audio = ${APPId}
- APISecret_Audio = ${APISecret}
- APIKey_Audio = ${APIKey}
- `;
- var _code = "";
- return _code;
- }
- Blockly.Blocks['ai_audio_play_state'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.text_conversion_voice); //
- this.appendValueInput("A")
- .setCheck(null)
- .appendField('APP ID');
- this.appendValueInput("B")
- .setCheck(null)
- .appendField('API Secret');
- this.appendValueInput("C")
- .setCheck(null)
- .appendField('API Key');
- this.appendValueInput("NAME")
- .setCheck(null)
- .appendField(Blockly.Msg.Content_of_text); //
- this.appendValueInput("path")
- .setCheck(null)
- .appendField(Blockly.Msg.Voice_path); //
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.text_conversion_voice);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_audio_play_state'] = function (block) {
- // TODO: Assemble Python into code variable.
- let text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC)
- let url = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC)
- let path = `${url.slice(1, url.length - 1)}`
- var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
- var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
- var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_['v831_import_time'] = `import time`
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- Blockly.Python.definitions_['v831_import_json'] = `import json`
- Blockly.Python.definitions_['v831_import_wave'] = `import wave`
- Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode`
- Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time`
- Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime`
- Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
- // Blockly.Python.definitions_['v831_import_datetime'] = `import datetime`
- Blockly.Python.definitions_['v831_import_websocket'] = `import websocket`
- Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
- Blockly.Python.definitions_['v831_import_base64'] = `import base64`
- Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
- Blockly.Python.definitions_['v831_import_ssl'] = `import ssl`
- Blockly.Python.definitions_['v831_import_thread_as_thread'] = `import _thread as thread`
- Blockly.Python.definitions_.ai_audio_init_function = `
- STATUS_FIRST_FRAME = 0 # 第一帧的标识
- STATUS_CONTINUE_FRAME = 1 # 中间帧标识
- STATUS_LAST_FRAME = 2 # 最后一帧的标识
- class Ws_Param_Audio(object):
- # 初始化
- def __init__(self, APPID, APIKey, APISecret, Text):
- self.APPID = APPID
- self.APIKey = APIKey
- self.APISecret = APISecret
- self.Text = Text
-
- # 公共参数(common)
- self.CommonArgs = {"app_id": self.APPID}
- # 业务参数(business),更多个性化参数可在官网查看
- self.BusinessArgs = {"aue": "raw", "auf": "audio/L16;rate=16000", "vcn": "xiaoyan", "tte": "utf8"}
- self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode("utf-8")), "UTF8")}
- #使用小语种须使用以下方式,此处的unicode指的是 utf16小端的编码方式,即"UTF-16LE"”
- #self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode('utf-16')), "UTF8")}
-
- # 生成url
- def create_url(self):
- url = "wss://tts-api.xfyun.cn/v2/tts"
- # 生成RFC1123格式的时间戳
- now = datetime.now()
- date = format_date_time(mktime(now.timetuple()))
-
- # 拼接字符串
- signature_origin = "host: " + "ws-api.xfyun.cn" + "\\n"
- signature_origin += "date: " + date + "\\n"
- signature_origin += "GET " + "/v2/tts " + "HTTP/1.1"
- # 进行hmac-sha256进行加密
- signature_sha = hmac.new(self.APISecret.encode("utf-8"), signature_origin.encode("utf-8"),digestmod=hashlib.sha256).digest()
- signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
-
- authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (self.APIKey, "hmac-sha256", "host date request-line", signature_sha)
- authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8")
- # 将请求的鉴权参数组合为字典
- v = {
- "authorization": authorization,
- "date": date,
- "host": "ws-api.xfyun.cn"
- }
- # 拼接鉴权参数,生成url
- url = url + "?" + urlencode(v)
- # print("date: ",date)
- # print("v: ",v)
- # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致
- # print('websocket url :', url)
- return url
- APPId_Audio = ${APPId}
- APISecret_Audio = ${APISecret}
- APIKey_Audio = ${APIKey}
- `;
- Blockly.Python.definitions_.on_message = `
- def on_message(ws, message):
- try:
- message =json.loads(message)
- code = message["code"]
- sid = message["sid"]
- audio = message["data"]["audio"]
- audio = base64.b64decode(audio)
- status = message["data"]["status"]
- #print(message)
- if status == 2:
- print("ws is closed")
- ws.close()
- if code != 0:
- errMsg = message["message"]
- print("sid:%s call error:%s code is:%s" % (sid, errMsg, code))
- else:
- pcm_path = "${path}"
- with open(pcm_path, "ab") as f:
- f.write(audio)
- print("tts")
-
- with open(pcm_path, "rb") as pcmfile:
- pcmdata = pcmfile.read()
- with wave.open(pcm_path + ".wav", "wb") as wavfile:
- wavfile.setparams((1, 2, 16000, 0, "NONE", "NONE"))
- wavfile.writeframes(pcmdata)
-
- except Exception as e:
- print("receive msg,but parse exception:", e)
-
- # 收到websocket错误的处理
- def on_error(ws, error):
- print("### error:", error)
- # 收到websocket关闭的处理
- def on_close(ws):
- print("### closed ###")
-
- # 收到websocket连接建立的处理
- def on_open(ws):
- def run(*args):
- global wsParam_Audio
- d = {"common": wsParam_Audio.CommonArgs,"business": wsParam_Audio.BusinessArgs,"data": wsParam_Audio.Data,}
- d = json.dumps(d)
- print("------>开始发送文本数据")
- ws.send(d)
- if os.path.exists(${url}):
- os.remove(${url})
-
- thread.start_new_thread(run, ())
- `
- Blockly.Python.addVariable('wsParam_Audio', 'wsParam_Audio = ""', true);
- let code = `if __name__ == "__main__":
- #with open('word.txt', 'r',encoding="UTF-8")as f:#txt= f.read()
- txt_Audio=${text}
- if os.path.exists(${url}):
- os.remove(${url})
- # 测试时候在此处正确填写相关信息即可运行
- wsParam_Audio = Ws_Param_Audio(APPID=APPId_Audio, APISecret=APISecret_Audio,APIKey=APIKey_Audio,Text=txt_Audio)
- websocket.enableTrace(False)
- wsUrl = wsParam_Audio.create_url()
- ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close)
- ws.on_open = on_open
- ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
- `
- // TODO: Change ORDER_NONE to the correct strength.
- return code
- };
- // 在线物体识别
- Blockly.Blocks['ai_online_object_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.online_object_init); //
- this.appendValueInput("A").setCheck(null).appendField('APP ID');
- // this.appendValueInput("B").setCheck(null).appendField('APISecret');
- this.appendValueInput("C").setCheck(null).appendField('API Key'); //Blockly.Msg.online_voice_init_path
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.online_object_init);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_online_object_init'] = function (block) {
- var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
- var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
- var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- Blockly.Python.definitions_['v831_import_time'] = `import time`
- Blockly.Python.definitions_['v831_import_requests'] = `import requests`
- Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
- Blockly.Python.definitions_['v831_import_base64'] = `import base64`
- Blockly.Python.definitions_.ai_online_object_init = `
- API_KEY = ${APIKey}
- APPID = ${APPId}
-
- def objectGetHeader(APPID, image_url, API_KEY):
- with open(image_url, "rb") as f:
- img_data = f.read()
- curTime = str(int(time.time()))
- paramBase64 = base64.b64encode(img_data)
- tmp = str(paramBase64, "utf-8")
-
- m2 = hashlib.md5()
- m2.update((API_KEY + curTime + tmp).encode("utf-8"))
- checkSum = m2.hexdigest()
-
- header = {
- 'X-CurTime': curTime,
- 'X-Param': paramBase64,
- 'X-Appid': APPID,
- 'X-CheckSum': checkSum,
- }
- return header
- `
- var code = '';
- return code;
- };
- Blockly.Blocks['ai_online_object_loading'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.online_object_load); //
- this.appendValueInput("path").setCheck(null).appendField(Blockly.Msg.online_face_init_path);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.online_object_load);
- this.setHelpUrl("");
- }
- }
- Blockly.Python.ai_online_object_loading = function (block) {
- var AudioFile = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
- let code = `ImageUrl = ${AudioFile}
- OBJECTRESULT = requests.post("http://tupapi.xfyun.cn/v1/currency", headers=objectGetHeader(APPID, ImageUrl,API_KEY))
- `
- return code
- }
- Blockly.Blocks['ai_online_object_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.online_object_result); //
- this.setOutput(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.online_object_result);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_online_object_result'] = function (block) {
- let code = `OBJECTRESULT.content`;
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- // 在线车牌识别
- Blockly.Blocks['ai_online_card_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.online_card_init); //
- this.appendValueInput("A").setCheck(null).appendField('APP ID');
- this.appendValueInput("B").setCheck(null).appendField('API Secret');
- this.appendValueInput("C").setCheck(null).appendField('API Key'); //Blockly.Msg.online_voice_init_path
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.online_card_init);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_online_card_init'] = function (block) {
- var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
- var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
- var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode`
- Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time`
- Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime`
- Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
- Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
- Blockly.Python.definitions_['v831_import_base64'] = `import base64`
- Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
- Blockly.Python.definitions_['v831_import_traceback'] = `import traceback`
- Blockly.Python.definitions_['v831_import_json'] = `import json`
- Blockly.Python.definitions_['v831_import_requests'] = `import requests`
- Blockly.Python.definitions_.ai_online_card_init = `
- APPId_Card = ${APPId}
- APISecret_Card = ${APISecret}
- APIKey_Card = ${APIKey}
- class AssembleHeaderException_Card(Exception):
- def __init__(self, msg):
- self.message = msg
-
- class Url_Card:
- def __init__(this, host, path, schema):
- this.host = host
- this.path = path
- this.schema = schema
- pass
-
- # 进行sha256加密和base64编码
- def sha256base64_Card(data):
- sha256 = hashlib.sha256()
- sha256.update(data)
- digest = base64.b64encode(sha256.digest()).decode(encoding="utf-8")
- return digest
-
- def parse_url_Card(requset_url):
- stidx = requset_url.index("://")
- host = requset_url[stidx + 3:]
- schema = requset_url[:stidx + 3]
- edidx = host.index("/")
- if edidx <= 0:
- raise AssembleHeaderException_Card("invalid request url:" + requset_url)
- path = host[edidx:]
- host = host[:edidx]
- u = Url_Card(host, path, schema)
- return u
-
- def assemble_ws_auth_url_Card(requset_url, method="GET", api_key="", api_secret=""):
- u = parse_url_Card(requset_url)
- host = u.host
- path = u.path
- now = datetime.now()
- date = format_date_time(mktime(now.timetuple()))
- print(date)
- # date = "Thu, 12 Dec 2019 01:57:27 GMT"
- signature_origin = "host: {}\\ndate: {}\\n{} {} HTTP/1.1".format(host, date, method, path)
- print(signature_origin)
- signature_sha = hmac.new(api_secret.encode("utf-8"), signature_origin.encode("utf-8"),
- digestmod=hashlib.sha256).digest()
- signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
- authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (
- api_key, "hmac-sha256", "host date request-line", signature_sha)
- authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8")
- print(authorization_origin)
- values = {
- "host": host,
- "date": date,
- "authorization": authorization
- }
-
- return requset_url + "?" + urlencode(values)
-
- def gen_body_Card(appid, img_path, server_id):
- with open(img_path, "rb") as f:
- img_data = f.read()
- body = {
- "header": {
- "app_id": appid,
- "status": 3
- },
- "parameter": {
- server_id: {
- "carLicenseRes": {
- "encoding": "utf8",
- "compress": "raw",
- "format": "json"
- }
- }
- },
- "payload": {
- "carImgBase64Str": {
- "encoding": "jpg",
- "status": 3,
- "image": str(base64.b64encode(img_data), "utf-8")
- }
- }
- }
- return json.dumps(body)
- `
- var code = '';
- return code;
- };
- Blockly.Blocks['ai_online_card_loading'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.online_card_load); //
- this.appendValueInput("path").setCheck(null).appendField(Blockly.Msg.online_face_init_path);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.online_card_load);
- this.setHelpUrl("");
- }
- }
- Blockly.Python.ai_online_card_loading = function (block) {
- var AudioFile = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_.ai_online_card_load = `def run_Card(appid, apikey, apisecret, img_path, server_id="jd_ocr_car"):
- url = "http://api.xf-yun.com/v1/private/{}".format(server_id)
- request_url = assemble_ws_auth_url_Card(url, "POST", apikey, apisecret)
- headers = {"content-type": "application/json", "host": "api.xf-yun.com", "app_id": appid}
- #print(request_url)
- response = requests.post(request_url, data=gen_body_Card(appid, img_path, server_id), headers=headers)
- resp_data = json.loads(response.content.decode("utf-8"))
- print(resp_data)
- resultCard = base64.b64decode(resp_data["payload"]["carLicenseRes"]["text"]).decode("utf-8")
- return json.loads(resultCard)
- CARDRESULT = ""
- `
- let code = `if __name__ == "__main__":
- img_path_Card = ${AudioFile}
- CARDRESULT = run_Card(appid=APPId_Card,apisecret=APISecret_Card,apikey=APIKey_Card,img_path=img_path_Card,)
- `
- return code
- }
- Blockly.Blocks['ai_online_card_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.online_card_result); //
- this.setOutput(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.online_card_result);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_online_card_result'] = function (block) {
- let code = `CARDRESULT`;
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- // 机器翻译
- Blockly.Blocks['ai_online_machine_translation_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.machine_translation_init); //
- this.appendDummyInput()
- .appendField(Blockly.Msg.BLYNK_GET_DATANAME)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "cn"],
- [Blockly.Msg.ai_speech_recognition_setup_set_english, "en"],
- ]), "from")
- .appendField(Blockly.Msg.machine_translation_to)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_speech_recognition_setup_set_english, "en"],
- [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "cn"],
- ]), "to");
- this.appendValueInput("A").setCheck(null).appendField('APP ID');
- this.appendValueInput("B").setCheck(null).appendField('API Secret');
- this.appendValueInput("C").setCheck(null).appendField('API Key');
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.machine_translation_init);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_online_machine_translation_init'] = function (block) {
- var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
- var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
- var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
- let FROM = block.getFieldValue('from')
- let TO = block.getFieldValue('to')
- // TODO: Assemble Python into code variable.
- Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
- Blockly.Python.definitions_['v831_import_requests'] = `import requests`
- Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
- Blockly.Python.definitions_['v831_import_base64'] = `import base64`
- Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
- Blockly.Python.definitions_['v831_import_json'] = `import json`
- Blockly.Python.definitions_.ai_online_machine_translation_init = `
- APPId_machine = ${APPId}
- APISecret_machine = ${APISecret}
- APIKey_machine = ${APIKey}
- TRANSLATIONTEXT = ""
- class get_result_machine(object):
- def __init__(self,host,TRANSLATIONTEXT):
- # 应用ID(到控制台获取)
- self.APPID_machine = ${APPId}
- # 接口APISercet(到控制台机器翻译服务页面获取)
- self.Secret_machine = ${APISecret}
- # 接口APIKey(到控制台机器翻译服务页面获取)
- self.APIKey_machine= ${APIKey}
-
-
- # 以下为POST请求
- self.Host = "itrans.xfyun.cn"
- self.RequestUri = "/v2/its"
- # 设置url
- # print(host)
- self.url="https://"+host+self.RequestUri
- self.HttpMethod = "POST"
- self.Algorithm = "hmac-sha256"
- self.HttpProto = "HTTP/1.1"
- # 设置当前时间
- curTime_utc = datetime.utcnow()
- self.Date = self.httpdate_machine(curTime_utc)
- # 设置业务参数
- # 语种列表参数值请参照接口文档:https://www.xfyun.cn/doc/nlp/xftrans/API.html
- self.Text=TRANSLATIONTEXT
- self.BusinessArgs={
- "from": "${FROM}",
- "to": "${TO}",
- }
- def hashlib_256_machine(self, res):
- m = hashlib.sha256(bytes(res.encode(encoding="utf-8"))).digest()
- result = "SHA-256=" + base64.b64encode(m).decode(encoding="utf-8")
- return result
- def httpdate_machine(self, dt):
- """
- Return a string representation of a date according to RFC 1123
- (HTTP/1.1).
- The supplied date must be in UTC.
- """
- weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
- month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
- "Oct", "Nov", "Dec"][dt.month - 1]
- return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month,
- dt.year, dt.hour, dt.minute, dt.second)
- def generateSignature_machine(self, digest):
- signatureStr = "host: " + self.Host + "\\n"
- signatureStr += "date: " + self.Date + "\\n"
- signatureStr += self.HttpMethod + " " + self.RequestUri \\
- + " " + self.HttpProto + "\\n"
- signatureStr += "digest: " + digest
- signature = hmac.new(bytes(self.Secret_machine.encode(encoding="utf-8")),
- bytes(signatureStr.encode(encoding="utf-8")),
- digestmod=hashlib.sha256).digest()
- result = base64.b64encode(signature)
- return result.decode(encoding="utf-8")
- def init_header_machine(self, data):
- digest = self.hashlib_256_machine(data)
- #print(digest)
- sign = self.generateSignature_machine(digest)
- authHeader = "api_key=\\""+self.APIKey_machine+"\\", algorithm=\\""+self.Algorithm+"\\", headers=\\"host date request-line digest\\", signature=\\""+sign+"\\""
- #print(authHeader)
- headers = {
- "Content-Type": "application/json",
- "Accept": "application/json",
- "Method": "POST",
- "Host": self.Host,
- "Date": self.Date,
- "Digest": digest,
- "Authorization": authHeader
- }
- return headers
- def get_body_machine(self):
- content = str(base64.b64encode(self.Text.encode("utf-8")), "utf-8")
- postdata = {
- "common": {"app_id": self.APPID_machine},
- "business": self.BusinessArgs,
- "data": {
- "text": content,
- }
- }
- body = json.dumps(postdata)
- #print(body)
- return body
- def call_url_machine(self):
- if self.APPID_machine == "" or self.APIKey_machine == "" or self.Secret_machine == "":
- print("Appid 或APIKey 或APISecret 为空!请打开demo代码,填写相关信息。")
- else:
- code = 0
- body=self.get_body_machine()
- headers=self.init_header_machine(body)
- #print(self.url)
- response = requests.post(self.url, data=body, headers=headers,timeout=8)
- status_code = response.status_code
- #print(response.content)
- if status_code!=200:
- # 鉴权失败
- print("Http请求失败,状态码:" + str(status_code) + ",错误信息:" + response.text)
- print("请根据错误信息检查代码,接口文档:https://www.xfyun.cn/doc/nlp/xftrans/API.html")
- else:
- # 鉴权成功
- respData = json.loads(response.text)
- #print('result',respData["data"]['result']['trans_result']['dst'])
- # return
- # 以下仅用于调试
- code = str(respData["code"])
- if code=="0":
- return respData["data"]["result"]["trans_result"]["dst"]
- else:
- print("请前往https://www.xfyun.cn/document/error-code?code=" + code + "查询解决办法")
- `
- var code = '';
- return code;
- };
- Blockly.Blocks['ai_online_machine_translation_loading'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.machine_translation_load); //
- this.appendDummyInput()
- .appendField(Blockly.Msg.BLYNK_GET_DATANAME)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "cn"],
- [Blockly.Msg.ai_speech_recognition_setup_set_english, "en"],
- ]), "from")
- .appendField(Blockly.Msg.machine_translation_to)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_speech_recognition_setup_set_english, "en"],
- [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "cn"],
- ]), "to");
- this.appendValueInput("A").setCheck(null).appendField('APP ID');
- this.appendValueInput("B").setCheck(null).appendField('API Secret');
- this.appendValueInput("C").setCheck(null).appendField('API Key');
- this.appendValueInput("NAME")
- .setCheck(null)
- .appendField(Blockly.Msg.Content_of_text); //
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.machine_translation_load);
- this.setHelpUrl("");
- }
- }
- Blockly.Python.ai_online_machine_translation_loading = function (block) {
- let text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC)
- var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
- var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
- var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
- let FROM = block.getFieldValue('from')
- let TO = block.getFieldValue('to')
- // TODO: Assemble Python into code variable.
- Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
- Blockly.Python.definitions_['v831_import_requests'] = `import requests`
- Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
- Blockly.Python.definitions_['v831_import_base64'] = `import base64`
- Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
- Blockly.Python.definitions_['v831_import_json'] = `import json`
- Blockly.Python.definitions_.ai_online_machine_translation_init = `
- APPId_machine = ${APPId}
- APISecret_machine = ${APISecret}
- APIKey_machine = ${APIKey}
- TRANSLATIONTEXT = ""
- class get_result_machine(object):
- def __init__(self,host,TRANSLATIONTEXT):
- # 应用ID(到控制台获取)
- self.APPID_machine = ${APPId}
- # 接口APISercet(到控制台机器翻译服务页面获取)
- self.Secret_machine = ${APISecret}
- # 接口APIKey(到控制台机器翻译服务页面获取)
- self.APIKey_machine= ${APIKey}
-
-
- # 以下为POST请求
- self.Host = "itrans.xfyun.cn"
- self.RequestUri = "/v2/its"
- # 设置url
- # print(host)
- self.url="https://"+host+self.RequestUri
- self.HttpMethod = "POST"
- self.Algorithm = "hmac-sha256"
- self.HttpProto = "HTTP/1.1"
- # 设置当前时间
- curTime_utc = datetime.utcnow()
- self.Date = self.httpdate_machine(curTime_utc)
- # 设置业务参数
- # 语种列表参数值请参照接口文档:https://www.xfyun.cn/doc/nlp/xftrans/API.html
- self.Text=TRANSLATIONTEXT
- self.BusinessArgs={
- "from": "${FROM}",
- "to": "${TO}",
- }
- def hashlib_256_machine(self, res):
- m = hashlib.sha256(bytes(res.encode(encoding="utf-8"))).digest()
- result = "SHA-256=" + base64.b64encode(m).decode(encoding="utf-8")
- return result
- def httpdate_machine(self, dt):
- """
- Return a string representation of a date according to RFC 1123
- (HTTP/1.1).
- The supplied date must be in UTC.
- """
- weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
- month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
- "Oct", "Nov", "Dec"][dt.month - 1]
- return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month,
- dt.year, dt.hour, dt.minute, dt.second)
- def generateSignature_machine(self, digest):
- signatureStr = "host: " + self.Host + "\\n"
- signatureStr += "date: " + self.Date + "\\n"
- signatureStr += self.HttpMethod + " " + self.RequestUri \\
- + " " + self.HttpProto + "\\n"
- signatureStr += "digest: " + digest
- signature = hmac.new(bytes(self.Secret_machine.encode(encoding="utf-8")),
- bytes(signatureStr.encode(encoding="utf-8")),
- digestmod=hashlib.sha256).digest()
- result = base64.b64encode(signature)
- return result.decode(encoding="utf-8")
- def init_header_machine(self, data):
- digest = self.hashlib_256_machine(data)
- #print(digest)
- sign = self.generateSignature_machine(digest)
- authHeader = "api_key=\\""+self.APIKey_machine+"\\", algorithm=\\""+self.Algorithm+"\\", headers=\\"host date request-line digest\\", signature=\\""+sign+"\\""
- #print(authHeader)
- headers = {
- "Content-Type": "application/json",
- "Accept": "application/json",
- "Method": "POST",
- "Host": self.Host,
- "Date": self.Date,
- "Digest": digest,
- "Authorization": authHeader
- }
- return headers
- def get_body_machine(self):
- content = str(base64.b64encode(self.Text.encode("utf-8")), "utf-8")
- postdata = {
- "common": {"app_id": self.APPID_machine},
- "business": self.BusinessArgs,
- "data": {
- "text": content,
- }
- }
- body = json.dumps(postdata)
- #print(body)
- return body
- def call_url_machine(self):
- if self.APPID_machine == "" or self.APIKey_machine == "" or self.Secret_machine == "":
- print("Appid 或APIKey 或APISecret 为空!请打开demo代码,填写相关信息。")
- else:
- code = 0
- body=self.get_body_machine()
- headers=self.init_header_machine(body)
- #print(self.url)
- response = requests.post(self.url, data=body, headers=headers,timeout=8)
- status_code = response.status_code
- #print(response.content)
- if status_code!=200:
- # 鉴权失败
- print("Http请求失败,状态码:" + str(status_code) + ",错误信息:" + response.text)
- print("请根据错误信息检查代码,接口文档:https://www.xfyun.cn/doc/nlp/xftrans/API.html")
- else:
- # 鉴权成功
- respData = json.loads(response.text)
- #print('result',respData["data"]['result']['trans_result']['dst'])
- # return
- # 以下仅用于调试
- code = str(respData["code"])
- if code=="0":
- return respData["data"]["result"]["trans_result"]["dst"]
- else:
- print("请前往https://www.xfyun.cn/document/error-code?code=" + code + "查询解决办法")
- `
- let code = `TRANSLATIONTEXT = ${text}
- machinehost = "itrans.xfyun.cn"
- #初始化类
- gClass=get_result_machine(host=machinehost,TRANSLATIONTEXT=TRANSLATIONTEXT)
- TRANSLATIONRESULT = gClass.call_url_machine()
- `
- return code
- }
- Blockly.Blocks['ai_online_machine_translation_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.machine_translation_result); //
- this.setOutput(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.machine_translation_result);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_online_machine_translation_result'] = function (block) {
- let code = `TRANSLATIONRESULT`;
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- // 手写文字识别
- Blockly.Blocks['ai_online_handwritten_text_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.handwritten_text_init); //
- this.appendValueInput("A").setCheck(null).appendField('APP ID');
- // this.appendValueInput("B").setCheck(null).appendField('API Secret');
- this.appendValueInput("C").setCheck(null).appendField('API Key');
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.handwritten_text_init);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_online_handwritten_text_init'] = function (block) {
- var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
- // var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
- var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- Blockly.Python.definitions_['v831_import_time'] = `import time`
- Blockly.Python.definitions_['v831_import_base64'] = `import base64`
- Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
- Blockly.Python.definitions_['v831_import_requests'] = `import requests`
- Blockly.Python.definitions_['v831_import_json'] = `import json`
- Blockly.Python.definitions_['v831_import_from_urllib_parse'] = `from urllib import parse`
- Blockly.Python.definitions_.ai_online_handwritten_text_init = `
- URL_handwritten_text = "http://webapi.xfyun.cn/v1/service/v1/ocr/handwriting"
- APPId_handwritten_text = ${APPId}
- APIKey_handwritten_text = ${APIKey}
- def textGetHeader_handwritten_text(language, location):
- curTime = str(int(time.time()))
- param = "{\\"language\\":\\""+language+"\\",\\"location\\":\\""+location+"\\"}"
- paramBase64 = base64.b64encode(param.encode("utf-8"))
- m2 = hashlib.md5()
- str1 = APIKey_handwritten_text + curTime + str(paramBase64, "utf-8")
- m2.update(str1.encode("utf-8"))
- checkSum = m2.hexdigest()
- # 组装http请求头
- header = {
- "X-CurTime": curTime,
- "X-Param": paramBase64,
- "X-Appid": APPId_handwritten_text,
- "X-CheckSum": checkSum,
- "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
- }
- return header
- def getBody_handwritten_text(filepath):
- with open(filepath, "rb") as f:
- imgfile = f.read()
- data = {"image": str(base64.b64encode(imgfile), "utf-8")}
- return data
-
- `
- var code = '';
- return code;
- };
- Blockly.Blocks['ai_online_handwritten_text_loading'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.handwritten_text_load); //
- this.appendValueInput("A").setCheck(null).appendField('APP ID');
- // this.appendValueInput("B").setCheck(null).appendField('API Secret');
- this.appendValueInput("C").setCheck(null).appendField('API Key');
- this.appendValueInput("path")
- .setCheck(null)
- .appendField(Blockly.Msg.online_face_init_path); //
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.handwritten_text_load);
- this.setHelpUrl("");
- }
- }
- Blockly.Python.ai_online_handwritten_text_loading = function (block) {
- let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC)
- var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
- // var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
- var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- Blockly.Python.definitions_['v831_import_time'] = `import time`
- Blockly.Python.definitions_['v831_import_base64'] = `import base64`
- Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
- Blockly.Python.definitions_['v831_import_requests'] = `import requests`
- Blockly.Python.definitions_['v831_import_json'] = `import json`
- Blockly.Python.definitions_['v831_import_from_urllib_parse'] = `from urllib import parse`
- Blockly.Python.definitions_.ai_online_handwritten_text_init = `
- URL_handwritten_text = "http://webapi.xfyun.cn/v1/service/v1/ocr/handwriting"
- APPId_handwritten_text = ${APPId}
- APIKey_handwritten_text = ${APIKey}
- def textGetHeader_handwritten_text(language, location):
- curTime = str(int(time.time()))
- param = "{\\"language\\":\\""+language+"\\",\\"location\\":\\""+location+"\\"}"
- paramBase64 = base64.b64encode(param.encode("utf-8"))
- m2 = hashlib.md5()
- str1 = APIKey_handwritten_text + curTime + str(paramBase64, "utf-8")
- m2.update(str1.encode("utf-8"))
- checkSum = m2.hexdigest()
- # 组装http请求头
- header = {
- "X-CurTime": curTime,
- "X-Param": paramBase64,
- "X-Appid": APPId_handwritten_text,
- "X-CheckSum": checkSum,
- "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
- }
- return header
- def getBody_handwritten_text(filepath):
- with open(filepath, "rb") as f:
- imgfile = f.read()
- data = {"image": str(base64.b64encode(imgfile), "utf-8")}
- return data
-
- `
- let code = `# 语种设置
- textLanguage = "cn|en"
- # 是否返回文本位置信息
- textLocation = "false"
- # 图片上传接口地址
- picFilePath_handwritten_text = ${text}
- HandwrittenTextData = requests.post(URL_handwritten_text, headers=textGetHeader_handwritten_text(textLanguage, textLocation), data=getBody_handwritten_text(picFilePath_handwritten_text))
- `
- return code
- }
- Blockly.Blocks['ai_online_handwritten_text_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.handwritten_text_result); //
- this.setOutput(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.handwritten_text_result);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_online_handwritten_text_result'] = function (block) {
- Blockly.Python.definitions_.ai_online_handwritten_text_result = `def handwrittenTextDatas_handwritten_text(r):
- my_json_data = r.content.decode("utf8")
- # print(type(my_json))
- loadsData = json.loads(my_json_data)
- # s = json.dumps(data, indent=4, sort_keys=True)
- print("data",my_json_data)
- deal_data = ""
- if loadsData["code"] == "0" :
- t = loadsData["data"]["block"][0]["line"]
- for i in t:
- print(i)
- for j in i["word"]:
- print(j["content"])
- deal_data = deal_data + j["content"] + " "
- #print('deal_data',deal_data)
- return deal_data
- `
- let code = `handwrittenTextDatas_handwritten_text(HandwrittenTextData)`;
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- // 公式识别
- Blockly.Blocks['ai_online_formula_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.formula_init); //
- this.appendValueInput("A").setCheck(null).appendField('APP ID');
- this.appendValueInput("B").setCheck(null).appendField('API Secret');
- this.appendValueInput("C").setCheck(null).appendField('API Key');
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.formula_init);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_online_formula_init'] = function (block) {
- var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
- var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
- var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- Blockly.Python.definitions_['v831_import_time'] = `import time`
- Blockly.Python.definitions_['v831_import_base64'] = `import base64`
- Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
- Blockly.Python.definitions_['v831_import_requests'] = `import requests`
- Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
- Blockly.Python.definitions_['v831_import_json'] = `import json`
- Blockly.Python.definitions_['v831_import_from_urllib_parse'] = `from urllib import parse`
- Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
- Blockly.Python.definitions_.ai_online_formula_init = `class get_result_formula(object):
- def __init__(self,host,path):
- # 应用ID(到控制台获取)
- self.APPID_formula = ${APPId}
- # 接口APISercet(到控制台公式识别服务页面获取)
- self.Secret_formula = ${APISecret}
- # 接口APIKey(到控制台公式识别服务页面获取)
- self.APIKey_formula = ${APIKey}
-
-
- # 以下为POST请求
- self.Host_formula = host
- self.RequestUri_formula = "/v2/itr"
- # 设置url
- # print(host)
- self.url_formula="https://"+host+self.RequestUri_formula
- self.HttpMethod_formula = "POST"
- self.Algorithm_formula = "hmac-sha256"
- self.HttpProto_formula = "HTTP/1.1"
- # 设置当前时间
- curTime_utc = datetime.utcnow()
- self.Date_formula = self.httpdate_formula(curTime_utc)
- #设置测试图片文件
- self.AudioPath_formula = path
- self.BusinessArgs_formula={
- "ent": "teach-photo-print",
- "aue": "raw",
- }
- def imgRead_formula(self, path):
- with open(path, "rb") as fo:
- return fo.read()
- def hashlib_256_formula(self, res):
- m = hashlib.sha256(bytes(res.encode(encoding="utf-8"))).digest()
- result = "SHA-256=" + base64.b64encode(m).decode(encoding="utf-8")
- return result
- def httpdate_formula(self, dt):
- """
- Return a string representation of a date according to RFC 1123
- (HTTP/1.1).
- The supplied date must be in UTC.
- """
- weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
- month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
- "Oct", "Nov", "Dec"][dt.month - 1]
- return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month,
- dt.year, dt.hour, dt.minute, dt.second)
- def generateSignature_formula(self, digest):
- signatureStr = "host: " + self.Host_formula + "\\n"
- signatureStr += "date: " + self.Date_formula + "\\n"
- signatureStr += self.HttpMethod_formula + " " + self.RequestUri_formula \\
- + " " + self.HttpProto_formula + "\\n"
- signatureStr += "digest: " + digest
- signature = hmac.new(bytes(self.Secret_formula.encode(encoding="utf-8")),
- bytes(signatureStr.encode(encoding="utf-8")),
- digestmod=hashlib.sha256).digest()
- result = base64.b64encode(signature)
- return result.decode(encoding="utf-8")
- def init_header_formula(self, data):
- digest = self.hashlib_256_formula(data)
- #print(digest)
- sign = self.generateSignature_formula(digest)
- authHeader = "api_key=\\""+self.APIKey_formula+"\\", algorithm=\\""+self.Algorithm_formula+"\\", headers=\\"host date request-line digest\\", signature=\\""+sign+"\\""
- #print(authHeader)
- headers = {
- "Content-Type": "application/json",
- "Accept": "application/json",
- "Method": "POST",
- "Host": self.Host_formula,
- "Date": self.Date_formula,
- "Digest": digest,
- "Authorization": authHeader
- }
- return headers
- def get_body_formula(self):
- audioData = self.imgRead_formula(self.AudioPath_formula)
- content = base64.b64encode(audioData).decode(encoding="utf-8")
- postdata = {
- "common": {"app_id": self.APPID_formula},
- "business": self.BusinessArgs_formula,
- "data": {
- "image": content,
- }
- }
- body = json.dumps(postdata)
- #print(body)
- return body
- def call_url_formula(self):
- if self.APPID_formula == "" or self.APIKey_formula == "" or self.Secret_formula == "":
- print("Appid 或APIKey 或APISecret 为空!请打开demo代码,填写相关信息。")
- else:
- code = 0
- body=self.get_body_formula()
- headers=self.init_header_formula(body)
- #print(self.url_formula)
- response = requests.post(self.url_formula, data=body, headers=headers,timeout=8)
- status_code = response.status_code
- #print(response.content)
- if status_code!=200:
- # 鉴权失败
- print("Http请求失败,状态码:" + str(status_code) + ",错误信息:" + response.text)
- print("请根据错误信息检查代码,接口文档:https://www.xfyun.cn/doc/words/formula-discern/API.html")
- else:
- # 鉴权成功
- respData = json.loads(response.text)
- dataCotent = ""
- try:
- for i in respData["data"]["region"]:
- dataCotent += i["recog"]["content"]
- except:
- dataCotent = "Failure"
- return dataCotent
- FORMULARESULT = ""
- `
- var code = '';
- return code;
- };
- Blockly.Blocks['ai_online_formula_loading'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.formula_load); //
- this.appendValueInput("A").setCheck(null).appendField('APP ID');
- this.appendValueInput("B").setCheck(null).appendField('API Secret');
- this.appendValueInput("C").setCheck(null).appendField('API Key');
- this.appendValueInput("path")
- .setCheck(null)
- .appendField(Blockly.Msg.online_face_init_path); //
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.formula_load);
- this.setHelpUrl("");
- }
- }
- Blockly.Python.ai_online_formula_loading = function (block) {
- let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC)
- var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
- var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
- var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- Blockly.Python.definitions_['v831_import_time'] = `import time`
- Blockly.Python.definitions_['v831_import_base64'] = `import base64`
- Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
- Blockly.Python.definitions_['v831_import_requests'] = `import requests`
- Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
- Blockly.Python.definitions_['v831_import_json'] = `import json`
- Blockly.Python.definitions_['v831_import_from_urllib_parse'] = `from urllib import parse`
- Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
- Blockly.Python.definitions_.ai_online_formula_init = `class get_result_formula(object):
- def __init__(self,host,path):
- # 应用ID(到控制台获取)
- self.APPID_formula = ${APPId}
- # 接口APISercet(到控制台公式识别服务页面获取)
- self.Secret_formula = ${APISecret}
- # 接口APIKey(到控制台公式识别服务页面获取)
- self.APIKey_formula = ${APIKey}
-
-
- # 以下为POST请求
- self.Host_formula = host
- self.RequestUri_formula = "/v2/itr"
- # 设置url
- # print(host)
- self.url_formula="https://"+host+self.RequestUri_formula
- self.HttpMethod_formula = "POST"
- self.Algorithm_formula = "hmac-sha256"
- self.HttpProto_formula = "HTTP/1.1"
- # 设置当前时间
- curTime_utc = datetime.utcnow()
- self.Date_formula = self.httpdate_formula(curTime_utc)
- #设置测试图片文件
- self.AudioPath_formula = path
- self.BusinessArgs_formula={
- "ent": "teach-photo-print",
- "aue": "raw",
- }
- def imgRead_formula(self, path):
- with open(path, "rb") as fo:
- return fo.read()
- def hashlib_256_formula(self, res):
- m = hashlib.sha256(bytes(res.encode(encoding="utf-8"))).digest()
- result = "SHA-256=" + base64.b64encode(m).decode(encoding="utf-8")
- return result
- def httpdate_formula(self, dt):
- """
- Return a string representation of a date according to RFC 1123
- (HTTP/1.1).
- The supplied date must be in UTC.
- """
- weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
- month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
- "Oct", "Nov", "Dec"][dt.month - 1]
- return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month,
- dt.year, dt.hour, dt.minute, dt.second)
- def generateSignature_formula(self, digest):
- signatureStr = "host: " + self.Host_formula + "\\n"
- signatureStr += "date: " + self.Date_formula + "\\n"
- signatureStr += self.HttpMethod_formula + " " + self.RequestUri_formula \\
- + " " + self.HttpProto_formula + "\\n"
- signatureStr += "digest: " + digest
- signature = hmac.new(bytes(self.Secret_formula.encode(encoding="utf-8")),
- bytes(signatureStr.encode(encoding="utf-8")),
- digestmod=hashlib.sha256).digest()
- result = base64.b64encode(signature)
- return result.decode(encoding="utf-8")
- def init_header_formula(self, data):
- digest = self.hashlib_256_formula(data)
- #print(digest)
- sign = self.generateSignature_formula(digest)
- authHeader = "api_key=\\""+self.APIKey_formula+"\\", algorithm=\\""+self.Algorithm_formula+"\\", headers=\\"host date request-line digest\\", signature=\\""+sign+"\\""
- #print(authHeader)
- headers = {
- "Content-Type": "application/json",
- "Accept": "application/json",
- "Method": "POST",
- "Host": self.Host_formula,
- "Date": self.Date_formula,
- "Digest": digest,
- "Authorization": authHeader
- }
- return headers
- def get_body_formula(self):
- audioData = self.imgRead_formula(self.AudioPath_formula)
- content = base64.b64encode(audioData).decode(encoding="utf-8")
- postdata = {
- "common": {"app_id": self.APPID_formula},
- "business": self.BusinessArgs_formula,
- "data": {
- "image": content,
- }
- }
- body = json.dumps(postdata)
- #print(body)
- return body
- def call_url_formula(self):
- if self.APPID_formula == "" or self.APIKey_formula == "" or self.Secret_formula == "":
- print("Appid 或APIKey 或APISecret 为空!请打开demo代码,填写相关信息。")
- else:
- code = 0
- body=self.get_body_formula()
- headers=self.init_header_formula(body)
- #print(self.url_formula)
- response = requests.post(self.url_formula, data=body, headers=headers,timeout=8)
- status_code = response.status_code
- #print(response.content)
- if status_code!=200:
- # 鉴权失败
- print("Http请求失败,状态码:" + str(status_code) + ",错误信息:" + response.text)
- print("请根据错误信息检查代码,接口文档:https://www.xfyun.cn/doc/words/formula-discern/API.html")
- else:
- # 鉴权成功
- respData = json.loads(response.text)
- dataCotent = ""
- try:
- for i in respData["data"]["region"]:
- dataCotent += i["recog"]["content"]
- except:
- dataCotent = "Failure"
- return dataCotent
- FORMULARESULT = ""
- `
- let code = `
- if __name__ == "__main__":
- formulaUrlPath_formula = ${text}
- ##示例: host="rest-api.xfyun.cn"域名形式
- host = "rest-api.xfyun.cn"
- #初始化类
- gClass=get_result_formula(host,path=formulaUrlPath_formula)
- FORMULARESULT = gClass.call_url_formula()
- `
- return code
- }
- Blockly.Blocks['ai_online_formula_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.formula_result); //
- this.setOutput(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.formula_result);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_online_formula_result'] = function (block) {
- let code = `FORMULARESULT`;
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- // 身份证识别
- Blockly.Blocks['ai_online_ID_card_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField('身份证识别初始化'); //
- this.appendValueInput("A").setCheck(null).appendField('APP ID');
- this.appendValueInput("B").setCheck(null).appendField('API Secret');
- this.appendValueInput("C").setCheck(null).appendField('API Key');
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.handwritten_text_init);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_online_ID_card_init'] = function (block) {
- var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
- var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
- var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- Blockly.Python.definitions_['v831_import_time'] = `import time`
- Blockly.Python.definitions_['v831_import_base64'] = `import base64`
- Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
- Blockly.Python.definitions_['v831_import_requests'] = `import requests`
- Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
- Blockly.Python.definitions_['v831_import_json'] = `import json`
- Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime`
- Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
- Blockly.Python.definitions_['v831_import_from_urllib_parse'] = `from urllib import parse`
- Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time`
- Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode`
- Blockly.Python.definitions_.ai_online_formula_init = `class AssembleHeaderException(Exception):
- def __init__(self, msg):
- self.message = msg
- class Url:
- def __init__(this, host, path, schema):
- this.host = host
- this.path = path
- this.schema = schema
- pass
- # calculate sha256 and encode to base64
- def sha256base64(data):
- sha256 = hashlib.sha256()
- sha256.update(data)
- digest = base64.b64encode(sha256.digest()).decode(encoding="utf-8")
- return digest
- def parse_url(requset_url):
- stidx = requset_url.index("://")
- host = requset_url[stidx + 3:]
- schema = requset_url[:stidx + 3]
- edidx = host.index("/")
- if edidx <= 0:
- raise AssembleHeaderException("invalid request url:" + requset_url)
- path = host[edidx:]
- host = host[:edidx]
- u = Url(host, path, schema)
- return u
- # build websocket auth request url
- def assemble_ws_auth_url(requset_url, method="POST", api_key="", api_secret=""):
- u = parse_url(requset_url)
- host = u.host
- path = u.path
- now = datetime.now()
- date = format_date_time(mktime(now.timetuple()))
- #print(date)
- # date = "Thu, 12 Dec 2019 01:57:27 GMT"
- signature_origin = "host: {}\\ndate: {}\\n{} {} HTTP/1.1".format(host, date, method, path)
- #print(signature_origin)
- signature_sha = hmac.new(api_secret.encode("utf-8"), signature_origin.encode("utf-8"),
- digestmod=hashlib.sha256).digest()
- signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
- authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (
- api_key, "hmac-sha256", "host date request-line", signature_sha)
- authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8")
- #print(authorization_origin)
- values = {
- "host": host,
- "date": date,
- "authorization": authorization
- }
- return requset_url + "?" + urlencode(values)
- # 控制台获取以下信息
- APPId = ${APPId}
- APISecret = ${APISecret}
- APIKey = ${APIKey}
- `
- var code = '';
- return code;
- };
- Blockly.Blocks['ai_online_ID_card_loading'] = {
- init: function () {
- this.appendDummyInput()
- .appendField('身份证识别加载'); //
- // this.appendDummyInput()
- // .appendField('设置识别语种')
- // .appendField(new Blockly.FieldDropdown([
- // ["en", "en"],
- // ["cn|en", "cn|en"],
- // ]), "language");
- this.appendValueInput("path")
- .setCheck(null)
- .appendField(Blockly.Msg.online_face_init_path); //
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.handwritten_text_load);
- this.setHelpUrl("");
- }
- }
- Blockly.Python.ai_online_ID_card_loading = function (block) {
- let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC)
- // let language = Blockly.Python.valueToCode(block, 'language', Blockly.Python.ORDER_ATOMIC);
- let code = `with open(${text}, "rb") as f:
- imageBytes = f.read()
- url = 'http://api.xf-yun.com/v1/private/s5ccecfce'
-
- body = {
- "header": {
- "app_id": APPId,
- "status": 3,
- },
- "parameter": {
- "s5ccecfce": {
- "template_list": "id_card",
- "result": {
- "encoding": "utf8",
- "compress": "raw",
- "format": "json"
- }
- }
- },
- "payload": {
- "s5ccecfce_data_1": {
- "encoding": "jpg",
- "image": str(base64.b64encode(imageBytes), 'UTF-8'),
- "status": 3
- }
- }
- }
- request_Id_card_url = assemble_ws_auth_url(url, "POST", APIKey, APISecret)
- headers = {'content-type': "application/json", 'host': 'api.xf-yun.com', 'app_id': APPId}
- #print(request_url)
- Id_card_response = requests.post(request_Id_card_url, data=json.dumps(body), headers=headers)
- IDCardtempResult = json.loads(Id_card_response.content.decode())
- IDCardfinalResult = base64.b64decode(IDCard['payload']['result']['text']).decode()
- IDCardfinalResult = IDCardfinalResult.replace(" ", "").replace("\n", "").replace("\t", "").strip()
- `
- return code
- }
- Blockly.Blocks['ai_online_ID_card_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField('身份证识别结果'); //
- this.setOutput(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.handwritten_text_result);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_online_ID_card_result'] = function (block) {
- let code = `IDCardfinalResult`;
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- // 情绪识别
- Blockly.Blocks['ai_online_emotion_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.emotion_init);
- // this.appendValueInput("path")
- // .setCheck(null).appendField(Blockly.Msg.set_dictionary)
- // .appendField(new Blockly.FieldVariable("emotion_recognize_result"), "varitem");
- // this.appendDummyInput().appendField(Blockly.Msg.dictionary_contain);
- this.setInputsInline(false)
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);; //
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.emotion_init);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_online_emotion_init'] = function (block) {
- // let = []
- // let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC)
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- // TODO: Assemble Python into code variable.
- Blockly.Python.definitions_['v831_import_base64'] = `import base64`
- Blockly.Python.definitions_['v831_import_requests'] = `import requests`
- Blockly.Python.definitions_['v831_import_json'] = `import json`
- Blockly.Python.addVariable("EMOTION_SEND_REQUEST", "EMOTION_SEND_REQUEST = {}", true);
- Blockly.Python.definitions_['emotion_init'] = `def get_img_base64str(single_image_path):
- with open(single_image_path, "rb") as fp:
- imgbase64 = base64.b64encode(fp.read())
- return imgbase64.decode()
- url = "https://ai-api.cocorobo.hk/face"
- `
- // ${variable_name} =${text}
- var code = ``;
- return code;
- };
- Blockly.Blocks['ai_online_emotion_loading'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.emotion_load); //
- this.appendValueInput("path")
- .setCheck(null)
- .appendField(Blockly.Msg.online_face_init_path); //
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.emotion_load);
- this.setHelpUrl("");
- }
- }
- Blockly.Python.ai_online_emotion_loading = function (block) {
- let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC)
- Blockly.Python.definitions_['v831_import_base64'] = `import base64`
- Blockly.Python.definitions_['v831_import_requests'] = `import requests`
- Blockly.Python.definitions_['v831_import_json'] = `import json`
- Blockly.Python.addVariable("EMOTION_SEND_REQUEST", "EMOTION_SEND_REQUEST = {}", true);
- Blockly.Python.definitions_['emotion_init'] = `def get_img_base64str(single_image_path):
- with open(single_image_path, "rb") as fp:
- imgbase64 = base64.b64encode(fp.read())
- return imgbase64.decode()
- url = "https://ai-api.cocorobo.cn/face"
- `
- // let language = Blockly.Python.valueToCode(block, 'language', Blockly.Python.ORDER_ATOMIC);
- let code = `imageEmotionURLbase64 = str(get_img_base64str(${text}))
- # print(imageURLbase64)
- data = "{\\"image\\":\\"" + str(imageEmotionURLbase64) + "\\"}"
- try:
- EMOTION_SEND_REQUEST = requests.post(url, data = data , headers = { "Ocp-Apim-Subscription-Key": "6baf787532ef4eec8bc93c88518b8916", "Content-type": "application/json" }, timeout = 10000)
- EMOTION_SEND_REQUEST = json.loads(EMOTION_SEND_REQUEST.content)["data"]["result"]["face_list"][0]
- # print(str(_COCOCLOUD_SEND_REQUEST.status_code)+", "+str(_COCOCLOUD_SEND_REQUEST.content))
- except BaseException as e:
- EMOTION_SEND_REQUEST = "no result"
- pass
- `
- return code
- }
- Blockly.Blocks['ai_online_emotion_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.emotion_result)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.emotion_result_age, "age"],
- [Blockly.Msg.emotion_result_emotion, "emotion"],
- [Blockly.Msg.emotion_result_gender, "gender"],
- [Blockly.Msg.emotion_result_expression, "expression"]
- ]), "emotion_type");
- this.setOutput(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.emotion_result);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_online_emotion_result'] = function (block) {
- var type = block.getFieldValue('emotion_type');
- let code = ""
- // console.log(type)
- if (type == "age") {
- code = `EMOTION_SEND_REQUEST["age"]`
- } else {
- code = `EMOTION_SEND_REQUEST["${type}"]["type"]`
- }
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- // 手势识别
- Blockly.Blocks['ai_online_gesture_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.gesture_init); //
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.gesture_init);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_online_gesture_init'] = function (block) {
- // let = []
- // TODO: Assemble Python into code variable.
- Blockly.Python.definitions_['v831_import_fromPIL_Image'] = `from PIL import Image`
- Blockly.Python.definitions_['v831_import_base64'] = `import base64`
- Blockly.Python.definitions_['v831_import_requests'] = `import requests`
- Blockly.Python.definitions_['v831_import_json'] = `import json`
- Blockly.Python.definitions_['emotion_init'] = `
- def getImgData(single_image_path):
- imgGesture = Image.open(single_image_path).convert("RGB")
- imgGesture.save(single_image_path.split(".")[0] + ".png", "png")
- with open(single_image_path.split(".")[0] + ".png", "rb") as fp:
- return fp.read()
-
- url = "https://ai-api.cocorobo.hk/gesture"
- `
- var code = '';
- return code;
- };
- Blockly.Blocks['ai_online_gesture_loading'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.gesture_load);
- this.appendValueInput("path")
- .setCheck(null)
- .appendField(Blockly.Msg.online_face_init_path); //
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.gesture_load);
- this.setHelpUrl("");
- }
- }
- Blockly.Python.ai_online_gesture_loading = function (block) {
- let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC)
- Blockly.Python.definitions_['v831_import_fromPIL_Image'] = `from PIL import Image`
- Blockly.Python.definitions_['v831_import_base64'] = `import base64`
- Blockly.Python.definitions_['v831_import_requests'] = `import requests`
- Blockly.Python.definitions_['v831_import_json'] = `import json`
- Blockly.Python.definitions_['emotion_init'] = `
- def getImgData(single_image_path):
- imgGesture = Image.open(single_image_path).convert("RGB")
- imgGesture.save(single_image_path.split(".")[0] + ".png", "png")
- with open(single_image_path.split(".")[0] + ".png", "rb") as fp:
- return fp.read()
-
- url = "https://ai-api.cocorobo.cn/gesture"
- `
- let code = `try:
- payload={}
- files=[("image",("filename.png", getImgData(${text}),"image/png"))]
- headers = {}
- GESTURE_SEND_REQUEST = requests.post(url, headers=headers, data=payload, files=files, timeout = 10000)
- GESTURE_SEND_REQUEST = json.loads(GESTURE_SEND_REQUEST.content)["data"]["result"][0]["classname"]
- # print(str(_COCOCLOUD_SEND_REQUEST.status_code)+", "+str(_COCOCLOUD_SEND_REQUEST.content))
- except BaseException as e:
- GESTURE_SEND_REQUEST = "no result"
- pass
- `
- return code
- }
- Blockly.Blocks['ai_online_gesture_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.gesture_result);
- this.setOutput(true, null);
- this.setColour("#0000ff");
- this.setTooltip(Blockly.Msg.gesture_result);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_online_gesture_result'] = function (block) {
- let code = `GESTURE_SEND_REQUEST`
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks['ai_audio_set'] = {
- init: function () {
- this.appendValueInput("Num")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_audio_set_music_vol);
- this.setInputsInline(true);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#603ea0");
- this.setTooltip("");
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_audio_set = function (block) {
- var _num = Blockly.Python.valueToCode(block, 'Num', Blockly.Python.ORDER_ATOMIC);
- var _code = "_player.volume(" + _num + ")\n"
- return _code;
- }
- var SPEECH_RECOGNITION_BLOCK_COLOR = "230";
- Blockly.Blocks['speech_recognition_new_setup'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/speech_recognition_header_new.png", 70, 70, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_speech_recognition_setup);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.speech_recognition_new_setup_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['speech_recognition_new_setup'] = function (block) {
- Blockly.Python.definitions_["v831_import_coco_mfcc"] = `import _coco_mfcc`
- Blockly.Python.definitions_["v831_import_time"] = `import time`
- Blockly.Python.definitions_["v831_coco_mfcc_init"] = `mfcc = _coco_mfcc.MFCC(is_reply=False)`;
- Blockly.Python.addVariable("RecordState", "RecordState = 0", true);
- Blockly.Python.addVariable("recordFrequency", "recordFrequency = 0", true);
- Blockly.Python.addVariable("recordResultData", `recordResultData = None`, true);
- let code = ""
- return code;
- };
- Blockly.Blocks['speech_recognition_clear'] = {
- init: function () {
- // this.appendDummyInput()
- // .appendField(new Blockly.FieldImage("blockly/media/speech_recognition_header_new.png", 70, 70, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.speech_recognition_Clean_up_the_last_study_result);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.speech_recognition_Clean_up_the_last_study_result);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['speech_recognition_clear'] = function (block) {
- Blockly.Python.definitions_["v831_import_coco_mfcc"] = `import _coco_mfcc`
- Blockly.Python.definitions_["v831_coco_mfcc_init"] = `mfcc = _coco_mfcc.MFCC(is_reply=False)`;
- var code = `mfcc.clear()
- `;
- return code;
- };
- Blockly.Blocks['speech_recognition_record_start_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/speech_recognition_header_recording_new.png", 130, 60, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_speech_recognition_start_recording);
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_speech_recognition_start_recording_clip_text)
- .appendField(new Blockly.FieldNumber(2, 1, 6, 1), "clip")
- // .appendField(Blockly.Msg.ai_speech_recognition_start_recording_take_note);
- this.appendDummyInput()
- .appendField(Blockly.Msg.image_process_interface)
- .appendField(new Blockly.FieldVariable("recordCanvas"), "varitem");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_speech_recognition_start_recording);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['speech_recognition_record_start_result'] = function (block) {
- var number_take = block.getFieldValue('clip');
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- Blockly.Python.definitions_["v831_import_coco_mfcc"] = `import _coco_mfcc`
- Blockly.Python.definitions_["v831_import_time"] = `import time`
- Blockly.Python.definitions_["v831_coco_mfcc_init"] = `mfcc = _coco_mfcc.MFCC(is_reply=False)`;
- Blockly.Python.addVariable("RecordState", "RecordState = 0", true);
- Blockly.Python.addVariable("recordFrequency", "recordFrequency = 0", true);
- Blockly.Python.addVariable("recordResultData", `recordResultData = None`, true);
- Blockly.Python.addVariable('number_take', `number_take = ${number_take}`, true)
- Blockly.Python.definitions_["v831_mfcc_clear"] = `mfcc.clear()
- `
- Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
- Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
- Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
- def CAMERATYPE():
- global cameraSize
- try:
- if os.path.exists("/etc/cameraSize.cfg"):
- cameraSize = True
- else:
- cameraSize = False
- except:
- cameraSize = False
- CAMERATYPE()
- `
- Blockly.Python.addVariable("ScreenOrientation", `ScreenOrientation = False`, true)
- Blockly.Python.addVariable(variable_name, `${variable_name} = image.new(size = (320, 240))`, true)
- Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf")
- if cameraSize==True:
- camera.camera.config(size=(320,240))
- else:
- camera.camera.config(size=(240,320))
- `
- let idenSuccess = "录制成功";
- let speek = "说第";
- let SpeechFragment = "语音片段";
- if (localStorage.getItem('handPyLanguage') == "zh-hant") {
- idenSuccess = "錄製成功";
- speek = "說第 ";
- SpeechFragment = "語音片段";
- } else if (localStorage.getItem('handPyLanguage') == "en") {
- idenSuccess = "Recorded successfully";
- speek = "Speek ";
- SpeechFragment = "Speech fragment";
- }
- var code = `if RecordState == 0:
- mfcc.recording(recordFrequency)
- recordFrequency = recordFrequency + 1
- time.sleep(1)
- RecordState = 1
- if RecordState == 1:
- recordData = mfcc.state()
- if recordData == mfcc._mfcc_result:
- ${variable_name}.draw_string(0,80,"${idenSuccess}", scale = 2, color = (0,204,204) , thickness = 1)
- time.sleep(1)
- if recordFrequency < number_take:
- RecordState = 0
- else:
- ${variable_name}.draw_string(0,80, "${speek} "+str(recordFrequency)+" ${SpeechFragment}", scale = 2, color = (0,204,204) , thickness = 1)
- `
- return code
- };
- Blockly.Blocks['speech_recognition_new_start_recognition'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/speech_recognition_header_recognition_new.png", 130, 60, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_speech_recognition_start_recognizing);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.speech_recognition_new_start_recognition_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['speech_recognition_new_start_recognition'] = function (block) {
- Blockly.Python.definitions_["v831_import_coco_mfcc"] = `import _coco_mfcc`
- Blockly.Python.definitions_["v831_import_time"] = `import time`
- Blockly.Python.definitions_["v831_coco_mfcc_init"] = `mfcc = _coco_mfcc.MFCC(is_reply=False)`;
- Blockly.Python.addVariable("RecordState", "RecordState = 0", true);
- Blockly.Python.addVariable("recordFrequency", "recordFrequency = 0", true);
- Blockly.Python.addVariable("recordResultData", `recordResultData = None`, true);
- var code = `if RecordState == 0:
- mfcc.recognize()
- recordResultData = None
- time.sleep(1)
- RecordState = 1
- `
- return code
- };
- Blockly.Blocks['speech_recognition_new_recognition_get_any_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_speech_recognition_any_result_text);
- this.appendStatementInput("NAME")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_speech_recognition_any_result_text_do);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.speech_recognition_new_recognition_get_any_result_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['speech_recognition_new_recognition_get_any_result'] = function (block) {
- var statements_name = Blockly.Python.statementToCode(block, 'NAME');
- // TODO: Assemble Python into code variable.
- var code = `if RecordState == 1:
- recordData = mfcc.state()
- if recordData == mfcc._mfcc_result:
- recordResultData = mfcc.result()
- time.sleep(1)
- RecordState = 0
- ${statements_name}
- `;
- return code;
- };
- Blockly.Blocks['speech_recognition_new_recognition_get_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_speech_recognition_get_result)
- .appendField(new Blockly.FieldNumber(1, 1, 6, 1), "index")
- .appendField(Blockly.Msg.ai_speech_recognition_get_result_after);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.speech_recognition_new_recognition_get_result_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['speech_recognition_new_recognition_get_result'] = function (block) {
- var number_index = block.getFieldValue('index');
- // TODO: Assemble Python into code variable.
- var code = `recordResultData == ${number_index - 1}`;
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- /*
- _ ___ ____ _
- / \ |_ _| / ___| _ __ ___ __ _| | _____ _ __
- / _ \ | | \___ \| '_ \ / _ \/ _` | |/ / _ \ '__|
- / ___ \ _ | | _ ___) | |_) | __/ (_| | < __/ |
- /_/ \_(_)___(_) |____/| .__/ \___|\__,_|_|\_\___|_|
- |_|
- */
- Blockly.Blocks['ai_audio_init_speaker'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/speaker_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_audio_init);
- this.setColour("#5f7fc1");
- this.setTooltip(Blockly.Msg.ai_audio_init_speaker_TOOLTIP);
- this.setHelpUrl("");
- this.setPreviousStatement(true);
- this.setNextStatement(true);
- }
- };
- Blockly.Python.ai_audio_init_speaker = function (block) {
- Blockly.Python.definitions_.import_Maix = "from Maix import I2S, GPIO";
- Blockly.Python.definitions_.import_fpioa_manager = "from fpioa_manager import *";
- Blockly.Python.definitions_.import_audio = "import audio";
- var _code = "";
- return _code;
- }
- Blockly.Blocks['ai_audio_play_song_speaker'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_audio_play_music_file);
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol)
- // .appendField(new Blockly.FieldNumber(95, 0, 100, 1), "play_vol");
- this.appendValueInput("volume")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol);
- this.appendValueInput("path")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_audio_play_music_file_set_file_path);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#5f7fc1");
- this.setTooltip(Blockly.Msg.ai_audio_play_song_speaker_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_audio_play_song_speaker'] = function (block) {
- // var number_play_vol = block.getFieldValue('play_vol');
- var number_play_vol = Blockly.Python.valueToCode(block, 'volume', Blockly.Python.ORDER_ATOMIC);
- var value_name = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
- var _in = "" +
- "_audio_rx = I2S(I2S.DEVICE_1)\n" +
- "\n" +
- "def _speaker_play_song(path, volume):\n" +
- " global _audio_play_state,_player\n" +
- " _player = audio.Audio(path = path)\n" +
- " _player.volume(volume)\n" +
- " try:\n" +
- " _wav_info = _player.play_process(_audio_rx)\n" +
- " _audio_rx.channel_config(_audio_rx.CHANNEL_1, I2S.TRANSMITTER, resolution = I2S.RESOLUTION_16_BIT, align_mode = I2S.STANDARD_MODE)\n" +
- " _audio_rx.set_sample_rate(_wav_info[1])\n" +
- " _audio_play_state = 0\n" +
- "\n" +
- " fm.register(34,fm.fpioa.I2S1_OUT_D1)\n" +
- " fm.register(35,fm.fpioa.I2S1_SCLK)\n" +
- " fm.register(33,fm.fpioa.I2S1_WS)\n" +
- "\n" +
- " while True:\n" +
- " _audio_play_state = _player.play()\n" +
- " if (_audio_play_state) == True:\n" +
- " print(\"Playing.\")\n" +
- " elif (_audio_play_state) == False:\n" +
- " print(\"Done.\")\n" +
- " break\n" +
- "\n" +
- " except:\n" +
- " pass\n" +
- "\n";
- // Blockly.Python.definitions_.import_audio = _in;
- Blockly.Python.addVariable('_audio_play_state', _in, true);
- // Blockly.Python.addSetup("ai_audio_read", _in);
- var _code = "_speaker_play_song(path=" + value_name + ", volume=" + number_play_vol + ")\n";
- return _code;
- };
- Blockly.Blocks['ai_audio_play_finish_speaker'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_audio_end_play);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#5f7fc1");
- this.setTooltip(Blockly.Msg.ai_audio_play_finish_speaker_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_audio_play_finish_speaker'] = function (block) {
- // TODO: Assemble Python into code variable.
- var code = '_player.finish()\n';
- return code;
- };
- Blockly.Blocks['ai_audio_set_speaker'] = {
- init: function () {
- this.appendValueInput("Num")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_audio_set_music_vol);
- this.setInputsInline(true);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#5f7fc1");
- this.setTooltip(Blockly.Msg.ai_audio_set_speaker_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_audio_set_speaker = function (block) {
- var _num = Blockly.Python.valueToCode(block, 'Num', Blockly.Python.ORDER_ATOMIC);
- var _code = "_player.volume(" + _num + ")\n"
- return _code;
- }
- Blockly.Blocks['ai_audio_files_list'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_audio_files_list);
- this.appendValueInput("path")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_audio_files_list_set_file_path);
- this.setOutput(true, null);
- this.setColour("#5f7fc1");
- this.setTooltip(Blockly.Msg.ai_audio_files_list_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_audio_files_list = function (block) {
- var value_name = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- Blockly.Python.definitions_.import_ai_audio_files_list = '' +
- 'def getRawFileList(path):\n' +
- ' files = []\n' +
- ' for f in os.listdir(path):\n' +
- ' if (not f.endswith("~") or not f == "") and f.split(".")[1] == "wav":\n' +
- ' files.append(path + "/" + f)\n' +
- ' return files\n' +
- '\n';
- var code = 'getRawFileList(' + value_name + ')';
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_audio_play_song_list_loop_speaker'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_audio_play_music_file_list_loop);
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol)
- // .appendField(new Blockly.FieldNumber(95, 0, 100, 1), "play_vol");
- this.appendValueInput("volume")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol);
- // this.appendValueInput("path")
- // .setCheck(null)
- // .appendField(Blockly.Msg.ai_audio_play_music_file_set_file_path);
- this.appendValueInput("my_list")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_audio_play_music_file_set_files_list);
- this.appendValueInput("firstIndex")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_audio_play_music_file_set_first_index);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#5f7fc1");
- this.setTooltip(Blockly.Msg.ai_audio_play_song_speaker_list_loop_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_audio_play_song_list_loop_speaker'] = function (block) {
- // var number_play_vol = block.getFieldValue('play_vol');
- var number_play_vol = Blockly.Python.valueToCode(block, 'volume', Blockly.Python.ORDER_ATOMIC);
- // var value_name = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
- var my_list = Blockly.Python.valueToCode(block, 'my_list', Blockly.Python.ORDER_ATOMIC);
- var firstIndex = Blockly.Python.valueToCode(block, 'firstIndex', Blockly.Python.ORDER_ATOMIC);
- var _in = "" +
- "_audio_rx = I2S(I2S.DEVICE_1)\n" +
- "direction = 0\n" +
- "firstIndex = " + firstIndex + "\n" +
- "\n" +
- "# 上一首\n" +
- "def previous_song(index,my_list):\n" +
- " global direction\n" +
- " index = index - 1\n" +
- " direction = 1\n" +
- " if index == -1:\n" +
- " index = len(my_list) - 1\n" +
- " return index\n" +
- "\n" +
- "# 切换上一首\n" +
- "def change_previous_song(index):\n" +
- " global _audio_play_state,direction,firstIndex,_player\n" +
- " _player.finish()\n" +
- " _audio_play_state = 0\n" +
- " firstIndex = index\n" +
- " direction = 1\n" +
- "\n" +
- "# 下一首\n" +
- "def next_song(index,my_list):\n" +
- " global direction\n" +
- " index = index + 1\n" +
- " direction = 2\n" +
- " if index == len(my_list):\n" +
- " index = 0\n" +
- " return index\n" +
- "\n" +
- "# 切换下一首\n" +
- "def change_next_song(index):\n" +
- " global _audio_play_state,direction,firstIndex,_player\n" +
- " _player.finish()\n" +
- " _audio_play_state = 0\n" +
- " firstIndex = index\n" +
- " direction = 2\n" +
- "\n" +
- "def _speaker_play_song_list_loop(volume, my_list):\n" +
- " global _audio_play_state,_player,firstIndex,play_again,direction\n" +
- " _player = audio.Audio(path = my_list[firstIndex])\n" +
- " _player.volume(volume)\n" +
- " try:\n" +
- // " firstIndex = index\n" +
- " _wav_info = _player.play_process(_audio_rx)\n" +
- " _audio_rx.channel_config(_audio_rx.CHANNEL_1, I2S.TRANSMITTER, resolution = I2S.RESOLUTION_16_BIT, align_mode = I2S.STANDARD_MODE)\n" +
- " _audio_rx.set_sample_rate(_wav_info[1])\n" +
- " _audio_play_state = 0\n" +
- "\n" +
- " fm.register(34,fm.fpioa.I2S1_OUT_D1)\n" +
- " fm.register(35,fm.fpioa.I2S1_SCLK)\n" +
- " fm.register(33,fm.fpioa.I2S1_WS)\n" +
- "\n" +
- " button_a_state = False\n" +
- " button_b_state = False\n" +
- " while True:\n" +
- " _audio_play_state = _player.play()\n" +
- " if (_audio_play_state) == True:\n" +
- " #print(\"Playing.\")\n" +
- " if (_gp_side_a.value() == 1) and button_a_state == False:\n" +
- " index = previous_song(firstIndex,my_list)\n" +
- " button_a_state = True\n" +
- " elif (_gp_side_a.value() == 0) and button_a_state == True:\n" +
- " button_a_state = False\n" +
- " change_previous_song(index)\n" +
- " break\n" +
- " if (_gp_side_b.value() == 1) and button_b_state == False:\n" +
- " index = next_song(firstIndex,my_list)\n" +
- " button_b_state = True\n" +
- " elif (_gp_side_b.value() == 0) and button_b_state == True:\n" +
- " button_b_state = False\n" +
- " change_next_song(index)\n" +
- " break\n" +
- "\n" +
- " elif (_audio_play_state) == False:\n" +
- " #print(\"Done.\")\n" +
- " index = firstIndex + 1\n" +
- " if index == len(my_list):\n" +
- " index = 0\n" +
- " firstIndex = index\n" +
- " break\n" +
- "\n" +
- " except:\n" +
- " play_again = True\n" +
- " if direction == 0:\n" +
- " direction = 3\n" +
- " return\n" +
- "\n";
- // Blockly.Python.definitions_.import_audio = _in;
- Blockly.Python.addVariable('_audio_play_list_loop_state', _in, true);
- Blockly.Python.definitions_['import_define_x_ai_button'] = '' +
- 'from fpioa_manager import *\n' +
- 'from Maix import FPIOA, GPIO\n' +
- '\n' +
- '_gp_side_buttons = [9, 10, 11]\n' +
- '\n' +
- 'FPIOA().set_function(_gp_side_buttons[0],FPIOA.GPIO0)\n' +
- 'FPIOA().set_function(_gp_side_buttons[1],FPIOA.GPIO1)\n' +
- 'FPIOA().set_function(_gp_side_buttons[2],FPIOA.GPIO2)\n' +
- '\n' +
- '_gp_side_a = GPIO(GPIO.GPIO0,GPIO.IN,GPIO.PULL_UP)\n' +
- '_gp_side_b = GPIO(GPIO.GPIO1,GPIO.IN,GPIO.PULL_UP)\n' +
- '_gp_side_c = GPIO(GPIO.GPIO2,GPIO.IN,GPIO.PULL_UP)\n' +
- '\n';
- // Blockly.Python.addSetup("ai_audio_read", _in);
- var _code = "_speaker_play_song_list_loop(volume=" + number_play_vol + ", my_list=" + my_list + ")\n";
- return _code;
- };
- Blockly.Blocks['ai_audio_play_song_list_random_speaker'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_audio_play_music_file_list_random);
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol)
- // .appendField(new Blockly.FieldNumber(95, 0, 100, 1), "play_vol");
- this.appendValueInput("volume")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol);
- // this.appendValueInput("path")
- // .setCheck(null)
- // .appendField(Blockly.Msg.ai_audio_play_music_file_set_file_path);
- this.appendValueInput("my_list")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_audio_play_music_file_set_files_list);
- this.appendValueInput("firstIndex")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_audio_play_music_file_set_first_index);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#5f7fc1");
- this.setTooltip(Blockly.Msg.ai_audio_play_music_file_list_random_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_audio_play_song_list_random_speaker'] = function (block) {
- // var number_play_vol = block.getFieldValue('play_vol');
- var number_play_vol = Blockly.Python.valueToCode(block, 'volume', Blockly.Python.ORDER_ATOMIC);
- // var value_name = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
- var my_list = Blockly.Python.valueToCode(block, 'my_list', Blockly.Python.ORDER_ATOMIC);
- var firstIndex = Blockly.Python.valueToCode(block, 'firstIndex', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_['v831_import_time'] = `import time`
- Blockly.Python.definitions_['v831_import_random'] = `import random`
- var _in = "" +
- "random.seed(time.ticks_cpu())\n" +
- "\n" +
- "_audio_rx = I2S(I2S.DEVICE_1)\n" +
- "firstIndex = " + firstIndex + "\n" +
- "\n" +
- "# 随机一首\n" +
- "def random_song(index,my_list):\n" +
- " index = random.randrange(0, len(my_list), 1)\n" +
- " return index\n" +
- "\n" +
- "# 切换歌曲\n" +
- "def change_random_song(index):\n" +
- " global _audio_play_state,firstIndex,_player\n" +
- " _player.finish()\n" +
- " _audio_play_state = 0\n" +
- " firstIndex = index\n" +
- "\n" +
- "def _speaker_play_song_list_random(volume, my_list):\n" +
- " global _audio_play_state,_player,firstIndex,play_again\n" +
- " _player = audio.Audio(path = my_list[firstIndex])\n" +
- " _player.volume(volume)\n" +
- " try:\n" +
- // " firstIndex = index\n" +
- " _wav_info = _player.play_process(_audio_rx)\n" +
- " _audio_rx.channel_config(_audio_rx.CHANNEL_1, I2S.TRANSMITTER, resolution = I2S.RESOLUTION_16_BIT, align_mode = I2S.STANDARD_MODE)\n" +
- " _audio_rx.set_sample_rate(_wav_info[1])\n" +
- " _audio_play_state = 0\n" +
- "\n" +
- " fm.register(34,fm.fpioa.I2S1_OUT_D1)\n" +
- " fm.register(35,fm.fpioa.I2S1_SCLK)\n" +
- " fm.register(33,fm.fpioa.I2S1_WS)\n" +
- "\n" +
- " button_a_state = False\n" +
- " while True:\n" +
- " _audio_play_state = _player.play()\n" +
- " if (_audio_play_state) == True:\n" +
- " #print(\"Playing.\")\n" +
- " if (_gp_side_a.value() == 1) and button_a_state == False:\n" +
- " index = random_song(firstIndex,my_list)\n" +
- " button_a_state = True\n" +
- " elif (_gp_side_a.value() == 0) and button_a_state == True:\n" +
- " button_a_state = False\n" +
- " change_random_song(index)\n" +
- " break\n" +
- "\n" +
- " elif (_audio_play_state) == False:\n" +
- " #print(\"Done.\")\n" +
- " index = random_song(firstIndex,my_list)\n" +
- " firstIndex = index\n" +
- " break\n" +
- "\n" +
- " except:\n" +
- " play_again = True\n" +
- " return\n" +
- "\n";
- // Blockly.Python.definitions_.import_audio = _in;
- Blockly.Python.addVariable('_audio_play_list_random_state', _in, true);
- Blockly.Python.definitions_['import_define_x_ai_button'] = '' +
- 'from fpioa_manager import *\n' +
- 'from Maix import FPIOA, GPIO\n' +
- '\n' +
- '_gp_side_buttons = [9, 10, 11]\n' +
- '\n' +
- 'FPIOA().set_function(_gp_side_buttons[0],FPIOA.GPIO0)\n' +
- 'FPIOA().set_function(_gp_side_buttons[1],FPIOA.GPIO1)\n' +
- 'FPIOA().set_function(_gp_side_buttons[2],FPIOA.GPIO2)\n' +
- '\n' +
- '_gp_side_a = GPIO(GPIO.GPIO0,GPIO.IN,GPIO.PULL_UP)\n' +
- '_gp_side_b = GPIO(GPIO.GPIO1,GPIO.IN,GPIO.PULL_UP)\n' +
- '_gp_side_c = GPIO(GPIO.GPIO2,GPIO.IN,GPIO.PULL_UP)\n' +
- '\n';
- // Blockly.Python.addSetup("ai_audio_read", _in);
- var _code = "_speaker_play_song_list_random(volume=" + number_play_vol + ", my_list=" + my_list + ")\n";
- return _code;
- };
- /*
- _ ___ __ ___ _
- / \ |_ _| \ \ / (_) __| | ___ ___
- / _ \ | | \ \ / /| |/ _` |/ _ \/ _ \
- / ___ \ | | \ V / | | (_| | __/ (_) |
- /_/ \_\___| \_/ |_|\__,_|\___|\___/
- */
- Blockly.Blocks['ai_video_record_setup'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/video_record_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_video_start_recording);
- this.appendValueInput("save_path")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_video_start_recording_file_path);
- this.appendValueInput("w")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_video_start_recording_width);
- this.appendValueInput("h")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_video_start_recording_height);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#60c1bb");
- this.setTooltip(Blockly.Msg.ai_video_record_setup_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_video_record_setup'] = function (block) {
- var value_save_path = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC);
- var value_w = Blockly.Python.valueToCode(block, 'w', Blockly.Python.ORDER_ATOMIC);
- var value_h = Blockly.Python.valueToCode(block, 'h', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_.import_video = "import video";
- Blockly.Python.definitions_.import_Maix = "from Maix import GPIO";
- Blockly.Python.addVariable('record_vid', 'record_vid = None', true);
- // TODO: Assemble Python into code variable.
- var code = "_record_vid = video.open(" + value_save_path + ", record=1, width=" + value_w + ", height=" + value_h + ", interval=20000, quality=80)\n";
- return code;
- };
- Blockly.Blocks['ai_video_get'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_video_to_canvas)
- .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- .appendField(Blockly.Msg.ai_video_record);
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#60c1bb");
- this.setTooltip(Blockly.Msg.ai_video_get_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_video_get = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var _code = "_record_vid.record(" + variable_name + ")\n"
- return _code;
- }
- Blockly.Blocks['ai_video_stop'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_video_stop_recording);
- this.setPreviousStatement(true);
- this.setNextStatement(true);
- this.setColour("#60c1bb");
- this.setTooltip(Blockly.Msg.ai_video_stop_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_video_stop = function (block) {
- var _code = "_record_vid.record_finish()\n"
- return _code;
- }
- Blockly.Blocks['ai_video_set_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/video_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_video_set_play_init);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#4d9994");
- this.setTooltip(Blockly.Msg.ai_video_set_play_init);
- this.setHelpUrl("");
- }
- }
- Blockly.Python['ai_video_set_init'] = function (block) {
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio`
- Blockly.Python.definitions_['v831_import_av'] = `import av`
- Blockly.Python.definitions_['v831_import_from_maix_display'] = `from maix import display`
- Blockly.Python.definitions_['v831_import_from_maix_camera'] = `from maix import camera`
- Blockly.Python.definitions_['v831_import_from_maix_image'] = `from maix import image`
- // Blockly.Python.addVariable("VIDEOPLAY",`VIDEOPLAY = False`,true)
- let code = ``
- return code;
- }
- Blockly.Blocks['ai_video_set'] = {
- init: function () {
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_video_play_video);
- this.appendValueInput("path")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_video_play_video_file_path);
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_video_play_video_2);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#4d9994");
- this.setTooltip(Blockly.Msg.ai_video_play_video);
- this.setHelpUrl("https://cn.maixpy.sipeed.com/maixpy/zh/api_reference/media/video.html#1-avi");
- }
- };
- Blockly.Python['ai_video_set'] = function (block) {
- // Blockly.Python.definitions_.import_Maix = "from maix import display, camera, image";
- var value_path = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
- var code = `pathToVideo = ${value_path}
- containerVideo = av.open(pathToVideo)
- streamVideo = containerVideo.streams.video[0]
- `
- return code;
- };
- Blockly.Blocks['ai_video_set_stats'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_video_set_play_stats);
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_video_play_video_2);
- this.setOutput(true, null)
- this.setColour("#4d9994");
- this.setTooltip(Blockly.Msg.ai_video_set_play_stats);
- this.setHelpUrl("https://cn.maixpy.sipeed.com/maixpy/zh/api_reference/media/video.html#1-avi");
- }
- };
- Blockly.Python['ai_video_set_stats'] = function (block) {
- var code = `containerVideo.decode(video=0)`
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_video_set_play'] = {
- init: function () {
- this.appendDummyInput().appendField(Blockly.Msg.ai_models_from)
- .appendField(new Blockly.FieldVariable("i"), "varitem")
- .appendField(Blockly.Msg.ai_video_set_play);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#4d9994");
- this.setTooltip(Blockly.Msg.ai_video_set_play);
- this.setHelpUrl("");
- }
- }
- Blockly.Python['ai_video_set_play'] = function (block) {
- var value = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- let code = `if "Video" in repr(${value}):
- VideoImg = image.load(bytes(${value}.to_rgb().planes[0]), (streamVideo.width, streamVideo.height))
- display.show(VideoImg)
- `
- return code;
- }
- Blockly.Blocks['ai_video_stop_play'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_video_stop_video_playing);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#4d9994");
- this.setTooltip(Blockly.Msg.ai_video_stop_play_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_video_stop_play'] = function (block) {
- // TODO: Assemble Python into code variable.
- var code = `break
- `;
- return code;
- };
- Blockly.Blocks['ai_video_record_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/video_record_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_video_start_recording);
- this.appendValueInput("save_path")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_video_start_recording_file_path);
- this.appendValueInput("w")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_video_start_recording_width);
- this.appendValueInput("h")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_video_start_recording_height);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#4d9994");
- this.setTooltip(Blockly.Msg.ai_video_record_setup_TOOLTIP);
- // this.setHelpUrl("https://cn.maixpy.sipeed.com/maixpy/zh/api_reference/media/video.html#1-avi");
- }
- };
- Blockly.Python['ai_video_record_init'] = function (block) {
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio`
- Blockly.Python.definitions_['v831_import_av'] = `import av`
- Blockly.Python.definitions_['v831_import_from_maix_display'] = `from maix import display`
- Blockly.Python.definitions_['v831_import_from_maix_camera'] = `from maix import camera`
- Blockly.Python.definitions_['v831_import_from_maix_image'] = `from maix import image`
- var value_path = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC);
- var w = Blockly.Python.valueToCode(block, 'w', Blockly.Python.ORDER_ATOMIC);
- var h = Blockly.Python.valueToCode(block, 'h', Blockly.Python.ORDER_ATOMIC);
- var code = `path_to_video = ${value_path}
- fps = 10
- container = av.open(path_to_video, mode='w')
- stream = container.add_stream('h264', rate=fps) # h264 or mpeg4
- stream.width = ${w}
- stream.height = ${h}
- stream.pix_fmt = 'yuv420p'
-
- `
- return code;
- };
- Blockly.Blocks['ai_video_record_get'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_video_to_canvas)
- .appendField(new Blockly.FieldVariable("canvas"), "varitem")
- .appendField(Blockly.Msg.ai_video_record);
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#4d9994");
- this.setTooltip(Blockly.Msg.ai_video_get_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_video_record_get = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var _code = `frame = av.VideoFrame(${variable_name}.width, ${variable_name}.height, 'rgb24')
- frame.planes[0].update(${variable_name}.tobytes())
- for packet in stream.encode(frame):
- container.mux(packet)
- `
- return _code;
- }
- Blockly.Blocks['ai_video_record_stop'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_video_stop_recording);
- this.setPreviousStatement(true);
- this.setNextStatement(true);
- this.setColour("#4d9994");
- this.setTooltip(Blockly.Msg.ai_video_stop_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_video_record_stop = function (block) {
- var _code = `
- #Flush stream
- for packet in stream.encode():
- container.mux(packet)
-
- #Close the file
- container.close()
- `
- return _code;
- }
- // 视频录制
- Blockly.Blocks['ai_video_record'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/video_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_video_recording_and_save);
- this.appendValueInput("path")
- .setCheck(null)
- .appendField(Blockly.Msg.VIDEO_SET_P);
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_video_play_video_2);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#4d9994");
- this.setTooltip(Blockly.Msg.ai_video_set_TOOLTIP);
- this.setHelpUrl("https://cn.maixpy.sipeed.com/maixpy/zh/api_reference/media/video.html#1-avi");
- }
- };
- Blockly.Python['ai_video_record'] = function (block) {
- var value_path = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_['v831_import_time'] = `import time`
- Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio`
- Blockly.Python.definitions_['v831_import_av'] = `import av`
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- Blockly.Python.definitions_['v831_import_from_maix_display'] = `import display`
- Blockly.Python.definitions_['v831_import_from_maix_camera'] = `import camera`
- Blockly.Python.definitions_['v831_import_from_maix_image'] = `import image`
- var code = `path_to_video = ${value_path};
- duration, fps = 4, 10
- total_frames = duration * fps
- container = av.open(path_to_video, mode='w')
- stream = container.add_stream('h264', rate=fps) # h264 or mpeg4
- stream.width = 320
- stream.height = 240
- stream.pix_fmt = 'yuv420p'
- for frame_i in range(total_frames):
- img = image.new(size=(stream.width, stream.height), mode='RGB')
- img.draw_string(0, 0, str(time.time()), 2)
- frame = av.VideoFrame(img.width, img.height, 'rgb24')
- frame.planes[0].update(img.tobytes())
- for packet in stream.encode(frame):
- container.mux(packet)
-
- #Flush stream
- for packet in stream.encode():
- container.mux(packet)
-
- #Close the file
- container.close()
-
- #Play the video
-
- container = av.open(path_to_video)
- stream = container.streams.video[0]
- for frame in container.decode(video=0):
- if 'Video' in repr(frame):
- img = image.load(bytes(frame.to_rgb().planes[0]), (stream.width, stream.height))
- display.show(img)`
- return code;
- };
- Blockly.Blocks['ai_video_status'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_video_get_video_playing_status);
- this.setOutput(true, null);
- this.setColour("#4d9994");
- this.setTooltip(Blockly.Msg.ai_video_status_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_video_status = function (block) {
- var code = "_video_play.play()";
- return [code, Blockly.Python.ORDER_NONE];
- }
- /*
- _ ___ __ __ _ _
- / \ |_ _| | \/ | ___ __| | ___| |___
- / _ \ | | | |\/| |/ _ \ / _` |/ _ \ / __|
- / ___ \ | | | | | | (_) | (_| | __/ \__ \
- /_/ \_\___| |_| |_|\___/ \__,_|\___|_|___/
- */
- Blockly.Blocks['ai_model_allinit'] = {
- init: function () {
- // let types = getLocalStorage("isQiehuan");
- // if (!types) {
- // saveLocalStorage("isQiehuan", 0);
- // }
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_init_title)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_models_init_hand_written_model, "Single Digit Recognition"],
- [Blockly.Msg.ai_models_init_object_model, "Common Object Recognition"],
- [Blockly.Msg.ai_models_init_face_model, "Human Face Recognition"]
- ]), "DEGREE");
- this.appendDummyInput().appendField(Blockly.Msg.ai_model_allinit_language).appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_speech_recognition_setup_set_english, "English"],
- [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "Simplified Chinese"],
- [Blockly.Msg.ai_speech_recognition_setup_set_traditional_chinese, "Traditional Chinese"]
- ]), "interface")
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_camera_camera_fit_set1)
- // .appendField(new Blockly.FieldVariable("img_mnist"), "camera_varitem");
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_models_init_source)
- // .appendField(new Blockly.FieldVariable("img_mnist"), "varitem");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('DEGREE');
- var TOOLTIPS = {
- 'Single Digit Recognition': Blockly.Msg.ai_model_allinit_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_hand_written_model),
- 'Common Object Recognition': Blockly.Msg.ai_model_allinit_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model),
- 'Human Face Recognition': Blockly.Msg.ai_model_allinit_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_face_model)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_model_allinit = function (block) {
- Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
- var degee = block.getFieldValue('DEGREE');
- var _code = "";
- if (degee == "Single Digit Recognition") {
- Blockly.Python.addVariable('task_mnist', "task_mnist = kpu.load(\"/sd/preset/models/mnist.kmodel\")\n", true);
- } else if (degee == "Common Object Recognition") {
- var language = localStorage.getItem("handPyLanguage");
- Blockly.Python.addVariable('task_objectrecognition', 'task_objectrecognition = None', true);
- if (language == "en") {
- _code = '' +
- 'classes_objectrecognition = [\'aeroplane\', \'bicycle\', \'bird\', \'boat\', \'bottle\', \'bus\', \'car\', \'cat\', \'chair\', \'cow\', \'diningtable\', \'dog\', \'horse\', \'motorbike\', \'person\', \'pottedplant\', \'sheep\', \'sofa\', \'train\', \'tvmonitor\']\n' +
- 'task_objectrecognition = kpu.load("/sd/preset/models/tinyyolo_v2_20class.kmodel")\n' +
- 'object_anchor = (1.08, 1.19, 3.42, 4.41, 6.63, 11.38, 9.42, 5.11, 16.62, 10.52)\n' +
- 'a = kpu.init_yolo2(task_objectrecognition, 0.5, 0.3, 5, object_anchor)\n' +
- '';
- }
- else if (language == "zh-hans") {
- _code = '' +
- 'classes_objectrecognition = [\'飞机\', \'自行车\', \'鸟\', \'船\', \'瓶子\', \'公共汽车\', \'汽车\', \'猫\', \'椅子\', \'牛\', \'餐桌\', \'狗\', \'马\', \'摩托车\', \'人\', \'盆栽\', \'羊\', \'沙发\', \'火车\', \'电视监视器\']\n' +
- 'task_objectrecognition = kpu.load("/sd/preset/models/tinyyolo_v2_20class.kmodel")\n' +
- 'object_anchor = (1.08, 1.19, 3.42, 4.41, 6.63, 11.38, 9.42, 5.11, 16.62, 10.52)\n' +
- 'a = kpu.init_yolo2(task_objectrecognition, 0.5, 0.3, 5, object_anchor)\n' +
- '';
- }
- else {
- _code = '' +
- 'classes_objectrecognition = [\'飛機\', \'自行車\', \'鳥\', \'船\', \'瓶子\', \'公共汽車\', \'汽車\', \'貓\', \'椅子\', \'牛\', \'餐桌\', \'狗\', \'馬\', \'摩托車\', \'人\', \'盆栽\', \'羊\', \'沙發\', \'火車\', \'電視監視器\']\n' +
- 'task_objectrecognition = kpu.load("/sd/preset/models/tinyyolo_v2_20class.kmodel")\n' +
- 'object_anchor = (1.08, 1.19, 3.42, 4.41, 6.63, 11.38, 9.42, 5.11, 16.62, 10.52)\n' +
- 'a = kpu.init_yolo2(task_objectrecognition, 0.5, 0.3, 5, object_anchor)\n' +
- '';
- }
- } else {
- Blockly.Python.addVariable('task_facerecognition', 'task_facerecognition = None', true);
- _code = "" +
- "task_facerecognition = kpu.load(\"/sd/preset/models/preset/face-recognition.kmodel\")\n" +
- "anchor_face = (1.889, 2.5245, 2.9465, 3.94056, 3.99987, 5.3658, 5.155437, 6.92275, 6.718375, 9.01025)\n" +
- "a = kpu.init_yolo2(task_facerecognition, 0.5, 0.3, 5, anchor_face)\n" +
- "\n";
- }
- return _code;
- }
- // 边缘检测
- Blockly.Blocks['ai_model_edge_init'] = {
- init: function () {
- // let types = getLocalStorage("isQiehuan");
- // if (!types) {
- // saveLocalStorage("isQiehuan", 0);
- // }
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_init_title)
- .appendField(Blockly.Msg.ai_models_edge_detection_model);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_models_init_title + Blockly.Msg.ai_models_edge_detection_model);
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_model_edge_init = function (block) {
- Blockly.Python.definitions_['v831_import_numpy_as_np'] = `import numpy as np`
- Blockly.Python.definitions_.import_KPU = `
- class Edge:
- model = {
- "param": "/root/preset/model/sobel_int8.param",
- "bin": "/root/preset/model/sobel_int8.bin"
- }
- input_size = (224, 224, 3)
- output_size = (222, 222, 3)
- options = {
- "model_type": "awnn",
- "inputs": {
- "input0": input_size
- },
- "outputs": {
- "output0": output_size
- },
- "mean": [127.5, 127.5, 127.5],
- "norm": [0.0078125, 0.0078125, 0.0078125],
- }
- def __init__(self):
- from maix import nn
- print("-- load model:", self.model)
- self.model = nn.load(self.model, opt=self.options)
- print("-- load ok")
- def __del__(self):
- del self.model
- m = Edge()`;
- // var degee = block.getFieldValue('DEGREE');
- var _code = "";
- return _code;
- }
- // 加载边缘检测模型
- Blockly.Blocks['ai_model_edge_loading'] = {
- init: function () {
- // let types = getLocalStorage("isQiehuan");
- // if (!types) {
- // saveLocalStorage("isQiehuan", 0);
- // }
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_load_edge_detection_model);
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_models_init_source)
- // .appendField(new Blockly.FieldVariable("img_edgedetection"), "varitem");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- // var thisBlock = this;
- this.setTooltip(Blockly.Msg.ai_models_load_edge_detection_model);
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_model_edge_loading = function (block) {
- // var degee = block.getFieldValue('varitem');
- Blockly.Python.definitions_['v831_import_numpy_as_np'] = `import numpy as np`
- Blockly.Python.definitions_.import_KPU = `
- class Edge:
- model = {
- "param": "/root/preset/model/sobel_int8.param",
- "bin": "/root/preset/model/sobel_int8.bin"
- }
- input_size = (224, 224, 3)
- output_size = (222, 222, 3)
- options = {
- "model_type": "awnn",
- "inputs": {
- "input0": input_size
- },
- "outputs": {
- "output0": output_size
- },
- "mean": [127.5, 127.5, 127.5],
- "norm": [0.0078125, 0.0078125, 0.0078125],
- }
- def __init__(self):
- from maix import nn
- print("-- load model:", self.model)
- self.model = nn.load(self.model, opt=self.options)
- print("-- load ok")
- def __del__(self):
- del self.model
- m = Edge()`;
- // ${degee} = camera.capture().resize(224,224)
- var _code = `canvas = canvas.resize(224, 224, padding = 0)
- out = m.model.forward(canvas, quantize=True, layout="hwc")
- out = out.astype(np.float32).reshape(m.output_size)
- out = (np.ndarray.__abs__(out) * 255 / out.max()).astype(np.uint8)
- data = out.tobytes()
- canvas = canvas.load(data,(222, 222), mode="RGB")
- `;
- return _code;
- }
- // 获取边缘测试模型结果
- Blockly.Blocks['ai_model_edge_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_get_edge_detection_result);
- this.setOutput(true, null);
- // this.setNextStatement(true, null);
- this.setColour("#ee783a");
- // var thisBlock = this;
- this.setTooltip(Blockly.Msg.ai_models_get_edge_detection_result);
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_model_edge_result = function (block) {
- var degee = block.getFieldValue('varitem');
- var _code = "edgeModel";
- return [_code, Blockly.Python.ORDER_ATOMIC];
- }
- Blockly.Blocks['ai_model_allload'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_load_title)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_models_init_hand_written_model, "Single Digit Recognition"],
- [Blockly.Msg.ai_models_init_object_model, "Common Object Recognition"],
- [Blockly.Msg.ai_models_init_face_model, "Human Face Recognition"]
- ]), "DEGREE");
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_camera_camera_fit_set1)
- // .appendField(new Blockly.FieldVariable("img_mnist"), "camera_varitem");
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_init_source)
- .appendField(new Blockly.FieldVariable("img_mnist"), "varitem");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('DEGREE');
- var TOOLTIPS = {
- 'Single Digit Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_hand_written_model),
- 'Common Object Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model),
- 'Human Face Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_face_model)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_model_allload = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- // var camera_variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('camera_varitem'), Blockly.Variables.NAME_TYPE);
- Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
- var degee = block.getFieldValue('DEGREE');
- var _code = ""
- if (degee == "Single Digit Recognition") {
- // Blockly.Python.addVariable('img_mnist_resized', '', true);
- _code += "img_mnist1=" + variable_name + ".to_grayscale(1)\n";
- _code += "img_mnist_resized=img_mnist1.resize(28,28)\n";
- _code += "a=img_mnist_resized.invert()\n";
- _code += "a=img_mnist_resized.strech_char(1)\n";
- _code += "a=img_mnist_resized.pix_to_ai()\n";
- _code += "fmap_mnist=kpu.forward(task_mnist, img_mnist_resized)\n";
- _code += "plist_mnist=fmap_mnist[:]\n";
- _code += "pmax_mnist=max(plist_mnist)\n";
- _code += "max_index_mnist=plist_mnist.index(pmax_mnist)\n";
- } else if (degee == "Common Object Recognition") {
- // Blockly.Python.addVariable('code_objectrecognition', '', true);
- _code += "code_objectrecognition = kpu.run_yolo2(task_objectrecognition, " + variable_name + ")\n";
- _code += variable_name + ".ai_to_pix()\n";
- } else {
- // Blockly.Python.addVariable('code_facerecognition', '', true);
- _code += "code_facerecognition = kpu.run_yolo2(task_facerecognition, " + variable_name + ")\n";
- _code += variable_name + ".ai_to_pix()\n";
- }
- return _code;
- }
- Blockly.Blocks['ai_model_index_init'] = {
- init: function () {
- this.appendValueInput("class_input")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_models_init_title)
- // .appendField("DEGREE");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_models_init_title);
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_model_index_init = function (block) {
- var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
- console.log('value_class_input', value_class_input)
- var _code = value_class_input;
- // Blockly.Python.addVariable('task_mnist', "task_mnist = kpu.load(\"/sd/preset/models/mnist.kmodel\")\n", true);
- return _code;
- }
- // 手写数字识别
- Blockly.Blocks['ai_model_look_written_model'] = {
- init: function () {
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_models_init_title)
- // .appendField(new Blockly.FieldDropdown([
- // [Blockly.Msg.ai_models_init_hand_written_model, "Human Face Recognition"]
- // ]), "DEGREE");
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_init_hand_written_model);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_models_init_title + Blockly.Msg.ai_models_init_hand_written_model);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_model_look_written_model = function (block) {
- // Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
- var _code = "task_mnist = kpu.load(\"/sd/preset/models/mnist.kmodel\")\n";
- return [_code, Blockly.Python.ORDER_ATOMIC];
- }
- Blockly.Blocks['ai_model_look_written_model_old'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_init_title)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_models_init_hand_written_model, "Human Face Recognition"]
- ]), "DEGREE");
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_models_init_hand_written_model);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_models_init_title + Blockly.Msg.ai_models_init_hand_written_model);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_model_look_written_model_old = function (block) {
- Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
- var _code = "task_mnist = kpu.load(\"/sd/preset/models/mnist.kmodel\")\n";
- return _code;
- }
- Blockly.Blocks['ai_model_index_load'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_load_title)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_models_init_hand_written_model, "Single Digit Recognition"]
- ]), "DEGREE");
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_init_source)
- .appendField(new Blockly.FieldVariable("img_mnist"), "varitem");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('DEGREE');
- var TOOLTIPS = {
- 'Single Digit Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_hand_written_model)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_model_index_load = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- // var camera_variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('camera_varitem'), Blockly.Variables.NAME_TYPE);
- Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
- var degee = block.getFieldValue('DEGREE');
- var _code = ""
- if (degee == "Single Digit Recognition") {
- // Blockly.Python.addVariable('img_mnist_resized', '', true);
- _code += "img_mnist1=" + variable_name + ".to_grayscale(1)\n";
- _code += "img_mnist_resized=img_mnist1.resize(28,28)\n";
- _code += "a=img_mnist_resized.invert()\n";
- _code += "a=img_mnist_resized.strech_char(1)\n";
- _code += "a=img_mnist_resized.pix_to_ai()\n";
- _code += "fmap_mnist=kpu.forward(task_mnist, img_mnist_resized)\n";
- _code += "plist_mnist=fmap_mnist[:]\n";
- _code += "pmax_mnist=max(plist_mnist)\n";
- _code += "max_index_mnist=plist_mnist.index(pmax_mnist)\n";
- }
- return _code;
- }
- Blockly.Blocks['ai_model_index_mnist'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/digit_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_hand_written_model_result);
- this.appendDummyInput()
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_models_hand_written_model_number, "c"],
- [Blockly.Msg.ai_models_hand_written_model_confidence, "confidence"]
- ]), "value");
- this.setOutput(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_index_mnist_TOOLTIP);
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_model_index_mnist = function (block) {
- var value = block.getFieldValue('value');
- var _code = "max_index_mnist";
- if (value == "confidence") {
- _code = "int(pmax_mnist*100)";
- }
- return [_code, Blockly.Python.ORDER_ATOMIC];
- }
- Blockly.Blocks['ai_model_digital_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_init_title)
- .appendField(Blockly.Msg.ai_models_init_hand_written_model);
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_models_init_hand_written_model);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_models_init_title + Blockly.Msg.ai_models_init_hand_written_model);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_model_digital_init = function (block) {
- // Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
- Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
- Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
- var _code = `
- class Number_recognition:
- mdsc_path = "/root/preset/model/Number.mud"
- labels = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
- anchors = [1.0, 5.0, 1.35, 5.42, 0.49, 2.55, 0.86, 3.75, 0.65, 4.38]
- def __init__(self):
- self.model = nn.load(self.mdsc_path)
- self.decoder = decoder.Yolo2(len(self.labels) , self.anchors , net_in_size = (224, 224) ,net_out_size = (7,7))
- def __del__(self):
- del self.model
- del self.decoder
- def cal_fps(self ,start , end):
- one_second = 1
- one_flash = end - start
- fps = one_second / one_flash
- return fps
- number_recognition = Number_recognition()
- `;
- return _code;
- }
- Blockly.Blocks['ai_model_digital_init_loding'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_init_hand_written_model);
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_models_init_source)
- // .appendField(new Blockly.FieldVariable("img_mnist"), "varitem");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('DEGREE');
- var TOOLTIPS = {
- 'Single Digit Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_hand_written_model)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_model_digital_init_loding = function (block) {
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- // var camera_variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('camera_varitem'), Blockly.Variables.NAME_TYPE);
- Blockly.Python.definitions_.import_KPU = ``;
- Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
- Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
- Blockly.Python.definitions_['v831_import_from_Number_recognition'] = `
- class Number_recognition:
- mdsc_path = "/root/preset/model/Number.mud"
- labels = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
- anchors = [1.0, 5.0, 1.35, 5.42, 0.49, 2.55, 0.86, 3.75, 0.65, 4.38]
- def __init__(self):
- self.model = nn.load(self.mdsc_path)
- self.decoder = decoder.Yolo2(len(self.labels) , self.anchors , net_in_size = (224, 224) ,net_out_size = (7,7))
- self.NumberRecognition = []
- def __del__(self):
- del self.model
- del self.decoder
- def cal_fps(self ,start , end):
- one_second = 1
- one_flash = end - start
- fps = one_second / one_flash
- return fps
- def digitalShowCanvas(self,canvas):
- out = number_recognition.model.forward(canvas, quantize=1, layout = "hwc")
- BOXES, PROBS = number_recognition.decoder.run(out, nms=0.5, threshold=0.3, img_size=(224,224))
- if len(BOXES):
- for BOXESI, BOXOBJ in enumerate(BOXES):
- 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)
- canvas.draw_rectangle(BOXOBJ[0],BOXOBJ[1], BOXOBJ[0]+BOXOBJ[2],BOXOBJ[1]+ BOXOBJ[3], color=(255,0,0), thickness=1)
- BOXES[BOXESI].append(PROBS[BOXESI])
- #self.NumberRecognition = BOXES
- else:
- BOXES = []
- return BOXES
- number_recognition = Number_recognition()
- `;
- var _code = `canvas = canvas.crop(48,8,224,224)
- BOXES = number_recognition.digitalShowCanvas(canvas)
- `
- return _code;
- }
- // ai_model_digital_new
- Blockly.Blocks['ai_model_digital_new'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_digital_new_text)
- this.appendStatementInput("input")
- .setCheck(null)
- .appendField(Blockly.Msg.basic_motion_statement_exec);
- this.appendStatementInput("input1")
- .setCheck(null)
- .appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE);
- this.setColour("#ee783a");
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null);
- this.setTooltip(Blockly.Msg.ai_model_digital_new_text);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_model_digital_new = function (block) {
- var statements_input = Blockly.Python.statementToCode(block, 'input');
- var statements_input1 = Blockly.Python.statementToCode(block, 'input1');
- let allBlocks = block.workspace.getAllBlocks();
- let global = ""
- try {
- global = allBlocks[0].workspace.variableList.toString()
- }
- catch (e) {
- console.log(e)
- }
- Blockly.Python.addFunction("digitalStatements", `def digitalStatements(BOXESI):
- ${global != "" ? `global ${global}` : "pass"}
- ${statements_input}
- `)
- var code = `if (len(BOXES)):
- for BOXESI in BOXES:
- digitalStatements(BOXESI)
- else:
- ${statements_input1}
- `
- return code;
- }
- Blockly.Blocks['ai_model_digital_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/digit_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_models_from)
- // .appendField(new Blockly.FieldVariable("i"), "varitem")
- .appendField(Blockly.Msg.ai_models_hand_written_model_result);
- this.appendDummyInput()
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_models_hand_written_model_number, "c"],
- [Blockly.Msg.ai_models_hand_written_model_confidence, "confidence"],
- [Blockly.Msg.ai_models_object_model_x, "X"],
- [Blockly.Msg.ai_models_object_model_y, "Y"],
- [Blockly.Msg.ai_models_object_model_w, "W"],
- [Blockly.Msg.ai_models_object_model_h, "H"],
- [Blockly.Msg.ai_models_face_model_ws, "2"],
- [Blockly.Msg.ai_models_face_model_hs, "3"],
- [Blockly.Msg.ai_models_object_model_x_center, "CX"],
- [Blockly.Msg.ai_models_object_model_y_center, "CY"]
- ]), "value");
- this.setOutput(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_models_hand_written_model_result);
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_model_digital_result = function (block) {
- var value = "BOXESI"
- var type = block.getFieldValue('value');
- // var _code = `"{}:{:.2f}%".format(number_recognition.labels[probs[${value}][0]], probs[${value}][1][probs[${value}][0]]*100)`;
- if (type == "confidence") {
- _code = `${value}[4][1][${value}[4][0]]*100`;
- }
- else if (type == "X") {
- _code = `${value}[0]`;
- }
- else if (type == "Y") {
- _code = `${value}[1]`;
- }
- else if (type == "W") {
- _code = `int(${value}[0] + ${value}[2])`;
- }
- else if (type == "H") {
- _code = `int(${value}[1] + ${value}[3])`;
- }
- else if (type == "c") {
- _code = `number_recognition.labels[${value}[4][0]]`;
- } else if (type == "CX") {
- _code = `int((${value}[0] +${value}[0] + ${value}[2])/2)`;
- } else if (type == "CY") {
- _code = `int((${value}[1] + ${value}[1] + ${value}[3])/2)`;
- }
- else {
- _code = `${value}[${type}]`;
- }
- return [_code, Blockly.Python.ORDER_ATOMIC];
- }
- Blockly.Blocks['ai_model_digital'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_digital);
- // this.appendDummyInput()
- // .appendField(new Blockly.FieldDropdown([
- // [Blockly.Msg.ai_models_hand_written_model_number, "digitalResult"],
- // [Blockly.Msg.ai_models_hand_written_model_confidence, "digitalConfidence"],
- // ["检测框", "digitalCheckout"]
- // ]), "digital");
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip();
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_model_digital = function (block) {
- Blockly.Python.addVariable("getDigitalResult", `getDigitalResult = []`)
- Blockly.Python.addFunction("digitalShowCanvas", `def digitalShowCanvas():
- global BOXES,getDigitalResult
- getDigitalResult = []
- if len(BOXES):
- for BOXESI, BOXOBJ in enumerate(BOXES):
- 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)
- canvas.draw_rectangle(BOXOBJ[0],BOXOBJ[1], BOXOBJ[0]+BOXOBJ[2],BOXOBJ[1]+ BOXOBJ[3], color=(255,0,0), thickness=1)
- getDigitalResult.append({"digitalResult":number_recognition.labels[PROBS[BOXESI][0]],"digitalConfidence":round(PROBS[BOXESI][1][PROBS[BOXESI][0]]*100, 2)})
- `)
- var _code = "digitalShowCanvas()\n";
- return _code;
- }
- Blockly.Blocks['ai_model_digital_attribute'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_digital_attribute);
- this.setOutput(false, null);
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_digital_attribute);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_digital_attribute'] = function (block) {
- Blockly.Python.addFunction("", `def ai_model_digital_attribute():`)
- var code = 'len(BOXES)';
- return code;
- };
- Blockly.Blocks['ai_model_object_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_init_title)
- .appendField(Blockly.Msg.ai_models_init_object_model);
- // this.appendDummyInput().appendField(Blockly.Msg.ai_model_allinit_language).appendField(new Blockly.FieldDropdown([
- // [Blockly.Msg.ai_speech_recognition_setup_set_english, "English"],
- // [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "Simplified Chinese"],
- // [Blockly.Msg.ai_speech_recognition_setup_set_traditional_chinese, "Traditional Chinese"]
- // ]), "interface")
- // this.appendValueInput("class_input")
- // .setCheck(null)
- // .appendField(Blockly.Msg.ai_models_customized_init_setup_name);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('DEGREE');
- var TOOLTIPS = {
- 'Common Object Recognition': Blockly.Msg.ai_model_allinit_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model_title)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_model_object_init = function (block) {
- var language = localStorage.getItem("handPyLanguage");
- let a = ''
- if (language == "en") {
- a = '["aeroplane","bicycle","bird","boat","bottle","bus","car","cat","chair","cow","diningtable","dog","horse","motorbike","person","pottedplant","sheep","sofa","train","tvmonitor"]'
- } else if (language == "zh-hans") {
- a = '["飞机", "自行车", "鸟", "船", "瓶子", "公共汽车", "汽车", "猫", "椅子", "牛", "餐桌", "狗", "马", "摩托车", "人", "盆栽", "羊", "沙发", "火车", "电视监视器"]'
- } else {
- a = '["飛機", "自行車", "鳥", "船", "瓶子", "公共汽車", "汽車", "貓", "椅子", "牛", "餐桌", "狗", "馬", "摩托車", "人", "盆栽", "羊", "沙發", "火車", "電視監視器"]'
- }
- console.log(language)
- Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
- Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
- Blockly.Python.definitions_.import_object = `
- model = {
- "param": "/root/preset/model/yolo2_20class_awnn.param",
- "bin": "/root/preset/model/yolo2_20class_awnn.bin"
- }
- options = {
- "model_type": "awnn",
- "inputs": {
- "input0": (224, 224, 3)
- },
- "outputs": {
- "output0": (7, 7, (1+4+20)*5)
- },
- "mean": [127.5, 127.5, 127.5],
- "norm": [0.0078125, 0.0078125, 0.0078125],
- }
- labels = ${a}
- anchors = [5.4, 5.38, 1.65, 2.09, 0.8, 1.83, 2.45, 4.14, 0.46, 0.8]
- m = nn.load(model, opt=options)
- yolo2_decoder = decoder.Yolo2(len(labels), anchors, net_in_size=(options["inputs"]["input0"][0], options["inputs"]["input0"][1]), net_out_size=(7, 7))
- `;
- var _code = "";
- return _code;
- }
- Blockly.Blocks['ai_model_object_load'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_load_title)
- .appendField(Blockly.Msg.ai_models_init_object_model);
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_models_init_source)
- // .appendField(new Blockly.FieldVariable("img_objectrecognition"), "varitem");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('DEGREE');
- var TOOLTIPS = {
- 'Common Object Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_model_object_load = function (block) {
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- // var degee = block.getFieldValue('DEGREE');
- var language = localStorage.getItem("handPyLanguage");
- let a = ''
- if (language == "en") {
- a = '["aeroplane","bicycle","bird","boat","bottle","bus","car","cat","chair","cow","diningtable","dog","horse","motorbike","person","pottedplant","sheep","sofa","train","tvmonitor"]'
- } else if (language == "zh-hans") {
- a = '["飞机", "自行车", "鸟", "船", "瓶子", "公共汽车", "汽车", "猫", "椅子", "牛", "餐桌", "狗", "马", "摩托车", "人", "盆栽", "羊", "沙发", "火车", "电视监视器"]'
- } else {
- a = '["飛機", "自行車", "鳥", "船", "瓶子", "公共汽車", "汽車", "貓", "椅子", "牛", "餐桌", "狗", "馬", "摩托車", "人", "盆栽", "羊", "沙發", "火車", "電視監視器"]'
- }
- Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
- Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
- Blockly.Python.definitions_.import_object = `class ObjectRecognition:
- def __init__(self):
- model = {
- "param": "/root/preset/model/yolo2_20class_awnn.param",
- "bin": "/root/preset/model/yolo2_20class_awnn.bin"
- }
- options = {
- "model_type": "awnn",
- "inputs": {
- "input0": (224, 224, 3)
- },
- "outputs": {
- "output0": (7, 7, (1+4+20)*5)
- },
- "mean": [127.5, 127.5, 127.5],
- "norm": [0.0078125, 0.0078125, 0.0078125],
- }
- self.labels = ${a}
- anchors = [5.4, 5.38, 1.65, 2.09, 0.8, 1.83, 2.45, 4.14, 0.46, 0.8]
- self.m = nn.load(model, opt=options)
- self.yolo2_decoder = decoder.Yolo2(len(self.labels), anchors, net_in_size=(224,224), net_out_size=(7, 7))
- self.OBJECTS = {
- "OBJECT_START_X": [],
- "OBJECT_START_Y": [],
- "OBJECT_CONFIDENCE": [],
- "OBJECT_WIDTH": [],
- "OBJECT_HEIGHT": [],
- "OBJECT_CENTER_X": [],
- "OBJECT_CENTER_Y": [],
- "OBJECT_RESULT": [],
- }
- def objectRecognize(self, canvas):
- self.OBJECTS = {
- "OBJECT_START_X": [],
- "OBJECT_START_Y": [],
- "OBJECT_CONFIDENCE": [],
- "OBJECT_WIDTH": [],
- "OBJECT_HEIGHT": [],
- "OBJECT_CENTER_X": [],
- "OBJECT_CENTER_Y": [],
- "OBJECT_RESULT": [],
- }
- out = self.m.forward(canvas.tobytes(), quantize=True, layout="hwc")
- BOXES, PROBS = self.yolo2_decoder.run(out, nms=0.3, threshold=0.3, img_size=(224,224))
- if len(BOXES):
- for BOXESI, BOXOBJ in enumerate(BOXES):
- 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)
- canvas.draw_rectangle(BOXOBJ[0],BOXOBJ[1], BOXOBJ[0]+BOXOBJ[2],BOXOBJ[1]+ BOXOBJ[3], color=(255,0,0), thickness=1)
- BOXES[BOXESI].append(PROBS[BOXESI])
- else:
- BOXES = []
- return BOXES
- ObjectRecognition = ObjectRecognition()
- `;
- var _code = `canvas = canvas.crop(48,8,224,224)
- BOXES = ObjectRecognition.objectRecognize(canvas)
- `
- return _code;
- }
- // ai_model_look_new
- Blockly.Blocks['ai_model_look_new'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_object_model_if)
- this.appendStatementInput("input")
- .setCheck(null)
- .appendField(Blockly.Msg.basic_motion_statement_exec);
- this.appendStatementInput("input1")
- .setCheck(null)
- .appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE);
- this.setColour("#ee783a");
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null);
- this.setTooltip(Blockly.Msg.ai_models_object_model_if);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_model_look_new = function (block) {
- var statements_input = Blockly.Python.statementToCode(block, 'input');
- var statements_input1 = Blockly.Python.statementToCode(block, 'input1');
- let allBlocks = block.workspace.getAllBlocks();
- let global = ""
- try {
- global = allBlocks[0].workspace.variableList.toString()
- }
- catch (e) {
- console.log(e)
- }
- Blockly.Python.addFunction("modelStatements", `def modelStatements(BOXESI):
- ${global != "" ? `global ${global}` : "pass"}
- ${statements_input}
- `)
- var code = `if len(BOXES):
- for BOXESI in BOXES:
- modelStatements(BOXESI)
- else:
- ${statements_input1}
- `
- return code;
- }
- Blockly.Blocks['ai_model_get'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/object_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_from)
- .appendField(Blockly.Msg.ai_models_object_model_get)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_models_object_model_name, "Object"],
- [Blockly.Msg.ai_models_object_model_x, "X"],
- [Blockly.Msg.ai_models_object_model_y, "Y"],
- // [Blockly.Msg.ai_models_object_model_w, "W"],
- // [Blockly.Msg.ai_models_object_model_h, "H"],
- // [Blockly.Msg.ai_models_object_model_x_center, "CX"],
- // [Blockly.Msg.ai_models_object_model_y_center, "CY"],
- // [Blockly.Msg.ai_models_object_model_count, "Number"],
- // [Blockly.Msg.ai_models_object_model_index, "Serial"],
- [Blockly.Msg.ai_models_object_model_confidence, "Confidence"],
- [Blockly.Msg.ai_models_face_model_ws, "2"],
- [Blockly.Msg.ai_models_face_model_hs, "3"],
- [Blockly.Msg.ai_models_object_model_x_center, "CX"],
- [Blockly.Msg.ai_models_object_model_y_center, "CY"]
- ]), "TYPE");
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('TYPE');
- var TOOLTIPS = {
- 'Object': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_name),
- 'X': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_x),
- 'Y': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_y),
- 'W': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_w),
- 'H': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_h),
- // 'CX': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_x_center),
- // 'CY': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_y_center),
- // 'Number': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_count),
- // 'Serial': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_index),
- // 'Confidence': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_confidence)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_model_get = function (block) {
- var type = block.getFieldValue('TYPE');
- var variable_name = "BOXESI";
- var _code = "";
- if (type == "Object") {
- _code = `labels[${variable_name}[4][0]]`
- // _code = `"{}:{:.2f}%".format(labels[probs[${variable_name}][0]], probs[${variable_name}][1][probs[${variable_name}][0]]*100)`
- } else if (type == "X") {
- _code = '' + variable_name + '[0]';
- } else if (type == "Y") {
- _code = '' + variable_name + '[1]';
- } else if (type == "W") {
- _code = 'int(' + variable_name + '[0]+' + '' + variable_name + '[2])';
- } else if (type == "H") {
- _code = 'int(' + variable_name + '[1]+' + '' + variable_name + '[3])';
- } else if (type == "Confidence") {
- _code = `${variable_name}[4][1][${variable_name}[4][0]]*100`;
- } else if (type == "CX") {
- _code = `int((${variable_name}[0] +${variable_name}[0] + ${variable_name}[2])/2)`;
- } else if (type == "CY") {
- _code = `int((${variable_name}[1] + ${variable_name}[1] + ${variable_name}[3])/2)`;
- }
- else {
- _code = `${variable_name}[${type}]`;
- }
- return [_code, Blockly.Python.ORDER_ATOMIC];
- }
- Blockly.Blocks['ai_model_look'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_object_model_if);
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_look_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_model_look = function (block) {
- var _code = "len(boxes)";
- return [_code, Blockly.Python.ORDER_ATOMIC];
- }
- Blockly.Blocks['ai_model_look_attribute'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_look_attribute);
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_look_attribute);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_look_attribute'] = function (block) {
- Blockly.Python.addFunction("objectRecognize", `def objectRecognize():
- global BOXES
- if len(BOXES):
- for BOXESI, BOXOBJ in enumerate(BOXES):
- 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)
- canvas.draw_rectangle(BOXOBJ[0],BOXOBJ[1], BOXOBJ[0]+BOXOBJ[2],BOXOBJ[1]+ BOXOBJ[3], color=(255,0,0), thickness=1)
- `)
- var code = 'objectRecognize()\n';
- return code;
- };
- // 猜拳识别
- Blockly.Blocks['ai_model_Guesswork_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_init_title)
- .appendField(Blockly.Msg.ai_models_init_guesswork_model);
- // this.appendDummyInput().appendField(Blockly.Msg.ai_model_allinit_language).appendField(new Blockly.FieldDropdown([
- // [Blockly.Msg.ai_speech_recognition_setup_set_english, "English"],
- // [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "Simplified Chinese"],
- // [Blockly.Msg.ai_speech_recognition_setup_set_traditional_chinese, "Traditional Chinese"]
- // ]), "interface")
- // this.appendValueInput("class_input")
- // .setCheck(null)
- // .appendField(Blockly.Msg.ai_models_customized_init_setup_name);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('DEGREE');
- var TOOLTIPS = {
- 'Common Object Recognition': Blockly.Msg.ai_model_allinit_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model_title)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_model_Guesswork_init = function (block) {
- var language = localStorage.getItem("handPyLanguage");
- console.log(language)
- let a = ''
- if (language == "en") {
- a = '["Scissors", "Stone" ,"Paper"]'
- } else if (language == "zh-hans") {
- a = '["剪刀", "石头" ,"布"]'
- } else {
- a = '["剪刀", "石頭" ,"布"]'
- }
- Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
- Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
- Blockly.Python.definitions_.import_Guesswork_init = `class Mora:
- mud_path = "/root/preset/model/mora_int8.mud"
- labels = ${a}
- anchors = [3.23, 3.25, 1.47, 1.55, 5.09, 5.33, 4.03, 4.28, 2.12, 2.56]
- def __init__(self) -> None:
- from maix import nn
- self.model = nn.load(self.mud_path)
- from maix.nn import decoder
- self.decoder = decoder.Yolo2(len(self.labels) , self.anchors , net_in_size = (224, 224) ,net_out_size = (7,7))
- def __del__(self):
- del self.model
- del self.decoder
- def cal_fps(self ,start , end):
- one_second = 1
- one_flash = end - start
- fps = one_second / one_flash
- return fps
- def draw_rectangle_with_title(self ,img, box, disp_str , fps ):
- img.draw_rectangle(box[0], box[1], box[0] + box[2], box[1] + box[3],color=(255, 0, 0), thickness=2)
- img.draw_string(box[0], box[1] ,disp_str, scale=1,color=(222, 0, 3), thickness=2)
- #img.draw_string(0, 0 ,"FPS :"+str(fps), scale=2 ,color=(0, 0, 255), thickness=2)
- def process(self,input):
- t = time()
- out = self.model.forward(input, quantize=1, layout = "hwc")
- boxes, probs = self.decoder.run(out, nms=0.5, threshold=0.3, img_size=(224,224))
- for i, box in enumerate(boxes):
- class_id = probs[i][0]
- prob = probs[i][1][class_id]
- disp_str = "{}:{:.2f}%".format(self.labels[class_id], prob*100)
- fps = self.cal_fps(t, time())
- self.draw_rectangle_with_title(input, box, disp_str, fps)
- Mora = Mora()
- `;
- var _code = "";
- return _code;
- }
- Blockly.Blocks['ai_model_Guesswork_load'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_load_title)
- .appendField(Blockly.Msg.ai_models_init_guesswork_model);
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_models_init_source)
- // .appendField(new Blockly.FieldVariable("img_guessworkrecognition"), "varitem");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('DEGREE');
- var TOOLTIPS = {
- 'Common Object Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_model_Guesswork_load = function (block) {
- var language = localStorage.getItem("handPyLanguage");
- let a = ''
- if (language == "en") {
- a = '["Scissors", "Stone" ,"Paper"]'
- } else if (language == "zh-hans") {
- a = '["剪刀", "石头" ,"布"]'
- } else {
- a = '["剪刀", "石頭" ,"布"]'
- }
- Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
- Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
- Blockly.Python.definitions_.import_Guesswork_init = `class Mora:
- mud_path = "/root/preset/model/mora_int8.mud"
- labels = ${a}
- anchors = [3.23, 3.25, 1.47, 1.55, 5.09, 5.33, 4.03, 4.28, 2.12, 2.56]
- def __init__(self) -> None:
- self.model = nn.load(self.mud_path)
- self.decoder = decoder.Yolo2(len(self.labels) , self.anchors , net_in_size = (224, 224) ,net_out_size = (7,7))
- self.MORAS = {
- "MORA_START_X": [],
- "MORA_START_Y": [],
- "MORA_CONFIDENCE": [],
- "MORA_WIDTH": [],
- "MORA_HEIGHT": [],
- "MORA_CENTER_X": [],
- "MORA_CENTER_Y": [],
- "MORA_RESULT": [],
- }
- def __del__(self):
- del self.model
- del self.decoder
- def cal_fps(self ,start , end):
- one_second = 1
- one_flash = end - start
- fps = one_second / one_flash
- return fps
- def draw_rectangle_with_title(self ,img, box, disp_str ):
- img.draw_rectangle(box[0], box[1], box[0] + box[2], box[1] + box[3],color=(255, 0, 0), thickness=2)
- img.draw_string(box[0], box[1] ,disp_str, scale=1,color=(222, 0, 3), thickness=2)
- def process(self,input):
- out = self.model.forward(input, quantize=1, layout = "hwc")
- boxes, probs = self.decoder.run(out, nms=0.5, threshold=0.3, img_size=(224,224))
- for i, box in enumerate(boxes):
- class_id = probs[i][0]
- prob = probs[i][1][class_id]
- disp_str = "{}:{:.2f}%".format(self.labels[class_id], prob*100)
- self.draw_rectangle_with_title(input, box, disp_str)
- boxes[i].append(probs[i])
- return boxes
-
- Mora = Mora()
- `;
- var _code = `canvas = canvas.crop(48,8,224,224)
- BOXES = Mora.process(canvas)
- `
- return _code;
- }
- // ai_model_Guesswork_look_new
- Blockly.Blocks['ai_model_Guesswork_look_new'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_guesswork_look_attribute)
- this.appendStatementInput("input")
- .setCheck(null)
- .appendField(Blockly.Msg.basic_motion_statement_exec);
- this.appendStatementInput("input1")
- .setCheck(null)
- .appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE);
- this.setColour("#ee783a");
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null);
- this.setTooltip(Blockly.Msg.ai_model_guesswork_look_attribute);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_model_Guesswork_look_new = function (block) {
- var statements_input = Blockly.Python.statementToCode(block, 'input');
- var statements_input1 = Blockly.Python.statementToCode(block, 'input1');
- let allBlocks = block.workspace.getAllBlocks();
- let global = ""
- try {
- global = allBlocks[0].workspace.variableList.toString()
- }
- catch (e) {
- console.log(e)
- }
- Blockly.Python.addFunction("GuessworkStatements", `def GuessworkStatements(BOXESI):
- ${global != "" ? `global ${global}` : "pass"}
- ${statements_input}
- `)
- var code = `if len(BOXES) > 0:
- for BOXESI in BOXES:
- GuessworkStatements(BOXESI)
- else:
- ${statements_input1}
- `
- return code;
- }
- Blockly.Blocks['ai_model_Guesswork_get'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/object_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_from)
- .appendField(Blockly.Msg.ai_models_guesswork_model_get)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_models_object_model_name, "Object"],
- [Blockly.Msg.ai_models_object_model_x, "X"],
- [Blockly.Msg.ai_models_object_model_y, "Y"],
- // [Blockly.Msg.ai_models_object_model_w, "W"],
- // [Blockly.Msg.ai_models_object_model_h, "H"],
- // [Blockly.Msg.ai_models_object_model_x_center, "CX"],
- // [Blockly.Msg.ai_models_object_model_y_center, "CY"],
- // [Blockly.Msg.ai_models_object_model_count, "Number"],
- // [Blockly.Msg.ai_models_object_model_index, "Serial"],
- [Blockly.Msg.ai_models_object_model_confidence, "Confidence"],
- [Blockly.Msg.ai_models_face_model_ws, "2"],
- [Blockly.Msg.ai_models_face_model_hs, "3"],
- [Blockly.Msg.ai_models_object_model_x_center, "CX"],
- [Blockly.Msg.ai_models_object_model_y_center, "CY"]
- ]), "TYPE");
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- var thisBlock = this;
- this.setTooltip(Blockly.Msg.ai_models_guesswork_model_get);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_model_Guesswork_get = function (block) {
- var type = block.getFieldValue('TYPE');
- var variable_name = "BOXESI";
- var _code = "";
- if (type == "Object") {
- _code = `Mora.labels[${variable_name}[4][0]]`
- // _code = `"{}:{:.2f}%".format(labels[probs[${variable_name}][0]], probs[${variable_name}][1][probs[${variable_name}][0]]*100)`
- } else if (type == "X") {
- _code = '' + variable_name + '[0]';
- } else if (type == "Y") {
- _code = '' + variable_name + '[1]';
- } else if (type == "W") {
- _code = 'int(' + variable_name + '[0]+' + '' + variable_name + '[2])';
- } else if (type == "H") {
- _code = 'int(' + variable_name + '[1]+' + '' + variable_name + '[3])';
- } else if (type == "Confidence") {
- _code = `${variable_name}[4][1][${variable_name}[4][0]]*100`;
- } else if (type == "CX") {
- _code = `int((${variable_name}[0] +${variable_name}[0] + ${variable_name}[2])/2)`;
- } else if (type == "CY") {
- _code = `int((${variable_name}[1] + ${variable_name}[1] + ${variable_name}[3])/2)`;
- }
- else {
- _code = `${variable_name}[${type}]`;
- }
- return [_code, Blockly.Python.ORDER_ATOMIC];
- }
- Blockly.Blocks['ai_model_Guesswork_look'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_guesswork_model_if);
- this.setInputsInline(false);
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_models_guesswork_model_if);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_model_Guesswork_look = function (block) {
- Blockly.Python.addFunction("guessworkShowRecognize", `def guessworkShowRecognize():
- global BOXES
- if len(BOXES):
- for BOXESI, BOXOBJ in enumerate(BOXES):
- 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)
- canvas.draw_rectangle(BOXOBJ[0],BOXOBJ[1], BOXOBJ[0]+BOXOBJ[2],BOXOBJ[1]+ BOXOBJ[3], color=(255,0,0), thickness=1)
- `)
- var _code = "guessworkShowRecognize()\n";
- return _code;
- }
- Blockly.Blocks['ai_model_Guesswork_look_attribute'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_guesswork_look_attribute);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_guesswork_look_attribute);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_Guesswork_look_attribute'] = function (block) {
- var code = 'len(BOXES)';
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_model_face_recognition_load'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_load_title)
- .appendField(Blockly.Msg.ai_models_init_face_model);
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_models_init_source)
- // .appendField(new Blockly.FieldVariable("img_facedetection"), "varitem");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('DEGREE');
- var TOOLTIPS = {
- 'Human Face Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_face_model)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_model_face_recognition_load = function (block) {
- Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
- Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
- Blockly.Python.definitions_.import_face_recognition = `class YoloFaceRecognize:
- labels = ["person"]
- anchors = [1.19, 1.98, 2.79, 4.59, 4.53, 8.92, 8.06, 5.29, 10.32, 10.65]
- m = {
- "param": "/root/preset/model/yolo2_face_awnn.param",
- "bin": "/root/preset/model/yolo2_face_awnn.bin"
- }
- options = {
- "model_type": "awnn",
- "inputs": {
- "input0": (224, 224, 3)
- },
- "outputs": {
- "output0": (7, 7, (1+4+len(labels))*5)
- },
- "mean": [127.5, 127.5, 127.5],
- "norm": [0.0078125, 0.0078125, 0.0078125],
- }
- def __init__(self):
- self.model = nn.load(self.m, opt=self.options)
- self.decoder = decoder.Yolo2(len(self.labels), self.anchors, net_in_size=(224, 224), net_out_size=(7, 7))
- self.FACES = {
- "FACES_START_X": [],
- "FACES_START_Y": [],
- "FACENUM": 0,
- "FACES_CONFIDENCE": [],
- "FACES_WIDTH": [],
- "FACES_HEIGHT": [],
- "FACES_CENTER_X": [],
- "FACES_CENTER_Y": []
- }
- def __del__(self):
- del self.model
- del self.decoder
- def faceShowDetection(self,canvas):
- out = YoloFaceRecognize.model.forward(canvas.tobytes(), quantize=True, layout="hwc")
- BOXES, PROBS = YoloFaceRecognize.decoder.run(out, nms=0.3, threshold=0.5, img_size=(224, 224))
- if len(BOXES):
- for BOXESI, BOXOBJ in enumerate(BOXES):
- canvas.draw_rectangle(BOXOBJ[0],BOXOBJ[1], BOXOBJ[0]+BOXOBJ[2],BOXOBJ[1]+ BOXOBJ[3], color=(255,0,0), thickness=1)
- BOXES[BOXESI].append(PROBS[BOXESI])
- def returnFaces(self):
- return self.FACES
- YoloFaceRecognize = YoloFaceRecognize()
- `;
- var _code = `canvas = canvas.crop(48,8,224,224)
- BOXES = YoloFaceRecognize.faceShowDetection(canvas)\n`
- return _code;
- }
- Blockly.Blocks['ai_model_xy'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/face_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_from)
- .appendField(Blockly.Msg.ai_models_face_model_get)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_models_object_model_name, "Object"],
- [Blockly.Msg.ai_models_face_model_x, "X"],
- [Blockly.Msg.ai_models_face_model_y, "Y"],
- // [Blockly.Msg.ai_models_face_model_w, "W"],
- // [Blockly.Msg.ai_models_face_model_h, "H"],
- // [Blockly.Msg.ai_models_face_model_x_center, "CX"],
- // [Blockly.Msg.ai_models_face_model_y_center, "CY"],
- [Blockly.Msg.ai_models_face_model_count, "Number"],
- // [Blockly.Msg.ai_models_face_model_index, "Serial"],
- [Blockly.Msg.ai_models_face_model_confidence, "Confidence"],
- [Blockly.Msg.ai_models_face_model_ws, "2"],
- [Blockly.Msg.ai_models_face_model_hs, "3"],
- [Blockly.Msg.ai_models_object_model_x_center, "CX"],
- [Blockly.Msg.ai_models_object_model_y_center, "CY"]
- ]), "TYPE");
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('TYPE');
- var TOOLTIPS = {
- 'X': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x),
- 'Y': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y),
- 'W': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_w),
- 'H': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_h),
- // 'CX': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x_center),
- // 'CY': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y_center),
- 'Number': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_count),
- // 'Serial': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_index),
- // 'Confidence': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_confidence)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_model_xy = function (block) {
- var type = block.getFieldValue('TYPE');
- var variable_name = "BOXESI";
- var _code = "";
- if (type == "X") {
- _code = '' + variable_name + '[0]';
- } else if (type == "Y") {
- _code = '' + variable_name + '[1]';
- } else if (type == "W") {
- _code = 'int(' + variable_name + '[0]+' + '' + variable_name + '[2])';
- } else if (type == "H") {
- _code = 'int(' + variable_name + '[1]+' + '' + variable_name + '[3])';
- } else if (type == "Confidence") {
- _code = `${variable_name}[4][1][${variable_name}[4][0]]*100`;
- } else if (type == "Object") {
- _code = `"Face"`;
- } else if (type == "CX") {
- _code = `int((${variable_name}[0] +${variable_name}[0] + ${variable_name}[2])/2)`;
- } else if (type == "CY") {
- _code = `int((${variable_name}[1] + ${variable_name}[1] + ${variable_name}[3])/2)`;
- } else if (type == "Number") {
- _code = `len(boxes)`;
- }
- else {
- _code = `${variable_name}[${type}]`;
- }
- return [_code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks['ai_model_face_new'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_face_model_list)
- this.appendStatementInput("input")
- .setCheck(null)
- .appendField(Blockly.Msg.basic_motion_statement_exec);
-
- this.appendStatementInput("input1")
- .setCheck(null)
- .appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE);
- this.setColour("#ee783a");
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null);
- this.setTooltip(Blockly.Msg.ai_model_face_model_list);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_model_face_new = function (block) {
- var statements_input = Blockly.Python.statementToCode(block, 'input');
- var statements_input1 = Blockly.Python.statementToCode(block, 'input1');
- let allBlocks = block.workspace.getAllBlocks();
- let global = ""
- try {
- global = allBlocks[0].workspace.variableList.toString()
- }
- catch (e) {
- console.log(e)
- }
- Blockly.Python.addFunction("GuessworkStatements", `def GuessworkStatements(BOXESI):
- ${global != "" ? `global ${global}` : "pass"}
- ${statements_input}
- `)
- var code = `if len(BOXES) > 0:
- for BOXESI in BOXES:
- GuessworkStatements(BOXESI)
- else:
- ${statements_input1}
- `
- return code;
- }
- Blockly.Blocks['ai_model_face'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_face_model_if);
- this.setInputsInline(false);
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_models_face_model_if);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_model_face = function (block) {
- Blockly.Python.addFunction("faceShowDetection", `def faceShowDetection():
- global BOXES
- if len(BOXES):
- for BOXESI, BOXOBJ in enumerate(BOXES):
- canvas.draw_rectangle(BOXOBJ[0],BOXOBJ[1], BOXOBJ[0]+BOXOBJ[2],BOXOBJ[1]+ BOXOBJ[3], color=(255,0,0), thickness=1)
- `)
- var _code = "faceShowDetection()\n";
- return _code;
- }
- Blockly.Blocks['ai_model_face_attribute'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_face_model_list);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_face_model_list);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_face_attribute'] = function (block) {
- var code = 'boxes';
- return [code, Blockly.Python.ORDER_NONE];
- };
- // 车牌识别
- Blockly.Blocks['ai_model_card_recognition_init'] = {
- init: function () {
- // this.appendDummyInput()
- // .appendField(new Blockly.FieldImage("blockly/media/header_customized_model.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_init_title)
- .appendField(Blockly.Msg.ai_models_init_card_model);
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_customized_init_setup_definition_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_card_recognition_init'] = function (block) {
- // TODO: Assemble Python into code variable.
- Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
- Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
- Blockly.Python.addVariable('CARDDATABOEX', `CARDDATABOEX = ""`, true)
- Blockly.Python.definitions_['v831_card_recognition_init'] = `class LPR:
- loc_model_path = "/root/preset/model/loc.mud"
- reg_model_path = "/root/preset/model/reg.mud"
- chars = ["皖", "沪", "津", "渝", "冀", "晋", "蒙", "辽", "吉", "黑",
- "苏", "浙", "京", "闽", "赣", "鲁", "豫", "鄂", "湘", "粤",
- "桂", "琼", "川", "贵", "云", "藏", "陕", "甘", "青", "宁",
- "新", "警", "学", "A", "B", "C", "D", "E", "F", "G",
- "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S",
- "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3",
- "4", "5", "6", "7", "8", "9", "-"]
- variances = [0.1, 0.2]
- steps = [8, 16, 32]
- min_sizes = [12, 24, 48, 96, 192, 320]
- card_input_img = None
- def __init__(self) -> None:
- from maix import nn
- self.loc_model = nn.load(self.loc_model_path, opt=None)
- self.reg_model = nn.load(self.reg_model_path, opt=None)
- from maix.nn import decoder
- self.loc_decoder = decoder.license_plate_location(
- [224, 224], self.steps, self.min_sizes, self.variances)
- self.reg_decoder = decoder.CTC((1, 68, 18))
- def __del__(self):
- del self.loc_model
- del self.loc_decoder
- def cal_fps(self, start, end):
- one_second = 1
- one_flash = end - start
- fps = one_second / one_flash
- return fps
- def draw_fps(self, img, fps):
- img.draw_string(0, 0, "FPS :"+str(fps), scale=1,
- color=(255, 0, 255), thickness=1)
- def draw_string(self, img, x, y, string, color):
- img.draw_string(x, y, string, color=color)
- def draw_paste(self, src, dst):
- src.paste(dst, 0, 0)
- def draw_rectangle(self, img, box):
- img.draw_rectangle(box[0], box[1], box[2], box[3],
- color=(230, 230, 250), thickness=2)
- def draw_point(self, img, landmark):
- for i in range(4):
- x = landmark[2 * i]
- y = landmark[2 * i + 1]
- img.draw_rectangle(x-2, y-2, x+2, y+2,
- color=(193, 255, 193), thickness=-1)
- def process(self, input):
- global CARDDATABOEX
- self.card_input_img = input
- # retinaface decoder only support chw layout
- loc_out = self.loc_model.forward(input, quantize=1, layout="chw")
- 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]])
- if len(boxes):
- # print(boxes,landmarks)
- for boxesi, box in enumerate(boxes):
- boxes[boxesi].append(landmarks[boxesi])
- CARDDATABOEX = boxes
- def get_card_data(self, landmark):
- # landmark = i[4][:6]
- reg_in = self.card_input_img.crop_affine(landmark, 94, 24)
- reg_out = self.reg_model.forward(reg_in, quantize=1, layout="chw")
- LP_number = self.reg_decoder.run(reg_out)
- string_LP = ""
- for id in LP_number:
- string_LP += self.chars[id]
- return string_LP
- LPRCARD = LPR()
- `;
- var code = '';
- return code;
- };
- // 车牌识别
- Blockly.Blocks['ai_model_card_recognition_load'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_load_title)
- .appendField(Blockly.Msg.ai_models_init_card_model);
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_models_customized_init_setup_source)
- // .appendField(new Blockly.FieldVariable("img_card_recognition"), "varitem");
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_customized_init_setup_definition_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_card_recognition_load'] = function (block) {
- Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
- Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
- Blockly.Python.addVariable('CARDDATABOEX', `CARDDATABOEX = ""`, true)
- Blockly.Python.definitions_['v831_card_recognition_init'] = `class LPR:
- loc_model_path = "/root/preset/model/loc.mud"
- reg_model_path = "/root/preset/model/reg.mud"
- chars = ["皖", "沪", "津", "渝", "冀", "晋", "蒙", "辽", "吉", "黑",
- "苏", "浙", "京", "闽", "赣", "鲁", "豫", "鄂", "湘", "粤",
- "桂", "琼", "川", "贵", "云", "藏", "陕", "甘", "青", "宁",
- "新", "警", "学", "A", "B", "C", "D", "E", "F", "G",
- "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S",
- "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3",
- "4", "5", "6", "7", "8", "9", "-"]
- variances = [0.1, 0.2]
- steps = [8, 16, 32]
- min_sizes = [12, 24, 48, 96, 192, 320]
- card_input_img = None
- def __init__(self) -> None:
- self.loc_model = nn.load(self.loc_model_path, opt=None)
- self.reg_model = nn.load(self.reg_model_path, opt=None)
- self.loc_decoder = decoder.license_plate_location(
- [224, 224], self.steps, self.min_sizes, self.variances)
- self.reg_decoder = decoder.CTC((1, 68, 18))
- self.LPRS = {
- "LPR_START_X":[],
- "LPR_START_Y":[],
- "LPR_CENTER_X":[],
- "LPR_CENTER_Y":[],
- "LPR_WIDTH":[],
- "LPR_HEIGHT":[],
- "LPR_CONFIDENCE":[],
- "LPR_RESULT":[],
- }
- def __del__(self):
- del self.loc_model
- del self.loc_decoder
- def cal_fps(self, start, end):
- one_second = 1
- one_flash = end - start
- fps = one_second / one_flash
- return fps
- def draw_fps(self, img, fps):
- img.draw_string(0, 0, "FPS :"+str(fps), scale=1,
- color=(255, 0, 255), thickness=1)
- def draw_string(self, img, x, y, string, color):
- img.draw_string(x, y, string, color=color)
- def draw_paste(self, src, dst):
- src.paste(dst, 0, 0)
- def draw_rectangle(self, img, box):
- img.draw_rectangle(box[0], box[1], box[2], box[3],
- color=(230, 230, 250), thickness=2)
- def draw_point(self, img, landmark):
- for i in range(4):
- x = landmark[2 * i]
- y = landmark[2 * i + 1]
- img.draw_rectangle(x-2, y-2, x+2, y+2,
- color=(193, 255, 193), thickness=-1)
- def process(self, input):
- self.card_input_img = input
- # retinaface decoder only support chw layout
- loc_out = self.loc_model.forward(input, quantize=1, layout="chw")
- 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]])
- self.LPRS = {
- "LPR_START_X":[],
- "LPR_START_Y":[],
- "LPR_CENTER_X":[],
- "LPR_CENTER_Y":[],
- "LPR_WIDTH":[],
- "LPR_HEIGHT":[],
- "LPR_CONFIDENCE":[],
- "LPR_RESULT":[],
- }
- for i,box in enumerate(boxes):
- landmark = landmarks[i][:6]
- reg_in = input.crop_affine(landmark , 94 , 24)
- reg_out = self.reg_model.forward(reg_in , quantize=1, layout = "chw")
- LP_number = self.reg_decoder.run(reg_out)
- string_LP = ''
- for id in LP_number:
- string_LP += self.chars[id]
- # string_LP += str(id)
- input.draw_string(box[0]+5, box[1]+5, string_LP, color=(225,0,0))
- input.draw_rectangle(box[0], box[1], box[2], box[3],color=(250,0,0), thickness=1)
- boxes[i].append(landmarks[i])
- return boxes
- def get_card_data(self, landmark):
- # landmark = i[4][:6]
- reg_in = self.card_input_img.crop_affine(landmark, 94, 24)
- reg_out = self.reg_model.forward(reg_in, quantize=1, layout="chw")
- LP_number = self.reg_decoder.run(reg_out)
- string_LP = ""
- for id in LP_number:
- string_LP += self.chars[id]
- return string_LP
- LPRCARD = LPR()
- `;
- // TODO: Assemble Python into code variable.
- var code = `canvas = canvas.crop(48,8,224,224)
- BOXES = LPRCARD.process(canvas)
- `;
- return code;
- };
- // 车牌识别
- Blockly.Blocks['ai_model_card_xy_new'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_card_attribute)
- this.appendStatementInput("input")
- .setCheck(null)
- .appendField(Blockly.Msg.basic_motion_statement_exec);
- this.appendStatementInput("input1")
- .setCheck(null)
- .appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE);
- this.setColour("#ee783a");
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null);
- this.setTooltip(Blockly.Msg.ai_models_card_attribute);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_card_xy_new'] = function (block) {
- var statements_input = Blockly.Python.statementToCode(block, 'input');
- var statements_input1 = Blockly.Python.statementToCode(block, 'input1');
- let allBlocks = block.workspace.getAllBlocks();
- let global = ""
- try {
- global = allBlocks[0].workspace.variableList.toString()
- }
- catch (e) {
- console.log(e)
- }
- Blockly.Python.addFunction("cardStatements", `def cardStatements(BOXESI):
- ${global != "" ? `global ${global}` : "pass"}
- ${statements_input}
- `)
- var code = `if len(BOXES) > 0:
- for BOXESI in BOXES:
- cardStatements(BOXESI)
- else:
- ${statements_input1}
- `
- return code;
- };
- Blockly.Blocks['ai_model_card_get'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/object_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_from)
- .appendField(Blockly.Msg.ai_models_card_model_get)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_models_init_card_result, "Object"],
- [Blockly.Msg.ai_models_object_model_x, "X"],
- [Blockly.Msg.ai_models_object_model_y, "Y"],
- [Blockly.Msg.ai_models_object_model_w, "W"],
- [Blockly.Msg.ai_models_object_model_h, "H"],
- // [Blockly.Msg.ai_models_object_model_x_center, "CX"],
- // [Blockly.Msg.ai_models_object_model_y_center, "CY"],
- // [Blockly.Msg.ai_models_object_model_count, "Number"],
- // [Blockly.Msg.ai_models_object_model_index, "Serial"],
- [Blockly.Msg.ai_models_object_model_confidence, "Confidence"],
- [Blockly.Msg.ai_models_face_model_ws, "2"],
- [Blockly.Msg.ai_models_face_model_hs, "3"],
- [Blockly.Msg.ai_models_object_model_x_center, "CX"],
- [Blockly.Msg.ai_models_object_model_y_center, "CY"]
- ]), "TYPE");
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- var thisBlock = this;
- this.setTooltip(Blockly.Msg.ai_models_guesswork_model_get);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_model_card_get = function (block) {
- var type = block.getFieldValue('TYPE');
- var variable_name = "BOXESI";
- var _code = "";
- if (type == "Object") {
- _code = `LPRCARD.get_card_data(${variable_name}[4][:6])`
- // _code = `"{}:{:.2f}%".format(labels[probs[${variable_name}][0]], probs[${variable_name}][1][probs[${variable_name}][0]]*100)`
- } else if (type == "X") {
- _code = '' + variable_name + '[0]';
- } else if (type == "Y") {
- _code = '' + variable_name + '[1]';
- } else if (type == "W") {
- _code = 'int(' + variable_name + '[2])';
- } else if (type == "H") {
- _code = 'int(' + variable_name + '[3])';
- } else if (type == "Confidence") {
- _code = `${variable_name}[4][1][${variable_name}[4][0]]*100`;
- } else if (type == "CX") {
- _code = `int((${variable_name}[0] + ${variable_name}[2])/2)`;
- } else if (type == "CY") {
- _code = `int((${variable_name}[1] + ${variable_name}[3])/2)`;
- }
- else {
- _code = `${variable_name}[${type}]-${variable_name}[${type - 2}]`;
- }
- // }
- return [_code, Blockly.Python.ORDER_ATOMIC];
- }
- //
- // 车牌识别
- Blockly.Blocks['ai_model_card_xy'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_card_if_true);
- this.setInputsInline(false);
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_models_card_if_true);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_card_xy'] = function (block) {
- Blockly.Python.addFunction("cardShowRecognize", `def cardShowRecognize():
- global CARDDATABOEX
- if len(CARDDATABOEX):
- for CARDDATABOEXI in CARDDATABOEX:
- 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)
- canvas.draw_string(CARDDATABOEXI[0],CARDDATABOEXI[1], (str(LPRCARD.get_card_data(CARDDATABOEXI[4][:6]))), scale = 1, color = (255,255,255) , thickness = 1)
- `)
- var code = 'cardShowRecognize()\n';
- return code;
- };
- Blockly.Blocks['ai_model_card_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_card_attribute);
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_models_card_attribute);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_card_result'] = function (block) {
- var code = 'CARDDATABOEX';
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks['ai_model_face_recognition_init_new'] = {
- init: function () {
- this.appendDummyInput().appendField(Blockly.Msg.ai_models_init_title)
- .appendField('人脸识别模型');
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_models_init_title + Blockly.Msg.ai_models_init_face_model);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_model_face_recognition_init_new = function (block) {
- Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
- Blockly.Python.definitions_['v831_import_FaceRecognize'] = `from maix.nn.app.face import FaceRecognize`
- Blockly.Python.definitions_.import_face_recognition_init_new = `
- class Face_recognize:
- score_threshold = 70 #识别分数阈值
- input_size = (224, 224, 3) #输入图片尺寸
- input_size_fe = (128, 128, 3) #输入人脸数据
- feature_len = 256 #人脸数据宽度
- steps = [8, 16, 32] #
- channel_num = 0 #通道数量
- users = [] #初始化用户列表
- threshold = 0.5 #人脸阈值
- nms = 0.3
- max_face_num = 3 #输出的画面中的人脸的最大个数
- 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"] #人脸标签定义
- model = {
- "param": "/root/preset/model/model_int8.param",
- "bin": "/root/preset/model/model_int8.bin"
- }
- model_fe = {
- "param": "/root/preset/model/fe_res18_117.param",
- "bin": "/root/preset/model/fe_res18_117.bin"
- }
- def __init__(self):
-
- for i in range(len(self.steps)):
- self.channel_num += self.input_size[1] / self.steps[i] * (self.input_size[0] / self.steps[i]) * 2
- self.channel_num = int(self.channel_num) #统计通道数量
- self.options = { #准备人脸输出参数
- "model_type": "awnn",
- "inputs": {
- "input0": self.input_size
- },
- "outputs": {
- "output0": (1, 4, self.channel_num) ,
- "431": (1, 2, self.channel_num) ,
- "output2": (1, 10, self.channel_num)
- },
- "mean": [127.5, 127.5, 127.5],
- "norm": [0.0078125, 0.0078125, 0.0078125],
- }
- self.options_fe = { #准备特征提取参数
- "model_type": "awnn",
- "inputs": {
- "inputs_blob": self.input_size_fe
- },
- "outputs": {
- "FC_blob": (1, 1, self.feature_len)
- },
- "mean": [127.5, 127.5, 127.5],
- "norm": [0.0078125, 0.0078125, 0.0078125],
- }
- print("-- load model:", self.model)
- self.m = nn.load(self.model, opt=self.options)
- print("-- load ok")
- print("-- load model:", self.model_fe)
- self.m_fe = nn.load(self.model_fe, opt=self.options_fe)
- print("-- load ok")
- self.face_recognizer = FaceRecognize(self.m, self.m_fe, self.feature_len, self.input_size, self.threshold, self.nms, self.max_face_num)
- def map_face(self,box,points): #将224*224空间的位置转换到240*240或320*240空间内
- from maix import display # print(box,points)
- if display.width() == display.height():
- def tran(x):
- return int(x/224*display.width())
- box = list(map(tran, box))
- def tran_p(p):
- return list(map(tran, p))
- points = list(map(tran_p, points))
- else:
- # 168x224(320x240) > 224x224(240x240) > 320x240
- s = (224*display.height()/display.width()) # 168x224
- w, h, c = display.width()/224, display.height()/224, 224/s
- t, d = c*h, (224 - s) // 2 # d = 224 - s // 2 == 28
- 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)
- def tran_p(p):
- return [int(p[0]*w), int((p[1]-d)*t)] # 224 - 168 / 2 = 28 so 168 / (old_h - 28) = 240 / new_h
- points = list(map(tran_p, points))
- # print(box,points)
- return box,points
- def recognize(self, feature): #进行人脸匹配
- def _compare(user): #定义映射函数
- return self.face_recognizer.compare(user, feature) #推测匹配分数 score相关分数
- face_score_l = list(map(_compare,self.users)) #映射特征数据在记录中的比对分数
- return max(enumerate(face_score_l), key=lambda x: x[-1]) #提取出人脸分数最大值和最大值所在的位置
- def __del__(self):
- del self.face_recognizer
- del self.m_fe
- del self.m
- face_recognizer = Face_recognize()
- `;
- // var degee = block.getFieldValue('DEGREE');
- var _code = "";
- // Blockly.Python.addVariable('task_facerecognition', 'task_facerecognition = None', true);
- return [_code, Blockly.Python.ORDER_ATOMIC];
- }
- Blockly.Blocks['ai_model_face_recognition_load_new'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_load_title)
- .appendField(Blockly.Msg.ai_models_init_face_model);
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_init_source)
- .appendField(new Blockly.FieldVariable("img_facerecognition"), "varitem");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('DEGREE');
- var TOOLTIPS = {
- 'Human Face Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_face_model)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_model_face_recognition_load_new = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- // var camera_variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('camera_varitem'), Blockly.Variables.NAME_TYPE);
- // Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
- // var degee = block.getFieldValue('DEGREE');
- var _code = `facesRecognitionLoadNew = face_recognizer.face_recognizer.get_faces(AI_img.tobytes(),False) #提取人脸特征信息
- `;
- // Blockly.Python.addVariable('code_facerecognition', '', true);
- // _code += "code_facerecognition = kpu.run_yolo2(task_facerecognition, " + variable_name + ")\n";
- // _code += variable_name + ".ai_to_pix()\n";
- return _code;
- }
- Blockly.Blocks['ai_model_xy_new'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/face_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_from)
- .appendField(new Blockly.FieldVariable("i"), "varitem")
- .appendField(Blockly.Msg.ai_models_face_model_get)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_models_face_model_x, "X"],
- [Blockly.Msg.ai_models_face_model_y, "Y"],
- [Blockly.Msg.ai_models_face_model_w, "W"],
- [Blockly.Msg.ai_models_face_model_h, "H"],
- [Blockly.Msg.ai_models_face_model_x_center, "CX"],
- [Blockly.Msg.ai_models_face_model_y_center, "CY"],
- [Blockly.Msg.ai_models_face_model_count, "Number"],
- [Blockly.Msg.ai_models_face_model_index, "Serial"],
- [Blockly.Msg.ai_models_face_model_confidence, "Confidence"]
- ]), "TYPE");
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('TYPE');
- var TOOLTIPS = {
- 'X': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x),
- 'Y': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y),
- 'W': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_w),
- 'H': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_h),
- 'CX': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x_center),
- 'CY': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y_center),
- 'Number': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_count),
- 'Serial': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_index),
- 'Confidence': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_confidence)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_model_xy_new = function (block) {
- var type = block.getFieldValue('TYPE');
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var _code = "";
- if (type == "X") {
- _code = variable_name + "[0]";
- } else if (type == "Y") {
- _code = variable_name + "[1]";
- } else if (type == "W") {
- _code = variable_name + "[0] + " + variable_name + "[2]";
- } else if (type == "H") {
- _code = variable_name + "[1] + " + variable_name + "[3]";
- }
- // else if (type == "Number") {
- // _code = variable_name + ".objnum()";
- // } else if (type == "Serial") {
- // _code = variable_name + ".index()";
- // } else if (type == "Confidence") {
- // _code = variable_name + ".value()";
- // } else if (type == "CX") {
- // _code = variable_name + ".x()+(" + variable_name + ".w()/2)";
- // } else if (type == "CY") {
- // _code = variable_name + ".y()+(" + variable_name + ".h()/2)";
- // }
- return [_code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks['ai_model_face_attribute_new'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_face_attribute);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_face_attribute_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_face_attribute_new'] = function (block) {
- var code = 'facesRecognitionLoadNew';
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['face_recognition_load'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_face_name);
- this.appendDummyInput()
- .appendField(Blockly.Msg.v831_face_recognition_load);
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_models_init_source)
- // .appendField(new Blockly.FieldVariable("img_recognized_face"), "varitem");
- this.appendValueInput("class_input")
- .setCheck(null)
- .appendField(Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD + ":")
- // .appendField(new Blockly.FieldVariable("people_name_list"), "people_name");
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.v831_face_recognition_load_title);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['face_recognition_load'] = function (block) {
- // var face_list = Blockly.Python.variableDB_.getName(block.getFieldValue('people_name'), Blockly.Variables.NAME_TYPE);
- var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
- Blockly.Python.definitions_['v831_import_from_maix_nn_face'] = `from maix.nn.app import face`
- Blockly.Python.definitions_['v831_import_from_maix_nn_FaceRecognize'] = `from maix.nn.app.face import FaceRecognize`
- Blockly.Python.addVariable('NUMBERPERSON', 'NUMBERPERSON = 0', true);
- Blockly.Python.definitions_.import_Face_Recognizer = `class Face_Recognizer:
- max_face_num = 4
- detect_threshold = 0.5
- detect_nms = 0.3
- FEATURES = []
-
- def __init__(self, threshold = 0.5, nms = 0.3, max_face_num = 1):
- model = "/root/preset/model/retinaface.mud"
- model_fe = "/root/preset/model/fe_resnet.mud"
- self.input_size = (224, 224, 3)
- input_size_fe = (128, 128, 3)
- self.feature_len = 256
- self.features = []
- m = nn.load(model)
- m_fe = nn.load(model_fe)
- self.isLoadRecoredFace = False
- self.CLASSNAMEFACELIST = ${value_class_input}
- self.recognizer = FaceRecognize(m, m_fe, self.feature_len, self.input_size, threshold, nms, max_face_num)
- self.FACERECOGNIZES = {
- }
- self.FACESRECOGNITONRESULT = []
- def get_faces(self, img, std_img = False):
- faces = self.recognizer.get_faces(img, std_img)
- return faces
- def __len__(self):
- return len(self.features)
- def add_user(self, name, feature):
- self.features.append([name, feature])
- return True
- def remove_user(self, name_del):
- rm = None
- for name, feature in self.features:
- if name_del == name:
- rm = [name, feature]
- if rm:
- self.features.remove(rm)
- return True
- return False
- def recognize(self, feature):
- max_score = 0
- uid = -1
- for i, user in enumerate(self.features):
- score = self.recognizer.compare(user[1], feature)
- if score > max_score:
- max_score = score
- uid = i
- if uid >= 0:
- return self.features[uid][0], max_score
- return None, 0
- def get_input_size(self):
- return self.input_size
- def get_feature_len(self):
- return self.feature_len
- def darw_info(self, img, box, points, disp_str, bg_color=(255, 0, 0, 255), font_color=(255, 255, 255, 255), font_size=32):
- font_wh = image.get_string_size(disp_str)
- for p in points:
- img.draw_rectangle(p[0] - 1, p[1] -1, p[0] + 1, p[1] + 1, color=bg_color)
- img.draw_rectangle(box[0], box[1], box[0] + box[2], box[1] + box[3], color=bg_color, thickness=2)
- if disp_str:
- img.draw_rectangle(box[0], box[1] - font_wh[1], box[0] + font_wh[0], box[1], color=bg_color, thickness = -1)
- img.draw_string(box[0], box[1] - font_wh[1], disp_str, color=font_color)
- def map_face(self,box,points,IMAGEFACESHOW):
- # print(box,points)
- for p in points:
- IMAGEFACESHOW.draw_rectangle(p[0] - 1, p[1] -1, p[0] + 1, p[1] + 1, color=(255,200,255))
- #return box,points
- def darw_title(self, img, dis_size ,key_l = None, key_r =None):
- if key_C:
- key_l = "| "+ key_l
- img.draw_string( 1, 2 ,key_l , scale = 1, color = (255, 255, 255), thickness = 2)
- if key_D:
- key_r = key_r+" |"
- w = int(dis_size[0] - 4 - image.get_string_size(key_r)[0] * 1)
- img.draw_string( w, 2 ,key_r , scale = 1, color = (255, 255, 255), thickness = 2)
- def recognizeShowMessage(self, canvas):
- self.FACESRECOGNITONRESULT = FACERECGNIZER.get_faces(canvas)
- if len(self.FACESRECOGNITONRESULT):
- for FACESRECOGNITONRESULTI in self.FACESRECOGNITONRESULT:
- if self.isLoadRecoredFace:
- if int(FACERECGNIZER.recognize(FACESRECOGNITONRESULTI[3])[1])>85:
- 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)
- 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)
- else:
- 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)
- 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)
- else:
- FACERECGNIZER.map_face(FACESRECOGNITONRESULTI[1],FACESRECOGNITONRESULTI[2],canvas)
- 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)
-
- FACERECGNIZER = Face_Recognizer(0.5, 0.3, max_face_num = 4)
- `
- var code = `canvas = canvas.crop(48, 8,224, 224)
- FACERECGNIZER.recognizeShowMessage(canvas)
- `;
- return code;
- };
- Blockly.Blocks['face_recognition_if_face_new'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_face_attribute_new)
- this.appendStatementInput("input")
- .setCheck(null)
- .appendField(Blockly.Msg.basic_motion_statement_exec);
- this.appendStatementInput("input1")
- .setCheck(null)
- .appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE);
- this.setColour("#ee783a");
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null);
- this.setTooltip(Blockly.Msg.ai_model_face_attribute_new);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['face_recognition_if_face_new'] = function (block) {
- var statements_input = Blockly.Python.statementToCode(block, 'input');
- var statements_input1 = Blockly.Python.statementToCode(block, 'input1');
- let allBlocks = block.workspace.getAllBlocks();
- let global = ""
- try {
- global = allBlocks[0].workspace.variableList.toString()
- }
- catch (e) {
- console.log(e)
- }
- Blockly.Python.addFunction("recognitionStatements", `def recognitionStatements(BOXESI):
- ${global != "" ? `global ${global}` : "pass"}
- ${statements_input}
- `)
- var code = `if len(FACERECGNIZER.FACESRECOGNITONRESULT) > 0:
- for BOXESI in FACERECGNIZER.FACESRECOGNITONRESULT:
- recognitionStatements(BOXESI)
- else:
- ${statements_input1}
- `
- return code;
- };
- Blockly.Blocks['face_recognition_if_face'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_face_model_if_new);
- this.setInputsInline(false);
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_models_face_model_if_new);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['face_recognition_if_face'] = function (block) {
- var code = ``;
- return code;
- };
- Blockly.Blocks['face_recognition_face_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_face_attribute_new);
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_face_attribute_new);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['face_recognition_face_result'] = function (block) {
- var code = `FACESRECOGNITONRESULT`;
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks['face_recognition_detection_rectangle'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_face_model_get)
- .appendField(new Blockly.FieldDropdown([
- // [Blockly.Msg.face_information, "rect"],
- [Blockly.Msg.ai_models_face_model_x, "X"],
- [Blockly.Msg.ai_models_face_model_y, "Y"],
- [Blockly.Msg.ai_models_face_model_confidence_1, "Confidence"],
- [Blockly.Msg.ai_models_face_model_ws, "2"],
- [Blockly.Msg.ai_models_face_model_hs, "3"],
- [Blockly.Msg.ai_models_object_model_x_center, "CX"],
- [Blockly.Msg.ai_models_object_model_y_center, "CY"],
- [Blockly.Msg.v831_model_face_name, "0"],
- [Blockly.Msg.v831_models_face_model_confidence, "1"],
- ]), "TYPE");
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('TYPE');
- var TOOLTIPS = {
- 'rect': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_rect),
- 'X': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x),
- 'Y': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y),
- 'W': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_w),
- 'H': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_h),
- 'CX': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x_center),
- 'CY': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y_center),
- 'Number': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_count),
- 'Serial': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_index),
- 'Confidence': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_confidence)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl("");
- }
- };
- Blockly.Python.face_recognition_detection_rectangle = function (block) {
- var type = block.getFieldValue('TYPE');
- var _code = "";
- if (type == "rect") {
- _code = "FACESRECOGNITONRESULTI[3]";
- } else if (type == "X") {
- _code = "FACESRECOGNITONRESULTI[1][0]";
- } else if (type == "Y") {
- _code = "FACESRECOGNITONRESULTI[1][1]";
- } else if (type == "W") {
- _code = `int(FACESRECOGNITONRESULTI[1][2]+FACESRECOGNITONRESULTI[1][0])`;
- } else if (type == "H") {
- _code = `int(FACESRECOGNITONRESULTI[1][3]+FACESRECOGNITONRESULTI[1][1])`;
- } else if (type == "Number") {
- _code = "FACESRECOGNITONRESULTI.objnum()";
- } else if (type == "Serial") {
- _code = "FACESRECOGNITONRESULTI.index()";
- } else if (type == "Confidence") {
- _code = "FACESRECOGNITONRESULTI[0]";
- } else if (type == "CX") {
- _code = `int((FACESRECOGNITONRESULTI[1][2]+FACESRECOGNITONRESULTI[1][0]+FACESRECOGNITONRESULTI[1][0])/2)`;
- } else if (type == "CY") {
- _code = `int((FACESRECOGNITONRESULTI[1][3]+FACESRECOGNITONRESULTI[1][1]+FACESRECOGNITONRESULTI[1][1])/2)`;
- } else if (type == "0" || type == "1") {
- _code = `FACERECGNIZER.recognize(FACESRECOGNITONRESULTI[3])[${type}]`
- }
- else {
- _code = `FACESRECOGNITONRESULTI[1][${type}]`;
- }
- return [_code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks['face_recognition_map_face'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.face_recognition_map_face_canvas)
- .appendField(new Blockly.FieldVariable("img_recognized_face"), "varitem")
- .appendField(Blockly.Msg.face_recognition_map_face_show)
- .appendField(Blockly.Msg.face_recognition_map_face_key_point);
- // this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.v831_setting_face_data_save_title);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['face_recognition_map_face'] = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- // var variable1 = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem1'), Blockly.Variables.NAME_TYPE);
- var code = `FACERECGNIZER.map_face(FACESRECOGNITONRESULTI[1],FACESRECOGNITONRESULTI[2],${variable_name})
- `;
- return code;
- };
- Blockly.Blocks['face_recognition_add'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.CocoRobo_EVENT_ACTION_OPT1)
- .appendField(new Blockly.FieldDropdown([
- ["A", "A"],
- ["B", "B"],
- ["C", "C"],
- ["D", "D"]
- ]), "button_type")
- .appendField(Blockly.Msg.ai_model_face_gather_1);
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.v831_setting_face_data_save_title);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['face_recognition_add'] = function (block) {
- var _type = block.getFieldValue('button_type');
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
- // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
- Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
- key_B = BUTTON(8)
- key_C = BUTTON(13)
- key_D = BUTTON(7)
- `
- // var code = `key_${_type}.is_pressed()`
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- Blockly.Python.definitions_['v831_import_json'] = `import json`
- Blockly.Python.addVariable('ai_model_face_gather', `
- def _CREATE_TEXT_FILE_WITH_CONTENT(_path, _data, _sep):
- f = open(_path, "a")
- f.write(_data + _sep)
- f.close()
- `, true);
- var language = localStorage.getItem("handPyLanguage");
- let saveFace = ""
- if (language == "en") {
- saveFace = "Save Face"
- } else if (language == "zh-hant") {
- saveFace = "儲存人臉"
- } else {
- saveFace = "保存人脸"
- }
- var code = `if key_${_type}.is_pressed():
- while not (key_${_type}.is_pressed() == False):
- time.sleep(0.1)
- if NUMBERPERSON < len(FACERECGNIZER.CLASSNAMEFACELIST):
- NUMBERPERSON = NUMBERPERSON + 1
- FACERECGNIZER.add_user(FACERECGNIZER.CLASSNAMEFACELIST[len(FACERECGNIZER)], FACESRECOGNITONRESULTI[3])
- FEATURES = FACERECGNIZER.features
- try:
- os.remove("/root/user/model/recorded_face_features.py")
- except:
- pass
- try:
- _CREATE_TEXT_FILE_WITH_CONTENT("/root/user/model/recorded_face_features.py", json.dumps(FACERECGNIZER.features), "\\r\\n")
- except:
- pass
- canvas.draw_string(0,0, str("${saveFace}") + str(NUMBERPERSON), scale = 1, color = (51,204,0) , thickness = 1)
- v831_display_show_canvas(canvas,_canvas_x,_canvas_y)
- time.sleep(1000 / 1000)
- `;
- return code;
- };
- Blockly.Blocks['face_recognition_remove'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.CocoRobo_EVENT_ACTION_OPT1)
- .appendField(new Blockly.FieldDropdown([
- ["A", "A"],
- ["B", "B"],
- ["C", "C"],
- ["D", "D"]
- ]), "button_type")
- .appendField(Blockly.Msg.v831_setting_face_data_remove)
- // this.appendStatementInput("input")
- // .setCheck(null)
- // .appendField(Blockly.Msg.basic_motion_statement_exec);
- // .appendField(new Blockly.FieldVariable("save_face_data"), "varitem");
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.v831_setting_face_data_remove_title);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['face_recognition_remove'] = function (block) {
- var _type = block.getFieldValue('button_type');
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
- // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
- Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
- key_B = BUTTON(8)
- key_C = BUTTON(13)
- key_D = BUTTON(7)
- `
- let language = localStorage.getItem("handPyLanguage");
- let removeFace = ""
- let faceData = ""
- if (language == "en") {
- removeFace = "Remove Face"
- faceData = "Data"
- } else if (language == "zh-hant") {
- removeFace = "刪除人臉"
- faceData = "數據"
- } else {
- removeFace = "删除人脸"
- faceData = "数据"
- }
- var code = `if key_${_type}.is_pressed() and NUMBERPERSON > 0:
- while not (key_${_type}.is_pressed() == False):
- time.sleep(0.1)
-
- canvas.draw_rectangle(0,0, 0+320,0+ 20, color=(0,0,0), thickness=-1)
- canvas.draw_string(40,0, ("".join([str(x) for x in ["${removeFace}", NUMBERPERSON, "${faceData}"]])), scale = 1, color = (255,255,255) , thickness = 1)
- v831_display_show_canvas(canvas,_canvas_x,_canvas_y)
- time.sleep(1000 / 1000)
- NUMBERPERSON = NUMBERPERSON - 1
- FACERECGNIZER.remove_user(FACERECGNIZER.CLASSNAMEFACELIST[len(FACERECGNIZER)-1])
- FEATURES = FACERECGNIZER.features
- `;
- return code;
- };
- Blockly.Blocks['face_recognition_data_load'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_face_data_load);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_face_data_load);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['face_recognition_data_load'] = function (block) {
- var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_['v831_import_json'] = `import json`
- Blockly.Python.definitions_['load_face_data'] = `isLoadRecoredFace = False
- try:
- with open("/root/user/model/recorded_face_features.py", "r") as file:
- FACERECGNIZER.features = json.loads(file.read())
- FACERECGNIZER.isLoadRecoredFace = True
- except:
- FACERECGNIZER.isLoadRecoredFace = False
- `
- var code = ``;
- return code;
- };
- Blockly.Blocks['face_recognition_data_results'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_from)
- .appendField(new Blockly.FieldVariable("img_face_Recognizer"), "varitem")
- .appendField(Blockly.Msg.WIFIEASYMODE_COCOCLOUD_TYPE)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.v831_model_face_name, "0"],
- [Blockly.Msg.ai_models_face_model_confidence, "1"],
- ]), "TYPE");
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.v831_face_recognition_result_title);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['face_recognition_data_results'] = function (block) {
- var type = block.getFieldValue('TYPE');
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var code = `FACERECGNIZER.recognize(${variable_name})[${type}]
- `;
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- // 自学习
- Blockly.Blocks['ai_model_self_learning_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_self_learning_init);
- this.appendValueInput("class_input")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_models_customized_init_setup_name);
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_self_learning_init);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_self_learning_init'] = function (block) {
- var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
- Blockly.Python.definitions_.import_self_learning_init = `
- CLASSNUM = ${JSON.parse(value_class_input).length}
- SAMPLENUM = ${JSON.parse(value_class_input).length * 5}
- CLASSNAMELIST = ${value_class_input}
- `
- var code = ``;
- return code;
- };
- Blockly.Blocks['ai_model_self_learning_load'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_self_learning_load);
- this.appendValueInput("class_input")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_models_customized_init_setup_name);
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_self_learning_load);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_self_learning_load'] = function (block) {
- Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
- Blockly.Python.definitions_['v831_import_Classifier'] = `from maix.nn.app.classifier import Classifier`
- Blockly.Python.addVariable("SELFLEARNCOUNT", `SELFLEARNCOUNT = 0`, true)
- var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_.import_self_learning_init = `
- CLASSNUM = ${JSON.parse(value_class_input).length}
- SAMPLENUM = ${JSON.parse(value_class_input).length * 5}
- CLASSNAMELIST = ${value_class_input}
- `
- Blockly.Python.definitions_.self_learing_load = `class Self_learn:
- model = {
- "param": "/root/preset/model/resnet18_1000_awnn.param",
- "bin": "/root/preset/model/resnet18_1000_awnn.bin"
- }
- options = {
- "model_type": "awnn",
- "inputs": {
- "input0": (224, 224, 3)
- },
- "outputs": {
- "190": (1, 1, 512)
- },
- "mean": [127.5, 127.5, 127.5],
- "norm": [0.0176, 0.0176, 0.0176],
- }
- class_num = CLASSNUM #学习类别
- sample_num = SAMPLENUM #学习类别总数量
- curr_class = 0
- curr_sample = 0
- def __init__(self):
- self.m = nn.load(self.model, opt=self.options)
- self.classifier = Classifier(self.m, self.class_num, self.sample_num, 512, 224, 224)
- SELFLEARN = Self_learn()
- `
- var code = '';
- return code;
- };
- Blockly.Blocks['ai_model_self_learning_recognize_load'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_self_learning_recognize_load);
- this.appendValueInput("class_input")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_models_customized_init_setup_name);
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_self_learning_recognize_load);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_self_learning_recognize_load'] = function (block) {
- Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
- Blockly.Python.definitions_['v831_import_Classifier'] = `from maix.nn.app.classifier import Classifier`
- Blockly.Python.definitions_['v831_from_nn_import_load'] = `from maix.nn.app.classifier import load`
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.addVariable("SELFLEARNCOUNT", `SELFLEARNCOUNT = 0`, true)
- Blockly.Python.definitions_.import_self_learning_init = `
- CLASSNUM = ${JSON.parse(value_class_input).length}
- SAMPLENUM = ${JSON.parse(value_class_input).length * 5}
- CLASSNAMELIST = ${value_class_input}
- `
- Blockly.Python.definitions_.self_learing_load = `class Self_learn:
- model = {
- "param": "/root/preset/model/resnet18_1000_awnn.param",
- "bin": "/root/preset/model/resnet18_1000_awnn.bin"
- }
- options = {
- "model_type": "awnn",
- "inputs": {
- "input0": (224, 224, 3)
- },
- "outputs": {
- "190": (1, 1, 512)
- },
- "mean": [127.5, 127.5, 127.5],
- "norm": [0.0176, 0.0176, 0.0176],
- }
- class_num = CLASSNUM #学习类别
- sample_num = SAMPLENUM #学习类别总数量
- curr_class = 0
- curr_sample = 0
- def __init__(self):
- if os.path.isfile("/root/module.bin"):
- self.m = nn.load(self.model, opt=self.options)
- self.classifier = load(self.m,"/root/module.bin")
- else:
- self.m = nn.load(self.model, opt=self.options)
- self.classifier = Classifier(self.m, self.class_num, self.sample_num, 512, 224, 224)
- print("not have model!")
-
- SELFLEARN = Self_learn()
- `
- var code = '';
- return code;
- };
- Blockly.Blocks['ai_model_self_learning_add_class'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.CocoRobo_EVENT_ACTION_OPT1)
- .appendField(new Blockly.FieldDropdown([
- ["A", "A"],
- ["B", "B"],
- ["C", "C"],
- ["D", "D"]
- ]), "button_type")
- .appendField(Blockly.Msg.ai_model_self_learning_add_class_category + Blockly.Msg.ai_model_self_learning_make_data_set);
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_self_learning_add_class_category + Blockly.Msg.ai_model_self_learning_make_data_set);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_self_learning_add_class'] = function (block) {
- var _type = block.getFieldValue('button_type');
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
- // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
- Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
- key_B = BUTTON(8)
- key_C = BUTTON(13)
- key_D = BUTTON(7)
- `
- var code = `canvas = canvas.crop(48, 8, 224, 224)
- if key_${_type}.is_pressed() and SELFLEARNCOUNT < SELFLEARN.class_num:
- while not (key_${_type}.is_pressed() == False):
- time.sleep(0.1)
- SELFLEARN.classifier.add_class_img(canvas)
- for i in range(5):
- SELFLEARN.classifier.add_sample_img(canvas)
- SELFLEARNCOUNT = SELFLEARNCOUNT + 1
- `;
- return code;
- };
- Blockly.Blocks['ai_model_self_learning_make_data_set'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_self_learning_make_data_set);
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_self_learning_make_data_set);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_self_learning_make_data_set'] = function (block) {
- var code = `for i in range(5):
- SELFLEARN.classifier.add_sample_img(canvas)
- `;
- return code;
- };
- Blockly.Blocks['ai_model_self_learning_picture'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.CocoRobo_EVENT_ACTION_OPT1)
- .appendField(new Blockly.FieldDropdown([
- ["A", "A"],
- ["B", "B"],
- ["C", "C"],
- ["D", "D"]
- ]), "button_type")
- .appendField(Blockly.Msg.ai_model_self_learning_picture + Blockly.Msg.ai_model_self_learning_save_modal);
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_self_learning_picture + Blockly.Msg.ai_model_self_learning_save_modal);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_self_learning_picture'] = function (block) {
- var _type = block.getFieldValue('button_type');
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
- // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
- Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
- key_B = BUTTON(8)
- key_C = BUTTON(13)
- key_D = BUTTON(7)
- `
- var code = `if key_${_type}.is_pressed() and SELFLEARNCOUNT >= SELFLEARN.class_num:
- while not (key_${_type}.is_pressed() == False):
- time.sleep(0.1)
- SELFLEARN.classifier.train()
- SELFLEARN.classifier.save("/root/module.bin")
- `;
- return code;
- }; Blockly.Blocks['ai_model_self_learning_save_modal'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_self_learning_save_modal);
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_self_learning_save_modal);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_self_learning_save_modal'] = function (block) {
- var code = `SELFLEARN.classifier.save("/root/module.bin")
- `;
- return code;
- };
- Blockly.Blocks['ai_model_self_learning_class_verification'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_self_learning_class_verification);
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_self_learning_class_verification);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_self_learning_class_verification'] = function (block) {
- var code = `canvas = canvas.crop(48, 8, 224, 224)
- SELFLEARNidx, SELFLEARNdistance = SELFLEARN.classifier.predict(canvas)
- `;
- return code;
- };
- Blockly.Blocks['ai_model_self_learning_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_self_learning_result)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_model_self_learning_result_name, "X"],
- [Blockly.Msg.ai_models_object_model_confidence, "Y"]
- ]), "TYPE");;
- this.setOutput(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_self_learning_result);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_self_learning_result'] = function (block) {
- var type = block.getFieldValue('TYPE');
- var code = '';
- if (type == 'X') {
- code = `CLASSNAMELIST[SELFLEARNidx]`
- } else {
- code = `100-SELFLEARNdistance`
- }
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks['ai_model_customized_init_setup_definition'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/header_customized_model.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_customized_init_setup_definition);
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_customized_init_setup_definition_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_customized_init_setup_definition'] = function (block) {
- // TODO: Assemble Python into code variable.
- Blockly.Python.includes_.import_amxisd = '' +
- 'print("Clearing Cached Variables...", end="")\n' +
- 'for name in dir(): \n' +
- ' if not name.startswith(\'_\'): \n' +
- ' del globals()[name]\n' +
- 'print(" Done")\n' +
- 'import KPU as kpu\n' +
- 'kpu.memtest()\n' +
- 'from Maix import utils\n' +
- 'import gc\n' +
- 'gc.enable()\n' +
- 'utils.gc_heap_size()\n' +
- '\n' +
- '################# Done Init #################\n' +
- '';
- var code = '';
- return code;
- };
- // 初始化serialcomm_read_setup_title_text_1
- Blockly.Blocks['ai_model_index_custom_initialization_init_1'] = {
- init: function () {
- this.appendValueInput("class_input")
- .setCheck(null)
- .appendField(Blockly.Msg.serialcomm_read_setup_title_text_1)
- // .appendField("DEGREE");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.serialcomm_read_setup_title_text_1);
- this.setHelpUrl('');
- }
- };
- Blockly.Python.ai_model_index_custom_initialization_init_1 = function (block) {
- var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
- var _code = value_class_input;
- return _code;
- }
- // 自定义人脸识别
- Blockly.Blocks['ai_model_face_model'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_face_setup);
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_face_setup);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_model_face_model = function (block) {
- Blockly.Python.definitions_['v831_import_time'] = `import time`
- Blockly.Python.definitions_['v831_import_gc'] = `import gc`
- Blockly.Python.includes_.import_amxisd = '' +
- 'for name in dir(): \n' +
- ' if not name.startswith(\'_\'): \n' +
- ' del globals()[name]\n' +
- 'gc.enable()\n' +
- '\n' +
- 'try:\n' +
- ' from cocorobo import firmware_info\n' +
- 'except BaseException as e:\n' +
- ' print(str(e))\n' +
- ' pass\n' +
- '\n' +
- 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
- ' from Maix import utils\n' +
- ' utils.gc_heap_size(0xAF000)\n' +
- 'else:\n' +
- ' import utime\n' +
- ' clock = None\n' +
- ' ACCURACY = 85\n' +
- '\n' +
- 'task_fd = None\n' +
- 'task_ld = None\n' +
- 'task_fe = None\n' +
- '\n' +
- '';
- var code = `
- from fpioa_manager import *
- from Maix import FPIOA, GPIO
-
- _gp_side_buttons = [9, 10, 11]
-
- FPIOA().set_function(_gp_side_buttons[0],FPIOA.GPIO0)
- FPIOA().set_function(_gp_side_buttons[1],FPIOA.GPIO1)
- FPIOA().set_function(_gp_side_buttons[2],FPIOA.GPIO2)
-
- _gp_side_a = GPIO(GPIO.GPIO0,GPIO.IN,GPIO.PULL_UP)
- _gp_side_b = GPIO(GPIO.GPIO1,GPIO.IN,GPIO.PULL_UP)
- _gp_side_c = GPIO(GPIO.GPIO2,GPIO.IN,GPIO.PULL_UP)
-
- side_button_state = False
- def run_face_compare(record_ftrs, feature):
- scores = []
- for j in range(len(record_ftrs)):
- score = kpu.face_compare(record_ftrs[j], feature)
- scores.append(score)
- max_score = 0
- # if int(str(firmware_info.ai()).split("-")[0]) < 2021:
- # index = -1
- # else:
- # index = 0
- index = -1
- for k in range(len(scores)):
- if max_score < scores[k]:
- max_score = scores[k]
- index = k
- return [scores, max_score, index]
- # print(scores)
- `;
- // var code = '';
- return [code, Blockly.Python.ORDER_ATOMIC];
- }
- // 设置人脸识别名称
- Blockly.Blocks['ai_model_face_setup'] = {
- init: function () {
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_model_face_setup);
- this.appendValueInput("class_input")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_model_face_name);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_face_name.replace(":", ""));
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_face_setup'] = function (block) {
- var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
- var code = `
- img_lcd = image.Image()
- # img_face = image.Image(size=(128, 128))
- collectNum = 0
- record_ftrs = []
- result = []
- res_index = -1
- # a = img_face.pix_to_ai()
- names = ` + value_class_input + `
- `;
- return code;
- };
- Blockly.Blocks['ai_face_detection_model'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_face_detection_model);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_face_detection_model_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_face_detection_model'] = function (block) {
- var code = '\n' +
- 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
- ' task_fd = kpu.load("/sd/preset/models/face_reocgnition/FD.emodel") # 人脸检测模型\n' +
- 'else:\n' +
- ' task_fd = kpu.load("/sd/preset/models/face/v2/FaceDetection.emodel") # 0x300000)\n' +
- 'anchor = (1.889, 2.5245, 2.9465, 3.94056, 3.99987, 5.3658, 5.155437, 6.92275, 6.718375, 9.01025)\n' +
- 'a = kpu.init_yolo2(task_fd, 0.5, 0.3, 5, anchor)\n' +
- '\n' +
- '';
- return code;
- };
- Blockly.Blocks['ai_face_point_detection_model'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_face_point_detection_model);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_face_point_detection_model_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_face_point_detection_model'] = function (block) {
- Blockly.Python.definitions_.import_ai_face_point_detection_model = `
- def run_five_points_inference(canvas, canvas_face, detected_face_rect):
- a = canvas.draw_rectangle(detected_face_rect)
- # Create face image from detection
- face_cut = canvas.cut(detected_face_rect[0], detected_face_rect[1], detected_face_rect[2], detected_face_rect[3])
- # Convert created face image to a dimension of 128x128
- face_cut_128 = face_cut.resize(128, 128)
- # 将正脸图像转为kpu格式, 便于后面的关键点模型的使用
- a = face_cut_128.pix_to_ai()
- # Get landmark for 5 points of the detected face
- # 运行人脸5点关键点检测模型, 获取当前识别人脸的关键点数据
- fmap = kpu.forward(task_ld, face_cut_128)
- # print("fmap", fmap)
- # 获取关键点预测结果
- plist = fmap[:]
- # print("plist", plist)
- # Get position of left eye, then draw it on the canvas.
- le = (i.x()+int(plist[0]*i.w() - 10), i.y()+int(plist[1]*i.h()))
- a = canvas.draw_circle(le[0], le[1], 4)
- # Get position of Right eye, then draw it on the canvas.
- re = (i.x()+int(plist[2]*i.w()), i.y()+int(plist[3]*i.h()))
- a = canvas.draw_circle(re[0], re[1], 4)
- # Get position of Nose, then draw it on the canvas.
- nose = (i.x()+int(plist[4]*i.w()), i.y()+int(plist[5]*i.h()))
- a = canvas.draw_circle(nose[0], nose[1], 4)
- # Get position of Left cheek, then draw it on the canvas.
- lm = (i.x()+int(plist[6]*i.w()), i.y()+int(plist[7]*i.h()))
- a = canvas.draw_circle(lm[0], lm[1], 4)
- # Get position of Right cheek, then draw it on the canvas.
- rm = (i.x()+int(plist[8]*i.w()), i.y()+int(plist[9]*i.h()))
- a = canvas.draw_circle(rm[0], rm[1], 4)
- # Align face to standard position
- src_point = [le, re, nose, lm, rm]
- '''
- get_affine_transform() 函数, 根据获得的5点坐标与标准正脸坐标获取仿射变换矩阵
- - 计算3个二维点对之间的仿射变换矩阵H(2行x3列),自由度为6。
- - 仿射变换的原理就是根据源图像中一个三角形的顶点坐标和应用仿射变换之后的
- - 目标图像中一个三角形的顶点坐标计算出一个变换矩阵,然后将这个矩阵应用到整个源图像。
- src_point 为输入源图像中的三角形顶点坐标
- dst_point 为输出目标图像中的三角形顶点坐标
- Ref: https://zhuanlan.zhihu.com/p/142260846
- '''
- T = image.get_affine_transform(src_point, dst_point)
- '''
- warp_affine_ai() 函数, 对原始图片人脸图片进行仿射变换,变换为正脸图像
- '''
- a = image.warp_affine_ai(canvas, canvas_face, T)
- '''
- 将正脸图像转为kpu格式
- '''
- a = canvas_face.ai_to_pix()
- # Recycle face_cut_128 in order to reduce memory usage
- del(face_cut_128)
- `;
- var code = '\n' +
- 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
- ' task_ld = kpu.load("/sd/preset/models/face_reocgnition/KP_chwise.emodel") # 人脸5点关键点检测模型\n' +
- 'else:\n' +
- ' task_ld = kpu.load("/sd/preset/models/face/v2/FaceLandmarkDetection.emodel")# 0x400000)\n' +
- 'dst_point = [(44, 59), (84, 59), (64, 82), (47, 105),(81, 105)]\n' +
- '\n' +
- '';
- return code;
- };
- Blockly.Blocks['ai_face_Vitter_eigenvalue_model'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_face_Vitter_eigenvalue_model);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_face_Vitter_eigenvalue_model_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_face_Vitter_eigenvalue_model'] = function (block) {
- Blockly.Python.definitions_.import_ai_face_Vitter_eigenvalue_model = `
- def run_fmap_calculation(canvas_face):
- global fmap
- # Calculate face feature vector from 'img_face', 计算正脸图片的196维特征值
- fmap = kpu.forward(task_fe, canvas_face)
- # 获取计算结果
- feature = kpu.face_encode(fmap[:])
- return feature
- `;
- var code = '\n' +
- 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
- ' task_fe = kpu.load("/sd/preset/models/face_reocgnition/face_recognition_v4_2020_09_07.emodel") # 人脸196维特征值模型\n' +
- ' kpu.set_outputs(task_fe, 0,1,1, 512)\n' +
- 'else:\n' +
- ' task_fe = kpu.load("/sd/preset/models/face/v2/FeatureExtraction.emodel")# 0x500000)\n' +
- ' clock = time.clock()\n' +
- '\n' +
- '';
- return code;
- };
- // 加载人脸检测模型,设置识别图像源
- Blockly.Blocks['ai_model_face_start_recognition'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_face_start_recognition + Blockly.Msg.ai_models_customized_init_setup_source)
- .appendField(new Blockly.FieldVariable("img"), "varitem");
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_models_customized_init_type_set)
- // .appendField(new Blockly.FieldDropdown([
- // [Blockly.Msg.ai_models_customized_init_type_set_fast, "fast"],
- // [Blockly.Msg.ai_models_customized_init_type_set_slow, "slow"]
- // ]), "detect_type");
- // this.appendStatementInput("NAME")
- // .setCheck(null)
- // .appendField(Blockly.Msg.ai_speech_recognition_any_result_text_do);
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_face_start_recognition_TOOLTIP);
- this.setHelpUrl("");
- }
- }
- Blockly.Python['ai_model_face_start_recognition'] = function (block) {
- // var statements_name = Blockly.Python.statementToCode(block, 'NAME');
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- // var dropdown_detect_type = block.getFieldValue('detect_type');
- localStorage.setItem("ai_model_face_variable_name", variable_name);
- var code = '' +
- 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
- ' index = -1\n' +
- 'else:\n' +
- ' clock.tick()\n' +
- 'a = img_face.pix_to_ai()\n' +
- 'code = kpu.run_yolo2(task_fd, ' + variable_name + ')\n';
- return code;
- }
- Blockly.Blocks['ai_models_customized_init_type_set'] = {
- init: function () {
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_model_face_start_recognition + Blockly.Msg.ai_models_customized_init_setup_source)
- // .appendField(new Blockly.FieldVariable("img"), "varitem");
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_customized_init_type_set)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_models_customized_init_type_set_fast, "fast"],
- [Blockly.Msg.ai_models_customized_init_type_set_slow, "slow"]
- ]), "detect_type");
- // this.appendStatementInput("NAME")
- // .setCheck(null)
- // .appendField(Blockly.Msg.ai_speech_recognition_any_result_text_do);
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_models_customized_init_type_set.replace(":", ""));
- this.setHelpUrl("");
- }
- }
- Blockly.Python['ai_models_customized_init_type_set'] = function (block) {
- // var statements_name = Blockly.Python.statementToCode(block, 'NAME');
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var dropdown_detect_type = block.getFieldValue('detect_type');
- // localStorage.setItem("ai_model_face_variable_name", variable_name);
- if (dropdown_detect_type == "fast") {
- // var break_string = " break\n";
- var break_string = "break_string = True\n";
- } else if (dropdown_detect_type == "slow") {
- // var break_string = " # break\n";
- var break_string = "break_string = False\n";
- }
- var code = '' +
- break_string +
- '\n';
- return code;
- }
- Blockly.Blocks['ai_model_face_model_load_finish'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_face_model_load_finish);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_face_model_load_finish_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_face_model_load_finish'] = function (block) {
- var code = 'code is not None';
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_model_face_model_list'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_face_model_list);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_face_model_list_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_face_model_list'] = function (block) {
- var code = 'code';
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_model_face_detection_rectangle'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/face_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_from)
- .appendField(new Blockly.FieldVariable("i"), "varitem")
- .appendField(Blockly.Msg.ai_models_face_model_get)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_models_face_model_rect, "rect"],
- [Blockly.Msg.ai_models_face_model_x, "X"],
- [Blockly.Msg.ai_models_face_model_y, "Y"],
- [Blockly.Msg.ai_models_face_model_w, "W"],
- [Blockly.Msg.ai_models_face_model_h, "H"],
- [Blockly.Msg.ai_models_face_model_x_center, "CX"],
- [Blockly.Msg.ai_models_face_model_y_center, "CY"],
- [Blockly.Msg.ai_models_face_model_count, "Number"],
- [Blockly.Msg.ai_models_face_model_index, "Serial"],
- [Blockly.Msg.ai_models_face_model_confidence, "Confidence"]
- ]), "TYPE");
- this.setInputsInline(false);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('TYPE');
- var TOOLTIPS = {
- 'rect': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_rect),
- 'X': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x),
- 'Y': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y),
- 'W': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_w),
- 'H': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_h),
- 'CX': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x_center),
- 'CY': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y_center),
- 'Number': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_count),
- 'Serial': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_index),
- 'Confidence': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_confidence)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_model_face_detection_rectangle = function (block) {
- var type = block.getFieldValue('TYPE');
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var _code = "";
- if (type == "rect") {
- _code = variable_name + ".rect()";
- } else if (type == "X") {
- _code = variable_name + ".x()";
- } else if (type == "Y") {
- _code = variable_name + ".y()";
- } else if (type == "W") {
- _code = variable_name + ".w()";
- } else if (type == "H") {
- _code = variable_name + ".h()";
- } else if (type == "Number") {
- _code = variable_name + ".objnum()";
- } else if (type == "Serial") {
- _code = variable_name + ".index()";
- } else if (type == "Confidence") {
- _code = variable_name + ".value()";
- } else if (type == "CX") {
- _code = variable_name + ".x()+(" + variable_name + ".w()/2)";
- } else if (type == "CY") {
- _code = variable_name + ".y()+(" + variable_name + ".h()/2)";
- }
- return [_code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks['ai_model_face_load_point_detection_model'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_face_load_point_detection_model + Blockly.Msg.ai_models_customized_init_setup_source)
- .appendField(new Blockly.FieldVariable("img"), "varitem");
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_face_load_point_detection_model_1)
- .appendField(new Blockly.FieldVariable("img_face"), "varitem1");
- this.appendValueInput("class_input")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_model_face_load_point_detection_model_2);
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_face_load_point_detection_model_TOOLTIP);
- this.setHelpUrl("");
- }
- }
- Blockly.Python.ai_model_face_load_point_detection_model = function (block) {
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var variable_name_1 = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem1'), Blockly.Variables.NAME_TYPE);
- var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
- var _code = "run_five_points_inference(" + variable_name + ", " + variable_name_1 + ", " + value_class_input + ")\n";
- return _code;
- };
- Blockly.Blocks['ai_model_face_gather'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_face_gather);
- this.appendValueInput("class_input")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_model_face_gather_1);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_face_gather_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_face_gather'] = function (block) {
- var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC).replace('\"', '').replace('\"', '');
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- Blockly.Python.addVariable('ai_model_face_gather', `
- def _CREATE_TEXT_FILE_WITH_CONTENT(_path, _data, _sep):
- f = open(_path, 'a')
- f.write(_data + _sep)
- f.close()
- `, true);
- var code = '' +
- '# start to gather faces\n' +
- 'result = run_face_compare(record_ftrs, feature)\n' +
- 'if int(str(firmware_info.ai()).split("-")[0]) < 2021 and collectNum < len(names):\n' +
- ' if(len(names) > result[2]):\n' +
- ' if result[1] <= 80:\n' +
- ' 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' +
- ' if _gp_side_b.value() == True and side_button_state == False:\n' +
- ' record_ftrs.append(feature)\n' +
- ' collectNum = collectNum + 1\n' +
- ' side_button_state = True\n' +
- ' elif _gp_side_b.value() == False and side_button_state == True:\n' +
- ' side_button_state = False\n' +
- 'elif int(str(firmware_info.ai()).split("-")[0]) >= 2021 and collectNum < len(names):\n' +
- ' if(len(names) > result[2]):\n' +
- ' if result[1] <= ACCURACY:\n' +
- ' 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' +
- ' if _gp_side_b.value() == True and side_button_state == False:\n' +
- ' record_ftrs.append(feature)\n' +
- ' collectNum = collectNum + 1\n' +
- ' side_button_state = True\n' +
- ' elif _gp_side_b.value() == False and side_button_state == True:\n' +
- ' side_button_state = False\n' +
- 'if collectNum >= len(names):\n' +
- ' try:\n' +
- ' os.remove("/sd/user/' + value_class_input + '.py")\n' +
- ' except:\n' +
- ' pass\n' +
- ' all = {}\n' +
- ' try:\n' +
- ' for j in range(len(names)):\n' +
- ' all[names[j]] = record_ftrs[j]\n' +
- ' _CREATE_TEXT_FILE_WITH_CONTENT("/sd/user/' + value_class_input + '.py", "all =" + str(all), "\\r\\n")\n' +
- '\n' +
- ' except:\n' +
- ' pass\n' +
- // 'if break_string == True:\n' +
- // ' break\n' +
- '\n';
- return code;
- };
- Blockly.Blocks['ai_model_face_gather_num_judge'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_face_gather_num_judge);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_face_gather_num_judge_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_face_gather_num_judge'] = function (block) {
- var code = 'collectNum >= len(names)';
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_model_face_data_load'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_face_data_load);
- this.appendValueInput("class_input")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_model_face_data_load_1);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_face_data_load_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_face_data_load'] = function (block) {
- var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC).replace('\"', '').replace('\"', '');
- Blockly.Python.addVariable('ai_model_face_data_load', `
-
- try:
- import user.${value_class_input} as recorded_face_features
- except:
- pass
- `, true);
- var code = '' +
- '# load faces data\n' +
- 'all = {}\n' +
- 'record_ftrs = []\n' +
- 'collectNum = len(names)\n' +
- 'try:\n' +
- ' all = recorded_face_features.all\n' +
- ' for j in range(len(names)):\n' +
- ' record_ftrs.append(all[names[j]])\n' +
- '\n' +
- 'except:\n' +
- ' pass\n' +
- '\n';
- // 'all = recorded_face_features.all\n' +
- return code;
- };
- Blockly.Blocks['ai_model_face_recognition'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_face_recognition);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_face_recognition_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_face_recognition'] = function (block) {
- var code = '' +
- 'if collectNum >= len(names):\n' +
- ' result = run_face_compare(record_ftrs, feature)\n' +
- ' if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
- ' if(len(names) > result[2]):\n' +
- ' if result[1] > 80:\n' +
- ' 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' +
- ' else:\n' +
- ' if(len(names) > result[2]):\n' +
- ' if result[1] > ACCURACY:\n' +
- ' 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' +
- ' res_index = result[2]\n' +
- '\n' +
- 'if break_string == True:\n' +
- ' break\n' +
- '\n' +
- '';
- return code;
- };
- Blockly.Blocks['ai_model_face_recognition_get_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_face_recognition_get_result);
- // this.appendStatementInput("NAME")
- // .setCheck(null)
- // .appendField(Blockly.Msg.ai_speech_recognition_any_result_text_do);
- this.setOutput(true);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_face_recognition_get_result_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_face_recognition_get_result'] = function (block) {
- // var statements_name = Blockly.Python.statementToCode(block, 'NAME');
- var code = '(len(names) > result[2] and collectNum >= len(names))';
- // statements_name +
- // 'if break_string == True:\n' +
- // ' break\n' +
- // 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
- // ' ' + localStorage.getItem("ai_model_face_variable_name") + ' = ' + localStorage.getItem("ai_model_face_variable_name") + '.cut(40,0,240,240)\n' +
- // ' a = lcd.display(' + localStorage.getItem("ai_model_face_variable_name") + ', oft=(0,0))\n' +
- // ' gc.collect()\n' +
- // ' # kpu.memtest()\n' +
- // 'else:\n' +
- // ' fps = clock.fps()\n' +
- // ' a = lcd.display(' + localStorage.getItem("ai_model_face_variable_name") + ')\n' +
- // ' gc.collect()\n' +
- // ' # kpu.memtest()\n' +
- // '\n' +
- // '';
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_model_getfaceresult'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_getface);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_getface_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_getfaceresult'] = function (block) {
- // TODO: Assemble Python into code variable.
- var code = 'names[res_index] if (res_index != -1 and len(names) > res_index and collectNum >= len(names)) else ""';
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_model_show_face'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_show_face);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_show_face_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_show_face'] = function (block) {
- var code = '' +
- // ' if break_string == True:\n' +
- // ' break\n' +
- 'lcd_draw_string(img, 240, 0, (str(num)), color = (255, 102, 0), scale = 2, mono_space = False)\n' +
- 'if isCollect == 0:\n' +
- ' lcd_draw_string(img, 40, 0, "按A识别上次样本", color = (255, 0, 0), scale = 1, mono_space = False)\n' +
- ' lcd_draw_string(img, 40, 16, "按C重新拍摄", color = (255, 0, 0), scale = 1, mono_space = False)\n' +
- 'elif isCollect == 1:\n' +
- ' lcd_draw_string(img, 40, 0, "开始识别", color = (255, 0, 0), scale = 1, mono_space = False)\n' +
- 'elif isCollect == 2:\n' +
- ' lcd_draw_string(img, 40, 0, "开始采集人脸模板数据", color = (255, 0, 0), scale = 1, mono_space = False)\n' +
- 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
- ' ' + localStorage.getItem("ai_model_face_variable_name") + ' = ' + localStorage.getItem("ai_model_face_variable_name") + '.cut(40,0,240,240)\n' +
- ' lcd.display(' + localStorage.getItem("ai_model_face_variable_name") + ', oft=(0,0))\n' +
- ' gc.collect()\n' +
- 'else:\n' +
- ' fps = clock.fps()\n' +
- ' a = lcd.display(' + localStorage.getItem("ai_model_face_variable_name") + ')\n' +
- ' gc.collect()\n' +
- '';
- return code;
- };
- Blockly.Blocks['ai_model_class_setup'] = {
- init: function () {
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_model_class_setup);
- this.appendValueInput("class_input")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_model_class_name);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_class_name.replace(":", ""));
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_class_setup'] = function (block) {
- var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
- var code = `
- ############### config #################
- class_names = ` + value_class_input + `
- class_num = len(class_names)
- sample_num = len(class_names) * 5
- THRESHOLD = 11
- board_cube = 0
- button_state = False
- FPIOA().set_function(10, FPIOA.GPIO1)
- key1 = GPIO(GPIO.GPIO1, GPIO.IN, GPIO.PULL_UP)
- `;
- return code;
- };
- Blockly.Blocks['ai_class_model'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_class_model);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_class_model_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_class_model'] = function (block) {
- Blockly.Python.addVariable('ai_class_model', `
- try:
- del model
- except Exception:
- pass
- try:
- del classifier
- except Exception:
- pass
- gc.collect()
- cap_num = 0
- train_status = 0
- last_cap_time = 0
- last_btn_status = 0
- res_index = -1
- is_save = 0
- `)
- var code = 'model = kpu.load("/sd/preset/models/object_classifier.emodel")\n';
- return code;
- };
- Blockly.Blocks['ai_class_model_cluster'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_class_model_cluster);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_class_model_cluster_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_class_model_cluster'] = function (block) {
- // Blockly.Python.addVariable('ai_class_model_cluster', `
- // `)
- var code = 'classifier = kpu.classifier(model, class_num, sample_num)\n';
- return code;
- };
- Blockly.Blocks['ai_model_class_start_load'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_customized_init_setup_source)
- .appendField(new Blockly.FieldVariable("img"), "varitem");
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_class_start_load);
- // this.appendStatementInput("NAME")
- // .setCheck(null)
- // .appendField(Blockly.Msg.ai_speech_recognition_any_result_text_do);
- this.setInputsInline(false);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_class_start_load_TOOLTIP);
- this.setHelpUrl("");
- }
- }
- Blockly.Python['ai_model_class_start_load'] = function (block) {
- // var statements_name = Blockly.Python.statementToCode(block, 'NAME');
- var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- localStorage.setItem("ai_model_class_start_load", variable_name);
- var code = '' +
- 'if board_cube:\n' +
- ' ' + variable_name + ' = ' + variable_name + '.rotation_corr(z_rotation=90)\n' +
- ' ' + variable_name + '.pix_to_ai()\n' +
- '\n';
- return code;
- }
- Blockly.Blocks['ai_model_class_data_load'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_class_data_load);
- this.appendValueInput("class_input")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_model_class_data_load_1);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_class_data_load_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_class_data_load'] = function (block) {
- var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC).replace('\"', '').replace('\"', '');
- var code = '' +
- 'try:\n' +
- ' saved_path = "/sd/user/' + value_class_input + '.classifier"\n' +
- ' f=open(saved_path,"r")\n' +
- ' classifier, class_num, sample_num = kpu.classifier.load(model, saved_path)\n' +
- ' train_status = 1\n' +
- 'except:\n' +
- ' ' + localStorage.getItem("ai_model_class_start_load") + '.draw_rectangle(0, 0, 240,20, fill=True, color=(0,0,0))\n' +
- ' 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' +
- '\n';
- return code;
- };
- Blockly.Blocks['ai_model_class_gather_load_finish'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_class_gather_load_finish);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_class_gather_load_finish_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_class_gather_load_finish'] = function (block) {
- var code = 'train_status == 0';
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_model_class_cluster_train'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_class_cluster_train);
- this.appendValueInput("class_input")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_model_class_cluster_train_1);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_class_cluster_train_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_class_cluster_train'] = function (block) {
- var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC).replace('\"', '').replace('\"', '');
- var code = '' +
- 'if cap_num >= class_num + sample_num and train_status == 0:\n' +
- ' ' + localStorage.getItem("ai_model_class_start_load") + '.draw_rectangle(58,98, len("training...")*10+8 , 24, fill=True, color=lcd.RED)\n' +
- ' ' + 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' +
- ' lcd.display(' + localStorage.getItem("ai_model_class_start_load") + ')\n' +
- ' try:\n' +
- ' classifier.train()\n' +
- ' saved_path = "/sd/user/' + value_class_input + '.classifier"\n' +
- ' f=open(saved_path,"r")\n' +
- ' os.remove("/sd/user/' + value_class_input + '.classifier")\n' +
- ' classifier.save("/sd/user/' + value_class_input + '.classifier")\n' +
- ' except:\n' +
- ' classifier.save("/sd/user/' + value_class_input + '.classifier")\n' +
- ' time.sleep(2)\n' +
- ' train_status = 1\n' +
- '\n';
- return code;
- };
- Blockly.Blocks['ai_model_class_recognition'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_class_recognition);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_class_recognition_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_class_recognition'] = function (block) {
- var code = '' +
- '# predict\n' +
- 'if train_status == 1:\n' +
- ' res_index = -1\n' +
- ' try:\n' +
- ' res_index, min_dist = classifier.predict(' + localStorage.getItem("ai_model_class_start_load") + ')\n' +
- ' except Exception as e:\n' +
- ' print("predict err:", e)\n' +
- ' if res_index >= 0 and min_dist < THRESHOLD :\n' +
- ' ' + 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' +
- ' ' + 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' +
- ' else:\n' +
- ' ' + 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' +
- ' ' + 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' +
- '\n';
- return code;
- };
- Blockly.Blocks['ai_model_show_class'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_show_face);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_show_face_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_show_class'] = function (block) {
- var code = '' +
- '' + localStorage.getItem("ai_model_class_start_load") + ' = ' + localStorage.getItem("ai_model_class_start_load") + '.cut(0,0,240,240)\n' +
- 'lcd.display(' + localStorage.getItem("ai_model_class_start_load") + ', oft=(0,0))\n' +
- '';
- return code;
- };
- Blockly.Blocks['ai_model_customized_init_setup'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_customized_init_setup_title);
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_customized_init_setup_path)
- .appendField(new Blockly.FieldTextInput("yolov2_int8"), "model_path");
- this.appendValueInput("class_input")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_models_customized_init_setup_name);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_customized_init_setup_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_customized_init_setup'] = function (block) {
- var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
- var text_model_path = block.getFieldValue('model_path');
- Blockly.Python.definitions_['v831_import_from_maix_nn'] = "from maix import nn";
- Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
- let path = `/root/user/model/${text_model_path}`
- if (text_model_path == "autologistics") {
- path = `/root/preset/model/${text_model_path}`
- }
- let code = `class Yolo:
- labels = ${value_class_input}
- anchors = [1.19, 1.98, 2.79, 4.59, 4.53, 8.92, 8.06, 5.29, 10.32, 10.65]
- m = {
- "param": "${path}.param",
- "bin": "${path}.bin"
- }
- options = {
- "model_type": "awnn",
- "inputs": {
- "input0": (224, 224, 3)
- },
- "outputs": {
- "output0": (7, 7, (1+4+len(labels))*5)
- },
- "mean": [127.5, 127.5, 127.5],
- "norm": [0.0078125, 0.0078125, 0.0078125],
- }
- def __init__(self):
- from maix import nn
- from maix.nn import decoder
- self.model = nn.load(self.m, opt=self.options)
- self.decoder = decoder.Yolo2(len(self.labels), self.anchors, net_in_size=(224, 224), net_out_size=(7, 7))
- def __del__(self):
- del self.model
- del self.decoder
- Yolo = Yolo()
- `;
- return code;
- };
- Blockly.Blocks['ai_model_customized_load_setup'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_customized_load_setup_title);
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_customized_init_setup_path)
- .appendField(new Blockly.FieldTextInput("yolov2_int8"), "model_path");
- // this.appendDummyInput()
- // .appendField(Blockly.Msg.ai_models_customized_init_setup_source)
- // .appendField(new Blockly.FieldVariable("img_modelrecognition"), "varitem");
- this.appendValueInput("class_input")
- .setCheck(null)
- .appendField(Blockly.Msg.ai_models_customized_init_setup_name);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_customized_load_setup_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_customized_load_setup'] = function (block) {
- var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
- var text_model_path = block.getFieldValue('model_path');
- Blockly.Python.definitions_['v831_import_from_maix_nn'] = "from maix import nn";
- Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
- let path = `/root/user/model/${text_model_path}`
- if (text_model_path == "autologistics") {
- path = `/root/preset/model/${text_model_path}`
- }
- Blockly.Python.definitions_['CLASSYOLO'] = `class Yolo:
- labels = ${value_class_input}
- anchors = [1.19, 1.98, 2.79, 4.59, 4.53, 8.92, 8.06, 5.29, 10.32, 10.65]
- m = {
- "param": "${path}.param",
- "bin": "${path}.bin"
- }
- options = {
- "model_type": "awnn",
- "inputs": {
- "input0": (224, 224, 3)
- },
- "outputs": {
- "output0": (7, 7, (1+4+len(labels))*5)
- },
- "mean": [127.5, 127.5, 127.5],
- "norm": [0.0078125, 0.0078125, 0.0078125],
- }
- def __init__(self):
- self.model = nn.load(self.m, opt=self.options)
- self.decoder = decoder.Yolo2(len(self.labels), self.anchors, net_in_size=(224, 224), net_out_size=(7, 7))
- self.FACESYOLOS = {
- "FACE_START_X": [],
- "FACE_START_Y": [],
- "FACE_CENTET_X": [],
- "FACE_CENTET_Y": [],
- "FACE_WIDTH": [],
- "FACE_HEIGHT": [],
- "FACE_RESULT": [],
- "FACE_CONFIDENCE": [],
- }
- def __del__(self):
- del self.model
- del self.decoder
- def faceRecognizeShowResult(self,canvas):
- out = self.model.forward(canvas, quantize=True, layout="hwc")
- BOXES, PROBS = self.decoder.run(out, nms=0.3, threshold=0.3, img_size=(224, 224))
- if len(BOXES):
- for BOXESI, BOXOBJ in enumerate(BOXES):
- 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)
- canvas.draw_rectangle((BOXOBJ[0]),(BOXOBJ[1]), (BOXOBJ[0])+(BOXOBJ[2]),(BOXOBJ[1])+ (BOXOBJ[3]), color=(255,0,0), thickness=1)
- BOXES[BOXESI].append(PROBS[BOXESI])
- return BOXES
-
- FaceYolo = Yolo()
- `;
- var code = `canvas = canvas.crop(48,8,224,224)
- BOXES = FaceYolo.faceRecognizeShowResult(canvas)
- `;
- return code;
- };
- Blockly.Blocks['ai_model_customized_get_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_from)
- .appendField(Blockly.Msg.ai_models_customized_get_result_any)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_models_customized_get_result_name, "classid"],
- [Blockly.Msg.ai_models_customized_get_result_x, "x"],
- [Blockly.Msg.ai_models_customized_get_result_y, "y"],
- // [Blockly.Msg.ai_models_customized_get_result_w, "w"],
- // [Blockly.Msg.ai_models_customized_get_result_h, "h"],
- // [Blockly.Msg.ai_models_customized_get_result_x_center, "cx"],
- // [Blockly.Msg.ai_models_customized_get_result_y_center, "cy"],
- // [Blockly.Msg.ai_models_customized_get_result_count, "objnum"],
- // [Blockly.Msg.ai_models_customized_get_result_index, "index"],
- [Blockly.Msg.ai_models_customized_get_result_confidence, "value"],
- [Blockly.Msg.ai_models_face_model_ws, "2"],
- [Blockly.Msg.ai_models_face_model_hs, "3"],
- [Blockly.Msg.ai_models_object_model_x_center, "CX"],
- [Blockly.Msg.ai_models_object_model_y_center, "CY"]
- ]), "get_results");
- this.setOutput(true, null);
- this.setColour("#ee783a");
- var thisBlock = this;
- this.setTooltip(function () {
- var mode = thisBlock.getFieldValue('get_results');
- var TOOLTIPS = {
- 'classid': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_name),
- 'x': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_x),
- 'y': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_y),
- 'w': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_w),
- 'h': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_h),
- 'cx': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_x_center),
- 'cy': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_y_center),
- 'objnum': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_count),
- 'index': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_index),
- 'value': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_confidence)
- };
- return TOOLTIPS[mode];
- });
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_customized_get_result'] = function (block) {
- var variable_name = "BOXESI";
- var dropdown_get_results = block.getFieldValue('get_results');
- // TODO: Assemble Python into code variable.
- var code = '';
- if (dropdown_get_results == "classid") {
- code = 'Yolo.labels[' + variable_name + '[4][0]]';
- } else if (dropdown_get_results == 'x') {
- code = variable_name + '[0]';
- } else if (dropdown_get_results == "y") {
- code = variable_name + "[1]";
- } else if (dropdown_get_results == "w") {
- code = `${variable_name}[0]+${variable_name}[2]`;
- } else if (dropdown_get_results == "h") {
- code = `${variable_name}[1]+${variable_name}[3]`;
- } else if (dropdown_get_results == "value") {
- code = `${variable_name}[4][1][${variable_name}[4][0]]`;
- } else if (dropdown_get_results == "CX") {
- code = `int((${variable_name}[0] + ${variable_name}[2])/2)`;
- } else if (dropdown_get_results == "CY") {
- code = `int((${variable_name}[1] + ${variable_name}[3])/2)`;
- }
- else {
- code = `${variable_name}[${dropdown_get_results}]`;
- }
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['ai_model_customized_if_got_new'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_customized_attribute)
- this.appendStatementInput("input")
- .setCheck(null)
- .appendField(Blockly.Msg.basic_motion_statement_exec);
- this.appendStatementInput("input1")
- .setCheck(null)
- .appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE);
- this.setColour("#ee783a");
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null);
- this.setTooltip(Blockly.Msg.ai_model_customized_attribute);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_customized_if_got_new'] = function (block) {
- var statements_input = Blockly.Python.statementToCode(block, 'input');
- var statements_input1 = Blockly.Python.statementToCode(block, 'input1');
- let allBlocks = block.workspace.getAllBlocks();
- let global = ""
- try {
- global = allBlocks[0].workspace.variableList.toString()
- }
- catch (e) {
- console.log(e)
- }
- Blockly.Python.addFunction("cardStatements", `def cardStatements(BOXESI):
- ${global != "" ? `global ${global}` : "pass"}
- ${statements_input}
- `)
- var code = `if len(BOXES) > 0:
- for BOXESI in BOXES:
- cardStatements(BOXESI)
- else:
- ${statements_input1}
- `
- return code;
- };
- Blockly.Blocks['ai_model_customized_if_got'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_models_customized_if_got);
- this.setNextStatement(true, null);
- this.setPreviousStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_models_customized_if_got);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_customized_if_got'] = function (block) {
- Blockly.Python.addFunction("faceRecognizeShowResult", `def faceRecognizeShowResult():
- global BOXES
- if len(BOXES):
- for BOXESI, BOXOBJ in enumerate(BOXES):
- 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)
- canvas.draw_rectangle((BOXOBJ[0]),(BOXOBJ[1]), (BOXOBJ[0])+(BOXOBJ[2]),(BOXOBJ[1])+ (BOXOBJ[3]), color=(255,0,0), thickness=1)
- `)
- var code = 'faceRecognizeShowResult()\n';
- return code;
- };
- Blockly.Blocks['ai_model_customized_attribute'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_model_customized_attribute);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_customized_attribute_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_model_customized_attribute'] = function (block) {
- var code = 'len(BOXES)';
- return [code, Blockly.Python.ORDER_NONE];
- };
- /*
- _ ___ ____ _
- / \ |_ _| / ___| _ _ ___| |_ ___ _ __ ___
- / _ \ | | \___ \| | | / __| __/ _ \ '_ ` _ \
- / ___ \ | | ___) | |_| \__ \ || __/ | | | | |
- /_/ \_\___| |____/ \__, |___/\__\___|_| |_| |_|
- |___/
- */
- Blockly.Blocks['ai_system_off'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_system_off);
- this.setPreviousStatement(true);
- this.setNextStatement(true);
- this.setColour("#22398e");
- this.setTooltip(Blockly.Msg.ai_system_restart_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_system_off = function (block) {
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- var _code = `os.system("poweroff")
- `
- return _code;
- }
- Blockly.Blocks['ai_system_restart'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_system_restart);
- this.setPreviousStatement(true);
- this.setNextStatement(true);
- this.setColour("#22398e");
- this.setTooltip(Blockly.Msg.ai_system_off_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_system_restart = function (block) {
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- var _code = `os.system("reboot")
- `
- return _code;
- }
- Blockly.Blocks['ai_system_refresh'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_system_refresh);
- this.setPreviousStatement(true);
- this.setNextStatement(true);
- this.setColour("#22398e");
- this.setTooltip(Blockly.Msg.ai_system_refresh_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python.ai_system_refresh = function (block) {
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- var _code = `os.system("sync")
- `
- return _code;
- }
- Blockly.Blocks['ai_system_volume'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.system_voice)
- .appendField(new Blockly.FieldNumber(25, 0, 100), "play_vol");
- this.setPreviousStatement(true);
- this.setNextStatement(true);
- this.setColour("#22398e");
- }
- }
- Blockly.Python.ai_system_volume = function (block) {
- var number_play_vol = block.getFieldValue('play_vol');
- Blockly.Python.definitions_['v831_import_os'] = `import os`
- Blockly.Python.definitions_['systemVoice_numberMap'] = `def voice_numberMap(value):
- valueScaled = float(value - 0) / float(100)
- return int(valueScaled * 31)
- `
- var _code = `VOICENUMP = str(voice_numberMap(${number_play_vol}))
- time.sleep(0.01)
- SYSTEMVOICE = "amixer cset numid=8,iface=MIXER,name=\\"LINEOUT volume\\" "+ VOICENUMP+""
- os.system(SYSTEMVOICE)
- `
- return _code;
- }
- Blockly.Blocks['ai_system_thread'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_system_thread_setting)
- .appendField(new Blockly.FieldNumber(1, 1, 5), "thread")
- this.appendStatementInput("input")
- .setCheck(null)
- .appendField(Blockly.Msg.basic_motion_statement_exec);
- this.setColour("#22398e");
- this.setTooltip(Blockly.Msg.ai_system_thread_setting);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_system_thread'] = function (block) {
- var threadNum = block.getFieldValue('thread');
- var statements_input = Blockly.Python.statementToCode(block, 'input');
- Blockly.Python.definitions_['v831_import_threading'] = `import threading`
- let allBlocks = block.workspace.getAllBlocks();
- let global = ""
- try {
- global = allBlocks[0].workspace.variableList.toString()
- }
- catch (e) {
- console.log(e)
- }
- Blockly.Python.definitions_['v831_import_thread_calsss_fun' + threadNum] = `def thread_calsss_fun${threadNum}():
- ${global != "" ? global : ""}
- ${statements_input}
- CocoPiThread${threadNum} = threading.Thread(target=thread_calsss_fun${threadNum})
- `
- var code = ``;
- return code;
- };
- Blockly.Blocks['ai_system_thread_create_with_container'] = {
- init: function () {
- this.setColour("#22398e");
- this.appendDummyInput()
- .appendField(Blockly.Msg.serialcomm_write_item);
- this.appendStatementInput('STACK');
- this.setTooltip('');
- this.contextMenu = false;
- }
- };
- Blockly.Blocks['ai_system_thread_data_create_with_item'] = {
- init: function () {
- this.setColour("#22398e");
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_systen_thread_val);
- this.setPreviousStatement(true);
- this.setNextStatement(true);
- this.setTooltip('');
- this.contextMenu = false;
- }
- };
- Blockly.Blocks['ai_system_thread_set_setDaemon'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_system_thread_setting).appendField(new Blockly.FieldNumber(1, 1, 5), "thread")
- .appendField(Blockly.Msg.digital_set_as).appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ai_system_thread_setDaemon, "True"],
- [Blockly.Msg.ai_system_thread_not_setDaemon, "False"]
- ]), "setDaemon");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null)
- this.setColour("#22398e");
- this.setTooltip(Blockly.Msg.ai_system_thread_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_system_thread_set_setDaemon'] = function (block) {
- var threadNum = block.getFieldValue('thread');
- var queue_value = block.getFieldValue('setDaemon');
- var code = `CocoPiThread${threadNum}.setDaemon(${queue_value})
- `;
- return code;
- };
- Blockly.Blocks['ai_system_thread_set_join'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_system_thread_setting)
- .appendField(new Blockly.FieldNumber(1, 1, 5), "thread")
- .appendField(Blockly.Msg.ai_system_thread_set_join)
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null)
- this.setColour("#22398e");
- this.setTooltip(Blockly.Msg.ai_system_thread_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_system_thread_set_join'] = function (block) {
- var threadNum = block.getFieldValue('thread');
- var code = `CocoPiThread${threadNum}.join()
- `;
- return code;
- };
- Blockly.Blocks['ai_system_thread_start'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_system_thread).appendField(new Blockly.FieldNumber(1, 1, 5), "thread");
- // this.appendStatementInput("input")
- // .setCheck(null)
- // .appendField(Blockly.Msg.basic_motion_statement_exec);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null)
- this.setColour("#22398e");
- this.setTooltip(Blockly.Msg.ai_system_thread_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['ai_system_thread_start'] = function (block) {
- var threadNum = block.getFieldValue('thread');
- // var statements_input = Blockly.Python.statementToCode(block, 'input');
- var code = `CocoPiThread${threadNum}.start()
- `;
- return code;
- };
- Blockly.Blocks["ai_system_set_queue"] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_systen_queue_aritem)
- this.appendValueInput("queueVaritem")
- .setCheck(null);
- this.appendDummyInput().appendField(Blockly.Msg.ai_systen_queue_put)
- .appendField(new Blockly.FieldDropdown([
- ["1", "1"],
- ["2", "2"],
- ["3", "3"],
- ["4", "4"],
- ["5", "5"]
- ]), "queue_value");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#22398e");
- this.setTooltip("");
- }
- }
- Blockly.Python['ai_system_set_queue'] = function (block) {
- var variable_name = Blockly.Python.valueToCode(block, 'queueVaritem', Blockly.Python.ORDER_ATOMIC);
- // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
- var queue_value = block.getFieldValue('queue_value');
- Blockly.Python.definitions_["v831_import_queue"] = `import queue`
- Blockly.Python.definitions_["v831_import_queue_init" + queue_value] = `queue${queue_value} = queue.Queue()`
- var code = `queue${queue_value}.put(${variable_name})
- `;
- return code;
- }
- Blockly.Blocks["ai_system_get_queue"] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_systen_queue_get)
- .appendField(new Blockly.FieldDropdown([
- ["1", "1"],
- ["2", "2"],
- ["3", "3"],
- ["4", "4"],
- ["5", "5"]
- ]), "queue_value")
- .appendField(Blockly.Msg.ai_systen_queue_value);
- this.setOutput(true, null);
- this.setColour("#22398e");
- this.setTooltip("");
- }
- }
- Blockly.Python['ai_system_get_queue'] = function (block) {
- var queue_value = block.getFieldValue('queue_value');
- var code = `queue${queue_value}.get()`;
- return [code, Blockly.Python.ORDER_NONE];
- }
- // 拼音识别
- Blockly.Blocks['speech_recognition_phonetic_to_pinyin_setup'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(new Blockly.FieldImage("blockly/media/speech_recognition_header_recognition_new.png", 130, 60, { alt: "*", flipRtl: "FALSE" }));
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_setup);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.speech_recognition_phonetic_to_pinyin_setup_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['speech_recognition_phonetic_to_pinyin_setup'] = function (block) {
- Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
- Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
- Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
- Blockly.Python.definitions_["v831_import_maix_speech"] = `import _maix_speech`
- Blockly.Python.definitions_.speech_recognition_phonetic_to_pinyin_setup_def = `asr = _maix_speech.Asr()
- asr.open("hw:0,0", "/root/preset/drivers/ASR/CocoPi_Asr_Model/CocoPi_Asr_Model_V2.1")
- asr.clear()
- asr_kws_result=[0,0] #获取识别结果及识别概率
- similars = [
- ["pai3", "ai4"],
- ["le4", "luo4"],
- ]
- def asr_kws(keys):
- global asr_kws_result
- tmp = max(keys)
- asr_kws_result[0] = keys.index(tmp)
- asr_kws_result[1] = round(tmp,2)
- `
- var code = "";
- return code;
- };
- Blockly.Blocks.set_pinyin_dict_create_with_items_insert = {
- init: function () {
- this.setColour("#ee783a");
- this.appendDummyInput("").appendField(new Blockly.FieldLabel(Blockly.Msg.ai_speech_recognition_setup_pinyin), "TIP");
- this.itemCount_ = 3;
- this.updateShape_();
- this.setOutput(!0);
- this.setMutator(new Blockly.Mutator(["set_pinyin_dict_create_with_item"]));
- this.setTooltip(Blockly.Msg.ai_speech_recognition_setup_pinyin_and_tone)
- },
- mutationToDom: function () {
- var a = document.createElement("mutation");
- a.setAttribute("items", this.itemCount_);
- return a
- },
- domToMutation: function (a) {
- this.itemCount_ = parseInt(a.getAttribute("items"), 10);
- this.updateShape_()
- },
- decompose: function (a) {
- var b = a.newBlock("set_pinyin_dict_create_with_container");
- b.initSvg();
- for (var c = b.getInput("STACK").connection, e = 0; e < this.itemCount_; e++) {
- var d = a.newBlock("set_pinyin_dict_create_with_item");
- d.initSvg();
- c.connect(d.previousConnection);
- c = d.nextConnection
- }
- return b
- },
- compose: function (a) {
- a = a.getInputTargetBlock("STACK");
- for (var b = [], c = 0; a;)
- b[c] = a.valueConnection_,
- a = a.nextConnection && a.nextConnection.targetBlock(),
- c++;
- this.itemCount_ = c;
- this.updateShape_();
- for (c = 0; c < this.itemCount_; c++)
- b[c] && this.getInput("ADD" + c).connection.connect(b[c])
- },
- saveConnections: function (a) {
- a = a.getInputTargetBlock("STACK");
- for (var b = 0; a;) {
- var c = this.getInput("ADD" + b);
- a.valueConnection_ = c && c.connection;
- b++;
- a = a.nextConnection && a.nextConnection.targetBlock()
- }
- },
- updateShape_: function () {
- this.getInput("EMPTY") && this.removeInput("EMPTY");
- for (var a = [], b = 0; this.getInput("ADD" + b); b++)
- a.push(this.getFieldValue("KEY" + b)),
- this.removeInput("ADD" + b);
- if (0 == this.itemCount_)
- this.getField("TIP").setText(Blockly.Msg.ai_speech_recognition_setup_pinyin);
- else
- for (this.getField("TIP").setText(Blockly.Msg.ai_speech_recognition_setup_pinyin),
- b = 0; b < this.itemCount_; b++)
- 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(":")
- .appendField(Blockly.Msg.ai_speech_recognition_setup_tone).appendField(new Blockly.FieldDropdown([
- ["1", "1"],
- ["2", "2"],
- ["3", "3"],
- ["4", "4"],
- ]), "toneADD" + b + b)
- },
- getVars: function () {
- return [this.getFieldValue("VAR")]
- },
- renameVar: function (a, b) {
- Blockly.Names.equals(a, this.getFieldValue("VAR")) && this.setTitleValue(b, "VAR")
- }
- };
- Blockly.Blocks.set_pinyin_dict_create_with_item = {
- init: function () {
- this.setColour("#ee783a");
- this.appendDummyInput().appendField(Blockly.Msg.ai_speech_recognition_setup_pinyin);
- this.setPreviousStatement(!0);
- this.setNextStatement(!0);
- this.setTooltip(Blockly.Msg.ai_speech_recognition_setup_pinyin);
- this.contextMenu = !1
- }
- };
- Blockly.Blocks.set_pinyin_dict_create_with_container = {
- init: function () {
- this.setColour("#ee783a");
- this.appendDummyInput().appendField(Blockly.Msg.robot_dog_servo_execution);
- this.appendStatementInput("STACK");
- this.setTooltip(Blockly.Msg.robot_dog_servo_execution);
- this.contextMenu = !1
- }
- };
- Blockly.Python.set_pinyin_dict_create_with_items_insert = function (block) {
- for (var a = Array(this.itemCount_), b = 0; b < this.itemCount_; b++) {
- var c = this.getFieldValue("KEY" + b);
- a[b] = c + block.getFieldValue("toneADD" + b + b);
- }
- a = "{" + a.join(", ") + "}";
- return [a, Blockly.Python.ORDER_ATOMIC]
- };
- Blockly.Blocks['speech_recognition_phonetic_to_pinyin_set_param'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_set_param);
- // this.appendValueInput("data")
- // .setCheck(null)
- // .appendField(Blockly.Msg.ai_speech_recognition_setup_pinyin);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setInputsInline(false);
- this.setColour("#ee783a");
- this.pinyinitemCount_ = 1
- this.updateShape_();
- this.setMutator(new Blockly.Mutator(["v831_to_pinyin_set_param"]));
- this.setTooltip(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_set_param_TOOLTIP);
- this.setHelpUrl("");
- },
- mutationToDom: function () {
- var a = document.createElement("mutation");
- a.setAttribute("items", this.pinyinitemCount_);
- return a
- },
- domToMutation: function (a) {
- this.pinyinitemCount_ = parseInt(a.getAttribute("items"), 10);
- this.updateShape_()
- },
- decompose: function (a) {
- var b = a.newBlock("v831_to_pinyin_set_param_container");
- b.initSvg();
- for (var c = b.getInput("STACK").connection, e = 0; e < this.pinyinitemCount_; e++) {
- var d = a.newBlock("v831_to_pinyin_set_param");
- d.initSvg();
- c.connect(d.previousConnection);
- c = d.nextConnection
- }
- return b
- },
- compose: function (a) {
- var b = a.getInputTargetBlock("STACK");
- for (a = []; b;)
- a.push(b.valueConnection_),
- b = b.nextConnection && b.nextConnection.targetBlock();
- for (b = 0; b < this.pinyinitemCount_; b++) {
- var c = this.getInput("PINYIN" + b).connection.targetConnection;
- c && -1 == a.indexOf(c) && c.disconnect()
- }
- this.pinyinitemCount_ = a.length;
- this.updateShape_();
- for (b = 0; b < this.pinyinitemCount_; b++)
- Blockly.Mutator.reconnect(a[b], this, "PINYIN" + b)
- },
- saveConnections: function (a) {
- a = a.getInputTargetBlock("STACK");
- for (var b = 0; a;) {
- var c = this.getInput("PINYIN" + b);
- a.valueConnection_ = c && c.connection.targetConnection;
- b++;
- a = a.nextConnection && a.nextConnection.targetBlock()
- }
- },
- updateShape_: function () {
- // this.itemCount_ && this.getInput("EMPTY") ? this.removeInput("EMPTY") : this.itemCount_ || this.getInput("EMPTY") || this.appendDummyInput("EMPTY").appendField(Blockly.Msg.TUPLE_CREATE_EMPTY_TITLE);
- for (var a = 0; a < this.pinyinitemCount_; a++)
- if (!this.getInput("PINYIN" + a)) {
- var b = this.appendValueInput("PINYIN" + a);
- 0 == a && b.appendField(Blockly.Msg.ai_speech_recognition_setup_pinyin_and_tone)
- }
- for (; this.getInput("PINYIN" + a);)
- this.removeInput("PINYIN" + a),
- a++
- }
- };
- Blockly.Blocks['v831_to_pinyin_set_param'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_speech_recognition_setup_pinyin_and_tone);
- this.setPreviousStatement(true);
- this.setNextStatement(true);
- this.setColour("#ee783a")
- this.setTooltip('');
- this.contextMenu = false;
- }
- };
- Blockly.Blocks['v831_to_pinyin_set_param_container'] = {
- init: function () {
- this.setColour("#ee783a");
- this.appendDummyInput()
- .appendField(Blockly.Msg.ARD_SERIAL_SETUP);
- this.appendStatementInput('STACK');
- this.setTooltip('');
- this.contextMenu = false;
- }
- };
- Blockly.Python['speech_recognition_phonetic_to_pinyin_set_param'] = function (block) {
- // var data = Blockly.Python.valueToCode(block, 'data', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
- Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
- Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
- Blockly.Python.definitions_["v831_import_maix_speech"] = `import _maix_speech`
- var a = Array(this.pinyinitemCount_)
- for (let b = 0; b < this.pinyinitemCount_; b++) {
- var c = Blockly.Python.valueToCode(this, "PINYIN" + b, Blockly.Python.ORDER_NONE)
- a[b] = c.slice(1, -1).replaceAll(",", "")
- }
- a = a.map(r => [r, 0.1])
- Blockly.Python.definitions_.speech_recognition_phonetic_to_pinyin_setup_def = `asr = _maix_speech.Asr()
- asr.open("hw:0,0", "/home/ASR/CocoPi_Asr_Model/CocoPi_Asr_Model_V2.1")
- asr.clear()
- asr_kws_result=[0,0] #获取识别结果及识别概率
- similars = [
- ["pai3", "ai4"],
- ["le4", "luo4"],
- ]
- def asr_kws(keys):
- global asr_kws_result
- tmp = max(keys)
- asr_kws_result[0] = keys.index(tmp)
- asr_kws_result[1] = round(tmp,2)
- `
- // Blockly.Python.definitions_["set_keywords_function"] = `def SetKeywords(data):
- // dataList = []
- // for obj in data:
- // dataList.append([obj,0.1])
- // print(dataList)
- // return dataList
- // `
- var code = `keywords = ${JSON.stringify(a)}
- asr.set_kws(keywords, similars, asr_kws)
- `;
- return code;
- };
- Blockly.Blocks['speech_recognition_set_pinyin_tone'] = {
- init: function () {
- this.appendDummyInput()
- .appendField("声调").appendField(new Blockly.FieldDropdown([
- ["1", "1"],
- ["2", "2"],
- ["3", "3"],
- ["4", "4"],
- ]), "tone");
- this.setOutput(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_get_result_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['speech_recognition_set_pinyin_tone'] = function (block) {
- let tone = block.getFieldValue('tone');
- console.log(tone)
- Blockly.Python.definitions_.speech_recognition_phonetic_to_pinyin_start_recognition_def = `def getAsrResult():
- global asr_kws_result,keywords
- if(asr_kws_result[1]!=0):
- asr_kws_result_list = keywords[asr_kws_result[0]][0]
- return asr_kws_result_list
- `
- var code = tone;
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['speech_recognition_phonetic_to_pinyin_start_recognition'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.speech_recognition_phonetic_to_pinyin_start_recognition);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.speech_recognition_phonetic_to_pinyin_start_recognition_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['speech_recognition_phonetic_to_pinyin_start_recognition'] = function (block) {
- var code = "asr.run(1)\n";
- return code;
- };
- Blockly.Blocks['speech_recognition_phonetic_to_pinyin_stop_recognition'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.speech_recognition_phonetic_to_pinyin_stop_recognition);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.speech_recognition_phonetic_to_pinyin_stop_recognition_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['speech_recognition_phonetic_to_pinyin_stop_recognition'] = function (block) {
- var code = "asr.exit()\n";
- return code;
- };
- Blockly.Blocks['speech_recognition_phonetic_to_pinyin_pause_recognition'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.speech_recognition_phonetic_to_pinyin_pause_recognition);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.speech_recognition_phonetic_to_pinyin_pause_recognition_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['speech_recognition_phonetic_to_pinyin_pause_recognition'] = function (block) {
- var code = "asr.clear()\n";
- return code;
- };
- Blockly.Blocks['speech_recognition_phonetic_to_pinyin_get_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_get_result);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_get_result_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['speech_recognition_phonetic_to_pinyin_get_result'] = function (block) {
- Blockly.Python.definitions_.speech_recognition_phonetic_to_pinyin_start_recognition_def = `def getAsrResult():
- global asr_kws_result,keywords
- if(asr_kws_result[1]!=0):
- asr_kws_result_list = keywords[asr_kws_result[0]][0]
- return asr_kws_result_list
- `
- var code = 'getAsrResult()';
- return [code, Blockly.Python.ORDER_NONE];
- };
- // numpy + mnist
- Blockly.Blocks['Numpy_Neural_Network_init'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.numpy_mnist_model_init);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.numpy_mnist_model_init);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['Numpy_Neural_Network_init'] = function (block) {
- Blockly.Python.definitions_['v831_import_numpy_as_np'] = `import numpy as np`;
- Blockly.Python.definitions_["v831_import_pickle"] = `import pickle`
- Blockly.Python.definitions_["v831_NeuralNetwork_init"] = `def sigmoid(x):
- return 1/(1+np.exp(-x))
- def grad(x):
- return x*(1-x)
- class NeuralNetwork:
- """
- 三层全连接前馈神经网络
- """
- def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate, active_function=sigmoid, gradient=grad, lambda_=0.1):
- """
- :param inputnodes: 输入层结点数
- :param hiddennodes: 隐藏层节点数
- :param outputnodes: 输出层节点数
- :param learningrate: 学习率
- :param active_function: 激活函数
- :param gradient: 激活函数的导数
- :param lambda_: L2正则化系数
- """
- self.inputnodes = inputnodes
- self.hiddennodes = hiddennodes
- self.outputnodes = outputnodes
- self.learningrate = learningrate
- self.active_function = active_function
- self.gradient = gradient
- self.lambda_ = lambda_
- # 权值矩阵
- self.weights_i_h = np.random.rand(
- self.hiddennodes, self.inputnodes) - 0.5
- self.weights_h_o = np.random.rand(
- self.outputnodes, self.hiddennodes) - 0.5
- def train_sgd(self, x, y):
- """梯度下降训练"""
- TRAINX = np.array(x).reshape(-1, 1)
- target = np.zeros((self.outputnodes, 1)) + 0.01
- target[y, 0] = 0.99
- hiddeninputs = np.dot(self.weights_i_h, TRAINX)
- hiddenoutputs = self.active_function(hiddeninputs)
- outputinputs = np.dot(self.weights_h_o, hiddenoutputs)
- final_outputs = self.active_function(outputinputs)
- error = target - final_outputs
- hidden_error = np.dot(self.weights_h_o.transpose(), error)
- self.weights_h_o += self.learningrate * error * \
- np.dot(self.gradient(final_outputs), hiddenoutputs.transpose())
- self.weights_i_h += self.learningrate * hidden_error * \
- np.dot(self.gradient(hiddenoutputs), TRAINX.transpose())
- def fit(self, TRAINX, targets):
- TRAINX = np.array(TRAINX)
- for i in range(TRAINX.shape[0]):
- self.train_sgd(TRAINX[i], targets[i])
- def query(self, inputs, debug=False):
- """单个值预测"""
- inputs = np.array(inputs).reshape(-1, 1)
- hidden_input = np.dot(self.weights_i_h, inputs)
- hidden_output = self.active_function(hidden_input)
- output_input = np.dot(self.weights_h_o, hidden_output)
- final_output = self.active_function(output_input)
- if debug:
- print("predict: ", final_output)
- return np.argmax(final_output)
- def predict(self, inputs):
- """批量预测"""
- res = []
- for x in inputs:
- res.append(self.query(x))
- return res
- def __str__(self):
- return "NeuralNetwork: \\ninput_nodes = {0}, hidden_nodes = {1}, \\noutputnodes = {2}, learningrate = {3}".format(self.inputnodes, self.hiddennodes, self.outputnodes, self.learningrate)
- # 用测试数据测试
- def accuracy(y_true, y_pred):
- """准确度"""
- y_true = np.array(y_true)
- y_pred = np.array(y_pred)
- return sum(y_true == y_pred)/y_true.shape[0]
- # 用全部数据进行训练
- def get_data():
- # train_df = np.loadtxt("mnist_train.csv", delimiter=",", dtype=str)
- # test_df = np.loadtxt("mnist_test.csv", delimiter=",", dtype=str)
- global train_df, test_df
- print(train_df.shape)
- print(test_df.shape)
- train_data = train_df.astype("int")
- TRAINX = train_data[:, 1:]
- TRAINY = train_data[:, 0]
- TRAINX = TRAINX / 255 * 0.99 + 0.01
- test_data = test_df.astype("int")
- TESTX = test_data[:, 1:]
- TESTY = test_data[:, 0]
- TESTX = TESTX / 255 * 0.99 + 0.01
- return TRAINX, TRAINY, TESTX, TESTY
- `
- var code = '';
- return code;
- };
- Blockly.Blocks['Numpy_Neural_Network_load'] = {
- init: function () {
- this.appendDummyInput()
- .appendField("numpy + mnist 训练模型加载");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip("numpy + mnist 训练模型加载");
- this.setHelpUrl("");
- }
- };
- Blockly.Python['Numpy_Neural_Network_load'] = function (block) {
- Blockly.Python.definitions_['v831_import_numpy_as_np'] = `import numpy as np`;
- Blockly.Python.definitions_["v831_import_pickle"] = `import pickle`
- Blockly.Python.definitions_["v831_NeuralNetwork_init"] = `def sigmoid(x):
- return 1/(1+np.exp(-x))
- def grad(x):
- return x*(1-x)
- class NeuralNetwork:
- """
- 三层全连接前馈神经网络
- """
- def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate, active_function=sigmoid, gradient=grad, lambda_=0.1):
- """
- :param inputnodes: 输入层结点数
- :param hiddennodes: 隐藏层节点数
- :param outputnodes: 输出层节点数
- :param learningrate: 学习率
- :param active_function: 激活函数
- :param gradient: 激活函数的导数
- :param lambda_: L2正则化系数
- """
- self.inputnodes = inputnodes
- self.hiddennodes = hiddennodes
- self.outputnodes = outputnodes
- self.learningrate = learningrate
- self.active_function = active_function
- self.gradient = gradient
- self.lambda_ = lambda_
- # 权值矩阵
- self.weights_i_h = np.random.rand(
- self.hiddennodes, self.inputnodes) - 0.5
- self.weights_h_o = np.random.rand(
- self.outputnodes, self.hiddennodes) - 0.5
- def train_sgd(self, x, y):
- """梯度下降训练"""
- TRAINX = np.array(x).reshape(-1, 1)
- target = np.zeros((self.outputnodes, 1)) + 0.01
- target[y, 0] = 0.99
- hiddeninputs = np.dot(self.weights_i_h, TRAINX)
- hiddenoutputs = self.active_function(hiddeninputs)
- outputinputs = np.dot(self.weights_h_o, hiddenoutputs)
- final_outputs = self.active_function(outputinputs)
- error = target - final_outputs
- hidden_error = np.dot(self.weights_h_o.transpose(), error)
- self.weights_h_o += self.learningrate * error * \
- np.dot(self.gradient(final_outputs), hiddenoutputs.transpose())
- self.weights_i_h += self.learningrate * hidden_error * \
- np.dot(self.gradient(hiddenoutputs), TRAINX.transpose())
- def fit(self, TRAINX, targets):
- TRAINX = np.array(TRAINX)
- for i in range(TRAINX.shape[0]):
- self.train_sgd(TRAINX[i], targets[i])
- def query(self, inputs, debug=False):
- """单个值预测"""
- inputs = np.array(inputs).reshape(-1, 1)
- hidden_input = np.dot(self.weights_i_h, inputs)
- hidden_output = self.active_function(hidden_input)
- output_input = np.dot(self.weights_h_o, hidden_output)
- final_output = self.active_function(output_input)
- if debug:
- print("predict: ", final_output)
- return np.argmax(final_output)
- def predict(self, inputs):
- """批量预测"""
- res = []
- for x in inputs:
- res.append(self.query(x))
- return res
- def __str__(self):
- return "NeuralNetwork: \\ninput_nodes = {0}, hidden_nodes = {1}, \\noutputnodes = {2}, learningrate = {3}".format(self.inputnodes, self.hiddennodes, self.outputnodes, self.learningrate)
- # 用测试数据测试
- def accuracy(y_true, y_pred):
- """准确度"""
- y_true = np.array(y_true)
- y_pred = np.array(y_pred)
- return sum(y_true == y_pred)/y_true.shape[0]
- # 用全部数据进行训练
- def get_data():
- # train_df = np.loadtxt("mnist_train.csv", delimiter=",", dtype=str)
- # test_df = np.loadtxt("mnist_test.csv", delimiter=",", dtype=str)
- global train_df, test_df
- print(train_df.shape)
- print(test_df.shape)
- train_data = train_df.astype("int")
- TRAINX = train_data[:, 1:]
- TRAINY = train_data[:, 0]
- TRAINX = TRAINX / 255 * 0.99 + 0.01
- test_data = test_df.astype("int")
- TESTX = test_data[:, 1:]
- TESTY = test_data[:, 0]
- TESTX = TESTX / 255 * 0.99 + 0.01
- return TRAINX, TRAINY, TESTX, TESTY
- `
- var code = `#构建神经网络训练服务
- TRAINX, TRAINY, TESTX, TESTY = get_data()
- NN = NeuralNetwork(784, 100, 10, 0.3)
- NN.fit(TRAINX, TRAINY)
- y_pred = NN.predict(TESTX)
- `;
- return code;
- };
- Blockly.Blocks['Numpy_Neural_Network_LOading_test_train'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.numpy_mnist_loading_train_and_test_set);
- this.appendValueInput("class_input")
- .setCheck(null)
- .appendField(Blockly.Msg.numpy_mnist_train_set_url);
- this.appendValueInput("class_input1")
- .setCheck(null)
- .appendField(Blockly.Msg.numpy_mnist_test_set_url);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.numpy_mnist_loading_train_and_test_set);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['Numpy_Neural_Network_LOading_test_train'] = function (block) {
- var trainUrl = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
- var testUrl = Blockly.Python.valueToCode(block, 'class_input1', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- var code = `test_df = np.loadtxt(${testUrl}, delimiter=",", dtype=str)
- train_df = np.loadtxt(${trainUrl}, delimiter=",", dtype=str)
- `;
- // TODO: Change ORDER_NONE to the correct strength.
- return code;
- };
- Blockly.Blocks['Numpy_Neural_Network_numpy_isStart'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.numpy_mnist_is_training_start);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.numpy_mnist_is_training_start);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['Numpy_Neural_Network_numpy_isStart'] = function (block) {
- // TODO: Assemble Python into code variable.
- var code = `not os.path.exists("/usr/lib/python3.8/site-packages/numpy/random/__init__.py")`;
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- Blockly.Blocks['Numpy_Neural_Network_setting_training_argument'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.numpy_mnist_setting_training_argument);
- this.appendValueInput("class_input")
- .setCheck(null)
- .appendField(Blockly.Msg.numpy_mnist_input_trait_dimensionality);
- this.appendValueInput("class_input1")
- .setCheck(null)
- .appendField(Blockly.Msg.numpy_mnist_setting_training_argument_number_node);
- this.appendValueInput("class_input2")
- .setCheck(null)
- .appendField(Blockly.Msg.numpy_mnist_output_dimensionality);
- this.appendValueInput("class_input3")
- .setCheck(null)
- .appendField(Blockly.Msg.numpy_mnist_setting_training_argument_learning_rate);
- this.appendValueInput("class_input4")
- .setCheck(null)
- .appendField(Blockly.Msg.numpy_mnist_setting_training_argument_frequency);
- this.appendValueInput("class_input5")
- .setCheck(null)
- .appendField(Blockly.Msg.VIDEO_S_S);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.numpy_mnist_setting_training_argument);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['Numpy_Neural_Network_setting_training_argument'] = function (block) {
- var class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
- var class_input1 = Blockly.Python.valueToCode(block, 'class_input1', Blockly.Python.ORDER_ATOMIC);
- var class_input2 = Blockly.Python.valueToCode(block, 'class_input2', Blockly.Python.ORDER_ATOMIC);
- var class_input3 = Blockly.Python.valueToCode(block, 'class_input3', Blockly.Python.ORDER_ATOMIC);
- var class_input4 = Blockly.Python.valueToCode(block, 'class_input4', Blockly.Python.ORDER_ATOMIC);
- var class_input5 = Blockly.Python.valueToCode(block, 'class_input5', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- console.log(Number(class_input.slice(1, -1)), class_input1, class_input2, class_input3)
- var code = `TRAINX, TRAINY, TESTX, TESTY = get_data()
- 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))})
- #开启神经网络训练,记录时长
- AccuracyRATE = 0
- # 训练10次,每3次训练下降一次学习率
- for e in range(1, ${Number(class_input4.slice(1, -1)) + 1}):
- if e % 3 == 0:
- NN.learningrate /= 2
- NN.fit(TRAINX, TRAINY)
- y_pred = NN.predict(TESTX)
- CURRENTACCURACY = accuracy(TESTY, y_pred)
- if CURRENTACCURACY > AccuracyRATE:
- AccuracyRATE = CURRENTACCURACY
- #文件已保存至
- with open(${class_input5}, "wb") as f: # 保存模型
- pickle.dump(pickle.dumps(NN), f)
- os.system("touch /usr/lib/python3.8/site-packages/numpy/random/__init__.py")
- `;
- // TODO: Change ORDER_NONE to the correct strength.
- return code;
- };
- //
- Blockly.Blocks['Numpy_Neural_Network_numpy_loading_model'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.numpy_mnist_loading_model);
- this.appendValueInput("class_input")
- .setCheck(null)
- .appendField(Blockly.Msg.AUDIO_S_PF);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.numpy_mnist_loading_model);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['Numpy_Neural_Network_numpy_loading_model'] = function (block) {
- var trainUrl = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- var code = `try:
- with open(${trainUrl},"rb") as f:
- b_data = pickle.load(f)
- net_model = pickle.loads(b_data)
- except:
- pass
- `;
- // TODO: Change ORDER_NONE to the correct strength.
- return code;
- };
- Blockly.Python['Numpy_Neural_Network_LOading_test_train'] = function (block) {
- var trainUrl = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
- var testUrl = Blockly.Python.valueToCode(block, 'class_input1', Blockly.Python.ORDER_ATOMIC);
- // TODO: Assemble Python into code variable.
- var code = `test_df = np.loadtxt(${testUrl}, delimiter=",", dtype=str)
- train_df = np.loadtxt(${trainUrl}, delimiter=",", dtype=str)
- `;
- // TODO: Change ORDER_NONE to the correct strength.
- return code;
- };
- Blockly.Blocks['Numpy_Neural_Network_numpy_loading_model_fun'] = {
- init: function () {
- // this.appendDummyInput()
- // .appendField("获取检测结果");
- this.appendDummyInput()
- .appendField("在屏幕中显示numpy的检测结果")
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.ai_model_getclass_TOOLTIP);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['Numpy_Neural_Network_numpy_loading_model_fun'] = function (block) {
- Blockly.Python.definitions_["v831_import_PIL_image"] = `from PIL import Image`
- Blockly.Python.definitions_["v831_function_numpy_result"] = `def numpyResult(img):
- img_path="/root/user/image_1.png"
- img_gray_path="/root/user/image_gray.png"
- mk = img.crop(0, 0, 240, 240) #裁剪图像为320*240
- mk1=img.crop(0, 0, 240, 240).resize(224,224) #继续裁剪图像为224*224
- numpyResultcanvas= image.new(size = (320, 240), color = (0,255,0), mode = 'RGB') #创建背景图
- numpyResultcanvas.draw_image(mk1.rotate(90,adjust=1),58,8) #贴224*224的图片
- mk2=mk1.resize(28,28) #裁剪图片为28*28
- numpyResultcanvas.draw_image(mk2,8,8) #贴28*28的图
- mk2.save(img_path)
- origin=Image.open(img_path).convert('L') #转为8位分辨率灰度图(0~255)
- origin.save(img_gray_path)
- origin_gray=image.open(img_gray_path)
- numpyResultcanvas.draw_image(origin_gray,8,48)
- numpyResultImg = np.array(origin).reshape(1, 784).astype('int')
- numpyResultImg = numpyResultImg / 255 * 0.99 + 0.01
- print(numpyResultImg.shape)
- result = net_model.query(numpyResultImg)
- return result
- `
- // TODO: Assemble Python into code variable.
- var code = `canvas = canvas.crop(48,8,224,224)
- GETNUMPYRESULT = numpyResult(canvas)
- if GETNUMPYRESULT != "":
- canvas.draw_string(0,0, (str(GETNUMPYRESULT)), scale = 3, color = (204,204,204) , thickness = 1)
- else:
- canvas.draw_string(0,0, ("None"), scale = 3, color = (204,204,204) , thickness = 1)
- `;
- // TODO: Change ORDER_NONE to the correct strength.
- return code;
- };
- Blockly.Blocks['Numpy_Neural_Network_numpy_loading_model_result'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.numpy_mnist_get_result);
- this.setOutput(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.numpy_mnist_get_result);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['Numpy_Neural_Network_numpy_loading_model_result'] = function (block) {
- var code = `GETNUMPYRESULT`;
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_NONE];
- };
- //
- Blockly.Blocks['Numpy_Neural_Network_numpy_clear'] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.numpy_mnist_clear);
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#ee783a");
- this.setTooltip(Blockly.Msg.numpy_mnist_clear);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['Numpy_Neural_Network_numpy_clear'] = function (block) {
- var code = `os.system('rm -rf /usr/lib/python3.8/site-packages/numpy/random/__init__.py')
- `;
- // TODO: Change ORDER_NONE to the correct strength.
- return code;
- };
- Blockly.Blocks["cocopi_chatGpt_init"] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ChatGpt_init); //
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setColour("#7e3cca");
- this.setTooltip(Blockly.Msg.ChatGpt_init);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['cocopi_chatGpt_init'] = function (block) {
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try:
- from CocoPi import GPTrequest
- except:
- import sys
- sys.path.append("/home/drivers/pylib/")
- from GPTrequest import GPTrequest`
- Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()`
- var code = ``;
- // TODO: Change ORDER_NONE to the correct strength.
- return code;
- };
- Blockly.Blocks["cocopi_chatGpt_text_to_img_loading"] = {
- init: function () {
- this.appendValueInput("NAME")
- .setCheck(null)
- .appendField(Blockly.Msg.ChatGpt_set_img_des);
- this.appendDummyInput()
- .appendField(Blockly.Msg.ChatGpt_get_img_path_result);
- this.setOutput(true, null);
- this.setColour("#7e3cca");
- this.setTooltip(Blockly.Msg.ChatGpt_set_img_des);
- this.setInputsInline(false)
- this.setHelpUrl("");
- }
- };
- Blockly.Python['cocopi_chatGpt_text_to_img_loading'] = function (block) {
- var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try:
- from CocoPi import GPTrequest
- except:
- import sys
- sys.path.append("/home/drivers/pylib/")
- from GPTrequest import GPTrequest`
- Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()`
- // Blockly.Python.addVariable("TextContent", `TextContent = ""`, true)
- var code = `gptInit.get_text_to_img(${text})`;
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks["cocopi_chatGpt_image_to_text_loading"] = {
- init: function () {
- this.appendValueInput("NAME")
- .setCheck(null)
- .appendField(Blockly.Msg.ChatGpt_set_text_path);
- this.appendValueInput("NAME1")
- .setCheck(null)
- .appendField(Blockly.Msg.ChatGpt_set_text_text_content);
- this.appendDummyInput()
- .appendField(Blockly.Msg.ChatGpt_get_text_content_result);
- this.setOutput(true, null);
- this.setInputsInline(false);
- this.setColour("#7e3cca");
- this.setTooltip(Blockly.Msg.ChatGpt_set_text_path);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['cocopi_chatGpt_image_to_text_loading'] = function (block) {
- var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
- var content = Blockly.Python.valueToCode(block, 'NAME1', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try:
- from CocoPi import GPTrequest
- except:
- import sys
- sys.path.append("/home/drivers/pylib/")
- from GPTrequest import GPTrequest`
- Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()`
- var code = `gptInit.get_image_to_text(${text},${content})`;
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks["cocopi_chatGpt_text_to_voice_loading"] = {
- init: function () {
- this.appendValueInput("NAME")
- .setCheck(null)
- .appendField(Blockly.Msg.ChatGpt_set_text_content);
- this.appendDummyInput()
- .appendField(Blockly.Msg.ChatGpt_get_voice_path_result);
- this.setOutput(true, null);
- this.setInputsInline(false);
- this.setColour("#7e3cca");
- this.setTooltip(Blockly.Msg.ChatGpt_get_voice_path_result);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['cocopi_chatGpt_text_to_voice_loading'] = function (block) {
- var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try:
- from CocoPi import GPTrequest
- except:
- import sys
- sys.path.append("/home/drivers/pylib/")
- from GPTrequest import GPTrequest`
- Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()`
- var code = `gptInit.get_text_to_voice(${text})`;
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks["cocopi_chatGpt_text_to_voice_result"] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ChatGpt_get_voice_path_result);
- this.setOutput(true, null);
- this.setColour("#7e3cca");
- this.setTooltip(Blockly.Msg.ChatGpt_get_voice_path_result);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['cocopi_chatGpt_text_to_voice_result'] = function (block) {
- var code = `gptInit.get_text_to_voice(VOICECONTENT)`;
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks["cocopi_chatGpt_voice_to_text_loading"] = {
- init: function () {
- this.appendValueInput("NAME")
- .setCheck(null)
- .appendField(Blockly.Msg.ChatGpt_set_voice_path);
- this.appendDummyInput()
- .appendField(Blockly.Msg.ChatGpt_get_voice_text_content_result);
- this.setOutput(true, null);
- this.setInputsInline(false)
- this.setColour("#7e3cca");
- this.setTooltip(Blockly.Msg.ChatGpt_set_voice_path);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['cocopi_chatGpt_voice_to_text_loading'] = function (block) {
- var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try:
- from CocoPi import GPTrequest
- except:
- import sys
- sys.path.append("/home/drivers/pylib/")
- from GPTrequest import GPTrequest`
- Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()`
- var code = `gptInit.get_voice_to_text(${text})`;
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks["cocopi_chatGpt_post_chatgpt_loading"] = {
- init: function () {
- this.appendValueInput("NAME")
- .setCheck(null)
- .appendField(Blockly.Msg.ChatGpt_set_problem_content);
- this.appendDummyInput()
- .appendField(Blockly.Msg.ChatGpt_get_problem_result);
- this.setOutput(true, null);
- this.setInputsInline(false)
- this.setColour("#7e3cca");
- this.setTooltip(Blockly.Msg.ChatGpt_set_problem_content);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['cocopi_chatGpt_post_chatgpt_loading'] = function (block) {
- var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try:
- from CocoPi import GPTrequest
- except:
- import sys
- sys.path.append("/home/drivers/pylib/")
- from GPTrequest import GPTrequest`
- Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()`
- var code = `gptInit.get_post_chatgpt(${text})`;
- // TODO: Change ORDER_NONE to the correct strength.
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks["cocopi_chatGpt_post_chatgpt_result"] = {
- init: function () {
- this.appendDummyInput()
- .appendField(Blockly.Msg.ChatGpt_get_problem_result);
- this.setOutput(true, null);
- this.setColour("#7e3cca");
- this.setTooltip(Blockly.Msg.ChatGpt_get_problem_result);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['cocopi_chatGpt_post_chatgpt_result'] = function (block) {
- var code = `gptInit.get_post_chatgpt(CHATGPTPROBLEM)`;
- return [code, Blockly.Python.ORDER_ATOMIC];;
- };
- //
- Blockly.Blocks["cocopi_chatGpt_result"] = {
- init: function () {
- this.appendDummyInput()
- // .appendField(Blockly.Msg.ChatGpt_get_problem_result)
- .appendField(new Blockly.FieldDropdown([
- [Blockly.Msg.ChatGpt_get_img_path_result, "1"],
- [Blockly.Msg.ChatGpt_get_text_content_result, "2"],
- [Blockly.Msg.ChatGpt_get_voice_path_result, "3"],
- [Blockly.Msg.ChatGpt_get_voice_text_content_result, "4"],
- [Blockly.Msg.ChatGpt_get_problem_result, "5"],
- [Blockly.Msg.ChatGpt_ai_agent_chat_result, "6"]
- ]), "gpt_return");
- this.setOutput(true, null);
- this.setColour("#7e3cca");
- this.setTooltip(Blockly.Msg.ChatGpt_get_problem_result);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['cocopi_chatGpt_result'] = function (block) {
- var queue_value = block.getFieldValue('gpt_return');
- Blockly.Python.addVariable("CocoPiGPTRESULT", `CocoPiGPTRESULT = None`, true)
- var res = ``;
- if (queue_value == 5) {
- res = `gptInit.get_post_chatgpt(CHATGPTPROBLEM)`
- } else if (queue_value == 4) {
- res = `gptInit.get_voice_to_text(VOICEPATH)`
- } else if (queue_value == 3) {
- res = `gptInit.get_text_to_voice(VOICECONTENT)`
- } else if (queue_value == 2) {
- res = `gptInit.get_image_to_text(IMAGEPATH,IMAGECONTENT)`
- } else if (queue_value == 1) {
- res = `gptInit.get_text_to_img(TextContent)`
- }
- else if (queue_value == 6) {
- res = `gptInit.get_post_AI_Intelligence(AIAGENTCHATID,AIAGENTCHATMESSAGE)`
- }
- Blockly.Python.definitions_["CocoPiGPTRESULTFUNC"] = `def CocoPiGPTRESULTFUNC(res):
- global CocoPiGPTRESULT
- try:
- CocoPiGPTRESULT = res
- except:
- CocoPiGPTRESULT = ""
- return CocoPiGPTRESULT
- `
- var code = `CocoPiGPTRESULTFUNC(${res})`;
- return [code, Blockly.Python.ORDER_ATOMIC];;
- };
- Blockly.Blocks["cocopi_chatGpt_AI_loading"] = {
- init: function () {
- this.appendValueInput("NAME")
- .setCheck(null)
- .appendField(Blockly.Msg.ChatGpt_ai_agent_chat_set_appID);
- this.appendValueInput("NAME1")
- .setCheck(null)
- .appendField(Blockly.Msg.ChatGpt_set_problem_content);
- this.appendDummyInput().appendField(Blockly.Msg.ChatGpt_ai_agent_chat_result)
- this.setOutput(true, null);
- this.setInputsInline(false);
- this.setColour("#7e3cca");
- this.setTooltip(Blockly.Msg.ChatGpt_set_text_path);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['cocopi_chatGpt_AI_loading'] = function (block) {
- var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
- var content = Blockly.Python.valueToCode(block, 'NAME1', Blockly.Python.ORDER_ATOMIC);
- var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try:
- from CocoPi import GPTrequest
- except:
- import sys
- sys.path.append("/home/drivers/pylib/")
- from GPTrequest import GPTrequest`
- Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()`
- var code = `gptInit.get_post_AI_Intelligence(${text},${content})`
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- //
- Blockly.Blocks["cocopi_chatGpt_AI_loading_more"] = {
- init: function () {
- this.appendValueInput("NAME")
- .setCheck(null)
- .appendField(Blockly.Msg.ChatGpt_ai_agent_chat_set_appID_more);
- this.appendValueInput("NAME1")
- .setCheck(null)
- .appendField(Blockly.Msg.ChatGpt_set_problem_content);
- this.appendDummyInput().appendField(Blockly.Msg.ChatGpt_ai_agent_chat_result_more)
- this.setOutput(true, null);
- this.setInputsInline(false);
- this.setColour("#7e3cca");
- this.setTooltip(Blockly.Msg.ChatGpt_set_text_path);
- this.setHelpUrl("");
- }
- };
- Blockly.Python['cocopi_chatGpt_AI_loading_more'] = function (block) {
- var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
- var content = Blockly.Python.valueToCode(block, 'NAME1', Blockly.Python.ORDER_ATOMIC);
- var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
- Blockly.Python.definitions_['v831_import_sys'] = `import sys
- sys.path.append("/root/")`
- Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try:
- from CocoPi import GPTrequest
- except:
- import sys
- sys.path.append("/home/drivers/pylib/")
- from GPTrequest import GPTrequest`
- Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()`
- var code = `gptInit.cocopi_chatGpt_AI_loading_more(${text},${content})`
- // Blockly.Python.definitions_['v831_import_requests'] = `import requests`
- // Blockly.Python.definitions_['v831_import_json'] = `import json`
- // Blockly.Python.definitions_['v831_import_os'] = `import os`
- // Blockly.Python.definitions_['v831_import_time'] = `import time`
- // Blockly.Python.addFunction("cocopi_chatGpt_AI_loading_more", `def cocopi_chatGpt_AI_loading_more(appID,content):
- // url = "https://gpt4.cocorobo.cn/handle_muti_agent"
- // headers={
- // "Content-Type":"application/json",
- // }
- // cmd="cat /sys/class/sunxi_info/sys_info"
- // rec=os.popen(cmd).read()
- // hwMac=rec[rec.find("sunxi_serial : ")+20:rec.find("sunxi_serial : ")+52]
- // params = {
- // "muti_agent_id":appID,
- // "message":content,
- // "userId":"602def61-005d-11ee-91d8-005056b86db5",
- // "session_name":"0606"
- // }
- // textContent = ""
- // res = requests.post(url, headers=headers, data=json.dumps(params))
- // try:
- // textContent = json.loads(res.text)["FunctionResponse"]["response"]
- // except:
- // textContent = ""
- // return textContent
- // `, true)
- return [code, Blockly.Python.ORDER_ATOMIC];
- };
- Blockly.Blocks.tuple_create_with_items_inserts = {
- init: function () {
- this.setHelpUrl(Blockly.Msg.TUPLE_CREATE_WITH_ITEMS_INSERT_HELPURL);
- this.setColour("#ee783a");
- this.itemCount_ = 3;
- this.updateShape_();
- this.setOutput(!0);
- this.setMutator(new Blockly.Mutator(["tuple_create_with_items"]));
- this.setTooltip(Blockly.Msg.TUPLE_CREATE_WITH_ITEMS_INSERT_TOOLTIP)
- },
- mutationToDom: function () {
- var a = document.createElement("mutation");
- a.setAttribute("items", this.itemCount_);
- return a
- },
- domToMutation: function (a) {
- this.itemCount_ = parseInt(a.getAttribute("items"), 10);
- this.updateShape_()
- },
- decompose: function (a) {
- var b = a.newBlock("tuple_create_with_containers");
- b.initSvg();
- for (var c = b.getInput("STACK").connection, e = 0; e < this.itemCount_; e++) {
- var d = a.newBlock("tuple_create_with_items");
- d.initSvg();
- c.connect(d.previousConnection);
- c = d.nextConnection
- }
- return b
- },
- compose: function (a) {
- var b = a.getInputTargetBlock("STACK");
- for (a = []; b;)
- a.push(b.valueConnection_),
- b = b.nextConnection && b.nextConnection.targetBlock();
- for (b = 0; b < this.itemCount_; b++) {
- var c = this.getInput("ADD" + b).connection.targetConnection;
- c && -1 == a.indexOf(c) && c.disconnect()
- }
- this.itemCount_ = a.length;
- this.updateShape_();
- for (b = 0; b < this.itemCount_; b++)
- Blockly.Mutator.reconnect(a[b], this, "ADD" + b)
- },
- saveConnections: function (a) {
- a = a.getInputTargetBlock("STACK");
- for (var b = 0; a;) {
- var c = this.getInput("ADD" + b);
- a.valueConnection_ = c && c.connection.targetConnection;
- b++;
- a = a.nextConnection && a.nextConnection.targetBlock()
- }
- },
- updateShape_: function () {
- this.itemCount_ && this.getInput("EMPTY") ? this.removeInput("EMPTY") : this.itemCount_ || this.getInput("EMPTY") || this.appendDummyInput("EMPTY").appendField(Blockly.Msg.TUPLE_CREATE_EMPTY_TITLE);
- for (var a = 0; a < this.itemCount_; a++)
- if (!this.getInput("ADD" + a)) {
- var b = this.appendValueInput("ADD" + a);
- 0 == a && b.appendField(Blockly.Msg.TUPLE_CREATE_WITH_INPUT_WITH)
- }
- for (; this.getInput("ADD" + a);)
- this.removeInput("ADD" + a),
- a++
- }
- };
- Blockly.Blocks.tuple_create_with_items = {
- init: function () {
- this.setColour("#ee783a");
- this.appendDummyInput().appendField(Blockly.Msg.TUPLE_CREATE_WITH_ITEM_TITLE);
- this.setPreviousStatement(!0);
- this.setNextStatement(!0);
- this.setTooltip(Blockly.Msg.TUPLE_CREATE_WITH_ITEM_TOOLTIP);
- this.contextMenu = !1
- }
- };
- Blockly.Blocks.tuple_create_with_containers = {
- init: function () {
- this.setColour("#ee783a");
- this.appendDummyInput().appendField(Blockly.Msg.TUPLE_CREATE_WITH_CONTAINER_TITLE_ADD);
- this.appendStatementInput("STACK");
- this.setTooltip(Blockly.Msg.TUPLE_CREATE_WITH_CONTAINER_TOOLTIP);
- this.contextMenu = !1
- }
- };
- Blockly.Python.tuple_create_with_items_inserts = function (a) {
- for (var b = Array(a.itemCount_), c = 0; c < a.itemCount_; c++)
- b[c] = Blockly.Python.valueToCode(a, "ADD" + c, Blockly.Python.ORDER_NONE) || "None";
- return [1 == a.itemCount_ ? "(" + b[0] + ",)" : "(" + b.join(", ") + ")", Blockly.Python.ORDER_ATOMIC]
- };
|