1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516 |
- /*
- _ ___ ____ _
- / \ |_ _| | __ ) __ _ ___(_) ___
- / _ \ | | | _ \ / _` / __| |/ __|
- / ___ \ | | | |_) | (_| \__ \ | (__
- /_/ \_\___| |____/ \__,_|___/_|\___|
- */
- 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;
- }
- 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.updateShape_();
- this.setMutator(new Blockly.Mutator(['ai_model_false_create_with_item']));
- this.setColour("#ee783a");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setTooltip("");
- this.setHelpUrl("");
- this.itemCount_ = 0;
- },
- mutationToDom: function () {
- if (!this.itemCount_)
- return null;
- var container = document.createElement('mutation');
- this.itemCount_ && container.setAttribute('aielse', 1);
- return container;
- },
- domToMutation: function (a) {
- this.itemCount_ = parseInt(a.getAttribute('aielse'), 10);
- this.updateShape_();
- },
- decompose: function (a) {
- var b = a.newBlock('ai_model_false_create_with_container');
- b.initSvg();
- var c = b.nextConnection
- this.itemCount_ && (a = a.newBlock("ai_model_false_create_with_item"),
- a.initSvg(),
- c.connect(a.previousConnection));
- console.log("this.elseCount_", a)
- return b
- },
- compose: function (a) {
- var b = a.nextConnection.targetBlock();
- this.itemCount_ = 0;
- var e = null;
- if (b && b.type === "ai_model_false_create_with_item") {
- this.itemCount_++;
- e = b.statementConnection_;
- b = b.nextConnection && b.nextConnection.targetBlock()
- }
- this.updateShape_()
- Blockly.Mutator.reconnect(e, this, "AIELSE")
- },
- saveConnections: function (a) {
- a = a.nextConnection.targetBlock();
- if (a && a.type === "ai_model_false_create_with_item") {
- e = this.getInput("AIELSE");
- a.statementConnection_ = e && e.connection.targetConnection;
- a = a.nextConnection && a.nextConnection.targetBlock()
- }
- },
- updateShape_: function () {
- this.getInput("AIELSE") && this.removeInput("AIELSE");
- console.log("this.itemCount_", this.itemCount_)
- this.itemCount_ && this.appendStatementInput("AIELSE").appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE)
- },
- };
- Blockly.Blocks['ai_model_false_create_with_container'] = {
- init: function () {
- this.setColour("#ee783a");
- this.appendDummyInput()
- .appendField(Blockly.Msg.CONTROLS_REPEAT_INPUT_DO);
- this.setNextStatement(true)
- this.setTooltip('');
- this.contextMenu = false;
- }
- };
- Blockly.Blocks['ai_model_false_create_with_item'] = {
- init: function () {
- this.setColour("#ee783a");
- this.appendDummyInput().appendField(Blockly.Msg.CONTROLS_IF_ELSE_TITLE_ELSE);
- this.setPreviousStatement(!0);
- this.setTooltip(Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP);
- this.contextMenu = !1
- }
- };
- Blockly.Python['ai_model_digital_new'] = function (block) {
- var statements_input = Blockly.Python.statementToCode(block, 'input');
- var statements_input1 = Blockly.Python.statementToCode(block, 'AIELSE');
- let allBlocks = block.workspace.getAllBlocks();
- let global = ""
- try {
- global = allBlocks[0].workspace.variableList.toString()
- }
- catch (e) {
- console.log(e)
- }
- console.log(statements_input1)
- 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 != "" ? statements_input1 : " pass"}
- `
- 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.updateShape_();
- this.setMutator(new Blockly.Mutator(['ai_model_false_create_with_item']));
- this.setColour("#ee783a");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setTooltip("");
- this.setHelpUrl("");
- this.itemCount_ = 0;
- },
- mutationToDom: function () {
- if (!this.itemCount_)
- return null;
- var container = document.createElement('mutation');
- this.itemCount_ && container.setAttribute('aielse', 1);
- return container;
- },
- domToMutation: function (a) {
- this.itemCount_ = parseInt(a.getAttribute('aielse'), 10);
- this.updateShape_();
- },
- decompose: function (a) {
- var b = a.newBlock('ai_model_false_create_with_container');
- b.initSvg();
- var c = b.nextConnection
- this.itemCount_ && (a = a.newBlock("ai_model_false_create_with_item"),
- a.initSvg(),
- c.connect(a.previousConnection));
- console.log("this.elseCount_", a)
- return b
- },
- compose: function (a) {
- var b = a.nextConnection.targetBlock();
- this.itemCount_ = 0;
- var e = null;
- if (b && b.type === "ai_model_false_create_with_item") {
- this.itemCount_++;
- e = b.statementConnection_;
- b = b.nextConnection && b.nextConnection.targetBlock()
- }
- this.updateShape_()
- Blockly.Mutator.reconnect(e, this, "AIELSE")
- },
- saveConnections: function (a) {
- a = a.nextConnection.targetBlock();
- if (a && a.type === "ai_model_false_create_with_item") {
- e = this.getInput("AIELSE");
- a.statementConnection_ = e && e.connection.targetConnection;
- a = a.nextConnection && a.nextConnection.targetBlock()
- }
- },
- updateShape_: function () {
- this.getInput("AIELSE") && this.removeInput("AIELSE");
- console.log("this.itemCount_", this.itemCount_)
- this.itemCount_ && this.appendStatementInput("AIELSE").appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE)
- },
- };
- Blockly.Python.ai_model_look_new = function (block) {
- var statements_input = Blockly.Python.statementToCode(block, 'input');
- var statements_input1 = Blockly.Python.statementToCode(block, 'AIELSE');
- 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 != "" ? statements_input1 : " pass"}
- `
- 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.updateShape_();
- this.setMutator(new Blockly.Mutator(['ai_model_false_create_with_item']));
- this.setColour("#ee783a");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setTooltip("");
- this.setHelpUrl("");
- this.itemCount_ = 0;
- },
- mutationToDom: function () {
- if (!this.itemCount_)
- return null;
- var container = document.createElement('mutation');
- this.itemCount_ && container.setAttribute('aielse', 1);
- return container;
- },
- domToMutation: function (a) {
- this.itemCount_ = parseInt(a.getAttribute('aielse'), 10);
- this.updateShape_();
- },
- decompose: function (a) {
- var b = a.newBlock('ai_model_false_create_with_container');
- b.initSvg();
- var c = b.nextConnection
- this.itemCount_ && (a = a.newBlock("ai_model_false_create_with_item"),
- a.initSvg(),
- c.connect(a.previousConnection));
- console.log("this.elseCount_", a)
- return b
- },
- compose: function (a) {
- var b = a.nextConnection.targetBlock();
- this.itemCount_ = 0;
- var e = null;
- if (b && b.type === "ai_model_false_create_with_item") {
- this.itemCount_++;
- e = b.statementConnection_;
- b = b.nextConnection && b.nextConnection.targetBlock()
- }
- this.updateShape_()
- Blockly.Mutator.reconnect(e, this, "AIELSE")
- },
- saveConnections: function (a) {
- a = a.nextConnection.targetBlock();
- if (a && a.type === "ai_model_false_create_with_item") {
- e = this.getInput("AIELSE");
- a.statementConnection_ = e && e.connection.targetConnection;
- a = a.nextConnection && a.nextConnection.targetBlock()
- }
- },
- updateShape_: function () {
- this.getInput("AIELSE") && this.removeInput("AIELSE");
- console.log("this.itemCount_", this.itemCount_)
- this.itemCount_ && this.appendStatementInput("AIELSE").appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE)
- },
- };
- Blockly.Python.ai_model_Guesswork_look_new = function (block) {
- var statements_input = Blockly.Python.statementToCode(block, 'input');
- var statements_input1 = Blockly.Python.statementToCode(block, 'AIELSE');
- 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 != "" ? statements_input1 : " pass"}
- `
- 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.updateShape_();
- this.setMutator(new Blockly.Mutator(['ai_model_false_create_with_item']));
- this.setColour("#ee783a");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setTooltip("");
- this.setHelpUrl("");
- this.itemCount_ = 0;
- },
- mutationToDom: function () {
- if (!this.itemCount_)
- return null;
- var container = document.createElement('mutation');
- this.itemCount_ && container.setAttribute('aielse', 1);
- return container;
- },
- domToMutation: function (a) {
- this.itemCount_ = parseInt(a.getAttribute('aielse'), 10);
- this.updateShape_();
- },
- decompose: function (a) {
- var b = a.newBlock('ai_model_false_create_with_container');
- b.initSvg();
- var c = b.nextConnection
- this.itemCount_ && (a = a.newBlock("ai_model_false_create_with_item"),
- a.initSvg(),
- c.connect(a.previousConnection));
- console.log("this.elseCount_", a)
- return b
- },
- compose: function (a) {
- var b = a.nextConnection.targetBlock();
- this.itemCount_ = 0;
- var e = null;
- if (b && b.type === "ai_model_false_create_with_item") {
- this.itemCount_++;
- e = b.statementConnection_;
- b = b.nextConnection && b.nextConnection.targetBlock()
- }
- this.updateShape_()
- Blockly.Mutator.reconnect(e, this, "AIELSE")
- },
- saveConnections: function (a) {
- a = a.nextConnection.targetBlock();
- if (a && a.type === "ai_model_false_create_with_item") {
- e = this.getInput("AIELSE");
- a.statementConnection_ = e && e.connection.targetConnection;
- a = a.nextConnection && a.nextConnection.targetBlock()
- }
- },
- updateShape_: function () {
- this.getInput("AIELSE") && this.removeInput("AIELSE");
- console.log("this.itemCount_", this.itemCount_)
- this.itemCount_ && this.appendStatementInput("AIELSE").appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE)
- },
- };
- Blockly.Python.ai_model_face_new = function (block) {
- var statements_input = Blockly.Python.statementToCode(block, 'input');
- var statements_input1 = Blockly.Python.statementToCode(block, 'AIELSE');
- 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 != "" ? statements_input1 : " pass"}
- `
- 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.updateShape_();
- this.setMutator(new Blockly.Mutator(['ai_model_false_create_with_item']));
- this.setColour("#ee783a");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setTooltip("");
- this.setHelpUrl("");
- this.itemCount_ = 0;
- },
- mutationToDom: function () {
- if (!this.itemCount_)
- return null;
- var container = document.createElement('mutation');
- this.itemCount_ && container.setAttribute('aielse', 1);
- return container;
- },
- domToMutation: function (a) {
- this.itemCount_ = parseInt(a.getAttribute('aielse'), 10);
- this.updateShape_();
- },
- decompose: function (a) {
- var b = a.newBlock('ai_model_false_create_with_container');
- b.initSvg();
- var c = b.nextConnection
- this.itemCount_ && (a = a.newBlock("ai_model_false_create_with_item"),
- a.initSvg(),
- c.connect(a.previousConnection));
- console.log("this.elseCount_", a)
- return b
- },
- compose: function (a) {
- var b = a.nextConnection.targetBlock();
- this.itemCount_ = 0;
- var e = null;
- if (b && b.type === "ai_model_false_create_with_item") {
- this.itemCount_++;
- e = b.statementConnection_;
- b = b.nextConnection && b.nextConnection.targetBlock()
- }
- this.updateShape_()
- Blockly.Mutator.reconnect(e, this, "AIELSE")
- },
- saveConnections: function (a) {
- a = a.nextConnection.targetBlock();
- if (a && a.type === "ai_model_false_create_with_item") {
- e = this.getInput("AIELSE");
- a.statementConnection_ = e && e.connection.targetConnection;
- a = a.nextConnection && a.nextConnection.targetBlock()
- }
- },
- updateShape_: function () {
- this.getInput("AIELSE") && this.removeInput("AIELSE");
- console.log("this.itemCount_", this.itemCount_)
- this.itemCount_ && this.appendStatementInput("AIELSE").appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE)
- },
- };
- Blockly.Python['ai_model_card_xy_new'] = function (block) {
- var statements_input = Blockly.Python.statementToCode(block, 'input');
- var statements_input1 = Blockly.Python.statementToCode(block, 'AIELSE');
- 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 != "" ? statements_input1 : " pass"}
- `
- 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.updateShape_();
- this.setMutator(new Blockly.Mutator(['ai_model_false_create_with_item']));
- this.setColour("#ee783a");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setTooltip("");
- this.setHelpUrl("");
- this.itemCount_ = 0;
- },
- mutationToDom: function () {
- if (!this.itemCount_)
- return null;
- var container = document.createElement('mutation');
- this.itemCount_ && container.setAttribute('aielse', 1);
- return container;
- },
- domToMutation: function (a) {
- this.itemCount_ = parseInt(a.getAttribute('aielse'), 10);
- this.updateShape_();
- },
- decompose: function (a) {
- var b = a.newBlock('ai_model_false_create_with_container');
- b.initSvg();
- var c = b.nextConnection
- this.itemCount_ && (a = a.newBlock("ai_model_false_create_with_item"),
- a.initSvg(),
- c.connect(a.previousConnection));
- console.log("this.elseCount_",a)
- return b
- },
- compose: function (a) {
- var b = a.nextConnection.targetBlock();
- this.itemCount_ = 0;
- var e = null;
- if (b && b.type === "ai_model_false_create_with_item") {
- this.itemCount_++;
- e = b.statementConnection_;
- b = b.nextConnection && b.nextConnection.targetBlock()
- }
- this.updateShape_()
- Blockly.Mutator.reconnect(e, this, "AIELSE")
- },
- saveConnections: function (a) {
- a = a.nextConnection.targetBlock();
- if (a && a.type === "ai_model_false_create_with_item") {
- e = this.getInput("AIELSE");
- a.statementConnection_ = e && e.connection.targetConnection;
-
- a = a.nextConnection && a.nextConnection.targetBlock()
- }
- },
- updateShape_: function () {
- this.getInput("AIELSE") && this.removeInput("AIELSE");
- console.log("this.itemCount_",this.itemCount_)
- this.itemCount_ && this.appendStatementInput("AIELSE").appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE)
- },
- };
- Blockly.Python['face_recognition_if_face_new'] = function (block) {
- var statements_input = Blockly.Python.statementToCode(block, 'input');
- var statements_input1 = Blockly.Python.statementToCode(block, 'AIELSE');
- 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(FACESRECOGNITONRESULTI):
- ${global != "" ? `global ${global}` : "pass"}
- ${statements_input}
- `)
- var code = `if len(FACERECGNIZER.FACESRECOGNITONRESULT) > 0:
- for BOXESI in FACERECGNIZER.FACESRECOGNITONRESULT:
- recognitionStatements(BOXESI)
- else:
- ${statements_input1 != "" ? statements_input1 : " pass"}
- `
- 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.updateShape_();
- this.setMutator(new Blockly.Mutator(['ai_model_false_create_with_item']));
- this.setColour("#ee783a");
- this.setPreviousStatement(true, null);
- this.setNextStatement(true, null);
- this.setTooltip("");
- this.setHelpUrl("");
- this.itemCount_ = 0;
- },
- mutationToDom: function () {
- if (!this.itemCount_)
- return null;
- var container = document.createElement('mutation');
- this.itemCount_ && container.setAttribute('aielse', 1);
- return container;
- },
- domToMutation: function (a) {
- this.itemCount_ = parseInt(a.getAttribute('aielse'), 10);
- this.updateShape_();
- },
- decompose: function (a) {
- var b = a.newBlock('ai_model_false_create_with_container');
- b.initSvg();
- var c = b.nextConnection
- this.itemCount_ && (a = a.newBlock("ai_model_false_create_with_item"),
- a.initSvg(),
- c.connect(a.previousConnection));
- console.log("this.elseCount_",a)
- return b
- },
- compose: function (a) {
- var b = a.nextConnection.targetBlock();
- this.itemCount_ = 0;
- var e = null;
- if (b && b.type === "ai_model_false_create_with_item") {
- this.itemCount_++;
- e = b.statementConnection_;
- b = b.nextConnection && b.nextConnection.targetBlock()
- }
- this.updateShape_()
- Blockly.Mutator.reconnect(e, this, "AIELSE")
- },
- saveConnections: function (a) {
- a = a.nextConnection.targetBlock();
- if (a && a.type === "ai_model_false_create_with_item") {
- e = this.getInput("AIELSE");
- a.statementConnection_ = e && e.connection.targetConnection;
-
- a = a.nextConnection && a.nextConnection.targetBlock()
- }
- },
- updateShape_: function () {
- this.getInput("AIELSE") && this.removeInput("AIELSE");
- console.log("this.itemCount_",this.itemCount_)
- this.itemCount_ && this.appendStatementInput("AIELSE").appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE)
- },
- };
- 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, 'AIELSE');
- 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 != "" ? statements_input1 : " pass"}
- `
- 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);
- }
- console.log(a.join(" "))
- 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", "/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)
- `
- // 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("/root/preset/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("/root/preset/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("/root/preset/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("/root/preset/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("/root/preset/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("/root/preset/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("/root/preset/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("/root/preset/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]
- };
|